Skip to content

Add Anthropic/Claude providers (including experimental claude-oauth) with mixed-provider agent delegation - #1

Merged
martinthommesen merged 29 commits into
mainfrom
feat/anthropic-claude-support
Oct 20, 2026
Merged

martinthommesen merged 29 commits into
mainfrom
feat/anthropic-claude-support

Conversation

@martinthommesen

@martinthommesen martinthommesen commented Oct 18, 2026 •

Copy link
Copy Markdown
Owner

Summary

Codex model/tool loop
├── anthropic    → Messages API + isolated API key
├── claude-code  → official CLI + local MCP bridge
└── claude-oauth → experimental native OAuth + isolated encrypted credentials

Adds Claude model catalogs and mixed-provider agent delegation while retaining Codex tool execution, approvals, sandboxing, and history. Refactors request construction, credential storage, and Claude Code session lifecycle into smaller modules.

The review loop fixed recoverable OAuth rotation being marked unusable, pre-request failures invalidating credentials, ephemeral logout/refresh races and unwanted lock files, terminal input cancelling a working browser login, unusable credentials appearing connected, and explicit built-in wire-protocol overrides being silently discarded. Regression tests reproduce the affected cases.

Experimental OAuth: claude-oauth emulates undocumented Claude Code compatibility and client identity. It may violate Anthropic's credential/identity policies and carries account and billing risks. It is explicitly selected, never a fallback. Native OAuth live login, inference, and subscription-quota billing remain unverified. See setup and limitations and the compatibility record.

Evidence

  • Before: OAuth regression cases and the conflicting built-in wire-protocol configuration failed.
    After: OAuth tests: 27 passed; full config library: 373 passed.
  • Final provider library runs: API 279 passed, Claude Code 45 passed, provider configuration 38 passed.
  • Final CLI library run: 29 passed. Earlier focused CLI/runtime integration coverage also passed.
  • Formatting and whitespace checks pass. Review of the full merge diff and the fix round found no remaining actionable defects.
  • Tests use local mocks/fake CLI processes. Native OAuth was not exercised against Anthropic.

Local checks used Rust 1.97.1 with the locked dependencies and a 16 MiB test stack. This fork does not run Rust CI on pull requests; the reported results are local.

Merge Danger

Door: two-way

Code can be reverted. Claude credentials are isolated from existing OpenAI authentication. Refreshing a live rotating OAuth grant has account-side effects.

Blast Radius: providers

Changes span provider routing, streaming, credentials, CLI login, model catalogs, and agent delegation. Live native OAuth compatibility remains a material test gap.

Introduce codex-api anthropic module (request/history translation, tool
name mapping, SSE to ResponseEvent translation, error mapping, per-model
thinking/effort rules) and built-in anthropic / claude-code providers with
new wire_api variants.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016LLe9v3bPhB3jpwHdgqwSs
Introduce codex_login::AnthropicAuthConfig, which stores the Anthropic API
key separately from ChatGPT/OpenAI auth so connecting, rotating, or
disconnecting one provider never touches the other:

- file: $CODEX_HOME/anthropic_auth.json ({"version":1,"api_key":...}),
  written atomically with 0600 permissions on unix
- direct keyring: service "Codex Anthropic Auth", account
  "anthropic|<codex home hash>"
- secrets keyring: new LocalSecretsNamespace::AnthropicAuth
  (secrets/anthropic_auth.age) with its own passphrase account
  "secrets|<hash>|anthropic-auth"
- auto: keyring first with file fallback; ephemeral: separate in-memory map

resolve() prefers the stored key over ANTHROPIC_API_KEY and reports the
source. AnthropicCredential and AnthropicAuthConfig Debug output never
include the key, and storage parse errors go through the existing
credential error sanitizer. AuthManager::anthropic_auth_config() exposes
the store for the manager's home and storage settings.

Also teach redact_secrets to redact sk-ant-* keys.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016LLe9v3bPhB3jpwHdgqwSs
New crate codex-claude-code runs the unmodified `claude` CLI in
stream-json mode as a Codex model backend that uses Claude Code's own
sign-in (for example a Claude subscription). Codex never reads Claude
Code credentials; ANTHROPIC_API_KEY/ANTHROPIC_AUTH_TOKEN and Codex/OpenAI
secrets are scrubbed from the child environment.

Claude Code's built-in tools are disabled (--tools "", dontAsk,
--strict-mcp-config, no user settings or hooks) and Codex's tools are
exposed through an MCP bridge on a private Unix socket. Bridged
tools/call requests are parked until Codex has executed the tool through
its own sandbox/approval flow and supplies the output, so tool calls are
returned to Codex as normal FunctionCall/CustomToolCall items.

The session keeps Claude Code's transcript in sync with Codex history
(prefix hash, fresh session seeded with a transcript on rewrites),
persists the session id for --resume across restarts with a seeded
fallback, respawns on model/effort/system prompt changes, and interrupts
(or kills) the process when the consumer drops the stream.

Includes a fake CLI binary and integration tests for auth status, env
scrubbing, tool round trips, live-process reuse, resume, interruption,
history rewrites and failed resume, plus an ignored live test against
the real CLI.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016LLe9v3bPhB3jpwHdgqwSs
…legation

- Route `anthropic_messages` and `claude_code` wire APIs through ModelClientSession,
  with explicit warnings for settings Claude cannot honor.
- Resolve each thread's model catalog from its own provider and let spawn_agent
  pick a connected provider per child (`model_provider`), with plaintext
  collaboration messages whenever a Claude provider is in use.
- Add `codex login|logout|login status --provider anthropic|claude-code|all`,
  keeping each provider's credentials isolated.
- Add end-to-end tests for Anthropic streaming, tools, approvals, apply_patch,
  every parent/child provider combination, and the Claude Code bridge.
- Document setup, model selection, delegation, and known limitations.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016LLe9v3bPhB3jpwHdgqwSs
Copilot AI lite review requested due to automatic review settings October 18, 2026 22:14

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Critical and moderate findings remain unresolved, including MCP authorization, prompt caching, Windows persistence, provider routing, and delegation issues.

9 open issues
What changed in this PR

Adds Anthropic and Claude Code providers, isolated credentials, Claude model catalogs, and mixed-provider agent delegation.

Changes:

  • Adds Anthropic API translation and Claude Code CLI/MCP integration.
  • Adds provider-specific authentication, model routing, and delegation.
  • Adds configuration, documentation, and tests.
  • Requires fixes for reported provider, persistence, authorization, and delegation issues.
File Description
codex-rs/​tui/​src/​status/​card.rs Displays Claude reasoning settings.
codex-rs/​secrets/​src/​sanitizer.rs Redacts Anthropic keys.
codex-rs/​secrets/​src/​local.rs Adds isolated Anthropic secrets storage.
codex-rs/​secrets/​src/​lib.rs Isolates Anthropic keyring accounts.
codex-rs/​model-provider/​src/​provider.rs Routes provider wire APIs.
codex-rs/​model-provider/​src/​lib.rs Exposes provider APIs.
codex-rs/​model-provider/​src/​anthropic/​mod.rs Implements Claude providers.
codex-rs/​model-provider/​src/​anthropic/​mod_tests.rs Tests provider behavior.
codex-rs/​model-provider/​src/​anthropic/​catalog.rs Defines Claude model catalogs.
codex-rs/​model-provider/​src/​anthropic/​catalog_tests.rs Tests catalog metadata.
codex-rs/​model-provider-info/​src/​lib.rs Defines provider metadata.
codex-rs/​login/​src/​lib.rs Exposes authentication support.
codex-rs/​login/​src/​auth/​storage.rs Provides credential storage helpers.
codex-rs/​login/​src/​auth/​storage_error.rs Defines storage errors.
codex-rs/​login/​src/​auth/​mod.rs Registers Anthropic authentication.
codex-rs/​login/​src/​auth/​manager.rs Manages authentication configuration.
codex-rs/​exec/​src/​event_processor_with_human_output.rs Displays Claude settings.
codex-rs/​core/​tests/​suite/​mod.rs Registers integration suites.
codex-rs/​core/​tests/​suite/​claude_code_provider.rs Tests Claude Code integration.
codex-rs/​core/​src/​tools/​spec_plan.rs Configures collaboration tools.
codex-rs/​core/​src/​tools/​multi_agent_tool.rs Handles collaboration schemas.
codex-rs/​core/​src/​tools/​handlers/​multi_agents/​spawn.rs Passes V1 provider overrides.
codex-rs/​core/​src/​tools/​handlers/​multi_agents_v2/​spawn.rs Adds V2 provider-aware spawning.
codex-rs/​core/​src/​tools/​handlers/​multi_agents_v2/​send_message.rs Supports plaintext messages.
codex-rs/​core/​src/​tools/​handlers/​multi_agents_v2/​message_tool.rs Delivers agent messages.
codex-rs/​core/​src/​tools/​handlers/​multi_agents_v2/​followup_task.rs Supports plaintext follow-ups.
codex-rs/​core/​src/​tools/​handlers/​multi_agents_tests.rs Tests collaboration behavior.
codex-rs/​core/​src/​tools/​handlers/​multi_agents_spec.rs Defines delegation schemas.
codex-rs/​core/​src/​tools/​handlers/​multi_agents_spec_tests.rs Tests delegation schemas.
codex-rs/​core/​src/​thread_spawn.rs Carries provider selection.
codex-rs/​core/​src/​thread_manager.rs Resolves provider catalogs.
codex-rs/​core/​src/​session/​session.rs Supplies Claude launch context.
codex-rs/​core/​src/​provider_models.rs Tracks provider catalogs.
codex-rs/​core/​src/​provider_models_tests.rs Tests provider registry behavior.
codex-rs/​core/​src/​lib.rs Exposes provider utilities.
codex-rs/​core/​src/​client.rs Routes provider requests.
codex-rs/​core/​src/​client_claude_code.rs Implements Claude Code transport.
codex-rs/​core/​src/​client_anthropic.rs Implements Anthropic transport.
codex-rs/​core/​src/​agent/​control/​api.rs Resolves child catalogs.
codex-rs/​core/​src/​agent/​child_config.rs Applies child provider overrides.
codex-rs/​core/​src/​agent/​api.rs Extends agent control APIs.
codex-rs/​core/​config.schema.json Documents provider configuration.
codex-rs/​core/​Cargo.toml Adds provider dependencies.
codex-rs/​core/​BUILD.bazel Adds build targets.
codex-rs/​config/​src/​thread_config/​remote.rs Serializes provider settings.
codex-rs/​config/​src/​thread_config/​proto/​codex.thread_config.v1.rs Adds generated wire values.
codex-rs/​config/​src/​thread_config/​proto/​codex.thread_config.v1.proto Defines provider wire values.
codex-rs/​codex-api/​src/​lib.rs Exposes Anthropic API support.
codex-rs/​codex-api/​src/​endpoint/​mod.rs Exposes endpoint support.
codex-rs/​codex-api/​src/​anthropic/​tools_tests.rs Tests tool translation.
codex-rs/​codex-api/​src/​anthropic/​model_traits.rs Defines Claude reasoning rules.
codex-rs/​codex-api/​src/​anthropic/​model_traits_tests.rs Tests reasoning mapping.
codex-rs/​codex-api/​src/​anthropic/​mod.rs Exposes Anthropic modules.
codex-rs/​codex-api/​src/​anthropic/​error.rs Maps Anthropic errors.
codex-rs/​codex-api/​src/​anthropic/​error_tests.rs Tests error mapping.
codex-rs/​codex-api/​src/​anthropic/​client.rs Implements the Anthropic client.
codex-rs/​cli/​src/​main.rs Adds provider CLI options.
codex-rs/​cli/​src/​login.rs Implements login and logout flows.
codex-rs/​cli/​src/​lib.rs Exposes CLI authentication commands.
codex-rs/​cli/​src/​claude_login.rs Manages Claude credentials.
codex-rs/​cli/​src/​claude_login_tests.rs Tests credential management.
codex-rs/​cli/​Cargo.toml Adds CLI dependencies.
codex-rs/​claude-code/​tests/​live.rs Adds live CLI validation.
codex-rs/​claude-code/​tests/​env_scrub.rs Tests environment sanitization.
codex-rs/​claude-code/​tests/​auth.rs Tests authentication status.
codex-rs/​claude-code/​src/​state.rs Persists Claude sessions.
codex-rs/​claude-code/​src/​state_tests.rs Tests session persistence.
codex-rs/​claude-code/​src/​session_tests.rs Tests session handling.
codex-rs/​claude-code/​src/​process.rs Manages Claude processes.
codex-rs/​claude-code/​src/​process_tests.rs Tests process configuration.
codex-rs/​claude-code/​src/​lib.rs Defines the Claude Code backend.
codex-rs/​claude-code/​src/​lib_tests.rs Tests backend helpers.
codex-rs/​claude-code/​src/​history_tests.rs Tests history conversion.
codex-rs/​claude-code/​src/​error.rs Defines Claude Code errors.
codex-rs/​claude-code/​src/​env.rs Scrubs child environments.
codex-rs/​claude-code/​src/​env_tests.rs Tests environment handling.
codex-rs/​claude-code/​src/​auth.rs Reads Claude authentication status.
codex-rs/​claude-code/​src/​auth_tests.rs Tests authentication parsing.
codex-rs/​claude-code/​Cargo.toml Defines crate dependencies.
codex-rs/​claude-code/​BUILD.bazel Adds Bazel metadata.
codex-rs/​Cargo.toml Registers the workspace crate.
codex-rs/​Cargo.lock Locks dependencies.

Review effort: Lite

Comment thread codex-rs/claude-code/src/process.rs Resolved
Comment thread codex-rs/claude-code/src/state.rs Resolved
Comment thread codex-rs/core/src/provider_models.rs Resolved
Comment thread codex-rs/login/src/auth/anthropic.rs Resolved
Comment thread codex-rs/claude-code/src/session.rs Resolved
Comment thread codex-rs/core/src/client_claude_code.rs Resolved
…tion

Anthropic Messages:
- Hold tool calls whose input may be cut off until the stop reason is
  known, and drop them on max_tokens or refusal instead of dispatching
  truncated arguments.
- Flatten top-level anyOf/oneOf/allOf/not in tool input schemas, which
  the Messages API rejects, and report the rewrite.
- Never follow redirects for Messages requests, so x-api-key cannot leak
  to another origin.

Claude Code:
- Scrub the environment for `claude auth login` too.
- Refuse apiKeyHelper-only sign-ins, which sessions cannot load.
- Return forwarded tool calls to Codex whatever the stop reason, and
  answer bridged calls Codex never received after a grace period so a
  turn cannot hang.
- Rebuild the full payload after a session is lost before startup.
- Surface unsupported tools and unapplied reasoning effort as warnings,
  and point sign-in failures at the login commands.

Delegation and auth:
- Keep collaboration messages in plaintext across a tree that includes
  Claude, including resumed children.
- Clear provider-specific sub-agent defaults for cross-provider
  children, reject role models the child's provider does not serve, and
  resume V1 children on their recorded provider.
- Use the configured model catalog and API-key discovery for secondary
  OpenAI catalogs.
- Honor a configured Anthropic env_key in connection and status checks.

Docs: record Anthropic's published policy on subscription credentials,
plan API credits, billing and bare-mode caveats, and correct statements
the review found inaccurate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016LLe9v3bPhB3jpwHdgqwSs
Copilot AI lite review requested due to automatic review settings October 19, 2026 00:30

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment thread codex-rs/model-provider-info/src/lib.rs Resolved
Comment thread codex-rs/core/src/provider_models.rs Resolved
- Default a custom anthropic_messages provider without base_url to
  https://api.anthropic.com/v1 instead of the OpenAI API, so an
  Anthropic key is never sent to OpenAI.
- Refuse realtime conversations on Claude providers. Realtime uses
  OpenAI's protocol and credentials and would otherwise send the
  OpenAI key to the Claude endpoint.
- Say what provider_connection checks: presence of credentials, or the
  Claude Code marker, not their validity.
- Document the base_url default, the logged-out Claude Code sub-agent
  case, the realtime limitation, and the one live Claude Code test run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016LLe9v3bPhB3jpwHdgqwSs
Copilot AI lite review requested due to automatic review settings October 19, 2026 01:29

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment thread codex-rs/claude-code/src/bridge.rs Resolved
…accepting

- A declaration whose wire name collides with an earlier one (for
  example a top-level `alpha__beta` and namespace `alpha` with `beta`)
  no longer overwrites the earlier tool's routing target, so a call to
  the advertised name always reaches the tool whose schema Claude saw.
- The Claude Code tool bridge keeps accepting after an accept error,
  as the app-server control socket does, instead of stopping for the
  rest of the session. Document why it relies on the private socket
  directory rather than a Windows peer check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016LLe9v3bPhB3jpwHdgqwSs
Copilot AI lite review requested due to automatic review settings October 19, 2026 02:12

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Critical authentication and Claude Code memory-context issues remain unresolved.

2 open issues
1 previously missed issue

In code that hasn't changed since last review

Low severity Claude Code provider incorrectly fails HTTP auth prewarm

codex-rs/​model-provider/​src/​anthropic/​mod.rs:274

ClaudeCodeModelProvider::api_provider always returns an error, but every non-WebSocket session runs ModelClient::prewarm_auth() during startup (core/src/session/startup_prewarm.rs:244-252), which calls this method. As a result, opening any Claude Code thread logs startup auth prewarm failed even though the provider is correctly configured and does not use HTTP; skip the HTTP auth prewarm for WireApi::ClaudeCode (or make the prewarm path provider-aware) so this expected path is not reported as a startup failure.

2 resolved since last review

Review effort: Lite

Comment thread codex-rs/cli/src/claude_login.rs Resolved
Comment thread codex-rs/core/src/client_claude_code.rs Resolved
…aude-code

- `codex login --provider anthropic --with-api-key` still stores the key
  when model_providers.anthropic.env_key is set, but now says that the
  `anthropic` provider sends that variable instead, and whether it is
  set, matching `codex login status`.
- Skip memory extraction and consolidation on claude-code sessions.
  Stage one could not launch Claude Code from its detached client, and
  launching it there would share the live session's Claude Code state,
  could not return the strict JSON stage one needs, and would spend the
  user's Claude plan in the background.
- Skip the startup HTTP auth prewarm on claude-code, which has no HTTP
  endpoint and logged a spurious warning on every session start.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016LLe9v3bPhB3jpwHdgqwSs
Copilot AI lite review requested due to automatic review settings October 19, 2026 03:16

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The critical Claude catalog issue and moderate turn-cost retry loop remain unresolved; the 401 guidance nit also needs correction.

1 open issue
2 resolved since last review

Review effort: Lite

- Claude providers always serve the bundled Claude catalog. A
  configured model_catalog_json (OpenAI-shaped) replaced it for a root
  Claude thread, so a thread with no model picked a GPT default and
  every turn failed, while Claude sub-agents already ignored it.
- The Anthropic 401 message and the spawn remedy now name commands
  that work: `codex login --provider anthropic --with-api-key` for any
  anthropic_messages provider id, `codex login status` to see which key
  is sent, and that a stored key takes precedence over
  ANTHROPIC_API_KEY.
- The turn-cost worker no longer starts for Claude providers, which
  have no turn-cost endpoint: it retried forever on claude-code and
  resent the Anthropic key every poll after a 401.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016LLe9v3bPhB3jpwHdgqwSs
Copilot AI lite review requested due to automatic review settings October 19, 2026 04:12

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unresolved critical collaboration-state issues and moderate provider-routing and status issues block approval.

2 open issues
1 resolved since last review

Review effort: Lite

Comment thread codex-rs/core/src/provider_models.rs Resolved
Comment thread codex-rs/core/src/tools/spec_plan.rs Resolved
The plaintext decision was recomputed on every step from the providers
connected at that moment, and only children were marked. An OpenAI root
with a live Claude child therefore went back to encrypted send_message
and followup_task arguments once Claude was disconnected (for example
`codex logout --provider claude-code`, which leaves the CLI and the
child running), or on a resume without the key, and the child received
unreadable ciphertext.

- A tree-wide bit on the shared LocalAgentRuntime is set whenever a
  spawn makes the tree mixed (another provider, or a Claude parent), and
  every agent's tool plan reads it, so the root, siblings and
  grandchildren all stay on plaintext.
- On resume it is re-derived from each descendant's persisted provider.
- spawn_agent on another configured provider while messages are still
  encrypted switches the tree to plaintext and asks the model to resend,
  so the child's first task is readable.

OpenAI-only trees never set the bit and keep encrypted arguments.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016LLe9v3bPhB3jpwHdgqwSs
Copilot AI lite review requested due to automatic review settings October 19, 2026 05:08

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

One or more issues must be addressed before approval.

1 open issue
2 resolved since last review

Review effort: Lite

Comment thread codex-rs/claude-code/src/session.rs Resolved
claude and others added 4 commits October 19, 2026 05:42
When writing a user message to Claude Code's stdin failed, the session
only logged it, marked a query in flight, and still advanced the sync
cursor. After the process exited, the next request resumed from that
cursor and never sent the message again. The cursor now advances only
once the input was delivered, for the incremental, fresh and fallback
paths, so the next request replays it. Tool results for a process that
has already exited are no longer handed to the bridge; the next request
replays them to the replacement process.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016LLe9v3bPhB3jpwHdgqwSs
Add isolated PKCE authentication, encrypted credential storage and refresh, source-derived request signing and tool aliases, and normal Codex provider/CLI integration. Reuse the Anthropic stream and existing agent/tool runtime without API-key, Claude Code, or proxy fallback.

Reference CLIProxyAPI commit: 2422c6b0f5fe16495320fa29456493874c1977a0. Live authentication and subscription billing remain unverified.
@martinthommesen

Copy link
Copy Markdown
Owner Author

Full review: Anthropic/Claude providers with mixed-provider delegation

Pre-merge verdict: this PR is not ready as described. ~13.6k lines of new production code across 140 files was reviewed end-to-end at the pinned toolchain (Rust 1.95.0), plus all four subarea deep-dives. The engineering quality is unusually high and most of the PR is worth merging — but the final three commits ship a feature the PR description explicitly promises is absent, and there are four High-severity items to fix. Findings below are grouped by severity; file:line references are against the current head (57effb5).

Verification run in this environment:

  • cargo check on the seven touched crates — clean.
  • cargo test -p codex-api -p codex-claude-code -p codex-login -p codex-secrets -p codex-model-provider — 742 passed, 0 failed, the 2 live tests correctly #[ignore]-gated.
  • cargo test -p codex-core --test all -- anthropic_provider claude_code_provider — 16/16 pass but only with a raised stack size (see High fix: update package-lock.json name to codex openai/codex#4).
  • cargo clippy on all seven crates — clean.
  • Anthropic's live compliance page re-read in full; both compliant paths check out as described.
  • Release workflows build only codex, codex-code-mode-host, codex-responses-api-proxy, codex-app-server — the test-only codex-claude-code-fake binary is not shipped.

1. Blocking: the last three commits are not in the PR description (Critical, process/policy)

Commits 1–13 match the description exactly: two providers — anthropic (API key) and claude-code (delegates to the unmodified claude CLI) — both of which are legitimate under Anthropic's published policy, re-read in full today: third parties "should use API key authentication", and Anthropic explicitly permits "an end user to sign in to the unmodified Claude Code binary with their own Claude subscription". The description's "never" claims are accurate for exactly these two providers.

Then 00aae9d, 61b8319, 57effb5 add a third provider, claude-oauth, which does precisely what the description says Codex will never do:

"Codex never reads, stores or forwards Claude subscription credentials, and never calls Anthropic endpoints with them. Anthropic's legal and compliance page does not permit third-party developers to do that."

claude-oauth performs its own PKCE login using Claude Code's real OAuth client ID (9d1c250a-e61b-44d9-88ed-5944d1962f5e, redirect port 54545, user:sessions:claude_code scope) and stores/routes subscription tokens against plan limits. That falls inside the actual policy's prohibited list — third parties "may not collect, store, or intermediate Claude.ai credentials or session tokens" and "may not route requests through Free, Pro, or Max plan credentials on behalf of their users" — and docs/claude-oauth-compatibility.md says so itself ("may violate Anthropic's published third-party authentication/identity restrictions"), as does the login warning. The docs are honest; the PR description was never amended.

On top of that, the transport (codex-api/src/anthropic/oauth.rs) emulates the official client to pass server-side checks:

  • user-agent: claude-cli/2.1.280 (external, cli), x-app: cli, fabricated x-stainless-* Node-SDK headers claiming macOS/arm64/Node v26.3.0 from a Rust process;
  • the literal system string "You are Claude Code, Anthropic's official CLI for Claude.";
  • an emulated x-anthropic-billing-header whose fingerprint samples characters of the user's first message;
  • a reverse-engineered CCH body checksum (XXH64 over byte-preserved JSON, oauth/signing.rs, adapted from CLIProxyAPI under MIT with NOTICE attributed);
  • tool declarations renamed into fake MCP aliases (mcp__<word>__<word>_suffix, HMAC-derived from device id).

Whatever the user value, this is identity-emulation to defeat provider-side client identification — the exact category Anthropic's guidance prohibits — and the PR description, title, and "changes by area" summary do not mention it. Anyone triaging or consuming this PR from the description would wrongly conclude no subscription-credential path exists.

Required: either drop claude-oauth, or rewrite the PR description to lead with the three providers, put the policy risk where the description's "never" claims are, and make the impersonation client_id/headers/CCH usage findable in the summary that carries it.


2. High severity (fix before merge)

H1. The documented built-in overrides are rejected — docs example cannot load. docs/claude.md:284-293 shows a nameless [model_providers.anthropic] block, but config/src/config_toml.rs:955-990 runs at deserialization (before the built-in merge in core/src/config/mod.rs:3958) and allows empty names only for bedrock and claude-oauth, so the example fails with "model_providers.anthropic: provider name must not be empty" and the purpose-built validate_claude_override() partial-merge path (model-provider-info/src/lib.rs:975-1012) can never run. Same for [model_providers.claude-code]. Fix: special-case both ids like claude-oauth, or add name = "…" to the docs; add the missing test for that path.

H2. A padded model_provider id silently delivers an encrypted task to a Claude child. core/src/tools/handlers/multi_agents_v2/spawn.rs:119 compares the raw args.model_provider against the provider map, while core/src/agent/child_config.rs:328-334 trims before normalizing. With " anthropic" (or a padded custom claude gateway id), contains_key fails → the resend guard is skipped → the spawn proceeds and delivers AgentMessage::Encrypted to an Anthropic child, whose task text becomes the "could not be decrypted" placeholder — the exact case the guard exists to prevent. Fix: shared normalize (trim + empty-filter) in the guard, and add the missing resend-path test (the needs a plaintext message error string appears nowhere in the suite).

H3. The bridge accepts any same-user peer; tool-result theft and turn-stall are possible. claude-code/src/bridge.rs:176-199, 355-364, 517-532. Tool execution injection is genuinely impossible (arguments are never read; FunctionCalls originate only in the CLI's stdout) — but the socket path is CLI-visible via the relay's argv, the socket file is world-writable, and directory 0700 does not stop same-user peers. A squatter can park an id-less tools/call with a known mcp_name and receive Codex's real tool result via the name-based fallback, or consume a prepared answer so the real id-tagged call parks with no answer and the turn hangs until user interrupt. A peer can also grow line/parked unboundedly. Fix: peercreds/descendant check on accept (the absent-Windows-peer-check comment does not address the Unix gap), 0600 socket, line-cap + bounded parked/prepared queues.

H4. openai_child_of_a_claude_parent_keeps_plaintext_messages aborts the whole test binary at default stack size. Verified deterministically in isolation: default 2 MiB stack → thread overflow + SIGABRT of the entire all target; passes from 4 MiB up (bisected). The repo convention is 8 MiB (run_test_with_large_stack, CI RUST_MIN_STACK) with production threads at 16 MiB (async-utils::THREAD_STACK_SIZE_BYTES), so this is test hygiene, not a production crash — but a plain cargo test -p codex-core aborts with no results. Wrap it in run_test_with_large_stack, and consider why this flow needs >2 MiB even in tests.


3. Medium severity

  1. ensure_v2_agent_loaded doesn't clear parent tuning when reloading a child onto its stored provider (spawn.rs:474-488): inherits OpenAI model_context_window/auto_compact_token_limit/model_verbosity onto a Claude child → wrong compaction thresholds + spurious warning; inconsistent with resume_single_agent_from_rollout (:1475-1481). One shared "switch child to provider" helper for all three call sites.
  2. Empty thinking signatures are only rescued by a full streamed retry (codex-api/src/anthropic/request.rs:330-357, stream.rs:317-341): interrupted turns replay "signature": "" → 400 → burn a request → silently degrade the conversation to no-thinking replay. Mark "signature missing" at capture time and skip/note at build time.
  3. block_binding under adaptive thinking risks first-turn hard failing (request.rs:145-166) if the first-party adaptive shape rejects the beta field (conflicting evidence, opencode#46729 pattern); only drop_block is offered from turn one and input_transformations.thinking_dropped is never parsed/telemetered — a session that silently lost all thinking replay shows nothing. Reorder: offer drop_block only after an actual signature rejection, and surface input transformations.
  4. pause_turn continuation appends a synthetic user "Continue." turn (request.rs:722-730), conflicting with the documented as-is assistant-content resume; reachable via claude-code/OAuth even if not via the API-key path.
  5. AnthropicApiKeyAuth::add_auth_headers silently drops an invalid header value (codex-api/src/anthropic/client.rs:60-65) — a control-char key from ANTHROPIC_API_KEY proceeds unauthenticated → confusing 401. Validate at construction and fail loudly.
  6. Any custom anthropic_messages provider sends the shared Anthropic key to its own base URL unless it sets env_key (model-provider/src/anthropic/mod.rs:98-131); document this loudly and note redirects are refused for these providers too.
  7. claude auth status child leak on timeout (claude-code/src/auth.rs:126-128): wait_with_output() dropped without kill_on_drop(true) (every other spawn has it).
  8. A failed spawn permanently flips the tree to plaintext (spawn.rs:124-127 marks before validation; child_config.rs:124-131 marks before the child thread starts) — encryption becomes unrecoverable after one bad attempt, deviating from the documented invariant (conservative direction, but document it or mark only on success).
  9. Doc corrections: the "exact files" manifest in claude-oauth-compatibility.md lists 65 of the PR's 140 files (the whole claude-code crate is missing from it); note the auto store mode can fall back to plaintext anthropic_auth.json (contrast with claude-oauth's "no plaintext fallback"); claude-code also supports third-party sign-ins (Bedrock/Vertex), so the billing cell should say "whatever the credential's provider charges"; claude-oauth refresh can brick to re-login after one transient network failure (claude_oauth.rs:471-475) — a deliberate tradeoff, worth a doc sentence.

4. Lower severity

  • Unknown stop reasons and partial max_tokens truncation complete the turn with only tracing::debug (stream.rs:599-603, :559-571) — surface as a note; reused content_block_start index silently invalidates the open block (stream.rs:369).
  • strict: true tool declarations are dropped silently; Anthropic supports strict tools (tools.rs:180-186).
  • Provider http_headers entries like anthropic-version/anthropic-beta append alongside the canonical value (HeaderMap::extend appends — verified in http-1.4.0) — insert the canonical headers instead.
  • HTTP 408 mapped as terminal (error.rs:102-105); legacy claude-3* traits request more max_tokens than those models accept (model_traits.rs:93-101); unknown non-modern slugs default to adaptive instead of budgeted thinking.
  • Data-URL parsing misses ;base64, variants and case-folding (request.rs:533-552).
  • Cross-provider spawn: failed-catalog fallback silently substitutes the parent's catalog (child_config.rs:302-317); the no-requested-model path can propagate an empty slug when a custom provider's offline catalog is empty (:348-373).
  • logout --provider all aborts on the first failure instead of aggregating (cli/src/login.rs:625-637); non-sk-ant- keys warn-but-store on the Anthropic side vs hard-block on the OpenAI side (claude_login.rs:52-57) — make symmetric; status --provider all prints providers in a different order than default status and its exit-code semantics are undocumented; the claude-oauth turn-cost-worker gate lacks a test; the --provider all login error branch has no test.
  • [model_providers.anthropic] wire_api = "responses" parses/merges and silently keeps speaking Anthropic (model-provider-info/src/lib.rs:341-352 excludes name/wire_api from the unsupported-fields check; the merge never copies them) — warn or error on a differing restate.
  • Bridge: error_tool_result strings interpolate unbounded lengths of mcp_name into model-visible text (bridge.rs:44, 350-353); stale prepared answers live until the next respawn (TTL).

5. What is solid (the majority of the PR)

Credential isolation — exceptional, and test-substantiated. The Anthropic key lives in its own file (atomic tmp+rename, explicit 0600 pinning after umask), its own direct keyring service/account, its own encrypted .age namespace with its own passphrase account, and its own ephemeral map; auth.json cannot receive Anthropic keys (byte-equality tests run any direction); redact_secrets covers sk-ant- shapes including JSON/log/env forms; every Debug impl is redacted; storage parse errors are sanitized. The claude-oauth store is stronger still: no plaintext fallback, rotating-refresh persisted before send, cross-process lock + reload after both locks, constant-time-ish state compare, bounded and UTF-8-validated manual callback input, dedicated lock file 0600/0700.

Key egress, verified from several angles. Redirects are hard-disabled on the Messages transport at every construction site (ClientRedirectPolicy::Reject → reqwest::redirect::Policy::none(), http-client/src/client_builder.rs:376-377; the route-aware pool honors the builder flag, route_aware_client_pool.rs:498-508,548-556) — and a regression test covers it. OAuth bearers are triple-pinned to https://api.anthropic.com/v1/messages?beta=true (provider apply_auth + client-level URL check + request-destination validation), the token is set_sensitive, and OAuth telemetry is type-whitelisted so an upstream echo can't leak tokens into logs.

The two mainstream providers are exactly Anthropic's permitted paths. API-key direct Messages is the documented third-party route; claude-code runs the unmodified binary with the user's own sign-in, Codex reads no CLI credentials, scrubbed env from live env at every spawn (including claude auth login), built-in CLI tools disabled, and all tool execution stays under Codex's own sandbox/approvals.

Wire translation quality. FNV-stable name truncation with first-wins collision handling (30eec7e fixed a real wire-name collapse); held tool-call buffering for max_tokens/refusal so truncated arguments are dropped, never dispatched; turn repair guarantees every tool_use in history is answered (the API's hard requirement); faithful thinking round-trip with signature-prefix persistence and is_anthropic_reasoning_item keeping Anthropic thinking out of Responses requests; correct cumulative usage/cache semantics; freeform apply_patch bridging; bounded retry machinery for stream errors. Zero unwrap/expect/panic! in the ~13.6k added production lines (all 21 occurrences are in #[cfg(test)] blocks — verified by grep).

Core integration. OAuth continuity is sequence-generational keyed on account+device with stale-commit protection and drop-safe consumption; warnings dedupe per session and render as real events; unsupported tools warn instead of silently dropping (fixed per the Copilot thread); realtime is refused on Claude wires; the catalog is provider-scoped and immune to model_catalog_json contamination (b7898e8); prewarm_auth/turn-cost worker/websockets/remote compaction are all correctly gated off Claude providers; spawn validates unconnected providers, clears provider-specific sub-agent defaults, and rejects role models the child's provider doesn't serve — exercised by real four-way parent/child provider matrix tests over mock HTTP.

Honest docs where it counts. docs/claude.md quotes Anthropic's policy accurately, discloses the plan-credit billing caveat and the --bare future risk, and docs/claude-oauth-compatibility.md is a candid compatibility record (which makes its stale file manifest stand out).

Rebuttals that verified: both Windows fs::rename claims are correctly refuted (MOVEFILE_REPLACE_EXISTING); mcp__server wildcard permission matching checked against the real CLI; the V1-encryption claim correctly doesn't reproduce (V1 schemas are string-typed throughout).


6. Test gaps worth closing

  1. The resend path has no test at all (H2 would be caught by one).
  2. No e2e assertion that a Claude child's /v1/messages request contains the delivered plaintext content (current tests inspect schemas and tool declarations, not content).
  3. Bridge squatting/overflow cases (H3), and an interrupt test where the CLI continues after settling (the fake exits — the real CLI doesn't).
  4. Recorded-live test for the API-key path (auth headers against a recording proxy) — the claude-code live test exists, the API-key path is fully mock-covered.
  5. Both new suites are skip-gated (network / fake binary), and this fork's CI never runs RUST_MIN_STACK=8388608 — in fact, no Rust CI ran for this PR at all (the Actions API shows only Copilot-review and Socket scans on the branch). Enabling the existing rust-ci.yml template would make the next round machine-verifiable.

7. Bottom line

  • Merge-blocker: item §1 — the PR description and its "never" claims must be brought in sync with the three shipped providers before anything else; as written they describe a different PR than the one under review.
  • Policy decision on record: claude-oauth should ship as its own, clearly-scoped proposal (behind its own description, benchmarks, and risk/redline discussion), separate from the two fully-policy-compliant providers — which stand on their own merits and are close to mergeable.
  • After H1–H4 and the mediums, this is an easy approve: the credential store, isolation work, and two-provider translation are high-quality, and the review history (Copilot's five rounds of findings, each either fixed or correctly rebutted) shows the branch can absorb and verify fixes quickly.

@martinthommesen

Copy link
Copy Markdown
Owner Author

Comprehensive Technical Review of PR #1 (feat/anthropic-claude-support)

Reviewed 57effb5a32bd8685f14106973f5741639191d8c9 against main (8c076942cb1da97befefac62fa2acfd08dc0ffe8) across all 15 commits and 140 changed files.

Executive Summary

What is well-designed:

  • Credential & Endpoint Isolation: Outbound claude-oauth requests pin the target URL to POST https://api.anthropic.com:443/v1/messages?beta=true before attaching bearer headers (codex-rs/codex-api/src/anthropic/client.rs:142-172, codex-rs/model-provider/src/anthropic/oauth.rs:165-210). Secret redaction covers sk-ant-* keys (codex-rs/secrets/src/sanitizer.rs).
  • claude-code Process Hardening: Spawns claude with --tools "", --strict-mcp-config, --setting-sources "", disableAllHooks: true, scrubbed environment variables (codex-rs/claude-code/src/env.rs), and a < 100-byte Unix socket path guard (codex-rs/claude-code/src/bridge.rs:43).

What needs attention before merge (3 High, 7 Medium/Medium-High, 1 Low-Medium findings):
There are several correctness, state-machine, and configuration issues that can cause silent turn truncation on max_tokens, broken config.toml deserialization for documented [model_providers.anthropic] overrides, permanently dropped prompts/tool outputs on claude-code retries/errors, and bricked claude-oauth credentials.


Detailed Findings (Ordered by Severity)

1. [HIGH] AnthropicStreamState Silently Completes Truncated max_tokens Responses, Drops Completed Zero-Arg Tool Calls, and Eagerly Executes Earlier Tool Calls Before stop_reason Is Known

  • Locations:
    • codex-rs/codex-api/src/anthropic/stream.rs:248-295 (handle)
    • codex-rs/codex-api/src/anthropic/stream.rs:413-495 (stop_block, release_held_tool_calls)
    • codex-rs/codex-api/src/anthropic/stream.rs:552-611 (completion)
  • Problem:
    1. Silent truncation when any text precedes a cut-off tool_use block (or when text itself hits max_tokens):
      • When block 0 is a text block ("I'll edit the file now...") and block 1 is a tool_use block whose JSON arguments are cut off by max_tokens:
        • stop_block for block 0 sets self.produced_output = true (line 419) and stores self.pending_text.
        • ContentBlockStart for block 1 (lines 248-255) flushes self.pending_text as MessagePhase::Commentary.
        • stop_block for block 1 (lines 454-470) sees unparseable input_json and pushes the call to self.held_tool_calls.
        • MessageDelta receives stop_reason = Some("max_tokens"), and release_held_tool_calls (lines 480-490) drops self.held_tool_calls.
        • MessageStop calls self.completion() (lines 559-571):
          Some("max_tokens") => {
              if !self.produced_output {
                  return Err(ApiError::ResponseIncomplete(Box::new(
                      ResponseIncompleteError {
                          reason: "max_tokens".to_string(),
                          response_id: self.message_id.clone(),
                          token_usage,
                      },
                  )));
              }
              warn!("Anthropic response stopped at max_tokens; output may be truncated");
              None
          }
        • Because self.produced_output was set to true by the text block, completion() returns Ok(ResponseEvent::Completed { end_turn: None, .. }) instead of Err(ApiError::ResponseIncomplete). Since the truncated tool call was dropped, Codex sees no tool calls in the turn and ends the turn normally with only the Commentary message.
    2. Valid zero-argument tool calls are held and dropped if a later block hits max_tokens:
      • In stop_block (lines 448-453), any tool call with input_json.trim().is_empty() (which happens whenever a tool takes {} / no arguments and Anthropic streams no input_json_delta) is placed in self.held_tool_calls instead of being emitted, and is then discarded by release_held_tool_calls if a subsequent block in the same message hits max_tokens.
    3. Eager tool execution before stop_reason arrives:
  • Suggested Fix:
    • Hold all tool_use blocks until MessageDelta provides stop_reason.
    • If stop_reason == Some("max_tokens") and any tool_use block was cut off (or if max_tokens should match OpenAI's ResponseIncomplete semantics in codex-api/src/sse/responses.rs), return Err(ApiError::ResponseIncomplete(...)) rather than silently dropping tool calls and completing the turn.

2. [HIGH] Partial [model_providers.anthropic] and [model_providers.claude-code] Overrides Fail config.toml Deserialization and Managed Requirements Checks

  • Locations:
    • codex-rs/config/src/config_toml.rs:955-991 (validate_model_providers)
    • codex-rs/app-server/src/config_manager.rs:284-341 (ConfigManager::check_thread_model_provider)
    • codex-rs/model-provider-info/src/lib.rs:345-368, 974-1015 (validate_claude_override, merge_configured_model_providers)
    • docs/claude.md:286-293
  • Problem:
    • merge_configured_model_providers and docs/claude.md:286-293 allow users to write partial overrides in config.toml without restating name:
      [model_providers.anthropic]
      base_url = "https://gateway.example.com/anthropic"
      http_headers = { "X-Gateway-Tenant" = "eng" }
    • However, validate_model_providers (config_toml.rs:955-991) runs during ConfigToml deserialization before merge_configured_model_providers and only exempts Bedrock and CLAUDE_OAUTH_PROVIDER_ID:
      if matches!(
          key.as_str(),
          AMAZON_BEDROCK_PROVIDER_ID | AMAZON_BEDROCK_RUNTIME_PROVIDER_ID
      ) {
          provider
              .validate_bedrock_override()
              .map_err(|message| format!("model_providers.{key} {message}"))?;
      } else if key == CLAUDE_OAUTH_PROVIDER_ID {
          provider
              .validate_claude_oauth_override()
              .map_err(|message| format!("model_providers.{key} {message}"))?;
      } else {
          // ...
          if provider.name.trim().is_empty() {
              return Err(format!(
                  "model_providers.{key}: provider name must not be empty"
              ));
          }
      }
    • Similarly, ConfigManager::check_thread_model_provider (config_manager.rs:312-328) only merges partial requirements.toml overrides against built-in providers for AMAZON_BEDROCK_PROVIDER_ID | AMAZON_BEDROCK_RUNTIME_PROVIDER_ID | CLAUDE_OAUTH_PROVIDER_ID, leaving ANTHROPIC_PROVIDER_ID and CLAUDE_CODE_PROVIDER_ID unmerged so definition_changed (line 331) falsely fails with ModelProviderRequirementsChanged.
  • Suggested Fix:
    • Handle ANTHROPIC_PROVIDER_ID | CLAUDE_CODE_PROVIDER_ID in validate_model_providers (calling provider.validate_claude_override() and checking CLAUDE_CODE_PROVIDER_ID's base_url/env_key restriction) and include both IDs in ConfigManager::check_thread_model_provider.

3. [HIGH] codex-claude-code Advances synced_len/prefix_hash Before Turn Completion, Persists Them on Error Results, and Fails Turns When settle_query Kills an Unresponsive Process

  • Locations:
    • codex-rs/claude-code/src/session.rs:236-285 (ClaudeCodeSession::stream)
    • codex-rs/claude-code/src/session.rs:402-557 (deliver_input, send_incremental, settle_query, forget_unstarted_session)
    • codex-rs/claude-code/src/session.rs:761-774 (Driver::on_line)
    • codex-rs/claude-code/src/session.rs:911-981 (Driver::on_result, Driver::on_exit)
  • Problem:
    1. Premature cursor advancement & mid-turn crash loss:
      • deliver_input (lines 402-417) sets inner.synced_len = input.len() and inner.prefix_hash = prefix_hash(input) as soon as bytes are written to the child's stdin pipe or MCP answers are handed to core.answer(...).
      • inner.session_started becomes true as soon as system/init arrives on Turn 1 (line 772), before Turn 1 finishes.
      • If claude crashes or exits mid-turn (after system/init on Turn 1, or on any Turn >= 2), Driver::on_exit (line 975) calls forget_unstarted_session(&mut self.inner), which is a no-op because inner.session_started is already true.
    2. Persisting advanced synced_len on error results:
      • In Driver::on_result (lines 911-960), even when is_error == true or segment.held_error.is_some() (lines 926-929), line 957 unconditionally executes self.persist().await, saving the advanced synced_len and prefix_hash to $CODEX_HOME/claude-code/sessions/<thread_id>.json. On the next turn, prefix_matches (lines 228-230) is true, so the prompt or tool outputs from the failed turn are skipped and never re-sent.
    3. settle_query kills inner.process after needs_spawn has already run:
      • In ClaudeCodeSession::stream, needs_spawn (lines 236-277) runs before deliver_input (line 284).
      • Inside deliver_input -> send_incremental (lines 473-476), if inner.query_in_flight is true (from a previously cancelled stream), settle_query(inner, core).await is called.
      • If the old query does not settle within SETTLE_TIMEOUT (2s), settle_query (lines 543-546) takes and kills inner.process, leaving inner.process = None.
      • send_user_message (line 476) then sees inner.process.is_none() and returns false, and Driver::run (lines 699-702) immediately fails the new turn with ApiError::Stream("Claude Code is not running") instead of spawning a replacement claude --resume process.
  • Suggested Fix:
    • Stage the target (pending_synced_len, pending_prefix_hash) on Segment/Driver and only commit + persist() when on_result succeeds (outcome.is_ok()).
    • Run settle_query before evaluating needs_spawn in ClaudeCodeSession::stream.

4. [MEDIUM-HIGH] ClaudeOAuthAuthConfig::resolve Bricks Credentials on Pre-Network Failures or fetch_profile Cancellation, Replays Single-Use Refresh Tokens on 5xx, and Misreports Status

  • Locations:
    • codex-rs/login/src/auth/claude_oauth.rs:425-574 (resolve, lock_credentials)
    • codex-rs/cli/src/claude_oauth_login.rs:88-123 (status, describe_status)
    • codex-rs/core/src/provider_models.rs:114-131 (provider_connection)
  • Problem:
    1. refresh_requires_login = true is saved before control_client()? and kept true across fetch_profile:
      • At claude_oauth.rs:466-468, credential.refresh_requires_login = true; self.save(&credential)?; runs before let client = control_client()?;. If control_client() fails (or the task is cancelled before send()), the stored credential is permanently bricked (lines 453-456).
      • After token rotation succeeds (lines 500-507), the code comments:
        // Save rotation BEFORE advisory account lookup, including cancellation/failure.
        self.save(&credential)?;
        However, at line 507, credential.refresh_requires_login is still true (it is not set to false until line 518, after self.fetch_profile(...) at line 508). If the future is cancelled during fetch_profile at line 508, the newly rotated token is saved on disk with refresh_requires_login: true, which resolve() (lines 429, 448, 453) refuses to use.
    2. Replaying single-use refresh tokens on 5xx:
      • lines 469-495 retry status.is_server_error() up to 3 times with the same single-use refresh_token, and if all 3 fail with 5xx, reset credential.refresh_requires_login = false (line 492). If the upstream server rotated the token before returning 502/503, retrying replays a consumed token.
    3. codex login status --provider claude-oauth and provider_connection ignore refresh_requires_login and refresh_blocked_until:
      • claude_oauth_login::status (lines 88-123) and provider_models::provider_connection (lines 114-131) only check load_stored_credential().is_some(), reporting a credential with refresh_requires_login == true as connected/valid.
    4. Ephemeral store mode creates $CODEX_HOME/secrets/claude_oauth.lock on disk:
      • complete_login (line 379) and resolve (line 443) call self.lock_credentials().await? (lines 544-574) unconditionally, creating $CODEX_HOME/secrets/claude_oauth.lock even when self.store_mode == AuthCredentialsStoreMode::Ephemeral.

5. [MEDIUM-HIGH] ModelClientSession::stream_anthropic Does Not Persist strip_thinking Across Steps/Turns and Cannot Recover From SSE InvalidThinkingSignature

  • Locations:
    • codex-rs/core/src/client_anthropic.rs:123-210 (stream_anthropic)
    • codex-rs/codex-api/src/anthropic/stream.rs:292-294, 675-693 (anthropic_stream_error)
  • Problem:
    1. let mut strip_thinking = false; (client_anthropic.rs:123) is a local variable inside stream_anthropic. When a history contains a ResponseItem::Reasoning whose signature Anthropic rejects, attempt 1 fails with ApiError::InvalidThinkingSignature, strip_thinking becomes true, and attempt 2 succeeds. However, the rejected ResponseItem::Reasoning stays in the rollout history, so every subsequent tool-call step and user turn in the conversation starts with strip_thinking = false, fails attempt 1 with HTTP 400, and retries—doubling latency for the rest of the session.
    2. anthropic_stream_error (stream.rs:675-693) maps SSE event: error with invalid signature messages to ApiError::InvalidThinkingSignature, but once api_client.stream(...) returns Ok(stream) (client_anthropic.rs:171), the retry loop in stream_anthropic has already exited, so an SSE-delivered InvalidThinkingSignature fails the turn without retrying.

6. [MEDIUM] build_anthropic_request Conflicts With prepare_oauth_request Over thinking.display and Beta Headers

  • Locations:
    • codex-rs/codex-api/src/anthropic/request.rs:145-166
    • codex-rs/codex-api/src/anthropic/oauth.rs:354-382, 568-573 (normalize_thinking, headers_for_request)
    • codex-rs/codex-api/src/anthropic/client.rs:181-197 (stream_oauth)
  • Problem:
    1. In build_anthropic_request (request.rs:145-156), AnthropicThinking::Adaptive unconditionally sets thinking["display"] = "summarized" (or "omitted").
    2. Consequently, when prepare_oauth_request runs on claude-oauth:
      • if progress_model(model) && request["thinking"].get("display").is_none() (oauth.rs:374) is always false, so claude-opus-5-5 never gets thinking.display = "updates" on real Codex requests (only in isolated unit tests that construct raw JSON without build_anthropic_request).
      • if request["thinking"]["display"].as_str().is_none_or(str::is_empty) (oauth.rs:568-573) is always false, so redact-thinking-2026-02-12 is never added for adaptive models on real Codex requests.
    3. Conversely, when normalize_thinking (oauth.rs:355-368) removes "thinking" because tool_choice is "any" or "tool", AnthropicMessagesClient::stream_oauth (client.rs:187-194) still appends prepared.betas (thinking-binding-controls-2026-08-01) to anthropic-beta.

7. [MEDIUM] codex-claude-code Fresh-Session Splitting (trailing_user_input_start) Wraps User Prompts Into <prior_conversation> and Flattens Images to "[image]" When Control Items Follow User Input

  • Locations:
    • codex-rs/claude-code/src/history.rs:54-102, 396-480 (leading_system, trailing_user_input_start, is_user_input, render_transcript, render_message)
    • codex-rs/claude-code/src/session.rs:228-234, 368-385 (fresh_payload)
  • Problem:
    • On Turn 1 of every new claude-code session (as well as on session resets/fallbacks), prefix_matches (session.rs:228) is false, so Payload::Fresh (fresh_payload) is used.
    • trailing_user_input_start (history.rs:88-101) scans backwards from the end of input while is_user_input is true, where is_user_input only matches non-assistant Message and AgentMessage.
    • Unlike leading_system (history.rs:66-69), is_user_input returns false for transparent control items (ResponseItem::AdditionalTools, ResponseItem::ConfigurationUpdate, ResponseItem::CompactionTrigger, ResponseItem::Other).
    • Whenever any of those control items appears at the end of input after the user's message, trailing_user_input_start returns input.len(). fresh_payload then passes the user's prompt into render_transcript(&input[leading_len..split]), wrapping it in <prior_conversation>This Claude Code session was started fresh...</prior_conversation>, flattening any ContentItem::InputImage to the literal string "[image]" (history.rs:445), and sending "Continue." as the live user message.

8. [MEDIUM] Multi-Agent Cross-Provider V2 Resume and Same-Provider Role Model Validation Bugs in codex-core

  • Locations:
    • codex-rs/core/src/agent/control/spawn.rs:433-488 (V2 resume vs. V1 resume at L1470-L1482)
    • codex-rs/core/src/agent/child_config.rs:94-98, 460-479 (prepare_agent_spawn_config, apply_spawn_agent_role)
  • Problem:
    1. V2 cross-provider child resume leaks parent provider tuning and clobbers stored_reasoning_effort:
      • Unlike fresh cross-provider spawn (child_config.rs:267-273) and V1 cross-provider resume (spawn.rs:1477-1481), V2 child resume (spawn.rs:475-488) fails to clear config.model_verbosity, config.model_context_window, and config.model_auto_compact_token_limit when config.model_provider_id != stored_model_provider.
      • Additionally, config.model_reasoning_effort = stored_reasoning_effort; (spawn.rs:433) is set before apply_role_to_config(&mut config, Some(&role_name)) (line 451), whereas stored_model is restored after apply_role_to_config (line 471). A role that specifies model_reasoning_effort therefore overwrites the child's stored reasoning effort on V2 resume.
    2. Same-provider sub-agent spawn on a Claude session fails to reject a role that pins an OpenAI model:
      • In prepare_agent_spawn_config (child_config.rs:96-98), reject_role_model_from_other_provider only runs when provider_changed && config.model != model_before_role.
      • If the parent session is already running on a Claude provider (provider_changed == false) and spawns a child with a role whose config pins an OpenAI model (e.g. gpt-5.4), reject_role_model_from_other_provider is skipped, and apply_spawn_agent_role (lines 470-472) returns Ok(()) because model_info.used_fallback_model_metadata is true.

9. [MEDIUM] Startup Memory Pipeline Runs on claude-oauth Subscriptions and Queries ChatGPT Rate Limits / Telemetry During Claude Sessions

  • Locations:
    • codex-rs/memories/write/src/start.rs:35-41 (start_memories_startup_task)
    • codex-rs/memories/write/src/guard.rs:15-31 (rate_limits_check)
    • codex-rs/memories/write/src/runtime.rs:105-135 (build_session_telemetry)
  • Problem:
    • start_memories_startup_task (start.rs:35-41) only skips config.model_provider.is_claude_code(), not config.model_provider.is_claude_oauth(). Starting a root claude-oauth session therefore spawns background stage-1 extraction jobs (claude-haiku-4-5) and a phase-2 consolidation agent (claude-opus-5-5) against the user's Claude subscription.
    • Furthermore, when start_memories_startup_task runs under anthropic or claude-oauth, guard::rate_limits_ok(&auth_manager, &config) (guard.rs:16-31) calls auth_manager.auth().await (loading/refreshing the user's ChatGPT credentials and querying config.chatgpt_base_url for OpenAI rate limits), and build_session_telemetry (runtime.rs:113-117) attaches the ChatGPT account_id and account_email to the Claude memory job's telemetry—violating the PR's credential/endpoint isolation guarantee.

10. [MEDIUM] codex login --provider claude-oauth Terminal Reader Races the Localhost Callback Server and Aborts Login on <Enter>, Ctrl-D, or Raw-Mode Failure

  • Location: codex-rs/cli/src/claude_oauth_login.rs:58-68, 140-167, 206-260 (read_callback, read_terminal_callback)
  • Problem:
    • When callback_server binds successfully (lines 59-66), tokio::select! races server.wait_for_callback() against read_callback(true).
    • When io::stdin().is_terminal() is true (line 141), read_callback ignores callback_listener_available and calls read_terminal_callback().
    • If the user presses <Enter> with empty input (lines 221-223), presses Ctrl-D (lines 230-231), or terminal::enable_raw_mode() / events.next() returns an error while the browser is completing OAuth, read_terminal_callback() immediately returns Err(...), winning the tokio::select! and dropping server.wait_for_callback().

11. [LOW-MEDIUM] Anthropic Request & Tool Translation Edge Cases

  • Locations:
    • codex-rs/codex-api/src/anthropic/request.rs:662-702, 776-785 (merge_adjacent)
    • codex-rs/codex-api/src/anthropic/tools.rs:321-334
    • codex-rs/claude-code/src/bridge.rs:58-85
  • Issues:
    1. Merging adjacent assistant messages can place thinking blocks after text/tool_use blocks: merge_adjacent (request.rs:776-785) concatenates consecutive assistant messages (last.content.extend(message.content)). If two assistant turns are adjacent in history and the second starts with a thinking or redacted_thinking block, the merged assistant message has thinking after text, which Anthropic rejects unless thinking blocks lead the assistant turn (and merging invalidates the block signature).
    2. Duplicate tool_result blocks for the same tool_use_id: In request.rs:682, if previous_tool_uses.contains(&id) checks membership without removing id (previous_tool_uses.remove(&id)), allowing duplicate FunctionCallOutput items with the same call_id to emit duplicate tool_result blocks in one user turn.
    3. Silent tool drop on sanitized wire-name collision: prepare_anthropic_tools (tools.rs:327-332) and ToolRegistry::from_declarations (bridge.rs:71-74) skip tools whose sanitized 64-char wire name collides with an earlier tool (if !used_wire_names.insert(wire_name.clone()) { continue; }) without recording a note in unsupported.

- Enforce the managed model_provider requirement when spawn_agent or a
  resume switches an agent's provider, and when listing spawn options.
- Hold Anthropic tool calls until the stop reason is known: a refusal
  drops pending calls and the partial answer, max_tokens and
  context-window stops drop only truncated calls, and max_tokens with no
  tool call raises ResponseIncomplete.
- claude-code: hand already-forwarded calls back to Codex when the
  translator errors at message_stop instead of waiting for a result that
  never comes; look up prepared answers by tool_use id before the
  registry check; answer forwarded calls neutrally when a stream is
  dropped; clear stale sessions after a failed spawn.
- app-server: merge anthropic and claude-code requirement overrides with
  the built-ins before comparing providers.
- Cache slow credential probes (keyring, encrypted store) for 30s when
  listing spawn options.
- Keep only the newest 20 images in Anthropic requests.
- Accept name-less partial overrides for the anthropic and claude-code
  ids, and reject a conflicting name or wire_api with a rename hint.
- Merge configured anthropic-beta headers with request betas.
- Clear verbosity, context-window and auto-compact settings on a v2
  resume that switches provider.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019zo3Km75FmfBq4KdRfnTxT
martinthommesen and others added 11 commits October 19, 2026 13:50
Fix code-review findings on the Anthropic/Claude providers
- A-M2: skip replayed thinking/redacted_thinking blocks with an empty
  signature or data (always a 400, even with drop_block) and note it.
- A-M3: parse input_transformations from message_start and log dropped
  or flagged thinking blocks; drop_block stays on from the first turn.
- A-M5: validate Anthropic API keys when building auth: trim surrounding
  whitespace and fail with a clear error (never echoing the key) instead
  of sending the request without x-api-key.
- A-L1: log unrecognized stop reasons at warn level with their value.
- A-L4: resolve provider- and gateway-prefixed model ids
  (us.anthropic., anthropic/, dotted versions) to their Claude model's
  thinking rules.
- A-L5: parse image data URLs case-insensitively with parameters before
  base64, and omit non-base64 data URLs with a note instead of sending
  them as base64.
- B-11b: answer a tool_use with only the first of duplicate outputs;
  later ones are kept as text.
- B-11c: report tools dropped because their sanitized Anthropic name or
  bridged Claude Code name collides with a different tool.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019zo3Km75FmfBq4KdRfnTxT
…ns that never started

- B-7: trailing_user_input_start now passes over request controls
  (AdditionalTools, ConfigurationUpdate, CompactionTrigger, Other), the
  same items leading_system already skips, so a fresh session no longer
  renders the live prompt inside <prior_conversation> (images as
  "[image]") and sends "Continue." instead.
- B-3b: Driver::on_result forgets a session Claude Code never started
  (a result before system/init), as on_exit already does, so the retry
  reseeds a fresh session instead of sending "Continue." to an empty one.
  A started session keeps the advanced cursor: it already holds the
  failed query's input, and resending it would duplicate it.
- B-3a: no behaviour change; a guard test shows a retry after a mid-turn
  crash resumes the recorded session with "Continue." rather than
  repeating the prompt.
- A-T3: the fake CLI can survive interrupts like the real CLI, and fail
  a turn before or after system/init; new tests cover reusing the live
  process after a settled interrupt and the error-result paths.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019zo3Km75FmfBq4KdRfnTxT
…er tagged ones

- A-H3: the bridge socket is chmod 0600 on Unix (defense in depth; the
  0700 directory already keeps other users out); a client line over
  16 MiB closes that connection; each connection may park at most 128
  calls (further calls get an immediate error result); and once any
  tools/call carries Claude Code's tool_use id, id-less calls are
  refused and id-less calls parked earlier are released with an error,
  so the name-based fallback can no longer hand a Codex result or a
  prepared answer to another same-user client. No peer ancestry check:
  the doc comment on accept_loop explains why it is not proportionate.
- A-L9: prepared answers are capped at 128 (oldest dropped), and they
  can no longer be taken by name once calls are tagged. The unknown-tool
  message only goes back to the client that sent the name, so it is
  left as is.
- A-T3: bridge tests for a squatting client, an oversized message, and
  the parked and prepared bounds, plus the socket mode.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019zo3Km75FmfBq4KdRfnTxT
- A-H2: normalize the requested model_provider once (trim; blank keeps
  the parent's) and use it for both the plaintext-resend guard and the
  spawn, so a padded id for another provider asks for a plaintext resend
  instead of handing a Claude child an encrypted task it cannot read.
- A-M8: the resend guard first validates fork_turns, the message and the
  provider (known, allowed by requirements, connected); the tree switches
  to plaintext collaboration messages only once a child on another
  provider, or under a Claude agent, has started. A failed spawn no
  longer disables encryption for the whole tree.
- A-M1: one switch_agent_provider helper for spawn and both resume
  paths; a V2 reload switches provider before re-applying the role, so
  the role's verbosity survives the reload as it does on spawn.
- B-8b: a role that pins a model the closed Claude catalog does not list
  is rejected for a Claude child even on the parent's provider.
- A-L6: a cross-provider spawn fails when the agent backend cannot load
  the child provider's catalog, instead of resolving the child's models
  against the parent's.
- A-T2: end-to-end tests that a Claude child's /v1/messages request
  carries the delivered plaintext task, directly and after a padded-id
  resend.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019zo3Km75FmfBq4KdRfnTxT
- B-5: after Anthropic rejects replayed thinking (a tampered or
  undecryptable signature, or a gateway that refuses block_binding), the
  rest of the session omits replayed thinking and block_binding instead
  of re-sending the rejected blocks and paying a 400 plus a retry on
  every later request. The decision is kept on ModelClientState.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019zo3Km75FmfBq4KdRfnTxT
…Auth

- B-9: skip the startup memory pipeline for claude-oauth sessions, like
  claude-code, so background extraction and consolidation never spend the
  user's Claude subscription.
- B-9: the memory rate-limit guard no longer loads ChatGPT credentials or
  queries the ChatGPT usage endpoint for Claude providers; ChatGPT quota
  says nothing about Anthropic usage.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019zo3Km75FmfBq4KdRfnTxT
- A-L7a: `codex logout --provider all` no longer exits on the first
  failing provider. It now attempts Anthropic, Claude Code, Claude OAuth
  and OpenAI in turn, prints every result (the OpenAI line is prefixed
  "OpenAI: "), and exits 1 if any of them failed. The OpenAI/ChatGPT
  logout moves into `logout_openai`, which the default path reuses
  unchanged.
- A-L7c: the default `codex login status` now lists connected Claude
  providers in the same order as `--provider all` (OpenAI, Anthropic,
  Claude Code, Claude OAuth). The exit-status rules are documented on
  `run_login_status` and in `codex login status --help`.
- A-L7d: add tests for the `codex login --provider all` rejection,
  `login status --provider all` output and exit status, and
  `logout --provider all` with and without a failing provider. Add
  claude-oauth to the turn-cost worker gate test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019zo3Km75FmfBq4KdRfnTxT
…viour

- A-M6: docs/claude.md now says every anthropic_messages provider without
  env_key (including a base_url override of `anthropic` and any custom
  id) sends the shared stored Anthropic key to its own base_url, adds a
  warning to "Overriding the providers", and notes that redirects are
  refused for these providers as well as claude-oauth. A model-provider
  test pins the sharing so it cannot change silently.
- A-M9: the claude-oauth compatibility record scopes its file list and
  check results to the claude-oauth change set (61b8319..57effb5) and
  points to `git diff --stat main...HEAD` for the full PR; claude.md
  documents the `auto` store's plaintext anthropic_auth.json fallback,
  bills claude-code to whatever credential Claude Code uses (including
  Bedrock/Vertex), and discloses that one failed claude-oauth refresh
  request can require a new login (no code change).
- A-L7c-docs: document `codex login status` output order, stream and
  exit status for every --provider form, what "usable" means, and the
  `codex logout --provider all` order and exit status.
- DOCS-SYNC: document nameless built-in overrides and the rename
  requirement, anthropic-beta merging, managed model_provider pins,
  the 30s spawn-option cache, provider resets on resume, closed-catalog
  role models, when the tree switches to plaintext, the 20-image limit,
  non-base64 images, key trimming/validation, gateway model ids,
  thinking replay, duplicate tool outputs, tool name collisions,
  refusals and max_tokens, Claude Code session reseeding and bridge
  limits, and memories being off on claude-oauth and off ChatGPT quota.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019zo3Km75FmfBq4KdRfnTxT
…its checks

- A-M8 (MultiAgentV2): the plaintext-resend guard moves from the
  spawn_agent handler into thread_spawn::spawn, after
  prepare_agent_spawn_config (provider, model, role, role model, catalog)
  and the task-name check have passed. An encrypted spawn_agent call that
  fails any of those checks now returns that error and leaves the tree
  encrypted; before, it marked the whole tree plaintext as soon as the
  provider was known to be usable. The guard now keys on the message
  actually being encrypted.
- The failed-spawn test now runs the default (encrypted) handler as well
  as the plaintext one, with an invalid task name and an unknown
  agent_type, and checks that the tree stays encrypted.
- docs/claude.md: describe the remaining case. A MultiAgentV2 call that
  passes every check but carries an encrypted task for another provider
  switches the tree right away so the model can resend the task, and the
  tree stays plaintext even if that resend fails or never comes.
- cli: render `login --help` and `login status --help` without wrapping
  in the help tests, so "at least one provider" no longer depends on the
  terminal width or COLUMNS (it wrapped at 86-90 columns).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019zo3Km75FmfBq4KdRfnTxT
- The bridge counted a message's trailing newline toward the 16 MiB
  limit, so a message of exactly the limit was refused. The limit now
  applies to the message itself; a longer one is still detected after
  one byte past the limit.
- docs/claude.md: roles re-apply after the provider reset on spawn and
  on a multi-agent v2 reload, but not when a whole tree resumes from
  saved rollouts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019zo3Km75FmfBq4KdRfnTxT
@martinthommesen

Copy link
Copy Markdown
Owner Author

Review follow-up

This answers both review comments above (posted at 10:05 and 10:27), using their numbering. The branch is now at dcd2f22.

  • Fix commits: 360884b (merged from Fix code-review findings on the Anthropic/Claude providers #3), 52f3c37, f753d82, b82bbec, 5bffdcd, 167737d, 2376c3b, 76786fa, 09be5bc, a32c6d1, dcd2f22.
  • Not fixed: three findings inside claude-oauth itself (comment 2, items 4, 6 and 10). The author decided to keep claude-oauth in this PR and disclose it instead.

Full review (10:05)

§1 claude-oauth missing from the description. The description now leads with all three providers. A dedicated claude-oauth section says what it sends:

  • Claude Code's OAuth client ID;
  • the claude-cli/2.1.280 user agent, x-app: cli and the x-stainless-* headers;
  • the Claude Code identity text;
  • the billing block and its CCH checksum;
  • the MCP-style tool aliases.

The same section quotes the parts of Anthropic's policy it conflicts with, and says the provider was never validated live and is opt-in only. The "never" sentence now covers only anthropic and claude-code, with claude-oauth named as the exception. claude-oauth stays in this PR by the author's decision, and its own open bugs are not fixed here.

H1 (documented overrides rejected). Fixed in 360884b. One shared validator accepts name-less partial overrides of anthropic and claude-code. A differing name or wire_api is rejected with a hint to rename the provider.

H2 (padded model_provider). Fixed in 5bffdcd.

  • The resend guard and child_config now share one requested_spawn_provider normalization: trim, and a blank value keeps the parent's provider.
  • A unit test covers the resend path for "ollama" and " ollama ".
  • padded_provider_id_resends_the_task_in_plaintext checks end to end that a padded gateway id gets the "needs a plaintext message" reply, and that the resent task reaches the Claude child in plaintext.

H3 (bridge peers). Partly fixed in b82bbec.

  • The socket is now 0600.
  • A client message over 16 MiB closes only that connection. dcd2f22 fixes an off-by-one so a message of exactly 16 MiB is accepted.
  • Each connection can park at most 128 calls, and prepared answers are capped.
  • Claude Code tags every call with its tool_use id. Once a tagged call arrives, id-less calls are refused and earlier ones are released with an error. A squatter therefore can no longer receive a Codex result by tool name or consume a prepared answer, except by winning the race for a session's very first call.
  • No peer-ancestry check was added. The peer is a grandchild behind shims, ancestry checks need per-OS code and are racy under PID reuse, and a same-user process can already read Codex rollouts and Claude transcripts. The accept_loop doc comment records this.
  • Tests: id_less_calls_are_refused_once_calls_carry_tool_use_ids, overlong_messages_close_only_that_connection, parked_calls_per_connection_are_bounded, bridge_socket_is_owner_only, prepared_answers_are_bounded.

H4 (test stack overflow). Unchanged. Without RUST_MIN_STACK, every test in suite::anthropic_provider overflows the 2 MiB default when run alone, and so do upstream tests such as suite::client::configured_verbosity_is_sent. All of them still overflow at 3 MiB, so wrapping this one test would not stop a plain cargo test of the binary from aborting. The repo runs these suites with RUST_MIN_STACK=8388608 (justfile, rust-ci.yml, rust-ci-full.yml), and they pass there.

Medium

  1. Parent tuning on V2 reload. The reset was fixed in 360884b. 5bffdcd then moved the three copies into one switch_agent_provider helper, and the two resume paths now share resume_on_stored_provider. It also fixes an ordering drift: a V2 reload switched provider after applying the role, which dropped a model_verbosity set by the role. The new test ensure_v2_agent_loaded_keeps_role_verbosity_on_the_childs_provider covers it.
  2. Empty thinking signatures. Fixed in 52f3c37, though the trigger is different from the one described. An interrupted stream never records a thinking block. A block that closes without a signature_delta (for example behind a gateway that strips them) was stored and replayed as "signature": "", and every later request paid a 400 plus a retry. build_anthropic_request now skips thinking and redacted_thinking blocks with an empty signature or empty data and adds a note. This also cleans up histories that are already persisted. Test: thinking_blocks_without_a_signature_are_not_replayed.
  3. block_binding. Partly fixed in 52f3c37.
    • Sending drop_block from the first turn stays. The current docs say it is accepted with adaptive and enabled thinking, and accounts created on or after 2026-08-31 are enforced by default. Waiting for a rejection would cost a 400 on every history edit.
    • A gateway that rejects the field already goes through the strip-and-retry path.
    • The real gap was that input_transformations was never read. The stream translator now keeps it and logs it, at warn level for prefix_binding_mismatch. Test: input_transformations_from_message_start_are_kept.
  4. pause_turn "Continue.". Doesn't reproduce. pause_turn only happens when a server-side tool loop hits its limit, and Codex never sends server tools: every hosted tool type becomes an unsupported note. The documented resume would also need the server_tool_use blocks, which Codex does not keep. "Continue." is only the fallback for a history that ends with an assistant turn.
  5. Invalid key header dropped silently. Fixed in 52f3c37. AnthropicApiKeyAuth::new now trims the key and builds the header up front. It returns an error naming ANTHROPIC_API_KEY or the provider's env_key, never the key itself, instead of sending the request without x-api-key. Tests: api_keys_are_trimmed_and_unsendable_keys_are_rejected_without_echoing_them, env_key_that_cannot_be_sent_fails_without_echoing_it.
  6. Shared key sent to custom anthropic_messages providers. Documented in 09be5bc; the behaviour itself is deliberate.
    • docs/claude.md now says which providers receive the shared key, and when env_key replaces it.
    • It also says that redirects fail the request for these providers too.
    • It adds a warning to "Overriding the providers", and notes that provider definitions in a repository's .codex/config.toml are ignored.
    • custom_anthropic_messages_provider_without_env_key_sends_the_stored_key pins the behaviour so it cannot change silently.
  7. claude auth status child leak. Doesn't reproduce. That spawn already sets kill_on_drop(true), and wait_with_output takes the Child by value, so dropping the future on timeout kills the process.
  8. Failed spawn flips the tree to plaintext. Fixed in 5bffdcd and a32c6d1.
    • A spawn that fails its checks leaves the tree encrypted. The checks cover an unknown, disallowed or unconnected provider, an invalid task name, an unknown agent_type, and a model the provider doesn't serve.
    • The tree is marked only after the spawn succeeds, on both V1 and V2.
    • One exception, now documented: a V2 call that passes those checks but carries an encrypted task for another provider switches the tree to plaintext right away, so the model can resend.
    • Test: failed_multi_agent_v2_spawn_on_another_provider_keeps_tree_encrypted.
  9. Doc corrections. Done in 09be5bc.
    • The claude-oauth file list is now labelled as the files changed by 61b8319, 00aae9d and 57effb5, not the PR's full list.
    • The auto store's plaintext anthropic_auth.json fallback is documented.
    • Claude Code billing follows whatever credential Claude Code reports: a subscription, a Console key, or Bedrock/Vertex.
    • The docs disclose that one failed or interrupted claude-oauth refresh requires a new login. The refresh code itself is unchanged.

Lower severity

  • Unknown stop reasons and block-index reuse. Partly fixed in 52f3c37. An unrecognized stop_reason is now logged at warn level with its value. A user-visible note would need a new warning event type. Index reuse can't happen: the API assigns unique block indices per message, and claude-code starts a fresh translator on every message_start.
  • strict: true tools. Unchanged. No production Codex tool declares strict: true; the Responses path hard-codes false. Forwarding it after schema flattening could turn a harmless flag into a 400 for the whole request.
  • Duplicate canonical headers. Doesn't reproduce. The HeaderMap::extend(HeaderMap) impl used here replaces existing values for each name; only the (HeaderName, T) impl appends. A scratch run with conflicting provider headers recorded exactly one value per header. anthropic-beta merging was added in 360884b.
  • 408, claude-3 limits, unknown slugs. Partly fixed in 52f3c37.
    • A 408 already goes through core's retry with backoff.
    • The claude-3 limits stay, since those models are retired on the first-party API.
    • The real bug was slug normalization: region-prefixed and gateway ids such as us.anthropic.claude-sonnet-4-5-… or anthropic/claude-haiku-4.5 got adaptive thinking, which those models reject. ClaudeModelTraits::for_model now starts the slug at claude- and maps dots to dashes. Test: provider_prefixed_slugs_use_the_traits_of_their_claude_model.
  • Data URLs. Fixed in 52f3c37.
    • The scheme, media type and base64 marker are now matched case-insensitively, and the marker is found among any other parameters.
    • A data URL that isn't base64 becomes a placeholder plus a note, instead of a request that fails every time.
    • Test: image_data_urls_are_parsed_case_insensitively_and_must_be_base64.
  • Catalog fallback and empty slug. Partly fixed in 5bffdcd. A cross-provider spawn whose catalog can't load now fails with "spawn_agent cannot load the model catalog of model_provider …" instead of using the parent's catalog. The empty slug doesn't reproduce: session start rejects an empty default with "No models are available…".
  • CLI. Done in 76786fa, except the key-prefix item.
    • logout --provider all now tries Anthropic, Claude Code, Claude OAuth and then OpenAI, prints every result, and exits 1 if any failed. Before, the first error skipped the OpenAI logout.
    • Default login status now uses the same order as --provider all.
    • The exit codes are documented in --help and in docs/claude.md.
    • New tests: logout_all_attempts_every_provider_after_a_failure, logout_all_succeeds_when_every_provider_signs_out, login_provider_all_is_rejected, login_status_provider_all_reports_every_provider, login_status_help_documents_exit_codes, plus claude-oauth in worker_does_not_start_for_claude_providers.
    • The key-prefix asymmetry stays. The OpenAI side rejects only sk-ant- keys, because storing one there would overwrite auth.json and erase the ChatGPT sign-in. Anthropic gateways often issue keys without the sk-ant- prefix.
  • wire_api = "responses" restated on anthropic. Fixed in 360884b: a differing name or wire_api is rejected.
  • Bridge mcp_name in errors; stale prepared answers. Partly fixed in b82bbec. The name text goes back only to the client that sent it, never to the model; Claude Code only calls names from tools/list, which are at most 52 characters. Stale prepared answers are now capped at 128, and can't be taken by name once calls carry tool_use ids.

Test gaps

  1. Resend path. Covered by the H2 tests above.
  2. Plaintext content at the Claude child. openai_parent_delivers_plaintext_task_to_claude_child checks the child's /v1/messages request for a user text block carrying the task (5bffdcd).
  3. Bridge squatting and interrupts.
    • The bridge tests above cover the squatting and size cases.
    • The fake CLI can now survive an interrupt like the real CLI does; an_interrupt_the_cli_survives_reuses_the_live_process covers this (f753d82).
    • An interrupt during a bridged tool call is still not covered, because the fake blocks on the MCP request.
  4. Recorded-live API-key test. Not added, because it needs a live key. The API-key path stays covered by mocks.
  5. CI. GitHub Actions doesn't run on this fork's PRs: blocking-ci.yml has a pull_request trigger, but only Socket checks appear. That needs a repository settings change, not a code change. The checks below were run locally.

Technical review (10:27)

  1. Stream completion. Already fixed in 360884b.
    • Tool calls are held until stop_reason, and max_tokens after text raises ResponseIncomplete.
    • A completed zero-argument call is sent as {} on every normal stop.
    • Under max_tokens, only the last block is held back. A call cut off inside its first parameter streams exactly like a zero-argument call, and running it with {} would be worse.
  2. Partial overrides and managed requirements. Fixed in 360884b, in both config_toml.rs and the app-server requirement check.
  3. claude-code cursor. Handled in f753d82.
    • 3.1 stays by design. Once Claude Code emits system/init, it has recorded the message. After a crash, the retry resumes with --resume and sends "Continue.", so rolling the cursor back would put the prompt in the session twice. a_crash_after_startup_resumes_without_repeating_the_prompt pins this.
    • 3.2 has the same reasoning: an error result means the CLI ran the query. The one real loss was an error before system/init, when no session exists. That case now reseeds a fresh session with the full history (an_error_before_startup_reseeds_the_retry, and an_error_result_does_not_resend_the_prompt for the normal case).
    • 3.3 doesn't reproduce. A driver releases the session with query_in_flight set only after handing forwarded calls back, so send_incremental takes the answer branch. A cancelled stream settles in Driver::cancel, which kills the process itself on timeout, and the next stream respawns with --resume.
  4. claude-oauth resolve. Not fixed, because it is inside claude-oauth itself (author's decision). Re-login after a failed refresh is now disclosed in the docs.
  5. strip_thinking not persisted. Partly fixed in 167737d.
    • The decision is now stored on the session's ModelClientState. After one rejection, the rest of the session sends no replayed thinking and no block_binding.
    • Tests: anthropic_rejected_thinking_is_not_replayed_again_in_the_session, anthropic_block_binding_rejection_is_remembered_for_the_session.
    • The SSE half stays: Anthropic returns signature and block_binding rejections as a 400 before the stream starts. In-stream error events are documented only for overload-type errors.
  6. OAuth thinking display and betas. Not fixed: this is claude-oauth's request path only.
  7. Fresh-session splitting. Fixed in f753d82. trailing_user_input_start now passes over the same control items that leading_system skips, so the prompt stays live. Tests: trailing_user_input_passes_transparent_control_items, a_fresh_payload_keeps_a_prompt_followed_by_control_items_live, trailing_control_items_keep_the_prompt_live.
  8. V2 resume and role models.
    • 8.1: the tuning half is fixed (see Medium 1). The effort and role ordering predates this PR; main has the same order. On spawn, the stored effort already equals the role's effort; they differ only if the role file is edited between spawn and reload. It is left unchanged.
    • 8.2 is fixed in 5bffdcd. On a Claude provider, a role model outside the Claude catalog is rejected even when the child stays on its parent's provider. Test: claude_parent_rejects_a_role_model_its_provider_does_not_serve.
  9. Memory pipeline. Fixed in 2376c3b.
    • Memory jobs now skip claude-oauth sessions, as they already did for claude-code.
    • Rate-limit checks for Claude providers no longer read ChatGPT auth or query chatgpt_base_url.
    • Tests: memories_startup_skips_claude_oauth_sessions, claude_providers_do_not_consult_chatgpt_rate_limits.
    • Telemetry is unchanged. The local account id and email are only local labels, the main session sets them the same way for every provider, and none of it reaches Anthropic.
  10. claude-oauth login reader race. Not fixed, because it is inside claude-oauth itself.
  11. Request translation.
  • 11.1 doesn't reproduce: HistoryBuilder::push already folds consecutive assistant items into one message.
  • 11.2 is fixed in 52f3c37: a duplicate output now answers the call once (duplicate_tool_outputs_answer_the_call_once).
  • 11.3 is fixed in 52f3c37: a name collision now adds an unsupported note, in both the Anthropic translation and the Claude Code bridge.

Checks run on this head (in the container, with RUST_MIN_STACK=8388608)

  • cargo fmt --check and cargo clippy --tests are clean on codex-app-server, codex-claude-code, codex-cli, codex-api, codex-core, codex-memories-write and codex-model-provider.

  • codex-api, codex-claude-code, codex-model-provider and codex-memories-write all pass.

  • codex-core:

    • the anthropic_provider and claude_code_provider suites pass, 21 tests;
    • --lib has 2799 passed and 8 failed. The 8 are environmental, in code this branch doesn't touch: the codex-code-mode-host binary is missing, RUST_BACKTRACE changes compared error strings, and the container has credential-like environment variables.
  • codex-cli and codex-app-server pass apart from environmental failures:

    • the container runs as root;
    • bubblewrap is missing;
    • helper binaries from other crates aren't built;
    • RUST_BACKTRACE is set.

    None of these failures are in the code changed here.

  • Cargo.lock and MODULE.bazel.lock are unchanged.


Generated by Claude Code

@martinthommesen martinthommesen changed the title Add Anthropic/Claude providers with mixed-provider agent delegation Add Anthropic/Claude providers (including experimental claude-oauth) with mixed-provider agent delegation Oct 19, 2026
@martinthommesen
martinthommesen merged commit 2037b40 into main Oct 20, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants