Compare commits

...
Author SHA1 Message Date
Ahmed Ibrahim 3d72c4826c [6/6] Add Python goal cleanup integration coverage 2026-06-09 16:32:04 -07:00
Ahmed Ibrahim 879c090ccc Move SSE gate into goal control coverage 2026-06-09 16:32:04 -07:00
Ahmed Ibrahim dacc7e82c3 [5/6] Add Python goal control integration coverage 2026-06-09 16:32:04 -07:00
Ahmed Ibrahim 1f89f5233a Strengthen goal routing ID coverage 2026-06-09 16:31:53 -07:00
Ahmed Ibrahim a0de197076 [4/6] Expose dedicated Python goal operations 2026-06-09 16:30:09 -07:00
Ahmed Ibrahim 206478d338 Release goal routing when streams close 2026-06-09 16:29:57 -07:00
Ahmed Ibrahim 3fbee02b96 [3/6] Add private Python goal-aware turn handles 2026-06-09 16:12:31 -07:00
Ahmed Ibrahim 51b3cd51f6 [codex] Tighten MCP connection manager API visibility and order (#27257)
## Summary

- order `McpConnectionManager` methods by visibility, with the primary
constructor and public API first
- restrict `list_available_server_infos` to `codex-mcp`
- make `new_uninitialized` a private test-only helper

## Why

The manager exposed methods that are only used inside `codex-mcp` or its
unit tests. Tightening those methods keeps the exported API intentional,
while the new ordering makes the supported surface easier to scan.

## Validation

- `just fmt`
- `git diff --check`
- local tests not run; relying on CI
2026-06-09 16:07:34 -07:00
ssetty-oai 490340ffcf [codex] Retry streamable HTTP initialize failures (#25147)
## Summary
- Retry transient streamable HTTP failures during RMCP startup when the
failure happens while sending the initialize request.
- Retry transient streamable HTTP failures for tools/list, which is
read-only and safe to replay.
- Cover both retryable HTTP statuses and request-layer failures where no
HTTP status is returned.
- Surface retryable HTTP statuses from the streamable HTTP adapter as
typed client errors.
- Add integration coverage for initialize retry, tools/list retry,
no-status request failure retry, and non-retryable initialize status.

## Root cause
The observed codex_apps failures can happen before normal tool
execution: RMCP startup fails while sending initialize, or the first
read-only tools/list fails after startup. Retrying hosted_apps_bridge
tools/call would not cover initialize and would risk replaying
side-effecting tool calls. This change retries the streamable HTTP
handshake itself, recreates the transport between initialize attempts,
and retries only tools/list among post-initialize service operations.

## Validation
- cargo fmt --package codex-rmcp-client
- cargo test -p codex-rmcp-client --test streamable_http_recovery
2026-06-09 15:49:48 -07:00
Ahmed Ibrahim 9316acf9b2 [2/4] Add private Python goal operations (#27111)
## Why

The Python SDK must treat the runtime's initial goal turn and its
continuations as one logical operation. That requires a private
lifecycle engine before the public API can return the existing turn
handle and result types.

## What

- start goals by composing the existing clear/set goal RPCs
- enforce persisted, idle threads and a bounded startup handshake
- coalesce continuation notifications under a stable logical turn ID
- aggregate items, usage, timing, and terminal status
- support rollover-aware steering, interruption, cancellation, and
cleanup
- provide equivalent sync and async internals

This is the second PR in the stack and intentionally adds no public API.

## Test plan

- online CI, including the Python SDK suite
- behavioral coverage is added in the following two stack PRs
2026-06-09 15:32:15 -07:00
guinness-oai cc8325f181 Stop mirroring Codex user input into realtime (#27116)
## Why

The realtime frontend model and the backing Codex thread should present
one coherent assistant. Raw typed messages, steers, and worker reports
belong to the orchestrator; the frontend model should receive the
orchestrator's user-facing result rather than a second copy of those
inputs.

Today normal `turn/start` input is automatically inserted into the
realtime conversation, while `turn/steer` is not. Besides creating
inconsistent context, this can make the frontend model react
independently before Codex has produced the response it should speak.

## What changed

- Remove automatic accepted-user-input mirroring into realtime
- Remove the mirror-only echo-suppression flag and dead V2 prefix helper
- Preserve explicit app-to-realtime text injection and FEM-to-Codex
delegation
- Replace the positive mirror tests and obsolete snapshots with a
negative routing regression test

## Test plan

- `cargo test -p codex-core
conversation_user_text_turn_is_not_sent_to_realtime`
- `cargo test -p codex-core
conversation_startup_context_is_truncated_and_sent_once_per_start`
- `cargo test -p codex-core inbound_handoff_request_starts_turn`
2026-06-09 15:20:01 -07:00
pakrym-oai f2969f36e8 [codex] Handle Ctrl-C for non-TTY unified exec (#26734)
## Why

A long-running unified exec process started with `tty: false` could not
be interrupted via `write_stdin`: ordinary non-TTY stdin writes are
rejected once stdin is closed, but an exact U+0003 payload should still
map to a process interrupt. The interrupt should flow through the same
process lifecycle path as a real signal so Codex preserves
process-reported output and exit metadata instead of fabricating a
Ctrl-C exit code or tearing down the session early.

## What Changed

- Add `process/signal` to exec-server with `ProcessSignal::Interrupt`
and an empty response.
- Add a non-consuming `ProcessHandle::signal` path for spawned
processes; on Unix it sends SIGINT to the process group and leaves
terminate/hard-kill unchanged.
- Route non-TTY U+0003 `write_stdin` through `process.signal(...)`
instead of `terminate`, then let the normal post-write collection path
drain output and observe exit.
- Add exec-server coverage where a shell `trap INT` handler prints the
signal and exits with its own code.
- Add unified exec coverage where a `tty: false` process traps SIGINT,
emits output, and exits with its own code.

## Validation

- `just test -p codex-exec-server
exec_process_signal_interrupts_process`
- `just test -p codex-exec-server`
- `just test -p codex-core
write_stdin_ctrl_c_interrupts_non_tty_session`
2026-06-09 15:10:17 -07:00
Adam Perry @ OpenAI f574946960 [codex] Report unusable MCP OAuth credentials as logged out (#26713)
## Why

Persisted MCP OAuth credentials were reported as authenticated whenever
a credential record existed. An expired token without a usable refresh
token could therefore appear as `OAuth` even though startup could not
authenticate with it, leaving users with a misleading status instead of
a login prompt.

## What changed

- Classify stored OAuth credentials as missing, usable, or requiring
authorization.
- Reuse the existing refresh window so near-expiry credentials without a
refresh path are also treated as logged out.
- Validate required credential fields before reporting OAuth
authentication.
- Add unit coverage for credential usability and integration coverage
for expired, unexpired, and refreshable persisted credentials.

## Validation

- `just test -p codex-rmcp-client`
2026-06-09 14:18:24 -07:00
Adam Perry @ OpenAI 9e3081be96 [codex] Characterize global instruction lifecycle (#26830)
## Why

Global instruction behavior spans thread creation, resume, forks,
subagents, and compaction. Characterization coverage is needed before
changing those semantics so preserved history can be distinguished from
newly loaded configuration.

## What changed

- Extends the existing `agents_md` suite with fresh-thread, warning,
resume, fork, and subagent lifecycle coverage.
- Extends the existing `compact` suite with manual, mid-turn, and
remote-v2 compaction coverage.
- Asserts rendered instruction fragments, reported source paths, and
structured request history before and after instruction-file mutations.
2026-06-09 20:51:57 +00:00
jif 4ec3b8eeea Route hosted Apps MCP through extensions (#27191)
## Stack

- Base: #27184
- This PR is the second vertical and should be reviewed against
`jif/external-plugins-1`, not `main`.

## Why

CCA is moving toward a split runtime where the orchestrator may have no
filesystem or executor, but it still needs to activate remotely hosted
plugin components. HTTP MCP servers are the simplest complete example:
they need configuration and host authentication, but they do not need an
executor process.

The Apps MCP endpoint is currently synthesized by a special-purpose
loader inside the MCP runtime. That works locally, but it leaves hosted
MCP activation outside the extension model being established in #27184.
It also makes the Apps path a poor foundation for plugins whose skills,
MCP servers, connectors, and hooks may come from different sources or
execute in different places.

This PR moves that one behavior behind an extension-owned contribution
while preserving the existing local fallback. It deliberately does not
introduce a generic plugin activation framework.

## What changed

### MCP extension contribution

`codex-extension-api` gains an ordered `McpServerContributor` contract.
A contributor returns typed `Set` or `Remove` overlays for MCP server
configuration; later contributors win for the names they own.

The contract stays at the existing MCP configuration boundary.
Extensions do not create a second connection manager or transport
abstraction.

### Hosted Apps MCP extension

A new `codex-mcp-extension` contributes the reserved `codex_apps` server
from the existing Apps feature, ChatGPT base URL, path override, and
product SKU configuration.

When `apps_mcp_path_override` is enabled for `https://chatgpt.com`, the
resulting streamable HTTP endpoint is
`https://chatgpt.com/backend-api/ps/mcp`. The existing ChatGPT-auth gate
remains authoritative, so this server can run in an orchestrator-only
process without being exposed for API-key sessions.

### One resolved runtime view

`McpManager` now distinguishes three views:

- **configured:** config- and plugin-backed servers before extension
overlays;
- **runtime:** configured servers plus host-installed extension
contributions;
- **effective:** runtime servers after auth gating and compatibility
built-ins.

App-server installs the hosted MCP extension and uses the runtime view
for thread startup, refresh, status, threadless resource reads,
connector discovery, and MCP OAuth lookup. This keeps
`mcpServer/oauth/login` consistent with the servers exposed by the other
MCP APIs. The hosted Apps server itself continues to use existing
ChatGPT host authentication rather than MCP OAuth.

## Compatibility

Hosts that do not install the MCP extension retain the existing Apps MCP
synthesis path. This preserves current local-only, CLI, and
standalone-host behavior while app-server exercises the extension path.

Disabling Apps removes the reserved `codex_apps` entry, and losing
ChatGPT auth removes it from the effective runtime view. Executor
availability is not consulted for this HTTP transport.

## Follow-ups

The next vertical will resolve a manifest-declared stdio MCP server from
an executor-selected plugin root and execute it in the environment that
owns that root. Later verticals can add backend-owned skills, connector
metadata, hooks, durable selection semantics, and incremental local
convergence without changing the component-specific runtime boundaries
introduced here.

## Verification

Focused coverage was added for:

- contributing the hosted Apps MCP at `/backend-api/ps/mcp` without an
executor;
- requiring ChatGPT auth in the effective runtime view;
- removing a reserved configured Apps server when the Apps feature is
disabled.

`cargo check -p codex-app-server -p codex-mcp-extension -p
codex-extension-api -p codex-mcp` passed. Tests and Clippy were not run
locally under the current development instruction; CI provides the full
validation pass.
2026-06-09 22:44:16 +02:00
Ahmed Ibrahim 5a0f913426 [1/4] Add Python goal routing foundation (#27110)
## Why

Goal continuation turns are emitted by the existing runtime as separate
physical turns. The Python SDK needs private thread-scoped routing
before it can present those notifications as one logical operation,
without changing ordinary turn routing or the app-server protocol.

## What

- add private goal operation state and thread-scoped notification
routing
- add internal wrappers for the existing `thread/goal/clear` and
`thread/goal/set` RPCs
- include existing goal notifications in the SDK notification union
- preserve ordinary turn-ID routing unchanged
- add focused routing coverage

This PR does not expose a public goal API. It is the first PR in the
Python goal operations stack.

## Test plan

- online CI, including the Python SDK suite
- focused typed-notification routing coverage
2026-06-09 13:35:29 -07:00
Eric Traut 8e69d29521 Reduce TUI legacy core dependencies (#26711)
## Why

The TUI still reached through `app-server-client::legacy_core` for
thread-name normalization and project-instruction filename details. In
particular, checking the TUI's local filesystem for `/init` is incorrect
for remote app-server sessions, where the server owns the working
directory and instruction discovery.

## What changed

- use the instruction source paths supplied by the app server to decide
whether `/init` should avoid overwriting project instructions
- keep the small thread-name normalization helper local to the TUI
- remove the now-unused instruction filename constants, utility module,
and other unused `legacy_core` re-exports
- make status helper tests independent of concrete instruction filenames

## Verification

- `just test -p codex-app-server-client`
- `just test -p codex-tui
slash_init_skips_when_project_instructions_are_loaded`
- `just test -p codex-tui` ran 2,799 tests; 2,797 passed and two
unrelated guardian feature-flag tests failed reproducibly in untouched
code

### Manual test

Started an app server over WebSocket with a remote workspace containing
`AGENTS.md`, then connected the TUI using `--remote`. After confirming
`thread/start` returned the file in `instructionSources`, deleted
`AGENTS.md` and ran `/init` in the existing session.

The TUI still reported that project instructions already existed and
skipped `/init`. The trace contained no `turn/start` request, confirming
the decision came from app-server session state rather than a new
client-local filesystem check.
2026-06-09 13:26:00 -07:00
Eric Traut 36bf63a5cf Allow creating a new goal after completion (#26681)
## Why

Users have indicated that they want an agent to be able to create a new
goal for itself after completing the previous goal. Currently, that's
not possible because agents cannot overwrite an existing goal even if
it's complete. This PR removes this limitation and allows `create_goal`
to overwrite an existing goal if it is in the `complete` state.

## What changed

`create_goal` now replaces the existing goal only when its status is
`complete`. The replacement is performed atomically in the goal store,
creates a fresh active goal with reset usage, and continues to reject
creation while any unfinished goal exists. App server clients see a
single `thread/goal/updated` event when the previous goal is replaced
with the new one.

The tool description and error message now reflect these semantics.

## What didn't change

Agents are not allowed to create a new goal (overwrite their existing
goal) if an existing goal is still active, blocked, paused, or in any
other state other than "completed".
2026-06-09 13:23:31 -07:00
Winston Howes 472619f9fc Add SOCKS5 TCP MITM coverage (#22685)
## Summary
- reuse the MITM HTTPS serving path for raw SOCKS5 TCP streams
- route limited-mode and hooked SOCKS5 TCP requests through MITM before
dialing upstream
- keep SOCKS5 UDP limited-mode behavior unchanged

## Validation
- `just fmt`
- `just test -p codex-network-proxy`
- `just fix -p codex-network-proxy`
- `git diff --check`
2026-06-09 13:08:01 -07:00
Eric Ning 7a7cee1be4 fix: use plugin service route for remote uninstall (#27223) 2026-06-09 12:52:05 -07:00
Adam Perry @ OpenAI 6e7ab52929 [codex] Speed up local nextest runs (#26479)
## Why

`just test` currently uses the CI-oriented nextest profile, which
serializes app-server integration tests even on developer machines that
can run several safely. Bounded local parallelism substantially shortens
this common iteration loop without changing CI behavior.

Eight-worker experiments were faster, but keeping them reliable required
relaxing several test deadlines. Four workers for integration tests is a
solid tradeoff that speeds up local testing without needing to change
test logic.

## What changed

- Add a `local` nextest profile that inherits the existing defaults.
- Allow up to four app-server integration tests to run concurrently
under that profile.
- Make `just test` select the local profile on Unix and Windows.
- Keep the default CI profile serialized and leave all test deadlines
unchanged.

The tests use separate processes, randomized temporary `CODEX_HOME`
directories, and ephemeral ports. The remaining shared constraints are
system resources; each app-server also uses a multi-thread Tokio
runtime, and fuzzy-search tests can create additional worker threads, so
the local cap remains intentionally conservative.

## Performance and validation

All measurements below are warm, execution-only app-server runs with
nextest retries disabled.

On the current rebased branch, an AMD EPYC 7763 machine with 16 logical
CPUs and 62 GiB RAM completed three consecutive runs:

| Run | Nextest time | Wall time | Result |
| --- | ---: | ---: | --- |
| 1 | 142.941s | 145.17s | 836/836 passed |
| 2 | 143.402s | 145.59s | 836/836 passed |
| 3 | 142.870s | 145.08s | 836/836 passed |

The mean wall time was 145.28s. The slow-inventory, approval replay, and
zsh-fork tests all passed with their original deadlines.

Earlier measurements on the same Linux machine, before the suite grew,
showed the scaling that motivated the change:

| App-server concurrency | Nextest time | Result |
| --- | ---: | --- |
| 1 | 369.5s | 572/572 passed |
| 2 | 194.5s | 572/572 passed |
| 4 | 111.0s mean over 3 runs | 3/3 clean |

Four workers reduced that execution time by about 70%, a roughly 3.3x
speedup over serialization.
2026-06-09 12:48:04 -07:00
marksteinbrick-oai a71e040df5 [codex-analytics] add extensible feature thread sources (#27063)
## Why
- `ThreadSource` currently defines a closed set of core-owned values
- Product features also create threads for background or scheduled work
- Adding every product-specific value to the core enum would require
repeated `codex-rs` protocol changes
- Feature-backed values let product callers provide precise attribution
while preserving the existing core classifications

## What Changed
- Adds `ThreadSource::Feature(String)` for app-owned thread source
values
- Represents all app-server v2 thread sources as scalar strings, so a
feature source is supplied as `"automation"`
- Persists and emits the feature's plain string label, so `"automation"`
produces `thread_source="automation"` in analytics
- Keeps `user`, `subagent`, and `memory_consolidation` as explicit
core-owned values and regenerates the app-server schemas and TypeScript
bindings

## Verification
- `just write-app-server-schema`
- `cargo check --workspace`
- `just test -p codex-protocol
feature_thread_source_serializes_as_its_app_owned_label`
- `just test -p codex-app-server-protocol
thread_sources_round_trip_as_scalar_labels`
- `cargo test -p codex-analytics
thread_initialized_event_serializes_expected_shape`
- `just fmt`
2026-06-09 12:27:10 -07:00
Adam Perry @ OpenAI 99da697e4c [codex] Test extension API contracts (#26835)
## Why

`codex-extension-api` defines contracts shared by extension crates and
their hosts, but it had no direct test suite. Host and feature tests
cover downstream behavior, while regressions in the API crate's own
typed state, registry ordering, and capability adapters could go
unnoticed.

## What

- Add public-surface integration tests for `ExtensionData`, including
concurrent initialization and poison recovery.
- Cover contributor registration order, approval short-circuiting, event
sink retention, no-op response injection, and closure-based agent
spawning.
- Add the test-only dependencies used by the suite.

## Validation

- `just test -p codex-extension-api`
- `just argument-comment-lint -p codex-extension-api`
- `just bazel-lock-check`
2026-06-09 18:30:24 +00:00
jif 89ac3ec27c Load selected executor skills through extensions (#27184)
## Why

CCA is moving toward a split runtime where the orchestrator may not have
a filesystem, while executors can expose preinstalled plugins and
skills. A thread therefore needs to select capabilities without asking
app-server or core to interpret executor-owned paths through the
orchestrator's filesystem.

The longer-term model is broader than executor skills:

- A plugin is a bundle of skills, MCP servers, connectors/apps, and
hooks.
- A plugin root can be local, executor-owned, or hosted by a backend.
- Components inside one plugin can use different access and execution
mechanisms. A skill may be read from a filesystem or through backend
tools; an HTTP MCP server can run without an executor; a stdio MCP
server or hook needs an execution environment.
- Core should carry generic extension initialization data. The extension
that owns a component should discover it, expose it to the model, and
invoke it through the appropriate runtime.

This PR establishes that architecture through one complete vertical:
selecting a root on an executor, discovering the skills beneath it,
exposing those skills to the model, and reading an explicitly invoked
`SKILL.md` through the same executor.

## Contract

`thread/start` gains an experimental `selectedCapabilityRoots` field:

```json
{
  "selectedCapabilityRoots": [
    {
      "id": "deploy-plugin@1",
      "location": {
        "type": "environment",
        "environmentId": "workspace",
        "path": "/opt/codex/plugins/deploy"
      }
    }
  ]
}
```

The root is intentionally not classified as a "plugin" or "skill" in the
API. It can point at a standalone skill, a directory containing several
skills, or a plugin containing skills and other components. This PR only
teaches the skills extension how to consume it; later extensions can
resolve MCP, connector, and hook components from the same selection.

The platform-supplied `id` is stable selection identity. The location
says which runtime owns the root and gives that runtime an opaque path.
App-server does not inspect or canonicalize the path.

## What changed

### Generic thread extension initialization

App-server converts selected roots into `ExtensionDataInit`. Core
carries that generic initialization value until the final thread ID is
known, then creates thread-scoped `ExtensionData` before lifecycle
contributors run.

This keeps `Session` and core independent of the capability-selection
contract. The initialization value is consumed during construction; it
is not retained as another long-lived `Session` field.

### Executor-backed skills

The skills extension now owns an `ExecutorSkillProvider` that:

- resolves the selected environment through `EnvironmentManager`
- discovers, canonicalizes, and reads skills through that environment's
`ExecutorFileSystem`
- contributes the bounded selected-skill catalog as stable developer
context
- reads an explicitly invoked skill body through the authority that
listed it
- warns when an environment or root is unavailable
- never falls back to the orchestrator filesystem for an executor-owned
root

Skill catalog and instruction fragments have hard byte bounds, which
also bound them below the 10K-token per-item context limit. If a
selected executor skill has the same name as a legacy local skill, the
executor selection owns that invocation and the local body is not
injected a second time.

Existing local and bundled skill loading remains in place. Omitting
`selectedCapabilityRoots` therefore preserves current local-only
behavior.

## Current semantics

- Only environment-owned locations are represented in this first
contract.
- Roots are resolved by the destination extension, not by app-server or
core.
- An unavailable executor or invalid root produces a warning and no
capabilities from that root; it does not trigger a local-filesystem
fallback.
- Selection applies to a newly started active thread.
- MCP servers, connectors, and hooks beneath a selected plugin root are
not activated yet.
- Selection is not yet persisted or inherited across resume, fork, or
subagent creation. Existing local capabilities continue to behave as
they do today in those flows.

## Planned vertical follow-ups

1. **Hosted HTTP MCP:** add an extension-backed HTTP MCP source that
works without an executor, then replace the special-purpose MCP plugins
loader with that implementation.
2. **Executor MCP:** register and execute stdio MCP servers through the
environment that owns the selected plugin root.
3. **Backend skills:** add a hosted skill source whose catalog and
bodies are accessed through extension tools rather than a filesystem.
4. **Connectors and hooks:** activate those components through their
owning extensions, using the same selected-root boundary and
component-specific runtime.
5. **Durable selection:** define the desired-selection lifecycle,
persist it, and make resume, fork, and subagent inheritance explicit
rather than accidental.
6. **Local convergence:** incrementally route existing local plugin,
skill, and MCP loading through the same extension model while preserving
current local behavior.

Each follow-up remains reviewable as an end-to-end capability. The
platform selects roots, generic thread extension data carries the
selection, and the owning extension resolves and operates its component.

## Verification

Coverage added for:

- app-server end-to-end discovery and explicit invocation of a skill
inside an executor-selected plugin root
- exclusive invocation when a selected executor skill collides with a
local skill name
- executor filesystem authority for discovery, canonicalization, and
reads
- thread extension initialization before lifecycle contributors run
- stable executor catalog context, explicit invocation, context
rebuilding, hidden skills, and preserved host/remote catalog behavior

Targeted protocol, core-skills, skills-extension, core lifecycle, and
app-server executor-skill tests were run during development.
2026-06-09 19:51:54 +02:00
jif 1026e9de1b app-server: reject direct input to multi-agent v2 sub-agents (#27173)
## Why

Multi-agent v2 sub-agents are owned and coordinated by their parent
agent. Allowing an app-server client to start or steer turns on a
spawned child bypasses the multi-agent messaging path and creates a
second, conflicting source of work for that sub-agent.

## What changed

- Reject direct `turn/start` and `turn/steer` requests targeting
multi-agent v2 thread-spawn sub-agents.
- Identify these targets using both the thread's resolved multi-agent
version and its `SubAgentSource::ThreadSpawn` session source, leaving
root threads, v1 agents, and other sub-agent types unchanged.
- Return a consistent invalid-request error before validating or
applying the submitted input.

## Testing

- Added an app-server integration test that spawns a real multi-agent v2
child and verifies that direct `turn/start` and `turn/steer` requests
are rejected.
2026-06-09 19:40:40 +02:00
canvrno-oai 8a299fb704 fix: Prevent /review crash when entering Esc on steer message (#22879)
This changes the `/review` escape path so `Esc` no longer behaves like
the normal queued-follow-up interrupt flow while a review is running.
Steering is not currently supported in `/review` mode, without this
change users are able to attempt a steer but it leads to a crash (see
#22815). If the user has already tried to send additional guidance
during `/review`, the TUI now keeps the review running and shows a
warning that steer messages are not supported in that mode, while still
pointing users to `Ctrl+C` if they actually want to cancel. It also adds
regression coverage for the review-specific warning behavior. When users
do cancel with Ctrl+C during /review, the TUI now tolerates the
active-turn race that can happen during review handoff, and any queued
steer messages are restored to the composer instead of being discarded.

- Special-case `Esc` during an active `/review` when follow-up steer
input is pending or has already been deferred.
- Show a clear warning instead of interrupting the running review.
- Make the Ctrl+C cancel path during /review resilient to active-turn
races, while preserving any queued steer text by restoring it to the
composer.
- Add review-mode test coverage for the warning path.

## Testing

1. Start a `/review` with a diff large enough that the review stays
active for more than a few seconds.

2. While the review is still running, type a follow-up / steer message,
submit it, and then press `Esc`.
   Before: `Esc` causes the TUI to close abruptly.  
After: the review keeps running and the transcript shows a warning that
steer messages are not supported during `/review`, with guidance to use
`Ctrl+C` if you want to cancel.

3. Press `Ctrl+C` if you actually want to stop the review.  
Before: (after restarting the test since Pt. 2 crashed) this is the
intentional cancellation path.
After: this remains the intentional cancellation path, and any queued
follow-up steer text is restored to the composer instead of being lost.
   
## Note:
`/review` mode explicitly does not support steering at this time (as
noted in `turn_processer.rs`, if we want to explore that in the future
this code will need to be modified). This change keeps unsupported steer
attempts from crashing the TUI and preserves queued follow-up text if
the user cancels with Ctrl+C.
2026-06-09 09:41:58 -07:00
Zanie Blue 6a9a49b334 Avoid rereading rollout history during cold resume (#27031)
## Summary

- reuse the history-bearing `StoredThread` loaded while probing for a
running thread
- avoid rereading and reparsing the rollout when that probe finds no
active process
- reload after shutting down a loaded thread because shutdown may flush
newer rollout items
- add a regression test that verifies cold resume performs one
history-bearing store read

## Problem

`thread/resume` first reads the persisted thread with history while
checking whether the thread is
already running. When no running process exists, cold resume currently
falls through to
`resume_thread_from_rollout`, which reads and parses the same history
again.

That duplicate work grows with rollout size and remains on the
synchronous resume path even when
the caller requests `excludeTurns`.

## Background

The duplicate read was introduced by #24528, which fixed resume
overrides for idle cached
threads. To support resumes specified by rollout path,
`resume_running_thread` began loading the
stored thread with history so it could resolve the canonical thread ID
and determine whether a
cached `CodexThread` was already loaded.

That history is needed when the loaded-thread path handles the request.
On a cold miss, however,
the function's boolean result could only report that no loaded thread
handled the request. It
discarded the history-bearing `StoredThread`, and the normal cold-resume
path immediately loaded
and parsed the same rollout again.

This change preserves the idle cached-thread behavior from #24528 while
allowing the cold-resume
path to reuse the probe result.

## Performance

I benchmarked real retained rollouts using isolated `CODEX_HOME`
directories, explicit rollout
paths, debug builds of the commit and its exact parent, and alternating
parent/patch order. The
table below uses `thread/resume` with `excludeTurns: true`; response
payload sizes were identical.

| Rollout size | Records | Parent median | Patch median | Median paired
saving |
| ---: | ---: | ---: | ---: | ---: |
| 6 MB | 3,574 | 541 ms | 441 ms | 132 ms |
| 30 MB | 15,220 | 1.505 s | 1.041 s | 701 ms |
| 60 MB | 31,453 | 2.644 s | 1.742 s | 970 ms |
| 149 MB | 100,874 | 10.506 s | 7.156 s | 3.350 s |
| 559 MB | 259,734 | 27.759 s | 16.725 s | 9.836 s |

The absolute saving increases with thread size, as expected when
removing one complete JSONL
history read and parse. Total resume time is also content-dependent, so
the relationship is not
perfectly linear.

I also tested full-history resume with `excludeTurns: false`. The
response payload was
byte-identical between variants, and the same size-dependent improvement
remained visible:

| Rollout size | Parent median | Patch median | Median paired saving |
| ---: | ---: | ---: | ---: |
| 6 MB | 1.052 s | 904 ms | 270 ms |
| 30 MB | 2.667 s | 1.762 s | 924 ms |
| 60 MB | 8.464 s | 6.272 s | 3.680 s |
| 149 MB | 26.719 s | 12.118 s | 14.601 s |
| 559 MB | 40.359 s | 25.475 s | 16.590 s |

## Validation

- `just test -p codex-app-server
cold_thread_resume_reuses_non_local_history_probe`
- `just fix -p codex-app-server -p codex-thread-store`
- `just fmt`
2026-06-09 11:16:27 -05:00
Zanie Blue 18ce671fed Avoid no-op backfill state writes (#26420)
## Summary

- avoid acquiring SQLite's writer slot when the singleton backfill row
already exists
- preserve race-safe repair when the row is missing
- add regressions for writer contention and missing-row repair

## Why

State runtime initialization and backfill-state reads previously
executed
`INSERT ... ON CONFLICT DO NOTHING` even in the steady state. SQLite
still
enters the writer path for that statement, so TUI and app-server startup
could
wait behind another writer for up to the configured five-second busy
timeout.

## Validation

- `just test -p codex-state` (134 tests passed)
- `just fix -p codex-state`
- `just fmt`
2026-06-09 10:50:13 -05:00
Adam Perry @ OpenAI a770e5b847 [codex] Ignore pending PR review comments (#27080)
## Why

The PR babysitter could surface inline comments from a GitHub review
that was still in the `PENDING` state. That allowed Codex to start
acting on feedback before the reviewer submitted it.

## What changed

- Correlate inline comments with their parent review and ignore pending
reviews and their comments.
- Remove pending review IDs from saved watcher state so the feedback
surfaces normally after publication.
- Update the skill instructions and add regression coverage for the
draft-to-published transition.

## Validation

- `python3 -m pytest
.codex/skills/babysit-pr/scripts/test_gh_pr_watch.py`
- Skill package validation with `quick_validate.py`
- Live verification on #26835: the draft comment stayed hidden and
surfaced after the review was submitted.
2026-06-09 08:29:32 -07:00
jif 1547785657 app-server: clear stale thread watches after v2 agent interruption (#27166)
## Why

PR #27007 moved MultiAgentV2 interruption reporting from the legacy
collaboration close event to `SubAgentActivity::Interrupted`.
App-server's missing-thread cleanup still ran only for the legacy event,
so an interrupted child that had already been unloaded could remain
marked as loaded and running in `ThreadWatchManager`. That leaves thread
status and running-turn accounting stale, including the count used
during graceful shutdown.

## What changed

- Handle `SubAgentActivity::Interrupted` separately in app-server event
processing.
- Remove the child's thread watch when `ThreadManager` no longer has
that thread.
- Continue forwarding the same completed sub-agent activity notification
to clients.

## Testing

- Added a regression test that starts with a running watch for an
unloaded child, applies the interrupted activity event, and verifies the
watch is removed, the running count returns to zero, and the client
notification is still emitted.
2026-06-09 13:27:53 +02:00
jif fae2709320 multi-agent: add path-based v2 activity tracking (#27007)
## Why

Multi-agent v2 identifies agents by canonical paths, but its tool
handlers still emitted the larger legacy collaboration begin/end events
built around nickname and role metadata. App-server, rollout-trace,
analytics, and TUI consumers therefore lacked one compact path-based
completion signal that behaved consistently across live events and
replay.

The TUI also needs a bounded `/agent` status surface for v2 agents. It
should use recent local activity for previews, refresh liveness without
loading full histories, and keep the legacy picker available when no
path-backed v2 agent is known.

## What changed

- Replace the v2 `spawn_agent`, `send_message`, `followup_task`, and
`interrupt_agent` legacy lifecycle emissions with a success-only
`SubAgentActivity` event. The event records the tool call ID, occurrence
time, affected thread, canonical agent path, and `started`,
`interacted`, or `interrupted` kind.
- Expose the activity as a completion-only app-server v2
`subAgentActivity` thread item in live notifications and reconstructed
history, regenerate the protocol schemas, and count it in sub-agent tool
analytics.
- Track canonical paths from live activity and loaded-thread metadata in
the TUI, and render the activity in live and replayed transcripts.
- Make `/agent` list running path-backed agents with summaries from
bounded local event buffers. Each summary is capped at 240 graphemes,
the scan is capped at six recent items, only the last three wrapped
lines are shown, and command output is omitted. Liveness falls back to
metadata-only `thread/read` when local turn state is unavailable.
- Persist the activity as a terminal rollout-trace runtime payload and
reduce it to the corresponding spawn, send, follow-up, or close
interaction edge. `interrupt_agent` is classified as a close-edge
operation.
- Preserve the legacy picker when no path-backed v2 agent is known.

## Compatibility

App-server v2 clients that consumed `collabAgentToolCall` begin/end
pairs for these tools must handle the new completion-only
`subAgentActivity` item. Legacy v1 collaboration behavior is unchanged.

## Screenshot

<img width="684" height="288" alt="Screenshot 2026-06-08 at 15 40 47"
src="https://github.com/user-attachments/assets/194b3cd0-619d-45fb-b587-cf3e2b1b8a1d"
/>

## Testing

- `just test -p codex-app-server-protocol`
- `just test -p codex-rollout-trace`
- Added focused coverage for activity analytics, terminal trace
serialization, spawn-edge reduction, `interrupt_agent` classification,
TUI status rendering without aggregated command output, and clearing
stale running state after a completed turn.
2026-06-09 12:14:48 +02:00
xl-openai a304569c79 [codex] Return workspace directory installed plugins (#27098)
## Summary

- return installed `workspace-directory` remote plugins by default in
`plugin/installed`
- keep shared-with-me installed plugins gated behind `plugin_sharing`
- filter remote installed plugin marketplaces by canonical marketplace
name instead of coarse workspace scope

## Validation

- `just fmt`
- `just test -p codex-core-plugins`
- `just test -p codex-app-server`
- `just fix -p codex-core-plugins`
- `just fix -p codex-app-server`
- `$xin-build` targeted verification:
- `just test -p codex-core-plugins
build_remote_installed_plugin_marketplaces_from_cache_filters_by_marketplace_name`
- `just test -p codex-app-server
plugin_installed_includes_workspace_directory_without_plugin_sharing`
- `just test -p codex-app-server
plugin_installed_includes_remote_shared_with_me_plugins`
- `just test -p codex-app-server
plugin_list_omits_shared_with_me_kind_when_plugin_sharing_disabled`
2026-06-09 01:23:16 -07:00
xl-openai 14660c22d1 Use server app auth requirements for remote plugin install (#27085)
## Summary
- request `includeAppsNeedingAuth=true` when installing remote plugins
- return backend-provided `app_ids_needing_auth` from the remote install
client
- use those app IDs to populate `appsNeedingAuth` without refetching
accessible apps, with fallback for older responses

## Testing
- `just fmt`
- `just test -p codex-app-server`
- `just test -p codex-core-plugins`
- real app-server install/uninstall check with Notion remote plugin
- subagent review found no blocking issues
2026-06-08 21:39:35 -07:00
Tamir DubersteinandChris Bookholt dffc4bf75d [codex] preserve fsmonitor for worktree Git reads (#26880)
Codex forces `core.fsmonitor=false` on internal Git commands so a
repository cannot select an executable fsmonitor helper. This also
disables Git's built-in daemon for `status`, `diff`, and `ls-files`,
turning those worktree reads into full scans in large repositories.

Read the raw effective `core.fsmonitor` value and preserve it only when
Git interprets it as true and advertises built-in daemon support through
`git version --build-options`. Query uncommon boolean spellings back
through Git using the exact effective value. Unset, false, helper paths,
malformed values, probe failures, and unsupported Git builds continue to
force `core.fsmonitor=false`.

Centralize this policy in `git-utils` while keeping process execution in
the existing local and workspace-command adapters. Probe once per
worktree workflow and reuse the result for its Git commands, including
the TUI `/diff` path. Metadata-only commands and repository discovery
remain disabled without probing. Each probe and requested Git process
keeps its own existing timeout, and the decision is not cached because
layered and conditional Git configuration can change while Codex runs.

---------

Co-authored-by: Chris Bookholt <[email protected]>
2026-06-08 21:32:46 -07:00
pakrym-oai 08cb633c06 [codex] Remove remote compaction failure log (#27106)
## Why

`log_remote_compact_failure` was the only consumer of the
compact-request logging payload and most of the token-usage breakdown
fields. Once that failure log is removed, keeping the surrounding
carrier types leaves dead plumbing in the compaction path and context
manager.

## What changed

- Remove `log_remote_compact_failure`, `CompactRequestLogData`, and the
v2 wrapper that only fed that log.
- Let both remote compaction implementations return the original
compaction error directly.
- Replace `TotalTokenUsageBreakdown` with a narrow helper that returns
only the remaining value needed by compaction analytics.
- Keep `estimate_response_item_model_visible_bytes` private to the
context manager implementation.

## Validation

- `cargo check -p codex-core`
2026-06-08 19:23:35 -07:00
canvrno-oai 0beb5c7f32 Preserve cloud requirements across TUI thread resets (#25177)
Fixes a TUI regression where thread transitions such as `/new` and
`/clear` could rebuild config without the cloud requirements loader,
allowing users to fall back to non-cloud-managed settings. The config
refresh path now preserves cloud requirements during thread
reinitialization, and config loading is moved off the deep TUI event
stack to avoid stack-overflow crashes during those reloads.

- Passes the cloud requirements loader through TUI config rebuild paths.
- Keeps cloud requirements applied for `/new`, `/clear`, `/fork`, side
conversations, and session picker transitions.
- Runs config building on a Tokio task so reloads do not occur on the
deep TUI caller stack.
- Adds regression coverage that cloud requirements survive
thread-transition config refreshes.

## Test/Repro:
  - Start Codex with a cloud requirement applied.
  - Use `/new` or `/clear`.
- The refreshed/fresh-session config should still include the cloud
requirements
  
This can be tested with any config item, at this moment for oai staff
the easiest item to test is the `mentions_v2` feature. This is currently
enabled in cloud requirements, but is not enabled by default. As a
result, prior to these changes that feature is disabled after `/new` or
`/clear`. Testing the same steps with a binary from this branch should
not drop the feature enablement.
2026-06-08 18:08:48 -07:00
yuning-oai c656cc4a83 Update web search citation prompt (#27096)
## Summary

- Update the web search tool prompt to require Markdown links for cited
sources.
- Explicitly tell the model not to use `turnX`-style citations in
responses.

## Context


https://openai.slack.com/archives/C0AU83S0ZQU/p1780964147777649?thread_ts=1780352049.512299&cid=C0AU83S0ZQU

## Test plan

- `git diff --check`
- `python3 scripts/format.py --check` (fails only on Rust formatter
setup: rustup cannot create temp files under `/home/dev-user/.rustup`;
Just and Python formatter checks pass when using temp cache dirs)
2026-06-09 00:55:00 +00:00
Boyang Niu e127a0cf99 Add extra config to StoredThread, leave empty for now (#27092) 2026-06-09 00:38:35 +00:00
canvrno-oai 8534912df9 Show effective sandbox modes in /debug-config (#27068)
## Summary
- Render `/debug-config`'s `allowed_sandbox_modes` from the finalized
permission constraints instead of the raw requirements list.
- Add regression coverage for configured full-access and external
sandbox modes being omitted when effective permissions reject them.

## Details
`allowed_sandbox_modes` comes from managed requirements, but the final
permissions can be further constrained by derived validation rules. For
example, `permissions.filesystem.deny_read` requires sandbox
enforcement, so modes that disable or externalize Codex's sandbox are
not actually usable even if they were present in the raw requirements
TOML.

The debug renderer now enumerates the configured sandbox-mode labels and
keeps only those accepted by `Config.permissions`. That makes
`/debug-config` reflect the same effective permission-profile constraint
path used by runtime config validation, while preserving the existing
source/provenance display.

## Validation
- Added a regression test for effective sandbox-mode filtering in
`/debug-config`.
2026-06-08 17:03:52 -07:00
Felipe Coury 4ca2e436e5 fix(tui): linkify complete bare URLs with tildes (#27088)
## Background

Bare URLs containing `~` in their path are currently only clickable up
to the tilde in the interactive TUI. For example, Codex renders the
visible text for:


`https://www.cs.tufts.edu/~nr/cs257/archive/olin-shivers/dissertation.pdf`

but the OSC 8 destination stops at `https://www.cs.tufts.edu/`. This
makes Cmd-click open the wrong location even though the terminal
recognizes the complete URL outside Codex.

Fixes #26774.

## Root Cause

The URL scanner already accepts `~`. The truncation happens earlier:
with strikethrough parsing enabled, `pulldown-cmark` splits this URL
into adjacent decoded `Event::Text` values around the tilde. The
Markdown renderer annotated each text event independently, so only the
first event still looked like a complete URL with a supported scheme.

The renderer now merges adjacent decoded text events before URL
annotation. It preserves the combined source range while retaining
parser-decoded contents, which avoids regressing entities such as
`&amp;`.

## Changes

- Add a small iterator that merges adjacent decoded Markdown text events
and their source ranges.
- Apply it at the Markdown renderer boundary before hyperlink detection.
- Add regression coverage for the reported URL in prose, wrapped table
output, and entity-decoded URLs.

## How to Test

1. Run Codex with `just c`.
2. Ask the assistant to output this exact bare URL with no Markdown link
syntax:

`https://www.cs.tufts.edu/~nr/cs257/archive/olin-shivers/dissertation.pdf`
3. Hold Cmd and hover or click the URL.
4. Confirm the complete URL, including the suffix after `~`, is one
destination.
5. Repeat with the URL inside a Markdown table and confirm wrapped
portions retain the same complete destination.

Targeted tests:

- `just test -p codex-tui url_with_tilde`
- `just test -p codex-tui merged_text_events_preserve_entity_decoding`

The full `codex-tui` test run was also executed. Its only failures were
the two existing Guardian feature-flag tests:

-
`app::tests::update_feature_flags_disabling_guardian_clears_review_policy_and_restores_default`
-
`app::tests::update_feature_flags_disabling_guardian_clears_manual_review_policy_without_history`
2026-06-08 17:02:36 -07:00
Adam Perry @ OpenAI ffec7c0933 Add typed file URIs (#26840)
## Why

Codex needs stable `file:` URI identifiers that can cross process and
operating-system boundaries without eagerly interpreting them as native
paths. Existing fields also need to keep accepting absolute path strings
during migration.

## What changed

- Add `codex-utils-path-uri` with a validated, immutable `PathUri`
wrapper that currently accepts only `file:` URLs.
- Expose URI-level `basename`, `parent`, and `join` operations that
preserve authorities and percent encoding without guessing the source
operating system.
- Keep native conversion explicit through `AbsolutePathBuf` and the
current host rules.
- Serialize as canonical URI text while accepting both URI text and
legacy absolute native paths during deserialization.
- Add adversarial coverage for Windows-looking and POSIX paths, UNC
authorities, encoded metadata characters, non-UTF-8 POSIX paths, URI
hierarchy operations, and legacy serde round trips.
2026-06-08 16:33:41 -07:00
Celia Chen 6042e5810e chore: preserve one more schema layer during large tool compaction (#27084)
## Summary

Some customer MCP tools expose large input schemas that exceed Codex's
compact schema budget even after description stripping. Today, the final
compaction pass collapses complex schemas starting at depth 2, which can
erase important shallow call structure such as small `anyOf` branches,
required fields, and help-mode entry points. In one reported case, this
degraded a tool schema into `query: any | any`, leaving the model
without enough structure to discover the required help call.

This change raises the deep-schema collapse boundary from depth 2 to
depth 3. That preserves one additional layer of the tool contract while
still collapsing deeper expensive subtrees to `{}` when a schema remains
over budget.

## What Changed

- Increased `MAX_COMPACT_TOOL_SCHEMA_DEPTH` from `2` to `3`.
- Updated the schema compaction traversal test to assert the new
collapse boundary.
- The resulting compacted shape keeps useful shallow structure, for
example:
  - top-level argument names
  - shallow `anyOf` branches
  - required object fields
  - nested property names one level deeper than before

## Validation

- Ran `just test -p codex-tools`: 81 tests passed.
- Ran a golden schema corpus comparison over 214 discovered tool input
schemas under `golden_schemas/*/mcp_tools/*/input_schema.json`.
- Depth 2 and depth 3 had identical percentile token counts across the
corpus.
  - Both ended with `0 / 214` schemas over 1k tokens.
- Both ended with `0 / 214` schemas over the 4,000-byte compact JSON
budget.
- Only one golden schema changed, increasing from 49 to 56 tokens, so
this does not appear to introduce a meaningful corpus-wide regression.

Corpus percentile results:

| Percentile | Depth 2 | Depth 3 |
|---|---:|---:|
| p0 | 9 | 9 |
| p10 | 31 | 31 |
| p25 | 54 | 54 |
| p50 | 81 | 81 |
| p75 | 143 | 143 |
| p90 | 290 | 290 |
| p95 | 431 | 431 |
| p99 | 600 | 600 |
| max | 832 | 832 |
2026-06-08 23:07:56 +00:00
Felipe Coury 0473a5cc52 feat(doctor): report editor and pager environment (#27081)
## Background

This was prompted by
[#26858](https://github.com/openai/codex/issues/26858), where the
attached doctor report did not include the editor selection and I had to
[ask which editor was in
use](https://github.com/openai/codex/issues/26858#issuecomment-4653829891)
before investigating the external-editor newline issue. Capturing these
variables in doctor makes that context available up front in future
reports.

`codex doctor` is intended to capture enough local context to diagnose
startup and terminal behavior, but it did not report the environment
variables that select an external editor or configure command pagers.

The TUI [prefers `VISUAL` over
`EDITOR`](https://github.com/openai/codex/blob/56554904babcaacf4444a2cc90716880837dff7c/codex-rs/tui/src/external_editor.rs#L31-L38),
so missing or unexpected values can explain why the external-editor
shortcut fails or launches the wrong command. Pager values are also
useful inherited-shell context even though [unified exec normalizes its
effective pager variables to
`cat`](https://github.com/openai/codex/blob/56554904babcaacf4444a2cc90716880837dff7c/codex-rs/core/src/unified_exec/process_manager.rs#L60-L70).

These variables can contain arbitrary command arguments or inline
environment assignments. The human report is local, but `codex doctor
--json` may be attached to feedback, so the machine-readable report
should not include their raw contents.

## What Changed

- Report `VISUAL` and `EDITOR` in the system environment details, using
`not set` when either variable is absent.
- Report inherited `PAGER`, `GIT_PAGER`, `GH_PAGER`, and `LESS` values
when present.
- Preserve full values in local human output while reducing these fields
to `set` or `not set` in redacted JSON output.
- Add structured check, JSON-redaction, rendered-output, and snapshot
coverage.

## How to Test

1. From `codex-rs`, run Codex with explicit editor and pager variables:

   ```sh
env VISUAL='code --wait' EDITOR=vim PAGER='less -R' GIT_PAGER=delta
GH_PAGER=less LESS=-FRX \
     cargo run -p codex-cli --bin codex -- doctor --no-color
   ```

2. Confirm the `system` details show the full values for all six
variables.
3. Unset the pager variables and rerun the command. Confirm pager rows
are omitted while missing editor variables are shown as `not set`.
4. Run the same configured environment with `doctor --json`. Confirm
each configured editor or pager field is reported as `set` and none of
the raw commands or arguments appear in the JSON.

Targeted tests:

- `just test -p codex-cli` (279 tests passed)
2026-06-08 15:43:08 -07:00
richardopenai feca160da4 [codex] Add OTEL counter descriptions (#26091)
## Why

Metric descriptions should be declared with reusable OTEL instruments
instead of being coupled to individual consumers. Counter descriptions
are the smallest API primitive needed by the exec-server observability
work.

## What changed

- Adds `counter_with_description` while preserving the existing counter
API.
- Caches counters by name and description so instrument metadata remains
part of the declaration identity.
- Covers the exported description together with the existing value and
attribute contract.

This PR only adds counter descriptions. It does not add gauges,
second-based durations, or exec-server adoption.

## Stack

1. **#26091: counter descriptions**
2. #27057: gauge instruments
3. #27058: second-based duration histograms

Related independent coverage: #27059 tests OTLP HTTP log and trace event
export.

The `codex-exec-server` bounded service tag now stays with the
exec-server adoption change instead of this reusable infrastructure
stack.

## Validation

- `just test -p codex-otel`
- `just fix -p codex-otel`
- `just fmt`
2026-06-08 22:29:51 +00:00
xl-openai 381f0de531 Use cached remote plugin catalog for plugin list (#26932)
## Summary

This changes the default remote plugin marketplace listing to use the
cached global remote catalog when it is already present on disk. The
foreground `plugin/list` response can then return from the local catalog
cache instead of waiting on `/ps/plugins/list`.

When a cached global catalog was present at the start of the request,
`plugin/list` still schedules a background refresh through the existing
plugin-list background task path so the disk cache is updated for future
requests. Cache misses keep the existing synchronous remote fetch path
and write the cache, and they do not schedule an extra duplicate
background `/ps/plugins/list` refresh.

Installed/enabled state continues to come from the existing remote
installed overlay path. This change only affects the global remote
catalog directory data used by `plugin/list`.

## Testing

- `just fmt`
- `just test -p codex-app-server
plugin_list_uses_cached_global_remote_catalog_and_refreshes_it`
- `just test -p codex-core-plugins`
- `git diff --check`
2026-06-08 14:47:09 -07:00
xl-openai daf76a57d2 [codex] Prune stale curated plugin caches (#26934)
Curated plugin startup refresh now removes cached plugins whose names no
longer appear in the raw openai-curated marketplace. This prevents users
with the old standalone Google Sheets plugin selected locally from
continuing to load its stale cache after the curated repo drops it.

Existing config is left untouched, and plugins still present in the
marketplace continue to refresh from local curated sources.

Validation:
- `just fmt`
- `just test -p codex-core-plugins`
- `git diff --check`
2026-06-08 14:46:59 -07:00
Celia Chen b89d91f6ff feat: support oneOf and allOf in tool input schemas (#24118)
## Why

Some connector golden schemas use JSON Schema composition keywords
beyond `anyOf`, specifically top-level or nested `oneOf` and `allOf`.
Codex currently needs to preserve those shapes when parsing MCP tool
input schemas so connector tools do not lose valid schema structure
during normalization.

To prevent an increased Responses API error rate, this PR will be merged
after the Responses API supports top-level `oneOf`/`allOf`.

## What Changed

- Adds `oneOf` and `allOf` support to `JsonSchema`, matching the
existing `anyOf` handling.
- Traverses `oneOf` and `allOf` anywhere schema children are visited,
including sanitization, definition reachability, description stripping,
and deep schema compaction.
- Adds a final large-schema compaction pass that prunes schema objects
containing `anyOf`, `oneOf`, or `allOf` to `{}` if earlier compaction
passes still leave the schema over budget.

## Validation
Golden schema token validation over `2,025` schemas under
`golden_schemas`, all parsed successfully. Token count is `o200k_base`
over compact JSON from `parse_tool_input_schema`.

| Percentile | Before PR | After oneOf/allOf | After pruning |
|---|---:|---:|---:|
| p0 | 9 | 9 | 9 |
| p10 | 63 | 64 | 64 |
| p25 | 86 | 87 | 87 |
| p50 | 125 | 128 | 128 |
| p75 | 203 | 206 | 206 |
| p90 | 327 | 333 | 333 |
| p95 | 460 | 473 | 473 |
| p99 | 763 | 779 | 779 |
| max | 891 | 955 | 955 |

Totals:

| Parser state | Total tokens |
|---|---:|
| Before PR | 345,713 |
| After oneOf/allOf | 352,686 |
| After pruning | 352,686 |

The pruning column matches the oneOf/allOf column for this corpus
because no parsed compact golden schema remains over the `4,000`
compact-byte budget after the earlier compaction passes.
2026-06-08 21:41:05 +00:00
fchen-oai 56554904ba [codex] Require complete main-agent skill reads (#27044)
## Summary
- require the main agent to read selected `SKILL.md` files completely,
continuing truncated or paginated reads through EOF
- require the main agent to personally read task-required instruction
references instead of delegating their interpretation
- clarify that progressive disclosure selects relevant files without
permitting partial reads
- preserve subagent use for task work when the selected skill allows it
- cover both absolute-path and aliased-root prompt variants

## Why
Partial reads can skip routing and verification requirements later in
skill instructions. Delegated summaries can also omit constraints the
main agent needs to follow. The existing "Read only enough" wording made
both behaviors appear acceptable.

## Impact
Agents should follow complete selected skill instructions while
continuing to avoid unrelated references, scripts, and assets. Subagents
remain available for task execution where permitted.

## Test plan
- `just test -p codex-core-skills` (101 passed)
- `just fmt`
- `git diff --check`
2026-06-08 14:33:57 -07:00
rhan-oai ee6c91d5cf [codex-analytics] stop sending codex error subreason (#27060)
## Summary
- stop emitting `codex_error_subreason` on `codex_turn_event`
- remove the transient analytics fact plumbing that copied
`CodexErr::InvalidRequest(String)` into the event
- update analytics serialization coverage accordingly

## Why
`codex_error_subreason` is a free-form copy of `InvalidRequest(String)`,
including raw provider 400 bodies in some paths. That makes it unsafe as
an analytics field because it can carry user-derived or sensitive text.

## Validation
- `just fmt`
- `just test -p codex-analytics`
2026-06-08 21:29:06 +00:00
Won Park 123cf62a48 Route image edits through referenced file paths (#26486)
## Why

Image edits should use the exact images selected by the model instead of
inferring edit inputs from conversation history.

## What changed

- Replaced the image tool's `action` argument with optional
`referenced_image_paths`.
- Treats omitted or empty references as generation and populated
references as editing.
- Reads referenced absolute image paths and packages them as image data
URLs for the edit request.
- Removed the previous history-selection and image-count heuristics.
- Updated direct and code-mode tool instructions and calls.
- Added an app-server integration test covering an attached image routed
to the image edit endpoint.

## Validation
- Tested end-to-end on local `just codex` with copy pasted image,
attached image, etc.
- `just test -p codex-image-generation-extension`
- `just test -p codex-app-server
standalone_image_edit_uses_attached_model_visible_image`
- `just fix -p codex-image-generation-extension`
- `just bazel-lock-check`
2026-06-08 14:23:55 -07:00
viyatb-oai 85fd52f7e4 Enforce configured network proxy in codex sandbox (#27035)
## Why

`codex sandbox` can start a network proxy from a configured permission
profile. Previously, sandbox-level containment was tied to managed
network requirements rather than whether a proxy was actually active.
This meant config-driven proxy policies were not consistently enforced
as the sandbox's only network path.

## What changed

- Enable proxy-only network containment whenever `codex sandbox` starts
a network proxy.
- Apply the same active-proxy check to the macOS and Linux sandbox
paths.
- Add a Linux regression test that verifies a sandboxed command cannot
establish a direct connection while the configured proxy is active.

## Test plan

- `just test -p codex-cli debug_sandbox::tests`
- `sandbox_with_network_proxy_blocks_direct_loopback_access` runs on
Linux to cover the config-driven proxy path end to end.
2026-06-08 14:03:37 -07:00
Michael Bolin e0ee491df3 cli: add -P sandbox permissions profile alias (#27054)
## Why

`codex sandbox --permissions-profile` is useful when running commands
under a named permissions profile, but the long option is cumbersome for
a debugging-oriented command. `-p` is already used for the config
profile selector, so `-P` gives the permissions profile selector a
compact, non-conflicting alias.

## What Changed

- Added `short = 'P'` to the `permissions_profile` option for the macOS,
Linux, and Windows sandbox command structs in
[`codex-rs/cli/src/lib.rs`](https://github.com/openai/codex/blob/6d9f9c5cdcaa0a156aa2dabbde259ae5e9e8bc0b/codex-rs/cli/src/lib.rs#L29-L112).
- Added parser coverage for `codex sandbox -P :workspace -- echo` in
[`codex-rs/cli/src/main.rs`](https://github.com/openai/codex/blob/6d9f9c5cdcaa0a156aa2dabbde259ae5e9e8bc0b/codex-rs/cli/src/main.rs#L2883-L2896).

## Verification

- `just test -p codex-cli` passed, including the new
`sandbox_parses_permissions_profile_short_alias` parser test.
2026-06-08 20:59:23 +00:00
pakrym-oai f3c1283411 Pair thread environment settings (#26687)
## Why

Thread cwd and environment selections are a single logical setting in
core: updating one without the other can silently desynchronize the
next-turn execution context. This change makes that relationship
explicit in the internal thread settings flow while preserving the
existing app-server public API shape.

## What changed

- Moved the cwd/environment pair through internal
`ThreadSettingsOverrides.environment_settings` instead of a top-level
internal `cwd` field.
- Kept `thread/settings/update` public params unchanged, with app-server
translating top-level `cwd` into the paired internal settings shape.
- Moved `Op::UserInput` environment overrides into thread settings so
user turns and settings updates use the same core path.
- Updated core, app-server, MCP, memories, sample, and test callsites to
construct the paired settings shape.

## Verification

- `git diff --check`
- Local test run starting after PR creation.
2026-06-08 13:55:15 -07:00
jif f9a680b907 [codex] Calm multi-agent v2 usage prompts (#27037)
## Summary
- tighten the default multi-agent v2 root and subagent usage hints to
bias toward local work
- add a pre-call gate to the v2 spawn_agent description for independent,
bounded, parallelizable subtasks

## Validation
- just fmt
- started just test -p codex-core, but it was interrupted before
completion per follow-up request to commit and push immediately
2026-06-08 22:32:10 +02:00
Adam Perry @ OpenAI f3a8074975 [codex] Clarify PR babysitter state mutations (#27038)
# Why

Codex is doing a bit too much on my PRs that it's babysitting. In
particular I'd like it to not interact with comment threads that involve
other humans -- I should be the one doing human interaction. This is
tricky because it's still very useful to be able to drop review comments
myself and have Codex iterate on them.

## What

This updates `.codex/skills/babysit-pr/SKILL.md` with an explicit GitHub
state mutation policy.
2026-06-08 13:09:06 -07:00
viyatb-oaiandsaud-oai 9e0d7f02c9 fix: preserve auto review across config and delegation (#26230)
## Why

Auto Review should remain the effective approval reviewer when settings
cross runtime boundaries. A config or app-server round trip must not
change the reviewer identity, and delegated work must not silently fall
back to user review.

This requires both a stable canonical serialized value and propagation
of the effective setting. `auto_review` is the canonical value across
protocol and app-server output, while `guardian_subagent` remains
accepted as backward-compatible input.

## What changed

- serialize `ApprovalsReviewer::AutoReview` consistently as
`auto_review` across core protocol and app-server v2
- continue accepting `guardian_subagent` when reading existing config or
client requests
- carry the active turn's approval reviewer into spawned agents
- update config/debug expectations and add delegated-task regression
coverage

## Scope

This does not change Guardian policy or remove compatibility with
existing `guardian_subagent` inputs. It preserves the selected reviewer
across serialization, config reloads, app-server settings, and delegated
task setup.

Related Guardian changes are split independently:

- #26231 adds denials and soft denials
- #26334 retries transient reviewer failures
- #26333 reuses narrowly scoped low-risk approvals
- #26232 adds TUI denial recovery

## Validation

- `just test -p codex-app-server-protocol` (224 passed)
- regression coverage for delegated task reviewer propagation
- serialization coverage for canonical `auto_review` output and legacy
`guardian_subagent` input

---------

Co-authored-by: saud-oai <[email protected]>
2026-06-08 18:59:50 +00:00
Michael Bolin 2375cb6449 ci: template custom runner names by repo (#27024)
## Why

These workflows currently hard-code the `codex` runner group and custom
runner labels. That makes the same workflow definitions less portable
across repository copies or renamed repos, even though the runner fleet
follows the repository name scheme. Template the runner identities from
the repository name so `openai/codex` still resolves to the existing
`codex-*` runners while other repos can use their own `<repo>-*` runner
names.

## What Changed

- Replaced custom runner `group` values such as `codex-runners` with
`${{ github.event.repository.name }}-runners`.
- Replaced custom runner labels such as `codex-linux-x64` and
`codex-windows-arm64` with `${{ github.event.repository.name }}-...`.
- Covered direct `runs-on` objects, matrix `runs_on` entries, reusable
workflow runner inputs, and release runner labels.

## Verification

- Parsed all `.github/workflows/*.yml` files as YAML with Ruby.
- Searched `.github/workflows` to confirm no hardcoded runner-field
`codex-runners` or `codex-*` labels remain.
2026-06-08 11:47:23 -07:00
mpc-oai 0aa9931aea [plugins] Expose marketplace source in marketplace list JSON (#27009)
## Summary
- Follow-up to #26417 and #26631
- Add `marketplaceSource` to `codex plugin marketplace list --json`
entries for configured marketplaces
- Reuse the existing `marketplaceSource` shape from `codex plugin list
--json`
- Keep human-readable marketplace list output unchanged
- Add CLI coverage for configured local and git marketplace sources

Example:

```json
{
  "marketplaces": [
    {
      "name": "debug",
      "root": "/path/to/.codex/.tmp/marketplaces/debug",
      "marketplaceSource": {
        "sourceType": "git",
        "source": "https://example.com/acme/agent-skills.git"
      }
    }
  ]
}
```

## Validation
- `just fmt`
- `just fix -p codex-cli`
- `just test -p codex-cli marketplace_list`
- `just test -p codex-cli`
2026-06-08 13:37:55 -05:00
stefanstokic-oai 6d8e12ac42 [codex] Speed up external agent session imports (#26637)
## Why

Importing large external-agent session histories currently starts a full
live Codex thread for every imported session. This initializes unrelated
runtime systems and repeats expensive transcript, metadata, hashing, and
ledger work.

On a 50-session, 238 MiB fixture, the existing path took roughly 70
seconds to complete the import and 77 seconds end to end.

## What changed

- Persist imported sessions directly through `ThreadStore` instead of
starting full live threads.
- Process imports through a bounded five-session pipeline.
- Parse, extract, and hash each source file in one pass.
- Move blocking source preparation onto the blocking thread pool.
- Reuse prepared content hashes and update the import ledger once per
batch.
- Avoid metadata readback for newly written rollouts.
- Preserve imported conversation history and visible thread metadata.
- Keep the implementation out of `codex-core` and avoid changes to the
public `ThreadStore` trait.

## Performance

For the same 50-session, 238 MiB fixture:

| Path | Import completion | End to end |
| --- | ---: | ---: |
| Existing import | 69.61s | 76.62s |
| This change | 5.95s | 6.58s |

All 50 sessions imported successfully with no warnings or contention
signals.

## Validation

- `just test -p codex-external-agent-sessions`
- `just test -p codex-app-server external_agent_config_import`
- Verified imports do not initialize unrelated required MCP servers.
- Verified previously imported source versions are skipped and changed
sources can be imported again.
- Verified imported rollouts remain readable through thread listing and
history APIs.
2026-06-08 14:16:32 -04:00
rhan-oai f1c18df9ae [codex-analytics] report compaction analytics details (#26680)
## Why

Compaction analytics adds retained image count and compaction summary
output tokens for v1.5 specifically.

## What changed

- Add nullable `retained_image_count` and `compaction_summary_tokens`
fields to `codex_compaction_event`.
- Populate them only for `responses_compaction_v2`: retained images come
from the retained v2 compacted history, and summary tokens come from
`response.completed.token_usage.output_tokens`.
- Leave local and legacy remote compaction events as `null` for these
detail fields.

## Verification

- `just fmt`
- `just fix -p codex-core`
- `just test -p codex-core
build_v2_compacted_history_counts_retained_input_images`
- `git diff --check`
2026-06-08 10:52:31 -07:00
ningyi-oai a815311466 Add HTTP window ID to Responses client metadata (#26923)
## Summary

- Keep the existing `x-codex-window-id` HTTP header unchanged.
- Also send the same window ID in Responses `client_metadata`, allowing
supported backend paths to surface it as
`x-client-meta-x-codex-window-id`.
- Cover normal HTTP Responses and remote compaction v2 requests without
changing window generation or compaction behavior.

## Why

In the `2026-06-06T23` production hour, all 28,729 HTTP compaction
requests had `window_id` in `x-codex-turn-metadata`, but only 73
retained the direct `x-codex-window-id` header. The request-body
`client_metadata` path is already used for installation ID and is
preserved through supported Responses API paths.

This is additive metadata only. It does not change the direct header,
request count, model input, compaction routing, window generation, or
user response behavior.

Legacy `/v1/responses/compact` is intentionally unchanged. Its current
server-side `CompressBody` schema does not accept `client_metadata` and
rejects unknown fields, so supporting that path requires a backend
schema change before the Codex client can safely send this field.

## Validation

- Current head: `219baef3c`, rebased onto `origin/main` at `26d932983`.
- The post-rebase diff remains limited to the original five files (`22`
insertions, `6` deletions); the legacy experiment remains fully
reverted.
- `just test -p codex-core
responses_stream_includes_subagent_header_on_review`: passed; validates
normal HTTP Responses metadata.
- `just test -p codex-core
remote_compact_v2_reuses_compaction_trigger_for_followups`: passed;
validates remote compaction v2.
- `just test -p codex-core
remote_manual_compact_chatgpt_auth_reuses_service_tier_and_prompt_cache_key`:
passed; validates that legacy compact keeps its accepted payload shape.
- `just test -p codex-core
remote_manual_compact_api_auth_omits_service_tier_and_reuses_prompt_cache_key`:
passed; validates the legacy API-key payload as well.
- `just fmt`: passed; an unrelated root `justfile` rewrite produced by
the formatter was discarded.
- `git diff --check origin/main...HEAD`: passed.

The focused server pytest could not start in the local monorepo
environment because test setup is missing the `dotenv` module. Server
source and tests explicitly show that `CompressBody` omits
`client_metadata` and `/v1/responses/compact` returns HTTP 400 for
unknown body fields.
2026-06-08 10:49:59 -07:00
Anton Panasenko b128da272e fix(app-server): avoid blocking connection cleanup (#26852)
## Why

Remote-control app-server sessions can reconnect every 5-7 seconds when
the shared transport-event queue fills. The queue's consumer handled
`ConnectionClosed` by awaiting all in-flight RPCs for the disconnected
connection. A stuck RPC therefore blocked processing of replacement
connection and initialize events until remote-control forwarding hit its
five-second timeout and reconnected again.

Related issue: N/A (internal remote-control incident investigation).

## What Changed

- Split fast RPC admission closure from draining:
`ConnectionRpcGate::close()` rejects queued and future RPCs, while
`shutdown()` continues waiting for RPCs that already started.
- Close a disconnected connection's RPC gate before spawning the
existing RPC drain and resource cleanup in a tracked background task, so
the transport-event consumer remains available without waiting for
active RPCs.
- Reap completed cleanup tasks during normal operation, drain them
during graceful shutdown, and abort them during forced shutdown.
- Add regression coverage for closing with an active RPC, rejecting
post-close requests without polling them, and preserving the existing
shutdown wait behavior.

## Verification

`just test -p codex-app-server --lib connection_rpc_gate` passes all 6
tests, including the new close-versus-drain regression coverage.
2026-06-08 10:20:54 -07:00
Jeremy Rose 6d0e313e23 [codex] Restore release symbol artifacts with line tables (#26202)
## Summary

- Restore separate release symbol archives for macOS, Linux, and Windows
binaries.
- Build release binaries with `line-tables-only` debuginfo instead of
full debuginfo.
- Strip Unix distribution binaries after extracting symbols, preserve
Windows PDBs, and keep symbol archives available to the release job.
- Strip the packaged Linux `bwrap` binary before hashing it so the
embedded digest matches the distributed bytes.

## Root cause

The first symbol-artifact implementation enabled
`CARGO_PROFILE_RELEASE_DEBUG=full`. In the June 2 release runs, macOS
ARM primary builds reached the 90-minute timeout while still inside
`Cargo build`. After the symbol changes were reverted, the same primary
build completed in about 22 minutes. The archive step itself completed
in tens of seconds when reached.

Rust's `line-tables-only` debuginfo level preserves function names and
source locations for symbolication without emitting the heavier variable
and type information from full debuginfo.

## Validation

- Ran `just fmt` from `codex-rs`.
- Ran `just test-github-scripts` from the repository root: 23 tests
passed.
- Ran `bash -n` and `shellcheck` on
`.github/scripts/archive-release-symbols-and-strip-binaries.sh`.
- Parsed both modified workflows as YAML and ran `git diff --check`.
- Built a macOS release smoke binary with `line-tables-only`, archived
its dSYM through the restored script, stripped the production binary,
and verified that `atos` resolves `symbol_smoke_function` to
`main.rs:2`.
- Ran Linux archive-script control-flow coverage with stubbed `objcopy`
and `strip` commands.
- Ran Windows PDB archive staging coverage and verified
underscore-emitted Rust PDB names are staged under shipped hyphenated
binary names.

## Follow-up

The release workflow only runs for tags or manual dispatches, so CI
cannot dry-run the full release matrix on this PR. The next release run
will verify runner time and memory behavior under `line-tables-only`.
2026-06-08 17:16:36 +00:00
rka-oai 26d9329833 [codex] Exclude external tool output from memories (#26821)
## Summary

- add contains_external_context() to tool output so other tools can be
opted out of influencing memory when disable_on_external_context=true
- Classify standalone web-search output as external context (to match
behavior as hosted web search)
- Verify with integration test
2026-06-08 16:53:04 +00:00
402 changed files with 17406 additions and 3484 deletions

No files matched your search

+35 -6
View File
@@ -28,8 +28,8 @@ Accept any of the following:
3. Inspect the `actions` list in the JSON response.
4. If `diagnose_ci_failure` is present, inspect failed run logs and classify the failure.
5. If the failure is likely caused by the current branch, patch code locally, commit, and push. Do not patch random flaky tests, CI infrastructure, dependency outages, runner issues, or other failures that are unrelated to the branch.
6. If `process_review_comment` is present, inspect surfaced review items and decide whether to address them.
7. If a review item is actionable and correct, patch code locally, commit, push, and then mark the associated review thread/comment as resolved once the fix is on GitHub.
6. If `process_review_comment` is present, inspect surfaced published review items and decide whether to address them.
7. If a review item is actionable and correct, patch code locally, commit, push, and then resolve the associated review thread only when allowed by the GitHub state mutation policy below.
8. Do not post replies to human-authored review comments/threads unless the user explicitly confirms the exact response. If a human review item is non-actionable, already addressed, or not valid, surface the item and recommended response to the user instead of replying on GitHub.
9. If the failure is likely flaky/unrelated and `retry_failed_checks` is present, rerun failed jobs with `--retry-failed-now`.
10. If both actionable review feedback and `retry_failed_checks` are present, prioritize review feedback first; a new commit will retrigger CI, so avoid rerunning flaky checks on the old SHA unless you intentionally defer the review change.
@@ -92,16 +92,20 @@ The watcher surfaces review items from:
- Inline review comments
- Review submissions (COMMENT / APPROVED / CHANGES_REQUESTED)
Only act on published feedback. Ignore review submissions in GitHub's `PENDING` state and inline
comments attached to those pending reviews. Do not mark pending review feedback as seen; it should
be eligible to surface after the reviewer submits the review.
It intentionally surfaces Codex reviewer bot feedback (for example comments/reviews from `chatgpt-codex-connector[bot]`) in addition to human reviewer feedback. Most unrelated bot noise should still be ignored.
For safety, the watcher only auto-surfaces trusted human review authors (for example repo OWNER/MEMBER/COLLABORATOR, plus the authenticated operator) and approved review bots such as Codex.
On a fresh watcher state file, existing pending review feedback may be surfaced immediately (not only comments that arrive after monitoring starts). This is intentional so already-open review comments are not missed.
On a fresh watcher state file, existing unaddressed published review feedback may be surfaced immediately (not only comments that arrive after monitoring starts). This is intentional so already-open review comments are not missed.
When you agree with a comment and it is actionable:
1. Patch code locally.
2. Commit with `codex: address PR review feedback (#<n>)`.
3. Push to the PR head branch.
4. After the push succeeds, mark the associated GitHub review thread/comment as resolved.
4. After the push succeeds, resolve the associated GitHub review thread only when allowed by the GitHub state mutation policy below.
5. Resume watching on the new SHA immediately (do not stop after reporting the push).
6. If monitoring was running in `--watch` mode, restart `--watch` immediately after the push in the same turn; do not wait for the user to ask again.
@@ -109,6 +113,31 @@ Do not post replies to human-authored GitHub review comments/threads automatical
If the watcher later surfaces your own approved reply because the authenticated operator is treated as a trusted review author, treat that self-authored item as already handled and do not reply again.
If a code review comment/thread is already marked as resolved in GitHub, treat it as non-actionable and safely ignore it unless new unresolved follow-up feedback appears.
## GitHub State Mutation Policy
You can read any PR state you need for monitoring. Writes must comply with this policy.
You can push PRs to update the code under review or to force CI re-runs as described above.
You can resolve review comment threads from the human who requested babysitting or from the Codex
review bot. When resolving, leave a comment prefixed with `[from Codex]: ` and explain what changes
you made and which commit includes them. Don't touch review threads if other humans other than the
user who requested babysitting have participated.
Before making any changes, fetch the PR state yourself instead of relying on the PR watcher script's
output.
Unless explicitly asked, do not:
* comment on other humans' review threads, communicate with the user in chat instead
* resolve review threads from humans other than the user
* interact with humans other than the user
* mark PRs as drafts or ready for review
* close or reopen PRs
In general, never act on GitHub in ways that would make it hard to tell whether you or the user did
something visible to other humans. When in doubt, ask the user for clarification in chat.
## Git Safety Rules
- Work only on the PR head branch.
@@ -133,10 +162,10 @@ Use this loop in a live Codex session:
3. First check whether the PR is now merged or otherwise closed; if so, report that terminal state and stop polling immediately.
4. Check CI summary, new review items, and mergeability/conflict status.
5. Diagnose CI failures and classify branch-related vs flaky/unrelated. If the overall run is still pending but `failed_jobs` already includes a failed job, fetch that job's logs and diagnose immediately instead of waiting for the whole workflow run to finish. Patch only when the failure is branch-related.
6. For each surfaced review item from another author, patch/commit/push and then resolve it if it is actionable. If it is non-actionable, already addressed, or requires a written answer, surface it to the user with a suggested response instead of posting automatically. If a later snapshot surfaces your own approved reply, treat it as informational and continue without responding again.
6. For each surfaced review item from another author, patch/commit/push if it is actionable, then resolve it only when allowed by the GitHub state mutation policy above. If it is non-actionable, already addressed, or requires a written answer, surface it to the user with a suggested response instead of posting automatically. If a later snapshot surfaces your own approved reply, treat it as informational and continue without responding again.
7. Process actionable review comments before flaky reruns when both are present; if a review fix requires a commit, push it and skip rerunning failed checks on the old SHA.
8. Retry failed checks only when `retry_failed_checks` is present and you are not about to replace the current SHA with a review/CI fix commit. Do not make code changes for unrelated flakes or infrastructure failures just to get CI green.
9. If you pushed a commit, resolved a review thread, or triggered a rerun, report the action briefly and continue polling (do not stop). If a human review comment needs a written GitHub response, stop and ask for confirmation before posting.
9. If you pushed a commit, resolved an eligible review thread, or triggered a rerun, report the action briefly and continue polling (do not stop). If a human review comment needs a written GitHub response, stop and ask for confirmation before posting.
10. After a review-fix push, proactively restart continuous monitoring (`--watch`) in the same turn unless a strict stop condition has already been reached.
11. If everything is passing, mergeable, not blocked on required review approval, and there are no unaddressed review items, report that the PR is currently ready to merge but keep the watcher running so new review comments are surfaced quickly while the PR remains open.
12. If blocked on a user-help-required issue (infra outage, exhausted flaky retries, unclear reviewer request, permissions), report the blocker and stop.
+1 -1
View File
@@ -1,4 +1,4 @@
interface:
display_name: "PR Babysitter"
short_description: "Watch PR review comments, CI, and merge conflicts"
default_prompt: "Babysit the current PR: monitor reviewer comments, CI, and merge-conflict status (prefer the watcher’s --watch mode for live monitoring); surface new review feedback before acting on CI or mergeability work, fix valid issues, push updates, and rerun flaky failures up to 3 times. Do not post replies to human-authored review comments unless the user explicitly confirms the exact response. Do not patch unrelated flaky tests, CI infrastructure, dependency outages, runner issues, or other failures that are not caused by the branch. Keep exactly one watcher session active for the PR (do not leave duplicate --watch terminals running). If you pause monitoring to patch review/CI feedback, restart --watch yourself immediately after the push in the same turn. If a watcher is still running and no strict stop condition has been reached, the task is still in progress: keep consuming watcher output and sending progress updates instead of ending the turn. Do not treat a green + mergeable PR as a terminal stop while it is still open; continue polling autonomously after any push/rerun so newly posted review comments are surfaced until a strict terminal stop condition is reached or the user interrupts."
default_prompt: "Babysit the current PR: monitor published reviewer comments, CI, and merge-conflict status (prefer the watcher’s --watch mode for live monitoring); ignore unpublished comments in pending GitHub reviews; surface new published review feedback before acting on CI or mergeability work, fix valid issues, push updates, and rerun flaky failures up to 3 times. Do not post replies to human-authored review comments unless the user explicitly confirms the exact response. Do not patch unrelated flaky tests, CI infrastructure, dependency outages, runner issues, or other failures that are not caused by the branch. Keep exactly one watcher session active for the PR (do not leave duplicate --watch terminals running). If you pause monitoring to patch review/CI feedback, restart --watch yourself immediately after the push in the same turn. If a watcher is still running and no strict stop condition has been reached, the task is still in progress: keep consuming watcher output and sending progress updates instead of ending the turn. Do not treat a green + mergeable PR as a terminal stop while it is still open; continue polling autonomously after any push/rerun so newly posted review comments are surfaced until a strict terminal stop condition is reached or the user interrupts."
@@ -44,6 +44,9 @@ Reruns only failed jobs (and dependencies) for a workflow run.
- Review submissions:
- `gh api repos/{owner}/{repo}/pulls/<pr_number>/reviews?per_page=100`
Use each inline comment's `pull_request_review_id` to find its parent review. Ignore parent reviews
whose `state` is `PENDING`, along with their inline comments, until the review is submitted.
## JSON fields consumed by the watcher
### `gh pr view`
@@ -452,11 +452,14 @@ def normalize_issue_comments(items):
return out
def normalize_review_comments(items):
def normalize_review_comments(items, review_states):
out = []
for item in items:
if not isinstance(item, dict):
continue
review_id = str(item.get("pull_request_review_id") or "")
if review_states.get(review_id) == "PENDING":
continue
line = item.get("line")
if line is None:
line = item.get("original_line")
@@ -481,6 +484,8 @@ def normalize_reviews(items):
for item in items:
if not isinstance(item, dict):
continue
if str(item.get("state") or "").upper() == "PENDING":
continue
out.append(
{
"kind": "review",
@@ -534,16 +539,33 @@ def fetch_new_review_items(pr, state, fresh_state, authenticated_login=None):
review_payload = gh_api_list_paginated(endpoints["review"], repo=repo)
issue_items = normalize_issue_comments(issue_payload)
review_comment_items = normalize_review_comments(review_comment_payload)
review_states = {
str(item.get("id")): str(item.get("state") or "").upper()
for item in review_payload
if isinstance(item, dict) and item.get("id") not in (None, "")
}
pending_review_ids = {
review_id for review_id, review_state in review_states.items() if review_state == "PENDING"
}
pending_review_comment_ids = {
str(item.get("id"))
for item in review_comment_payload
if isinstance(item, dict)
and item.get("id") not in (None, "")
and str(item.get("pull_request_review_id") or "") in pending_review_ids
}
review_comment_items = normalize_review_comments(review_comment_payload, review_states)
review_items = normalize_reviews(review_payload)
all_items = issue_items + review_comment_items + review_items
seen_issue = {str(x) for x in state.get("seen_issue_comment_ids") or []}
seen_review_comment = {str(x) for x in state.get("seen_review_comment_ids") or []}
seen_review = {str(x) for x in state.get("seen_review_ids") or []}
seen_review_comment.difference_update(pending_review_comment_ids)
seen_review.difference_update(pending_review_ids)
# On a brand-new state file, surface existing review activity instead of
# silently treating it as seen. This avoids missing already-pending review
# silently treating it as seen. This avoids missing already-published review
# feedback when monitoring starts after comments were posted.
new_items = []
@@ -118,6 +118,74 @@ def test_recommend_actions_prioritizes_review_comments():
]
def test_pending_review_feedback_surfaces_only_after_publication(monkeypatch):
state = {
"seen_review_comment_ids": ["20"],
"seen_review_ids": ["10"],
}
review = {
"id": 10,
"user": {"login": "octocat"},
"author_association": "MEMBER",
"state": "PENDING",
"body": "Please rename this.",
"created_at": "2026-06-08T10:00:00Z",
"submitted_at": None,
"html_url": "https://github.com/openai/codex/pull/123#pullrequestreview-10",
}
review_comment = {
"id": 20,
"pull_request_review_id": 10,
"user": {"login": "octocat"},
"author_association": "MEMBER",
"body": "Please rename this.",
"created_at": "2026-06-08T10:00:00Z",
"path": "src/example.rs",
"line": 7,
"html_url": "https://github.com/openai/codex/pull/123#discussion_r20",
}
def fake_list(endpoint, **kwargs):
if endpoint.endswith("/issues/123/comments"):
return []
if endpoint.endswith("/pulls/123/comments"):
return [review_comment]
if endpoint.endswith("/pulls/123/reviews"):
return [review]
raise AssertionError(f"unexpected endpoint: {endpoint}")
monkeypatch.setattr(gh_pr_watch, "gh_api_list_paginated", fake_list)
assert (
gh_pr_watch.fetch_new_review_items(
sample_pr(),
state,
fresh_state=True,
authenticated_login="octocat",
)
== []
)
assert state["seen_review_comment_ids"] == []
assert state["seen_review_ids"] == []
review["state"] = "COMMENTED"
review["submitted_at"] = "2026-06-08T10:05:00Z"
published_items = gh_pr_watch.fetch_new_review_items(
sample_pr(),
state,
fresh_state=False,
authenticated_login="octocat",
)
assert {(item["kind"], item["id"]) for item in published_items} == {
("review", "10"),
("review_comment", "20"),
}
assert state["seen_review_comment_ids"] == ["20"]
assert state["seen_review_ids"] == ["10"]
def test_run_watch_keeps_polling_open_ready_to_merge_pr(monkeypatch):
sleeps = []
events = []
+1
View File
@@ -2,6 +2,7 @@
/codex-rs/core/ @openai/codex-core-agent-team
/codex-rs/ext/extension-api/ @openai/codex-core-agent-team
/codex-rs/prompts/ @openai/codex-core-agent-team
/codex-rs/utils/path-uri/ @openai/codex-core-agent-team
# Keep macOS AKV signing changes reviewed by Codex maintainers.
/.github/actions/setup-akv-pkcs11-codesigning/ @openai/codex-core-agent-team
@@ -0,0 +1,119 @@
#!/usr/bin/env bash
set -euo pipefail
usage() {
cat <<'EOF'
Usage: archive-release-symbols-and-strip-binaries.sh \
--target <rust-target> \
--artifact-name <artifact-name> \
--release-dir <dir> \
--archive-dir <dir> \
--binaries "<space-delimited binary basenames>"
EOF
}
target=""
artifact_name=""
release_dir=""
archive_dir=""
binaries=""
while [[ $# -gt 0 ]]; do
case "$1" in
--target)
target="${2:?--target requires a value}"
shift 2
;;
--artifact-name)
artifact_name="${2:?--artifact-name requires a value}"
shift 2
;;
--release-dir)
release_dir="${2:?--release-dir requires a value}"
shift 2
;;
--archive-dir)
archive_dir="${2:?--archive-dir requires a value}"
shift 2
;;
--binaries)
binaries="${2:?--binaries requires a value}"
shift 2
;;
-h|--help)
usage
exit 0
;;
*)
echo "Unexpected argument: $1" >&2
usage >&2
exit 1
;;
esac
done
if [[ -z "$target" || -z "$artifact_name" || -z "$release_dir" || -z "$archive_dir" || -z "$binaries" ]]; then
usage >&2
exit 1
fi
symbols_root="${RUNNER_TEMP:-/tmp}/codex-symbols-${artifact_name}"
symbols_dir="${symbols_root}/codex-symbols-${artifact_name}"
archive_path="${archive_dir%/}/codex-symbols-${artifact_name}.tar.gz"
rm -rf "$symbols_root"
mkdir -p "$symbols_dir" "$archive_dir"
read -r -a binary_names <<< "$binaries"
case "$target" in
*apple-darwin)
for binary in "${binary_names[@]}"; do
binary_path="${release_dir%/}/${binary}"
dsym_path="${binary_path}.dSYM"
if [[ ! -f "$binary_path" ]]; then
echo "Binary $binary_path not found" >&2
exit 1
fi
if [[ ! -d "$dsym_path" ]]; then
echo "dSYM $dsym_path not found" >&2
exit 1
fi
cp -RL "$dsym_path" "${symbols_dir}/${binary}.dSYM"
strip -S -x "$binary_path"
done
;;
*linux*)
objcopy_bin="${OBJCOPY:-objcopy}"
strip_bin="${STRIP:-strip}"
for binary in "${binary_names[@]}"; do
binary_path="${release_dir%/}/${binary}"
debug_path="${symbols_dir}/${binary}.debug"
if [[ ! -f "$binary_path" ]]; then
echo "Binary $binary_path not found" >&2
exit 1
fi
"$objcopy_bin" --only-keep-debug "$binary_path" "$debug_path"
"$strip_bin" --strip-debug --strip-unneeded "$binary_path"
"$objcopy_bin" --add-gnu-debuglink="$debug_path" "$binary_path"
done
;;
*windows*)
for binary in "${binary_names[@]}"; do
pdb_path="${release_dir%/}/${binary}.pdb"
if [[ ! -f "$pdb_path" ]]; then
echo "PDB $pdb_path not found" >&2
exit 1
fi
cp "$pdb_path" "${symbols_dir}/${binary}.pdb"
done
;;
*)
echo "No symbols packaging support for target: $target" >&2
exit 1
;;
esac
rm -f "$archive_path"
tar -C "$symbols_root" -czf "$archive_path" "codex-symbols-${artifact_name}"
+8 -8
View File
@@ -152,8 +152,8 @@ jobs:
- 3
- 4
runs-on:
group: codex-runners
labels: codex-windows-x64
group: ${{ github.event.repository.name }}-runners
labels: ${{ github.event.repository.name }}-windows-x64
name: Bazel test on windows-latest for x86_64-pc-windows-gnullvm shard ${{ matrix.shard }}/4
environment:
name: bazel
@@ -267,8 +267,8 @@ jobs:
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
timeout-minutes: 40
runs-on:
group: codex-runners
labels: codex-windows-x64
group: ${{ github.event.repository.name }}-runners
labels: ${{ github.event.repository.name }}-windows-x64
name: Bazel test on windows-latest for x86_64-pc-windows-gnullvm (native main)
environment:
name: bazel
@@ -357,8 +357,8 @@ jobs:
- os: windows-latest
target: x86_64-pc-windows-gnullvm
runs_on:
group: codex-runners
labels: codex-windows-x64
group: ${{ github.event.repository.name }}-runners
labels: ${{ github.event.repository.name }}-windows-x64
runs-on: ${{ matrix.runs_on || matrix.os }}
name: Bazel clippy on ${{ matrix.os }} for ${{ matrix.target }}
environment:
@@ -453,8 +453,8 @@ jobs:
- os: windows-latest
target: x86_64-pc-windows-gnullvm
runs_on:
group: codex-runners
labels: codex-windows-x64
group: ${{ github.event.repository.name }}-runners
labels: ${{ github.event.repository.name }}-windows-x64
runs-on: ${{ matrix.runs_on || matrix.os }}
name: Verify release build on ${{ matrix.os }} for ${{ matrix.target }}
environment:
+32 -32
View File
@@ -112,8 +112,8 @@ jobs:
- name: Windows
runner: windows-x64
runs_on:
group: codex-runners
labels: codex-windows-x64
group: ${{ github.event.repository.name }}-runners
labels: ${{ github.event.repository.name }}-windows-x64
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
@@ -185,38 +185,38 @@ jobs:
target: x86_64-unknown-linux-musl
profile: dev
runs_on:
group: codex-runners
labels: codex-linux-x64
group: ${{ github.event.repository.name }}-runners
labels: ${{ github.event.repository.name }}-linux-x64
- runner: ubuntu-24.04
target: x86_64-unknown-linux-gnu
profile: dev
runs_on:
group: codex-runners
labels: codex-linux-x64
group: ${{ github.event.repository.name }}-runners
labels: ${{ github.event.repository.name }}-linux-x64
- runner: ubuntu-24.04-arm
target: aarch64-unknown-linux-musl
profile: dev
runs_on:
group: codex-runners
labels: codex-linux-arm64
group: ${{ github.event.repository.name }}-runners
labels: ${{ github.event.repository.name }}-linux-arm64
- runner: ubuntu-24.04-arm
target: aarch64-unknown-linux-gnu
profile: dev
runs_on:
group: codex-runners
labels: codex-linux-arm64
group: ${{ github.event.repository.name }}-runners
labels: ${{ github.event.repository.name }}-linux-arm64
- runner: windows-x64
target: x86_64-pc-windows-msvc
profile: dev
runs_on:
group: codex-runners
labels: codex-windows-x64
group: ${{ github.event.repository.name }}-runners
labels: ${{ github.event.repository.name }}-windows-x64
- runner: windows-arm64
target: aarch64-pc-windows-msvc
profile: dev
runs_on:
group: codex-runners
labels: codex-windows-arm64
group: ${{ github.event.repository.name }}-runners
labels: ${{ github.event.repository.name }}-windows-arm64
# Also run representative release builds on Mac and Linux because
# there could be release-only build errors we want to catch.
@@ -229,26 +229,26 @@ jobs:
target: x86_64-unknown-linux-musl
profile: release
runs_on:
group: codex-runners
labels: codex-linux-x64
group: ${{ github.event.repository.name }}-runners
labels: ${{ github.event.repository.name }}-linux-x64
- runner: ubuntu-24.04-arm
target: aarch64-unknown-linux-musl
profile: release
runs_on:
group: codex-runners
labels: codex-linux-arm64
group: ${{ github.event.repository.name }}-runners
labels: ${{ github.event.repository.name }}-linux-arm64
- runner: windows-x64
target: x86_64-pc-windows-msvc
profile: release
runs_on:
group: codex-runners
labels: codex-windows-x64
group: ${{ github.event.repository.name }}-runners
labels: ${{ github.event.repository.name }}-windows-x64
- runner: windows-arm64
target: aarch64-pc-windows-msvc
profile: release
runs_on:
group: codex-runners
labels: codex-windows-arm64
group: ${{ github.event.repository.name }}-runners
labels: ${{ github.event.repository.name }}-windows-arm64
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
@@ -479,8 +479,8 @@ jobs:
uses: ./.github/workflows/rust-ci-full-nextest-platform.yml
with:
runner: ubuntu-24.04
runner_group: codex-runners
runner_labels: codex-linux-x64
runner_group: ${{ github.event.repository.name }}-runners
runner_labels: ${{ github.event.repository.name }}-linux-x64
target: x86_64-unknown-linux-gnu
profile: ci-test
artifact_id: linux-x64-remote
@@ -493,8 +493,8 @@ jobs:
uses: ./.github/workflows/rust-ci-full-nextest-platform.yml
with:
runner: ubuntu-24.04-arm
runner_group: codex-runners
runner_labels: codex-linux-arm64
runner_group: ${{ github.event.repository.name }}-runners
runner_labels: ${{ github.event.repository.name }}-linux-arm64
target: aarch64-unknown-linux-gnu
profile: ci-test
artifact_id: linux-arm64
@@ -506,8 +506,8 @@ jobs:
uses: ./.github/workflows/rust-ci-full-nextest-platform.yml
with:
runner: windows-x64
runner_group: codex-runners
runner_labels: codex-windows-x64
runner_group: ${{ github.event.repository.name }}-runners
runner_labels: ${{ github.event.repository.name }}-windows-x64
target: x86_64-pc-windows-msvc
profile: ci-test
artifact_id: windows-x64
@@ -519,11 +519,11 @@ jobs:
uses: ./.github/workflows/rust-ci-full-nextest-platform.yml
with:
runner: windows-arm64
runner_group: codex-runners
runner_labels: codex-windows-arm64
runner_group: ${{ github.event.repository.name }}-runners
runner_labels: ${{ github.event.repository.name }}-windows-arm64
archive_runner: windows-x64
archive_runner_group: codex-runners
archive_runner_labels: codex-windows-x64
archive_runner_group: ${{ github.event.repository.name }}-runners
archive_runner_labels: ${{ github.event.repository.name }}-windows-x64
target: aarch64-pc-windows-msvc
profile: ci-test
artifact_id: windows-arm64
+2 -2
View File
@@ -176,8 +176,8 @@ jobs:
runner: windows-x64
timeout_minutes: 30
runs_on:
group: codex-runners
labels: codex-windows-x64
group: ${{ github.event.repository.name }}-runners
labels: ${{ github.event.repository.name }}-windows-x64
steps:
- name: Check whether argument comment lint should run
id: argument_comment_lint_gate
@@ -57,8 +57,8 @@ jobs:
runner_binary: argument-comment-lint.exe
cargo_dylint_binary: cargo-dylint.exe
runs_on:
group: codex-runners
labels: codex-windows-x64
group: ${{ github.event.repository.name }}-runners
labels: ${{ github.event.repository.name }}-windows-x64
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+47 -18
View File
@@ -29,43 +29,43 @@ jobs:
bundle: primary
binaries: "codex codex-responses-api-proxy"
runs_on:
group: codex-runners
labels: codex-windows-x64
group: ${{ github.event.repository.name }}-runners
labels: ${{ github.event.repository.name }}-windows-x64
- runner: windows-arm64
target: aarch64-pc-windows-msvc
bundle: primary
binaries: "codex codex-responses-api-proxy"
runs_on:
group: codex-runners
labels: codex-windows-arm64
group: ${{ github.event.repository.name }}-runners
labels: ${{ github.event.repository.name }}-windows-arm64
- runner: windows-x64
target: x86_64-pc-windows-msvc
bundle: helpers
binaries: "codex-windows-sandbox-setup codex-command-runner"
runs_on:
group: codex-runners
labels: codex-windows-x64
group: ${{ github.event.repository.name }}-runners
labels: ${{ github.event.repository.name }}-windows-x64
- runner: windows-arm64
target: aarch64-pc-windows-msvc
bundle: helpers
binaries: "codex-windows-sandbox-setup codex-command-runner"
runs_on:
group: codex-runners
labels: codex-windows-arm64
group: ${{ github.event.repository.name }}-runners
labels: ${{ github.event.repository.name }}-windows-arm64
- runner: windows-x64
target: x86_64-pc-windows-msvc
bundle: app-server
binaries: "codex-app-server"
runs_on:
group: codex-runners
labels: codex-windows-x64
group: ${{ github.event.repository.name }}-runners
labels: ${{ github.event.repository.name }}-windows-x64
- runner: windows-arm64
target: aarch64-pc-windows-msvc
bundle: app-server
binaries: "codex-app-server"
runs_on:
group: codex-runners
labels: codex-windows-arm64
group: ${{ github.event.repository.name }}-runners
labels: ${{ github.event.repository.name }}-windows-arm64
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
@@ -112,10 +112,22 @@ jobs:
- name: Stage Windows binaries
shell: bash
run: |
output_dir="target/${{ matrix.target }}/release/staged-${{ matrix.bundle }}"
release_dir="target/${{ matrix.target }}/release"
output_dir="$release_dir/staged-${{ matrix.bundle }}"
mkdir -p "$output_dir"
for binary in ${{ matrix.binaries }}; do
cp "target/${{ matrix.target }}/release/${binary}.exe" "$output_dir/${binary}.exe"
pdb_name="${binary//-/_}"
pdb_path="$release_dir/${pdb_name}.pdb"
if [[ ! -f "$pdb_path" ]]; then
pdb_path="$release_dir/${binary}.pdb"
fi
if [[ ! -f "$pdb_path" ]]; then
echo "PDB for $binary not found at $release_dir/${pdb_name}.pdb or $release_dir/${binary}.pdb" >&2
exit 1
fi
cp "$release_dir/${binary}.exe" "$output_dir/${binary}.exe"
cp "$pdb_path" "$output_dir/${binary}.pdb"
done
- name: Upload Windows binaries
@@ -150,13 +162,13 @@ jobs:
- runner: windows-x64
target: x86_64-pc-windows-msvc
runs_on:
group: codex-runners
labels: codex-windows-x64
group: ${{ github.event.repository.name }}-runners
labels: ${{ github.event.repository.name }}-windows-x64
- runner: windows-arm64
target: aarch64-pc-windows-msvc
runs_on:
group: codex-runners
labels: codex-windows-arm64
group: ${{ github.event.repository.name }}-runners
labels: ${{ github.event.repository.name }}-windows-arm64
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
@@ -201,6 +213,23 @@ jobs:
account-name: ${{ secrets.AZURE_ARTIFACT_SIGNING_ACCOUNT_NAME }}
certificate-profile-name: ${{ secrets.AZURE_ARTIFACT_SIGNING_CERTIFICATE_PROFILE_NAME }}
- name: Build symbols archive
shell: bash
run: |
bash "${GITHUB_WORKSPACE}/.github/scripts/archive-release-symbols-and-strip-binaries.sh" \
--target "${{ matrix.target }}" \
--artifact-name "${{ matrix.target }}" \
--release-dir "target/${{ matrix.target }}/release" \
--archive-dir "symbols-dist/${{ matrix.target }}" \
--binaries "${WINDOWS_BINARIES}"
- name: Upload symbols archive
uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
with:
name: ${{ matrix.target }}-symbols
path: codex-rs/symbols-dist/${{ matrix.target }}/*
if-no-files-found: error
- name: Stage artifacts
shell: bash
run: |
+42 -5
View File
@@ -64,6 +64,8 @@ jobs:
run:
working-directory: codex-rs
env:
# macOS release packages archive packed dSYM bundles before stripping.
CARGO_PROFILE_RELEASE_SPLIT_DEBUGINFO: ${{ contains(matrix.target, 'apple-darwin') && 'packed' || 'off' }}
# Use the git CLI instead of Cargo's libgit2 path for git dependencies.
# macOS release runners have intermittently failed to fetch nested
# submodules through SecureTransport/libgit2, especially libwebrtc's
@@ -99,25 +101,25 @@ jobs:
binaries: "codex-app-server"
build_dmg: "false"
# Release artifacts intentionally ship MUSL-linked Linux binaries.
- runner: codex-linux-x64-xl
- runner: ${{ github.event.repository.name }}-linux-x64-xl
target: x86_64-unknown-linux-musl
bundle: primary
artifact_name: x86_64-unknown-linux-musl
binaries: "codex codex-responses-api-proxy bwrap"
build_dmg: "false"
- runner: codex-linux-x64-xl
- runner: ${{ github.event.repository.name }}-linux-x64-xl
target: x86_64-unknown-linux-musl
bundle: app-server
artifact_name: x86_64-unknown-linux-musl-app-server
binaries: "codex-app-server"
build_dmg: "false"
- runner: codex-linux-arm64
- runner: ${{ github.event.repository.name }}-linux-arm64
target: aarch64-unknown-linux-musl
bundle: primary
artifact_name: aarch64-unknown-linux-musl
binaries: "codex codex-responses-api-proxy bwrap"
build_dmg: "false"
- runner: codex-linux-arm64
- runner: ${{ github.event.repository.name }}-linux-arm64
target: aarch64-unknown-linux-musl
bundle: app-server
artifact_name: aarch64-unknown-linux-musl-app-server
@@ -163,7 +165,7 @@ jobs:
run: |
set -euo pipefail
sudo apt-get update -y
sudo DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends pkg-config libcap-dev
sudo DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends binutils pkg-config libcap-dev
- uses: dtolnay/rust-toolchain@e081816240890017053eacbb1bdf337761dc5582 # 1.95.0
with:
targets: ${{ matrix.target }}
@@ -222,6 +224,10 @@ jobs:
exit 1
fi
# Codex embeds this digest at build time and verifies the bundled
# bwrap resource before use. Strip bwrap before hashing so the digest
# covers the exact bytes that the release packages.
strip --strip-debug --strip-unneeded "$bwrap_path"
digest="$(sha256sum "$bwrap_path" | awk '{print $1}')"
echo "CODEX_BWRAP_SHA256=${digest}" >> "$GITHUB_ENV"
echo "Built bwrap ${bwrap_path} with sha256:${digest}"
@@ -235,6 +241,11 @@ jobs:
fi
build_args=()
for binary in ${{ matrix.binaries }}; do
# bwrap was built, finalized, and hashed before this build so
# Codex can embed the digest of the bytes that will be packaged.
if [[ "$binary" == "bwrap" ]]; then
continue
fi
build_args+=(--bin "$binary")
done
cargo build --target "$target" --release --timings "${build_args[@]}"
@@ -246,6 +257,32 @@ jobs:
path: codex-rs/target/**/cargo-timings/cargo-timing.html
if-no-files-found: warn
- name: Build symbols archive and strip binaries
shell: bash
run: |
binaries=()
for binary in ${{ matrix.binaries }}; do
# bwrap is already stripped before hashing. Its symbols are not
# useful enough to justify a separate pre-Codex symbols pass.
if [[ "$binary" == "bwrap" ]]; then
continue
fi
binaries+=("$binary")
done
bash "${GITHUB_WORKSPACE}/.github/scripts/archive-release-symbols-and-strip-binaries.sh" \
--target "${{ matrix.target }}" \
--artifact-name "${{ matrix.artifact_name }}" \
--release-dir "target/${{ matrix.target }}/release" \
--archive-dir "symbols-dist/${{ matrix.artifact_name }}" \
--binaries "${binaries[*]}"
- name: Upload symbols archive
uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
with:
name: ${{ matrix.artifact_name }}-symbols
path: codex-rs/symbols-dist/${{ matrix.artifact_name }}/*
if-no-files-found: error
- if: ${{ runner.os == 'macOS' }}
name: Stage unsigned macOS artifacts
shell: bash
+4 -4
View File
@@ -8,8 +8,8 @@ on:
jobs:
python-sdk:
runs-on:
group: codex-runners
labels: codex-linux-x64
group: ${{ github.event.repository.name }}-runners
labels: ${{ github.event.repository.name }}-linux-x64
timeout-minutes: 10
steps:
- name: Checkout repository
@@ -43,8 +43,8 @@ jobs:
sdks:
runs-on:
group: codex-runners
labels: codex-linux-x64
group: ${{ github.event.repository.name }}-runners
labels: ${{ github.event.repository.name }}-linux-x64
timeout-minutes: 10
environment:
name: bazel
+14
View File
@@ -8,12 +8,20 @@ retries = 1
[profile.default.junit]
path = "junit.xml"
[profile.local]
inherits = "default"
[test-groups.app_server_protocol_codegen]
max-threads = 1
[test-groups.app_server_integration]
max-threads = 1
# Higher concurrency causes integration test timeouts under resource contention
# on common developer machines.
[test-groups.app_server_integration_local]
max-threads = 4
[test-groups.core_apply_patch_cli_integration]
max-threads = 1
@@ -42,6 +50,12 @@ test-group = 'app_server_protocol_codegen'
filter = 'package(codex-app-server) & kind(test)'
test-group = 'app_server_integration'
[[profile.local.overrides]]
# Use up to four app-server subprocesses locally. The global nextest pool still
# limits this to the machine's logical CPU count.
filter = 'package(codex-app-server) & kind(test)'
test-group = 'app_server_integration_local'
[[profile.default.overrides]]
# These tests exercise full Codex turns and apply_patch execution, and they are
# sensitive to Windows runner process-startup stalls when many cases launch at once.
+41
View File
@@ -1982,6 +1982,7 @@ dependencies = [
"codex-image-generation-extension",
"codex-login",
"codex-mcp",
"codex-mcp-extension",
"codex-memories-extension",
"codex-memories-write",
"codex-model-provider",
@@ -1994,6 +1995,7 @@ dependencies = [
"codex-rollout",
"codex-sandboxing",
"codex-shell-command",
"codex-skills-extension",
"codex-state",
"codex-thread-store",
"codex-tools",
@@ -2919,9 +2921,12 @@ name = "codex-extension-api"
version = "0.0.0"
dependencies = [
"async-trait",
"codex-config",
"codex-context-fragments",
"codex-protocol",
"codex-tools",
"pretty_assertions",
"tokio",
]
[[package]]
@@ -3106,6 +3111,7 @@ dependencies = [
"codex-protocol",
"codex-tools",
"codex-utils-absolute-path",
"codex-utils-image",
"http 1.4.0",
"pretty_assertions",
"schemars 0.8.22",
@@ -3243,6 +3249,23 @@ dependencies = [
"url",
]
[[package]]
name = "codex-mcp-extension"
version = "0.0.0"
dependencies = [
"async-trait",
"codex-config",
"codex-core",
"codex-core-plugins",
"codex-extension-api",
"codex-features",
"codex-login",
"codex-mcp",
"pretty_assertions",
"tempfile",
"tokio",
]
[[package]]
name = "codex-mcp-server"
version = "0.0.0"
@@ -3795,8 +3818,11 @@ dependencies = [
"async-trait",
"codex-core",
"codex-core-skills",
"codex-exec-server",
"codex-extension-api",
"codex-protocol",
"codex-utils-absolute-path",
"codex-utils-string",
"pretty_assertions",
"tokio",
]
@@ -4151,6 +4177,21 @@ dependencies = [
"tempfile",
]
[[package]]
name = "codex-utils-path-uri"
version = "0.0.0"
dependencies = [
"codex-utils-absolute-path",
"pretty_assertions",
"schemars 0.8.22",
"serde",
"serde_json",
"thiserror 2.0.18",
"ts-rs",
"url",
"urlencoding",
]
[[package]]
name = "codex-utils-plugins"
version = "0.0.0"
+8 -3
View File
@@ -49,6 +49,7 @@ members = [
"ext/guardian",
"ext/image-generation",
"ext/memories",
"ext/mcp",
"ext/skills",
"ext/web-search",
"external-agent-migration",
@@ -83,6 +84,7 @@ members = [
"tools",
"v8-poc",
"utils/absolute-path",
"utils/path-uri",
"utils/cargo-bin",
"git-utils",
"utils/cache",
@@ -190,6 +192,7 @@ codex-web-search-extension = { path = "ext/web-search" }
codex-memories-read = { path = "memories/read" }
codex-memories-write = { path = "memories/write" }
codex-mcp = { path = "codex-mcp" }
codex-mcp-extension = { path = "ext/mcp" }
codex-mcp-server = { path = "mcp-server" }
codex-model-provider-info = { path = "model-provider-info" }
codex-models-manager = { path = "models-manager" }
@@ -211,6 +214,7 @@ codex-sandboxing = { path = "sandboxing" }
codex-secrets = { path = "secrets" }
codex-shell-command = { path = "shell-command" }
codex-shell-escalation = { path = "shell-escalation" }
codex-skills-extension = { path = "ext/skills" }
codex-skills = { path = "skills" }
codex-state = { path = "state" }
codex-stdio-to-uds = { path = "stdio-to-uds" }
@@ -501,10 +505,11 @@ strip = "symbols"
[profile.release]
lto = "thin"
debug = "line-tables-only"
split-debuginfo = "off"
# Because we bundle some of these executables with the TypeScript CLI, we
# remove everything to make the binary as small as possible.
strip = "symbols"
# Keep release binaries symbolicateable until packaging has archived the
# sidecar symbols and stripped the binaries.
strip = false
# See https://github.com/openai/codex/issues/1411 for details.
codegen-units = 1
@@ -108,6 +108,7 @@ use codex_app_server_protocol::ServerNotification;
use codex_app_server_protocol::ServerRequest;
use codex_app_server_protocol::ServerResponse;
use codex_app_server_protocol::SessionSource as AppServerSessionSource;
use codex_app_server_protocol::SubAgentActivityKind;
use codex_app_server_protocol::Thread;
use codex_app_server_protocol::ThreadArchiveParams;
use codex_app_server_protocol::ThreadArchiveResponse;
@@ -1253,6 +1254,8 @@ fn compaction_event_serializes_expected_shape() {
error: None,
active_context_tokens_before: 120_000,
active_context_tokens_after: 18_000,
retained_image_count: None,
compaction_summary_tokens: None,
started_at: 100,
completed_at: 106,
duration_ms: Some(6543),
@@ -1301,6 +1304,8 @@ fn compaction_event_serializes_expected_shape() {
"error": null,
"active_context_tokens_before": 120000,
"active_context_tokens_after": 18000,
"retained_image_count": null,
"compaction_summary_tokens": null,
"started_at": 100,
"completed_at": 106,
"duration_ms": 6543
@@ -1369,7 +1374,7 @@ fn thread_initialized_event_serializes_expected_shape() {
},
model: "gpt-5".to_string(),
ephemeral: true,
thread_source: Some(ThreadSource::User),
thread_source: Some(ThreadSource::Feature("automation".to_string())),
initialization_mode: ThreadInitializationMode::New,
subagent_source: None,
parent_thread_id: None,
@@ -1402,7 +1407,7 @@ fn thread_initialized_event_serializes_expected_shape() {
},
"model": "gpt-5",
"ephemeral": true,
"thread_source": "user",
"thread_source": "automation",
"initialization_mode": "new",
"subagent_source": null,
"parent_thread_id": null,
@@ -1821,6 +1826,8 @@ async fn compaction_event_ingests_custom_fact() {
error: Some("context limit exceeded".to_string()),
active_context_tokens_before: 131_000,
active_context_tokens_after: 131_000,
retained_image_count: None,
compaction_summary_tokens: None,
started_at: 100,
completed_at: 101,
duration_ms: Some(1200),
@@ -2743,6 +2750,8 @@ async fn subagent_thread_started_inherits_parent_connection_for_new_thread() {
error: None,
active_context_tokens_before: 131_000,
active_context_tokens_after: 64_000,
retained_image_count: None,
compaction_summary_tokens: None,
started_at: 100,
completed_at: 101,
duration_ms: Some(1200),
@@ -3310,7 +3319,6 @@ fn turn_event_serializes_expected_shape() {
status: Some(TurnStatus::Completed),
turn_error: None,
codex_error_kind: None,
codex_error_subreason: None,
codex_error_http_status_code: None,
steer_count: Some(0),
total_tool_call_count: None,
@@ -3383,7 +3391,6 @@ fn turn_event_serializes_expected_shape() {
"status": "completed",
"turn_error": null,
"codex_error_kind": null,
"codex_error_subreason": null,
"codex_error_http_status_code": null,
"steer_count": 0,
"total_tool_call_count": null,
@@ -3788,6 +3795,12 @@ async fn turn_event_counts_completed_tool_items() {
reasoning_effort: None,
agents_states: Default::default(),
},
ThreadItem::SubAgentActivity {
id: "sub-agent-activity-1".to_string(),
kind: SubAgentActivityKind::Interacted,
agent_thread_id: "thread-child".to_string(),
agent_path: "/root/child".to_string(),
},
ThreadItem::WebSearch {
id: "web-1".to_string(),
query: "codex".to_string(),
@@ -3835,14 +3848,14 @@ async fn turn_event_counts_completed_tool_items() {
.find(|event| matches!(event, TrackEventRequest::TurnEvent(_)))
.expect("turn event should be emitted");
let payload = serde_json::to_value(turn_event).expect("serialize turn event");
assert_eq!(payload["event_params"]["total_tool_call_count"], json!(7));
assert_eq!(payload["event_params"]["total_tool_call_count"], json!(8));
assert_eq!(payload["event_params"]["shell_command_count"], json!(1));
assert_eq!(payload["event_params"]["file_change_count"], json!(1));
assert_eq!(payload["event_params"]["mcp_tool_call_count"], json!(1));
assert_eq!(payload["event_params"]["dynamic_tool_call_count"], json!(1));
assert_eq!(
payload["event_params"]["subagent_tool_call_count"],
json!(1)
json!(2)
);
assert_eq!(payload["event_params"]["web_search_count"], json!(1));
assert_eq!(payload["event_params"]["image_generation_count"], json!(1));
@@ -4090,10 +4103,6 @@ async fn turn_lifecycle_emits_failed_turn_event() {
payload["event_params"]["codex_error_kind"],
json!("invalid_request")
);
assert_eq!(
payload["event_params"]["codex_error_subreason"],
json!("unknown turn environment id `env-2`")
);
assert_eq!(
payload["event_params"]["codex_error_http_status_code"],
json!(null)
+4 -1
View File
@@ -758,6 +758,8 @@ pub(crate) struct CodexCompactionEventParams {
pub(crate) error: Option<String>,
pub(crate) active_context_tokens_before: i64,
pub(crate) active_context_tokens_after: i64,
pub(crate) retained_image_count: Option<usize>,
pub(crate) compaction_summary_tokens: Option<i64>,
pub(crate) started_at: u64,
pub(crate) completed_at: u64,
pub(crate) duration_ms: Option<u64>,
@@ -801,7 +803,6 @@ pub(crate) struct CodexTurnEventParams {
pub(crate) status: Option<TurnStatus>,
pub(crate) turn_error: Option<CodexErrorInfo>,
pub(crate) codex_error_kind: Option<CodexErrKind>,
pub(crate) codex_error_subreason: Option<String>,
pub(crate) codex_error_http_status_code: Option<u16>,
pub(crate) steer_count: Option<usize>,
pub(crate) total_tool_call_count: Option<usize>,
@@ -970,6 +971,8 @@ pub(crate) fn codex_compaction_event_params(
error: input.error,
active_context_tokens_before: input.active_context_tokens_before,
active_context_tokens_after: input.active_context_tokens_after,
retained_image_count: input.retained_image_count,
compaction_summary_tokens: input.compaction_summary_tokens,
started_at: input.started_at,
completed_at: input.completed_at,
duration_ms: input.duration_ms,
+2 -24
View File
@@ -30,9 +30,6 @@ use codex_protocol::request_permissions::RequestPermissionsResponse;
use serde::Serialize;
use std::path::PathBuf;
const INVALID_REQUEST_SUBREASON_MAX_BYTES: usize = 512;
const INVALID_REQUEST_SUBREASON_TRUNCATION_SUFFIX: &str = "...";
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct AcceptedLineFingerprint {
pub path_hash: String,
@@ -182,7 +179,6 @@ pub(crate) enum CodexErrKind {
#[derive(Clone)]
pub(crate) struct TurnCodexError {
pub(crate) kind: CodexErrKind,
pub(crate) subreason: Option<String>,
pub(crate) http_status_code: Option<u16>,
}
@@ -190,26 +186,6 @@ impl TurnCodexError {
fn from_codex_err(error: &CodexErr) -> Self {
Self {
kind: error.into(),
subreason: match error {
CodexErr::InvalidRequest(message) => {
// InvalidRequest can contain raw provider response bodies, so bound the
// analytics copy without changing the source CodexErr.
let subreason = if message.len() <= INVALID_REQUEST_SUBREASON_MAX_BYTES {
message.clone()
} else {
let truncated_len = message.floor_char_boundary(
INVALID_REQUEST_SUBREASON_MAX_BYTES
.saturating_sub(INVALID_REQUEST_SUBREASON_TRUNCATION_SUFFIX.len()),
);
format!(
"{}{INVALID_REQUEST_SUBREASON_TRUNCATION_SUFFIX}",
&message[..truncated_len]
)
};
Some(subreason)
}
_ => None,
},
http_status_code: error.http_status_code_value(),
}
}
@@ -434,6 +410,8 @@ pub struct CodexCompactionEvent {
pub error: Option<String>,
pub active_context_tokens_before: i64,
pub active_context_tokens_after: i64,
pub retained_image_count: Option<usize>,
pub compaction_summary_tokens: Option<i64>,
pub started_at: u64,
pub completed_at: u64,
pub duration_ms: Option<u64>,
+21 -7
View File
@@ -360,7 +360,9 @@ impl TurnToolCounts {
ThreadItem::FileChange { .. } => self.file_change += 1,
ThreadItem::McpToolCall { .. } => self.mcp_tool_call += 1,
ThreadItem::DynamicToolCall { .. } => self.dynamic_tool_call += 1,
ThreadItem::CollabAgentToolCall { .. } => self.subagent_tool_call += 1,
ThreadItem::CollabAgentToolCall { .. } | ThreadItem::SubAgentActivity { .. } => {
self.subagent_tool_call += 1;
}
ThreadItem::WebSearch { .. } => self.web_search += 1,
ThreadItem::ImageGeneration { .. } => self.image_generation += 1,
ThreadItem::UserMessage { .. }
@@ -1091,6 +1093,18 @@ impl AnalyticsReducer {
);
}
ServerNotification::ItemCompleted(notification) => {
if matches!(notification.item, ThreadItem::SubAgentActivity { .. }) {
let Some(turn_state) = self.turns.get_mut(&notification.turn_id) else {
tracing::warn!(
thread_id = %notification.thread_id,
turn_id = %notification.turn_id,
"dropping sub-agent activity tool count update: missing turn state"
);
return;
};
turn_state.tool_counts.record(&notification.item);
return;
}
let Some(item_id) = tracked_tool_item_id(&notification.item) else {
return;
};
@@ -1249,7 +1263,7 @@ impl AnalyticsReducer {
thread_metadata.session_id.clone(),
connection_state.app_server_client.clone(),
connection_state.runtime.clone(),
thread_metadata.thread_source,
thread_metadata.thread_source.clone(),
thread_metadata.subagent_source.clone(),
thread_metadata.parent_thread_id.clone(),
),
@@ -1354,7 +1368,7 @@ impl AnalyticsReducer {
accepted_turn_id,
app_server_client: connection_state.app_server_client.clone(),
runtime: connection_state.runtime.clone(),
thread_source: thread_metadata.thread_source,
thread_source: thread_metadata.thread_source.clone(),
subagent_source: thread_metadata.subagent_source.clone(),
parent_thread_id: thread_metadata.parent_thread_id.clone(),
num_input_images: pending_request.num_input_images,
@@ -1397,7 +1411,7 @@ impl AnalyticsReducer {
review_id: pending_review.review_id,
app_server_client: connection_state.app_server_client.clone(),
runtime: connection_state.runtime.clone(),
thread_source: thread_metadata.thread_source,
thread_source: thread_metadata.thread_source.clone(),
subagent_source: thread_metadata.subagent_source.clone(),
parent_thread_id: thread_metadata.parent_thread_id.clone(),
subject_kind: pending_review.subject_kind,
@@ -1562,6 +1576,7 @@ fn tracked_tool_item_id(item: &ThreadItem) -> Option<&str> {
| ThreadItem::AgentMessage { .. }
| ThreadItem::Plan { .. }
| ThreadItem::Reasoning { .. }
| ThreadItem::SubAgentActivity { .. }
| ThreadItem::ImageView { .. }
| ThreadItem::EnteredReviewMode { .. }
| ThreadItem::ExitedReviewMode { .. }
@@ -1964,7 +1979,7 @@ fn tool_item_base(
item_id,
app_server_client: context.connection_state.app_server_client.clone(),
runtime: context.connection_state.runtime.clone(),
thread_source: thread_metadata.thread_source,
thread_source: thread_metadata.thread_source.clone(),
subagent_source: thread_metadata.subagent_source.clone(),
parent_thread_id: thread_metadata.parent_thread_id.clone(),
tool_name,
@@ -2444,7 +2459,7 @@ fn codex_turn_event_params(
runtime,
submission_type,
ephemeral,
thread_source: thread_metadata.thread_source,
thread_source: thread_metadata.thread_source.clone(),
initialization_mode: thread_metadata.initialization_mode,
subagent_source: thread_metadata.subagent_source.clone(),
parent_thread_id: thread_metadata.parent_thread_id.clone(),
@@ -2470,7 +2485,6 @@ fn codex_turn_event_params(
status: completed.status,
turn_error: completed.turn_error,
codex_error_kind: codex_error.map(|error| error.kind),
codex_error_subreason: codex_error.and_then(|error| error.subreason.clone()),
codex_error_http_status_code: codex_error.and_then(|error| error.http_status_code),
steer_count: Some(turn_state.steer_count),
total_tool_call_count: Some(turn_state.tool_counts.total),
-20
View File
@@ -70,13 +70,9 @@ pub use crate::remote::RemoteAppServerEndpoint;
/// module exists so clients can remove a direct `codex-core` dependency
/// while legacy startup/config paths are migrated to RPCs.
pub mod legacy_core {
pub use codex_core::DEFAULT_AGENTS_MD_FILENAME;
pub use codex_core::LOCAL_AGENTS_MD_FILENAME;
pub use codex_core::McpManager;
pub use codex_core::check_execpolicy_for_warnings;
pub use codex_core::format_exec_policy_error_with_source;
pub use codex_core::grant_read_root_non_elevated;
pub use codex_core::web_search_detail;
pub mod config {
pub use codex_core::config::*;
@@ -86,10 +82,6 @@ pub mod legacy_core {
}
}
pub mod connectors {
pub use codex_core::connectors::*;
}
pub mod otel_init {
pub use codex_core::otel_init::*;
}
@@ -98,22 +90,10 @@ pub mod legacy_core {
pub use codex_core::personality_migration::*;
}
pub mod review_format {
pub use codex_core::review_format::*;
}
pub mod review_prompts {
pub use codex_core::review_prompts::*;
}
pub mod test_support {
pub use codex_core::test_support::*;
}
pub mod util {
pub use codex_core::util::*;
}
pub mod windows_sandbox {
pub use codex_core::windows_sandbox::*;
}
+52 -5
View File
@@ -180,6 +180,36 @@
],
"type": "object"
},
"CapabilityRootLocation": {
"description": "Location used to resolve a selected capability root.",
"oneOf": [
{
"description": "A path owned by an execution environment.",
"properties": {
"environmentId": {
"type": "string"
},
"path": {
"type": "string"
},
"type": {
"enum": [
"environment"
],
"title": "EnvironmentCapabilityRootLocationType",
"type": "string"
}
},
"required": [
"environmentId",
"path",
"type"
],
"title": "EnvironmentCapabilityRootLocation",
"type": "object"
}
]
},
"ClientInfo": {
"properties": {
"name": {
@@ -2947,6 +2977,28 @@
}
]
},
"SelectedCapabilityRoot": {
"description": "A user-selected root that can expose one or more runtime capabilities.",
"properties": {
"id": {
"description": "Stable identifier supplied by the capability selection platform.",
"type": "string"
},
"location": {
"allOf": [
{
"$ref": "#/definitions/CapabilityRootLocation"
}
],
"description": "Where the selected root can be resolved."
}
},
"required": [
"id",
"location"
],
"type": "object"
},
"SendAddCreditsNudgeEmailParams": {
"properties": {
"creditType": {
@@ -3795,11 +3847,6 @@
"type": "string"
},
"ThreadSource": {
"enum": [
"user",
"subagent",
"memory_consolidation"
],
"type": "string"
},
"ThreadSourceKind": {
@@ -3177,6 +3177,14 @@
],
"type": "object"
},
"SubAgentActivityKind": {
"enum": [
"started",
"interacted",
"interrupted"
],
"type": "string"
},
"SubAgentSource": {
"oneOf": [
{
@@ -4107,6 +4115,38 @@
"title": "CollabAgentToolCallThreadItem",
"type": "object"
},
{
"properties": {
"agentPath": {
"type": "string"
},
"agentThreadId": {
"type": "string"
},
"id": {
"type": "string"
},
"kind": {
"$ref": "#/definitions/SubAgentActivityKind"
},
"type": {
"enum": [
"subAgentActivity"
],
"title": "SubAgentActivityThreadItemType",
"type": "string"
}
},
"required": [
"agentPath",
"agentThreadId",
"id",
"kind",
"type"
],
"title": "SubAgentActivityThreadItem",
"type": "object"
},
{
"properties": {
"action": {
@@ -4575,11 +4615,6 @@
"type": "object"
},
"ThreadSource": {
"enum": [
"user",
"subagent",
"memory_consolidation"
],
"type": "string"
},
"ThreadStartedNotification": {
@@ -6765,6 +6765,36 @@
],
"type": "string"
},
"CapabilityRootLocation": {
"description": "Location used to resolve a selected capability root.",
"oneOf": [
{
"description": "A path owned by an execution environment.",
"properties": {
"environmentId": {
"type": "string"
},
"path": {
"type": "string"
},
"type": {
"enum": [
"environment"
],
"title": "EnvironmentCapabilityRootLocationType",
"type": "string"
}
},
"required": [
"environmentId",
"path",
"type"
],
"title": "EnvironmentCapabilityRootLocation",
"type": "object"
}
]
},
"CodexErrorInfo": {
"description": "This translation layer make sure that we expose codex error code in camel case.\n\nWhen an upstream HTTP status is available (for example, from the Responses API or a provider), it is forwarded in `httpStatusCode` on the relevant `codexErrorInfo` variant.",
"oneOf": [
@@ -15061,6 +15091,28 @@
},
"type": "object"
},
"SelectedCapabilityRoot": {
"description": "A user-selected root that can expose one or more runtime capabilities.",
"properties": {
"id": {
"description": "Stable identifier supplied by the capability selection platform.",
"type": "string"
},
"location": {
"allOf": [
{
"$ref": "#/definitions/v2/CapabilityRootLocation"
}
],
"description": "Where the selected root can be resolved."
}
},
"required": [
"id",
"location"
],
"type": "object"
},
"SendAddCreditsNudgeEmailParams": {
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
@@ -15580,6 +15632,14 @@
],
"type": "object"
},
"SubAgentActivityKind": {
"enum": [
"started",
"interacted",
"interrupted"
],
"type": "string"
},
"SubAgentSource": {
"oneOf": [
{
@@ -16892,6 +16952,38 @@
"title": "CollabAgentToolCallThreadItem",
"type": "object"
},
{
"properties": {
"agentPath": {
"type": "string"
},
"agentThreadId": {
"type": "string"
},
"id": {
"type": "string"
},
"kind": {
"$ref": "#/definitions/v2/SubAgentActivityKind"
},
"type": {
"enum": [
"subAgentActivity"
],
"title": "SubAgentActivityThreadItemType",
"type": "string"
}
},
"required": [
"agentPath",
"agentThreadId",
"id",
"kind",
"type"
],
"title": "SubAgentActivityThreadItem",
"type": "object"
},
{
"properties": {
"action": {
@@ -18017,11 +18109,6 @@
"type": "string"
},
"ThreadSource": {
"enum": [
"user",
"subagent",
"memory_consolidation"
],
"type": "string"
},
"ThreadSourceKind": {
@@ -1087,6 +1087,36 @@
],
"type": "string"
},
"CapabilityRootLocation": {
"description": "Location used to resolve a selected capability root.",
"oneOf": [
{
"description": "A path owned by an execution environment.",
"properties": {
"environmentId": {
"type": "string"
},
"path": {
"type": "string"
},
"type": {
"enum": [
"environment"
],
"title": "EnvironmentCapabilityRootLocationType",
"type": "string"
}
},
"required": [
"environmentId",
"path",
"type"
],
"title": "EnvironmentCapabilityRootLocation",
"type": "object"
}
]
},
"ClientInfo": {
"properties": {
"name": {
@@ -11563,6 +11593,28 @@
},
"type": "object"
},
"SelectedCapabilityRoot": {
"description": "A user-selected root that can expose one or more runtime capabilities.",
"properties": {
"id": {
"description": "Stable identifier supplied by the capability selection platform.",
"type": "string"
},
"location": {
"allOf": [
{
"$ref": "#/definitions/CapabilityRootLocation"
}
],
"description": "Where the selected root can be resolved."
}
},
"required": [
"id",
"location"
],
"type": "object"
},
"SendAddCreditsNudgeEmailParams": {
"$schema": "http://json-schema.org/draft-07/schema#",
"properties": {
@@ -13397,6 +13449,14 @@
],
"type": "object"
},
"SubAgentActivityKind": {
"enum": [
"started",
"interacted",
"interrupted"
],
"type": "string"
},
"SubAgentSource": {
"oneOf": [
{
@@ -14709,6 +14769,38 @@
"title": "CollabAgentToolCallThreadItem",
"type": "object"
},
{
"properties": {
"agentPath": {
"type": "string"
},
"agentThreadId": {
"type": "string"
},
"id": {
"type": "string"
},
"kind": {
"$ref": "#/definitions/SubAgentActivityKind"
},
"type": {
"enum": [
"subAgentActivity"
],
"title": "SubAgentActivityThreadItemType",
"type": "string"
}
},
"required": [
"agentPath",
"agentThreadId",
"id",
"kind",
"type"
],
"title": "SubAgentActivityThreadItem",
"type": "object"
},
{
"properties": {
"action": {
@@ -15834,11 +15926,6 @@
"type": "string"
},
"ThreadSource": {
"enum": [
"user",
"subagent",
"memory_consolidation"
],
"type": "string"
},
"ThreadSourceKind": {
@@ -466,6 +466,14 @@
"minLength": 1,
"type": "string"
},
"SubAgentActivityKind": {
"enum": [
"started",
"interacted",
"interrupted"
],
"type": "string"
},
"TextElement": {
"properties": {
"byteRange": {
@@ -989,6 +997,38 @@
"title": "CollabAgentToolCallThreadItem",
"type": "object"
},
{
"properties": {
"agentPath": {
"type": "string"
},
"agentThreadId": {
"type": "string"
},
"id": {
"type": "string"
},
"kind": {
"$ref": "#/definitions/SubAgentActivityKind"
},
"type": {
"enum": [
"subAgentActivity"
],
"title": "SubAgentActivityThreadItemType",
"type": "string"
}
},
"required": [
"agentPath",
"agentThreadId",
"id",
"kind",
"type"
],
"title": "SubAgentActivityThreadItem",
"type": "object"
},
{
"properties": {
"action": {
@@ -466,6 +466,14 @@
"minLength": 1,
"type": "string"
},
"SubAgentActivityKind": {
"enum": [
"started",
"interacted",
"interrupted"
],
"type": "string"
},
"TextElement": {
"properties": {
"byteRange": {
@@ -989,6 +997,38 @@
"title": "CollabAgentToolCallThreadItem",
"type": "object"
},
{
"properties": {
"agentPath": {
"type": "string"
},
"agentThreadId": {
"type": "string"
},
"id": {
"type": "string"
},
"kind": {
"$ref": "#/definitions/SubAgentActivityKind"
},
"type": {
"enum": [
"subAgentActivity"
],
"title": "SubAgentActivityThreadItemType",
"type": "string"
}
},
"required": [
"agentPath",
"agentThreadId",
"id",
"kind",
"type"
],
"title": "SubAgentActivityThreadItem",
"type": "object"
},
{
"properties": {
"action": {
@@ -610,6 +610,14 @@
"minLength": 1,
"type": "string"
},
"SubAgentActivityKind": {
"enum": [
"started",
"interacted",
"interrupted"
],
"type": "string"
},
"TextElement": {
"properties": {
"byteRange": {
@@ -1133,6 +1141,38 @@
"title": "CollabAgentToolCallThreadItem",
"type": "object"
},
{
"properties": {
"agentPath": {
"type": "string"
},
"agentThreadId": {
"type": "string"
},
"id": {
"type": "string"
},
"kind": {
"$ref": "#/definitions/SubAgentActivityKind"
},
"type": {
"enum": [
"subAgentActivity"
],
"title": "SubAgentActivityThreadItemType",
"type": "string"
}
},
"required": [
"agentPath",
"agentThreadId",
"id",
"kind",
"type"
],
"title": "SubAgentActivityThreadItem",
"type": "object"
},
{
"properties": {
"action": {
@@ -73,11 +73,6 @@
"type": "string"
},
"ThreadSource": {
"enum": [
"user",
"subagent",
"memory_consolidation"
],
"type": "string"
}
},
@@ -861,6 +861,14 @@
}
]
},
"SubAgentActivityKind": {
"enum": [
"started",
"interacted",
"interrupted"
],
"type": "string"
},
"SubAgentSource": {
"oneOf": [
{
@@ -1617,6 +1625,38 @@
"title": "CollabAgentToolCallThreadItem",
"type": "object"
},
{
"properties": {
"agentPath": {
"type": "string"
},
"agentThreadId": {
"type": "string"
},
"id": {
"type": "string"
},
"kind": {
"$ref": "#/definitions/SubAgentActivityKind"
},
"type": {
"enum": [
"subAgentActivity"
],
"title": "SubAgentActivityThreadItemType",
"type": "string"
}
},
"required": [
"agentPath",
"agentThreadId",
"id",
"kind",
"type"
],
"title": "SubAgentActivityThreadItem",
"type": "object"
},
{
"properties": {
"action": {
@@ -1790,11 +1830,6 @@
]
},
"ThreadSource": {
"enum": [
"user",
"subagent",
"memory_consolidation"
],
"type": "string"
},
"ThreadStatus": {
@@ -676,6 +676,14 @@
}
]
},
"SubAgentActivityKind": {
"enum": [
"started",
"interacted",
"interrupted"
],
"type": "string"
},
"SubAgentSource": {
"oneOf": [
{
@@ -1432,6 +1440,38 @@
"title": "CollabAgentToolCallThreadItem",
"type": "object"
},
{
"properties": {
"agentPath": {
"type": "string"
},
"agentThreadId": {
"type": "string"
},
"id": {
"type": "string"
},
"kind": {
"$ref": "#/definitions/SubAgentActivityKind"
},
"type": {
"enum": [
"subAgentActivity"
],
"title": "SubAgentActivityThreadItemType",
"type": "string"
}
},
"required": [
"agentPath",
"agentThreadId",
"id",
"kind",
"type"
],
"title": "SubAgentActivityThreadItem",
"type": "object"
},
{
"properties": {
"action": {
@@ -1605,11 +1645,6 @@
]
},
"ThreadSource": {
"enum": [
"user",
"subagent",
"memory_consolidation"
],
"type": "string"
},
"ThreadStatus": {
@@ -676,6 +676,14 @@
}
]
},
"SubAgentActivityKind": {
"enum": [
"started",
"interacted",
"interrupted"
],
"type": "string"
},
"SubAgentSource": {
"oneOf": [
{
@@ -1432,6 +1440,38 @@
"title": "CollabAgentToolCallThreadItem",
"type": "object"
},
{
"properties": {
"agentPath": {
"type": "string"
},
"agentThreadId": {
"type": "string"
},
"id": {
"type": "string"
},
"kind": {
"$ref": "#/definitions/SubAgentActivityKind"
},
"type": {
"enum": [
"subAgentActivity"
],
"title": "SubAgentActivityThreadItemType",
"type": "string"
}
},
"required": [
"agentPath",
"agentThreadId",
"id",
"kind",
"type"
],
"title": "SubAgentActivityThreadItem",
"type": "object"
},
{
"properties": {
"action": {
@@ -1605,11 +1645,6 @@
]
},
"ThreadSource": {
"enum": [
"user",
"subagent",
"memory_consolidation"
],
"type": "string"
},
"ThreadStatus": {
@@ -676,6 +676,14 @@
}
]
},
"SubAgentActivityKind": {
"enum": [
"started",
"interacted",
"interrupted"
],
"type": "string"
},
"SubAgentSource": {
"oneOf": [
{
@@ -1432,6 +1440,38 @@
"title": "CollabAgentToolCallThreadItem",
"type": "object"
},
{
"properties": {
"agentPath": {
"type": "string"
},
"agentThreadId": {
"type": "string"
},
"id": {
"type": "string"
},
"kind": {
"$ref": "#/definitions/SubAgentActivityKind"
},
"type": {
"enum": [
"subAgentActivity"
],
"title": "SubAgentActivityThreadItemType",
"type": "string"
}
},
"required": [
"agentPath",
"agentThreadId",
"id",
"kind",
"type"
],
"title": "SubAgentActivityThreadItem",
"type": "object"
},
{
"properties": {
"action": {
@@ -1605,11 +1645,6 @@
]
},
"ThreadSource": {
"enum": [
"user",
"subagent",
"memory_consolidation"
],
"type": "string"
},
"ThreadStatus": {
@@ -861,6 +861,14 @@
}
]
},
"SubAgentActivityKind": {
"enum": [
"started",
"interacted",
"interrupted"
],
"type": "string"
},
"SubAgentSource": {
"oneOf": [
{
@@ -1617,6 +1625,38 @@
"title": "CollabAgentToolCallThreadItem",
"type": "object"
},
{
"properties": {
"agentPath": {
"type": "string"
},
"agentThreadId": {
"type": "string"
},
"id": {
"type": "string"
},
"kind": {
"$ref": "#/definitions/SubAgentActivityKind"
},
"type": {
"enum": [
"subAgentActivity"
],
"title": "SubAgentActivityThreadItemType",
"type": "string"
}
},
"required": [
"agentPath",
"agentThreadId",
"id",
"kind",
"type"
],
"title": "SubAgentActivityThreadItem",
"type": "object"
},
{
"properties": {
"action": {
@@ -1790,11 +1830,6 @@
]
},
"ThreadSource": {
"enum": [
"user",
"subagent",
"memory_consolidation"
],
"type": "string"
},
"ThreadStatus": {
@@ -676,6 +676,14 @@
}
]
},
"SubAgentActivityKind": {
"enum": [
"started",
"interacted",
"interrupted"
],
"type": "string"
},
"SubAgentSource": {
"oneOf": [
{
@@ -1432,6 +1440,38 @@
"title": "CollabAgentToolCallThreadItem",
"type": "object"
},
{
"properties": {
"agentPath": {
"type": "string"
},
"agentThreadId": {
"type": "string"
},
"id": {
"type": "string"
},
"kind": {
"$ref": "#/definitions/SubAgentActivityKind"
},
"type": {
"enum": [
"subAgentActivity"
],
"title": "SubAgentActivityThreadItemType",
"type": "string"
}
},
"required": [
"agentPath",
"agentThreadId",
"id",
"kind",
"type"
],
"title": "SubAgentActivityThreadItem",
"type": "object"
},
{
"properties": {
"action": {
@@ -1605,11 +1645,6 @@
]
},
"ThreadSource": {
"enum": [
"user",
"subagent",
"memory_consolidation"
],
"type": "string"
},
"ThreadStatus": {
@@ -64,6 +64,36 @@
}
]
},
"CapabilityRootLocation": {
"description": "Location used to resolve a selected capability root.",
"oneOf": [
{
"description": "A path owned by an execution environment.",
"properties": {
"environmentId": {
"type": "string"
},
"path": {
"type": "string"
},
"type": {
"enum": [
"environment"
],
"title": "EnvironmentCapabilityRootLocationType",
"type": "string"
}
},
"required": [
"environmentId",
"path",
"type"
],
"title": "EnvironmentCapabilityRootLocation",
"type": "object"
}
]
},
"DynamicToolSpec": {
"properties": {
"deferLoading": {
@@ -106,12 +136,29 @@
],
"type": "string"
},
"ThreadSource": {
"enum": [
"user",
"subagent",
"memory_consolidation"
"SelectedCapabilityRoot": {
"description": "A user-selected root that can expose one or more runtime capabilities.",
"properties": {
"id": {
"description": "Stable identifier supplied by the capability selection platform.",
"type": "string"
},
"location": {
"allOf": [
{
"$ref": "#/definitions/CapabilityRootLocation"
}
],
"description": "Where the selected root can be resolved."
}
},
"required": [
"id",
"location"
],
"type": "object"
},
"ThreadSource": {
"type": "string"
},
"ThreadStartSource": {
@@ -861,6 +861,14 @@
}
]
},
"SubAgentActivityKind": {
"enum": [
"started",
"interacted",
"interrupted"
],
"type": "string"
},
"SubAgentSource": {
"oneOf": [
{
@@ -1617,6 +1625,38 @@
"title": "CollabAgentToolCallThreadItem",
"type": "object"
},
{
"properties": {
"agentPath": {
"type": "string"
},
"agentThreadId": {
"type": "string"
},
"id": {
"type": "string"
},
"kind": {
"$ref": "#/definitions/SubAgentActivityKind"
},
"type": {
"enum": [
"subAgentActivity"
],
"title": "SubAgentActivityThreadItemType",
"type": "string"
}
},
"required": [
"agentPath",
"agentThreadId",
"id",
"kind",
"type"
],
"title": "SubAgentActivityThreadItem",
"type": "object"
},
{
"properties": {
"action": {
@@ -1790,11 +1830,6 @@
]
},
"ThreadSource": {
"enum": [
"user",
"subagent",
"memory_consolidation"
],
"type": "string"
},
"ThreadStatus": {
@@ -676,6 +676,14 @@
}
]
},
"SubAgentActivityKind": {
"enum": [
"started",
"interacted",
"interrupted"
],
"type": "string"
},
"SubAgentSource": {
"oneOf": [
{
@@ -1432,6 +1440,38 @@
"title": "CollabAgentToolCallThreadItem",
"type": "object"
},
{
"properties": {
"agentPath": {
"type": "string"
},
"agentThreadId": {
"type": "string"
},
"id": {
"type": "string"
},
"kind": {
"$ref": "#/definitions/SubAgentActivityKind"
},
"type": {
"enum": [
"subAgentActivity"
],
"title": "SubAgentActivityThreadItemType",
"type": "string"
}
},
"required": [
"agentPath",
"agentThreadId",
"id",
"kind",
"type"
],
"title": "SubAgentActivityThreadItem",
"type": "object"
},
{
"properties": {
"action": {
@@ -1605,11 +1645,6 @@
]
},
"ThreadSource": {
"enum": [
"user",
"subagent",
"memory_consolidation"
],
"type": "string"
},
"ThreadStatus": {
@@ -676,6 +676,14 @@
}
]
},
"SubAgentActivityKind": {
"enum": [
"started",
"interacted",
"interrupted"
],
"type": "string"
},
"SubAgentSource": {
"oneOf": [
{
@@ -1432,6 +1440,38 @@
"title": "CollabAgentToolCallThreadItem",
"type": "object"
},
{
"properties": {
"agentPath": {
"type": "string"
},
"agentThreadId": {
"type": "string"
},
"id": {
"type": "string"
},
"kind": {
"$ref": "#/definitions/SubAgentActivityKind"
},
"type": {
"enum": [
"subAgentActivity"
],
"title": "SubAgentActivityThreadItemType",
"type": "string"
}
},
"required": [
"agentPath",
"agentThreadId",
"id",
"kind",
"type"
],
"title": "SubAgentActivityThreadItem",
"type": "object"
},
{
"properties": {
"action": {
@@ -1605,11 +1645,6 @@
]
},
"ThreadSource": {
"enum": [
"user",
"subagent",
"memory_consolidation"
],
"type": "string"
},
"ThreadStatus": {
@@ -610,6 +610,14 @@
"minLength": 1,
"type": "string"
},
"SubAgentActivityKind": {
"enum": [
"started",
"interacted",
"interrupted"
],
"type": "string"
},
"TextElement": {
"properties": {
"byteRange": {
@@ -1133,6 +1141,38 @@
"title": "CollabAgentToolCallThreadItem",
"type": "object"
},
{
"properties": {
"agentPath": {
"type": "string"
},
"agentThreadId": {
"type": "string"
},
"id": {
"type": "string"
},
"kind": {
"$ref": "#/definitions/SubAgentActivityKind"
},
"type": {
"enum": [
"subAgentActivity"
],
"title": "SubAgentActivityThreadItemType",
"type": "string"
}
},
"required": [
"agentPath",
"agentThreadId",
"id",
"kind",
"type"
],
"title": "SubAgentActivityThreadItem",
"type": "object"
},
{
"properties": {
"action": {
@@ -610,6 +610,14 @@
"minLength": 1,
"type": "string"
},
"SubAgentActivityKind": {
"enum": [
"started",
"interacted",
"interrupted"
],
"type": "string"
},
"TextElement": {
"properties": {
"byteRange": {
@@ -1133,6 +1141,38 @@
"title": "CollabAgentToolCallThreadItem",
"type": "object"
},
{
"properties": {
"agentPath": {
"type": "string"
},
"agentThreadId": {
"type": "string"
},
"id": {
"type": "string"
},
"kind": {
"$ref": "#/definitions/SubAgentActivityKind"
},
"type": {
"enum": [
"subAgentActivity"
],
"title": "SubAgentActivityThreadItemType",
"type": "string"
}
},
"required": [
"agentPath",
"agentThreadId",
"id",
"kind",
"type"
],
"title": "SubAgentActivityThreadItem",
"type": "object"
},
{
"properties": {
"action": {
@@ -610,6 +610,14 @@
"minLength": 1,
"type": "string"
},
"SubAgentActivityKind": {
"enum": [
"started",
"interacted",
"interrupted"
],
"type": "string"
},
"TextElement": {
"properties": {
"byteRange": {
@@ -1133,6 +1141,38 @@
"title": "CollabAgentToolCallThreadItem",
"type": "object"
},
{
"properties": {
"agentPath": {
"type": "string"
},
"agentThreadId": {
"type": "string"
},
"id": {
"type": "string"
},
"kind": {
"$ref": "#/definitions/SubAgentActivityKind"
},
"type": {
"enum": [
"subAgentActivity"
],
"title": "SubAgentActivityThreadItemType",
"type": "string"
}
},
"required": [
"agentPath",
"agentThreadId",
"id",
"kind",
"type"
],
"title": "SubAgentActivityThreadItem",
"type": "object"
},
{
"properties": {
"action": {
@@ -0,0 +1,8 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
/**
* Location used to resolve a selected capability root.
*/
export type CapabilityRootLocation = { "type": "environment", environmentId: string, path: string, };
@@ -0,0 +1,17 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { CapabilityRootLocation } from "./CapabilityRootLocation";
/**
* A user-selected root that can expose one or more runtime capabilities.
*/
export type SelectedCapabilityRoot = {
/**
* Stable identifier supplied by the capability selection platform.
*/
id: string,
/**
* Where the selected root can be resolved.
*/
location: CapabilityRootLocation, };
@@ -0,0 +1,5 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type SubAgentActivityKind = "started" | "interacted" | "interrupted";
@@ -20,6 +20,7 @@ import type { McpToolCallResult } from "./McpToolCallResult";
import type { McpToolCallStatus } from "./McpToolCallStatus";
import type { MemoryCitation } from "./MemoryCitation";
import type { PatchApplyStatus } from "./PatchApplyStatus";
import type { SubAgentActivityKind } from "./SubAgentActivityKind";
import type { UserInput } from "./UserInput";
import type { WebSearchAction } from "./WebSearchAction";
@@ -98,4 +99,4 @@ reasoningEffort: ReasoningEffort | null,
/**
* Last known status of the target agents, when available.
*/
agentsStates: { [key in string]?: CollabAgentState }, } | { "type": "webSearch", id: string, query: string, action: WebSearchAction | null, } | { "type": "imageView", id: string, path: AbsolutePathBuf, } | { "type": "imageGeneration", id: string, status: string, revisedPrompt: string | null, result: string, savedPath?: AbsolutePathBuf, } | { "type": "enteredReviewMode", id: string, review: string, } | { "type": "exitedReviewMode", id: string, review: string, } | { "type": "contextCompaction", id: string, };
agentsStates: { [key in string]?: CollabAgentState }, } | { "type": "subAgentActivity", id: string, kind: SubAgentActivityKind, agentThreadId: string, agentPath: string, } | { "type": "webSearch", id: string, query: string, action: WebSearchAction | null, } | { "type": "imageView", id: string, path: AbsolutePathBuf, } | { "type": "imageGeneration", id: string, status: string, revisedPrompt: string | null, result: string, savedPath?: AbsolutePathBuf, } | { "type": "enteredReviewMode", id: string, review: string, } | { "type": "exitedReviewMode", id: string, review: string, } | { "type": "contextCompaction", id: string, };
@@ -2,4 +2,4 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type ThreadSource = "user" | "subagent" | "memory_consolidation";
export type ThreadSource = string;
@@ -40,6 +40,7 @@ export type { ByteRange } from "./ByteRange";
export type { CancelLoginAccountParams } from "./CancelLoginAccountParams";
export type { CancelLoginAccountResponse } from "./CancelLoginAccountResponse";
export type { CancelLoginAccountStatus } from "./CancelLoginAccountStatus";
export type { CapabilityRootLocation } from "./CapabilityRootLocation";
export type { ChatgptAuthTokensRefreshParams } from "./ChatgptAuthTokensRefreshParams";
export type { ChatgptAuthTokensRefreshReason } from "./ChatgptAuthTokensRefreshReason";
export type { ChatgptAuthTokensRefreshResponse } from "./ChatgptAuthTokensRefreshResponse";
@@ -334,6 +335,7 @@ export type { ReviewTarget } from "./ReviewTarget";
export type { SandboxMode } from "./SandboxMode";
export type { SandboxPolicy } from "./SandboxPolicy";
export type { SandboxWorkspaceWrite } from "./SandboxWorkspaceWrite";
export type { SelectedCapabilityRoot } from "./SelectedCapabilityRoot";
export type { SendAddCreditsNudgeEmailParams } from "./SendAddCreditsNudgeEmailParams";
export type { SendAddCreditsNudgeEmailResponse } from "./SendAddCreditsNudgeEmailResponse";
export type { ServerRequestResolvedNotification } from "./ServerRequestResolvedNotification";
@@ -356,6 +358,7 @@ export type { SkillsListParams } from "./SkillsListParams";
export type { SkillsListResponse } from "./SkillsListResponse";
export type { SortDirection } from "./SortDirection";
export type { SpendControlLimitSnapshot } from "./SpendControlLimitSnapshot";
export type { SubAgentActivityKind } from "./SubAgentActivityKind";
export type { SubagentMigration } from "./SubagentMigration";
export type { TerminalInteractionNotification } from "./TerminalInteractionNotification";
export type { TextElement } from "./TextElement";
@@ -178,6 +178,20 @@ pub fn item_event_to_server_notification(
completed_at_ms: end_event.completed_at_ms,
})
}
EventMsg::SubAgentActivity(activity) => {
let item = ThreadItem::SubAgentActivity {
id: activity.event_id,
kind: activity.kind.into(),
agent_thread_id: activity.agent_thread_id.to_string(),
agent_path: String::from(activity.agent_path),
};
ServerNotification::ItemCompleted(ItemCompletedNotification {
thread_id,
turn_id,
item,
completed_at_ms: activity.occurred_at_ms,
})
}
EventMsg::CollabWaitingBegin(begin_event) => {
let receiver_thread_ids = begin_event
.receiver_thread_ids
@@ -203,6 +203,7 @@ impl ThreadHistoryBuilder {
EventMsg::CollabAgentInteractionEnd(payload) => {
self.handle_collab_agent_interaction_end(payload)
}
EventMsg::SubAgentActivity(payload) => self.handle_sub_agent_activity(payload),
EventMsg::CollabWaitingBegin(payload) => self.handle_collab_waiting_begin(payload),
EventMsg::CollabWaitingEnd(payload) => self.handle_collab_waiting_end(payload),
EventMsg::CollabCloseBegin(payload) => self.handle_collab_close_begin(payload),
@@ -702,6 +703,18 @@ impl ThreadHistoryBuilder {
});
}
fn handle_sub_agent_activity(
&mut self,
payload: &codex_protocol::protocol::SubAgentActivityEvent,
) {
self.upsert_item_in_current_turn(ThreadItem::SubAgentActivity {
id: payload.event_id.clone(),
kind: payload.kind.into(),
agent_thread_id: payload.agent_thread_id.to_string(),
agent_path: String::from(payload.agent_path.clone()),
});
}
fn handle_collab_waiting_begin(
&mut self,
payload: &codex_protocol::protocol::CollabWaitingBeginEvent,
@@ -29,6 +29,7 @@ use codex_protocol::protocol::GuardianRiskLevel as CoreGuardianRiskLevel;
use codex_protocol::protocol::GuardianUserAuthorization as CoreGuardianUserAuthorization;
use codex_protocol::protocol::PatchApplyStatus as CorePatchApplyStatus;
use codex_protocol::protocol::ReviewDecision as CoreReviewDecision;
use codex_protocol::protocol::SubAgentActivityKind as CoreSubAgentActivityKind;
use codex_utils_absolute_path::AbsolutePathBuf;
use schemars::JsonSchema;
use serde::Deserialize;
@@ -336,6 +337,14 @@ pub enum ThreadItem {
},
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase")]
SubAgentActivity {
id: String,
kind: SubAgentActivityKind,
agent_thread_id: String,
agent_path: String,
},
#[serde(rename_all = "camelCase")]
#[ts(rename_all = "camelCase")]
WebSearch {
id: String,
query: String,
@@ -387,6 +396,7 @@ impl ThreadItem {
| ThreadItem::McpToolCall { id, .. }
| ThreadItem::DynamicToolCall { id, .. }
| ThreadItem::CollabAgentToolCall { id, .. }
| ThreadItem::SubAgentActivity { id, .. }
| ThreadItem::WebSearch { id, .. }
| ThreadItem::ImageView { id, .. }
| ThreadItem::ImageGeneration { id, .. }
@@ -1004,6 +1014,25 @@ pub enum CollabAgentToolCallStatus {
Failed,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
pub enum SubAgentActivityKind {
Started,
Interacted,
Interrupted,
}
impl From<CoreSubAgentActivityKind> for SubAgentActivityKind {
fn from(value: CoreSubAgentActivityKind) -> Self {
match value {
CoreSubAgentActivityKind::Started => SubAgentActivityKind::Started,
CoreSubAgentActivityKind::Interacted => SubAgentActivityKind::Interacted,
CoreSubAgentActivityKind::Interrupted => SubAgentActivityKind::Interrupted,
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export_to = "v2/")]
@@ -233,7 +233,7 @@ impl From<CoreAskForApproval> for AskForApproval {
pub enum ApprovalsReviewer {
#[serde(rename = "user")]
User,
#[serde(rename = "guardian_subagent", alias = "auto_review")]
#[serde(rename = "auto_review", alias = "guardian_subagent")]
AutoReview,
}
@@ -57,6 +57,30 @@ fn test_absolute_path() -> AbsolutePathBuf {
absolute_path("readable")
}
#[test]
fn thread_sources_round_trip_as_scalar_labels() {
for (source, label) in [
(ThreadSource::User, "user"),
(ThreadSource::Subagent, "subagent"),
(
ThreadSource::Feature("automation".to_string()),
"automation",
),
(ThreadSource::MemoryConsolidation, "memory_consolidation"),
] {
let value = serde_json::to_value(&source).expect("serialize thread source");
assert_eq!(value, json!(label));
assert_eq!(
serde_json::from_value::<ThreadSource>(value).expect("deserialize thread source"),
source
);
let core_source: codex_protocol::protocol::ThreadSource = source.clone().into();
assert_eq!(ThreadSource::from(core_source), source);
}
}
#[test]
fn approvals_reviewer_serializes_auto_review_and_accepts_legacy_guardian_subagent() {
assert_eq!(
@@ -65,7 +89,7 @@ fn approvals_reviewer_serializes_auto_review_and_accepts_legacy_guardian_subagen
);
assert_eq!(
serde_json::to_string(&ApprovalsReviewer::AutoReview).expect("serialize reviewer"),
"\"guardian_subagent\""
"\"auto_review\""
);
for value in ["user", "auto_review", "guardian_subagent"] {
@@ -11,6 +11,8 @@ use super::TurnEnvironmentParams;
use super::TurnItemsView;
use super::shared::v2_enum_from_core;
use codex_experimental_api_macros::ExperimentalApi;
pub use codex_protocol::capabilities::CapabilityRootLocation;
pub use codex_protocol::capabilities::SelectedCapabilityRoot;
use codex_protocol::config_types::CollaborationMode;
use codex_protocol::config_types::Personality;
use codex_protocol::config_types::ReasoningSummary;
@@ -153,6 +155,10 @@ pub struct ThreadStartParams {
#[experimental("thread/start.dynamicTools")]
#[ts(optional = nullable)]
pub dynamic_tools: Option<Vec<DynamicToolSpec>>,
/// Capability roots selected for this thread by the hosting platform.
#[experimental("thread/start.selectedCapabilityRoots")]
#[ts(optional = nullable)]
pub selected_capability_roots: Option<Vec<SelectedCapabilityRoot>>,
/// Test-only experimental field used to validate experimental gating and
/// schema filtering behavior in a stable way.
#[experimental("thread/start.mockExperimentalField")]
@@ -7,6 +7,8 @@ use codex_protocol::protocol::SubAgentSource as CoreSubAgentSource;
use codex_protocol::protocol::ThreadSource as CoreThreadSource;
use codex_utils_absolute_path::AbsolutePathBuf;
use schemars::JsonSchema;
use schemars::r#gen::SchemaGenerator;
use schemars::schema::Schema;
use serde::Deserialize;
use serde::Serialize;
use std::path::PathBuf;
@@ -61,20 +63,47 @@ impl From<SessionSource> for CoreSessionSource {
}
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)]
#[serde(rename_all = "snake_case")]
#[ts(rename_all = "snake_case", export_to = "v2/")]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, TS)]
#[serde(try_from = "String", into = "String")]
#[ts(type = "string")]
#[ts(export_to = "v2/")]
pub enum ThreadSource {
User,
Subagent,
Feature(String),
MemoryConsolidation,
}
impl JsonSchema for ThreadSource {
fn schema_name() -> String {
"ThreadSource".to_string()
}
fn json_schema(generator: &mut SchemaGenerator) -> Schema {
String::json_schema(generator)
}
}
impl TryFrom<String> for ThreadSource {
type Error = String;
fn try_from(value: String) -> Result<Self, Self::Error> {
value.parse::<CoreThreadSource>().map(Into::into)
}
}
impl From<ThreadSource> for String {
fn from(value: ThreadSource) -> Self {
CoreThreadSource::from(value).into()
}
}
impl From<CoreThreadSource> for ThreadSource {
fn from(value: CoreThreadSource) -> Self {
match value {
CoreThreadSource::User => ThreadSource::User,
CoreThreadSource::Subagent => ThreadSource::Subagent,
CoreThreadSource::Feature(feature) => ThreadSource::Feature(feature),
CoreThreadSource::MemoryConsolidation => ThreadSource::MemoryConsolidation,
}
}
@@ -85,6 +114,7 @@ impl From<ThreadSource> for CoreThreadSource {
match value {
ThreadSource::User => CoreThreadSource::User,
ThreadSource::Subagent => CoreThreadSource::Subagent,
ThreadSource::Feature(feature) => CoreThreadSource::Feature(feature),
ThreadSource::MemoryConsolidation => CoreThreadSource::MemoryConsolidation,
}
}
@@ -76,7 +76,7 @@ pub struct TurnStartParams {
#[experimental("turn/start.additionalContext")]
#[ts(optional = nullable)]
pub additional_context: Option<HashMap<String, AdditionalContextEntry>>,
/// Optional turn-scoped environments.
/// Optional environments for this turn and subsequent turns.
///
/// Omitted uses the thread sticky environments. Empty disables
/// environment access for this turn. Non-empty selects the first
+2
View File
@@ -49,6 +49,7 @@ codex-hooks = { workspace = true }
codex-otel = { workspace = true }
codex-plugin = { workspace = true }
codex-shell-command = { workspace = true }
codex-skills-extension = { workspace = true }
codex-utils-cli = { workspace = true }
codex-utils-pty = { workspace = true }
codex-backend-client = { workspace = true }
@@ -60,6 +61,7 @@ codex-memories-extension = { workspace = true }
codex-web-search-extension = { workspace = true }
codex-memories-write = { workspace = true }
codex-mcp = { workspace = true }
codex-mcp-extension = { workspace = true }
codex-model-provider = { workspace = true }
codex-models-manager = { workspace = true }
codex-protocol = { workspace = true }
+13 -1
View File
@@ -130,7 +130,7 @@ Example with notification opt-out:
## API Overview
- `thread/start` — create a new thread; emits `thread/started` (including the current `thread.status`) and auto-subscribes you to turn/item events for that thread. When the request includes a `cwd` and the resolved sandbox is `workspace-write` or full access, app-server also marks that project as trusted in the user `config.toml`. Pass `sessionStartSource: "clear"` when starting a replacement thread after clearing the current session so `SessionStart` hooks receive `source: "clear"` instead of the default `"startup"`. Experimental `runtimeWorkspaceRoots` replaces the thread-scoped runtime workspace roots used to materialize `:workspace_roots`; paths must be absolute. For permissions, prefer experimental `permissions` profile selection by id; the legacy `sandbox` shorthand is still accepted but cannot be combined with `permissions`. Experimental `environments` selects the sticky execution environments for turns on the thread; omit it to use the server default, pass `[]` to disable environments, or pass explicit environment ids with per-environment `cwd`.
- `thread/start` — create a new thread; emits `thread/started` (including the current `thread.status`) and auto-subscribes you to turn/item events for that thread. When the request includes a `cwd` and the resolved sandbox is `workspace-write` or full access, app-server also marks that project as trusted in the user `config.toml`. Pass `sessionStartSource: "clear"` when starting a replacement thread after clearing the current session so `SessionStart` hooks receive `source: "clear"` instead of the default `"startup"`. Experimental `runtimeWorkspaceRoots` replaces the thread-scoped runtime workspace roots used to materialize `:workspace_roots`; paths must be absolute. For permissions, prefer experimental `permissions` profile selection by id; the legacy `sandbox` shorthand is still accepted but cannot be combined with `permissions`. Experimental `environments` selects the sticky execution environments for turns on the thread; omit it to use the server default, pass `[]` to disable environments, or pass explicit environment ids with per-environment `cwd`. Experimental `selectedCapabilityRoots` selects environment-owned plugin or standalone-skill roots. Skills found below those roots are listed and read through the owning environment; other plugin capabilities are not activated yet.
- `thread/resume` — reopen an existing thread by id so subsequent `turn/start` calls append to it. Accepts the same permission override rules as `thread/start`.
- `thread/fork` — fork an existing thread into a new thread id by copying the stored history; if the source thread is currently mid-turn, the fork records the same interruption marker as `turn/interrupt` instead of inheriting an unmarked partial turn suffix. The returned `thread.forkedFromId` points at the source thread when known. Accepts `ephemeral: true` for an in-memory temporary fork, emits `thread/started` (including the current `thread.status`), and auto-subscribes you to turn/item events for the new thread. Experimental clients can pass `excludeTurns: true` when they plan to page fork history via `thread/turns/list` instead of receiving the full turn array immediately. Accepts the same permission override rules as `thread/start`.
- `thread/start`, `thread/resume`, and `thread/fork` responses include the legacy `sandbox` compatibility projection. Experimental clients can read `runtimeWorkspaceRoots` for the thread-scoped runtime roots and `activePermissionProfile` for the named or implicit built-in profile identity/provenance when known.
@@ -249,6 +249,18 @@ Start a fresh thread when you need a new Codex conversation.
// "permissions": ":workspace"
// Experimental runtime roots for :workspace_roots materialization:
// "runtimeWorkspaceRoots": ["/Users/me/project", "/Users/me/openai"],
// Experimental capability roots selected by the hosting platform:
"selectedCapabilityRoots": [
{
"id": "github@openai",
"location": {
"type": "environment",
"environmentId": "workspace",
// Opaque to app-server; interpreted in the selected environment.
"path": "/opt/cca/plugins/github"
}
}
],
// Do not send both "sandbox" and "permissions".
"personality": "friendly",
"serviceName": "my_app_server_client", // optional metrics tag (`service_name`)
@@ -100,6 +100,7 @@ use codex_protocol::protocol::Op;
use codex_protocol::protocol::RealtimeEvent;
use codex_protocol::protocol::ReviewDecision;
use codex_protocol::protocol::ReviewOutputEvent;
use codex_protocol::protocol::SubAgentActivityKind;
use codex_protocol::protocol::TokenCountEvent;
use codex_protocol::protocol::TurnAbortedEvent;
use codex_protocol::protocol::TurnCompleteEvent;
@@ -767,7 +768,7 @@ pub(crate) async fn apply_bespoke_event_handling(
let requested_permissions = request.permissions.clone();
let request_cwd = match request.cwd.clone() {
Some(cwd) => cwd,
None => conversation.config_snapshot().await.cwd,
None => conversation.config_snapshot().await.cwd().clone(),
};
let params = PermissionsRequestApprovalParams {
thread_id: conversation_id.to_string(),
@@ -861,6 +862,24 @@ pub(crate) async fn apply_bespoke_event_handling(
);
outgoing.send_server_notification(notification).await;
}
EventMsg::SubAgentActivity(activity) => {
if activity.kind == SubAgentActivityKind::Interrupted
&& thread_manager
.get_thread(activity.agent_thread_id)
.await
.is_err()
{
thread_watch_manager
.remove_thread(&activity.agent_thread_id.to_string())
.await;
}
let notification = item_event_to_server_notification(
EventMsg::SubAgentActivity(activity),
&conversation_id.to_string(),
&event_turn_id,
);
outgoing.send_server_notification(notification).await;
}
EventMsg::CollabCloseEnd(end_event) => {
if thread_manager
.get_thread(end_event.receiver_thread_id)
@@ -1161,7 +1180,7 @@ pub(crate) async fn apply_bespoke_event_handling(
return;
}
};
let fallback_cwd = conversation.config_snapshot().await.cwd;
let fallback_cwd = conversation.config_snapshot().await.cwd().clone();
let stored_thread = match conversation
.read_thread(
/*include_archived*/ true, /*include_history*/ true,
@@ -2104,6 +2123,7 @@ mod tests {
use codex_app_server_protocol::JSONRPCErrorError;
use codex_app_server_protocol::TurnPlanStepStatus;
use codex_login::CodexAuth;
use codex_protocol::AgentPath;
use codex_protocol::items::HookPromptFragment;
use codex_protocol::items::build_hook_prompt_message;
use codex_protocol::models::FileSystemPermissions as CoreFileSystemPermissions;
@@ -2125,6 +2145,7 @@ mod tests {
use codex_protocol::protocol::RateLimitWindow;
use codex_protocol::protocol::RolloutItem;
use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::SubAgentActivityEvent;
use codex_protocol::protocol::TokenUsage;
use codex_protocol::protocol::TokenUsageInfo;
use codex_protocol::protocol::UserMessageEvent;
@@ -2181,6 +2202,7 @@ mod tests {
];
let stored_thread = StoredThread {
thread_id,
extra_config: None,
rollout_path: None,
forked_from_id: None,
parent_thread_id: None,
@@ -3298,6 +3320,94 @@ mod tests {
Ok(())
}
#[tokio::test]
async fn interrupted_subagent_activity_removes_missing_thread_watch() -> Result<()> {
let codex_home = TempDir::new()?;
let config = load_default_config_for_test(&codex_home).await;
let thread_manager = Arc::new(
codex_core::test_support::thread_manager_with_models_provider_and_home(
CodexAuth::create_dummy_chatgpt_auth_for_testing(),
config.model_provider.clone(),
config.codex_home.to_path_buf(),
Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()),
),
);
let codex_core::NewThread {
thread_id: conversation_id,
thread: conversation,
..
} = thread_manager.start_thread(config).await?;
let child_thread_id = ThreadId::new();
let child_thread_id_string = child_thread_id.to_string();
let thread_watch_manager = ThreadWatchManager::new();
thread_watch_manager
.note_turn_started(&child_thread_id_string)
.await;
assert_eq!(thread_watch_manager.running_turn_count().await, 1);
let (tx, mut rx) = mpsc::channel(CHANNEL_CAPACITY);
let outgoing = Arc::new(OutgoingMessageSender::new(
tx,
codex_analytics::AnalyticsEventsClient::disabled(),
));
let outgoing = ThreadScopedOutgoingMessageSender::new(
outgoing,
vec![ConnectionId(1)],
conversation_id,
);
apply_bespoke_event_handling(
Event {
id: "turn-1".to_string(),
msg: EventMsg::SubAgentActivity(SubAgentActivityEvent {
event_id: "activity-1".to_string(),
occurred_at_ms: 42,
agent_thread_id: child_thread_id,
agent_path: AgentPath::try_from("/root/worker")
.expect("agent path should parse"),
kind: SubAgentActivityKind::Interrupted,
}),
},
conversation_id,
conversation,
thread_manager,
outgoing,
new_thread_state(),
thread_watch_manager.clone(),
Arc::new(tokio::sync::Semaphore::new(/*permits*/ 1)),
"test-provider".to_string(),
)
.await;
assert_eq!(
thread_watch_manager
.loaded_status_for_thread(&child_thread_id_string)
.await,
ThreadStatus::NotLoaded
);
assert_eq!(thread_watch_manager.running_turn_count().await, 0);
let message = recv_broadcast_message(&mut rx).await?;
let OutgoingMessage::AppServerNotification(ServerNotification::ItemCompleted(payload)) =
message
else {
bail!("unexpected message: {message:?}");
};
assert_eq!(
payload,
ItemCompletedNotification {
item: ThreadItem::SubAgentActivity {
id: "activity-1".to_string(),
kind: codex_app_server_protocol::SubAgentActivityKind::Interrupted,
agent_thread_id: child_thread_id_string,
agent_path: "/root/worker".to_string(),
},
thread_id: conversation_id.to_string(),
turn_id: "turn-1".to_string(),
completed_at_ms: 42,
}
);
Ok(())
}
#[tokio::test]
async fn test_handle_turn_complete_emits_completed_without_error() -> Result<()> {
let conversation_id = ThreadId::new();
@@ -0,0 +1,49 @@
use std::future::Future;
use std::future::pending;
use tokio::task::JoinError;
use tokio::task::JoinSet;
use tracing::warn;
pub(crate) struct ConnectionCleanupTasks {
tasks: JoinSet<()>,
}
impl ConnectionCleanupTasks {
pub(crate) fn new() -> Self {
Self {
tasks: JoinSet::new(),
}
}
pub(crate) fn spawn(&mut self, future: impl Future<Output = ()> + Send + 'static) {
self.tasks.spawn(future);
}
pub(crate) async fn reap_next(&mut self) {
if self.tasks.is_empty() {
pending::<()>().await;
}
if let Some(result) = self.tasks.join_next().await {
log_cleanup_result(result);
}
}
pub(crate) async fn drain(&mut self) {
while let Some(result) = self.tasks.join_next().await {
log_cleanup_result(result);
}
}
pub(crate) fn abort(&mut self) {
self.tasks.abort_all();
}
}
fn log_cleanup_result(result: Result<(), JoinError>) {
if let Err(err) = result
&& !err.is_cancelled()
{
warn!("connection cleanup task failed: {err}");
}
}
+36 -7
View File
@@ -38,12 +38,14 @@ impl ConnectionRpcGate {
drop(token);
}
pub(crate) async fn close(&self) {
let mut accepting = self.accepting.lock().await;
*accepting = false;
self.tasks.close();
}
pub(crate) async fn shutdown(&self) {
{
let mut accepting = self.accepting.lock().await;
*accepting = false;
self.tasks.close();
}
self.close().await;
self.tasks.wait().await;
}
@@ -90,9 +92,9 @@ mod tests {
}
#[tokio::test]
async fn run_drops_future_without_polling_after_shutdown() {
async fn run_drops_future_without_polling_after_close() {
let gate = ConnectionRpcGate::new();
gate.shutdown().await;
gate.close().await;
let polled = Arc::new(AtomicBool::new(/*v*/ false));
let polled_clone = Arc::clone(&polled);
@@ -105,6 +107,33 @@ mod tests {
assert!(!gate.is_accepting().await);
}
#[tokio::test]
async fn close_returns_while_started_run_remains_active() {
let gate = Arc::new(ConnectionRpcGate::new());
let (started_tx, started_rx) = oneshot::channel();
let (finish_tx, finish_rx) = oneshot::channel();
let gate_for_run = Arc::clone(&gate);
let run_task = tokio::spawn(async move {
gate_for_run
.run(async move {
started_tx.send(()).expect("receiver should be open");
let _ = finish_rx.await;
})
.await;
});
started_rx.await.expect("run should start");
gate.close().await;
assert!(!gate.is_accepting().await);
assert_eq!(gate.inflight_count(), 1);
finish_tx
.send(())
.expect("running future should be waiting");
run_task.await.expect("run task should complete");
gate.shutdown().await;
}
#[tokio::test]
async fn shutdown_waits_for_started_run_to_finish() {
let gate = Arc::new(ConnectionRpcGate::new());
+7
View File
@@ -32,6 +32,7 @@ pub(crate) fn thread_extensions<S>(
state_db: Option<StateDbHandle>,
thread_manager: Weak<ThreadManager>,
goal_service: Arc<GoalService>,
executor_skill_provider: Arc<dyn codex_skills_extension::SkillProvider>,
) -> Arc<ExtensionRegistry<Config>>
where
S: AgentSpawner<StartThreadOptions, Spawned = NewThread, Error = CodexErr> + 'static,
@@ -49,8 +50,14 @@ where
}
codex_guardian::install(&mut builder, guardian_agent_spawner);
codex_memories_extension::install(&mut builder, codex_otel::global());
codex_mcp_extension::install(&mut builder);
codex_web_search_extension::install(&mut builder, auth_manager.clone());
codex_image_generation_extension::install(&mut builder, auth_manager);
codex_skills_extension::install_with_providers(
&mut builder,
codex_skills_extension::SkillProviders::new()
.with_executor_provider(executor_skill_provider),
);
Arc::new(builder.build())
}
+17 -4
View File
@@ -20,6 +20,7 @@ use std::sync::atomic::AtomicBool;
use crate::analytics_utils::analytics_events_client_from_config;
use crate::config_manager::ConfigManager;
use crate::connection_cleanup::ConnectionCleanupTasks;
use crate::message_processor::MessageProcessor;
use crate::message_processor::MessageProcessorArgs;
use crate::outgoing_message::ConnectionId;
@@ -81,6 +82,7 @@ mod command_exec;
mod config;
mod config_manager;
mod config_manager_service;
mod connection_cleanup;
mod connection_rpc_gate;
mod dynamic_tools;
mod error_code;
@@ -819,6 +821,7 @@ pub async fn run_main_with_transport_options(
let mut thread_created_rx = processor.thread_created_receiver();
let mut running_turn_count_rx = processor.subscribe_running_assistant_turn_count();
let mut connections = HashMap::<ConnectionId, ConnectionState>::new();
let mut connection_cleanup_tasks = ConnectionCleanupTasks::new();
let mut remote_control_status_rx = remote_control_handle.status_receiver();
let mut remote_control_status = remote_control_status_rx.borrow().clone();
let transport_shutdown_token = transport_shutdown_token.clone();
@@ -906,14 +909,20 @@ pub async fn run_main_with_transport_options(
let Some(connection_state) = connections.remove(&connection_id) else {
continue;
};
if outbound_control_tx
connection_state.session.rpc_gate.close().await;
let outbound_closed = outbound_control_tx
.send(OutboundControlEvent::Closed { connection_id })
.await
.is_err()
{
.is_ok();
let processor = Arc::clone(&processor);
connection_cleanup_tasks.spawn(async move {
processor
.connection_closed(connection_id, &connection_state.session)
.await;
});
if !outbound_closed {
break;
}
processor.connection_closed(connection_id, &connection_state.session).await;
if shutdown_when_no_connections && connections.is_empty() {
break;
}
@@ -1010,6 +1019,7 @@ pub async fn run_main_with_transport_options(
}
}
}
_ = connection_cleanup_tasks.reap_next() => {}
changed = remote_control_status_rx.changed() => {
if changed.is_err() {
continue;
@@ -1062,8 +1072,11 @@ pub async fn run_main_with_transport_options(
.map(|connection_state| connection_state.session.rpc_gate.shutdown()),
)
.await;
connection_cleanup_tasks.drain().await;
processor.drain_background_tasks().await;
processor.shutdown_threads().await;
} else {
connection_cleanup_tasks.abort();
}
info!("processor task exited (channel closed)");
}
+10 -5
View File
@@ -67,10 +67,7 @@ async fn build_refresh_config(
let config = config_manager
.load_latest_config_for_thread(thread_config.as_ref())
.await?;
let mcp_servers = thread_manager
.mcp_manager()
.configured_servers(&config)
.await;
let mcp_servers = thread_manager.mcp_manager().runtime_servers(&config).await;
Ok(McpServerRefreshConfig {
mcp_servers: serde_json::to_value(mcp_servers).map_err(io::Error::other)?,
mcp_oauth_credentials_store_mode: serde_json::to_value(
@@ -181,12 +178,19 @@ mod tests {
.await
.expect("refresh tests require state db");
let thread_store = thread_store_from_config(&good_config, Some(state_db.clone()));
let environment_manager = Arc::new(EnvironmentManager::default_for_tests());
let executor_skill_provider: Arc<dyn codex_skills_extension::SkillProvider> = Arc::new(
codex_skills_extension::ExecutorSkillProvider::new_with_restriction_product(
Arc::clone(&environment_manager),
SessionSource::Exec.restriction_product(),
),
);
let thread_manager = Arc::new_cyclic(|thread_manager| {
ThreadManager::new(
&good_config,
auth_manager.clone(),
SessionSource::Exec,
Arc::new(EnvironmentManager::default_for_tests()),
Arc::clone(&environment_manager),
thread_extensions(
guardian_agent_spawner(thread_manager.clone()),
Arc::new(NoopExtensionEventSink),
@@ -194,6 +198,7 @@ mod tests {
Some(state_db.clone()),
thread_manager.clone(),
Arc::new(codex_goal_extension::GoalService::new()),
Arc::clone(&executor_skill_provider),
),
/*analytics_events_client*/ None,
Arc::clone(&thread_store),
+24 -1
View File
@@ -91,6 +91,7 @@ use tokio_util::sync::CancellationToken;
use tracing::Instrument;
const EXTERNAL_AUTH_REFRESH_TIMEOUT: Duration = Duration::from_secs(10);
const CONNECTION_RPC_DRAIN_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 30);
#[derive(Clone)]
struct ExternalAuthRefreshBridge {
@@ -306,6 +307,14 @@ impl MessageProcessor {
// resumed, or forked threads to a different persistence backend/root.
let thread_store = codex_core::thread_store_from_config(config.as_ref(), state_db.clone());
let environment_manager_for_requests = Arc::clone(&environment_manager);
let environment_manager_for_extensions = Arc::clone(&environment_manager);
let restriction_product = session_source.restriction_product();
let executor_skill_provider: Arc<dyn codex_skills_extension::SkillProvider> = Arc::new(
codex_skills_extension::ExecutorSkillProvider::new_with_restriction_product(
environment_manager_for_extensions,
restriction_product,
),
);
let goal_service = Arc::new(GoalService::new());
let thread_manager = Arc::new_cyclic(|thread_manager| {
ThreadManager::new(
@@ -320,6 +329,7 @@ impl MessageProcessor {
state_db.clone(),
thread_manager.clone(),
Arc::clone(&goal_service),
Arc::clone(&executor_skill_provider),
),
Some(analytics_events_client.clone()),
Arc::clone(&thread_store),
@@ -474,6 +484,7 @@ impl MessageProcessor {
let external_agent_config_processor = ExternalAgentConfigRequestProcessor::new(
outgoing.clone(),
Arc::clone(&thread_manager),
Arc::clone(&thread_store),
config_manager.clone(),
config_processor.clone(),
arg0_paths,
@@ -723,7 +734,19 @@ impl MessageProcessor {
connection_id: ConnectionId,
session_state: &ConnectionSessionState,
) {
session_state.rpc_gate.shutdown().await;
if timeout(
CONNECTION_RPC_DRAIN_TIMEOUT,
session_state.rpc_gate.shutdown(),
)
.await
.is_err()
{
tracing::warn!(
?connection_id,
timeout_seconds = CONNECTION_RPC_DRAIN_TIMEOUT.as_secs(),
"timed out waiting for connection RPCs to drain"
);
}
self.outgoing.connection_closed(connection_id).await;
self.fs_processor.connection_closed(connection_id).await;
self.command_exec_processor
@@ -280,6 +280,7 @@ use codex_config::types::McpServerTransportConfig;
use codex_core::CodexThread;
use codex_core::CodexThreadSettingsOverrides;
use codex_core::ForkSnapshot;
use codex_core::McpManager;
use codex_core::NewThread;
#[cfg(test)]
use codex_core::SessionMeta;
@@ -330,6 +331,7 @@ use codex_core_plugins::remote::RemotePluginShareContext as RemoteCatalogPluginS
use codex_core_plugins::remote::RemotePluginShareSummary as RemoteCatalogPluginShareSummary;
use codex_core_plugins::remote::RemotePluginSummary as RemoteCatalogPluginSummary;
use codex_exec_server::EnvironmentManager;
use codex_exec_server::LOCAL_ENVIRONMENT_ID;
use codex_exec_server::LOCAL_FS;
use codex_features::FEATURES;
use codex_features::Feature;
@@ -400,6 +402,7 @@ use codex_protocol::protocol::SessionConfiguredEvent;
#[cfg(test)]
use codex_protocol::protocol::SessionMetaLine;
use codex_protocol::protocol::TurnEnvironmentSelection;
use codex_protocol::protocol::TurnEnvironmentSelections;
use codex_protocol::protocol::USER_MESSAGE_BEGIN;
use codex_protocol::protocol::W3cTraceContext;
use codex_protocol::user_input::MAX_USER_INPUT_TEXT_CHARS;
@@ -461,6 +464,7 @@ mod command_exec_processor;
mod config_processor;
mod environment_processor;
mod external_agent_config_processor;
mod external_agent_session_import;
mod feedback_doctor_report;
mod feedback_processor;
mod fs_processor;
@@ -53,7 +53,7 @@ impl AppsRequestProcessor {
None
};
let fallback_cwd = match thread.as_ref() {
Some(thread) => Some(thread.config_snapshot().await.cwd.to_path_buf()),
Some(thread) => Some(thread.config_snapshot().await.cwd().to_path_buf()),
None => None,
};
let mut config = self.load_latest_config(fallback_cwd).await?;
@@ -88,11 +88,19 @@ impl AppsRequestProcessor {
let request = request_id.clone();
let outgoing = Arc::clone(&self.outgoing);
let environment_manager = self.thread_manager.environment_manager();
let mcp_manager = self.thread_manager.mcp_manager();
let shutdown_token = self.shutdown_token.child_token();
tokio::spawn(async move {
tokio::select! {
_ = shutdown_token.cancelled() => {}
_ = Self::apps_list_task(outgoing, request, params, config, environment_manager) => {}
_ = Self::apps_list_task(
outgoing,
request,
params,
config,
environment_manager,
mcp_manager,
) => {}
}
});
Ok(None)
@@ -108,11 +116,15 @@ impl AppsRequestProcessor {
params: AppsListParams,
config: Config,
environment_manager: Arc<EnvironmentManager>,
mcp_manager: Arc<McpManager>,
) {
let retry_params = params.clone();
let retry_config = config.clone();
let retry_environment_manager = Arc::clone(&environment_manager);
let result = Self::apps_list_response(&outgoing, params, config, environment_manager).await;
let retry_mcp_manager = Arc::clone(&mcp_manager);
let result =
Self::apps_list_response(&outgoing, params, config, environment_manager, mcp_manager)
.await;
let should_retry = result
.as_ref()
.is_ok_and(|(_, codex_apps_ready)| !codex_apps_ready);
@@ -128,6 +140,7 @@ impl AppsRequestProcessor {
retry_params,
retry_config,
retry_environment_manager,
retry_mcp_manager,
)
.await
{
@@ -141,6 +154,7 @@ impl AppsRequestProcessor {
params: AppsListParams,
config: Config,
environment_manager: Arc<EnvironmentManager>,
mcp_manager: Arc<McpManager>,
) -> Result<(AppsListResponse, bool), JSONRPCErrorError> {
let AppsListParams {
cursor,
@@ -167,14 +181,14 @@ impl AppsRequestProcessor {
let accessible_config = config.clone();
let accessible_tx = tx.clone();
tokio::spawn(async move {
let result =
connectors::list_accessible_connectors_from_mcp_tools_with_environment_manager(
&accessible_config,
force_refetch,
Arc::clone(&environment_manager),
)
.await
.map_err(|err| format!("failed to load accessible apps: {err}"));
let result = connectors::list_accessible_connectors_from_mcp_tools_with_mcp_manager(
&accessible_config,
force_refetch,
Arc::clone(&environment_manager),
mcp_manager,
)
.await
.map_err(|err| format!("failed to load accessible apps: {err}"));
let _ = accessible_tx.send(AppListLoadResult::Accessible(result));
});
@@ -26,53 +26,47 @@ use codex_app_server_protocol::MigrationDetails;
use codex_app_server_protocol::PluginsMigration;
use codex_app_server_protocol::ServerNotification;
use codex_arg0::Arg0DispatchPaths;
use codex_core::StartThreadOptions;
use codex_core::ThreadManager;
use codex_core::config::ConfigOverrides;
use codex_external_agent_sessions::ExternalAgentSessionMigration as CoreSessionMigration;
use codex_external_agent_sessions::ImportedExternalAgentSession;
use codex_external_agent_sessions::PendingSessionImport;
use codex_external_agent_sessions::prepare_validated_session_imports;
use codex_external_agent_sessions::record_imported_session;
use codex_protocol::ThreadId;
use codex_protocol::protocol::InitialHistory;
use codex_thread_store::ThreadMetadataPatch;
use codex_thread_store::ThreadStore;
use std::collections::HashSet;
use std::path::PathBuf;
use tokio::sync::Semaphore;
use super::ConfigRequestProcessor;
use super::external_agent_session_import::ExternalAgentSessionImporter;
#[derive(Clone)]
pub(crate) struct ExternalAgentConfigRequestProcessor {
outgoing: Arc<OutgoingMessageSender>,
codex_home: PathBuf,
migration_service: ExternalAgentConfigService,
session_import_permits: Arc<Semaphore>,
session_importer: ExternalAgentSessionImporter,
thread_manager: Arc<ThreadManager>,
config_manager: ConfigManager,
config_processor: ConfigRequestProcessor,
arg0_paths: Arg0DispatchPaths,
}
impl ExternalAgentConfigRequestProcessor {
pub(crate) fn new(
outgoing: Arc<OutgoingMessageSender>,
thread_manager: Arc<ThreadManager>,
thread_store: Arc<dyn ThreadStore>,
config_manager: ConfigManager,
config_processor: ConfigRequestProcessor,
arg0_paths: Arg0DispatchPaths,
codex_home: PathBuf,
) -> Self {
let session_importer = ExternalAgentSessionImporter::new(
codex_home.clone(),
Arc::clone(&thread_manager),
thread_store,
config_manager,
arg0_paths,
);
Self {
outgoing,
migration_service: ExternalAgentConfigService::new(codex_home.clone()),
codex_home,
session_import_permits: Arc::new(Semaphore::new(1)),
migration_service: ExternalAgentConfigService::new(codex_home),
session_importer,
thread_manager,
config_manager,
config_processor,
arg0_paths,
}
}
@@ -207,42 +201,12 @@ impl ExternalAgentConfigRequestProcessor {
return Ok(());
}
let session_import_permits = Arc::clone(&self.session_import_permits);
let session_processor = self.clone();
let session_importer = self.session_importer.clone();
let plugin_processor = self.clone();
let outgoing = Arc::clone(&self.outgoing);
let thread_manager = Arc::clone(&self.thread_manager);
tokio::spawn(async move {
let session_imports = async move {
if !pending_session_imports.is_empty() {
let Ok(_session_import_permit) = session_import_permits.acquire_owned().await
else {
return;
};
let pending_session_imports = session_processor
.prepare_validated_session_imports(pending_session_imports);
for pending_session_import in pending_session_imports {
match session_processor
.import_external_agent_session(pending_session_import.session)
.await
{
Ok(imported_thread_id) => {
session_processor.record_imported_session(
&pending_session_import.source_path,
imported_thread_id,
);
}
Err(error) => {
tracing::warn!(
error = %error.message,
path = %pending_session_import.source_path.display(),
"external agent session import failed"
);
}
}
}
}
};
let session_imports = session_importer.import_sessions(pending_session_imports);
let plugin_imports = async move {
for pending_plugin_import in pending_plugin_imports {
match plugin_processor
@@ -274,65 +238,6 @@ impl ExternalAgentConfigRequestProcessor {
Ok(())
}
async fn import_external_agent_session(
&self,
session: ImportedExternalAgentSession,
) -> Result<ThreadId, JSONRPCErrorError> {
let ImportedExternalAgentSession {
cwd,
title,
rollout_items,
} = session;
let config = self
.config_manager
.load_with_overrides(
/*request_overrides*/ None,
ConfigOverrides {
cwd: Some(PathBuf::from(cwd.to_string_lossy().into_owned())),
codex_linux_sandbox_exe: self.arg0_paths.codex_linux_sandbox_exe.clone(),
main_execve_wrapper_exe: self.arg0_paths.main_execve_wrapper_exe.clone(),
..Default::default()
},
)
.await
.map_err(|err| {
internal_error(format!("failed to load imported session config: {err}"))
})?;
let environments = self
.thread_manager
.default_environment_selections(&config.cwd);
let imported_thread = self
.thread_manager
.start_thread_with_options(StartThreadOptions {
config,
initial_history: InitialHistory::Forked(rollout_items),
session_source: None,
thread_source: None,
dynamic_tools: Vec::new(),
metrics_service_name: None,
parent_trace: None,
environments,
})
.await
.map_err(|err| internal_error(format!("failed to import session: {err}")))?;
if let Some(title) = title
&& let Some(name) = codex_core::util::normalize_thread_name(&title)
{
imported_thread
.thread
.update_thread_metadata(
ThreadMetadataPatch {
name: Some(Some(name)),
..Default::default()
},
/*include_archived*/ false,
)
.await
.map_err(|err| internal_error(format!("failed to name imported session: {err}")))?;
}
Ok(imported_thread.thread_id)
}
fn validate_pending_session_imports(
&self,
params: &ExternalAgentConfigImportParams,
@@ -371,24 +276,6 @@ impl ExternalAgentConfigRequestProcessor {
Ok(selected_sessions)
}
fn prepare_validated_session_imports(
&self,
sessions: Vec<CoreSessionMigration>,
) -> Vec<PendingSessionImport> {
prepare_validated_session_imports(&self.codex_home, sessions)
}
fn record_imported_session(&self, source_path: &std::path::Path, imported_thread_id: ThreadId) {
if let Err(err) = record_imported_session(&self.codex_home, source_path, imported_thread_id)
{
tracing::warn!(
error = %err,
path = %source_path.display(),
"external agent session import ledger update failed"
);
}
}
async fn import_external_agent_config(
&self,
params: ExternalAgentConfigImportParams,
@@ -0,0 +1,261 @@
use std::path::PathBuf;
use std::sync::Arc;
use chrono::Utc;
use codex_arg0::Arg0DispatchPaths;
use codex_core::ThreadManager;
use codex_core::config::ConfigOverrides;
use codex_external_agent_sessions::CompletedExternalAgentSessionImport;
use codex_external_agent_sessions::ExternalAgentSessionMigration;
use codex_external_agent_sessions::ImportedExternalAgentSession;
use codex_external_agent_sessions::PendingSessionImport;
use codex_external_agent_sessions::prepare_validated_session_import;
use codex_external_agent_sessions::record_completed_session_imports;
use codex_models_manager::manager::RefreshStrategy;
use codex_protocol::ThreadId;
use codex_protocol::models::BaseInstructions;
use codex_protocol::protocol::MultiAgentVersion;
use codex_protocol::protocol::ThreadMemoryMode;
use codex_rollout::is_persisted_rollout_item;
use codex_thread_store::AppendThreadItemsParams;
use codex_thread_store::CreateThreadParams;
use codex_thread_store::ThreadMetadataPatch;
use codex_thread_store::ThreadPersistenceMetadata;
use codex_thread_store::ThreadStore;
use codex_thread_store::UpdateThreadMetadataParams;
use futures::StreamExt;
use tokio::sync::Semaphore;
use crate::config_manager::ConfigManager;
const SESSION_IMPORT_CONCURRENCY: usize = 5;
#[derive(Clone)]
pub(super) struct ExternalAgentSessionImporter {
codex_home: PathBuf,
permits: Arc<Semaphore>,
thread_manager: Arc<ThreadManager>,
thread_store: Arc<dyn ThreadStore>,
config_manager: ConfigManager,
arg0_paths: Arg0DispatchPaths,
}
impl ExternalAgentSessionImporter {
pub(super) fn new(
codex_home: PathBuf,
thread_manager: Arc<ThreadManager>,
thread_store: Arc<dyn ThreadStore>,
config_manager: ConfigManager,
arg0_paths: Arg0DispatchPaths,
) -> Self {
Self {
codex_home,
permits: Arc::new(Semaphore::new(1)),
thread_manager,
thread_store,
config_manager,
arg0_paths,
}
}
pub(super) async fn import_sessions(&self, sessions: Vec<ExternalAgentSessionMigration>) {
if sessions.is_empty() {
return;
}
let Ok(_permit) = self.permits.acquire().await else {
return;
};
let import_results = futures::stream::iter(sessions)
.map(|session| {
let importer = self.clone();
async move { importer.import_requested_session(session).await }
})
.buffer_unordered(SESSION_IMPORT_CONCURRENCY);
futures::pin_mut!(import_results);
let mut completed_imports = Vec::new();
while let Some(result) = import_results.next().await {
match result {
Ok(Some(completed_import)) => completed_imports.push(completed_import),
Ok(None) => {}
Err(failure) => {
tracing::warn!(
error = %failure.message,
path = %failure.source_path.display(),
"external agent session import failed"
);
}
}
}
if let Err(err) = record_completed_session_imports(&self.codex_home, completed_imports) {
tracing::warn!(
error = %err,
"external agent session import ledger update failed"
);
}
}
async fn import_requested_session(
&self,
session: ExternalAgentSessionMigration,
) -> Result<Option<CompletedExternalAgentSessionImport>, SessionImportFailure> {
let source_path = session.path.clone();
let Some(pending_import) =
self.prepare_session_import(session)
.await
.map_err(|message| SessionImportFailure {
source_path: source_path.clone(),
message,
})?
else {
return Ok(None);
};
let imported_thread_id =
self.persist_session(pending_import.session)
.await
.map_err(|message| SessionImportFailure {
source_path: pending_import.source_path.clone(),
message,
})?;
Ok(Some(CompletedExternalAgentSessionImport {
source_path: pending_import.source_path,
source_content_sha256: pending_import.source_content_sha256,
imported_thread_id,
}))
}
async fn prepare_session_import(
&self,
session: ExternalAgentSessionMigration,
) -> Result<Option<PendingSessionImport>, String> {
let codex_home = self.codex_home.clone();
tokio::task::spawn_blocking(move || prepare_validated_session_import(&codex_home, session))
.await
.map_err(|err| format!("external agent session preparation task failed: {err}"))?
.map_err(|err| format!("failed to prepare external agent session: {err}"))
}
async fn persist_session(
&self,
session: ImportedExternalAgentSession,
) -> Result<ThreadId, String> {
let ImportedExternalAgentSession {
cwd,
title,
first_user_message,
mut rollout_items,
} = session;
let config = self
.config_manager
.load_with_overrides(
/*request_overrides*/ None,
ConfigOverrides {
cwd: Some(cwd),
codex_linux_sandbox_exe: self.arg0_paths.codex_linux_sandbox_exe.clone(),
main_execve_wrapper_exe: self.arg0_paths.main_execve_wrapper_exe.clone(),
..Default::default()
},
)
.await
.map_err(|err| format!("failed to load imported session config: {err}"))?;
let models_manager = self.thread_manager.get_models_manager();
let model = models_manager
.get_default_model(&config.model, RefreshStrategy::Offline)
.await;
let model_info = models_manager
.get_model_info(model.as_str(), &config.to_models_manager_config())
.await;
let thread_id = ThreadId::new();
let source = self.thread_manager.session_source();
let cwd = config.cwd.to_path_buf();
let model_provider = config.model_provider_id.clone();
let memory_mode = if config.memories.generate_memories {
ThreadMemoryMode::Enabled
} else {
ThreadMemoryMode::Disabled
};
let now = Utc::now();
let create_params = CreateThreadParams {
thread_id,
extra_config: None,
forked_from_id: None,
parent_thread_id: None,
source: source.clone(),
thread_source: None,
base_instructions: BaseInstructions {
text: config
.base_instructions
.clone()
.unwrap_or_else(|| model_info.get_model_instructions(config.personality)),
},
dynamic_tools: Vec::new(),
multi_agent_version: Some(MultiAgentVersion::V1),
metadata: ThreadPersistenceMetadata {
cwd: Some(cwd.clone()),
model_provider: model_provider.clone(),
memory_mode,
},
};
rollout_items.retain(is_persisted_rollout_item);
let title = title
.as_deref()
.and_then(codex_core::util::normalize_thread_name);
let metadata = ThreadMetadataPatch {
title,
preview: first_user_message.clone(),
model_provider: Some(model_provider),
created_at: Some(now),
updated_at: Some(now),
source: Some(source.clone()),
thread_source: Some(None),
agent_nickname: Some(source.get_nickname()),
agent_role: Some(source.get_agent_role()),
agent_path: Some(source.get_agent_path().map(Into::into)),
cwd: Some(cwd),
cli_version: Some(env!("CARGO_PKG_VERSION").to_string()),
first_user_message,
memory_mode: Some(memory_mode),
..Default::default()
};
self.thread_store
.create_thread(create_params)
.await
.map_err(|err| format!("failed to import session: {err}"))?;
if !rollout_items.is_empty()
&& let Err(err) = self
.thread_store
.append_items(AppendThreadItemsParams {
thread_id,
items: rollout_items,
})
.await
{
let _ = self.thread_store.discard_thread(thread_id).await;
return Err(format!("failed to import session: {err}"));
}
self.thread_store
.update_thread_metadata(UpdateThreadMetadataParams {
thread_id,
patch: metadata,
include_archived: false,
})
.await
.map_err(|err| format!("failed to update imported session: {err}"))?;
self.thread_store
.persist_thread(thread_id)
.await
.map_err(|err| format!("failed to persist imported session: {err}"))?;
self.thread_store
.shutdown_thread(thread_id)
.await
.map_err(|err| format!("failed to shutdown imported session: {err}"))?;
Ok(thread_id)
}
}
struct SessionImportFailure {
source_path: PathBuf,
message: String,
}
@@ -120,12 +120,16 @@ impl McpRequestProcessor {
timeout_secs,
} = params;
let configured_servers = self
let auth = self.auth_manager.auth().await;
let effective_servers = self
.thread_manager
.mcp_manager()
.configured_servers(&config)
.effective_servers(&config, auth.as_ref())
.await;
let Some(server) = configured_servers.get(&name) else {
let Some(server) = effective_servers
.get(&name)
.and_then(codex_mcp::EffectiveMcpServer::configured_config)
else {
return Err(invalid_request(format!(
"No MCP server named '{name}' found."
)));
@@ -210,8 +214,10 @@ impl McpRequestProcessor {
}
None => self.load_latest_config(/*fallback_cwd*/ None).await?,
};
let mcp_config = config
.to_mcp_config(self.thread_manager.plugins_manager().as_ref())
let mcp_config = self
.thread_manager
.mcp_manager()
.runtime_config(&config)
.await;
let auth = self.auth_manager.auth().await;
let environment_manager = self.thread_manager.environment_manager();
@@ -361,8 +367,10 @@ impl McpRequestProcessor {
}
let config = self.load_latest_config(/*fallback_cwd*/ None).await?;
let mcp_config = config
.to_mcp_config(self.thread_manager.plugins_manager().as_ref())
let mcp_config = self
.thread_manager
.mcp_manager()
.runtime_config(&config)
.await;
let auth = self.auth_manager.auth().await;
let environment_manager = self.thread_manager.environment_manager();
@@ -7,9 +7,13 @@ use codex_app_server_protocol::PluginSharePrincipalRole;
use codex_app_server_protocol::PluginShareTargetRole;
use codex_config::types::McpServerConfig;
use codex_core_plugins::OPENAI_CURATED_MARKETPLACE_NAME;
use codex_core_plugins::PluginListBackgroundTaskOptions;
use codex_core_plugins::remote::REMOTE_GLOBAL_MARKETPLACE_NAME;
use codex_core_plugins::remote::REMOTE_WORKSPACE_MARKETPLACE_NAME;
use codex_core_plugins::remote::REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME;
use codex_core_plugins::remote::REMOTE_WORKSPACE_SHARED_WITH_ME_PRIVATE_MARKETPLACE_NAME;
use codex_core_plugins::remote::REMOTE_WORKSPACE_SHARED_WITH_ME_UNLISTED_MARKETPLACE_NAME;
use codex_core_plugins::remote::RemoteAppTemplateUnavailableReason;
use codex_core_plugins::remote::RemotePluginScope;
use codex_core_plugins::remote::is_valid_remote_plugin_id;
use codex_core_plugins::remote::validate_remote_plugin_id;
use codex_mcp::McpOAuthLoginSupport;
@@ -148,15 +152,18 @@ fn convert_configured_marketplace_plugin_to_plugin_summary(
}
}
fn remote_installed_plugin_visible_scopes(config: &Config) -> Vec<RemotePluginScope> {
let mut scopes = Vec::new();
fn remote_installed_plugin_visible_marketplaces(config: &Config) -> Vec<&'static str> {
let mut marketplaces = Vec::new();
if config.features.enabled(Feature::RemotePlugin) {
scopes.push(RemotePluginScope::Global);
marketplaces.push(REMOTE_GLOBAL_MARKETPLACE_NAME);
}
marketplaces.push(REMOTE_WORKSPACE_MARKETPLACE_NAME);
if config.features.enabled(Feature::PluginSharing) {
scopes.push(RemotePluginScope::Workspace);
marketplaces.push(REMOTE_WORKSPACE_SHARED_WITH_ME_MARKETPLACE_NAME);
marketplaces.push(REMOTE_WORKSPACE_SHARED_WITH_ME_PRIVATE_MARKETPLACE_NAME);
marketplaces.push(REMOTE_WORKSPACE_SHARED_WITH_ME_UNLISTED_MARKETPLACE_NAME);
}
scopes
marketplaces
}
fn filter_openai_curated_installed_conflicts(
@@ -543,21 +550,30 @@ impl PluginRequestProcessor {
return Ok(empty_response());
}
let plugins_input = config.plugins_config_input();
if include_local || marketplace_kinds.contains(&PluginListMarketplaceKind::SharedWithMe) {
plugins_manager.maybe_start_plugin_list_background_tasks_for_config(
&plugins_input,
auth.clone(),
&roots,
Some(self.effective_plugins_changed_callback()),
let include_shared_with_me =
marketplace_kinds.contains(&PluginListMarketplaceKind::SharedWithMe);
let include_global_remote =
!explicit_marketplace_kinds && config.features.enabled(Feature::RemotePlugin);
let remote_plugin_service_config = RemotePluginServiceConfig {
chatgpt_base_url: config.chatgpt_base_url.clone(),
};
let refresh_global_remote_catalog_cache = include_global_remote
&& codex_core_plugins::remote::has_cached_global_remote_plugin_catalog(
config.codex_home.as_path(),
&remote_plugin_service_config,
auth.as_ref(),
);
}
let (mut data, marketplace_load_errors) = if include_local {
let config_for_marketplace_listing = plugins_input.clone();
let plugins_manager_for_marketplace_listing = plugins_manager.clone();
let roots_for_marketplace_listing = roots.clone();
let shared_plugin_ids_by_local_path = load_shared_plugin_ids_by_local_path(&config)?;
match tokio::task::spawn_blocking(move || {
let outcome = plugins_manager_for_marketplace_listing
.list_marketplaces_for_config(&config_for_marketplace_listing, &roots)?;
.list_marketplaces_for_config(
&config_for_marketplace_listing,
&roots_for_marketplace_listing,
)?;
Ok::<
(
Vec<PluginMarketplaceEntry>,
@@ -617,9 +633,6 @@ impl PluginRequestProcessor {
// TODO(remote plugins): Remove this once remote plugins are ready and vertical plugins are
// served directly from the normal remote catalog.
if include_vertical && !config.features.enabled(Feature::RemotePlugin) {
let remote_plugin_service_config = RemotePluginServiceConfig {
chatgpt_base_url: config.chatgpt_base_url.clone(),
};
match codex_core_plugins::remote::fetch_openai_curated_remote_collection_marketplace(
&remote_plugin_service_config,
auth.as_ref(),
@@ -644,21 +657,16 @@ impl PluginRequestProcessor {
}
let mut remote_sources = Vec::new();
if !explicit_marketplace_kinds && config.features.enabled(Feature::RemotePlugin) {
if include_global_remote {
remote_sources.push(RemoteMarketplaceSource::Global);
}
if marketplace_kinds.contains(&PluginListMarketplaceKind::WorkspaceDirectory) {
remote_sources.push(RemoteMarketplaceSource::WorkspaceDirectory);
}
if marketplace_kinds.contains(&PluginListMarketplaceKind::SharedWithMe)
&& config.features.enabled(Feature::PluginSharing)
{
if include_shared_with_me && config.features.enabled(Feature::PluginSharing) {
remote_sources.push(RemoteMarketplaceSource::SharedWithMe);
}
if !remote_sources.is_empty() {
let remote_plugin_service_config = RemotePluginServiceConfig {
chatgpt_base_url: config.chatgpt_base_url.clone(),
};
match codex_core_plugins::remote::fetch_remote_marketplaces(
&remote_plugin_service_config,
auth.as_ref(),
@@ -702,6 +710,17 @@ impl PluginRequestProcessor {
}
}
}
if include_local || include_shared_with_me || include_global_remote {
plugins_manager.maybe_start_plugin_list_background_tasks_for_config(
&plugins_input,
auth.clone(),
&roots,
PluginListBackgroundTaskOptions {
refresh_global_remote_catalog_cache,
},
Some(self.effective_plugins_changed_callback()),
);
}
let featured_plugin_ids = if data
.iter()
@@ -763,8 +782,8 @@ impl PluginRequestProcessor {
}
let plugins_input = config.plugins_config_input();
let remote_installed_plugin_visible_scopes =
remote_installed_plugin_visible_scopes(&config);
let remote_installed_plugin_visible_marketplaces =
remote_installed_plugin_visible_marketplaces(&config);
plugins_manager.maybe_start_remote_installed_plugin_bundle_sync(
&plugins_input,
auth.clone(),
@@ -785,7 +804,7 @@ impl PluginRequestProcessor {
self.load_remote_installed_plugins(
plugins_manager,
&plugins_input,
&remote_installed_plugin_visible_scopes,
&remote_installed_plugin_visible_marketplaces,
auth.as_ref(),
)
.await,
@@ -885,11 +904,11 @@ impl PluginRequestProcessor {
&self,
plugins_manager: Arc<codex_core_plugins::PluginsManager>,
plugins_input: &codex_core_plugins::PluginsConfigInput,
visible_scopes: &[RemotePluginScope],
visible_marketplaces: &[&str],
auth: Option<&CodexAuth>,
) -> Vec<PluginMarketplaceEntry> {
let remote_marketplaces = if let Some(remote_marketplaces) =
plugins_manager.build_remote_installed_plugin_marketplaces_from_cache(visible_scopes)
let remote_marketplaces = if let Some(remote_marketplaces) = plugins_manager
.build_remote_installed_plugin_marketplaces_from_cache(visible_marketplaces)
{
Ok(remote_marketplaces)
} else {
@@ -897,7 +916,7 @@ impl PluginRequestProcessor {
.build_and_cache_remote_installed_plugin_marketplaces(
plugins_input,
auth,
visible_scopes,
visible_marketplaces,
Some(self.effective_plugins_changed_callback()),
)
.await
@@ -1017,6 +1036,7 @@ impl PluginRequestProcessor {
&config,
&outcome.plugin.apps,
Arc::clone(&environment_manager),
self.thread_manager.mcp_manager(),
)
.await;
let visible_skills = outcome
@@ -1099,6 +1119,7 @@ impl PluginRequestProcessor {
&config,
&plugin_apps,
Arc::clone(&environment_manager),
self.thread_manager.mcp_manager(),
)
.await;
remote_plugin_detail_to_info(remote_detail, app_summaries)
@@ -1506,7 +1527,7 @@ impl PluginRequestProcessor {
// Cache first so a backend install cannot succeed when local materialization fails.
// If this backend call fails, the cache entry is harmless because remote installed state
// is still backend-gated.
codex_core_plugins::remote::install_remote_plugin(
let install_result = codex_core_plugins::remote::install_remote_plugin(
&remote_plugin_service_config,
auth.as_ref(),
&actual_remote_marketplace_name,
@@ -1525,7 +1546,7 @@ impl PluginRequestProcessor {
let mut plugin_metadata =
plugin_telemetry_metadata_from_root(&result.plugin_id, &result.installed_path).await;
plugin_metadata.remote_plugin_id = Some(remote_plugin_id);
plugin_metadata.remote_plugin_id = Some(remote_plugin_id.clone());
self.analytics_events_client
.track_plugin_installed(plugin_metadata);
@@ -1535,15 +1556,42 @@ impl PluginRequestProcessor {
.await;
}
let plugin_apps = load_plugin_apps(result.installed_path.as_path()).await;
let apps_needing_auth = self
.plugin_apps_needing_auth_for_install(
&config,
auth.as_ref().is_some_and(CodexAuth::is_chatgpt_auth),
&result.plugin_id.as_key(),
&plugin_apps,
)
.await;
let is_chatgpt_auth = auth.as_ref().is_some_and(CodexAuth::is_chatgpt_auth);
let apps_needing_auth =
if let Some(app_ids_needing_auth) = install_result.app_ids_needing_auth {
if app_ids_needing_auth.is_empty()
|| !config.features.apps_enabled_for_auth(is_chatgpt_auth)
{
Vec::new()
} else {
let plugin_apps = app_ids_needing_auth
.into_iter()
.map(codex_plugin::AppConnectorId)
.collect::<Vec<_>>();
let all_connectors = connectors::list_cached_all_connectors(&config)
.await
.unwrap_or_default();
connectors::connectors_for_plugin_apps(all_connectors, &plugin_apps)
.into_iter()
.map(|connector| AppSummary {
id: connector.id,
name: connector.name,
description: connector.description,
install_url: connector.install_url,
needs_auth: true,
})
.collect()
}
} else {
let plugin_apps = load_plugin_apps(result.installed_path.as_path()).await;
self.plugin_apps_needing_auth_for_install(
&config,
is_chatgpt_auth,
&result.plugin_id.as_key(),
&plugin_apps,
)
.await
};
Ok(PluginInstallResponse {
auth_policy: remote_detail.summary.auth_policy,
@@ -1565,10 +1613,11 @@ impl PluginRequestProcessor {
let environment_manager = self.thread_manager.environment_manager();
let (all_connectors_result, accessible_connectors_result) = tokio::join!(
connectors::list_all_connectors_with_options(config, /*force_refetch*/ false),
connectors::list_accessible_connectors_from_mcp_tools_with_environment_manager(
connectors::list_accessible_connectors_from_mcp_tools_with_mcp_manager(
config,
/*force_refetch*/ true,
Arc::clone(&environment_manager)
Arc::clone(&environment_manager),
self.thread_manager.mcp_manager(),
),
);
@@ -1835,6 +1884,7 @@ async fn load_plugin_app_summaries(
config: &Config,
plugin_apps: &[codex_plugin::AppConnectorId],
environment_manager: Arc<EnvironmentManager>,
mcp_manager: Arc<McpManager>,
) -> Vec<AppSummary> {
if plugin_apps.is_empty() {
return Vec::new();
@@ -1854,10 +1904,11 @@ async fn load_plugin_app_summaries(
let plugin_connectors = connectors::connectors_for_plugin_apps(connectors, plugin_apps);
let accessible_connectors =
match connectors::list_accessible_connectors_from_mcp_tools_with_environment_manager(
match connectors::list_accessible_connectors_from_mcp_tools_with_mcp_manager(
config,
/*force_refetch*/ false,
environment_manager,
mcp_manager,
)
.await
{
@@ -627,6 +627,8 @@ pub(super) async fn handle_pending_thread_resume_request(
}
}
let config_snapshot = pending.config_snapshot;
let cwd = config_snapshot.cwd().clone();
let ThreadConfigSnapshot {
model,
model_provider_id,
@@ -635,11 +637,10 @@ pub(super) async fn handle_pending_thread_resume_request(
approvals_reviewer,
permission_profile,
active_permission_profile,
cwd,
workspace_roots,
reasoning_effort,
..
} = pending.config_snapshot;
} = config_snapshot;
let instruction_sources = pending.instruction_sources;
let sandbox = thread_response_sandbox_policy(&permission_profile, cwd.as_path());
let active_permission_profile =
@@ -1,5 +1,7 @@
use super::*;
use crate::error_code::method_not_found;
use codex_app_server_protocol::SelectedCapabilityRoot;
use codex_extension_api::ExtensionDataInit;
use codex_protocol::models::BUILT_IN_PERMISSION_PROFILE_DANGER_FULL_ACCESS;
use codex_protocol::models::BUILT_IN_PERMISSION_PROFILE_WORKSPACE;
@@ -47,11 +49,11 @@ fn collect_resume_override_mismatches(
}
if let Some(requested_cwd) = request.cwd.as_deref() {
let requested_cwd_path = std::path::PathBuf::from(requested_cwd);
if requested_cwd_path != config_snapshot.cwd.as_path() {
if requested_cwd_path != config_snapshot.cwd().as_path() {
mismatch_details.push(format!(
"cwd requested={} active={}",
requested_cwd_path.display(),
config_snapshot.cwd.display()
config_snapshot.cwd().display()
));
}
}
@@ -327,6 +329,17 @@ pub(crate) struct ThreadRequestProcessor {
pub(super) skills_watcher: Arc<SkillsWatcher>,
}
/// Outcome of trying to satisfy a resume request from an already loaded thread.
enum RunningThreadResumeResult {
/// The request was delegated to the loaded thread.
Handled,
/// No loaded thread handled the request.
///
/// The optional stored thread contains the history-bearing probe that cold
/// resume can reuse instead of reading the rollout again.
NotRunning(Option<Box<StoredThread>>),
}
impl ThreadRequestProcessor {
#[allow(clippy::too_many_arguments)]
pub(crate) fn new(
@@ -822,6 +835,7 @@ impl ThreadRequestProcessor {
base_instructions,
developer_instructions,
dynamic_tools,
selected_capability_roots,
mock_experimental_field: _mock_experimental_field,
experimental_raw_events,
personality,
@@ -877,6 +891,7 @@ impl ThreadRequestProcessor {
config,
typesafe_overrides,
dynamic_tools,
selected_capability_roots.unwrap_or_default(),
session_start_source,
thread_source.map(Into::into),
environment_selections,
@@ -949,6 +964,7 @@ impl ThreadRequestProcessor {
config_overrides: Option<HashMap<String, serde_json::Value>>,
typesafe_overrides: ConfigOverrides,
dynamic_tools: Option<Vec<ApiDynamicToolSpec>>,
selected_capability_roots: Vec<SelectedCapabilityRoot>,
session_start_source: Option<codex_app_server_protocol::ThreadStartSource>,
thread_source: Option<codex_protocol::protocol::ThreadSource>,
environments: Option<Vec<TurnEnvironmentSelection>>,
@@ -1050,6 +1066,10 @@ impl ThreadRequestProcessor {
.collect()
};
let core_dynamic_tool_count = core_dynamic_tools.len();
let mut thread_extension_init = ExtensionDataInit::new();
if !selected_capability_roots.is_empty() {
thread_extension_init.insert(selected_capability_roots);
}
let create_thread_started_at = std::time::Instant::now();
let NewThread {
thread_id,
@@ -1072,6 +1092,7 @@ impl ThreadRequestProcessor {
metrics_service_name: service_name,
parent_trace: request_trace,
environments,
thread_extension_init,
})
.instrument(tracing::info_span!(
"app_server.thread_start.create_thread",
@@ -1154,8 +1175,9 @@ impl ThreadRequestProcessor {
let sandbox = thread_response_sandbox_policy(
&config_snapshot.permission_profile,
config_snapshot.cwd.as_path(),
config_snapshot.cwd().as_path(),
);
let cwd = config_snapshot.cwd().clone();
let active_permission_profile =
thread_response_active_permission_profile(config_snapshot.active_permission_profile);
@@ -1164,7 +1186,7 @@ impl ThreadRequestProcessor {
model: config_snapshot.model,
model_provider: config_snapshot.model_provider_id,
service_tier: config_snapshot.service_tier,
cwd: config_snapshot.cwd,
cwd,
runtime_workspace_roots: config_snapshot.workspace_roots,
instruction_sources,
approval_policy: config_snapshot.approval_policy.into(),
@@ -2418,7 +2440,7 @@ impl ThreadRequestProcessor {
return Ok(());
}
};
match self
let stored_thread_from_running_probe = match self
.resume_running_thread(
&request_id,
&params,
@@ -2427,13 +2449,13 @@ impl ThreadRequestProcessor {
)
.await
{
Ok(true) => return Ok(()),
Ok(false) => {}
Ok(RunningThreadResumeResult::Handled) => return Ok(()),
Ok(RunningThreadResumeResult::NotRunning(stored_thread)) => stored_thread,
Err(error) => {
self.outgoing.send_error(request_id, error).await;
return Ok(());
}
}
};
let ThreadResumeParams {
thread_id,
@@ -2457,15 +2479,20 @@ impl ThreadRequestProcessor {
} = params;
let include_turns = !exclude_turns;
let (thread_history, resume_source_thread) = match if let Some(history) = history {
let resume_result = if let Some(history) = history {
self.resume_thread_from_history(history.as_slice())
.await
.map(|thread_history| (thread_history, None))
} else if let Some(stored_thread) = stored_thread_from_running_probe {
self.stored_thread_to_initial_history(&stored_thread)
.await
.map(|thread_history| (thread_history, Some(*stored_thread)))
} else {
self.resume_thread_from_rollout(&thread_id, path.as_ref())
.await
.map(|(thread_history, stored_thread)| (thread_history, Some(stored_thread)))
} {
};
let (thread_history, resume_source_thread) = match resume_result {
Ok(value) => value,
Err(error) => {
self.outgoing.send_error(request_id, error).await;
@@ -2601,7 +2628,7 @@ impl ThreadRequestProcessor {
let config_snapshot = codex_thread.config_snapshot().await;
let sandbox = thread_response_sandbox_policy(
&config_snapshot.permission_profile,
config_snapshot.cwd.as_path(),
config_snapshot.cwd().as_path(),
);
let active_permission_profile = thread_response_active_permission_profile(
config_snapshot.active_permission_profile,
@@ -2706,7 +2733,7 @@ impl ThreadRequestProcessor {
params: &ThreadResumeParams,
app_server_client_name: Option<String>,
app_server_client_version: Option<String>,
) -> Result<bool, JSONRPCErrorError> {
) -> Result<RunningThreadResumeResult, JSONRPCErrorError> {
let running_thread = if params.history.is_some() {
if let Ok(existing_thread_id) = ThreadId::from_string(&params.thread_id)
&& self
@@ -2742,7 +2769,11 @@ impl ThreadRequestProcessor {
let existing_thread_id = source_thread.thread_id;
match self.thread_manager.get_thread(existing_thread_id).await {
Ok(existing_thread) => Some((existing_thread_id, existing_thread, source_thread)),
Err(_) => None,
Err(_) => {
return Ok(RunningThreadResumeResult::NotRunning(Some(Box::new(
source_thread,
))));
}
}
};
@@ -2783,7 +2814,9 @@ impl ThreadRequestProcessor {
ThreadShutdownResult::Complete => {
self.thread_manager.remove_thread(&existing_thread_id).await;
self.finalize_thread_teardown(existing_thread_id).await;
return Ok(false);
// Shutdown can flush newer rollout items, so reload the
// stored thread before starting the replacement session.
return Ok(RunningThreadResumeResult::NotRunning(None));
}
ThreadShutdownResult::SubmitFailed => {
warn!("failed to submit Shutdown to thread {existing_thread_id}");
@@ -2875,9 +2908,9 @@ impl ThreadRequestProcessor {
"failed to enqueue running thread resume for thread {existing_thread_id}: thread listener command channel is closed"
)));
}
return Ok(true);
return Ok(RunningThreadResumeResult::Handled);
}
Ok(false)
Ok(RunningThreadResumeResult::NotRunning(None))
}
async fn resume_thread_from_history(
@@ -3335,7 +3368,7 @@ impl ThreadRequestProcessor {
let config_snapshot = forked_thread.config_snapshot().await;
let sandbox = thread_response_sandbox_policy(
&config_snapshot.permission_profile,
config_snapshot.cwd.as_path(),
config_snapshot.cwd().as_path(),
);
let active_permission_profile =
thread_response_active_permission_profile(config_snapshot.active_permission_profile);
@@ -4121,7 +4154,7 @@ fn summary_from_thread_metadata(metadata: &ThreadMetadata) -> ConversationSummar
metadata.cwd.clone(),
metadata.cli_version.clone(),
metadata.source.clone(),
metadata.thread_source,
metadata.thread_source.clone(),
metadata.agent_nickname.clone(),
metadata.agent_role.clone(),
metadata.git_sha.clone(),
@@ -4205,12 +4238,12 @@ fn build_thread_from_snapshot(
updated_at: now,
status: ThreadStatus::NotLoaded,
path,
cwd: config_snapshot.cwd.clone(),
cwd: config_snapshot.cwd().clone(),
cli_version: env!("CARGO_PKG_VERSION").to_string(),
agent_nickname: config_snapshot.session_source.get_nickname(),
agent_role: config_snapshot.session_source.get_agent_role(),
source: config_snapshot.session_source.clone().into(),
thread_source: config_snapshot.thread_source.map(Into::into),
thread_source: config_snapshot.thread_source.clone().map(Into::into),
git_info: None,
name: None,
turns: Vec::new(),
@@ -77,6 +77,7 @@ mod thread_processor_behavior_tests {
use codex_protocol::protocol::AskForApproval;
use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::SubAgentSource;
use codex_protocol::protocol::TurnEnvironmentSelections;
use codex_state::ThreadMetadataBuilder;
use codex_thread_store::StoredThread;
use codex_utils_absolute_path::test_support::PathBufExt;
@@ -393,6 +394,7 @@ mod thread_processor_behavior_tests {
ThreadId::from_string("00000000-0000-0000-0000-000000000123").expect("valid thread");
let stored_thread = StoredThread {
thread_id,
extra_config: None,
rollout_path: Some(PathBuf::from("/tmp/thread.jsonl")),
forked_from_id: None,
parent_thread_id: None,
@@ -685,7 +687,7 @@ mod thread_processor_behavior_tests {
approvals_reviewer: codex_protocol::config_types::ApprovalsReviewer::User,
permission_profile: codex_protocol::models::PermissionProfile::Disabled,
active_permission_profile: None,
cwd,
environments: TurnEnvironmentSelections::new(cwd, Vec::new()),
workspace_roots: Vec::new(),
profile_workspace_roots: Vec::new(),
ephemeral: false,
@@ -190,12 +190,12 @@ pub(crate) fn thread_settings_from_config_snapshot(
config_snapshot: &ThreadConfigSnapshot,
) -> ThreadSettings {
ThreadSettings {
cwd: config_snapshot.cwd.clone(),
cwd: config_snapshot.cwd().clone(),
approval_policy: config_snapshot.approval_policy.into(),
approvals_reviewer: config_snapshot.approvals_reviewer.into(),
sandbox_policy: thread_response_sandbox_policy(
&config_snapshot.permission_profile,
config_snapshot.cwd.as_path(),
config_snapshot.cwd().as_path(),
),
active_permission_profile: thread_response_active_permission_profile(
config_snapshot.active_permission_profile.clone(),
@@ -213,24 +213,36 @@ pub(crate) fn thread_settings_from_config_snapshot(
pub(crate) fn thread_settings_from_core_snapshot(
snapshot: codex_protocol::protocol::ThreadSettingsSnapshot,
) -> ThreadSettings {
let codex_protocol::protocol::ThreadSettingsSnapshot {
model,
model_provider_id,
service_tier,
approval_policy,
approvals_reviewer,
permission_profile,
active_permission_profile,
cwd,
reasoning_effort,
reasoning_summary,
personality,
collaboration_mode,
} = snapshot;
let sandbox_policy = thread_response_sandbox_policy(&permission_profile, cwd.as_path());
ThreadSettings {
sandbox_policy: thread_response_sandbox_policy(
&snapshot.permission_profile,
snapshot.cwd.as_path(),
),
cwd: snapshot.cwd,
approval_policy: snapshot.approval_policy.into(),
approvals_reviewer: snapshot.approvals_reviewer.into(),
sandbox_policy,
cwd,
approval_policy: approval_policy.into(),
approvals_reviewer: approvals_reviewer.into(),
active_permission_profile: thread_response_active_permission_profile(
snapshot.active_permission_profile,
active_permission_profile,
),
model: snapshot.model,
model_provider: snapshot.model_provider_id,
service_tier: snapshot.service_tier,
effort: snapshot.reasoning_effort,
summary: snapshot.reasoning_summary,
collaboration_mode: snapshot.collaboration_mode,
personality: snapshot.personality,
model,
model_provider: model_provider_id,
service_tier,
effort: reasoning_effort,
summary: reasoning_summary,
collaboration_mode,
personality,
}
}
@@ -1,6 +1,12 @@
use super::*;
use codex_protocol::protocol::AdditionalContextEntry as CoreAdditionalContextEntry;
use codex_protocol::protocol::AdditionalContextKind as CoreAdditionalContextKind;
use codex_protocol::protocol::MultiAgentVersion;
use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::SubAgentSource;
const DIRECT_INPUT_TO_MULTI_AGENT_V2_SUBAGENT_ERROR: &str =
"direct app-server input is not allowed for multi-agent v2 sub-agents";
#[derive(Clone)]
pub(crate) struct TurnRequestProcessor {
@@ -43,7 +49,7 @@ fn map_additional_context(
struct ThreadSettingsBuildParams {
method: &'static str,
cwd: Option<AbsolutePathBuf>,
environments: Option<TurnEnvironmentSelections>,
runtime_workspace_roots: Option<Vec<AbsolutePathBuf>>,
approval_policy: Option<codex_app_server_protocol::AskForApproval>,
approvals_reviewer: Option<codex_app_server_protocol::ApprovalsReviewer>,
@@ -236,6 +242,26 @@ impl TurnRequestProcessor {
Ok((thread_id, thread))
}
async fn ensure_direct_input_allowed(
&self,
request_id: &ConnectionRequestId,
thread: &CodexThread,
) -> Result<(), JSONRPCErrorError> {
if thread.multi_agent_version() == Some(MultiAgentVersion::V2)
&& matches!(
thread.config_snapshot().await.session_source,
SessionSource::SubAgent(SubAgentSource::ThreadSpawn { .. })
)
{
let error = invalid_request(DIRECT_INPUT_TO_MULTI_AGENT_V2_SUBAGENT_ERROR);
self.track_error_response(request_id, &error, /*error_type*/ None);
return Err(error);
}
Ok(())
}
fn normalize_collaboration_mode(
&self,
mut collaboration_mode: CollaborationMode,
@@ -370,6 +396,14 @@ impl TurnRequestProcessor {
app_server_client_name: Option<String>,
app_server_client_version: Option<String>,
) -> Result<TurnStartResponse, JSONRPCErrorError> {
let (thread_id, thread) =
self.load_thread(&params.thread_id)
.await
.inspect_err(|error| {
self.track_error_response(&request_id, error, /*error_type*/ None);
})?;
self.ensure_direct_input_allowed(&request_id, thread.as_ref())
.await?;
if let Err(error) = Self::validate_v2_input_limit(&params.input) {
self.track_error_response(
&request_id,
@@ -378,12 +412,6 @@ impl TurnRequestProcessor {
);
return Err(error);
}
let (thread_id, thread) =
self.load_thread(&params.thread_id)
.await
.inspect_err(|error| {
self.track_error_response(&request_id, error, /*error_type*/ None);
})?;
Self::set_app_server_client_info(
thread.as_ref(),
app_server_client_name,
@@ -406,12 +434,14 @@ impl TurnRequestProcessor {
let additional_context = map_additional_context(params.additional_context);
let turn_has_input = !mapped_items.is_empty();
let cwd = resolve_request_cwd(params.cwd)?;
let environments =
Self::build_environment_override(thread.as_ref(), cwd, environment_selections).await;
let thread_settings = self
.build_thread_settings_overrides(
thread.as_ref(),
ThreadSettingsBuildParams {
method: "turn/start",
cwd,
environments,
runtime_workspace_roots: params.runtime_workspace_roots,
approval_policy: params.approval_policy,
approvals_reviewer: params.approvals_reviewer,
@@ -430,7 +460,6 @@ impl TurnRequestProcessor {
// Start the turn by submitting the user input. Return its submission id as turn_id.
let turn_op = Op::UserInput {
items: mapped_items,
environments: environment_selections,
final_output_json_schema: params.output_schema,
responsesapi_client_metadata: params.responsesapi_client_metadata,
additional_context,
@@ -478,6 +507,31 @@ impl TurnRequestProcessor {
Ok(TurnStartResponse { turn })
}
async fn build_environment_override(
thread: &CodexThread,
cwd: Option<AbsolutePathBuf>,
environment_selections: Option<Vec<TurnEnvironmentSelection>>,
) -> Option<TurnEnvironmentSelections> {
if cwd.is_none() && environment_selections.is_none() {
return None;
}
let snapshot = thread.config_snapshot().await;
let environment_selections =
environment_selections.unwrap_or_else(|| snapshot.environment_selections().to_vec());
let legacy_fallback_cwd = cwd.unwrap_or_else(|| {
environment_selections
.iter()
.find(|selection| selection.environment_id == LOCAL_ENVIRONMENT_ID)
.map(|selection| selection.cwd.clone())
.unwrap_or_else(|| snapshot.cwd().clone())
});
Some(TurnEnvironmentSelections::new(
legacy_fallback_cwd,
environment_selections,
))
}
async fn build_thread_settings_overrides(
&self,
thread: &CodexThread,
@@ -485,7 +539,7 @@ impl TurnRequestProcessor {
) -> Result<codex_protocol::protocol::ThreadSettingsOverrides, JSONRPCErrorError> {
let ThreadSettingsBuildParams {
method,
cwd,
environments,
runtime_workspace_roots,
approval_policy,
approvals_reviewer,
@@ -508,6 +562,7 @@ impl TurnRequestProcessor {
let collaboration_mode =
collaboration_mode.map(|mode| self.normalize_collaboration_mode(mode));
let runtime_workspace_roots_request = runtime_workspace_roots;
let has_environment_override = environments.is_some();
// `thread/settings/update` only acknowledges that the update was queued.
// Clients that send dependent partial updates should wait for
// `thread/settings/updated` or combine the fields in one request.
@@ -517,7 +572,7 @@ impl TurnRequestProcessor {
None
};
let has_any_overrides = cwd.is_some()
let has_any_overrides = has_environment_override
|| runtime_workspace_roots_request.is_some()
|| approval_policy.is_some()
|| approvals_reviewer.is_some()
@@ -545,7 +600,9 @@ impl TurnRequestProcessor {
)));
};
let overrides = ConfigOverrides {
cwd: cwd.as_ref().map(AbsolutePathBuf::to_path_buf),
cwd: environments
.as_ref()
.map(|environments| environments.legacy_fallback_cwd.to_path_buf()),
workspace_roots: Some(
runtime_workspace_roots
.clone()
@@ -561,7 +618,7 @@ impl TurnRequestProcessor {
.load_for_cwd(
/*request_overrides*/ None,
overrides,
Some(snapshot.cwd.to_path_buf()),
Some(snapshot.cwd().to_path_buf()),
)
.await
.map_err(|err| config_load_error(&err))?;
@@ -588,7 +645,7 @@ impl TurnRequestProcessor {
if has_any_overrides {
thread
.preview_thread_settings_overrides(CodexThreadSettingsOverrides {
cwd: cwd.clone(),
environments: environments.clone(),
workspace_roots: runtime_workspace_roots.clone(),
approval_policy,
approvals_reviewer,
@@ -611,7 +668,7 @@ impl TurnRequestProcessor {
}
Ok(codex_protocol::protocol::ThreadSettingsOverrides {
cwd,
environments,
workspace_roots: runtime_workspace_roots,
profile_workspace_roots,
approval_policy,
@@ -636,12 +693,18 @@ impl TurnRequestProcessor {
) -> Result<ThreadSettingsUpdateResponse, JSONRPCErrorError> {
let (_, thread) = self.load_thread(&params.thread_id).await?;
let cwd = resolve_request_cwd(params.cwd)?;
let environments = Self::build_environment_override(
thread.as_ref(),
cwd,
/*environment_selections*/ None,
)
.await;
let thread_settings = self
.build_thread_settings_overrides(
thread.as_ref(),
ThreadSettingsBuildParams {
method: "thread/settings/update",
cwd,
environments,
runtime_workspace_roots: None,
approval_policy: params.approval_policy,
approvals_reviewer: params.approvals_reviewer,
@@ -727,6 +790,8 @@ impl TurnRequestProcessor {
.inspect_err(|error| {
self.track_error_response(request_id, error, /*error_type*/ None);
})?;
self.ensure_direct_input_allowed(request_id, thread.as_ref())
.await?;
if params.expected_turn_id.is_empty() {
return Err(invalid_request("expectedTurnId must not be empty"));
@@ -311,7 +311,7 @@ mod tests {
let key = RequestSerializationQueueKey::Global("test");
let live_gate = gate();
let closed_gate = gate();
closed_gate.shutdown().await;
closed_gate.close().await;
let (tx, mut rx) = mpsc::unbounded_channel();
let (blocked_tx, blocked_rx) = oneshot::channel::<()>();
@@ -122,6 +122,7 @@ async fn get_conversation_summary_by_thread_id_reads_pathless_store_thread() ->
store
.create_thread(CreateThreadParams {
thread_id,
extra_config: None,
forked_from_id: None,
parent_thread_id: None,
source: SessionSource::Cli,
@@ -0,0 +1,148 @@
use std::time::Duration;
use anyhow::Result;
use app_test_support::TestAppServer;
use app_test_support::to_response;
use codex_app_server_protocol::CapabilityRootLocation;
use codex_app_server_protocol::JSONRPCResponse;
use codex_app_server_protocol::RequestId;
use codex_app_server_protocol::SelectedCapabilityRoot;
use codex_app_server_protocol::ThreadStartParams;
use codex_app_server_protocol::ThreadStartResponse;
use codex_app_server_protocol::TurnStartParams;
use codex_app_server_protocol::UserInput;
use core_test_support::responses;
use tempfile::TempDir;
use tokio::time::timeout;
const READ_TIMEOUT: Duration = Duration::from_secs(10);
const SKILL_NAME: &str = "demo-plugin:deploy";
const SKILL_MARKER: &str = "EXECUTOR_SKILL_BODY_MARKER";
const LOCAL_SKILL_MARKER: &str = "LOCAL_SKILL_BODY_MARKER";
#[tokio::test]
async fn selected_executor_root_exposes_plugin_skill() -> Result<()> {
let server = responses::start_mock_server().await;
let response_mock = responses::mount_sse_once(
&server,
responses::sse(vec![
responses::ev_response_created("resp-selected"),
responses::ev_assistant_message("msg-selected", "Done"),
responses::ev_completed("resp-selected"),
]),
)
.await;
let codex_home = TempDir::new()?;
std::fs::write(
codex_home.path().join("config.toml"),
format!(
r#"
model = "mock-model"
approval_policy = "never"
sandbox_mode = "read-only"
model_provider = "mock_provider"
[skills]
include_instructions = true
[model_providers.mock_provider]
name = "Mock provider for test"
base_url = "{}/v1"
wire_api = "responses"
request_max_retries = 0
stream_max_retries = 0
"#,
server.uri()
),
)?;
let local_skill_dir = codex_home.path().join("skills/local-deploy");
std::fs::create_dir_all(&local_skill_dir)?;
std::fs::write(
local_skill_dir.join("SKILL.md"),
format!(
"---\nname: {SKILL_NAME}\ndescription: Colliding local skill.\n---\n\n# Local deploy\n\n{LOCAL_SKILL_MARKER}\n"
),
)?;
let plugin_dir = TempDir::new()?;
let manifest_dir = plugin_dir.path().join(".codex-plugin");
let skill_dir = plugin_dir.path().join("skills/deploy");
std::fs::create_dir_all(&manifest_dir)?;
std::fs::create_dir_all(&skill_dir)?;
std::fs::write(
manifest_dir.join("plugin.json"),
r#"{"name":"demo-plugin"}"#,
)?;
std::fs::write(
skill_dir.join("SKILL.md"),
format!(
"---\nname: deploy\ndescription: Deploy through the executor.\n---\n\n# Deploy\n\n{SKILL_MARKER}\n"
),
)?;
let mut app_server = TestAppServer::new(codex_home.path()).await?;
timeout(READ_TIMEOUT, app_server.initialize()).await??;
let request_id = app_server
.send_thread_start_request(ThreadStartParams {
model: Some("mock-model".to_string()),
selected_capability_roots: Some(vec![SelectedCapabilityRoot {
id: "demo-plugin@1".to_string(),
location: CapabilityRootLocation::Environment {
environment_id: "local".to_string(),
path: plugin_dir.path().to_string_lossy().into_owned(),
},
}]),
..Default::default()
})
.await?;
let response: JSONRPCResponse = timeout(
READ_TIMEOUT,
app_server.read_stream_until_response_message(RequestId::Integer(request_id)),
)
.await??;
let ThreadStartResponse { thread, .. } = to_response(response)?;
let request_id = app_server
.send_turn_start_request(TurnStartParams {
thread_id: thread.id,
input: vec![UserInput::Text {
text: format!("Use ${SKILL_NAME}"),
text_elements: Vec::new(),
}],
..Default::default()
})
.await?;
timeout(
READ_TIMEOUT,
app_server.read_stream_until_response_message(RequestId::Integer(request_id)),
)
.await??;
timeout(
READ_TIMEOUT,
app_server.read_stream_until_notification_message("turn/completed"),
)
.await??;
let request = response_mock.single_request();
assert!(
request
.message_input_texts("developer")
.iter()
.any(|text| text.contains(SKILL_NAME))
);
let skill_fragments = request
.message_input_texts("user")
.into_iter()
.filter(|text| text.starts_with("<skill>"))
.collect::<Vec<_>>();
assert_eq!(1, skill_fragments.len());
let skill_fragment = skill_fragments
.first()
.expect("executor skill instructions should be model-visible");
assert!(skill_fragment.contains(&format!("<name>{SKILL_NAME}</name>")));
assert!(skill_fragment.contains(SKILL_MARKER));
assert!(!skill_fragment.contains(LOCAL_SKILL_MARKER));
Ok(())
}
@@ -435,6 +435,98 @@ async fn external_agent_config_import_creates_session_rollouts() -> Result<()> {
Ok(())
}
#[tokio::test]
async fn external_agent_config_import_does_not_initialize_required_mcp() -> Result<()> {
let server = create_mock_responses_server_repeating_assistant("unused").await;
let codex_home = TempDir::new()?;
create_config_toml(codex_home.path(), &server.uri())?;
let mut config = std::fs::read_to_string(codex_home.path().join("config.toml"))?;
config.push_str(
r#"
[mcp_servers.required_broken]
command = "this-command-does-not-exist"
required = true
"#,
);
std::fs::write(codex_home.path().join("config.toml"), config)?;
let project_root = codex_home.path().join("repo");
let recent_timestamp = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
let session_dir = codex_home.path().join(".claude/projects/repo");
let session_path = session_dir.join("session.jsonl");
std::fs::create_dir_all(&project_root)?;
std::fs::create_dir_all(&session_dir)?;
std::fs::write(
&session_path,
serde_json::json!({
"type": "user",
"cwd": &project_root,
"timestamp": &recent_timestamp,
"message": { "content": "first request" },
})
.to_string(),
)?;
let home_dir = codex_home.path().display().to_string();
let mut mcp =
TestAppServer::new_with_env(codex_home.path(), &[("HOME", Some(home_dir.as_str()))])
.await?;
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
let request_id = mcp
.send_raw_request(
"externalAgentConfig/import",
Some(serde_json::json!({
"migrationItems": [{
"itemType": "SESSIONS",
"description": "Migrate recent sessions",
"cwd": null,
"details": {
"sessions": [{
"path": session_path,
"cwd": project_root,
"title": "first request"
}]
}
}]
})),
)
.await?;
timeout(
DEFAULT_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(request_id)),
)
.await??;
timeout(
DEFAULT_TIMEOUT,
mcp.read_stream_until_notification_message("externalAgentConfig/import/completed"),
)
.await??;
let request_id = mcp
.send_thread_list_request(ThreadListParams {
cursor: None,
limit: None,
sort_key: None,
sort_direction: None,
model_providers: None,
source_kinds: None,
archived: None,
cwd: None,
use_state_db_only: false,
search_term: None,
})
.await?;
let response: JSONRPCResponse = timeout(
DEFAULT_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(request_id)),
)
.await??;
let response: ThreadListResponse = to_response(response)?;
assert_eq!(response.data.len(), 1);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn external_agent_config_import_accepts_detected_session_payload_after_restart() -> Result<()>
{
@@ -29,6 +29,11 @@ use wiremock::matchers::method;
use wiremock::matchers::path;
const RESULT: &str = "cG5n";
const TINY_PNG_BYTES: &[u8] = &[
137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 1, 0, 0, 0, 1, 8, 6, 0,
0, 0, 31, 21, 196, 137, 0, 0, 0, 11, 73, 68, 65, 84, 120, 156, 99, 96, 0, 2, 0, 0, 5, 0, 1,
122, 94, 171, 63, 0, 0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130,
];
#[derive(Clone, Copy)]
enum ImagegenTestMode {
@@ -59,7 +64,6 @@ async fn standalone_image_generation_returns_saved_path_hint_to_model() -> Resul
"image_gen",
"imagegen",
&json!({
"action": "generate",
"prompt": "paint a blue whale",
})
.to_string(),
@@ -142,6 +146,67 @@ async fn standalone_image_generation_returns_saved_path_hint_to_model() -> Resul
Ok(())
}
#[tokio::test]
async fn standalone_image_edit_uses_attached_model_visible_image() -> Result<()> {
let edit_request = run_image_edit_test(|codex_home| {
let image_path = codex_home.join("attached.png");
std::fs::write(&image_path, TINY_PNG_BYTES)?;
Ok((
json!({
"prompt": "add a red hat",
"referenced_image_paths": [image_path.display().to_string()],
}),
vec![
V2UserInput::Text {
text: "Edit the attached image".to_string(),
text_elements: Vec::new(),
},
V2UserInput::LocalImage {
path: image_path,
detail: None,
},
],
))
})
.await?;
assert_eq!(edit_request["prompt"], "add a red hat");
assert!(
edit_request["images"][0]["image_url"]
.as_str()
.is_some_and(|image_url| image_url.starts_with("data:image/png;base64,"))
);
Ok(())
}
#[tokio::test]
async fn standalone_image_edit_uses_recent_pathless_image() -> Result<()> {
let image_url = "https://example.com/reference.png";
let edit_request = run_image_edit_test(|_| {
Ok((
json!({
"prompt": "add a red hat",
"num_last_images_to_include": 1,
}),
vec![
V2UserInput::Text {
text: "Edit the attached image".to_string(),
text_elements: Vec::new(),
},
V2UserInput::Image {
url: image_url.to_string(),
detail: None,
},
],
))
})
.await?;
assert_eq!(edit_request["prompt"], "add a red hat");
assert_eq!(edit_request["images"][0]["image_url"], image_url);
Ok(())
}
#[tokio::test]
async fn standalone_image_generation_is_exposed_in_code_mode_only() -> Result<()> {
let server = responses::start_mock_server().await;
@@ -202,7 +267,6 @@ async fn standalone_image_generation_is_callable_from_code_mode_only() -> Result
"exec",
r#"
const result = await tools.image_gen__imagegen({
action: "generate",
prompt: "paint a blue whale",
});
generatedImage(result);
@@ -263,6 +327,81 @@ generatedImage(result);
}
async fn start_image_generation_turn(mcp: &mut TestAppServer) -> Result<()> {
start_turn(
mcp,
vec![V2UserInput::Text {
text: "Generate an image".to_string(),
text_elements: Vec::new(),
}],
)
.await
}
async fn run_image_edit_test(
input: impl FnOnce(&Path) -> Result<(serde_json::Value, Vec<V2UserInput>)>,
) -> Result<serde_json::Value> {
let call_id = "image-edit-1";
let server = responses::start_mock_server().await;
mount_image_edit_response(&server).await;
let codex_home = TempDir::new()?;
let (arguments, input) = input(codex_home.path())?;
let response_mock = responses::mount_sse_sequence(
&server,
vec![
responses::sse(vec![
responses::ev_response_created("resp-1"),
responses::ev_function_call_with_namespace(
call_id,
"image_gen",
"imagegen",
&arguments.to_string(),
),
responses::ev_completed("resp-1"),
]),
responses::sse(vec![
responses::ev_assistant_message("msg-1", "Done"),
responses::ev_completed("resp-2"),
]),
],
)
.await;
create_config_toml(codex_home.path(), &server.uri(), ImagegenTestMode::Direct)?;
write_chatgpt_auth(
codex_home.path(),
ChatGptAuthFixture::new("access-chatgpt"),
AuthCredentialsStoreMode::File,
)?;
let mut mcp =
TestAppServer::new_with_env(codex_home.path(), &[("OPENAI_API_KEY", None)]).await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
start_turn(&mut mcp, input).await?;
timeout(
DEFAULT_READ_TIMEOUT,
wait_for_image_generation_completed(&mut mcp),
)
.await??;
timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_notification_message("turn/completed"),
)
.await??;
assert_eq!(response_mock.requests().len(), 2);
let requests = server
.received_requests()
.await
.context("failed to fetch received requests")?;
Ok(requests
.iter()
.find(|request| request.url.path() == "/api/codex/images/edits")
.context("image edit request should be sent")?
.body_json::<serde_json::Value>()?)
}
async fn start_turn(mcp: &mut TestAppServer, input: Vec<V2UserInput>) -> Result<()> {
let thread_req = mcp
.send_thread_start_request(ThreadStartParams::default())
.await?;
@@ -277,10 +416,7 @@ async fn start_image_generation_turn(mcp: &mut TestAppServer) -> Result<()> {
.send_turn_start_request(TurnStartParams {
thread_id: thread.id,
client_user_message_id: None,
input: vec![V2UserInput::Text {
text: "Generate an image".to_string(),
text_elements: Vec::new(),
}],
input,
..Default::default()
})
.await?;
@@ -324,6 +460,18 @@ async fn mount_image_response(server: &MockServer) {
.await;
}
async fn mount_image_edit_response(server: &MockServer) {
Mock::given(method("POST"))
.and(path("/api/codex/images/edits"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"created": 1,
"data": [{"b64_json": RESULT}],
})))
.expect(1)
.mount(server)
.await;
}
fn create_config_toml(
codex_home: &Path,
server_uri: &str,
@@ -12,6 +12,7 @@ mod connection_handling_websocket;
#[cfg(unix)]
mod connection_handling_websocket_unix;
mod dynamic_tools;
mod executor_skills;
mod experimental_api;
mod experimental_feature_list;
mod external_agent_config;
@@ -288,6 +288,59 @@ async fn plugin_install_writes_remote_plugin_to_cloud_and_cache() -> Result<()>
Ok(())
}
#[tokio::test]
async fn plugin_install_uses_remote_apps_needing_auth_response() -> Result<()> {
let codex_home = TempDir::new()?;
let server = MockServer::start().await;
let bundle_url = mount_remote_plugin_bundle(
&server,
/*status_code*/ 200,
remote_plugin_bundle_tar_gz_bytes("linear")?,
)
.await;
configure_remote_plugin_with_apps_test(codex_home.path(), &server)?;
mount_remote_plugin_detail(&server, REMOTE_PLUGIN_ID, "1.2.3", Some(&bundle_url)).await;
mount_empty_remote_installed_plugins(&server).await;
mount_remote_plugin_install_with_apps_needing_auth(&server, REMOTE_PLUGIN_ID, &["alpha"]).await;
let mut mcp = TestAppServer::new_with_env(
codex_home.path(),
&[(TEST_ALLOW_HTTP_REMOTE_PLUGIN_BUNDLE_DOWNLOADS, Some("1"))],
)
.await?;
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
let request_id = send_remote_plugin_install_request(&mut mcp, REMOTE_PLUGIN_ID).await?;
let response: JSONRPCResponse = timeout(
DEFAULT_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(request_id)),
)
.await??;
let response: PluginInstallResponse = to_response(response)?;
assert_eq!(
response,
PluginInstallResponse {
auth_policy: PluginAuthPolicy::OnUse,
apps_needing_auth: vec![AppSummary {
id: "alpha".to_string(),
name: "alpha".to_string(),
description: None,
install_url: Some("https://chatgpt.com/apps/alpha/alpha".to_string()),
needs_auth: true,
}],
}
);
wait_for_remote_plugin_request_count(
&server,
"GET",
"/backend-api/connectors/directory/list",
/*expected_count*/ 0,
)
.await?;
Ok(())
}
#[tokio::test]
async fn plugin_install_rejects_missing_remote_bundle_url() -> Result<()> {
let codex_home = TempDir::new()?;
@@ -1398,6 +1451,34 @@ fn configure_remote_plugin_test(codex_home: &std::path::Path, server: &MockServe
)
}
fn configure_remote_plugin_with_apps_test(
codex_home: &std::path::Path,
server: &MockServer,
) -> Result<()> {
std::fs::write(
codex_home.join("config.toml"),
format!(
r#"
chatgpt_base_url = "{}/backend-api/"
[features]
plugins = true
remote_plugin = true
connectors = true
"#,
server.uri()
),
)?;
write_chatgpt_auth(
codex_home,
ChatGptAuthFixture::new("chatgpt-token")
.account_id("account-123")
.chatgpt_user_id("user-123")
.chatgpt_account_id("account-123"),
AuthCredentialsStoreMode::File,
)
}
async fn mount_remote_plugin_bundle(
server: &MockServer,
status_code: u16,
@@ -1552,6 +1633,27 @@ async fn mount_remote_plugin_install(server: &MockServer, remote_plugin_id: &str
.await;
}
async fn mount_remote_plugin_install_with_apps_needing_auth(
server: &MockServer,
remote_plugin_id: &str,
app_ids_needing_auth: &[&str],
) {
Mock::given(method("POST"))
.and(path(format!(
"/backend-api/ps/plugins/{remote_plugin_id}/install"
)))
.and(query_param("includeAppsNeedingAuth", "true"))
.and(header("authorization", "Bearer chatgpt-token"))
.and(header("chatgpt-account-id", "account-123"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"id": remote_plugin_id,
"enabled": true,
"app_ids_needing_auth": app_ids_needing_auth,
})))
.mount(server)
.await;
}
#[derive(Debug, Clone)]
struct CacheManifestExists {
manifest_path: std::path::PathBuf,
@@ -1863,6 +1863,102 @@ async fn plugin_list_includes_remote_marketplaces_when_remote_plugin_enabled() -
Ok(())
}
#[tokio::test]
async fn plugin_list_uses_cached_global_remote_catalog_and_refreshes_it() -> Result<()> {
let codex_home = TempDir::new()?;
let server = MockServer::start().await;
write_remote_plugin_catalog_config(
codex_home.path(),
&format!("{}/backend-api/", server.uri()),
)?;
write_chatgpt_auth(
codex_home.path(),
ChatGptAuthFixture::new("chatgpt-token")
.account_id("account-123")
.chatgpt_user_id("user-123")
.chatgpt_account_id("account-123"),
AuthCredentialsStoreMode::File,
)?;
let cached_remote_plugin_id = "plugins~Plugin_00000000000000000000000000000000";
let refreshed_remote_plugin_id = "plugins~Plugin_11111111111111111111111111111111";
let cached_body =
remote_plugin_list_body(cached_remote_plugin_id, "linear", "Linear", "Plan work");
let refreshed_body = remote_plugin_list_body(
refreshed_remote_plugin_id,
"notion",
"Notion",
"Capture notes",
);
mount_remote_plugin_list(&server, "GLOBAL", &cached_body).await;
mount_remote_installed_plugins(&server, "GLOBAL", empty_remote_installed_plugins_body()).await;
mount_remote_installed_plugins(&server, "WORKSPACE", empty_remote_installed_plugins_body())
.await;
let mut mcp = TestAppServer::new(codex_home.path()).await?;
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
let request_id = mcp
.send_plugin_list_request(PluginListParams {
cwds: None,
marketplace_kinds: None,
})
.await?;
let response: PluginListResponse = to_response(
timeout(
DEFAULT_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(request_id)),
)
.await??,
)?;
let remote_marketplace = response
.marketplaces
.iter()
.find(|marketplace| marketplace.name == "openai-curated-remote")
.expect("expected warmed remote marketplace");
assert_eq!(
remote_marketplace.plugins[0].id,
"linear@openai-curated-remote"
);
wait_for_remote_plugin_request_count(&server, "/ps/plugins/list", /*expected_count*/ 1).await?;
wait_for_cached_remote_catalog_plugin_ids(codex_home.path(), &[cached_remote_plugin_id])
.await?;
server.reset().await;
mount_remote_plugin_list(&server, "GLOBAL", &refreshed_body).await;
mount_remote_installed_plugins(&server, "GLOBAL", empty_remote_installed_plugins_body()).await;
mount_remote_installed_plugins(&server, "WORKSPACE", empty_remote_installed_plugins_body())
.await;
let request_id = mcp
.send_plugin_list_request(PluginListParams {
cwds: None,
marketplace_kinds: None,
})
.await?;
let response: PluginListResponse = to_response(
timeout(
DEFAULT_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(request_id)),
)
.await??,
)?;
let remote_marketplace = response
.marketplaces
.iter()
.find(|marketplace| marketplace.name == "openai-curated-remote")
.expect("expected cached remote marketplace");
assert_eq!(
remote_marketplace.plugins[0].id,
"linear@openai-curated-remote"
);
wait_for_remote_plugin_request_count(&server, "/ps/plugins/list", /*expected_count*/ 1).await?;
wait_for_cached_remote_catalog_plugin_ids(codex_home.path(), &[refreshed_remote_plugin_id])
.await?;
Ok(())
}
#[tokio::test]
async fn plugin_list_includes_openai_curated_remote_collection_when_requested() -> Result<()> {
let codex_home = TempDir::new()?;
@@ -2275,6 +2371,92 @@ plugin_sharing = true
Ok(())
}
#[tokio::test]
async fn plugin_installed_includes_workspace_directory_without_plugin_sharing() -> Result<()> {
let codex_home = TempDir::new()?;
let server = MockServer::start().await;
std::fs::write(
codex_home.path().join("config.toml"),
format!(
r#"chatgpt_base_url = "{}/backend-api/"
[features]
plugins = true
remote_plugin = false
plugin_sharing = false
"#,
server.uri()
),
)?;
write_chatgpt_auth(
codex_home.path(),
ChatGptAuthFixture::new("chatgpt-token")
.account_id("account-123")
.chatgpt_user_id("user-123")
.chatgpt_account_id("account-123"),
AuthCredentialsStoreMode::File,
)?;
let mut workspace_installed_body: serde_json::Value =
serde_json::from_str(&workspace_remote_plugin_page_body(
"plugins~Plugin_11111111111111111111111111111111",
"workspace-linear",
"Workspace Linear",
"LISTED",
/*enabled*/ Some(true),
))?;
let shared_installed_body: serde_json::Value =
serde_json::from_str(&workspace_remote_plugin_page_body(
"plugins~Plugin_22222222222222222222222222222222",
"shared-linear",
"Shared Linear",
"PRIVATE",
/*enabled*/ Some(true),
))?;
workspace_installed_body["plugins"]
.as_array_mut()
.expect("installed plugins should be an array")
.push(shared_installed_body["plugins"][0].clone());
let workspace_installed_body = serde_json::to_string(&workspace_installed_body)?;
mount_remote_installed_plugins(&server, "GLOBAL", empty_remote_installed_plugins_body()).await;
mount_remote_installed_plugins(&server, "WORKSPACE", &workspace_installed_body).await;
let mut mcp = TestAppServer::new(codex_home.path()).await?;
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
let request_id = mcp
.send_plugin_installed_request(PluginInstalledParams {
cwds: None,
install_suggestion_plugin_names: None,
})
.await?;
let response: JSONRPCResponse = timeout(
DEFAULT_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(request_id)),
)
.await??;
let response: PluginInstalledResponse = to_response(response)?;
assert_eq!(response.marketplaces.len(), 1);
let marketplace = &response.marketplaces[0];
assert_eq!(marketplace.name, "workspace-directory");
assert_eq!(
marketplace
.plugins
.iter()
.map(|plugin| (plugin.id.clone(), plugin.installed, plugin.enabled))
.collect::<Vec<_>>(),
vec![(
"workspace-linear@workspace-directory".to_string(),
true,
true
)]
);
wait_for_remote_installed_scope_request(&server, "WORKSPACE").await?;
wait_for_remote_installed_scope_request(&server, "GLOBAL").await?;
Ok(())
}
#[tokio::test]
async fn plugin_installed_starts_remote_installed_bundle_sync() -> Result<()> {
let codex_home = TempDir::new()?;
@@ -3025,6 +3207,52 @@ async fn wait_for_remote_installed_scope_request(server: &MockServer, scope: &st
Ok(())
}
async fn wait_for_cached_remote_catalog_plugin_ids(
codex_home: &std::path::Path,
expected_plugin_ids: &[&str],
) -> Result<()> {
let mut expected_plugin_ids = expected_plugin_ids
.iter()
.copied()
.map(str::to_string)
.collect::<Vec<_>>();
expected_plugin_ids.sort();
timeout(DEFAULT_TIMEOUT, async {
loop {
let plugin_ids = cached_remote_catalog_plugin_ids(codex_home)?;
if plugin_ids == expected_plugin_ids {
return Ok::<(), anyhow::Error>(());
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await??;
Ok(())
}
fn cached_remote_catalog_plugin_ids(codex_home: &std::path::Path) -> Result<Vec<String>> {
let cache_dir = codex_home.join("cache/remote_plugin_catalog");
if !cache_dir.exists() {
return Ok(Vec::new());
}
let mut plugin_ids = Vec::new();
for entry in std::fs::read_dir(cache_dir)? {
let path = entry?.path();
let cached_catalog: serde_json::Value = serde_json::from_slice(&std::fs::read(path)?)?;
let Some(plugins) = cached_catalog["plugins"].as_array() else {
continue;
};
plugin_ids.extend(
plugins
.iter()
.filter_map(|plugin| plugin["id"].as_str())
.map(str::to_string),
);
}
plugin_ids.sort();
Ok(plugin_ids)
}
async fn wait_for_path_exists(path: &std::path::Path) -> Result<()> {
timeout(DEFAULT_TIMEOUT, async {
loop {
@@ -3063,6 +3291,43 @@ async fn mount_remote_plugin_list(server: &MockServer, scope: &str, body: &str)
.await;
}
fn remote_plugin_list_body(
remote_plugin_id: &str,
plugin_name: &str,
display_name: &str,
short_description: &str,
) -> String {
format!(
r#"{{
"plugins": [
{{
"id": "{remote_plugin_id}",
"name": "{plugin_name}",
"scope": "GLOBAL",
"installation_policy": "AVAILABLE",
"authentication_policy": "ON_USE",
"status": "ENABLED",
"release": {{
"version": "1.2.3",
"display_name": "{display_name}",
"description": "{display_name}",
"app_ids": [],
"interface": {{
"short_description": "{short_description}",
"capabilities": ["Read"]
}},
"skills": []
}}
}}
],
"pagination": {{
"limit": 50,
"next_page_token": null
}}
}}"#
)
}
async fn mount_openai_curated_remote_collection_plugin_list(server: &MockServer, body: &str) {
Mock::given(method("GET"))
.and(path("/backend-api/ps/plugins/list"))
@@ -206,7 +206,7 @@ async fn plugin_uninstall_writes_remote_plugin_to_cloud_when_remote_plugin_enabl
Mock::given(method("POST"))
.and(path(format!(
"/backend-api/plugins/{REMOTE_PLUGIN_ID}/uninstall"
"/backend-api/ps/plugins/{REMOTE_PLUGIN_ID}/uninstall"
)))
.and(header("authorization", "Bearer chatgpt-token"))
.and(header("chatgpt-account-id", "account-123"))
@@ -249,7 +249,7 @@ async fn plugin_uninstall_writes_remote_plugin_to_cloud_when_remote_plugin_enabl
wait_for_remote_plugin_request_count(
&server,
"POST",
&format!("/plugins/{REMOTE_PLUGIN_ID}/uninstall"),
&format!("/ps/plugins/{REMOTE_PLUGIN_ID}/uninstall"),
/*expected_count*/ 1,
)
.await?;
@@ -278,7 +278,7 @@ async fn plugin_uninstall_uses_detail_scope_for_cache_namespace() -> Result<()>
Mock::given(method("POST"))
.and(path(format!(
"/backend-api/plugins/{REMOTE_PLUGIN_ID}/uninstall"
"/backend-api/ps/plugins/{REMOTE_PLUGIN_ID}/uninstall"
)))
.and(header("authorization", "Bearer chatgpt-token"))
.and(header("chatgpt-account-id", "account-123"))
@@ -321,7 +321,7 @@ async fn plugin_uninstall_uses_detail_scope_for_cache_namespace() -> Result<()>
wait_for_remote_plugin_request_count(
&server,
"POST",
&format!("/plugins/{REMOTE_PLUGIN_ID}/uninstall"),
&format!("/ps/plugins/{REMOTE_PLUGIN_ID}/uninstall"),
/*expected_count*/ 1,
)
.await?;
@@ -357,7 +357,7 @@ async fn plugin_uninstall_accepts_workspace_remote_plugin_id_shape() -> Result<(
Mock::given(method("POST"))
.and(path(format!(
"/backend-api/plugins/{WORKSPACE_REMOTE_PLUGIN_ID}/uninstall"
"/backend-api/ps/plugins/{WORKSPACE_REMOTE_PLUGIN_ID}/uninstall"
)))
.and(header("authorization", "Bearer chatgpt-token"))
.and(header("chatgpt-account-id", "account-123"))
@@ -395,7 +395,7 @@ async fn plugin_uninstall_accepts_workspace_remote_plugin_id_shape() -> Result<(
wait_for_remote_plugin_request_count(
&server,
"POST",
&format!("/plugins/{WORKSPACE_REMOTE_PLUGIN_ID}/uninstall"),
&format!("/ps/plugins/{WORKSPACE_REMOTE_PLUGIN_ID}/uninstall"),
/*expected_count*/ 1,
)
.await?;
@@ -451,7 +451,7 @@ async fn plugin_uninstall_rejects_before_post_when_remote_detail_fetch_fails() -
wait_for_remote_plugin_request_count(
&server,
"POST",
&format!("/plugins/{REMOTE_PLUGIN_ID}/uninstall"),
&format!("/ps/plugins/{REMOTE_PLUGIN_ID}/uninstall"),
/*expected_count*/ 0,
)
.await?;
@@ -487,7 +487,7 @@ async fn plugin_uninstall_rejects_remote_plugin_id_with_spaces_before_network_ca
wait_for_remote_plugin_request_count(
&server,
"POST",
"/plugins/sample plugin/uninstall",
"/ps/plugins/sample plugin/uninstall",
/*expected_count*/ 0,
)
.await?;
@@ -522,7 +522,7 @@ async fn plugin_uninstall_rejects_invalid_remote_plugin_id_before_network_call()
wait_for_remote_plugin_request_count(
&server,
"POST",
"/plugins/linear/../../oops/uninstall",
"/ps/plugins/linear/../../oops/uninstall",
/*expected_count*/ 0,
)
.await?;
@@ -29,6 +29,7 @@ use codex_app_server_protocol::RequestId;
use codex_app_server_protocol::ServerNotification;
use codex_app_server_protocol::ThreadListParams;
use codex_app_server_protocol::ThreadListResponse;
use codex_app_server_protocol::ThreadResumeParams;
use codex_app_server_protocol::ThreadStartParams;
use codex_app_server_protocol::ThreadStartResponse;
use codex_app_server_protocol::TurnStartParams;
@@ -37,6 +38,7 @@ use codex_arg0::Arg0DispatchPaths;
use codex_config::CloudConfigBundleLoader;
use codex_config::LoaderOverrides;
use codex_config::NoopThreadConfigLoader;
use codex_core::config::Config;
use codex_core::config::ConfigBuilder;
use codex_exec_server::EnvironmentManager;
use codex_feedback::CodexFeedback;
@@ -183,6 +185,122 @@ async fn thread_start_with_non_local_thread_store_does_not_create_local_persiste
Ok(())
}
#[tokio::test]
async fn cold_thread_resume_reuses_non_local_history_probe() -> Result<()> {
let server = create_mock_responses_server_repeating_assistant("Done").await;
let codex_home = TempDir::new()?;
let store_id = Uuid::new_v4().to_string();
create_config_toml_with_thread_store(codex_home.path(), &server.uri(), &store_id)?;
let loader_overrides = LoaderOverrides::without_managed_config_for_tests();
let config = Arc::new(
ConfigBuilder::default()
.codex_home(codex_home.path().to_path_buf())
.fallback_cwd(Some(codex_home.path().to_path_buf()))
.loader_overrides(loader_overrides.clone())
.build()
.await?,
);
let thread_store = InMemoryThreadStore::for_id(store_id.clone());
let _in_memory_store = InMemoryThreadStoreId { store_id };
let mut client = start_in_process_client(config.clone(), loader_overrides.clone()).await?;
let response = client
.request(ClientRequest::ThreadStart {
request_id: RequestId::Integer(1),
params: ThreadStartParams::default(),
})
.await?
.expect("thread/start should succeed");
let ThreadStartResponse { thread, .. } = serde_json::from_value(response)?;
client
.request(ClientRequest::TurnStart {
request_id: RequestId::Integer(2),
params: TurnStartParams {
thread_id: thread.id.clone(),
client_user_message_id: None,
input: vec![V2UserInput::Text {
text: "Materialize the thread".to_string(),
text_elements: Vec::new(),
}],
..Default::default()
},
})
.await?
.expect("turn/start should succeed");
timeout(DEFAULT_READ_TIMEOUT, async {
loop {
let Some(event) = client.next_event().await else {
anyhow::bail!("in-process app-server stopped before turn/completed");
};
if let InProcessServerEvent::ServerNotification(ServerNotification::TurnCompleted(
completed,
)) = event
&& completed.thread_id == thread.id
{
return Ok::<(), anyhow::Error>(());
}
}
})
.await??;
client.shutdown().await?;
let client = start_in_process_client(config, loader_overrides).await?;
let reads_before_resume = thread_store.calls().await.read_thread_with_history;
// The in-memory store is pathless, so resume currently fails later while
// assembling the response. The history-bearing probe must still be reused.
let _resume_result = client
.request(ClientRequest::ThreadResume {
request_id: RequestId::Integer(3),
params: ThreadResumeParams {
thread_id: thread.id.clone(),
..Default::default()
},
})
.await?;
assert_eq!(
thread_store.calls().await.read_thread_with_history,
reads_before_resume + 1
);
client.shutdown().await?;
Ok(())
}
async fn start_in_process_client(
config: Arc<Config>,
loader_overrides: LoaderOverrides,
) -> std::io::Result<in_process::InProcessClientHandle> {
in_process::start(InProcessStartArgs {
arg0_paths: Arg0DispatchPaths::default(),
config,
cli_overrides: Vec::new(),
loader_overrides,
strict_config: false,
cloud_config_bundle: CloudConfigBundleLoader::default(),
thread_config_loader: Arc::new(NoopThreadConfigLoader),
feedback: CodexFeedback::new(),
log_db: None,
state_db: None,
environment_manager: Arc::new(EnvironmentManager::default_for_tests()),
config_warnings: Vec::new(),
session_source: SessionSource::Cli,
enable_codex_api_key_env: false,
initialize: InitializeParams {
client_info: ClientInfo {
name: "codex-app-server-tests".to_string(),
title: None,
version: "0.1.0".to_string(),
},
capabilities: None,
},
channel_capacity: in_process::DEFAULT_IN_PROCESS_CHANNEL_CAPACITY,
})
.await
}
fn assert_no_local_persistence_artifacts(codex_home: &Path) -> Result<()> {
// These are the observable tripwires for accidental local persistence. If a
// future code path constructs a local rollout/session store or opens the
@@ -793,6 +793,7 @@ async fn skills_changed_notification_is_emitted_after_skill_change() -> Result<(
thread_source: None,
dynamic_tools: None,
environments: None,
selected_capability_roots: None,
mock_experimental_field: None,
experimental_raw_events: false,
})
@@ -1356,6 +1356,7 @@ async fn seed_pathless_store_thread(
store
.create_thread(CreateThreadParams {
thread_id,
extra_config: None,
forked_from_id: None,
parent_thread_id: None,
source: ProtocolSessionSource::Cli,
@@ -209,6 +209,7 @@ async fn thread_unarchive_preserves_pathless_store_metadata() -> Result<()> {
store
.create_thread(CreateThreadParams {
thread_id,
extra_config: None,
forked_from_id: Some(parent_thread_id),
parent_thread_id: None,
source: SessionSource::Cli,
@@ -41,6 +41,7 @@ use codex_app_server_protocol::PatchChangeKind;
use codex_app_server_protocol::RequestId;
use codex_app_server_protocol::ServerRequest;
use codex_app_server_protocol::ServerRequestResolvedNotification;
use codex_app_server_protocol::SubAgentActivityKind;
use codex_app_server_protocol::TextElement;
use codex_app_server_protocol::ThreadItem;
use codex_app_server_protocol::ThreadSource;
@@ -53,6 +54,7 @@ use codex_app_server_protocol::TurnStartParams;
use codex_app_server_protocol::TurnStartResponse;
use codex_app_server_protocol::TurnStartedNotification;
use codex_app_server_protocol::TurnStatus;
use codex_app_server_protocol::TurnSteerParams;
use codex_app_server_protocol::UserInput as V2UserInput;
use codex_app_server_protocol::WarningNotification;
use codex_config::config_toml::ConfigToml;
@@ -3363,6 +3365,134 @@ async fn turn_start_emits_spawn_agent_item_with_model_metadata_v2() -> Result<()
Ok(())
}
#[tokio::test]
async fn direct_input_to_multi_agent_v2_subagent_is_rejected() -> Result<()> {
const CHILD_PROMPT: &str = "child: do work";
const PARENT_PROMPT: &str = "spawn a child and continue";
const SPAWN_CALL_ID: &str = "spawn-call-direct-input-rejection";
const ERROR_MESSAGE: &str =
"direct app-server input is not allowed for multi-agent v2 sub-agents";
let server = responses::start_mock_server().await;
let spawn_args = serde_json::to_string(&json!({
"message": CHILD_PROMPT,
"task_name": "worker",
}))?;
let _parent_turn = responses::mount_sse_once_match(
&server,
|req: &wiremock::Request| body_contains(req, PARENT_PROMPT),
responses::sse(vec![
responses::ev_response_created("resp-parent-1"),
responses::ev_function_call(SPAWN_CALL_ID, "spawn_agent", &spawn_args),
responses::ev_completed("resp-parent-1"),
]),
)
.await;
let codex_home = TempDir::new()?;
create_config_toml(
codex_home.path(),
&server.uri(),
"never",
&BTreeMap::from([(Feature::MultiAgentV2, true)]),
)?;
write_models_cache(codex_home.path())?;
let mut mcp = TestAppServer::new(codex_home.path()).await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??;
let thread_req = mcp
.send_thread_start_request(ThreadStartParams {
model: Some("gpt-5.3-codex".to_string()),
..Default::default()
})
.await?;
let thread_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(thread_req)),
)
.await??;
let ThreadStartResponse { thread, .. } = to_response::<ThreadStartResponse>(thread_resp)?;
let turn_req = mcp
.send_turn_start_request(TurnStartParams {
thread_id: thread.id,
input: vec![V2UserInput::Text {
text: PARENT_PROMPT.to_string(),
text_elements: Vec::new(),
}],
..Default::default()
})
.await?;
let turn_resp: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(turn_req)),
)
.await??;
let _: TurnStartResponse = to_response(turn_resp)?;
let child_thread_id = timeout(DEFAULT_READ_TIMEOUT, async {
loop {
let completed_notif = mcp
.read_stream_until_notification_message("item/completed")
.await?;
let completed: ItemCompletedNotification =
serde_json::from_value(completed_notif.params.expect("item/completed params"))?;
if let ThreadItem::SubAgentActivity {
id,
kind: SubAgentActivityKind::Started,
agent_thread_id,
..
} = completed.item
&& id == SPAWN_CALL_ID
{
return Ok::<String, anyhow::Error>(agent_thread_id);
}
}
})
.await??;
let direct_turn_req = mcp
.send_turn_start_request(TurnStartParams {
thread_id: child_thread_id.clone(),
input: vec![V2UserInput::Text {
text: "direct app-server turn".to_string(),
text_elements: Vec::new(),
}],
..Default::default()
})
.await?;
let direct_turn_error: JSONRPCError = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_error_message(RequestId::Integer(direct_turn_req)),
)
.await??;
assert_eq!(direct_turn_error.error.code, INVALID_REQUEST_ERROR_CODE);
assert_eq!(direct_turn_error.error.message, ERROR_MESSAGE);
let direct_steer_req = mcp
.send_turn_steer_request(TurnSteerParams {
thread_id: child_thread_id,
client_user_message_id: None,
input: vec![V2UserInput::Text {
text: "direct app-server steer".to_string(),
text_elements: Vec::new(),
}],
responsesapi_client_metadata: None,
additional_context: None,
expected_turn_id: "any-active-turn".to_string(),
})
.await?;
let direct_steer_error: JSONRPCError = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_error_message(RequestId::Integer(direct_steer_req)),
)
.await??;
assert_eq!(direct_steer_error.error.code, INVALID_REQUEST_ERROR_CODE);
assert_eq!(direct_steer_error.error.message, ERROR_MESSAGE);
Ok(())
}
#[tokio::test]
async fn turn_start_emits_spawn_agent_item_with_effective_role_model_metadata_v2() -> Result<()> {
skip_if_no_network!(Ok(()));
+1
View File
@@ -14,6 +14,7 @@ use codex_connectors::merge::merge_plugin_connectors;
use codex_core::config::Config;
pub use codex_core::connectors::list_accessible_connectors_from_mcp_tools;
pub use codex_core::connectors::list_accessible_connectors_from_mcp_tools_with_environment_manager;
pub use codex_core::connectors::list_accessible_connectors_from_mcp_tools_with_mcp_manager;
pub use codex_core::connectors::list_accessible_connectors_from_mcp_tools_with_options;
pub use codex_core::connectors::list_accessible_connectors_from_mcp_tools_with_options_and_status;
pub use codex_core::connectors::list_cached_accessible_connectors_from_mcp_tools;
+3
View File
@@ -3,6 +3,9 @@ load("//:defs.bzl", "MACOS_WEBRTC_RUSTC_LINK_FLAGS", "codex_rust_crate", "multip
codex_rust_crate(
name = "cli",
crate_name = "codex_cli",
extra_binaries = [
"//codex-rs/bwrap:bwrap",
],
rustc_flags_extra = MACOS_WEBRTC_RUSTC_LINK_FLAGS,
)
+5 -2
View File
@@ -258,6 +258,9 @@ async fn run_command_under_sandbox(
let network = network_proxy
.as_ref()
.map(codex_core::config::StartedNetworkProxy::proxy);
// Proxy containment depends on whether a proxy is active, not whether its
// policy came from managed requirements.
let enforce_managed_network = network.is_some();
let managed_mitm_ca_trust_bundle_path = match network.as_ref() {
Some(network) => network.managed_mitm_ca_trust_bundle_path(),
None => None,
@@ -278,7 +281,7 @@ async fn run_command_under_sandbox(
file_system_sandbox_policy: &file_system_sandbox_policy,
network_sandbox_policy,
sandbox_policy_cwd: sandbox_policy_cwd.as_path(),
enforce_managed_network: false,
enforce_managed_network,
network: network.as_ref(),
extra_allow_unix_sockets: allow_unix_sockets,
});
@@ -311,7 +314,7 @@ async fn run_command_under_sandbox(
&runtime_permission_profile,
sandbox_policy_cwd.as_path(),
use_legacy_landlock,
allow_network_for_proxy(managed_network_requirements_enabled),
allow_network_for_proxy(enforce_managed_network),
);
spawn_debug_sandbox_child(
codex_linux_sandbox_exe,
+55 -1
View File
@@ -682,7 +682,7 @@ fn structured_json_details(details: &[String]) -> (BTreeMap<String, JsonDetailVa
notes.push(redacted);
continue;
}
let value = value.to_string();
let value = json_detail_value(key, value);
match structured.get_mut(key) {
Some(existing) => existing.push(value),
None => {
@@ -693,6 +693,21 @@ fn structured_json_details(details: &[String]) -> (BTreeMap<String, JsonDetailVa
(structured, notes)
}
fn json_detail_value(key: &str, value: &str) -> String {
if matches!(
key,
"VISUAL" | "EDITOR" | "PAGER" | "GIT_PAGER" | "GH_PAGER" | "LESS"
) && !value.eq_ignore_ascii_case("not set")
{
// Editor and pager configuration can contain arbitrary arguments or
// inline environment assignments. Keep full values local to human output
// because the JSON report may be attached to feedback.
"set".to_string()
} else {
value.to_string()
}
}
fn run_sync_check(
label: &'static str,
progress: Arc<dyn DoctorProgress>,
@@ -3226,6 +3241,18 @@ mod tests {
overall_status: CheckStatus::Warning,
codex_version: "0.0.0".to_string(),
checks: vec![
DoctorCheck::new(
"system.environment",
"system",
CheckStatus::Ok,
"OS language en-US",
)
.detail("VISUAL: code --wait")
.detail("EDITOR: env AWS_ACCESS_KEY_ID=AKIAEXAMPLE vim")
.detail("PAGER: env PRIVATE_PAGER_VALUE=pager-secret less")
.detail("GIT_PAGER: delta")
.detail("GH_PAGER: less")
.detail("LESS: -FRX"),
DoctorCheck::new(
"mcp.config",
"mcp",
@@ -3260,8 +3287,35 @@ mod tests {
assert!(!redacted.contains("user:pass"));
assert!(!redacted.contains("x=abc"));
assert!(!redacted.contains("sk-live-secret"));
assert!(!redacted.contains("AKIAEXAMPLE"));
assert!(!redacted.contains("pager-secret"));
assert!(!redacted.contains("code --wait"));
assert!(redacted.contains("https://example.com/mcp"));
assert_eq!(json["checks"].is_object(), true);
assert_eq!(
json["checks"]["system.environment"]["details"]["VISUAL"],
"set"
);
assert_eq!(
json["checks"]["system.environment"]["details"]["EDITOR"],
"set"
);
assert_eq!(
json["checks"]["system.environment"]["details"]["PAGER"],
"set"
);
assert_eq!(
json["checks"]["system.environment"]["details"]["GIT_PAGER"],
"set"
);
assert_eq!(
json["checks"]["system.environment"]["details"]["GH_PAGER"],
"set"
);
assert_eq!(
json["checks"]["system.environment"]["details"]["LESS"],
"set"
);
assert_eq!(json["checks"]["mcp.config"]["id"], "mcp.config");
assert_eq!(
json["checks"]["mcp.config"]["details"]["OPENAI_API_KEY"],
+13 -1
View File
@@ -1133,7 +1133,13 @@ mod tests {
"OS language en-US",
)
.detail("os: macOS 15.0")
.detail("os language: en-US"),
.detail("os language: en-US")
.detail("VISUAL: code --wait")
.detail("EDITOR: vim")
.detail("PAGER: less -R")
.detail("GIT_PAGER: delta")
.detail("GH_PAGER: less")
.detail("LESS: -FRX"),
DoctorCheck::new(
"runtime.provenance",
"runtime",
@@ -1246,6 +1252,12 @@ Environment
✓ system en-US
os macOS 15.0
OS language en-US
VISUAL code --wait
EDITOR vim
PAGER less -R
GIT_PAGER delta
GH_PAGER less
LESS -FRX
✓ runtime running local build on darwin-arm64
✓ install consistent
managed by npm: no · bun: no · package root —
+12
View File
@@ -62,6 +62,12 @@ fn system_details(parsed: &[ParsedDetail]) -> Vec<HumanDetail> {
push_row_if_present(&mut out, parsed, "LC_ALL", "LC_ALL");
push_row_if_present(&mut out, parsed, "LC_CTYPE", "LC_CTYPE");
push_row_if_present(&mut out, parsed, "LANG", "LANG");
push_row_if_present(&mut out, parsed, "VISUAL", "VISUAL");
push_row_if_present(&mut out, parsed, "EDITOR", "EDITOR");
push_row_if_present(&mut out, parsed, "PAGER", "PAGER");
push_row_if_present(&mut out, parsed, "GIT_PAGER", "GIT_PAGER");
push_row_if_present(&mut out, parsed, "GH_PAGER", "GH_PAGER");
push_row_if_present(&mut out, parsed, "LESS", "LESS");
push_remaining(
&mut out,
parsed,
@@ -73,6 +79,12 @@ fn system_details(parsed: &[ParsedDetail]) -> Vec<HumanDetail> {
"LC_ALL",
"LC_CTYPE",
"LANG",
"VISUAL",
"EDITOR",
"PAGER",
"GIT_PAGER",
"GH_PAGER",
"LESS",
],
&[],
);
@@ -13,6 +13,12 @@ Environment
✓ system en-US
os macOS 15.0
OS language en-US
VISUAL code --wait
EDITOR vim
PAGER less -R
GIT_PAGER delta
GH_PAGER less
LESS -FRX
✓ runtime running local build on darwin-arm64
✓ install consistent
managed by npm: no · bun: no · package root —
+77 -7
View File
@@ -4,6 +4,9 @@ use std::env;
use super::DoctorCheck;
use super::LOCALE_ENV_VARS;
const EDITOR_ENV_VARS: &[&str] = &["VISUAL", "EDITOR"];
const PAGER_ENV_VARS: &[&str] = &["PAGER", "GIT_PAGER", "GH_PAGER", "LESS"];
#[derive(Clone, Debug, Default, Eq, PartialEq)]
struct SystemCheckInputs {
os: String,
@@ -11,6 +14,8 @@ struct SystemCheckInputs {
os_version: String,
os_language: Option<String>,
locale_env: BTreeMap<String, String>,
editor_env: BTreeMap<String, String>,
pager_env: BTreeMap<String, String>,
}
impl SystemCheckInputs {
@@ -24,12 +29,30 @@ impl SystemCheckInputs {
.map(|value| ((*name).to_string(), value))
})
.collect();
let editor_env = EDITOR_ENV_VARS
.iter()
.map(|name| {
let value = env::var_os(name)
.map(|value| value.to_string_lossy().into_owned())
.unwrap_or_else(|| "not set".to_string());
((*name).to_string(), value)
})
.collect();
let pager_env = PAGER_ENV_VARS
.iter()
.filter_map(|name| {
env::var_os(name)
.map(|value| ((*name).to_string(), value.to_string_lossy().into_owned()))
})
.collect();
Self {
os: info.to_string(),
os_type: info.os_type().to_string(),
os_version: info.version().to_string(),
os_language: sys_locale::get_locale(),
locale_env,
editor_env,
pager_env,
}
}
}
@@ -54,6 +77,16 @@ fn system_check_from_inputs(inputs: SystemCheckInputs) -> DoctorCheck {
details.push(format!("{name}: {value}"));
}
}
for name in EDITOR_ENV_VARS {
if let Some(value) = inputs.editor_env.get(*name) {
details.push(format!("{name}: {value}"));
}
}
for name in PAGER_ENV_VARS {
if let Some(value) = inputs.pager_env.get(*name) {
details.push(format!("{name}: {value}"));
}
}
let summary = inputs
.os_language
@@ -76,20 +109,46 @@ mod tests {
use super::*;
#[test]
fn system_check_reports_os_language_and_locale_env() {
fn system_check_reports_os_language_locale_editor_and_pager_env() {
let mut locale_env = BTreeMap::new();
locale_env.insert("LANG".to_string(), "en_US.UTF-8".to_string());
let editor_env = BTreeMap::from([
("EDITOR".to_string(), "vim".to_string()),
("VISUAL".to_string(), "code --wait".to_string()),
]);
let pager_env = BTreeMap::from([
("GH_PAGER".to_string(), "less".to_string()),
("GIT_PAGER".to_string(), "delta".to_string()),
("LESS".to_string(), "-FRX".to_string()),
("PAGER".to_string(), "less -R".to_string()),
]);
let check = system_check_from_inputs(SystemCheckInputs {
os: "macOS 15.0".to_string(),
os_type: "macos".to_string(),
os_version: "15.0".to_string(),
os_language: Some("en-US".to_string()),
locale_env,
editor_env,
pager_env,
});
assert_eq!(check.summary, "OS language en-US");
assert!(check.details.contains(&"os language: en-US".to_string()));
assert!(check.details.contains(&"LANG: en_US.UTF-8".to_string()));
assert_eq!(
check.details,
vec![
"os: macOS 15.0",
"os type: macos",
"os version: 15.0",
"os language: en-US",
"LANG: en_US.UTF-8",
"VISUAL: code --wait",
"EDITOR: vim",
"PAGER: less -R",
"GIT_PAGER: delta",
"GH_PAGER: less",
"LESS: -FRX",
]
);
}
#[test]
@@ -100,13 +159,24 @@ mod tests {
os_version: "unknown".to_string(),
os_language: None,
locale_env: BTreeMap::new(),
editor_env: BTreeMap::from([
("EDITOR".to_string(), "not set".to_string()),
("VISUAL".to_string(), "not set".to_string()),
]),
pager_env: BTreeMap::new(),
});
assert_eq!(check.summary, "OS language unavailable");
assert!(
check
.details
.contains(&"os language: unavailable".to_string())
assert_eq!(
check.details,
vec![
"os: Linux",
"os type: linux",
"os version: unknown",
"os language: unavailable",
"VISUAL: not set",
"EDITOR: not set",
]
);
}
}
+3 -3
View File
@@ -26,7 +26,7 @@ pub use login::run_logout;
#[derive(Debug, Parser)]
pub struct SeatbeltCommand {
/// Named permissions profile to apply from the active configuration stack.
#[arg(long = "permissions-profile", value_name = "NAME")]
#[arg(long = "permissions-profile", short = 'P', value_name = "NAME")]
pub permissions_profile: Option<String>,
/// Layer $CODEX_HOME/<name>.config.toml on top of the base user config.
@@ -74,7 +74,7 @@ fn parse_allow_unix_socket_path(raw: &str) -> Result<AbsolutePathBuf, String> {
#[derive(Debug, Parser)]
pub struct LandlockCommand {
/// Named permissions profile to apply from the active configuration stack.
#[arg(long = "permissions-profile", value_name = "NAME")]
#[arg(long = "permissions-profile", short = 'P', value_name = "NAME")]
pub permissions_profile: Option<String>,
/// Layer $CODEX_HOME/<name>.config.toml on top of the base user config.
@@ -109,7 +109,7 @@ pub struct LandlockCommand {
#[derive(Debug, Parser)]
pub struct WindowsCommand {
/// Named permissions profile to apply from the active configuration stack.
#[arg(long = "permissions-profile", value_name = "NAME")]
#[arg(long = "permissions-profile", short = 'P', value_name = "NAME")]
pub permissions_profile: Option<String>,
/// Layer $CODEX_HOME/<name>.config.toml on top of the base user config.
Loaded 100 of 402 files, more files were not shown because too many files have changed in this diff. Show more