From b7d683bd9b8e0444ce964272a2629550091bbaf0 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 20 Oct 2026 21:58:06 +0000 Subject: [PATCH 1/2] =?UTF-8?q?codex:=20opt-in=20bridged=20route=20?= =?UTF-8?q?=E2=80=94=20incode's=20toolbox=20runs=20every=20tool=20call?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With `codex_tools: "incode"` in admin.json (or INCODE_CODEX_TOOLS=incode), codex is driven like the Claude route: a model only, its own tools switched off by `-c` overrides, `--ignore-user-config`, read-only + approval never, and one MCP server — `incode --tool-server` — reached over the tool bridge. runs_tools_here() is true there, so allowed-tools, permission rules, guards, hooks, the engine and the OS sandbox apply and the "not enforced" notice stops. The default stays `own`, byte-identical (argv pinned by a test), until a turn with a real model has run this way. Every override was read from codex's source (rust-v0.163.0, checked against 0.153.4 and 0.145.0) and measured on the 0.163.0 binary against a stand-in Responses endpoint that recorded the tool list, then end to end through `incode -t`: a scripted Write ran in the toolbox, a deny rule refused one, and apply_patch (no switch exists) was rejected unrun. - tool_bridge: the turn loop (Incoming, pump, Turn::open, drive, CANCELLED) factored out of claude_code and shared. - codex: CodexTools, MODEL_ONLY_OVERRIDES, the bridge registration (env_vars — codex passes a stdio server only listed variables —, approve, required, tool_timeout_sec, omit_tools_from), bridged_command, run_bridged, toolbox forwarding, one line reader for both routes that does not show codex's echo of incode's own calls twice. - admin: codex_tools, resolve_codex_tools, the report line. - cli: codex_backend builds either route. - agy: why it cannot be bridged. README, ARCHITECTURE §5a, ROADMAP. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011DiH8n52ifWoCd5Kx2aHwT --- README.md | 67 +- docs/ARCHITECTURE.md | 26 + docs/ROADMAP.md | 11 +- src/admin.rs | 111 +++ src/agent/agy.rs | 12 + src/agent/claude_code.rs | 108 +-- src/agent/codex.rs | 1476 ++++++++++++++++++++++++++++++++++---- src/cli/mod.rs | 125 +++- src/custom_commands.rs | 3 +- src/tool_bridge.rs | 142 +++- 10 files changed, 1811 insertions(+), 270 deletions(-) diff --git a/README.md b/README.md index cc35517..523acc7 100644 --- a/README.md +++ b/README.md @@ -8,8 +8,8 @@ before it calls it done. in to — `claude`, `codex` and `agy` — are used only as models, run headless on your own subscriptions. The loop's tools, the permission checks, the undo history, the memory hooks and the record of what happened are incode's own. -(Today that is fully true for `claude`; `codex` and `agy` still run their own -tools — see [Limits](#limits).) +(Today that is fully true for `claude`, and for `codex` when you opt in; `codex` +by default and `agy` still run their own tools — see [Limits](#limits).) --- @@ -450,6 +450,56 @@ it sets; any other `id` adds an agent. - An `id` holding `/` or `:` is skipped: those mark provider agents and role qualifiers. +### The codex route: whose tools + +By default `codex` runs its own tools (`exec_command`, `apply_patch`, …) and +incode watches the result afterwards. With `"codex_tools": "incode"` in +`admin.json` (or `INCODE_CODEX_TOOLS=incode`, which wins) it is driven like +`claude`: a model only, with every tool call run by incode. `incode --admin` +shows which is in force and where it was decided. It is opt-in until a turn with +a real model has been run this way; everything below was measured on codex 0.163.0 +against a stand-in model endpoint, end to end through `incode -t`. + +Each turn incode opens its tool bridge and starts `codex exec --json` with: + +- `--ignore-user-config` — `~/.codex/config.toml` is not read (so no MCP server + you registered there is reachable); login still comes from `CODEX_HOME`. A + model provider set only in that file is not used on this route. +- its tools off: `features.shell_tool=false`, `features.view_image=false`, + `web_search="disabled"`, `features.goals=false`, `agents.enabled=false`, + `features.multi_agent=false`, `features.apps=false`, `features.plugins=false`, + `features.browser_use=false`, `features.computer_use=false`, + `features.image_generation=false`, + `tools.experimental_request_user_input.enabled=false`; +- `sandbox_mode="read-only"`, `approval_policy="never"`; +- one MCP server, `incode --tool-server`, given the bridge's address and token + through `env_vars` (codex passes a server only the variables it is told to), + approval mode `approve`, `required`, a one-hour call timeout, and its tools + listed directly rather than behind codex's tool search. + +What is enforced there: every file, shell, web, team, desktop and sub-agent +call is incode's, so the guards, the [permission rules](#permission-rules), a +command's `allowed-tools`, the permission mode, your hooks, the memory engine +and the [OS sandbox](#the-os-sandbox) apply to it before it runs, and the +"not enforced" notice is not shown. What is not incode's: + +- `apply_patch` stays on offer — codex has no switch for it (the model catalogue + decides). Under read-only + never codex rejects it before it runs ("patch + rejected: writing is blocked by read-only sandbox"), so it cannot write. +- The three MCP resource readers (`list_mcp_resources`, …) stay; they read only + what incode's server offers. +- On code-mode models (`gpt-5.6-terra`) incode's tools are reached through + codex's own `exec`, a JavaScript sandbox without file system or network that + calls them — each call still lands in incode. +- A project's own `.codex/config.toml` is outside `--ignore-user-config`; + codex loads it only for a project it trusts. +- Older codex: 0.145 has no `view_image` switch and lists incode's tools behind + its tool search; 0.153 has every switch above. + +`agy` cannot be driven this way: it has no flag to switch its tools off, and +takes MCP servers only through a persistent `agy mcp add`, which would edit your +machine rather than one run. + ### The API providers contract ```json @@ -596,8 +646,9 @@ rule (`Bash(npm test:*)`, `Read`, `Edit(src/**)` — the grammar of refused, with the list named to the model. A compound shell line is covered only when every part is. Only that turn: the next one is unrestricted. It only narrows — deny and ask rules, guards, the mode and hooks still apply. It binds -where incode runs the tools (the API route and Claude Code); on Codex and -Antigravity, which bring their own tools, the turn says it was not enforced. +where incode runs the tools (the API route, Claude Code, and Codex with +`codex_tools: "incode"`); on Codex's own tools and Antigravity, the turn says it +was not enforced. A **plugin** is a folder in `~/.incode/plugins//` or `.incode/plugins//` with a `plugin.toml` (`name`, `version`, @@ -1237,6 +1288,7 @@ and `--admin` prints which layer decided each value. | `sandbox` | `off` · `workspace-write` · `read-only`; unset follows the permission mode | | `sandbox_network` | `allow` (default) · `deny` — see [the OS sandbox](#the-os-sandbox) | | `sandbox_engine` · `sandbox_allow_hosts` · `sandbox_backend` | `builtin` (default) · `sbx`; under sbx, the hosts a command may reach and, on Windows, `native` · `wsl` · `auto` — see [the OS sandbox](#the-os-sandbox) | +| `codex_tools` | `own` (default) · `incode` — whose tools a `codex` model runs; see [the codex route](#the-codex-route-whose-tools) | | `hooks` (also `desktop_hooks`) | Your `pre_tool_use` / `post_tool_use` commands, run for every tool. The event is JSON on stdin; exit 2 on a pre-tool command denies; bounded at 10 s | | `desktop_limits` | The desktop's limits, each optional: `max_actions_per_minute` (120), `heartbeat_deadline_secs` (30), `tree_depth` (12), `tree_max_elements` (400), `journal_max_bytes` (262144), `xvfb_start_timeout_secs` (10), `clipboard_timeout_secs` (5), `accessibility_call_timeout_ms` (1000), `paste_restore_delay_ms` (500, how long the pasted text stays on the clipboard before the old one is put back), `settle_ms` (300, the pause before a `screenshot_after`), `max_scroll_steps` (50, wheel steps in one `scroll`), `tree_max_visited` (4000, elements one tree walk may visit), and `blocked_apps` (application names, matched case-insensitively as a part of the name, added to the built-in password managers: 1Password, Bitwarden, LastPass, Dashlane, KeePass, NordPass, Proton Pass, Enpass, RoboForm, Keeper). The first two are safety limits and may only be lowered; zero and unknown keys are refused, and the desktop does not start on a malformed admin.json | | `desktop_display` | Linux computer use: `":N"` drives a running X display; `"xvfb"` or `"xvfb:1280x800"` starts a private Xvfb for the desktop server's lifetime (default 1920x1080). Unset refuses rather than using `$DISPLAY`. `paste_text` needs `xclip` or `xsel`; `ui_tree` needs a D-Bus session with at-spi2-core | @@ -1256,6 +1308,7 @@ Environment variables: | `INCODE_LANES` | Parallel `/run` lanes (needs git; at most 8) | | `INCODE_SANDBOX` · `INCODE_SANDBOX_NETWORK` | The sandbox mode · the network switch | | `INCODE_DESKTOP` | `1` offers the [computer use](#computer-use) tools | +| `INCODE_CODEX_TOOLS` | `own` · `incode`, over `admin.json` `codex_tools` | | The variable each `key_env` names | That entry's key — the only part of an API route read from the environment | | `INCORD_MEMORY_URL` · `INCORD_ENGINE_BIN` | The memory service · its engine binary | | `INCODE_BROWSER` · `INCODE_PDF_BROWSER` · `INCODE_SOFFICE` | The headless browser · the PDF printer · LibreOffice | @@ -1337,8 +1390,10 @@ moved. The old `INCORD_*` variables are not read any more: rename them. ## Limits -- `codex` and `agy` still use their own tools; only `claude` runs as a model - only. On those routes the guards are a sentinel (detection), not a gate. +- `codex` (by default) and `agy` still use their own tools; `claude` runs as a + model only, and so does `codex` with `codex_tools: "incode"` + ([opt-in](#the-codex-route-whose-tools)). On the other routes the guards are a + sentinel (detection), not a gate. - A client's MCP servers are stdio or Streamable HTTP; the older SSE transport is not spoken. - The Windows sandbox confines workspace-write only when you name it, and does diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 5a3d0c9..060d66a 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -993,6 +993,32 @@ feature flag or config key (only the model catalogue's `apply_patch_tool_type`); to switch them off was found. Until both are proved, codex keeps its own tools, the Sentinel remains detection-only there, and its edit events still feed the diff. +**codex 0.163.0 — bridged, OPT-IN (`codex_tools: "incode"` / `INCODE_CODEX_TOOLS`).** +The default stays `own` until a turn with a real model has run this way. The tool list +was observed by pointing codex at a stand-in Responses endpoint +(`-c model_providers..base_url=…`) that recorded each request — no login needed: + +| Need | Override | Evidence | +|---|---|---| +| No shell, image, web, goals or ask tools | `features.shell_tool=false`, `features.view_image=false`, `web_search="disabled"`, `features.goals=false`, `tools.experimental_request_user_input.enabled=false` | `gpt-5.5` control: `exec_command, write_stdin, request_user_input, apply_patch, view_image, get_goal, create_goal, update_goal, tool_search, web_search`; with them: `list_mcp_resources, list_mcp_resource_templates, read_mcp_resource, apply_patch, mcp__incode{…}`. | +| No sub-agents of its own | `agents.enabled=false` (+ `features.multi_agent=false`) | `gpt-5.6-terra` (catalogue: multi-agent v2) still had a `collaboration` namespace (`spawn_agent`, …) with only the feature off; gone with `agents.enabled=false`, which `Config::multi_agent_version_override` puts above the catalogue. | +| Its MCP servers and settings unread | `--ignore-user-config` | `exec/src/cli.rs` (global flag, 0.145+); auth still from `CODEX_HOME`. Hooks stay off by `--disable hooks`. | +| incode's server, reachable | `mcp_servers.incode.{command,args}`, `env_vars=["INCODE_TOOL_BRIDGE","INCODE_TOOL_TOKEN"]` | codex gives a stdio server only `HOME`, `PATH`, … plus `env_vars` (`rmcp-client/src/utils.rs`); a probe server got the two named and not a third variable set beside them. | +| Calls not refused by codex | `default_tools_approval_mode="approve"` | `auto` asks for any tool not marked read-only (`requires_mcp_tool_approval_for_mode`), and under `approval_policy="never"` the ask is a refusal. | +| Tools listed directly | `omit_tools_from=["deferred"]` | without it the tools sat behind `tool_search`; with it `mcp__incode{…}` was in the list and `tool_search` was not (0.153+; 0.145 ignores the key). | +| Long calls survive | `tool_timeout_sec=3600` | codex's default is 300 s (`DEFAULT_TOOL_TIMEOUT`); the bridge's own bound is an hour. | +| `apply_patch` cannot write | `sandbox_mode="read-only"`, `approval_policy="never"` | no switch exists (the catalogue's `apply_patch_tool_type`); `assess_patch_safety` rejects it before it runs. Live: a scripted `apply_patch` adding a file came back "patch rejected: writing is blocked by read-only sandbox; rejected by user approval settings", and no file appeared. | + +Through `incode -t` with the stand-in scripted to call `mcp__incode` `Write`: codex +started `incode --tool-server`, the call ran in the toolbox (`tool Write (change)`), +the file was written, the stream showed it once as `incode-1` (codex's own +`mcp_tool_call` items for the `incode` server are not shown again), and the model was +handed the toolbox's answer. With `"permissions": {"deny": ["Write(secret.txt)"]}` the +same call came back "NOT RUN — Write is refused by the deny rule" and nothing was +written. On a code-mode model (`gpt-5.6-terra`) the tools are nested under codex's +`exec` (JavaScript, no file system or network), and each call still lands in the +toolbox. NOT run: a turn with a real model. + **agy 1.2.11 (antigravity) — NOT bridged; cannot be.** `agy --help` has no flag to remove or restrict its built-in tools, no per-run MCP configuration (only a persistent `agy mcp add`, which edits the operator's machine), and no way to skip its settings. A diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 069ca32..c0b3e6c 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -40,10 +40,13 @@ This is fully true for claude; section 0b says what is not. ### 0b. Still open -- **codex and agy still use their own tools.** agy has no switch to turn them off - or add MCP per run; codex has no switch for `apply_patch` / `update_plan`, and - its candidate flags could not be proved (usage limit). On both routes the guards - are the Sentinel (detection), not a gate (`ARCHITECTURE.md` §5a). +- **codex and agy still use their own tools by default.** agy has no switch to + turn them off or add MCP per run. codex can now be bridged, opt-in + (`codex_tools: "incode"`): measured on 0.163.0 against a stand-in model + endpoint, end to end; `apply_patch` has no switch and is rejected unrun under + read-only + never. Left: a turn with a real model, then making it the default. + On the unbridged routes the guards are the Sentinel (detection), not a gate + (`ARCHITECTURE.md` §5a). - **Driving ACP agents (opencode, gemini).** Built in `fcfa2d9`, reverted in `c98757a`; not in HEAD. gemini, opencode and cursor are detected, not driven. - ~~**Provider agents** from `api_providers` are listed and marked not usable.~~ diff --git a/src/admin.rs b/src/admin.rs index 8481d11..9b959a5 100644 --- a/src/admin.rs +++ b/src/admin.rs @@ -210,6 +210,12 @@ pub struct AdminConfig { /// cmd.exe, and never the WSL launcher. #[serde(default, skip_serializing_if = "Option::is_none")] pub shell: Option, + /// Whose tools a codex model runs: `own` (the default — codex's, watched + /// afterwards by the Sentinel) or `incode` (incode's toolbox through the + /// tool bridge, codex's own switched off) — see + /// [`crate::agent::codex::CodexTools`]. `INCODE_CODEX_TOOLS` wins over it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub codex_tools: Option, /// The capability ladder, named by the operator. /// /// A tier is a list of models that can do the same JOB — `"top"` might hold @@ -992,6 +998,36 @@ impl AdminConfig { } } + /// Whose tools a codex model runs, and where that was decided: the + /// environment, then the settings, then `own`. A word nobody uses is + /// `own` from the built-in layer — the route that has run live — and is + /// reported as such rather than guessed at. + #[must_use] + pub fn resolve_codex_tools(&self) -> Resolved { + self.resolve_codex_tools_with( + std::env::var(crate::agent::codex::CODEX_TOOLS_ENV) + .ok() + .as_deref(), + ) + } + + /// [`Self::resolve_codex_tools`] with the environment's value passed in, + /// so a test drives every layer without setting a variable that the + /// backend tests running beside it read. + fn resolve_codex_tools_with( + &self, + env: Option<&str>, + ) -> Resolved { + use crate::agent::codex::CodexTools; + if let Some(tools) = env.and_then(CodexTools::parse) { + return Resolved::new(tools, Source::Environment); + } + match self.codex_tools.as_deref().and_then(CodexTools::parse) { + Some(tools) => Resolved::new(tools, Source::AdminFile), + None => Resolved::new(CodexTools::Own, Source::BuiltIn), + } + } + /// The check that decides whether work is finished, and where it came from. #[must_use] pub fn resolve_verify(&self, workspace: &Path) -> Option>> { @@ -1086,6 +1122,13 @@ impl AdminConfig { )), } + let codex_tools = self.resolve_codex_tools(); + out.push_str(&format!( + " codex tools {} <- {}\n", + codex_tools.value.as_str(), + codex_tools.source.as_str() + )); + // Every one of these is optional. Saying which are OFF is the point: a // harness quietly doing less looks exactly like one doing nothing. let off = self.plugins.disabled(); @@ -1155,6 +1198,7 @@ mod tests { std::env::remove_var(crate::config::MODEL_ENV); std::env::remove_var(crate::budget::BUDGET_ENV); std::env::remove_var(crate::verify::VERIFY_COMMAND_ENV); + std::env::remove_var(crate::agent::codex::CODEX_TOOLS_ENV); for role in crate::roles::KNOWN_ROLES { std::env::remove_var(format!( "{}{}", @@ -1512,6 +1556,7 @@ mod tests { sandbox_backend: Some("wsl".to_string()), // The Bash tool's shell, which the owner may pin on Windows. shell: Some("C:/Program Files/Git/bin/bash.exe".to_string()), + codex_tools: Some("incode".to_string()), // The ladder has to survive the file too — a tier an operator // writes and cannot read back is a setting that does not exist. tiers: BTreeMap::from([( @@ -1611,6 +1656,72 @@ mod tests { clear_env(); } + /// **CODEX KEEPS ITS OWN TOOLS UNLESS SOMEONE SAID OTHERWISE.** Unset is + /// `own`; the settings switch it to `incode`; the environment wins over + /// the settings; a word nobody uses is `own` from the built-in layer, + /// never a guess at what was meant. + #[test] + fn codex_tools_resolve_like_the_other_settings() { + use crate::agent::codex::CodexTools; + let unset = AdminConfig::default(); + assert_eq!( + unset.resolve_codex_tools_with(None), + Resolved::new(CodexTools::Own, Source::BuiltIn) + ); + + let admin = AdminConfig { + codex_tools: Some("incode".to_string()), + ..Default::default() + }; + assert_eq!( + admin.resolve_codex_tools_with(None), + Resolved::new(CodexTools::Incode, Source::AdminFile) + ); + let parsed: AdminConfig = + serde_json::from_str(r#"{"codex_tools":"incode"}"#).expect("admin.json"); + assert_eq!(parsed, admin, "the admin.json spelling"); + + let typo = AdminConfig { + codex_tools: Some("bridged".to_string()), + ..Default::default() + }; + assert_eq!( + typo.resolve_codex_tools_with(None), + Resolved::new(CodexTools::Own, Source::BuiltIn) + ); + + assert_eq!( + admin.resolve_codex_tools_with(Some("own")), + Resolved::new(CodexTools::Own, Source::Environment) + ); + assert_eq!( + unset.resolve_codex_tools_with(Some(" Incode ")), + Resolved::new(CodexTools::Incode, Source::Environment) + ); + // An unusable value in the environment is no answer: the settings speak. + assert_eq!( + admin.resolve_codex_tools_with(Some("")).source, + Source::AdminFile + ); + } + + /// The report names the choice and who made it. + #[test] + fn the_report_says_whose_tools_codex_runs() { + let _guard = lock(); + clear_env(); + let admin = AdminConfig { + codex_tools: Some("incode".to_string()), + ..Default::default() + }; + let report = admin.report(Path::new("."), None); + assert!( + report.contains("codex tools incode <- admin file"), + "{report}" + ); + clear_env(); + } + /// The engine: `builtin` unless named, the settings name it, the /// environment wins, and a word nobody uses is the built-in default. #[test] diff --git a/src/agent/agy.rs b/src/agent/agy.rs index 6533f07..d4db316 100644 --- a/src/agent/agy.rs +++ b/src/agent/agy.rs @@ -17,6 +17,18 @@ //! //! It showed up as something worse, and more useful: **this agent cannot //! express the policy at all.** See [`AgyBackend::enforces`]. +//! +//! # Why it is not driven over the tool bridge +//! +//! The Claude route, and codex with `codex_tools: "incode"`, run every tool call +//! in incode's toolbox ([`crate::tool_bridge`]). That needs two things of the CLI +//! for ONE run: a way to switch its own tools off, and a way to hand it an MCP +//! server. `agy --help` (1.2.11) has neither — no flag removes or restricts a +//! built-in tool, and MCP servers are added only by `agy mcp add`, which writes +//! the operator's persistent configuration rather than this spawn's. Without the +//! first, the bridge would be one more tool beside `run_command` and +//! `write_to_file`, refusing nothing. So agy keeps its own tools, and the +//! Sentinel stays its check. use std::io::{BufRead, BufReader}; use std::path::PathBuf; diff --git a/src/agent/claude_code.rs b/src/agent/claude_code.rs index 1e98436..18c84d0 100644 --- a/src/agent/claude_code.rs +++ b/src/agent/claude_code.rs @@ -5,7 +5,9 @@ //! `-p` and a structured `--output-format`. The wire shapes below were taken //! from real runs of CLI 2.1.229, not from documentation. -use std::io::{BufRead, BufReader}; +#[cfg(test)] +use std::io::BufRead; +use std::io::BufReader; use std::path::PathBuf; use std::process::{Command, Stdio}; @@ -1125,49 +1127,15 @@ pub fn debug_stream_path() -> Option { .filter(|p| !p.is_empty()) } +use crate::tool_bridge::Incoming; /// What a cancelled turn reports, so the caller can tell it apart from a crash. -pub const CANCELLED: &str = "the turn was cancelled"; - -/// What the turn's loop hears: a line the CLI printed, or a tool call the -/// model made, forwarded by the bridge. -enum Incoming { - Line(String), - ReadFailed(String), - Ended, - Tool(crate::tool_bridge::Request), -} - -/// How long the loop waits for something to arrive before looking at the -/// cancel flag again. A turn that has gone quiet — the model thinking, a long -/// command running — still stops within this of being asked to. -const POLL: std::time::Duration = std::time::Duration::from_millis(100); - -/// Read the CLI's output on its own thread, one line at a time, into the loop. -/// -/// Its own thread because the loop must also answer tool calls, and the CLI -/// is BLOCKED on each of those until it is answered: a loop sitting in a read -/// of the CLI's output would never see the call the CLI is waiting on. -fn pump(reader: R, to: std::sync::mpsc::Sender) { - std::thread::spawn(move || { - for line in reader.lines() { - let message = match line { - Ok(line) => Incoming::Line(line), - Err(e) => { - let _ = to.send(Incoming::ReadFailed(e.to_string())); - return; - } - }; - if to.send(message).is_err() { - return; - } - } - let _ = to.send(Incoming::Ended); - }); -} +/// One wording for every bridged CLI — see [`crate::tool_bridge::CANCELLED`]. +pub use crate::tool_bridge::CANCELLED; /// The turn itself: the CLI's output mapped to events, and every tool call /// the model makes run by `tools`, until the CLI finishes or the turn is -/// stopped. +/// stopped. The loop is the bridge's ([`crate::tool_bridge::drive`]); what a +/// line of THIS CLI means is decided here. fn consume( from: &std::sync::mpsc::Receiver, session: &mut Option, @@ -1176,31 +1144,8 @@ fn consume( tools: &mut crate::toolbox::Toolbox, calls: &mut u64, ) -> Result, AgentError> { - let stopped = || cancel.is_some_and(crate::runtime::cancel::CancelToken::is_cancelled); let mut outcome = None; - - loop { - if stopped() { - return Err(AgentError::new(CANCELLED)); - } - let line = match from.recv_timeout(POLL) { - Ok(Incoming::Line(line)) => line, - Ok(Incoming::Tool(request)) => { - // Numbered per CALL: the list the server asks for first is - // not a call, and must not use up an id. - if matches!(request, crate::tool_bridge::Request::Call { .. }) { - *calls += 1; - } - let id = format!("incode-{calls}"); - crate::tool_bridge::answer(tools, request, &id, stopped(), on_event); - continue; - } - Ok(Incoming::ReadFailed(e)) => { - return Err(AgentError::new(format!("reading agent output: {e}"))) - } - Ok(Incoming::Ended) | Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break, - Err(std::sync::mpsc::RecvTimeoutError::Timeout) => continue, - }; + crate::tool_bridge::drive(from, cancel, tools, calls, on_event, &mut |line, tools| { // Every raw line, when asked for. A turn that fails for a reason the // harness cannot explain — "stopped without finishing: stop_sequence" — // is unanswerable without the bytes the agent actually sent, and @@ -1216,10 +1161,11 @@ fn consume( } } if line.trim().is_empty() { - continue; + return Vec::new(); } - for event in map_line(&line, &mut outcome) { - if let AgentEvent::SessionStarted { session_id, .. } = &event { + let events = map_line(&line, &mut outcome); + for event in &events { + if let AgentEvent::SessionStarted { session_id, .. } = event { if !session_id.is_empty() { *session = Some(session_id.clone()); // The engine files its cards and backups under the @@ -1227,10 +1173,9 @@ fn consume( tools.set_session(session_id); } } - on_event(&event); } - } - + events + })?; Ok(outcome) } @@ -1506,21 +1451,12 @@ impl ClaudeCodeBackend { // process answers for the whole turn. Without the bridge there would // be no tools but the CLI's, so a bridge that cannot open stops the // turn rather than falling back to them. - let exe = std::env::current_exe().map_err(|e| { - AgentError::new(format!( - "incode could not name its own binary, so it cannot offer its tools; \ - the turn was not started: {e}" - )) - })?; - let (to_loop, from_cli) = std::sync::mpsc::channel(); - let bridge = - crate::tool_bridge::Bridge::open(to_loop.clone(), Incoming::Tool, self.cancel.clone()) - .map_err(|e| { - AgentError::new(format!( - "incode could not open the channel its tools run over, so the turn \ - was not started: {e}" - )) - })?; + let crate::tool_bridge::Turn { + exe, + bridge, + to: to_loop, + from: from_cli, + } = crate::tool_bridge::Turn::open(self.cancel.clone())?; let (servers, allowed) = servers_for(&exe); let mut cmd = self.command( @@ -1618,7 +1554,7 @@ impl ClaudeCodeBackend { // blocks on the write and never exits. See `stderr_tail`. let stderr = crate::agent::stderr_tail::StderrTail::capture(child.stderr.take()); - pump(BufReader::new(stdout), to_loop); + crate::tool_bridge::pump(BufReader::new(stdout), to_loop); let outcome = consume( &from_cli, &mut self.session_id, diff --git a/src/agent/codex.rs b/src/agent/codex.rs index 3929025..dd09571 100644 --- a/src/agent/codex.rs +++ b/src/agent/codex.rs @@ -22,15 +22,193 @@ //! Like Antigravity, Codex CLI does not provide external flags to disallow specific tools //! or protected file paths. Protection is derived from [`crate::guards::Sentinel`] which //! detects changes after the turn. See [`CodexBackend::enforces`]. +//! +//! # Bridged: incode's tools instead of codex's ([`CodexTools::Incode`]) +//! +//! Opt-in (`codex_tools: "incode"` in admin.json, or `INCODE_CODEX_TOOLS=incode`), +//! because no turn with a REAL model has been run this way yet. When on, codex is +//! driven the way the Claude route is ([`crate::tool_bridge`]): its own tools are +//! switched off by config, it is handed ONE MCP server — `incode --tool-server` — +//! and every call the model makes comes back to this process and runs through the +//! toolbox. What each override does was read from codex's source at +//! `rust-v0.163.0`, checked against `rust-v0.153.4` and `rust-v0.145.0`, and +//! measured on the 0.163.0 binary against a stand-in Responses endpoint +//! (`model_providers..base_url`) that recorded what codex sent: +//! +//! - `gpt-5.5`, own tools (control): `exec_command, write_stdin, +//! request_user_input, apply_patch, view_image, get_goal, create_goal, +//! update_goal, tool_search, web_search`; +//! - `gpt-5.5`, with [`MODEL_ONLY_OVERRIDES`] and the bridge's registration: +//! `list_mcp_resources, list_mcp_resource_templates, read_mcp_resource, +//! apply_patch, mcp__incode{…}`; +//! - `gpt-5.6-terra`, a code-mode model: one `exec` tool (JavaScript in an +//! isolate with no file system or network, calling nested tools) whose nested +//! tools were `apply_patch`, the three resource readers and every +//! `mcp__incode__*`, plus `wait` — and, before `agents.enabled=false`, a +//! `collaboration` namespace (`spawn_agent`, …). +//! +//! Driven end to end through `incode -t` with that endpoint scripted to call +//! `mcp__incode` `Write`: codex started `incode --tool-server`, the call ran in +//! incode's toolbox (trace `tool Write (change)`), the file was written, the event +//! was incode's (`incode-1`), and the model was handed the toolbox's answer. +//! +//! `apply_patch` cannot be switched off: it is offered when the MODEL CATALOGUE +//! says so (`model_info.apply_patch_tool_type`, `core/src/tools/spec_plan.rs`), not +//! by any config key or feature. It is neutralised instead: with +//! `sandbox_mode="read-only"` and `approval_policy="never"`, codex's +//! `assess_patch_safety` (`core/src/safety.rs`) finds no writable root and REJECTS +//! the patch before it runs, on every platform, sandbox or not. The three +//! `*_mcp_resource*` tools only read resources the MCP servers offer, and the only +//! server is incode's. use std::io::{BufRead, BufReader}; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use serde::Deserialize; use super::{AgentBackend, AgentError, AgentEvent, TurnOutcome}; +/// Whose tools a codex model runs, from admin.json's `codex_tools` or +/// [`CODEX_TOOLS_ENV`] — see [`crate::admin::AdminConfig::resolve_codex_tools`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum CodexTools { + /// Codex's own (`exec_command`, `apply_patch`, …), watched afterwards by + /// the Sentinel. The default until a live turn has proved the other. + #[default] + Own, + /// incode's, through the tool bridge: codex is a model and nothing else. + Incode, +} + +impl CodexTools { + /// `own` or `incode`, ignoring case; anything else is no answer. + #[must_use] + pub fn parse(raw: &str) -> Option { + match raw.trim().to_ascii_lowercase().as_str() { + "own" => Some(Self::Own), + "incode" => Some(Self::Incode), + _ => None, + } + } + + #[must_use] + pub fn as_str(self) -> &'static str { + match self { + Self::Own => "own", + Self::Incode => "incode", + } + } +} + +/// The variable that wins over admin.json's `codex_tools`. +pub const CODEX_TOOLS_ENV: &str = "INCODE_CODEX_TOOLS"; + +/// Codex's own hooks file off, on both spawn paths: incode fires the memory +/// engine's lifecycle itself, and codex firing it too would record each +/// session twice. Proved on 0.145.0 and 0.153.4, `exec` and `exec resume`: +/// with a probe hooks file (trust bypassed), hooks on recorded `session-start` +/// and `user-prompt`; `--disable hooks` recorded nothing, and codex no longer +/// read `~/.codex/hooks.json`. +const HOOKS_OFF: [&str; 2] = ["--disable", "hooks"]; + +/// The `-c` overrides that make codex a model and nothing else, on the +/// bridged route. Each key is from codex's own config types (`ConfigToml`, +/// `ToolsToml`, `features/src/lib.rs`), present in 0.145.0, 0.153.4 and +/// 0.163.0 unless said; a key a version does not know is ignored by it, not +/// refused (measured on 0.163.0 with an invented feature name), so a typo +/// here would do nothing — which is why each was watched leave the tool list. +/// +/// - `features.shell_tool=false`: no `exec_command` / `write_stdin` / `shell`. +/// - `features.view_image=false`: no `view_image` (the key is 0.153+; 0.145 +/// has no switch). +/// - `web_search="disabled"`: no hosted `web_search`. +/// - `features.goals=false`: no `get_goal` / `create_goal` / `update_goal`. +/// - `tools.experimental_request_user_input.enabled=false`: no +/// `request_user_input` — incode asks the person itself. +/// - `agents.enabled=false`: no sub-agents of codex's own. Needed beside +/// `features.multi_agent=false`, which only covers models the catalogue +/// leaves to the features: measured on 0.163.0, `gpt-5.6-terra` (whose +/// catalogue entry names multi-agent v2) was still offered +/// `collaboration.spawn_agent` & co. with the feature off. `agents.enabled` +/// wins over the catalogue (`Config::multi_agent_version_override`). +/// - `features.multi_agent=false`, `features.apps=false`, +/// `features.plugins=false`, `features.browser_use=false`, +/// `features.computer_use=false`, `features.image_generation=false`: no +/// sub-agents, connectors, plugin tools, browser, desktop or image tools of +/// codex's own; incode's toolbox has its own sub-agent, browser and desktop. +/// - `sandbox_mode="read-only"`, `approval_policy="never"`: what is left of +/// codex's own reach writes nothing — `apply_patch` is rejected before it +/// runs (see the module notes) — and nothing waits on a person. +pub const MODEL_ONLY_OVERRIDES: [&str; 14] = [ + "features.shell_tool=false", + "features.view_image=false", + "web_search=\"disabled\"", + "features.goals=false", + "tools.experimental_request_user_input.enabled=false", + "agents.enabled=false", + "features.multi_agent=false", + "features.apps=false", + "features.plugins=false", + "features.browser_use=false", + "features.computer_use=false", + "features.image_generation=false", + "sandbox_mode=\"read-only\"", + "approval_policy=\"never\"", +]; + +/// Codex's user config (`$CODEX_HOME/config.toml`) is not read on the +/// bridged route — the counterpart of the Claude route's +/// `--setting-sources ""`: an MCP server the operator registered there would +/// be a tool incode cannot refuse. Auth still comes from `CODEX_HOME` +/// (`codex exec --help`). A global flag, taken by `exec resume` too. +const IGNORE_USER_CONFIG: &str = "--ignore-user-config"; + +/// The bridge's registration, as `-c` overrides: incode's tool server and +/// nothing else. +/// +/// - `env_vars`: codex starts a stdio MCP server with ONLY a short list of +/// variables (`HOME`, `PATH`, …; `rmcp-client/src/utils.rs` +/// `create_env_for_mcp_server`) plus the ones named here. Measured on +/// 0.163.0: a stand-in server received the two named and NOT a third set +/// beside them. The values never reach the argv. +/// - `default_tools_approval_mode="approve"`: the one mode in which codex never +/// asks before an MCP call (`requires_mcp_tool_approval_for_mode`); `auto` +/// asks for any tool not marked read-only, and with `approval_policy="never"` +/// that ask is a refusal. Whether a call may run is incode's decision. +/// - `required=true`: a server that fails to start fails the turn, rather than +/// the model running on with no tools. +/// - `tool_timeout_sec`: codex gives up on an MCP call after 300 s by default; +/// incode may still be asking the person, or running a long command. +/// - `omit_tools_from=["deferred"]`: the tools are listed to the model +/// directly. Without it codex hid them behind its `tool_search` (measured); +/// 0.145.0 has no such key, and its model finds them through `tool_search`. +fn bridge_registration(exe: &Path) -> Vec { + let key = crate::tool_bridge::CLIENT_KEY; + // TOML basic strings take backslash escapes: a Windows path must have its + // separators doubled — see `desktop::mcp::codex_config_overrides`. + let exe = exe.to_string_lossy().replace('\\', "\\\\"); + vec![ + format!("mcp_servers.{key}.command=\"{exe}\""), + format!( + "mcp_servers.{key}.args=[\"{}\"]", + crate::tool_bridge::SERVER_FLAG + ), + format!( + "mcp_servers.{key}.env_vars=[\"{}\",\"{}\"]", + crate::tool_bridge::ADDR_ENV, + crate::tool_bridge::TOKEN_ENV + ), + format!("mcp_servers.{key}.default_tools_approval_mode=\"approve\""), + format!("mcp_servers.{key}.required=true"), + format!( + "mcp_servers.{key}.tool_timeout_sec={}", + crate::tool_bridge::REPLY_BOUND_SECS + ), + format!("mcp_servers.{key}.omit_tools_from=[\"deferred\"]"), + ] +} + // --------------------------------------------------------------------------- // Wire types — measured from real Codex CLI runs // --------------------------------------------------------------------------- @@ -46,10 +224,7 @@ enum Wire { #[serde(rename = "turn.started")] TurnStarted, #[serde(rename = "item.started")] - ItemStarted { - #[allow(dead_code)] - item: WireItem, - }, + ItemStarted { item: WireItem }, #[serde(rename = "item.completed")] ItemCompleted { item: WireItem }, #[serde(rename = "turn.completed")] @@ -85,7 +260,6 @@ struct WireItem { aggregated_output: Option, #[serde(default)] exit_code: Option, - #[allow(dead_code)] #[serde(default)] server: Option, #[serde(default)] @@ -151,6 +325,16 @@ pub struct CodexBackend { images: Vec, /// Where this turn's pictures were written, while its command is built. image_files: Vec, + /// Every tool the model has, run HERE — on the bridged route only + /// ([`CodexTools::Incode`]). `None` is codex running its own tools, and + /// then nothing below this line is used. + tools: Option, + /// How many calls the toolbox has run for this backend, so each gets an + /// id no earlier turn used. + calls: u64, + /// The binary codex is told to start as the tool server, when not this + /// one — a test's stand-in. `None` is this process's own binary. + tool_server: Option, } /// A turn's pictures as files for `--image`, removed when the turn is over. @@ -201,9 +385,94 @@ impl CodexBackend { cancel: None, images: Vec::new(), image_files: Vec::new(), + tools: None, + calls: 0, + tool_server: None, } } + /// Run this model's tool calls in incode's toolbox, through the bridge, + /// with codex's own tools switched off — or not, for [`CodexTools::Own`]. + /// + /// Set before the toolbox builders below, which do nothing without it: + /// codex's own tools are not incode's to configure. + #[must_use] + pub fn with_tools(mut self, tools: CodexTools) -> Self { + self.tools = match tools { + // The filtered environment for the shell tool, as on the Claude + // route: a command the model chose must not inherit this + // process's credentials. No sub-agent CLI is named: the toolbox + // drives one as the Claude CLI, which codex is not. + CodexTools::Incode => Some(crate::toolbox::Toolbox::new(&self.workspace, true)), + CodexTools::Own => None, + }; + self + } + + /// The toolbox, when this model's tools are incode's. + fn toolbox(&mut self) -> Option<&mut crate::toolbox::Toolbox> { + self.tools.as_mut() + } + + /// Ask the memory engine before every tool call this model makes — on the + /// bridged route, where incode runs them. + #[must_use] + pub fn with_engine(mut self, engine: Option) -> Self { + self.tools = self.tools.map(|t| t.with_engine(engine)); + self + } + + /// Announce each file write to the engine's edit check — bridged only. + #[must_use] + pub fn with_code_edits(mut self, edits: Option) -> Self { + self.tools = self.tools.map(|t| t.with_code_edits(edits)); + self + } + + /// Run the operator's own pre- and post-tool commands around every call — + /// bridged only. See [`crate::hooks`]. + #[must_use] + pub fn with_operator_hooks(mut self, hooks: Option) -> Self { + self.tools = self.tools.map(|t| t.with_operator_hooks(hooks)); + self + } + + /// Confine this model's shell commands to `policy` — bridged only: codex's + /// own shell is off there, and incode's runs under incode's sandbox. + #[must_use] + pub fn with_sandbox(mut self, policy: crate::sandbox::SandboxPolicy) -> Self { + self.tools = self.tools.map(|t| t.with_sandbox(policy)); + self + } + + /// Offer the model the desktop tools, run through incode's toolbox — + /// bridged only; codex's own route registers the desktop server instead + /// ([`Self::with_mcp_overrides`]). + #[must_use] + pub fn with_desktop(mut self, setup: crate::toolbox::DesktopSetup) -> Self { + if let Some(tools) = self.toolbox() { + tools.enable_desktop(setup); + } + self + } + + /// Offer the model only `tools`, when given — a user-defined sub-agent's + /// allow-list, refused by the toolbox. Bridged only. + #[must_use] + pub fn with_tool_allowlist(mut self, allowed: Option>) -> Self { + if let (Some(tools), Some(allowed)) = (self.toolbox(), allowed) { + tools.restrict_tools(allowed); + } + self + } + + /// Have codex start `exe` as the tool server instead of this binary. + #[cfg(test)] + fn with_tool_server(mut self, exe: PathBuf) -> Self { + self.tool_server = Some(exe); + self + } + /// Hand this agent an MCP server, as `-c key=value` overrides. /// /// Build them with [`crate::desktop::mcp::codex_config_overrides`] so the @@ -252,14 +521,19 @@ impl CodexBackend { }) } + /// The binary codex is told to start as the tool server. + fn server_exe(&self) -> PathBuf { + self.tool_server + .clone() + .or_else(|| std::env::current_exe().ok()) + .unwrap_or_else(|| PathBuf::from("incode")) + } + + /// The command for one turn, on whichever route this backend is on. fn command(&self, prompt: &str) -> Command { - /// Codex's own hooks file off, on both spawn paths: incode fires the - /// memory engine's lifecycle itself, and codex firing it too would - /// record each session twice. Proved on 0.145.0 and 0.153.4, `exec` - /// and `exec resume`: with a probe hooks file (trust bypassed), hooks - /// on recorded `session-start` and `user-prompt`; `--disable hooks` - /// recorded nothing, and codex no longer read `~/.codex/hooks.json`. - const HOOKS_OFF: [&str; 2] = ["--disable", "hooks"]; + if self.tools.is_some() { + return self.bridged_command(prompt, &self.server_exe()); + } let mut cmd = Command::new(&self.binary); crate::agent::parent_session::detach_from_parent_session(&mut cmd); cmd.current_dir(&self.workspace); @@ -330,6 +604,58 @@ impl CodexBackend { cmd.stdin(Stdio::null()); cmd } + + /// The command for one bridged turn: codex as a model only, with `exe` + /// started as its one MCP server. The bridge's address and token are + /// added by the caller, which holds the bridge. + /// + /// Not handed over, because incode decides them in its toolbox: the + /// permission mode (`-s`), the added roots (`--add-dir`), the bypass + /// flag, the team and desktop servers ([`Self::with_mcp_overrides`] — both + /// are toolbox tools here) and the memory server's approval override (the + /// server lives in the user config this route does not read). + fn bridged_command(&self, prompt: &str, exe: &Path) -> Command { + let mut cmd = Command::new(&self.binary); + crate::agent::parent_session::detach_from_parent_session(&mut cmd); + cmd.current_dir(&self.workspace); + cmd.arg("exec"); + if self.thread_id.is_some() { + cmd.arg("resume"); + } + // The pictures FIRST, as on the other route: `--image` takes several + // values, and the next flag is what ends the list. + for file in &self.image_files { + cmd.arg("--image").arg(file); + } + cmd.arg("--skip-git-repo-check"); + cmd.arg("--json"); + cmd.args(HOOKS_OFF); + cmd.arg(IGNORE_USER_CONFIG); + for override_ in MODEL_ONLY_OVERRIDES + .iter() + .map(|o| (*o).to_string()) + .chain(bridge_registration(exe)) + { + cmd.arg("-c").arg(override_); + } + if let Some(model) = &self.model { + cmd.arg("-m").arg(model); + } + match &self.thread_id { + // `exec resume` takes no `-C`: the thread carries its directory. + Some(tid) => { + cmd.arg(tid); + } + None => { + cmd.arg("-C").arg(&self.workspace); + } + } + cmd.arg(prompt); + // No team identity in the environment: the team channel's tools are + // the toolbox's on this route, and it is told who speaks. + cmd.stdin(Stdio::null()); + cmd + } } impl AgentBackend for CodexBackend { @@ -337,9 +663,20 @@ impl AgentBackend for CodexBackend { "codex" } - /// Neither half. Measured from the CLI surface: no per-tool deny flag exists, - /// so Sentinel detection covers file writes after the fact. + /// On its own tools, neither half. Measured from the CLI surface: no + /// per-tool deny flag exists, so Sentinel detection covers file writes + /// after the fact. + /// + /// Bridged, both — by incode's toolbox, as on the Claude route: every + /// write the model can make is a toolbox call refused before it runs, and + /// its only sub-agent tool is incode's, which stops at its depth limit. + /// What codex keeps of its own cannot do either: `apply_patch` is rejected + /// unrun under read-only + never, and its sub-agent tools are off + /// (`features.multi_agent=false`) — both measured; see the module notes. fn enforces(&self) -> crate::guards::Enforcement { + if self.tools.is_some() { + return crate::guards::Enforcement::EVERYTHING; + } crate::guards::Enforcement::NOTHING } @@ -349,11 +686,21 @@ impl AgentBackend for CodexBackend { || crate::agent::moves_the_work(&outcome.failure()) } + /// Bridged, the team channel's tools are the toolbox's, so the toolbox is + /// who speaks; otherwise the team server reads it from the spawn. fn set_team_identity(&mut self, role: &str) { - self.team_identity = Some(role.to_string()); + match self.toolbox() { + Some(tools) => tools.set_team_identity(role), + None => self.team_identity = Some(role.to_string()), + } } fn mcp_config(&self) -> Option { + // Bridged, the one server codex is handed is the bridge — the binary + // is the one each turn names, so this is what the next turn sends. + if self.tools.is_some() { + return Some(bridge_registration(&self.server_exe()).join("\n")); + } // EVERY override, not the first. Returning one of them read as the // whole registration, which was true while there was a single server // and became a lie the moment there were two — the second was simply @@ -364,6 +711,76 @@ impl AgentBackend for CodexBackend { Some(self.mcp_overrides.join("\n")) } + // What follows reaches the toolbox, and so means something only on the + // bridged route. On codex's own tools each is the trait's default: there + // is no call of incode's to ask about, record or watch. + + /// Bridged: codex's own tools are switched off and every call comes back + /// through the bridge to this backend's toolbox. + fn runs_tools_here(&self) -> bool { + self.tools.is_some() + } + + fn set_prompter(&mut self, prompter: std::sync::Arc) { + if let Some(tools) = self.toolbox() { + tools.set_prompter(prompter); + } + } + + fn set_owner(&mut self, owner: std::sync::Arc) { + if let Some(tools) = self.toolbox() { + tools.set_owner(owner); + } + } + + fn share_allowed_writes(&mut self, record: std::sync::Arc) { + if let Some(tools) = self.toolbox() { + tools.share_allowed_writes(record); + } + } + + fn share_session_tools(&mut self, state: std::sync::Arc) { + if let Some(tools) = self.toolbox() { + tools.share_session(state); + } + } + + fn set_watch(&mut self, watch: std::sync::Arc) { + if let Some(tools) = self.toolbox() { + tools.set_watch(watch); + } + } + + /// The engine hears incode's session id with every call, not codex's + /// thread id: incode's is the one its session events carry too. + fn set_memory_session(&mut self, session: &str) { + if let Some(tools) = self.toolbox() { + tools.pin_session(session); + } + } + + fn end_code_edits(&mut self) { + if let Some(tools) = self.toolbox() { + tools.end_code_edits(); + } + } + + fn children(&self) -> Vec<(String, String)> { + self.tools.as_ref().map_or_else(Vec::new, |tools| { + tools + .children() + .into_iter() + .map(|c| (c.session, c.title)) + .collect() + }) + } + + fn offered_tools(&self) -> Vec { + self.tools + .as_ref() + .map_or_else(Vec::new, crate::toolbox::Toolbox::names) + } + fn system_context(&self) -> &[String] { &self.system_context } @@ -406,11 +823,24 @@ impl AgentBackend for CodexBackend { self.model = candidates.iter().find(|c| self.serves(c)).cloned(); } + /// Bridged, incode's toolbox does the writing, so it is the toolbox that + /// must reach the added roots — under the same guards. Codex is not told: + /// its own sandbox is read-only there. fn set_extra_dirs(&mut self, dirs: Vec) { + if let Some(tools) = self.toolbox() { + tools.set_extra_dirs(dirs.clone()); + } self.extra_dirs = dirs; } + /// Bridged, decided by incode's toolbox and never handed to codex: its + /// own sandbox stays read-only whatever the mode, because it runs nothing + /// that writes. A spelling nobody recognises lands on read-only. fn set_permission_mode(&mut self, mode: &str) { + if let Some(tools) = self.toolbox() { + tools.set_permission_mode(crate::permissions::PermissionMode::from_agent_mode(mode)); + return; + } self.sandbox = match mode { "plan" | "read-only" => Some("read-only".to_string()), "acceptEdits" | "accept-edits" | "workspace-write" => { @@ -421,6 +851,9 @@ impl AgentBackend for CodexBackend { } fn set_cancel(&mut self, token: crate::runtime::cancel::CancelToken) { + if let Some(tools) = self.toolbox() { + tools.set_cancel(token.clone()); + } self.cancel = Some(token); } @@ -442,6 +875,21 @@ impl AgentBackend for CodexBackend { let pictures = ImageFiles::write(&std::mem::take(&mut self.images)).map_err(AgentError::new)?; self.image_files.clone_from(&pictures.paths); + if self.tools.is_some() { + // The turn's channel first: the command names the binary it was + // opened for, and a channel that cannot open starts nothing. + let turn = match crate::tool_bridge::Turn::open(self.cancel.clone()) { + Ok(turn) => turn, + Err(e) => { + self.image_files.clear(); + return Err(e); + } + }; + let exe = self.tool_server.clone().unwrap_or_else(|| turn.exe.clone()); + let command = self.bridged_command(&sent, &exe); + self.image_files.clear(); + return self.run_bridged(command, turn, on_event); + } let mut command = self.command(&sent); self.image_files.clear(); crate::agent::process_tree::prepare(&mut command); @@ -459,8 +907,7 @@ impl AgentBackend for CodexBackend { let stderr = crate::agent::stderr_tail::StderrTail::capture(child.stderr.take()); - let mut outcome: Option = None; - let mut usage = crate::runtime::usage::TokenUsage::default(); + let mut reading = Reading::new(&mut self.thread_id, self.model.clone(), false); for line in BufReader::new(stdout).lines() { if let Some(token) = &self.cancel { @@ -470,146 +917,11 @@ impl AgentBackend for CodexBackend { } } let Ok(line) = line else { break }; - let Ok(wire) = serde_json::from_str::(&line) else { - continue; - }; - match wire { - Wire::ThreadStarted { thread_id } => { - self.thread_id = Some(thread_id.clone()); - on_event(&AgentEvent::SessionStarted { - session_id: thread_id, - model: self.model.clone().unwrap_or_default(), - }); - } - Wire::TurnStarted => {} - Wire::ItemStarted { item } => match item.item_type.as_str() { - "command_execution" => { - if let Some(cmd) = item.command { - on_event(&AgentEvent::ToolUse { - id: item.id, - name: "Bash".to_string(), - input: cmd, - }); - } - } - "mcp_tool_call" => { - if let Some(tool) = item.tool { - let input = item - .arguments - .as_ref() - .map(|a| a.to_string()) - .unwrap_or_default(); - on_event(&AgentEvent::ToolUse { - id: item.id, - name: tool, - input, - }); - } - } - _ => {} - }, - Wire::ItemCompleted { item } => match item.item_type.as_str() { - "agent_message" => { - if let Some(text) = item.text { - if !text.trim().is_empty() { - on_event(&AgentEvent::TextDelta(text.clone())); - on_event(&AgentEvent::Text(text)); - } - } - } - "command_execution" => { - if let Some(cmd) = item.command { - on_event(&AgentEvent::ToolUse { - id: item.id.clone(), - name: "Bash".to_string(), - input: cmd, - }); - on_event(&AgentEvent::ToolResult { - id: item.id, - output: item.aggregated_output.unwrap_or_default(), - is_error: item.exit_code.unwrap_or(0) != 0, - }); - } - } - "mcp_tool_call" => { - if let Some(tool) = item.tool { - let input = item - .arguments - .as_ref() - .map(|a| a.to_string()) - .unwrap_or_default(); - on_event(&AgentEvent::ToolUse { - id: item.id.clone(), - name: tool, - input, - }); - let mut output = extract_mcp_output(&item.result); - if output.is_empty() { - if let Some(err) = &item.error { - output = err - .as_str() - .map(|s| s.to_string()) - .unwrap_or_else(|| parse_error_detail(&err.to_string())); - } - } - let is_error = - item.error.is_some() || item.status.as_deref() == Some("failed"); - on_event(&AgentEvent::ToolResult { - id: item.id, - output, - is_error, - }); - } - } - "error" => { - if let Some(msg) = item.text { - crate::trace!("agent", "codex item error: {msg}"); - } - } - _ => {} - }, - Wire::TurnCompleted { usage: u } => { - if let Some(u) = &u { - usage = to_usage(u); - } - let sid = self.thread_id.clone().unwrap_or_default(); - outcome = Some(TurnOutcome { - session_id: sid, - stop_reason: "SUCCESS".to_string(), - is_error: false, - detail: None, - served_by: self.model.clone().into_iter().collect(), - }); - } - Wire::TurnFailed { error } => { - let err_msg = error - .map(|e| parse_error_detail(&e.message)) - .unwrap_or_else(|| "turn failed".to_string()); - let sid = self.thread_id.clone().unwrap_or_default(); - outcome = Some(TurnOutcome { - session_id: sid, - stop_reason: "ERROR".to_string(), - is_error: true, - detail: Some(err_msg), - served_by: self.model.clone().into_iter().collect(), - }); - } - Wire::Error { message } => { - let err_msg = message - .map(|m| parse_error_detail(&m)) - .unwrap_or_else(|| "codex error".to_string()); - let sid = self.thread_id.clone().unwrap_or_default(); - outcome = Some(TurnOutcome { - session_id: sid, - stop_reason: "ERROR".to_string(), - is_error: true, - detail: Some(err_msg), - served_by: self.model.clone().into_iter().collect(), - }); - } - Wire::Other => {} + for event in reading.line(&line) { + on_event(&event); } } + let (outcome, usage) = reading.finish(); on_event(&AgentEvent::Usage { input_tokens: usage.input_tokens, @@ -639,6 +951,289 @@ impl AgentBackend for CodexBackend { } } +impl CodexBackend { + /// One bridged turn: `command` spawned with the bridge's address and token + /// in its environment, its tool calls answered by the toolbox, its stream + /// read to the end — the Claude route's loop ([`crate::tool_bridge::drive`]) + /// over codex's lines. + fn run_bridged( + &mut self, + mut command: Command, + turn: crate::tool_bridge::Turn, + on_event: &mut dyn FnMut(&AgentEvent), + ) -> Result { + let crate::tool_bridge::Turn { + bridge, to, from, .. + } = turn; + // How the tool server finds this process: codex's environment, which + // it passes on to the server by the names `env_vars` lists — never + // its argv. + for (key, value) in bridge.env() { + command.env(key, value); + } + crate::agent::process_tree::prepare(&mut command); + let mut child = command + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .map_err(|e| AgentError::new(format!("could not start `{}`: {e}", self.binary)))?; + let tree = crate::agent::process_tree::Tree::adopt(&child); + let stdout = child + .stdout + .take() + .ok_or_else(|| AgentError::new("the agent produced no output stream"))?; + let stderr = crate::agent::stderr_tail::StderrTail::capture(child.stderr.take()); + crate::tool_bridge::pump(BufReader::new(stdout), to); + + let Self { + tools, + calls, + thread_id, + model, + cancel, + .. + } = self; + let tools = tools + .as_mut() + .ok_or_else(|| AgentError::new("a bridged turn needs incode's toolbox"))?; + let mut reading = Reading::new(thread_id, model.clone(), true); + let driven = crate::tool_bridge::drive( + &from, + cancel.as_ref(), + tools, + calls, + on_event, + &mut |line, tools| { + let events = reading.line(&line); + for event in &events { + if let AgentEvent::SessionStarted { session_id, .. } = event { + // The engine files its cards under the conversation. + tools.set_session(session_id); + } + } + events + }, + ); + let (outcome, usage) = reading.finish(); + // Closed as soon as the loop is done: a call that arrives from here on + // is refused rather than left waiting on a loop that is gone. + drop(bridge); + if let Err(e) = driven { + // Whatever happened, codex must not outlive the turn — nor + // whatever it started. + tree.kill(&mut child); + return Err(e); + } + + on_event(&AgentEvent::Usage { + input_tokens: usage.input_tokens, + output_tokens: usage.output_tokens, + cache_creation_tokens: usage.cache_creation_input_tokens, + cache_read_tokens: usage.cache_read_input_tokens, + }); + let status = child + .wait() + .map_err(|e| AgentError::new(format!("the agent did not exit cleanly: {e}")))?; + outcome.ok_or_else(|| { + let stderr_output = stderr.finish(); + let detail = if stderr_output.is_empty() { + String::new() + } else { + format!(": {stderr_output}") + }; + AgentError::new(format!( + "the agent produced no result line (exit {}){detail}", + status.code().unwrap_or(-1) + )) + }) + } +} + +/// What one turn of `codex exec --json` has said so far, and what each line +/// means — the same reading on both routes. +struct Reading<'a> { + /// The backend's own: a thread that started is resumable even if the + /// turn is then stopped. + thread_id: &'a mut Option, + model: Option, + outcome: Option, + usage: crate::runtime::usage::TokenUsage, + /// Bridged: a call to incode's own server is shown by the bridge, as + /// incode ran it, under incode's id; codex's record of the same call is + /// not shown a second time. + bridged: bool, +} + +impl<'a> Reading<'a> { + fn new(thread_id: &'a mut Option, model: Option, bridged: bool) -> Self { + Self { + thread_id, + model, + outcome: None, + usage: crate::runtime::usage::TokenUsage::default(), + bridged, + } + } + + /// The turn's result, if it reported one, and what it cost. + fn finish(self) -> (Option, crate::runtime::usage::TokenUsage) { + (self.outcome, self.usage) + } + + /// Whether an item is codex's own echo of a call the bridge already showed. + fn shown_by_the_bridge(&self, item: &WireItem) -> bool { + self.bridged && item.server.as_deref() == Some(crate::tool_bridge::CLIENT_KEY) + } + + /// The events one line stands for. A line that is not one of codex's is + /// nothing. + fn line(&mut self, line: &str) -> Vec { + let Ok(wire) = serde_json::from_str::(line) else { + return Vec::new(); + }; + let mut events = Vec::new(); + match wire { + Wire::ThreadStarted { thread_id } => { + *self.thread_id = Some(thread_id.clone()); + events.push(AgentEvent::SessionStarted { + session_id: thread_id, + model: self.model.clone().unwrap_or_default(), + }); + } + Wire::TurnStarted => {} + Wire::ItemStarted { item } if self.shown_by_the_bridge(&item) => {} + Wire::ItemStarted { item } => match item.item_type.as_str() { + "command_execution" => { + if let Some(cmd) = item.command { + events.push(AgentEvent::ToolUse { + id: item.id, + name: "Bash".to_string(), + input: cmd, + }); + } + } + "mcp_tool_call" => { + if let Some(tool) = item.tool { + let input = item + .arguments + .as_ref() + .map(|a| a.to_string()) + .unwrap_or_default(); + events.push(AgentEvent::ToolUse { + id: item.id, + name: tool, + input, + }); + } + } + _ => {} + }, + Wire::ItemCompleted { item } if self.shown_by_the_bridge(&item) => {} + Wire::ItemCompleted { item } => match item.item_type.as_str() { + "agent_message" => { + if let Some(text) = item.text { + if !text.trim().is_empty() { + events.push(AgentEvent::TextDelta(text.clone())); + events.push(AgentEvent::Text(text)); + } + } + } + "command_execution" => { + if let Some(cmd) = item.command { + events.push(AgentEvent::ToolUse { + id: item.id.clone(), + name: "Bash".to_string(), + input: cmd, + }); + events.push(AgentEvent::ToolResult { + id: item.id, + output: item.aggregated_output.unwrap_or_default(), + is_error: item.exit_code.unwrap_or(0) != 0, + }); + } + } + "mcp_tool_call" => { + if let Some(tool) = item.tool { + let input = item + .arguments + .as_ref() + .map(|a| a.to_string()) + .unwrap_or_default(); + events.push(AgentEvent::ToolUse { + id: item.id.clone(), + name: tool, + input, + }); + let mut output = extract_mcp_output(&item.result); + if output.is_empty() { + if let Some(err) = &item.error { + output = err + .as_str() + .map(|s| s.to_string()) + .unwrap_or_else(|| parse_error_detail(&err.to_string())); + } + } + let is_error = + item.error.is_some() || item.status.as_deref() == Some("failed"); + events.push(AgentEvent::ToolResult { + id: item.id, + output, + is_error, + }); + } + } + "error" => { + if let Some(msg) = item.text { + crate::trace!("agent", "codex item error: {msg}"); + } + } + _ => {} + }, + Wire::TurnCompleted { usage: u } => { + if let Some(u) = &u { + self.usage = to_usage(u); + } + let sid = self.thread_id.clone().unwrap_or_default(); + self.outcome = Some(TurnOutcome { + session_id: sid, + stop_reason: "SUCCESS".to_string(), + is_error: false, + detail: None, + served_by: self.model.clone().into_iter().collect(), + }); + } + Wire::TurnFailed { error } => { + let err_msg = error + .map(|e| parse_error_detail(&e.message)) + .unwrap_or_else(|| "turn failed".to_string()); + let sid = self.thread_id.clone().unwrap_or_default(); + self.outcome = Some(TurnOutcome { + session_id: sid, + stop_reason: "ERROR".to_string(), + is_error: true, + detail: Some(err_msg), + served_by: self.model.clone().into_iter().collect(), + }); + } + Wire::Error { message } => { + let err_msg = message + .map(|m| parse_error_detail(&m)) + .unwrap_or_else(|| "codex error".to_string()); + let sid = self.thread_id.clone().unwrap_or_default(); + self.outcome = Some(TurnOutcome { + session_id: sid, + stop_reason: "ERROR".to_string(), + is_error: true, + detail: Some(err_msg), + served_by: self.model.clone().into_iter().collect(), + }); + } + Wire::Other => {} + } + events + } +} + /// Extract readable text from MCP tool result JSON. fn extract_mcp_output(res: &Option) -> String { let Some(val) = res else { @@ -1013,5 +1608,574 @@ mod tests { let mut resumed = CodexBackend::new(PathBuf::from(".")); resumed.thread_id = Some("thread-abc".to_string()); assert!(off(&resumed)); + for mut backend in [fresh, resumed] { + backend = backend.with_tools(CodexTools::Incode); + assert!(off(&backend), "bridged too"); + } + } + + // ----------------------------------------------------------------------- + // Bridged: codex as a model, incode's toolbox as its tools. + // ----------------------------------------------------------------------- + + fn args_of(cmd: &Command) -> Vec { + cmd.get_args() + .map(|a| a.to_string_lossy().into_owned()) + .collect() + } + + /// Every `-c` value on an argv. + fn overrides_in(args: &[String]) -> Vec { + args.windows(2) + .filter(|w| w[0] == "-c") + .map(|w| w[1].clone()) + .collect() + } + + /// **CODEX ON ITS OWN TOOLS IS STARTED EXACTLY AS BEFORE.** The whole argv, + /// both spawn paths, pinned: the bridged route must not leak a flag onto + /// the route that has run live. + #[test] + fn the_own_tools_argv_is_unchanged() { + let mut backend = CodexBackend::new(PathBuf::from(".")) + .with_mcp_overrides(vec!["mcp_servers.team.command=\"incode\"".to_string()]); + backend.set_models(&["gpt-5.5".to_string()]); + backend.set_permission_mode("plan"); + backend.set_extra_dirs(vec![PathBuf::from("/more")]); + let auto = "mcp_servers.memory.default_tools_approval_mode=\"auto\""; + let team = "mcp_servers.team.command=\"incode\""; + assert_eq!( + args_of(&backend.command("the task")), + [ + "exec", + "--skip-git-repo-check", + "--json", + "--disable", + "hooks", + "-c", + auto, + "-c", + team, + "-s", + "read-only", + "-m", + "gpt-5.5", + "--add-dir", + "/more", + "-C", + ".", + "the task", + ] + ); + backend.thread_id = Some("t-1".to_string()); + assert_eq!( + args_of(&backend.command("again")), + [ + "exec", + "resume", + "--skip-git-repo-check", + "--json", + "--disable", + "hooks", + "--dangerously-bypass-approvals-and-sandbox", + "-c", + auto, + "-c", + team, + "-m", + "gpt-5.5", + "t-1", + "again", + ] + ); + assert!(!backend.runs_tools_here()); + assert!(backend.offered_tools().is_empty()); + } + + /// **BRIDGED, CODEX IS STARTED AS A MODEL AND NOTHING ELSE**, on both + /// spawn paths: its user config unread, every tool switch off, read-only + /// and never asking, and incode's tool server its one MCP server — and + /// none of the flags the other route hands it, because incode's toolbox + /// decides what they decided. + #[test] + fn bridged_codex_is_started_as_a_model_with_incodes_server_only() { + let exe = Path::new(r"C:\Program Files\incode\incode.exe"); + let mut backend = CodexBackend::new(PathBuf::from(".")) + .with_mcp_overrides(vec!["mcp_servers.team.command=\"incode\"".to_string()]) + .with_tools(CodexTools::Incode); + backend.set_models(&["gpt-5.5".to_string()]); + backend.set_permission_mode("acceptEdits"); + backend.set_extra_dirs(vec![PathBuf::from("/more")]); + backend.set_team_identity("implement"); + for resumed in [false, true] { + if resumed { + backend.thread_id = Some("t-1".to_string()); + } + let cmd = backend.bridged_command("the task", exe); + let args = args_of(&cmd); + let lead: &[&str] = if resumed { + &["exec", "resume"] + } else { + &["exec"] + }; + assert_eq!(&args[..lead.len()], lead, "{args:?}"); + for flag in ["--skip-git-repo-check", "--json", "--ignore-user-config"] { + assert!(args.iter().any(|a| a == flag), "{flag}: {args:?}"); + } + assert!(args.windows(2).any(|w| w == ["--disable", "hooks"])); + let overrides = overrides_in(&args); + let mut expected: Vec = MODEL_ONLY_OVERRIDES + .iter() + .map(|o| (*o).to_string()) + .collect(); + expected.extend([ + r#"mcp_servers.incode.command="C:\\Program Files\\incode\\incode.exe""#.to_string(), + r#"mcp_servers.incode.args=["--tool-server"]"#.to_string(), + r#"mcp_servers.incode.env_vars=["INCODE_TOOL_BRIDGE","INCODE_TOOL_TOKEN"]"# + .to_string(), + r#"mcp_servers.incode.default_tools_approval_mode="approve""#.to_string(), + "mcp_servers.incode.required=true".to_string(), + "mcp_servers.incode.tool_timeout_sec=3600".to_string(), + r#"mcp_servers.incode.omit_tools_from=["deferred"]"#.to_string(), + ]); + assert_eq!(overrides, expected, "resumed={resumed}"); + for gone in [ + "--dangerously-bypass-approvals-and-sandbox", + "-s", + "--add-dir", + ] { + assert!(!args.iter().any(|a| a == gone), "{gone}: {args:?}"); + } + assert!( + !overrides + .iter() + .any(|o| o.starts_with("mcp_servers.team.") + || o.starts_with("mcp_servers.memory.")), + "a server beside the bridge: {overrides:?}" + ); + assert_eq!( + args.iter().any(|a| a == "-C"), + !resumed, + "`exec resume` takes no -C: {args:?}" + ); + assert_eq!(args.last().map(String::as_str), Some("the task")); + if resumed { + assert_eq!(args[args.len() - 2], "t-1", "{args:?}"); + } + assert!( + !cmd.get_envs() + .any(|(k, _)| k == std::ffi::OsStr::new(crate::team_mcp::IDENTITY_ENV)), + "the team identity is the toolbox's on this route" + ); + assert!( + cmd.get_envs() + .any(|(k, v)| k == "CLAUDECODE" && v.is_none()), + "issue #3 on this route too" + ); + } + // The mode and the roots went to the toolbox, not to codex. + assert_eq!(backend.sandbox, None); + } + + /// Bridged, the backend says so to every caller that asks: its calls run + /// here, it enforces both halves, and it offers the toolbox's tools. + #[test] + fn bridged_codex_runs_its_tools_here() { + let backend = CodexBackend::new(PathBuf::from(".")).with_tools(CodexTools::Incode); + assert!(backend.runs_tools_here()); + assert_eq!(backend.enforces(), crate::guards::Enforcement::EVERYTHING); + let tools = backend.offered_tools(); + for tool in ["Read", "Write", "Edit", "Bash", "team_ask"] { + assert!(tools.iter().any(|t| t == tool), "{tool}: {tools:?}"); + } + assert!( + backend + .mcp_config() + .is_some_and(|c| c.contains("--tool-server")), + "{:?}", + backend.mcp_config() + ); + // And setting it back to codex's own is the route as it was. + let own = CodexBackend::new(PathBuf::from(".")) + .with_tools(CodexTools::Incode) + .with_tools(CodexTools::Own); + assert!(!own.runs_tools_here()); + assert_eq!(own.mcp_config(), None); + } + + #[test] + fn the_setting_spells_own_and_incode() { + assert_eq!(CodexTools::parse("own"), Some(CodexTools::Own)); + assert_eq!(CodexTools::parse(" INCODE "), Some(CodexTools::Incode)); + assert_eq!(CodexTools::parse("bridge"), None); + assert_eq!(CodexTools::parse(""), None); + assert_eq!(CodexTools::default(), CodexTools::Own); + for tools in [CodexTools::Own, CodexTools::Incode] { + assert_eq!(CodexTools::parse(tools.as_str()), Some(tools)); + } + } + + /// The events a sequence of `codex exec --json` lines stands for. + fn read(lines: &[&str], bridged: bool) -> (Vec, Option) { + let mut thread = None; + let mut reading = Reading::new(&mut thread, Some("gpt-5.5".to_string()), bridged); + let events = lines.iter().flat_map(|l| reading.line(l)).collect(); + drop(reading); + (events, thread) + } + + /// An MCP call to incode's own server, in the shape `codex exec --json` + /// prints it (`exec/src/exec_events.rs` `McpToolCallItem`, 0.163.0): a + /// started item, then a completed one with the result's content blocks. + const INCODE_CALL: [&str; 2] = [ + r#"{"type":"item.started","item":{"id":"item_1","type":"mcp_tool_call","server":"incode","tool":"Write","arguments":{"path":"a.txt","content":"x"},"result":null,"error":null,"status":"in_progress"}}"#, + r#"{"type":"item.completed","item":{"id":"item_1","type":"mcp_tool_call","server":"incode","tool":"Write","arguments":{"path":"a.txt","content":"x"},"result":{"content":[{"type":"text","text":"wrote a.txt"}],"structured_content":null},"error":null,"status":"completed"}}"#, + ]; + + /// **BRIDGED, A CALL TO incode's SERVER IS SHOWN ONCE — AS INCODE RAN + /// IT.** The bridge shows the call under incode's id when it runs it; + /// codex's own record of the same call is not shown again. A call to any + /// other server is still shown from codex's record. + #[test] + fn bridged_codex_does_not_show_incodes_calls_twice() { + let (events, _) = read(&INCODE_CALL, true); + assert!(events.is_empty(), "{events:?}"); + + let other = r#"{"type":"item.completed","item":{"id":"item_2","type":"mcp_tool_call","server":"elsewhere","tool":"lookup","arguments":{},"result":{"content":[{"type":"text","text":"found"}]},"error":null,"status":"completed"}}"#; + let (events, _) = read(&[other], true); + assert!( + matches!(&events[..], [AgentEvent::ToolUse { name, .. }, AgentEvent::ToolResult { output, is_error: false, .. }] if name == "lookup" && output == "found"), + "{events:?}" + ); + } + + /// On codex's own tools the same lines are its tool calls, mapped as + /// they always were: a use when the call starts, and the use and its + /// result when it completes. + #[test] + fn own_tools_codex_shows_an_mcp_call_from_its_record() { + let (events, _) = read(&INCODE_CALL, false); + assert!( + matches!( + &events[..], + [ + AgentEvent::ToolUse { id: a, name: n1, .. }, + AgentEvent::ToolUse { id: b, name: n2, input }, + AgentEvent::ToolResult { output, is_error: false, .. }, + ] if a == "item_1" && b == "item_1" && n1 == "Write" && n2 == "Write" + && input.contains("a.txt") && output == "wrote a.txt" + ), + "{events:?}" + ); + } + + /// A failed MCP call carries its error as an object — `{"message": …}`, + /// not a string — and is shown as a failed result with that message. + #[test] + fn a_failed_mcp_call_shows_its_message() { + let failed = r#"{"type":"item.completed","item":{"id":"item_3","type":"mcp_tool_call","server":"elsewhere","tool":"Write","arguments":{},"result":null,"error":{"message":"tool call timed out"},"status":"failed"}}"#; + let (events, _) = read(&[failed], false); + assert!( + matches!(&events[..], [_, AgentEvent::ToolResult { output, is_error: true, .. }] if output == "tool call timed out"), + "{events:?}" + ); + } + + /// The rest of a turn reads the same on both routes: the thread, the + /// reply, and the result. + #[test] + fn a_turn_reads_the_same_on_both_routes() { + let lines = [ + r#"{"type":"thread.started","thread_id":"th-1"}"#, + r#"{"type":"turn.started"}"#, + r#"Reading additional input from stdin..."#, + r#"{"type":"item.completed","item":{"id":"item_0","type":"agent_message","text":"done"}}"#, + r#"{"type":"turn.completed","usage":{"input_tokens":3,"cached_input_tokens":1,"output_tokens":2}}"#, + ]; + let (own, own_thread) = read(&lines, false); + let (bridged, bridged_thread) = read(&lines, true); + assert_eq!(own, bridged); + assert_eq!(own_thread.as_deref(), Some("th-1")); + assert_eq!(bridged_thread.as_deref(), Some("th-1")); + assert!( + matches!(&own[0], AgentEvent::SessionStarted { session_id, .. } if session_id == "th-1") + ); + assert!(own + .iter() + .any(|e| matches!(e, AgentEvent::Text(t) if t == "done"))); + } + + // ----------------------------------------------------------------------- + // The flow, end to end, with a stand-in codex. + // ----------------------------------------------------------------------- + + /// Set only in the stand-in codex the flow test starts: the directory it + /// reads its argv from. + const FAKE_CODEX: &str = "INCODE_FAKE_CODEX"; + /// Set only in the stand-in tool server the stand-in codex starts. + const FAKE_TOOL_SERVER: &str = "INCODE_FAKE_TOOL_SERVER"; + + /// The value of the `-c` override for `key`, as codex's TOML reads it. + fn override_value<'a>(overrides: &'a [String], key: &str) -> &'a str { + overrides + .iter() + .find_map(|o| o.strip_prefix(&format!("{key}="))) + .unwrap_or_else(|| panic!("no {key} among {overrides:?}")) + } + + /// The tool server half, as `incode --tool-server` runs it. + #[test] + fn tool_server_child() { + if std::env::var_os(FAKE_TOOL_SERVER).is_none() { + return; + } + let _ = crate::tool_bridge::run_stdio(); + std::process::exit(0); + } + + /// A stand-in codex: reads the argv it was started with, starts the MCP + /// server it was told to — with ONLY the variables `env_vars` names, as + /// codex does — and, over MCP stdio, lists the tools and calls `Write` + /// twice. It prints what it did as `codex exec --json` lines. + #[test] + fn fake_codex_child() { + use std::io::Write as _; + let Some(dir) = std::env::var_os(FAKE_CODEX) else { + return; + }; + let dir = PathBuf::from(dir); + let argv = std::fs::read(dir.join("argv")).expect("argv"); + let args: Vec = argv + .split(|b| *b == 0) + .filter(|a| !a.is_empty()) + .map(|a| String::from_utf8_lossy(a).into_owned()) + .collect(); + let overrides = overrides_in(&args); + let command = override_value(&overrides, "mcp_servers.incode.command") + .trim_matches('"') + .replace("\\\\", "\\"); + let server_args: Vec = + serde_json::from_str(override_value(&overrides, "mcp_servers.incode.args")) + .expect("args"); + let passed: Vec = + serde_json::from_str(override_value(&overrides, "mcp_servers.incode.env_vars")) + .expect("env_vars"); + let mut server = std::process::Command::new(&command) + .args(&server_args) + .env_clear() + .env("PATH", std::env::var_os("PATH").unwrap_or_default()) + .envs( + passed + .iter() + .filter_map(|name| Some((name, std::env::var_os(name)?))), + ) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn() + .expect("start the tool server"); + let mut to = server.stdin.take().expect("stdin"); + let mut from = BufReader::new(server.stdout.take().expect("stdout")); + let mut ask = |id: u64, method: &str, params: serde_json::Value| -> serde_json::Value { + let request = + serde_json::json!({"jsonrpc":"2.0","id":id,"method":method,"params":params}); + writeln!(to, "{request}").expect("send"); + to.flush().expect("flush"); + loop { + let mut line = String::new(); + if from.read_line(&mut line).expect("read") == 0 { + panic!("the tool server went away"); + } + // The test harness's own banner is not a reply. + if let Ok(reply) = serde_json::from_str::(&line) { + if reply["id"] == id { + return reply; + } + } + } + }; + let say = |line: serde_json::Value| println!("{line}"); + say(serde_json::json!({"type":"thread.started","thread_id":"fake-thread"})); + say(serde_json::json!({"type":"turn.started"})); + ask( + 0, + "initialize", + serde_json::json!({"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"fake-codex","version":"0"}}), + ); + let listed = ask(1, "tools/list", serde_json::json!({})); + let names: Vec<&str> = listed["result"]["tools"] + .as_array() + .map(|t| t.iter().filter_map(|t| t["name"].as_str()).collect()) + .unwrap_or_default(); + say( + serde_json::json!({"type":"item.completed","item":{"id":"item_0","type":"agent_message","text":format!("tools: {}", names.join(","))}}), + ); + for (n, path) in [(2, "notes.txt"), (3, "secret.txt")] { + let arguments = serde_json::json!({"path": path, "content": "written"}); + let item = format!("item_{n}"); + say( + serde_json::json!({"type":"item.started","item":{"id":item,"type":"mcp_tool_call","server":"incode","tool":"Write","arguments":arguments,"result":null,"error":null,"status":"in_progress"}}), + ); + let reply = ask( + n, + "tools/call", + serde_json::json!({"name":"Write","arguments":arguments}), + ); + let failed = reply["result"]["isError"] == true; + say( + serde_json::json!({"type":"item.completed","item":{"id":item,"type":"mcp_tool_call","server":"incode","tool":"Write","arguments":arguments, + "result": if failed { serde_json::Value::Null } else { serde_json::json!({"content": reply["result"]["content"]}) }, + "error": if failed { serde_json::json!({"message": reply["result"]["content"][0]["text"]}) } else { serde_json::Value::Null }, + "status": if failed { "failed" } else { "completed" }}}), + ); + } + drop(to); + let _ = server.wait(); + say( + serde_json::json!({"type":"item.completed","item":{"id":"item_9","type":"agent_message","text":"done"}}), + ); + say( + serde_json::json!({"type":"turn.completed","usage":{"input_tokens":1,"output_tokens":1}}), + ); + std::process::exit(0); + } + + /// A shell script at `path` that runs this test binary's `test` with + /// `marker` set to `value`, after `before`. + #[cfg(unix)] + fn child_script(path: &Path, before: &str, marker: &str, value: &Path, test: &str) { + use std::os::unix::fs::PermissionsExt; + let exe = std::env::current_exe().expect("test binary"); + let body = format!( + "#!/bin/sh\n{before}\n{marker}='{}' exec '{}' --exact '{test}' --nocapture -q --test-threads=1\n", + value.display(), + exe.display() + ); + std::fs::write(path, body).expect("write the script"); + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).expect("runnable"); + } + + /// **A BRIDGED CODEX TURN RUNS ITS TOOL CALLS IN incode's TOOLBOX**, end + /// to end: the backend opens the bridge and starts "codex" with the + /// bridged argv; the stand-in reads the registration off that argv, + /// starts the tool server with only the variables it names, and calls + /// `Write` twice over MCP. The first lands — written by incode. The + /// second is refused by a deny rule in incode's toolbox and nothing is + /// written. Each call is shown once, under incode's id; codex's record of + /// it is not shown again. + #[cfg(unix)] + #[test] + fn a_bridged_turn_runs_its_calls_in_incodes_toolbox_and_a_deny_rule_refuses_one() { + let ws = tempfile::tempdir().expect("ws"); + let bin = tempfile::tempdir().expect("bin"); + let codex = bin.path().join("codex.sh"); + let server = bin.path().join("server.sh"); + child_script( + &codex, + &format!( + "printf '%s\\0' \"$@\" > '{}'", + bin.path().join("argv").display() + ), + FAKE_CODEX, + bin.path(), + "agent::codex::tests::fake_codex_child", + ); + child_script( + &server, + "", + FAKE_TOOL_SERVER, + Path::new("1"), + "agent::codex::tests::tool_server_child", + ); + + let mut backend = CodexBackend::new(ws.path().to_path_buf()) + .with_binary(codex.to_string_lossy()) + .with_tools(CodexTools::Incode) + .with_tool_server(server.clone()); + let mut rules = crate::permissions::rules::PermissionRules::none(); + rules.add( + &crate::permissions::rules::RuleLists { + deny: vec!["Write(secret.txt)".to_string()], + ..Default::default() + }, + crate::permissions::rules::Layer::User, + None, + ); + backend + .tools + .as_mut() + .expect("bridged") + .set_permission_rules(rules); + + let mut seen = Vec::new(); + let outcome = backend + .run_turn("write two files", &mut |e| seen.push(e.clone())) + .expect("the turn completes"); + assert!(!outcome.is_error, "{outcome:?}"); + assert_eq!(outcome.session_id, "fake-thread"); + assert_eq!(backend.session_id(), Some("fake-thread")); + + // The argv codex was really started with: the bridged one. + let argv = String::from_utf8(std::fs::read(bin.path().join("argv")).expect("argv")) + .expect("utf-8"); + assert!(argv.contains("--ignore-user-config"), "{argv:?}"); + assert!(argv.contains("features.shell_tool=false"), "{argv:?}"); + assert!( + argv.contains(&format!( + "mcp_servers.incode.command=\"{}\"", + server.display() + )), + "{argv:?}" + ); + + // The model saw incode's tools. + assert!( + seen.iter().any(|e| matches!(e, AgentEvent::Text(t) if t.starts_with("tools: ") && t.contains("Write") && t.contains("Read"))), + "{seen:?}" + ); + // The first call ran in incode's toolbox; the second was refused there. + assert_eq!( + std::fs::read_to_string(ws.path().join("notes.txt")).expect("written by incode"), + "written" + ); + assert!( + !ws.path().join("secret.txt").exists(), + "the deny rule did not hold" + ); + let uses: Vec<(&str, &str)> = seen + .iter() + .filter_map(|e| match e { + AgentEvent::ToolUse { id, name, .. } => Some((id.as_str(), name.as_str())), + _ => None, + }) + .collect(); + assert_eq!( + uses, + [("incode-1", "Write"), ("incode-2", "Write")], + "each call once, under incode's id: {seen:?}" + ); + let results: Vec<(&str, bool, &str)> = seen + .iter() + .filter_map(|e| match e { + AgentEvent::ToolResult { + id, + is_error, + output, + } => Some((id.as_str(), *is_error, output.as_str())), + _ => None, + }) + .collect(); + assert_eq!(results.len(), 2, "{seen:?}"); + assert_eq!((results[0].0, results[0].1), ("incode-1", false)); + assert_eq!((results[1].0, results[1].1), ("incode-2", true)); + assert!( + results[1].2.contains("Write(secret.txt)"), + "refused by the rule, by name: {}", + results[1].2 + ); + assert!( + seen.iter() + .any(|e| matches!(e, AgentEvent::Text(t) if t == "done")), + "{seen:?}" + ); } } diff --git a/src/cli/mod.rs b/src/cli/mod.rs index a1102c3..f743e07 100644 --- a/src/cli/mod.rs +++ b/src/cli/mod.rs @@ -1600,22 +1600,16 @@ fn backend_for_protocol( // this whole split exists to prevent. .with_system_context(system_prompt.to_vec()), ), - Some(crate::agent::Protocol::CodexJson) => { - let mut backend = crate::agent::codex::CodexBackend::new(workspace.to_path_buf()) - .with_binary(binary.to_string()) - .with_system_context(system_prompt.to_vec()); - - // Codex spells registration as `-c key=value` TOML overrides rather - // than a JSON flag — verified from `codex mcp add --help`, whose own - // example passes an array. - let overrides = - mcp_overrides_for(desktop, std::env::current_exe().ok(), workspace, mode); - if !overrides.is_empty() { - backend = backend.with_mcp_overrides(overrides); - } - - Box::new(backend) - } + Some(crate::agent::Protocol::CodexJson) => Box::new(codex_backend( + workspace, + binary, + system_prompt, + desktop, + mode, + crate::admin::AdminConfig::load_default() + .resolve_codex_tools() + .value, + )), _ => { let mut backend = crate::agent::claude_code::ClaudeCodeBackend::new(workspace.to_path_buf()) @@ -1645,6 +1639,56 @@ fn backend_for_protocol( } } +/// The codex backend, on its own tools or on incode's ([`crate::agent::codex::CodexTools`]). +/// +/// The choice is an argument, not read here, for the reason +/// [`run_backend_with_desktop`] takes the desktop switch: a test can then +/// build both routes in one process and reach the lines of each. +fn codex_backend( + workspace: &Path, + binary: &str, + system_prompt: &[String], + desktop: bool, + mode: crate::permissions::PermissionMode, + tools: crate::agent::codex::CodexTools, +) -> crate::agent::codex::CodexBackend { + let backend = crate::agent::codex::CodexBackend::new(workspace.to_path_buf()) + .with_binary(binary.to_string()) + .with_system_context(system_prompt.to_vec()); + match tools { + // Codex as a model only. The toolbox gets what the Claude route's + // does — the engine's guard before each call, the operator's own + // commands around each, the OS sandbox on its shell — and the desktop + // and the team channel are toolbox tools reached through the bridge, + // so no server of their own is registered beside it. + crate::agent::codex::CodexTools::Incode => { + let mut backend = backend + .with_tools(tools) + .with_engine(crate::hooks::engine::Engine::locate()) + .with_code_edits(crate::toolbox::CodeEdits::locate()) + .with_operator_hooks(crate::hooks::HookRunner::from_settings()) + .with_sandbox(sandbox_for(mode)); + if let Some(setup) = desktop_setup_for(desktop, std::env::current_exe().ok(), workspace) + { + backend = backend.with_desktop(setup); + } + backend + } + crate::agent::codex::CodexTools::Own => { + // Codex spells registration as `-c key=value` TOML overrides rather + // than a JSON flag — verified from `codex mcp add --help`, whose own + // example passes an array. + let overrides = + mcp_overrides_for(desktop, std::env::current_exe().ok(), workspace, mode); + if overrides.is_empty() { + backend + } else { + backend.with_mcp_overrides(overrides) + } + } + } +} + /// Run one turn and print it, streaming the reply as it is generated. /// /// `augmented` is what the agent is sent — the instruction plus whatever skills @@ -2071,6 +2115,55 @@ mod tests { assert!(quiet.contains("mcp_servers.team."), "got: {quiet}"); } + /// **`codex_tools: "incode"` MAKES CODEX A MODEL ON incode's TOOLBOX**: its + /// calls run here (so allowed-tools and the permission rules bind and the + /// "not enforced" notice stops), the desktop is the toolbox's, and the + /// one server handed over is the bridge — no team or desktop server + /// beside it. And `own` is the codex route as it was. + #[test] + fn the_codex_setting_picks_whose_tools_codex_runs() { + use crate::agent::codex::CodexTools; + use crate::agent::AgentBackend as _; + let bridged = codex_backend( + Path::new("."), + "codex", + &[], + true, + ORDINARY, + CodexTools::Incode, + ); + assert!(bridged.runs_tools_here()); + assert_eq!(bridged.enforces(), crate::guards::Enforcement::EVERYTHING); + let tools = bridged.offered_tools(); + for tool in ["Read", "Write", "Bash", "screenshot", "team_ask"] { + assert!(tools.iter().any(|t| t == tool), "{tool}: {tools:?}"); + } + let config = bridged.mcp_config().expect("the bridge is handed over"); + assert!( + config.contains("mcp_servers.incode.args=[\"--tool-server\"]"), + "{config}" + ); + assert!( + !config.contains("mcp_servers.team.") && !config.contains("mcp_servers.desktop."), + "a server beside the bridge: {config}" + ); + + let own = codex_backend( + Path::new("."), + "codex", + &[], + true, + ORDINARY, + CodexTools::Own, + ); + assert!(!own.runs_tools_here()); + assert_eq!(own.enforces(), crate::guards::Enforcement::NOTHING); + assert!(own.offered_tools().is_empty()); + let config = own.mcp_config().expect("team and desktop"); + assert!(config.contains("mcp_servers.desktop.command="), "{config}"); + assert!(!config.contains("mcp_servers.incode."), "{config}"); + } + /// A Windows path must survive TOML's escape rules. /// /// `C:\Users\…` inside a TOML basic string is an invalid escape, so the diff --git a/src/custom_commands.rs b/src/custom_commands.rs index 04d7786..209e943 100644 --- a/src/custom_commands.rs +++ b/src/custom_commands.rs @@ -326,7 +326,8 @@ pub fn not_enforced_by(agent: &str, allowed: &[String]) -> String { ); format!( "allowed-tools ({}) was NOT enforced this turn: {agent} runs its own tools, which \ - incode cannot refuse. It binds on the API route and Claude Code.", + incode cannot refuse. It binds on the API route, Claude Code, and codex with \ + codex_tools \"incode\".", allowed.join(", ") ) } diff --git a/src/tool_bridge.rs b/src/tool_bridge.rs index 407e7f2..27f31a6 100644 --- a/src/tool_bridge.rs +++ b/src/tool_bridge.rs @@ -42,6 +42,11 @@ use crate::agent::AgentEvent; use crate::runtime::cancel::CancelToken; use crate::toolbox::{ToolOutput, Toolbox}; +/// How long, in whole seconds, the server half waits for a tool to finish — +/// what a CLI that bounds its own MCP calls must be told, or it gives up on +/// a call incode is still running. See `REPLY_BOUND`. +pub const REPLY_BOUND_SECS: u64 = 60 * 60; + /// Where the tool server finds the parent: `127.0.0.1:`. pub const ADDR_ENV: &str = "INCODE_TOOL_BRIDGE"; /// The turn's token, which every request must carry. @@ -67,7 +72,7 @@ const CONNECT_BOUND: Duration = Duration::from_secs(5); /// How long the server half waits for a tool to finish. A person may be asked /// (bounded at ten minutes by the engine) and a command may run long; past an /// hour nothing is still coming. -const REPLY_BOUND: Duration = Duration::from_secs(60 * 60); +const REPLY_BOUND: Duration = Duration::from_secs(REPLY_BOUND_SECS); /// What reached the parent from the tool server. pub enum Request { @@ -369,6 +374,141 @@ pub fn answer( } } +// --------------------------------------------------------------------------- +// The parent's turn: one loop for every CLI driven over the bridge. +// --------------------------------------------------------------------------- + +/// What a cancelled turn reports, so the caller can tell it apart from a crash. +pub const CANCELLED: &str = "the turn was cancelled"; + +/// What a bridged turn's loop hears: a line the CLI printed, or a tool call +/// the model made, forwarded by the bridge. +pub enum Incoming { + Line(String), + ReadFailed(String), + Ended, + Tool(Request), +} + +/// How long the loop waits for something to arrive before looking at the +/// cancel flag again. A turn that has gone quiet — the model thinking, a long +/// command running — still stops within this of being asked to. +pub const POLL: Duration = Duration::from_millis(100); + +/// Read the CLI's output on its own thread, one line at a time, into the loop. +/// +/// Its own thread because the loop must also answer tool calls, and the CLI +/// is BLOCKED on each of those until it is answered: a loop sitting in a read +/// of the CLI's output would never see the call the CLI is waiting on. +pub fn pump(reader: R, to: Sender) { + std::thread::spawn(move || { + for line in reader.lines() { + let message = match line { + Ok(line) => Incoming::Line(line), + Err(e) => { + let _ = to.send(Incoming::ReadFailed(e.to_string())); + return; + } + }; + if to.send(message).is_err() { + return; + } + } + let _ = to.send(Incoming::Ended); + }); +} + +/// One turn's channel, opened before the CLI is started: the bridge, the +/// loop's two ends, and the binary the CLI must start as the tool server. +pub struct Turn { + pub exe: std::path::PathBuf, + pub bridge: Bridge, + pub to: Sender, + pub from: std::sync::mpsc::Receiver, +} + +impl Turn { + /// Open the channel for one turn, refused once `cancel` trips. + /// + /// # Errors + /// + /// This binary cannot be named, or the socket cannot be bound. Either + /// way the turn is not started: without the bridge the model would have + /// no tools but the CLI's, and falling back to those is the thing this + /// route exists to avoid. + pub fn open(cancel: Option) -> Result { + let exe = std::env::current_exe().map_err(|e| { + crate::agent::AgentError::new(format!( + "incode could not name its own binary, so it cannot offer its tools; \ + the turn was not started: {e}" + )) + })?; + let (to, from) = std::sync::mpsc::channel(); + let bridge = Bridge::open(to.clone(), Incoming::Tool, cancel).map_err(|e| { + crate::agent::AgentError::new(format!( + "incode could not open the channel its tools run over, so the turn \ + was not started: {e}" + )) + })?; + Ok(Self { + exe, + bridge, + to, + from, + }) + } +} + +/// The turn itself: every tool call the model makes run by `tools`, and +/// every line the CLI prints handed to `on_line`, whose events are shown — +/// until the CLI finishes or the turn is stopped. +/// +/// `on_line` is given the toolbox too, so a CLI that names its conversation +/// can tell the engine which one the calls belong to. +/// +/// # Errors +/// +/// [`CANCELLED`] when the turn was stopped; the CLI's output could not be read. +pub fn drive( + from: &std::sync::mpsc::Receiver, + cancel: Option<&CancelToken>, + tools: &mut Toolbox, + calls: &mut u64, + on_event: &mut dyn FnMut(&AgentEvent), + on_line: &mut dyn FnMut(String, &mut Toolbox) -> Vec, +) -> Result<(), crate::agent::AgentError> { + let stopped = || cancel.is_some_and(CancelToken::is_cancelled); + loop { + if stopped() { + return Err(crate::agent::AgentError::new(CANCELLED)); + } + let line = match from.recv_timeout(POLL) { + Ok(Incoming::Line(line)) => line, + Ok(Incoming::Tool(request)) => { + // Numbered per CALL: the list the server asks for first is + // not a call, and must not use up an id. + if matches!(request, Request::Call { .. }) { + *calls += 1; + } + let id = format!("incode-{calls}"); + answer(tools, request, &id, stopped(), on_event); + continue; + } + Ok(Incoming::ReadFailed(e)) => { + return Err(crate::agent::AgentError::new(format!( + "reading agent output: {e}" + ))) + } + Ok(Incoming::Ended) | Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break, + Err(std::sync::mpsc::RecvTimeoutError::Timeout) => continue, + }; + for event in on_line(line, tools) { + on_event(&event); + } + } + Ok(()) +} + /// The MCP registration entry for the server half, for an `mcpServers` map. /// /// Carries no token and no address: those reach the server through the From 19dd1afd776ce128c9091d1115122982b6bcd5ba Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 20 Oct 2026 22:04:29 +0000 Subject: [PATCH 2/2] team: codex passes the team identity on to the team MCP server Codex starts an MCP stdio server with only HOME, PATH and a few others plus the variables named in its env_vars (codex rmcp-client/src/utils.rs), so INCODE_TEAM_AS, set on codex's own process, never reached incode's team server and its messages were filed as unrouted. The override now names it. Found while bridging codex's tools; an older codex ignores the key. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_011DiH8n52ifWoCd5Kx2aHwT --- src/team_mcp.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/src/team_mcp.rs b/src/team_mcp.rs index b33a6c8..f124687 100644 --- a/src/team_mcp.rs +++ b/src/team_mcp.rs @@ -319,6 +319,11 @@ pub fn codex_config_overrides(exe: &std::path::Path, channel: &std::path::Path) "mcp_servers.{CLIENT_KEY}.args=[\"--team-mcp\",\"--team-channel\",\"{}\"]", toml(channel) ), + // Codex starts an MCP stdio server with only HOME, PATH and a few + // others, plus the names listed here (codex `rmcp-client/src/utils.rs`): + // without it the server never sees who it speaks for, and every + // message is filed as unrouted. An older codex ignores the key. + format!("mcp_servers.{CLIENT_KEY}.env_vars=[\"{IDENTITY_ENV}\"]"), ] } @@ -340,6 +345,22 @@ pub fn run_stdio(mut server: Server) -> std::io::Result<()> { mod tests { use super::*; + /// **CODEX HANDS THE SERVER WHO IT SPEAKS FOR.** Codex passes an MCP + /// server only the variables it is told to; the identity must be one. + #[test] + fn codex_is_told_to_pass_the_team_identity_on() { + let overrides = codex_config_overrides( + std::path::Path::new("/bin/incode"), + std::path::Path::new("/w/.incode/team.jsonl"), + ); + assert!( + overrides + .iter() + .any(|o| o == &format!("mcp_servers.{CLIENT_KEY}.env_vars=[\"{IDENTITY_ENV}\"]")), + "{overrides:?}" + ); + } + fn temp_path(name: &str) -> std::path::PathBuf { let dir = std::env::temp_dir().join(format!( "incode-teammcp-{name}-{}-{:?}",