Repository navigation
Conversation
Codex reads contributed env vars only when a session is built, through shell_environment_policy.set in thread/start and thread/resume config. The bridge rebuilt a running session only when constructionSignature changed, and that signature covered CODEX_HOME and the account-pool route but no other env var. A rotated or removed plugin contribution therefore never reached a running thread. The signature now carries a sha256 of the sorted env map, so any added, changed or removed var rebuilds the session before the next turn and an unchanged map does not. A turn whose options omit envVars keeps the session's current env, the same rule Claude Code, Pi and ACP follow. Only the hash is kept, so env values stay out of the signature. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Recorded runtime traffic sends turn/start with envVars {}, and Pi and
ACP already read an empty map the same as an absent one. Hashing {}
rebuilt the session on every recorded Codex turn and stalled the
provider-parity replays. The live runtime always sends a non-empty map
with the thread identity vars, so rotation and removal still rebuild.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael
deleted the
bb/codex-sessions-ignore-changed-plugin-env-vars-thr_xbbjraynqm
branch
November 3, 2026 21:56
ymichael
added a commit
that referenced
this pull request
Nov 17, 2026
…; fix Pi turns after pi exits (#7551) ## Human comments ## What was wrong The bridge conformance recordings had no case for settings changed between turns or on a steer, for a steer that races the end of its turn, or for the provider process dying mid-turn. Bridge fixes in exactly those areas (#4789, #4794, #4922, #5141, #3299, #6939, #7319, #7321, #4947) were each caught by hand, after users hit them. ACP was recorded only for Cursor. ## What changed Besides the suite, this fixes the bugs it found: Pi's crash handling, two ACP permission bugs, where Pi keeps its session files, and a Windows process-kill race. No protocol change. The plugin SDK is bumped to 0.6.150 because its bundled ACP bridge and replay kit changed; its public surface did not. - **Pi fixes (`plugins/provider-pi/src/bridge`).** - **pi died, next message.** After the pi process died, the bridge kept the thread's session registered with a dead child, so the next `turn/start` failed with `No active Pi session` and the thread stayed in error. `PiRpcSession.hasExited()` now lets `reconcileTurnOptions` treat an exited pi like a settings change and rebuild the session from its session file through the existing rebuild path. Users see the next message continue the conversation. The `session/replaced` notice has `contextLost: false` and isn't shown in the timeline. - **Steer racing pi's death.** A steer that reached the bridge after pi died got a generic error: the message was lost and the thread went to error. It is now rejected with the stale-turn contract (`NO_ACTIVE_TURN` + `staleTurn`), as Codex and ACP do, so bb runs the message as a new turn, which rebuilds the session. - **Session file missing.** The rebuild silently started a blank session. It now announces `contextLost: true`, so the timeline shows "Provider session was replaced; provider-side context was lost. pi's session file was missing…". - **Session file corrupt.** pi refused to start, and every later message failed the same way. Before rebuilding, the bridge now reads the session file the way pi does. If it isn't a valid pi session, the bridge starts a new pi session and announces `contextLost: true`, so the timeline shows the context-loss note and the thread stays usable. - **Other restart failures.** Any other failure to restart pi is reported as an error. The thread keeps its session, and the next message resumes it, so a one-off startup failure doesn't lose the conversation. - New tests in `bridge.round2.test.ts` cover the steer, missing-file, corrupt-file and failed-restart cases; each fails without its fix. `session-cwd.test.ts` checks the session-file check against pi's own rules (an empty file is valid, and a leading blank or unparseable line is skipped). The fake pi now rejects an invalid session file the way real pi does. The Pi `provider-exit` scenario cell was re-recorded against the fixed bridge. - No protocol change. - **ACP permission rule.** It used to check only that permission requests the agent raised reached the user, so it was skipped whenever the agent never asked. It now checks that every command an ACP agent ran or asked to run after a change to a stricter mode went through the user's approval. The Cursor and OpenCode `settings-steer` cells are re-recorded with a command after the permission steer, and no rule is skipped in any cell. - The recording driver now answers approvals with allow-once. Cursor turns bb's "allow for session" into `allow-always` and stores it in its global allowlist. My earlier recordings had added `Shell(printf|sleep|python3)` there, which made Cursor stop asking in every thread; I removed those entries. - **OpenCode 2 ran shell commands under Accept-edits without asking (`packages/provider-bridge-acp`).** The bridge passed bb's policy in `OPENCODE_PERMISSION`, which OpenCode 2.x no longer reads. When the agent reports version 2 or later in `initialize`, the bridge now writes bb's rules to the session with `opencode api PATCH /api/session/<id>` before the first prompt: `edit` allow; `shell`, `webfetch` and `external_directory` ask (all allow in Full), each on `*`. They go ahead of the session's own rules, so additional-directory allows still apply. OpenCode 1.x keeps the environment variable. A mode change already restarts the session, which re-applies the rules. In Accept-edits, if the launch command does not end in `acp` or OpenCode rejects the call, the session fails to start instead of running unguarded. In Full Access there is nothing to enforce, so a launch command that does not end in `acp` logs once and the session starts. New bridge test for both modes. New bridge test: OpenCode 2 gets the rules and keeps its directory rule, and a switch to Full rewrites them; OpenCode 1.x gets no `api` call. - **"Allow for session" was stored permanently by Cursor.** The bridge answered it with the agent's `allow_always` option, which Cursor writes to `~/.cursor/cli-config.json` for every future thread. It now answers `allow_once` and keeps the grant in the bridge for that thread's ACP session, including across the bridge's own rebuilds on a settings change. Later requests with the same subject (same command, write scope or tool) are approved without asking. `allow_always` is sent only if an agent offers no allow-once option. New bridge test: the granted command runs again without a prompt, a different command asks, and a new thread asks for the granted command. - **ACP restore after the agent dies (`packages/provider-bridge-acp`).** - When a session rebuild failed because the agent exited during `session/load` or `session/resume`, the bridge had already stopped the old session and dropped the replacement. Every later message then got "No active ACP session", and the provider session was never tried again. The bridge now keeps the thread's settings and provider session after a failed rebuild and restores them on the next `turn/start`, announcing the replacement. A thread stop clears this. New bridge test: the agent dies on its first `session/load`, the next turn resumes the same session. It fails on the old code with "No active ACP session". - An agent exit that landed while the bridge awaited the OpenCode 2 `opencode api` calls left a session whose agent was gone, reported as started. The start now fails with "exited while its session was being set up". New bridge test, which fails on the old code. - **Pi sessions in the real `~/.bb` (`plugins/provider-pi`).** The Pi bridge wrote session files to `~/.bb/pi-bridge-sessions` whatever bb's data directory was, so source builds and second instances wrote into the production data dir. Sessions now live in the plugin's `bridge-data/sessions`. A thread whose file is still in the old place gets a copy the first time the bridge resolves it; the old file is left alone. New tests cover the new location, the copy, and that an existing file is never overwritten. - **Windows tree kills could hit an unrelated process (`packages/process-utils`).** `stopWindowsProcessTree` checked that the child was running, then launched `taskkill /pid <pid> /T /F` asynchronously. If the child exited in that gap, Node handled the exit and closed the handle, so Windows could give the PID to a new process before taskkill ran. taskkill then killed that process and its children. Forced Windows runs of this suite next to the Pi suite showed it: provider processes in random cells, Codex included, died at startup with exit code 1 and no output. With taskkill's output logged, 30 runs showed 9 kills of processes that were not the killer's children. `stopWindowsProcessTree` now keeps the child's process handle open until taskkill finishes. While taskkill runs, it holds back Node's internal close of that handle (`ChildProcess._handle.close`), then makes that close call once taskkill returns. Windows can't reuse a PID while a handle to the process is open. The event loop isn't blocked. This depends on Node's private `_handle`; if a child has none, the stop works as before, without the guard. A new test checks that the handle stays open through the child's exit until taskkill finishes, and is then closed exactly once. - **The recorder touched the real agent dirs.** `scripts/provider-recordings/isolate-agent-state.mjs` runs each CLI against temp config and state: Codex (`CODEX_HOME`), Pi (`PI_CODING_AGENT_DIR`), Cursor (`CURSOR_CONFIG_DIR` + `CURSOR_DATA_DIR`) and OpenCode (all four `XDG_*`, with its own service port, a copy of its active credentials, and a warmed model catalog). A refreshed `auth.json` is copied back. Two things can't be redirected, so they are snapshot-and-restore or cleanup. Cursor syncs its built-in skills into `$HOME/.cursor/skills-cursor` regardless, so that manifest is restored. Claude Code keeps its sign-in in the keychain under its config dir, so it can't be moved; instead the run's own `projects`, `session-env`, `file-history`, `todos` and `debug` directories are deleted afterwards. `~/.claude.json` is never rewritten, because other Claude Code sessions write it concurrently. - `packages/provider-bridge-protocol/recordings/scenarios/<provider>/<cell>`: 20 new recordings made against the real CLIs (Codex 0.169.0, Claude Code 2.1.323, Pi 1.5.2, Cursor, and OpenCode 2.0.22 as a second ACP agent). Four cells per provider: - `settings-follow-up`: follow-ups that each change one setting (model, env var, permission mode, reasoning level). - `settings-steer`: the same four changes, each sent with a steer. - `steer-race`: a steer sent as its turn ends, then a follow-up. - `provider-exit`: the provider process killed mid-command, then a follow-up. - `src/testing/provider-probe-child.mjs` + `scenario-replay.ts` (new `@bb/provider-bridge-protocol/scenarios` subpath, so the SDK bundle stays unchanged): replay each cell through the current bridge with a probe between the bridge and the existing replay child. The probe logs the argv, env and stdin each provider process received, and kills the provider where the recorded one died (`providerExit` in the manifest). - `src/testing/recorded-scenarios.ts`: rules that hold for every bridge, not snapshots: - every cell: each message is accepted exactly once; every turn carries the message that started it; every turn settles; a steer whose turn already ended is rejected as stale. - `settings-follow-up`: a changed model, reasoning level, env var or permission mode reaches the provider before it gets that turn's prompt. - `settings-steer`: a permission change sent with a steer reaches the provider before it gets the steer. Applying a model, reasoning or env var change mid-turn is deliberately not required: Codex, Claude Code and Pi leave it for the next turn, ACP applies it, and both are allowed. - `provider-exit`: the next message runs in a replacement process that resumes the same session, or the bridge announces lost context. - If a replay diverges from its recording, rules that depend on replayed provider output are reported as skipped with a re-record note instead of failing. - `packages/provider-parity/src/scenarios.self.test.ts`: replays all 20 cells (about 15 s wall locally). It fails on any new rule failure, and on any listed gap that now passes. - `recordings/scenarios/known-gaps.json` is empty. It held the two OpenCode Accept-edits gaps until the fix above; the OpenCode settings cells are re-recorded against the fixed bridge and every rule in them passes. The suite still fails on a new failure and on a listed gap that starts passing. - The replay kit answers `opencode api` calls the way it answers `--version`, and keeps the agent's own launch args (`acp`) after the replay args. The probe passes those calls straight through without logging them as provider processes. - Packaging normalizations, each noted in its manifest: - Codex `config/read` responses trimmed to `config.model` (the rest was the recording machine's config). - Claude CLI 2.1.323's echoed hook-callback `control_response`s dropped. The shared replay child would wait on them as answers to bridge requests. - Pi lines sent to a retiring child after its replacement spawned moved ahead of the replacement. - `scripts/provider-recordings/record-scenario-cell.mjs` records one cell against the real CLI, through the gated agent-runtime harness `src/integration.record-scenario-cells.test.ts`. It isn't run in CI. - `scripts/provider-recordings/package-scenario-cells.mjs` redacts and normalizes the raw recording and installs the cell. Re-packaging the raw recordings with it reproduces every committed lane file byte-for-byte. - The suite prints `<provider>/<cell> needs re-recording` when a replay drifts. - `docs/provider-bridge-protocol.md`: describes the scenario recordings, the rules, and how to re-record. Cut: a bb-shutdown-mid-turn cell was recorded too. Live, no provider leaked the running command. But bridges legitimately differ: Codex sends no interrupt and its app-server cleans up itself, while ACP, Claude and Pi cancel. So no replay rule holds for every bridge, and the cell isn't committed. ## Visible behaviour changes - OpenCode 2 threads in Accept-edits now ask before shell commands, web fetches and paths outside the workspace, as they did on OpenCode 1. A custom OpenCode 2 agent whose launch command does not end in `acp` now fails to start in Accept-edits with an error saying so; in Full Access it starts as before. - "Allow for session" on an ACP agent now lasts for that thread's session only, and nothing is written to the agent's own config. It covers the same command, write scope or tool. Cursor's own allow-always covered a command prefix (`Shell(uname)`), so `uname -a` after granting `uname -s` now asks again. After a server restart the thread asks again. - Pi session files move under the data dir's `plugins/provider-pi/bridge-data/sessions`. Existing threads are copied over on first use. The old files stay in `~/.bb/pi-bridge-sessions` and are not deleted. - If an ACP agent dies while its session is being restored, the next message restores the session instead of failing with "No active ACP session". ## How you verified - Pi, live on a source build (`pnpm start:worktree`, fresh dev data dir). Each case plants a codeword first: - **Killed mid-turn, then a message.** Before the fix it failed with `No active Pi session`. After, it answers the codeword. - **Killed while idle, then a message.** It answers the codeword, with no context-loss note. - **Steer racing the death** (bridge frozen with SIGSTOP, pi killed, steer sent, then SIGCONT). Before the fix it showed "steer failed" and the thread went to error. After, the steer runs as a new turn and answers the codeword. The event order confirms the steer was sent while the turn was still active. - **Session file removed.** Before the fix it silently answered `unknown`. After, the context-loss note shows, and the thread answers the next message. - **Session file corrupted.** Before the fix every message failed with "Session file is not a valid pi session". After, the timeline shows "pi's session file is not a valid pi session, so the conversation continues in a new session without its earlier context." and the message runs in a new session. - The `bb-plugin-provider-pi` tests, typecheck and lint pass. - Platforms: pi's exit detection has no platform-specific branch: it uses Node's `exit`/`close` events. The Linux and Windows CI replays run the real Pi bridge (exit detection, rebuild, stale-steer reply) against a replay child that the probe kills with SIGKILL, and the new unit tests run the same bridge against the fake pi. On Windows the probe proxies the Pi extension channel through a named pipe. The live runs above used the real pi CLI on macOS. - OpenCode 2 Accept-edits, live on a source build. Before the fix, a thread ran `touch` with no approval. After, it shows "Waiting for approval to run touch oc-accept.flag", and the file appears only once the command is approved. The session's rules read back with `opencode api GET` as bb's four, followed by the thread-storage directory allow. A Full thread runs the command with no prompt. - OpenCode 1.19.5 (installed in a temp prefix, run as a custom ACP agent with temp `XDG_*` and `HOME`): an Accept-edits thread still asks before `touch`, and the bridge makes no `api` call. - "For session", verified where each part lives. - On Cursor, the Cursor-specific part: before the fix, approving `uname -s` for session added `Shell(uname)` to `~/.cursor/cli-config.json`, and a new thread then ran `uname` without asking. After the fix, the same approval leaves the file byte-identical (same sha1), and the command runs. - On OpenCode 2.0.22, live, the two steps that run in bridge code shared by every ACP agent. Approving for session added no rule to OpenCode's session. The same command in the same thread then ran with no new prompt (one interaction in total), and a new thread asked again. The bridge test covers them too: the granted command runs again without a prompt, a different command asks, and a new thread asks. - Pi sessions, live on a source build with its own data dir. A new thread's session file is written to `<data dir>/plugins/provider-pi/bridge-data/sessions`, and `~/.bb/pi-bridge-sessions` is unchanged (325 files). After a server restart the thread resumes from the new location and recalls its codeword. Moving that file to the old location and restarting again copies it back on resume, with the codeword kept. - Isolation, live: one real cell each through the recorder for Codex, Pi, Claude Code and Cursor, plus the two OpenCode settings cells. Afterwards nothing tied to the run's workspace exists in `~/.codex` (rollouts, `state_5.sqlite` threads), `~/.pi/agent`, `~/.bb/pi-bridge-sessions`, `~/.claude`, `~/.cursor` (acp-sessions, projects, `cli-config.json` sha), or OpenCode's real database. Config and auth hashes are unchanged. Claude's own startup still rewrites `plugins/known_marketplaces.json` (refresh timestamp) and adds one shell snapshot, as any Claude start does; those are left. - `@bb/provider-bridge-acp` (589 tests), `@bb/provider-bridge-protocol` (312) and `@bb/provider-parity` (80) pass. The Pi session-file tests and the typecheck and lint for all five touched packages pass too. - Flakiness: a temporary workflow on a throwaway branch (this PR's head plus only that workflow, same runners as CI) ran `turbo run test --filter=@bb/provider-parity --filter=bb-plugin-provider-pi --force`. On the final code: Linux 10/10; Windows 280/280 (20 runs, 20 more with logging, and 240 looped runs). Every scenario suite was 21/21 with no drift notices and no skipped rules, and every Pi suite passed. The scenario suite takes about 21 s on Linux and 27 s on Windows (max 34 s). Re-running CI jobs can't show this, because every re-run is a turbo cache hit. - Before the process-utils fix, Windows failed 6 of 40 runs: provider processes in random cells died at startup and the replays stalled. The Linux run that caught the probe-log cleanup race (`ENOTEMPTY`) was fixed by retrying that removal. - Windows sometimes failed `provider-exit` on `conversation-survives`: twice on `acp-cursor` earlier, and once in 220 `acp-opencode` runs of a loop. The loop's per-process log showed the cause. The bridge had resumed the session correctly, but Windows had given the replacement probe the dead probe's PID. The probe named its log after its PID, so both processes' entries landed in one file, and the rule saw no replacement. Logs are now named per process. Afterwards a cache-bypassed Windows loop ran `acp-cursor/provider-exit` 1,100 times and every other provider-exit cell 220 times. All passed, with no drift. Zero failures in 1,100 puts the Cursor cell's failure rate below about 0.27% at 95% confidence, and below about 1.4% for each of the others. The same run's forced suite passed on Linux 10/10 and Windows 20/20. - `vitest run src/scenarios.self.test.ts` in `@bb/provider-parity`: 21/21 pass, three runs, including two at load average ~40. - Removing a known gap makes its cell fail with that rule. - `turbo run typecheck lint lint:type-aware` for `@bb/provider-bridge-protocol` and `@bb/provider-parity` passes. - The existing parity fixture checks and the recordings redaction test pass. The redaction sweep finds no survivors in the new cells. - The scenarios were also run against the commits before and after the past fixes listed above. Those proof runs are reported in the bb thread, not committed. > AGENT GENERATED 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
ymichael
added a commit
that referenced
this pull request
Nov 19, 2026
## Human comments ## What was wrong Every provider bridge built the environment for the CLI it starts by hand, and each one did it differently. Claude Code passed the thread env through. Codex passed `codex app-server` only an allow-list of three names (`CODEX_OPENAI_BASE_URL`, `CODEX_POOL_AUTH_TOKEN`, `CODEX_HOME`) and stripped every other `BB_*` name. So `BB_THREAD_ID`, `BB_THREAD_STORAGE` and plugin-contributed variables such as `BB_CODEX_BRIDGE_APP_SERVER_COMMAND` never reached the app-server or the MCP servers and hooks it starts. Pi and ACP dropped the contributed env when listing models. All four providers ran their health and installation probes with the bridge's own `process.env`, and the server never sent them the contributed env, so a plugin-supplied `BB_CLAUDE_CODE_EXECUTABLE` worked for threads while the composer still said "not installed". A spawn primitive already has one owner (#6194, #6394); env composition had none. Background notes: C6 in thr_qchecuan6n's `verify/host.md`. Live repro on main (installed bb built from `1320c88e8ab`, Nov 16; the bridge code is unchanged on main): `ps eww` on a running `codex app-server` lists no `BB_THREAD_ID`, `BB_THREAD_STORAGE` or `BB_PROJECT_ID`. A Claude Code CLI under the same daemon has all three. ### Issues and patches from this root cause | | Item | What happened | |---|---|---| | open | #4960 | Codex app-server lacks thread identity, so MCP servers cannot tell which thread they serve. **Fixed.** | | open | #7179 | Contributed `CODEX_HOME` / `BB_CODEX_BRIDGE_APP_SERVER_COMMAND` never reach the app-server. **Fixed** (the `CODEX_HOME` half had already been patched by #6887). | | open | #7614 | Claude Code installation status and health ignore a contributed `BB_CLAUDE_CODE_EXECUTABLE`. **Fixed** for the server and bridge. The app's cached host CLI status still refreshes only on reload; that is a separate query-policy issue. | | merged patch | #3056 | Added the pool URL and token to the Codex allow-list. **Deleted** (the allow-list is gone). | | merged patch | #6887 | Added `CODEX_HOME` to the Codex allow-list. **Deleted.** | | merged patch | #7401 | Gave Claude `model/list` the contributed env, Claude only. Now one rule for all four providers. | | merged patch | #5352 | Pi catalog inherited a stale `PI_BB_TOOLS_FILE`. Kept, in `catalogCliEnv`. | | related | #6939 | Codex rebuilds its session when a turn's env vars change. Unchanged; it now rebuilds onto an env that actually carries them. | | not this class | #4417 | bb CLI dir prepended to PATH. That is a PATH policy choice, not composition. Not changed. | With the builder in place from the start, #4960, #7179 and #7614 could not have happened, and #3056, #6887 and #7401 would not have been needed. Each of those patched one provider for one name. ## What changed - **One builder.** `buildProviderCliEnv(envVars)` in `@bb/provider-bridge-protocol/bridge-kit`, exported to plugins as `experimental_buildProviderCliEnv`. It returns the bridge env minus bridge-only runtime vars, plus the request's `envVars` (valid shell names). On Windows a request var replaces an inherited one whatever its case, so a thread `PATH` never sits beside an inherited `Path`. - **All four bridges use it** for session CLIs, model listing, health and installation probes, and read their launch overrides from its result: - Codex: deleted `appServerLaunchEnv`, `buildAppServerEnv` and `APP_SERVER_LAUNCH_ENV_NAMES`. `resolveAppServerLaunch` now takes the CLI env and has no `process.env` default. - Pi: deleted `buildPiChildEnv`. `resolvePiLaunch` reads the child env. The model-list catalog is keyed by cwd + contributed env. A thread no longer uses that catalog: the session starts Pi, asks that same process for its models (`get_available_models`), picks the exact `provider/id` match with the existing rules (canonical first, then one exact id; ambiguity rejected), and switches with `set_model` and `set_thinking_level`, the way T3 Code does. Model resolution therefore always uses the Pi the thread's env selects, and no second Pi process starts. A model missing from the list is retried like the existing transient login miss; a mid-thread model change is checked against the running Pi before the session is rebuilt. - Claude: `buildSessionEnv` is now the builder plus Claude's two entrypoint tweaks. - ACP: session, model list (now including the request `envVars`), model selection, maintenance and the agent probe. The thread-start model-list command drops the per-thread names, so thread starts share the cached catalog. - **ACP's cached model list drops thread identity.** `withoutThreadIdentityEnv(envVars)` in the bridge kit (internal, not exported to plugins) removes `BB_THREAD_ID`, `BB_THREAD_STORAGE`, `BB_PROJECT_ID` and `BB_ENVIRONMENT_ID` from the ACP thread-start list command, so thread starts share the cached list. - **Probes take an env.** `experimental_resolveExecutablePath`, `experimental_commandOutput`, `experimental_readCliVersion`, `experimental_npmLatestVersion` and `experimental_probeNpmGlobalPackage` take the env as an argument. Claude, Codex, Pi and ACP maintenance pass it through. - **Wire change, `HOST_DAEMON_PROTOCOL_VERSION` 269 → 270.** The `provider.*` host commands `list_models`, `list_commands`, `health`, `installation.status` and `installation.run` now require `contributedEnv`, and the runtime sends `envVars` on the matching sessionless bridge requests (`model/list`, `commands/list`, `provider/health`, `provider/installation/*`): the adapter command types require it, so the type system rejects any request built without it. `provider.usage` carries no env, as before: probing through the Account Pooler's routing env reports the machine as signed out (checked live: the local Claude account returns its Ultra limits, the same probe with the pool's `ANTHROPIC_BASE_URL`/`ANTHROPIC_AUTH_TOKEN` returns `unauthenticated`). - **Bridge compatibility:** the SDK-facing bridge param schemas (`modelListParamsSchema`, `commandListParamsSchema`, `providerMaintenanceParamsSchema`) keep `envVars` optional. A bridge built against the new SDK still accepts requests without it, as the echo provider's tests and the package smoke send. Those schemas were already `.passthrough()`, so a bridge built against the previous SDK accepts the new field. `protocol.test.ts` covers both shapes. The server resolves the env with `resolveHostProviderEnv` (shared with the model catalog store, which already did this inline) and puts it in its status and command-list cache keys. The runtime forwards it as `envVars`. The thread-start installation gate passes the thread's contributed env and includes it in its cache key. - **Reads that bypassed the CLI env:** - Claude's command list starts the CLI with the request's env and caches per folder + contributed env. - Codex auth reads `CODEX_HOME` from the probe env. - The Claude skills config dir reads `CLAUDE_CONFIG_DIR` from the thread's CLI env. - **`windowsHide` default:** - `forkHostProcess` and `spawnHostProcessSync` default it to `true`, as `spawnHostProcess` and `execHostFile` already did. This covers the plugin-host and watcher forks and the CLI re-exec. - The CLI re-exec inherits stdio. libuv only adds `CREATE_NO_WINDOW` when no stdio is inherited, so the re-exec keeps its console. - The browser-automation supervisor script sets it on its detached child. - Nine call sites that passed `windowsHide: true` to a helper that already defaults it no longer do. - **Lint:** a new `bb/no-raw-child-process` rule rejects value imports, `import x = require(...)`, `require`, `process.getBuiltinModule`, dynamic imports and re-exports of `node:child_process`, `child_process`, `cross-spawn` and `execa` in apps/packages/plugins TS. Exempt: `@bb/process-utils/src`, tests, test-support, scripts, `provider-parity`, `connect-next` (hosted service), Vite configs, and `apps/desktop/src/bb-process.ts` (the Linux-only AppImage bridge bootstrap, which runs before the toolchain loads). It is a custom rule because oxlint overrides replace `no-restricted-imports` per file, so the `apps/server` block would have dropped a repo-wide ban. The one production bypass, `workspace-processes.ts` (`ps`/`lsof`), now uses `execHostFileCallback`. - **Docs and surfaces:** `docs/provider-bridge-protocol.md` (Child processes), `docs/provider-plugin-api.md`, the plugin-authoring `providers.md`, `docs/api_to_audit.md` entries, the Plugin Guide symbols, Turbo inputs for the protocol tests (Pi + ACP sources), and the SDK bump to 0.6.163. ## Decisions for review These change what users or plugin authors can see: 1. **Codex app-server now gets the full thread env**, the same as Claude Code: thread identity, `BB_CLI`, `BB_SERVER_URL`, the thread `PATH` (with bb's CLI dir) and all contributed vars. MCP servers, hooks and anything codex starts see them. Codex shell commands already saw these through `shell_environment_policy`. 2. **Contributed launch overrides now take effect**: `BB_CODEX_BRIDGE_APP_SERVER_COMMAND`/`_ARGS` and `BB_PI_BRIDGE_COMMAND`/`_ARGS` from a plugin pick the CLI. Before, only the daemon's machine env could. 3. **Installation status and health now use the host's contributed env.** A plugin-shipped Claude Code counts as installed, and the composer unblocks after the status refreshes. Usage keeps reporting the machine's own sign-in. 4. **Pi resolves a thread's model inside the thread's own Pi process and requires Pi 0.84.3.** Pi 0.84.0–0.84.2 saved every RPC `set_model`/`set_thinking_level` as the user's global default in `~/.pi/agent/settings.json` (checked in the 0.84.2 package; fixed in 0.84.3, Aug 24), which is why bb previously pinned the model with launch flags. `PI_MINIMUM_SUPPORTED_VERSION` is now 0.84.3, so older installs get bb's existing "Update Pi" prompt. Pi 1.5.2 `set_model` records a model change in the session transcript and leaves settings untouched (checked live). The model-picker catalog is now one process per distinct contributed env instead of one per cwd. 5. **No provider env on `bb.host` calls.** An earlier revision added `ExperimentalHostCallOptions.providerEnv`. It is removed: a host worker applies only the first of several overlapping calls' env, and any plugin could have requested another provider's contributed secrets. Native-roots lookup and the ACP agent probe use the host env, as on main. 6. **SDK maintenance probes take an optional env.** `experimental_resolveExecutablePath`, `experimental_commandOutput`, `experimental_readCliVersion`, `experimental_npmLatestVersion` and `experimental_probeNpmGlobalPackage` accept an optional last `env` argument. Without it they behave exactly as before (the bridge's own environment), so existing third-party plugins keep building and typechecking. First-party bridges always pass `buildProviderCliEnv(params.envVars)`. **Accepted in review:** items 1–4 as described. Item 6 was changed at review from a required argument to an optional one. ## How you verified - **Guard test first:** `packages/provider-bridge-protocol/src/contract-tests/provider-cli-env.test.ts` drives all four bridges in-process through one table. A wrapper records the env the spawned CLI actually receives (the mocked Agent SDK `query` options for Claude). Rows per provider: - thread CLI receives every thread var (`BB_THREAD_ID`, `BB_THREAD_STORAGE`, `BB_PROJECT_ID`, `BB_ENVIRONMENT_ID`, a contributed `BB_*` and non-`BB_*` var, thread PATH first; no `ELECTRON_RUN_AS_NODE`); - model-list CLI receives the contributed env; - launch settings come from the thread env; - installation status and health probe the CLI the contributed env selects (skipped on Windows; it uses sh fakes); - installation run plans against that CLI (Claude, Codex, Pi); - the command-list CLI receives the contributed env and launch override (Claude). This row fails on the previous head. The run bridges already applied `envVars`; their gap was on the wire, and the required schema fields now close it. On main, **10 of 16 rows fail**: Codex thread (#4960), Codex launch (#7179), Codex/Pi/ACP model list, Pi launch, and the Claude/Codex/Pi/ACP probes (#7614). All pass on this branch. - **Provider-parity replays (Pi):** the committed Pi recordings were made while the bridge passed `--provider`/`--model`, so they hold no `get_available_models`/`set_model`/`set_thinking_level` on the session child. `replay-provider-child.mjs` now answers those (when the script does not expect them) from the models the recording itself reports and the replayed state. Without that change `pi/fork` fails locally with the same `unansweredRequests` error CI showed; with it all 80 parity and scenario replays pass. - `bridge.model-resolution.test.ts` (Pi): with the bridge's own `BB_PI_BRIDGE_COMMAND` pointing at a missing binary and the thread env carrying a working one, a thread starts on `fake-provider/fake-model`. Before the Pi change it failed with `spawn …/missing-pi ENOENT`. The existing canonical, slash, ambiguity and missing-model cases pass unchanged; `bridge.settings.test.ts` now expects `set_model`/`set_thinking_level` on start, resume and fork. - **Pi thread start, real `pi` 1.5.2 driven through the bridge** (picker lists models, then three threads start; `thread/start` latency): main ~210 ms in the picker's folder and ~400–700 ms for the first thread in another folder; this branch ~210 ms in both. An intermediate revision that resolved through a thread-env catalog measured ~395 ms for the first thread in the picker's folder, which is what this change removes. - `provider-maintenance-kit.test.ts`: the probes called with no env argument resolve, version and run a CLI through the bridge's own environment (today's behaviour); an explicit env overrides it. - `host-process-windows-hide.test.ts`: fails on main for `forkHostProcess` only, passes now. `no-raw-child-process.test.mjs` covers the rule. The rule flags main's `workspace-processes.ts`, and the repo now lints clean under it. - Server: `provider-states.test.ts` checks that health and installation status carry a plugin's `BB_CLAUDE_CODE_EXECUTABLE` to the host with a host-scoped context. Daemon: dispatch forwards `contributedEnv`, and the gate key separates contributed envs. - **Live before/after with a local plugin** contributing `BB_REPRO_MARKER`, a wrapper `BB_CODEX_BRIDGE_APP_SERVER_COMMAND`, and a fake `BB_CLAUDE_CODE_EXECUTABLE` that reports `9.9.9`. On main: the Codex app-server had no `BB_THREAD_ID`/`BB_THREAD_STORAGE`/`BB_PROJECT_ID` or marker, the wrapper never ran, and Settings → Updates showed the system `claude 2.1.325` even after a restart. On this branch: the app-server has all of them, it launches through the wrapper, Updates shows `9.9.9`, and Codex and Pi threads reply `ok`. - **Earlier live after-check:** I started this branch with `pnpm start:worktree` (isolated data dir) and spawned a Codex thread. The turn replied `ok`. `ps eww` on its `codex app-server` shows `BB_THREAD_ID=thr_atcfaipne3`, the thread's `BB_THREAD_STORAGE`, and `BB_SERVER_URL`/`BB_PROJECT_ID`/`BB_ENVIRONMENT_ID`. - Locally: `pnpm exec turbo run typecheck --filter='...[origin/main]'` (green), `turbo run lint --filter='[origin/main]'`, and targeted tests in provider-bridge-protocol, provider-bridge-acp, provider-codex, provider-claude-code, provider-pi, agent-runtime, process-utils, host-daemon (gate, dispatch, app), server (installations, model catalog, provider states) and scripts. Full suites are left to CI. - Not verified: the `windowsHide` fork and sync-spawn defaults on a real Windows console. They are unit-tested only. Fixes #4960 Fixes #7179 Fixes #7614 > AGENT GENERATED 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
ymichael
added a commit
that referenced
this pull request
Nov 24, 2026
…8075) ## Human comments ## What was wrong The Codex bridge copied every thread environment variable into `shell_environment_policy.set.*` in the `thread/start` and `thread/resume` config (`buildShellEnvironmentPolicyConfig` in `plugins/provider-codex/src/session-params.ts`). This included plugin contributions such as the Account Pooler's `CODEX_POOL_AUTH_TOKEN` and `BB_ACCOUNT_POOL_PARENT_TOKEN`, and `GH_TOKEN`. Codex applies `set` after `inherit` and `exclude`, so an admin's `shell_environment_policy.exclude = ["*TOKEN*"]` could not keep these values out of sandboxed commands (#8008, part 2). The `set` copy dates from when one app-server served several bb threads (901aebd). Now each bb thread starts its own app-server, and its process environment is the thread environment (`spawnChildConnection`, also on every rebuild from #6939). The copy therefore only overrode the user's or admin's Codex policy. ## What changed - `plugins/provider-codex/src/session-params.ts`: `buildCodexConfig` no longer copies the thread environment into `shell_environment_policy.set`. Codex's own `shell_environment_policy` decides which variables from the app-server environment reach commands. bb still forces its non-secret context variables through `set` (`BB_THREAD_ID`, `BB_PROJECT_ID`, `BB_ENVIRONMENT_ID`, `BB_THREAD_STORAGE`, `BB_CLI`, `BB_SERVER_URL`, `BB_HOST_DAEMON_PORT`), so the `bb` CLI works under any policy. With Codex's default policy (inherit all), commands get the same variables as before. - `plugins/provider-codex/skills/codex-provider/SKILL.md`: documents how the thread environment reaches Codex commands and how an `exclude` filters it. - Tests: `session-params.test.ts` asserts that only bb's context variables appear in `shell_environment_policy`, and no tokens or project variables. `bridge.session-signature.test.ts` now asserts that a rotated or removed variable reaches the relaunched app-server's process environment and not the session config. `fake-codex-app-server.mjs` logs `CODEX_SIGNATURE_TEST_*` variables at launch for that assertion. - Behavior change for strict Codex policies: with `inherit = "core"` or `"none"`, or a matching `exclude`, commands no longer get `GH_TOKEN`, plugin contributions or project variables, because bb no longer forces them through `set`. bb's context variables above are still forced, so `bb` CLI calls keep working. Codex's default policy is not affected. - No wire change, no `HOST_DAEMON_PROTOCOL_VERSION` bump, no plugin API change. - Not changed, left for a maintainer decision: - Part 1, `networkAccess: true` in `toWorkspaceWriteCodexSandboxPolicy`: this has been there since the first Codex adapter (c7a5bd2), next to `readOnly` with `networkAccess: false`. Codex's Linux sandbox with network off also blocks loopback, so `bb` CLI calls from sandboxed commands would fail (checked with `codex sandbox` and `curl` to 127.0.0.1: `000` with network off, `200` with network on). The `workspaceWrite` schema requires `networkAccess`, so the only way to defer to Codex is to stop sending a per-turn `sandboxPolicy`. Options: (a) keep it and document that the workspace modes allow network; (b) add a Codex provider setting, like Claude Code's `sandboxEnabled`, that leaves the sandbox to Codex's config and `requirements.toml`; (c) turn network off and route it through approval, like Claude's sandbox, which allows loopback only. - With Codex's default policy, sandboxed commands still see the hub token. `BB_ACCOUNT_POOL_PARENT_TOKEN` reaches agent commands on purpose so that a nested bb server can use the parent's pool (#3654). Claude Code threads get it the same way, and `CODEX_POOL_AUTH_TOKEN` has the same value. Whether routed threads should pass that token by default is a product decision. - The login-shell PATH order note. ## How you verified - The new `session-params.test.ts` and `bridge.session-signature.test.ts` assertions fail on origin/main (2 failed, 80 passed) and pass with the change. - End to end with Codex CLI 0.171.0: a real `codex app-server`, started with bb's `resolveAppServerLaunch`, `buildCodexConfig` and `toCodexPermissionSettings`, a scratch `CODEX_HOME`, a fake Responses server as the hub, and a fake pool token. An accept-edits workspace turn ran `env` in the workspace-write sandbox, and a write outside the workspace was denied. - With `exclude = ["*TOKEN*"]` in config.toml: origin/main showed `BB_ACCOUNT_POOL_PARENT_TOKEN` and `CODEX_POOL_AUTH_TOKEN` in the command environment. With this change the command environment has no TOKEN variables. - With Codex's default policy, both builds pass both variables (Codex inherits all). - In every run the hub received `x-bb-account-pool-token` on 2/2 model requests, and `BB_THREAD_ID` and `PLUGIN_API_URL` reached the command. - Live check on a `pnpm start:worktree` instance with Codex 0.171, reading raw command output from the event log: - Project `.codex/config.toml` with `exclude = ["*TOKEN*"]` and a project variable `QA_FAKE_TOKEN`: main passes `QA_FAKE_TOKEN` to the command; this branch does not, and `$BB_CLI status` works. - `inherit = "core"`: commands get only the bb context variables (no project variables or tokens), and `$BB_CLI status` works. - `pnpm exec turbo run typecheck test lint --filter=bb-plugin-provider-codex --force`: pass (625 tests). - `pnpm exec turbo run test --filter=@bb/provider-parity --force`: pass (80 tests). - `apps/server/test/skills/shipped-skills-quality.test.ts`: pass. Part of #8008. The network-access half and Codex permission profiles are in #8145. > AGENT GENERATED --------- Co-authored-by: Michael Yong <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Human comments
What was wrong
A running Codex thread never saw a changed or removed plugin-contributed env var, for example a rotated secret. Codex reads contributed env vars only when a session is built, through
shell_environment_policy.set.*in thethread/startandthread/resumeconfig. The bridge rebuilds a running session only whenconstructionSignaturechanges, and that signature coveredCODEX_HOMEand the account-pool route but no other env var. The runtime sent the new env with every turn, but the bridge ignored it. Codex env rotation in the live@bb/agent-runtimesuite failed on main for this reason.Claude Code (
applyTurnEnvironment), Pi (reconcileTurnOptions) and ACP (reconcileExecutionSettings) already rebuild or restart when the per-turn env changes. Only Codex had the gap.What changed
plugins/provider-codex/src/bridge/bridge.ts: the construction signature now includes a sha256 of the sorted env map, replacing the separateCODEX_HOMEand pool-route fields. Adding, changing or removing any var rebuilds the session before the next turn by resuming the same Codex thread, so context is kept. The same env in a different key order does not rebuild. Only the hash is kept on the session, so no env values are stored in it or logged. A turn whoseenvVarsis absent or empty keeps the session's current env. Pi and ACP follow the same rule, an existing Codex test asserts the absent case, and the recorded parity fixtures send{}on every turn. The live runtime always sends a non-empty map (it includesBB_THREAD_IDand the other thread identity vars), so real rotations and removals still rebuild.No wire changes, so no protocol version bump.
How you verified
bridge.session-signature.test.ts: four turns with the same env in a different key order, a rotated value, a removed var, then no change. Only the rotated and removed turns rebuild, and each resume sends the new values without the removed var. It fails without the fix.pnpm exec turbo run test typecheck lint --filter=bb-plugin-provider-codex --force: 556/556 tests pass; typecheck and lint pass.pnpm exec turbo run test:integration --filter=@bb/agent-runtime --force: 65/65 live tests pass, includingcodex provider applies rotated and removed contributions on the next turn. With the fix reverted, that test fails withexpected 'FAIL' to be 'PASS'.pnpm exec turbo run test --filter=@bb/provider-parity --force: 59/59 pass. The first CI run failed every Codex replay because the fixtures'envVars: {}turns triggered unrecorded rebuilds; the empty-map rule fixes that.--forcematters here:@bb/agent-runtime#test:integration's Turbo inputs don't includeplugins/source, so without it an unforced run can replay a stale pass for a bridge change.🤖 Generated with Claude Code