19. The Extension API

Codex adds features without editing its turn loop. A feature is a set of small contributor objects, each typed by the hook it serves. The app server installs them into one ExtensionRegistry per thread, Core walks those lists at fixed points of every turn, and each extension keeps its private state in typed stores that the host owns.

Goals, memories, web search, image generation, the durable message queue, and two generations of the Guardian reviewer share one shape. None is a branch inside codex-core. Each is a crate under codex-rs/ext/ that implements a few traits from codex-extension-api and registers those implementations with a builder. Core knows the traits, not the features.

This chapter explains that seam: the contributor traits, the registry and its ordering rules, the typed state stores, and the order in which Core calls each hook. It then walks through the crate’s toy example, reports what the code and commit history say about why features left Core, and tours every crate in codex-rs/ext/.

The picture

The app server’s thread_extensions function installs each ext crate into an ExtensionRegistryBuilder and builds one immutable ExtensionRegistry per thread; Core then reads the registry’s contributor lists at seven hook points inside the Session, from thread start through turn start, step preparation, model response, turn items, and tool calls to turn end and idle, while ExtensionData stores hold each extension’s typed state.

Read the figure from the left. Each ext/* crate exposes an install function. The app server’s thread_extensions calls them in a fixed order on an ExtensionRegistryBuilder and then calls build(), which freezes the lists into an ExtensionRegistry. The seven boxes on the right are the places where Core iterates a contributor list, numbered in the order a thread meets them. Tool calls are colored as a security point because the approval-review contributor sits there. The ExtensionData box is the state side: Core passes the session, thread, turn, or step store that each callback needs, so an extension never needs a global variable.

Contributors: one trait per hook

The contributor families

A contributor is a trait object that serves one kind of hook. An extension that needs three hooks implements three traits on one struct and registers it three times; the goal extension registers one GoalExtension value as six contributors. This is the Observer pattern with typed subjects: each hook has its own trait, so a contributor cannot receive a callback it did not ask for.

The table lists the families that ExtensionRegistryBuilder accepts, grouped by what they can add.

Trait Core calls it It can add or change
ThreadLifecycleContributor<C> thread start, ready, resume, idle, stop seed state; submit follow-up input when idle
TurnLifecycleContributor turn start, step refresh, item done, turn stop catalog refresh; observe items
TurnInputContributor when a turn’s input is submitted extra contextual fragments
ContextContributor prompt assembly PromptFragments, World State sections
ToolContributor each sampling step native tools (ToolExecutor)
McpServerContributor<C> MCP runtime build McpServerContributions
ModelRequestContributor each model request budget veto; wrap the response stream
TurnItemContributor each parsed item mutate the TurnItem
ToolLifecycleContributor around each tool call observe only; MCP request _meta
ApprovalReviewContributor each approval request the whole decision
ConfigContributor<C>, TokenUsageContributor config change, token report state updates
SkillInvocationContributor, MessageLifecycleContributor skill use, agent message observation

Two more entries are not contributor lists. turn_start_admission installs at most one TurnStartAdmission gate, and with_event_sink supplies the host’s ExtensionEventSink. Generic contributors take C, the host’s config type; the app server uses Core’s Config.

Default methods do nothing

Most trait methods have a default body that does nothing, so an extension overrides only the methods it uses. A few have no default and must be written, such as contribute on McpServerContributor, TurnInputContributor, and TurnItemContributor, and request on ModelRequestContributor. Asynchronous methods return ExtensionFuture, which codex-rs/ext/extension-api/src/contributors.rs defines as a pinned, boxed, Send future, so callers can hold contributors as Arc<dyn Trait>. The ToolContributor trait in the same file shows the pattern:

pub trait ToolContributor: Send + Sync {
    // ...
    /// Prepares step state once, before tools are built and without rendering.
    fn prepare_for_step<'a>(&'a self, _input: StepPreparationInput<'a>) -> ExtensionFuture<'a, ()> {
        Box::pin(async {})
    }

    /// Returns native tools bound to the supplied extension state.
    fn tools(
        &self,
        _session_store: &ExtensionData,
        _thread_store: &ExtensionData,
    ) -> Vec<Arc<dyn ToolExecutor>> {
        Vec::new()
    }

    /// Returns native tools bound to one sampling step.
    fn tools_for_step(
        &self,
        session_store: &ExtensionData,
        thread_store: &ExtensionData,
        _step_store: &ExtensionData,
    ) -> Vec<Arc<dyn ToolExecutor>> {
        self.tools(session_store, thread_store)
    }
}

A thread-scoped extension implements tools. A step-scoped one, such as web search, implements tools_for_step and reads per-step values, such as the web search mode, from the step store. Core always calls tools_for_step, whose default forwards to tools.

Prompt slots

A ContextContributor returns PromptFragment values. Each fragment names one of three PromptSlots: DeveloperPolicy, DeveloperCapabilities, or ContextWindow. The slot decides where the text lands inside the developer message, “regardless of its original role”. The contributor has three methods with different lifetimes: contribute_thread_context for stable thread inputs, contribute_turn_context for turn-local state, and contribute_world_state for per-step World State sections (see Chapter 7). Core’s build_turn_context_contribution_items renders every turn-context fragment into one developer message.

The registry

Builder, then freeze

ExtensionRegistryBuilder<C> is a mutable builder with one registration method per contributor list, 14 in all. build() returns an immutable ExtensionRegistry<C> that exposes each list as a slice. to_builder() copies a finished registry back into a builder. This is the Builder pattern used for one purpose: after build(), nothing can register or remove a contributor, so every turn in the thread sees the same set.

Order is the only policy the registry itself enforces. Lists keep registration order, and a test in codex-rs/ext/extension-api/tests/registry.rs, contributors_preserve_registration_order, pins that behavior. Several rules build on it:

The approval rule and the admission gate are short enough to read whole. From codex-rs/ext/extension-api/src/registry.rs:

pub fn admit_turn_start(&self) -> Option<Box<dyn Send>> {
    match &self.turn_start_admission {
        Some(admission) => admission.admit_turn_start(),
        None => Some(Box::new(())),
    }
}

pub async fn decide_approval(
    &self,
    input: &crate::ApprovalDecisionInput<'_>,
) -> Option<crate::ApprovalDecision> {
    for contributor in &self.approval_review_contributors {
        if let Some(decision) = contributor.decide(input).await {
            return Some(decision);
        }
    }
    None
}

A host without a gate gets an empty permit, so every turn may start. A host with a gate can return None, and the doc comment says the start is then rejected “before Core consumes pending input.” The gate’s module comment names its purpose: it lets turn submissions “participate in a host’s shutdown drain.”

The install order in the app server

thread_extensions in codex-rs/app-server/src/extensions.rs builds the registry for each thread in this order: the app server’s thread-state manager (a thread-lifecycle contributor), multi-environment copy-file, the admission gate, queue, history notes, the agent message board, goal, git attribution, Guardian v3, Guardian v2, memories, MCP, MCP plugins, web search, image generation, skills, and last the app server’s own sample-responses model-request contributor. Five entries are conditional. Copy-file installs only when multi_env_copy_file is on. The admission gate installs only when the host passes one. The queue installs only when the app server has a queue service. Goals need a state database. Guardian v3 installs with install_shadow when guardianv3 is off.

Installation is not activation. Most extensions install every time and decide at run time whether to contribute anything; the memories extension returns no fragments unless Feature::MemoryTool is on and memories.use_memories is true. Core also keeps a final say over tools. Its spec plan drops web.run unless the provider supports web search, the web search mode is not Disabled, and either standalone_web_search is on or the model’s catalog entry sets use_responses_lite. It drops image_gen.imagegen unless image_generation is on, the account is not on the Free plan, the provider supports image generation, the model accepts image input, and the provider uses OpenAI authorization.

State without globals: ExtensionData

ExtensionData in codex-rs/ext/extension-api/src/state.rs is a map from TypeId to Arc<dyn Any + Send + Sync>, guarded by a mutex. Core creates one per scope: session, thread, turn, and a step store each time it prepares a sampling step. An extension defines a private type and reads it back with get::<T>() or creates it lazily with get_or_init. Because the key is the type, two extensions cannot collide unless they share a type. This is the type-map pattern: private state per feature, with no string keys.

get_or_init runs its initializer while the map is locked, so the doc comment asks that it stay cheap. A host can seed a scope before it exists with ExtensionDataInit. The policy objects SessionIsolation and ToolPolicy arrive this way. SessionIsolation::Isolated starts a session without inherited extensions, implicit Apps, or executor-discovered MCP servers. A ToolPolicy with allowed_tools: Some(vec![]) permits no tools at all, while None keeps normal selection.

A minimal extension

The crate ships one example. Its extension, in codex-rs/ext/extension-api/examples/enabled_extensions/shared_state_extension.rs, registers two context contributors. The first one, trimmed:

pub fn install(registry: &mut ExtensionRegistryBuilder<()>) {
    registry.prompt_contributor(Arc::new(StyleContributor));
    registry.prompt_contributor(Arc::new(UsageContributor));
}

impl ContextContributor for StyleContributor {
    fn contribute_thread_context<'a>(
        &'a self,
        session_store: &'a ExtensionData,
        thread_store: &'a ExtensionData,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Vec<PromptFragment>> + Send + 'a>> {
        Box::pin(async move {
            contribution_counts(session_store).record_style();
            contribution_counts(thread_store).record_style();

            vec![PromptFragment::developer_policy(
                "Prefer short answers unless the user asks for detail.",
                ContentItemKind("example.style_instructions".to_string()),
            )]
        })
    }
}

contribution_counts calls store.get_or_init::<ContributionCounts>(Default::default), a struct of two atomic counters. The host in main builds a registry with config type (), creates one session store and two thread stores, and asks for thread context three times: twice for thread-1, once for thread-2. Reading the code (not running it), the program prints 2 fragments for the first call, 3 style and 3 usage contributions in the session store, 2 of each in thread-1, and 1 of each in thread-2. The example’s own comment states the lesson: “The host decides which stores are shared.” The extension writes to whichever stores it receives.

One thread’s lifecycle

Core calls the hooks in a fixed order. Each step names the Core function that walks the list.

  1. Thread start. During Session startup, Core creates the session store and calls on_thread_start on every thread-lifecycle contributor with the config, session source, environments, and both stores. Most extensions copy their config slice into the thread store here.
  2. Thread ready or resume. CodexThread calls on_thread_ready after the thread is registered, and on_thread_resume after a runtime is rebuilt from persisted history.
  3. Turn start. Core acquires the admission permit. emit_turn_start_lifecycle then calls on_turn_start on contributors whose turn_start_phase matches the current phase, BeforeTaskRegistration or RegularTaskStart. When the turn records the user’s input, each TurnInputContributor may add contextual fragments.
  4. Each sampling step. Tool contributors run prepare_for_step, turn-lifecycle contributors may refresh catalogs (refresh_catalog_for_step returns true when the MCP runtime needs a rebuild), extension_tool_executors collects tools_for_step from every tool contributor, and context contributors supply fragments and World State.
  5. Model response and items. A model-request contributor can fail a generation request when a budget is exhausted, and can wrap the response stream in an interceptor. apply_turn_item_contributors passes each parsed item to every TurnItemContributor in order; an error is logged as “turn item contributor failed” and the item continues.
  6. Tool calls. Tool-lifecycle observers see dispatch, start, MCP results, and finish. Approvals go through the registry’s decide_approval.
  7. Turn end and idle. on_turn_stop completes before Core emits the turn-complete event. When no turn is active, emit_thread_idle_lifecycle_if_idle calls on_thread_idle, unless mail that must start a turn is already waiting. On teardown, on_thread_stop runs before the host closes persistent history, and contributors must join their background work first.

Observe versus change

The API separates hooks that watch from hooks that change. ToolLifecycleContributor only observes. Its doc comment sends any “policy that changes tool payloads” to hooks (see Chapter 18), and on_tool_start fires only after pre-tool hooks have finalized the call, so a blocked call never reaches it. A TurnItemContributor, by contrast, receives &mut TurnItem and may rewrite the item before Core emits it. An ApprovalReviewContributor owns the whole decision: it returns ApprovalDecision::Allow, Reviewed(ReviewDecision), or AskUser, or None to pass. Core’s own wrapper in codex-rs/core/src/guardian/decision.rs states the safe default: “None requests the existing user flow. No contributor is never an implicit allow.” Chapter 16 follows that path into the Guardian.

Idle follow-up

on_thread_idle is how an extension continues work that no user asked for this second. The goal extension uses it: when the thread goes idle, it stops the active goal after interrupted empty turns, and then calls continue_if_idle, which can submit the next step of an active goal. The doc comment keeps the host in charge: the host “remains responsible for deciding whether that input starts a turn, is queued, or is ignored.”

Why features moved out of Core

The code and the commit history give the reasons directly. The commit that added the crate (d2c3ebac1f8, “extension: add initial typed extension API”) states the problem: “codex-core still owns a growing amount of product-specific behavior.” It describes the fix as “a small, typed first-party extension seam” where “features can install the contribution families they actually own, while the host keeps lifecycle and state ownership instead of pushing a broad service locator into the API.” A companion commit moved git attribution out of Core with a one-line argument: “Git commit attribution is prompt policy, not session orchestration.” A later commit routed the hosted Apps MCP server through an extension because a split runtime may have “no filesystem or executor” yet still needs to activate remote plugin components. The crate’s notes.md records the plan as a table that maps each feature to the contributor kinds it needs, such as “Tool + Runtime” for goals and “Context” for git attribution.

What follows is inference from the code, not a stated goal. The host, not Core, now chooses features per thread, so an isolated internal session can run with a separate registry (IsolatedSessionExtensions) and no inherited features. Features also gain a narrow, testable surface; the goal, skills, and history-notes crates have tests that call their contributors through a registry directly. The cost is that order carries meaning. “First Some wins” and “later Set replaces” are implicit in the install order, so moving one install call can change behavior without a compile error.

The extensions in ext/

The table summarizes each crate at commit 081295be9d: the contributor families it registers, what it gives the model or host, and where it is gated or covered.

Crate Registers Gives Gate or chapter
goal Thread, Config, Turn, TokenUsage, ToolLifecycle, Tool get_goal, create_goal, update_goal; idle continuation goals Stable, on; needs state DB
memories Thread, Config, Context, Tool memories namespace: add_ad_hoc_note, list, read, search memories Stable, off, plus use_memories
web-search Thread, Config, Tool web.run search-capable provider; mode not Disabled
image-generation Thread, Config, Tool image_gen.imagegen on gpt-image-2 OpenAI-auth provider; image_generation
queue Thread durable user-message queue, dispatched on idle host queue service
history-notes Thread, Config, Context, Tool history and notes namespaces use_history_notes_extension, Codex backend
git-attribution Thread, Context git_attribution World State section policy fetch, 5 s timeout
agent-message-board Thread, Tool (MCP mode: Thread, Turn, McpServer) board tools in the agent namespace Chapter 20
multi-env-copy-file Tool multi_env_copy_file multi_env_copy_file, off
connectors none (library) PluginAppProvider for plugin app declarations used by mcp
items none (library) ExtensionItem display items used by Core and protocol
mcp McpServer, plus Thread, Turn, Config for plugins hosted codex_apps server, plugin MCP servers Chapter 17
skills Thread, Config, Context, SkillInvocation, Tool, TurnInput, Turn skill catalog and skill tools Chapter 18
guardian-reviewer none (library) review policy and routing Chapter 16
guardian-v2, guardian-v3 v2: ApprovalReview, Thread, Turn, SkillInvocation, ToolLifecycle; v3: Thread, Turn (plus Config as a shadow) automatic approval review Chapter 16

A few rows need a sentence more. The goal objective is capped at 4,000 characters. The memories extension injects memory_summary.md, truncated to 2,500 tokens, as prompt context. When its policy is enabled, git attribution asks the model to end commit messages with Co-authored-by: Codex <noreply@openai.com>; the policy fetch times out after 5 seconds and retries after 30. ExtensionItem in items is a kind-tagged envelope with three kinds, image_gen.generation, clock.sleep, and web.search, so Core and the rollout can carry extension display items without knowing their schemas.

Status at commit 081295be9d. IMPLEMENTED: codex-extension-api and the app server’s per-thread registry. Feature flags that gate extensions: goals STABLE, on by default; memories (MemoryTool) STABLE, off; image_generation STABLE, on; apps STABLE, on; standalone_web_search UNDER DEVELOPMENT, off; multi_env_copy_file UNDER DEVELOPMENT, off; guardianv2 and guardianv3 UNDER DEVELOPMENT, off; agent_message_board and agent_message_board_mcp UNDER DEVELOPMENT, off. History notes has no feature flag; token_budget.use_history_notes_extension gates it.

What breaks

Symptom Cause Check
A new extension’s tool never appears Not installed in thread_extensions, or its gate is off codex-rs/app-server/src/extensions.rs; feature state
web.run missing Provider lacks web search, or standalone_web_search off and no lighter Responses path standalone_web_search_enabled in spec_plan.rs
Approval behaves as if no reviewer exists An earlier contributor returned Some first, or all returned None Install order; decide_approval
MCP server config differs from config.toml A later contributor replaced the same server name McpServerContributor order
Extension state missing in a callback Stored in the wrong scope, or never seeded at thread start on_thread_start; which store is passed
Turn start silently skipped during shutdown Admission gate returned no permit TurnStartAdmission
Item change lost TurnItemContributor returned Err Log line “turn item contributor failed”
Goal tools missing in the app server No state database, so thread_extensions skips the goal install state_db in codex-rs/app-server/src/extensions.rs

Code map

What it is Where it lives Identifier
Contributor traits codex:codex-rs/ext/extension-api/src/contributors.rs pub trait ToolContributor
Builder and registry codex:codex-rs/ext/extension-api/src/registry.rs pub struct ExtensionRegistryBuilder
Typed state codex:codex-rs/ext/extension-api/src/state.rs pub struct ExtensionData
Prompt slots codex:codex-rs/ext/extension-api/src/contributors/prompt.rs pub enum PromptSlot
Per-thread install codex:codex-rs/app-server/src/extensions.rs pub(crate) fn thread_extensions
Turn hooks in Core codex:codex-rs/core/src/tasks/lifecycle.rs emit_turn_start_lifecycle
Extension tools in Core codex:codex-rs/core/src/tools/spec_plan.rs pub(crate) fn extension_tool_executors
Example extension codex:codex-rs/ext/extension-api/examples/enabled_extensions/shared_state_extension.rs struct StyleContributor

Recall check

Why does the goal extension register the same value six times?
Each hook has its own trait and list, so one struct registers once per contributor family it implements.

What decides which approval-review contributor answers?
Registration order; decide_approval returns the first Some, and None everywhere falls back to the user flow.

Where does an extension keep per-turn state?
In the turn’s ExtensionData store, keyed by its own private type through get or get_or_init.

Can a tool-lifecycle contributor change a tool’s arguments?
No; it only observes, and calls blocked by pre-tool hooks never reach on_tool_start. Hooks change payloads.

Does installing an extension mean the model sees its tools?
No; the extension may contribute nothing for its config, and Core’s spec plan can still drop web.run or image_gen.imagegen.