diff --git a/ORCHESTRATION.md b/ORCHESTRATION.md index 6af5386..81c34c6 100644 --- a/ORCHESTRATION.md +++ b/ORCHESTRATION.md @@ -62,7 +62,7 @@ In `auto`/`eager`, tell the user after the fact. In `manual`, their explicit req - Devin CLI: advertised ids (`devin models list`; level is in the id, e.g. `swe-1-7-medium`). Unknown id fails; `effort` warns and is ignored. Mode forced to `bypass`. Revive via `session/load` (replays into `get_transcript`; `get_result` stays clean). - ZCode: `provider\model` or a unique bare id. Thought: `off`→`low`, `medium`→`high`. Unknown or ambiguous model fails; unmappable effort warns. Mode `yolo`. Revive via `session/resume`. - MiniMax Code: `provider/model` or `provider/model#variant`. `thinkingEffort` (`off`→`default`). Unknown model fails; unmappable effort warns. Permission `bypassPermissions`. Revive via `session/resume`. -3. Loop `wait_task` until terminal. A timeout is **not** failure — call it again. `silent_for_sec` is time since the last output. Silence past `stall_timeout_sec` (default 1800, per worker, 0 disables) ends `failed` / `stalled`: raise that worker's limit or resume the `session_id` with a narrower task. Size `timeout_sec` under the host MCP tool timeout: +3. Loop `wait_task` until terminal. A timeout is **not** failure — call it again. `silent_for_sec` is time since the last output. Silence past `stall_timeout_sec` (default 1800, per worker, 0 disables) ends `failed` / `stalled`: raise that worker's limit or resume the `session_id` with a narrower task. Stall counts only worker output — a chatty turn never stalls; `turn_timeout_sec` (per worker, 0 = off) caps a turn's wall-clock and ends `failed` / `timed_out`. Terminal `wait_task` carries `persisted`; `false` means `state.json` was not written — the result stays valid but may not survive a restart. `files_changed` lists only paths inside the task `cwd`; outside paths go to `files_outside_cwd` (absolute, capped alike, `files_outside_cwd_total`). A `session/load`-failed warning means the worker started a fresh native session — re-supply context next message. Size `timeout_sec` under the host MCP tool timeout: - Codex: `tool_timeout_sec` 600; default 180 is fine. - Cursor: host ~45–60 s; pass ~30 and loop. - Kimi Code: configure `toolTimeoutMs` 600000; otherwise ~45 s polls. @@ -78,3 +78,5 @@ Do not drive worker GUIs or CLIs. Session resume is Bridge's job. ACP `failure` supplements string `error` (fields: SETUP.md). Missing evidence or `failure.prompt_may_have_been_sent=true` forbids blind replay; false does not prove retry safety. Bridge never auto-retries prompts. For deduplication, send UUID `request_id` on the first dispatch; reuse its ID and exact arguments, including omitted `session_id`, on retry. Adding an ID only on retry cannot deduplicate earlier calls. Identical calls reuse the task (`reused=true`); changed arguments fail. Normal validation applies. Bindings last only in this instance until task pruning or restart; worker effects are not exactly-once. + +`check_task` / `get_result` on a task owned by another Bridge instance answer from `state.json` — with `from_state: true` and `silent_for_sec: null` — but `wait_task` / `cancel_task` still require the owning instance. diff --git a/ORCHESTRATION.zh-CN.md b/ORCHESTRATION.zh-CN.md index 6b9d491..0565185 100644 --- a/ORCHESTRATION.zh-CN.md +++ b/ORCHESTRATION.zh-CN.md @@ -72,7 +72,7 @@ Claude 的 `quota.status` 只汇总通用的 `5h` / `weekly` 额度。派发前 1. 先调 `list_agents`,选一个可用的 Worker。看返回里的 `coordinator.mode` / `coordinator.instructions` / `coordinator.dispatch_enabled`(用户偏好优先于第二步的默认分工),以及 `env.proxy` / `env.warnings`。`dispatch_enabled` 为 false 时立刻停止派发。直连网络上 proxy 为 null 是正常的;若机器需要代理而 Worker 报网络/连接错误,去改代理配置(仓库 `agents.toml` 或 `~/.agent-bridge/agents.toml` 里的 `[env.proxy]`),不要对同一次失败反复重试。 2. `dispatch_task` 的 `cwd` 必须是 **本次对话的项目目录**(绝对路径)。也就是你被启动时所在的文件夹——和用户自己 `cd` 再运行 `grok` / `kimi` / `agy` / `opencode` / `claude` 是同一个地方。Worker 的会话历史按 cwd 存放,换目录就是对方 UI 里的另一场对话,之后也更难看、更难续。**不要**把 Agent Bridge 的安装目录当作 cwd,除非用户正在改 Bridge 本身。不要自造临时目录。`message` 必须自洽:背景、绝对路径、验收标准、不要做什么。model 和 effort:没有特别理由就都不传,用 Worker 默认值——Antigravity 默认的 `gemini-3.7-flash` 就够了(要换才用 `agy models` 里的 slug)。确要指定时:Grok 的 `model` 是 `grok models` 里的 slug(用账号目录里有的,不要编),`effort` 为 `off` / `low` / `medium` / `high` / `max`(`off` → Grok `none`,`max` → Grok `xhigh`)。Grok 的 `/new` 总会落在活动默认模型上(目前是 grok-4.6 xhigh);Bridge 在会话建立后再 `session/setModel`。Kimi 的 `model` 取会话自己声明的那几个 slug(`kimi-code/k3`、`kimi-code/k3-256k`、`kimi-code/kimi-for-coding` 等),`effort` 还是那五个词,由 Bridge 映射到该模型声明的思考档位——k3 只声明 `low` / `high` / `max`,所以 `medium` 落到 `high`,`off` 落到 `low`。传了会话没声明的 slug 会让这一轮失败,错误里会列出真正可用的;`effort` 映射不上则只出 warning,不算失败。OpenCode 的 `model` 是会话声明的 `provider/model`(官方 OpenCode Zen / Go,或用 `opencode auth` 以 API key 接上的其它提供商——没有产品级登录)。`effort` 还是那五个词,映射到该模型的 variant(常见是 `default|low|medium|high`,`max` 通常落到 `high`)。未声明的 slug 会让这一轮失败;没有 effort 选项或映射不上只出 warning。`get_result.observed_model` / `observed_effort` 是 Bridge 映射后成功设上的最后值(例如 `max` → `high`),不是实时采样器转储。同一会话换模型会重新设 effort,因为 OpenCode 会把 variant 重置成新模型的默认。Bridge 用 `session/resume` 复活 OpenCode,不用 `session/load`。Claude Code 的 `model` 取会话声明的 slug(`sonnet` / `opus` / `haiku` 或完整 id),`effort` 还是那五个词(`off` → `default`,`max` → `xhigh`,除非会话列出了 `max`)。未声明的 slug 会让这一轮失败;没有 effort 选项或映射不上只出 warning。Bridge 在 `session/new` 后把模式切到 `bypassPermissions`,并用 `session/resume` 复活(`session/load` 会回放整段历史)。 Cursor 的 `model` 必须是 `cursor-agent --list-models` 当前列出的完整 ID;Bridge 会校验并固定首次启动,再把完整 ID 映射到 Cursor 会话声明的 ACP `model` 和参数选项。同一个 `session_id` 可以切换模型和变体;若所选模型声明了思考档位,单独传入的 `effort` 会覆盖 ID 中编码的档位。`observed_model` 是 Cursor 确认映射结果后的请求 ID,`observed_effort` 是 Cursor 确认的思考档位;两者都不是实时采样器。Codex CLI 的 `model` 是 Codex 自己的 slug(如 `gpt-5.6-sol`),`effort` 为 `off` / `low` / `medium` / `high` / `max`(`off` → `none`);默认 `--approve-for-me`,提示词走 stdin,用 `exec resume` 续会话;JSONL 建立前的启动失败会进入 `get_result.error`。Devin CLI 的 `model` 取会话声明的模型 id(`devin models list`;档位就在 id 里,如 `swe-1-7-medium`、`claude-opus-5-high`),未声明的 id 会让这一轮失败;`effort` 会被忽略并出 warning。Bridge 在 `session/new` 后把模式切到 `bypass`;续会话走 `session/load`,旧历史会被回放进 `get_transcript`(新一轮的 `get_result` 不受影响)。ZCode 的 `model` 是 `provider\model`,或在只对应一个选项时用裸模型 id(如 `GLM-5.3`);`effort` 映射到该模型的 thought 档(常见 `low|high|max`,`off` → `low`,`medium` → `high`)。未声明或有歧义的模型会让这一轮失败;映射不上只出 warning。Bridge 把模式切到 `yolo`,并用 `session/resume` 复活。MiniMax Code 的 `model` 是 `provider/model` 或 `provider/model#variant`;`effort` 映射到 `thinkingEffort`(`off` → `default`)。未声明的模型会让这一轮失败;映射不上只出 warning。Bridge 把 `permissionMode` 切到 `bypassPermissions`,并用 `session/resume` 复活。DSH 的 `model` 是 `provider/model` 或模型 id,`effort` 为 `off` / `low` / `high` / `max`。新版 `dsh --profile acp` 通过 `session/set_config_option` 在同一会话内切换——传了会话没声明的 model 会让这一轮失败,`effort` 映射不上只出 warning;旧版 `dsh-acp-demo` 走启动环境变量,改 model/effort 会重启进程(进程内不能切换),失败后换模型同样靠下次 `dispatch_task` 重启进程。 -3. 循环调用 `wait_task` 直到 `status` 为终态。超时不是失败,再调一次即可。`wait_task` / `check_task` 还会返回 `silent_for_sec`(Worker 最近一次输出到现在的秒数)。Worker 持续静默超过 `stall_timeout_sec`(默认 1800,可在 `agents.toml` 按 Worker 设置,0 关闭)时 Bridge 会取消这一轮,任务以 `status=failed`、`stop_reason="stalled"` 结束。长时间静默的构建和挂死的 Worker 看起来一样:如果那一步确实需要那么久,就调高该 Worker 的上限;否则在同一个 `session_id` 上派一个更小的任务。`timeout_sec` 必须低于宿主的 MCP 工具超时:Codex 配置 `tool_timeout_sec` 600,默认 180 即可;Cursor 宿主大约 45–60 秒,传约 30 并循环;Kimi Code 把 `toolTimeoutMs` 配到 600000,未配置则约 45 秒短轮询;ZCode 把 `timeoutMs` 配到 600000,未配置则约 15–20 秒短轮询;Grok Build 官方默认 `tool_timeout_sec` 是 6000,建议显式写成 600,拿不准或调用被掐掉时用约 30–45 秒短轮询;Claude Code 在 `.mcp.json` 里把每服务器 `timeout` 配成 600000(毫秒),CLI 默认很长,桌面端历史上大约 60 秒会掐掉,拿不准时用约 45 秒短轮询。等待期间可以并行做别的事。 +3. 循环调用 `wait_task` 直到 `status` 为终态。超时不是失败,再调一次即可。`wait_task` / `check_task` 还会返回 `silent_for_sec`(Worker 最近一次输出到现在的秒数)。Worker 持续静默超过 `stall_timeout_sec`(默认 1800,可在 `agents.toml` 按 Worker 设置,0 关闭)时 Bridge 会取消这一轮,任务以 `status=failed`、`stop_reason="stalled"` 结束。静默判定只看 Worker 输出——一直在产生事件的回合永远不会 stall。`turn_timeout_sec`(按 Worker 设置,默认 0 关闭)则给整轮设墙钟上限,超时以 `failed` / `timed_out` 结束。终态 `wait_task` 还带 `persisted`;为 `false` 表示 `state.json` 没写成功——结果仍然有效,但 Bridge 重启后可能丢失。`files_changed` 只列任务 `cwd` 内的路径;Worker 上报的 cwd 外路径进 `files_outside_cwd`(绝对路径,与 `files_changed` 同样截断,总数见 `files_outside_cwd_total`)。任务 warnings 里说 `session/load` 失败、先前上下文已丢失,表示 Worker 开了一个新的原生会话——下一条消息要重新带上上下文。长时间静默的构建和挂死的 Worker 看起来一样:如果那一步确实需要那么久,就调高该 Worker 的上限;否则在同一个 `session_id` 上派一个更小的任务。`timeout_sec` 必须低于宿主的 MCP 工具超时:Codex 配置 `tool_timeout_sec` 600,默认 180 即可;Cursor 宿主大约 45–60 秒,传约 30 并循环;Kimi Code 把 `toolTimeoutMs` 配到 600000,未配置则约 45 秒短轮询;ZCode 把 `timeoutMs` 配到 600000,未配置则约 15–20 秒短轮询;Grok Build 官方默认 `tool_timeout_sec` 是 6000,建议显式写成 600,拿不准或调用被掐掉时用约 30–45 秒短轮询;Claude Code 在 `.mcp.json` 里把每服务器 `timeout` 配成 600000(毫秒),CLI 默认很长,桌面端历史上大约 60 秒会掐掉,拿不准时用约 45 秒短轮询。等待期间可以并行做别的事。 4. 调 `get_result`;若 `has_more` 为 true,就继续用 `cursor=next_cursor` 读取并拼接所有分页。然后自己看 `git status` / `git diff`。该编的、该测的你来跑。不要只信 Worker 的自我汇报。Grok 的模型和 effort 以 `get_result.model` / `get_result.observed_model`(以及对应的 effort 字段)为准。`observed_model` 来自 Grok `events.jsonl` 的 `turn_started.model_id`。不要因为 Worker 说「I am Grok 4.6」或引用了 `You are Grok 4.6` 就判定切模型成败——那句横幅是 `/new` 写进系统提示的,`session/setModel` 换采样器时不会改它。Kimi 从不把失败的回合报成失败:它的 ACP 宿主会把失败回合映射成空文本的 `end_turn`,于是配额或服务端报错看起来和干净的空转一模一样。Kimi 交回空回合就要当可疑对待,去看 `get_result.warnings`——Bridge 每轮结束都会读 Kimi 的 `wire.jsonl`,把真实原因放在那里,旁边就是 `observed_model` / `observed_effort`。 5. 验收不通过时,用同一个 `session_id` 再 `dispatch_task`,并列出具体问题。最多跟进三轮。之后你自己改,并告诉用户。 6. 结束后总结 diff、剩余风险、用了哪个 Worker。不再需要时调用 `end_session`。 @@ -82,3 +82,5 @@ Claude 的 `quota.status` 只汇总通用的 `5h` / `weekly` 额度。派发前 ACP 失败保留字符串 `error`,并可附带 `failure`。`failure.prompt_may_have_been_sent=true` 或没有诊断证据时,不要盲目重发;false 也不保证初始化没有副作用或重试安全。Bridge 不自动重试 prompt。诊断字段详见 SETUP.md。 需要重试去重时,在首次调用 `dispatch_task` 前生成 UUID `request_id`,首次调用就传入。重试须使用同一 ID 和原始参数;首次省略了 `session_id`,重试也保持省略。只在重试时补 ID 无法对首次调用去重。相同参数复用原任务(`reused=true`),不同参数直接拒绝。去重只在同一 Bridge 实例内、原任务仍保留时有效,仍须通过正常派发校验。重启 Bridge、切换实例或清理原任务后不再保留绑定;Worker 的外部副作用不保证 exactly-once。 + +对另一个 Bridge 实例拥有的任务,`check_task` / `get_result` 从 `state.json` 作答——带 `from_state: true`、`silent_for_sec: null`;`wait_task` / `cancel_task` 仍须由拥有它的实例调用。 diff --git a/SETUP.md b/SETUP.md index eda3319..6c36eaf 100644 --- a/SETUP.md +++ b/SETUP.md @@ -62,7 +62,7 @@ npm install -g @deepseek-ai/dsh-acp-demo .\.venv\Scripts\python.exe scripts\install_dsh_acp.py ``` -The helper writes `$AGENT_BRIDGE_HOME/dsh-acp` (default `~/.agent-bridge/dsh-acp`) and installs the ACP peers the cordis file imports. Bridge copies that cordis file next to the chosen `node_modules` so ESM can resolve plugins. An unbuilt checkout `src/bin.ts` is ignored unless `tsx` is installed. DSH persistence is `$AGENT_BRIDGE_HOME/dsh-sessions/` so a user project does not get `./.sessions`. `get_result.files_changed` is a turn-scoped workspace diff, not only ACP tool_call events (DSH often sends none). It is capped at 200 paths; `files_changed_total` / `files_changed_truncated` tell you when to fall back to `git status`. `files_changed_state` is `pending` until that diff runs, `collected` when an empty list is a confirmed zero, and `unavailable` if collection could not run. +The helper writes `$AGENT_BRIDGE_HOME/dsh-acp` (default `~/.agent-bridge/dsh-acp`) and installs the ACP peers the cordis file imports. Bridge copies that cordis file next to the chosen `node_modules` so ESM can resolve plugins. An unbuilt checkout `src/bin.ts` is ignored unless `tsx` is installed. DSH persistence is `$AGENT_BRIDGE_HOME/dsh-sessions/` so a user project does not get `./.sessions`. `get_result.files_changed` is a turn-scoped workspace diff, not only ACP tool_call events (DSH often sends none). It is capped at 200 paths; `files_changed_total` / `files_changed_truncated` tell you when to fall back to `git status`. `files_changed_state` is `pending` until that diff runs, `collected` when an empty list is a confirmed zero, and `unavailable` if collection could not run. `files_changed` lists only paths inside the task `cwd`; worker-reported paths outside it land in `files_outside_cwd` (absolute, capped the same way, `files_outside_cwd_total`). `.agent-bridge` and Windows junctions are not scanned. Restart Codex after editing `config.toml`. @@ -287,6 +287,8 @@ Bridge rebuilds the environment **once at startup** (and again for each worker s | `[env.set]` | Explicit key/value map | | `[agents..env]` | Per-worker overlay | +`[env] deny = ["GLOB", ...]` removes worker env keys matching those globs. Keys set explicitly via `[env] set` or the agent's `env` always survive. There is no built-in denylist. + Do **not** put secrets in the repo `agents.toml`. Pin machine-local values in `%USERPROFILE%\.agent-bridge\agents.toml` (see [agents.toml.example](agents.toml.example)): ```toml @@ -327,7 +329,7 @@ error: failed to remove file `...\.venv\Lib\site-packages\../../Scripts/agent-br If you still launch from a checkout, use `uv --directory … run --no-sync agent-bridge` or `.venv/Scripts/python.exe -m agent_bridge`. POSIX hosts can replace a running binary, so this failure is Windows-only. `agent-bridge upgrade` / `uv tool upgrade` also need the coordinators closed first — same lock. -Instances share the `~/.agent-bridge` state directory but not sessions: every session and task record carries the identity of the Bridge instance that owns it. `list_sessions` shows only the calling instance's records, saves leave a live sibling's records untouched on disk, and records whose owning instance has exited are adopted at the next boot — their in-flight tasks surface as `failed` / `bridge_restarted`. A session started from one host is continued from that host; it does not appear in another host's `list_sessions` while its owner is alive. +Instances share the `~/.agent-bridge` state directory but not sessions: every session and task record carries the identity of the Bridge instance that owns it. `list_sessions` shows only the calling instance's records, saves leave a live sibling's records untouched on disk, and records whose owning instance has exited are adopted at the next boot — their in-flight tasks surface as `failed` / `bridge_restarted`. A session started from one host is continued from that host; it does not appear in another host's `list_sessions` while its owner is alive. `check_task` / `get_result` on a task owned by another instance answer from `state.json` (`from_state: true`, `silent_for_sec: null`); `wait_task` / `cancel_task` still require the owning instance. ## Server lifecycle @@ -481,7 +483,7 @@ opencode auth OpenCode has **no product login**. You connect providers by storing API keys (or that provider's own oauth) with `opencode auth`. Official routes are OpenCode Zen and OpenCode Go; anything else is just another connected provider. `list_agents` reports the CLI as available when `opencode` is on PATH — a missing provider key only shows up when a turn actually talks to the model. -`dispatch_task.model` is a `provider/model` slug the live session advertises (`opencode/...`, `xai/...`, …). `effort` maps onto that model's variants (`default|low|medium|high` is common; Bridge `max` usually becomes `high`). An unknown slug fails the turn and lists the real options; a model with no variants, or an effort that will not map, comes back as a warning. `get_result.observed_model` / `observed_effort` are the last values Bridge successfully set on the session after that mapping, not a live sampler dump. Switching model on a live session re-applies effort: OpenCode resets the variant to the new model's default. Bridge revives with `session/resume` rather than `session/load`. Permissions are ACP `requestPermission`; Bridge auto-picks `allow-always`. +`dispatch_task.model` is a `provider/model` slug the live session advertises (`opencode/...`, `xai/...`, …). `effort` maps onto that model's variants (`default|low|medium|high` is common; Bridge `max` usually becomes `high`). An unknown slug fails the turn and lists the real options; a model with no variants, or an effort that will not map, comes back as a warning. `get_result.observed_model` / `observed_effort` are the last values Bridge successfully set on the session after that mapping, not a live sampler dump. Switching model on a live session re-applies effort: OpenCode resets the variant to the new model's default. Bridge revives with `session/resume` rather than `session/load`. Permissions are ACP `requestPermission`; Bridge answers per `[agents.] permission_policy` — `allow_once` (default), `allow_always`, or `deny`. Under `allow_once` a prompt that offers only allow-always is denied. If OpenCode's configured default model is disabled, the first prompt fails with `Model is disabled`. Pass a slug from `opencode models` for a provider that still has a working key. @@ -517,7 +519,7 @@ $env:CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY = "1" If `OPENROUTER_API_KEY` is set and `ANTHROPIC_AUTH_TOKEN` is not, Bridge copies it and defaults the base URL to OpenRouter **only when** `ANTHROPIC_API_KEY` is also unset. A machine that uses OpenRouter for OpenCode and a direct Anthropic key for Claude keeps the Anthropic key. Set `ANTHROPIC_BASE_URL` yourself if you want that Anthropic key treated as a gateway conflict (Bridge then blanks it once a token and base URL are both present). -`dispatch_task.model` is a slug the live session advertises (`sonnet`, `opus`, `haiku`, or a full id). `effort` maps onto that model's levels (`default|low|medium|high|xhigh` is common; Bridge `off` → `default`, `max` → `xhigh` unless the session lists `max`). An unknown slug fails the turn and lists the real options; a model with no effort option, or an effort that will not map, comes back as a warning. `get_result.observed_model` / `observed_effort` are the last values Bridge successfully set after that mapping. Switching model on a live session re-applies effort. Bridge forces `bypassPermissions` after `session/new` (a fresh session starts in manual `default` mode); if that mode is not advertised — for example when the process is root — ACP `requestPermission` still auto-picks `allow-always`. Revive uses `session/resume`: `session/load` replays the whole history. +`dispatch_task.model` is a slug the live session advertises (`sonnet`, `opus`, `haiku`, or a full id). `effort` maps onto that model's levels (`default|low|medium|high|xhigh` is common; Bridge `off` → `default`, `max` → `xhigh` unless the session lists `max`). An unknown slug fails the turn and lists the real options; a model with no effort option, or an effort that will not map, comes back as a warning. `get_result.observed_model` / `observed_effort` are the last values Bridge successfully set after that mapping. Switching model on a live session re-applies effort. Bridge forces `bypassPermissions` after `session/new` (a fresh session starts in manual `default` mode); if that mode is not advertised — for example when the process is root — ACP `requestPermission` is still answered per `[agents.] permission_policy` (`allow_once` default; a prompt offering only allow-always is denied). Revive uses `session/resume`: `session/load` replays the whole history. ## Worker: Devin CLI diff --git a/agents.toml.example b/agents.toml.example index 159ac61..c5880fe 100644 --- a/agents.toml.example +++ b/agents.toml.example @@ -15,8 +15,17 @@ # Cancel a turn whose worker has produced no output for this long (seconds). # Default 1800; 0 disables. Raise it for a worker that runs long silent # builds or test suites. The task then ends failed / stop_reason "stalled". +# turn_timeout_sec instead caps a turn's wall-clock regardless of output +# (default 0 = off; timeout ends failed / "timed_out"). # [agents.grok] # stall_timeout_sec = 3600 +# turn_timeout_sec = 7200 + +# How Bridge answers ACP permission prompts: allow_once (default, least +# privilege), allow_always, or deny. Under allow_once a prompt that offers +# only allow-always is denied. +# [agents.grok] +# permission_policy = "allow_always" # Dispatch policy: mode = manual | auto | eager (default auto). # instructions is free text the coordinator reads via list_agents; it @@ -44,6 +53,11 @@ # [env.set] # DEEPSEEK_API_KEY = "do-not-commit" +# Remove worker env keys matching these globs. Keys set via [env.set] or +# the agent's own env always survive; there is no built-in denylist. +# [env] +# deny = ["AWS_*", "DATABASE_URL"] + # [agents.grok.env] # HTTPS_PROXY = "http://127.0.0.1:7897" diff --git a/skills/agent-bridge/SKILL.md b/skills/agent-bridge/SKILL.md index d31b06f..e553ca1 100644 --- a/skills/agent-bridge/SKILL.md +++ b/skills/agent-bridge/SKILL.md @@ -45,7 +45,7 @@ Examples: "fix the README typo" → yourself. "Add a None check at line 120" → ## The dispatch loop 1. `dispatch_task` with `cwd` = **this conversation's project folder** (absolute) — never the Agent Bridge install path, never a temp dir. The `message` must be self-contained: background, absolute paths, acceptance criteria, things not to do. Leave `model`/`effort` unset unless you have a reason; slugs and effort mappings per worker are documented in ORCHESTRATION.md in the Agent-Bridge repo. -2. Loop `wait_task` until terminal. A timeout is **not** failure — call it again. `silent_for_sec` in the payload is the time since the worker's last output; a turn silent past `stall_timeout_sec` (default 1800) ends `failed` / `stop_reason="stalled"` — raise that worker's limit in `agents.toml` if the step was legitimately long. Size `timeout_sec` under the host MCP tool timeout: +2. Loop `wait_task` until terminal. A timeout is **not** failure — call it again. `silent_for_sec` in the payload is the time since the worker's last output; a turn silent past `stall_timeout_sec` (default 1800) ends `failed` / `stop_reason="stalled"` — raise that worker's limit in `agents.toml` if the step was legitimately long. Stall counts only worker output; `turn_timeout_sec` (default 0 = off) instead caps a turn's wall-clock and ends `failed` / `timed_out`. A terminal `wait_task` carries `persisted`; `false` means `state.json` could not be written — the result is still valid but may not survive a restart. `files_changed` lists only paths inside the task `cwd`; outside-cwd paths land in `files_outside_cwd` (absolute, capped the same way, `files_outside_cwd_total`). A warning that `session/load` failed and prior context is lost means a fresh native session — re-supply context next message. Size `timeout_sec` under the host MCP tool timeout: - Codex: `tool_timeout_sec` 600; default 180 is fine. - Cursor: host ~45–60 s; pass ~30 and loop. - Kimi Code: configure `toolTimeoutMs` 600000; otherwise ~45 s polls. @@ -59,3 +59,5 @@ Examples: "fix the README typo" → yourself. "Add a None check at line 120" → ACP failures retain string `error` plus optional `failure`. If `failure.prompt_may_have_been_sent` is true or evidence is missing, do not blindly replay; false is not proof of safe retry. Bridge never auto-retries prompts. See SETUP.md for diagnostic fields. For optional retry deduplication, send a UUID `request_id` on the first `dispatch_task` call, then retry with the same ID and original arguments; keep `session_id` omitted if it was originally omitted. Adding an ID only on retry cannot deduplicate the first call. Identical retries reuse the task (`reused=true`) only within the same Bridge instance while the task is retained. Different arguments are rejected, and normal dispatch validation still applies. Restart, another instance, or task pruning loses the binding; this does not guarantee exactly-once worker side effects. + +`check_task` / `get_result` on a task owned by another Bridge instance answer from `state.json` (`from_state: true`, `silent_for_sec: null`); `wait_task` / `cancel_task` still require the owning instance. diff --git a/src/agent_bridge/adapters/acp.py b/src/agent_bridge/adapters/acp.py index 0d6b91e..7b96597 100644 --- a/src/agent_bridge/adapters/acp.py +++ b/src/agent_bridge/adapters/acp.py @@ -31,6 +31,7 @@ ) from agent_bridge.config import AgentConfig from agent_bridge.devin_meta import DEVIN_MODE_BYPASS, apply_devin_env +from agent_bridge.diagnostics import redact_diagnostic as _redact_diagnostic from agent_bridge.dsh_home import command_has_native_acp, prepare_dsh_launch, resolve_dsh_command from agent_bridge.kimi_meta import KIMI_MODE_YOLO, resolve_kimi_thinking from agent_bridge.minimax_meta import ( @@ -97,19 +98,6 @@ def _tool_io_summary(value: Any) -> str | None: return text if len(text) <= _TOOL_IO_LIMIT else text[:_TOOL_IO_LIMIT] + "…" -def _redact_diagnostic(text: str) -> str: - text = re.sub(r"\x1b\[[0-?]*[ -/]*[@-~]", "", text) - text = re.sub(r"(?im)^.*(?:authorization|(?:set-)?cookie)\s*[:=].*$", "[redacted]", text) - text = re.sub( - r"""(?i)(\b(?:[\w-]*(?:token|secret|password|api[_-]?key)|authorization|cookie)\b["']?\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;]+)""", - r"\1[redacted]", text, - ) - text = re.sub(r"(?i)\b(?:bearer|basic)\s+\S+", "[redacted]", text) - text = re.sub(r"""(?i)\b(?:https?|wss?)://[^\s<>"']+""", "[redacted URL]", text) - text = re.sub(r"\b(?:sk-[\w-]+|gh[pousr]_\w+)\b", "[redacted]", text) - return text[:2048] - - def _stderr_summary(text: str) -> str | None: hints = re.findall( r"\b(?:authentication required|not logged in|unauthorized|permission denied|" @@ -484,18 +472,35 @@ def _text_of(content: Any) -> str: return str(dumped) -def _pick_permission_option(options: Iterable[PermissionOption]) -> PermissionOption | None: +def _pick_permission_option( + options: Iterable[PermissionOption], + policy: str = "allow_once", +) -> PermissionOption | None: + """Pick the permission option matching the agent's policy. + + Bridge is the only approver in the loop — there is no human to click + "allow". Default policy ``allow_once`` grants each request for this turn + only; ``allow_always`` additionally persists the grant inside the worker; + ``deny`` cancels every request. + """ + if policy == "deny": + return None + allow_always_first = policy == "allow_always" ranked: list[tuple[int, PermissionOption]] = [] for option in options: kind = str(getattr(option, "kind", "")).lower().replace("_", "-") option_id = str(getattr(option, "option_id", "")).lower().replace("_", "-") blob = f"{kind} {option_id}" if "allow-always" in blob or kind == "allow-always": + # Under any non-allow_always policy a persistent grant must not be + # picked — falling back to it would make a one-time policy lie. + if not allow_always_first: + continue score = 0 elif "allow-once" in blob or kind == "allow-once" or blob.strip().startswith("allow"): - score = 1 + score = 1 if allow_always_first else 0 else: - score = 50 + score = 50 if allow_always_first else 90 ranked.append((score, option)) ranked.sort(key=lambda item: item[0]) return ranked[0][1] if ranked else None @@ -508,9 +513,10 @@ async def _observe_exit(proc: asyncio.subprocess.Process | None) -> None: class _BridgeClient: - def __init__(self, session_id: str, home: Path) -> None: + def __init__(self, session_id: str, home: Path, permission_policy: str = "allow_once") -> None: self.session_id = session_id self.home = home + self.permission_policy = permission_policy self.text_parts: list[str] = [] self.files: set[str] = set() self.usage: dict[str, Any] = {} @@ -529,7 +535,7 @@ async def request_permission( options: list[Any] | None, **kwargs: Any, ) -> RequestPermissionResponse: - option = _pick_permission_option(options or []) + option = _pick_permission_option(options or [], self.permission_policy) dumped = _dump(tool_call) if option is None: append_event( @@ -839,6 +845,7 @@ async def _spawn(self, session: Session) -> _Live: session_id=session.session_id, model=session.model, effort=session.effort, + env_cfg=self.env_config, ) elif self.agent.name == "grok": cmd = with_grok_cli_selection(cmd, session.model, session.effort) @@ -872,7 +879,9 @@ async def _spawn(self, session: Session) -> _Live: raise RuntimeError(f"{self.agent.name} did not expose stdio") live = _Live() live.proc = proc - live.client = _BridgeClient(session.session_id, self.home) + live.client = _BridgeClient( + session.session_id, self.home, self.agent.permission_policy + ) live.conn = connect_to_agent(live.client, proc.stdin, proc.stdout) live.stderr_task = asyncio.create_task( self._drain_stderr(proc, session.session_id, live) diff --git a/src/agent_bridge/adapters/antigravity.py b/src/agent_bridge/adapters/antigravity.py index eed8823..3b8ce8f 100644 --- a/src/agent_bridge/adapters/antigravity.py +++ b/src/agent_bridge/adapters/antigravity.py @@ -14,6 +14,7 @@ from agent_bridge.adapters.base import STDIO_LIMIT, Adapter from agent_bridge.config import AgentConfig +from agent_bridge.diagnostics import redact_diagnostic from agent_bridge.models import Session, Task, TurnResult, agy_effort from agent_bridge.processes import ( drop_pid, @@ -447,7 +448,12 @@ async def run_turn(self, session: Session, task: Task) -> TurnResult: native_session_id=cid, warnings=[err, *exit_warnings], ) - append_event(session.session_id, "error", {"error": err, "code": proc.returncode}, self.home) + append_event( + session.session_id, + "error", + {"error": redact_diagnostic(err), "code": proc.returncode}, + self.home, + ) return TurnResult( text=result_text, files_changed=sorted(files), diff --git a/src/agent_bridge/adapters/codex.py b/src/agent_bridge/adapters/codex.py index af25379..72fb29c 100644 --- a/src/agent_bridge/adapters/codex.py +++ b/src/agent_bridge/adapters/codex.py @@ -19,6 +19,7 @@ resolve_codex_command, yolo_requested, ) +from agent_bridge.diagnostics import redact_diagnostic from agent_bridge.models import Session, Task, TurnResult from agent_bridge.processes import ( drop_pid, @@ -207,7 +208,9 @@ async def run_turn(self, session: Session, task: Task) -> TurnResult: observed_effort=observed_effort, ) if stop_reason == "error": - append_event(session.session_id, "error", {"error": error}, self.home) + append_event( + session.session_id, "error", {"error": redact_diagnostic(error or "")}, self.home + ) return TurnResult( text=state.text, files_changed=sorted(state.files), diff --git a/src/agent_bridge/codex_exec.py b/src/agent_bridge/codex_exec.py index 8f49627..17c4ebd 100644 --- a/src/agent_bridge/codex_exec.py +++ b/src/agent_bridge/codex_exec.py @@ -8,6 +8,7 @@ from pathlib import Path from typing import Any +from agent_bridge.diagnostics import redact_diagnostic from agent_bridge.processes import resolve_command log = logging.getLogger(__name__) @@ -289,13 +290,15 @@ def finalize_codex_turn( if returncode not in (0, None): warnings.append(f"codex exited with code {returncode}") if state.turn_failed: - return "error", state.error or "codex turn failed", warnings + return "error", redact_diagnostic(state.error or "codex turn failed"), warnings if state.turn_completed: - warnings.extend(state.errors) + warnings.extend(redact_diagnostic(err) for err in state.errors) return "end_turn", None, warnings if state.errors: - return "error", state.error or "codex turn failed", warnings - stderr_error = (stderr or "").strip() + return "error", redact_diagnostic(state.error or "codex turn failed"), warnings + # Codex stderr is raw worker output (may echo env secrets it read); + # sanitize before it becomes the task's error text. + stderr_error = redact_diagnostic((stderr or "").strip()) if stderr_error: return "error", stderr_error, warnings error = ( diff --git a/src/agent_bridge/config.py b/src/agent_bridge/config.py index ed952bd..3d79a4f 100644 --- a/src/agent_bridge/config.py +++ b/src/agent_bridge/config.py @@ -121,6 +121,11 @@ class AgentConfig(BaseModel): # stall_timeout_sec alone cannot see that case (H-16). turn_timeout_sec: int = Field(default=0, ge=0) print_timeout: str = "120m" + # How Bridge answers worker permission prompts when no human is present: + # "allow_once" grants each request for that call only (default, least + # privilege), "allow_always" persists the grant inside the worker, + # "deny" cancels every request. + permission_policy: str = "allow_once" class EnvConfig(BaseModel): @@ -131,6 +136,9 @@ class EnvConfig(BaseModel): set: dict[str, str] = Field(default_factory=dict) proxy_url: str | None = None no_proxy: str | None = None + # Glob patterns of env keys a worker subprocess must never see; keys + # explicitly assigned via ``set``/agent ``env`` always survive. + deny: list[str] = Field(default_factory=list) class ServerConfig(BaseModel): @@ -251,7 +259,9 @@ def _coerce_env(raw: dict[str, Any]) -> dict[str, Any]: proxy: dict[str, Any] = raw_proxy if isinstance(raw_proxy, dict) else {} out: dict[str, Any] = {} if "inherit" in block and block["inherit"] is not None: - out["inherit"] = [str(item) for item in block["inherit"]] + raw_inherit = block["inherit"] + # A bare string is one name, not an iterable of characters. + out["inherit"] = [raw_inherit] if isinstance(raw_inherit, str) else [str(item) for item in raw_inherit] if "discover_proxy" in block: out["discover_proxy"] = bool(block["discover_proxy"]) if isinstance(block.get("set"), dict): @@ -262,6 +272,10 @@ def _coerce_env(raw: dict[str, Any]) -> dict[str, Any]: no_proxy = proxy.get("no_proxy") or proxy.get("no") or block.get("no_proxy") if no_proxy: out["no_proxy"] = str(no_proxy).strip() + if "deny" in block and block["deny"] is not None: + raw_deny = block["deny"] + # A bare string is one glob, not an iterable of characters. + out["deny"] = [raw_deny] if isinstance(raw_deny, str) else [str(item) for item in raw_deny] return out @@ -272,6 +286,10 @@ def _merge_env(base: dict[str, Any], overlay: dict[str, Any]) -> dict[str, Any]: raw_set = out.get("set") current: dict[str, Any] = raw_set if isinstance(raw_set, dict) else {} out["set"] = {**current, **value} + elif key == "deny" and isinstance(value, list): + raw_deny = out.get("deny") + deny_list: list[Any] = raw_deny if isinstance(raw_deny, list) else [] + out["deny"] = [*deny_list, *value] else: out[key] = value return out diff --git a/src/agent_bridge/diagnostics.py b/src/agent_bridge/diagnostics.py new file mode 100644 index 0000000..3a7a2ac --- /dev/null +++ b/src/agent_bridge/diagnostics.py @@ -0,0 +1,29 @@ +"""Sanitization for worker-derived diagnostic text before it crosses into +trusted surfaces (state.json, transcripts, MCP responses, logs). + +Worker output is untrusted: a worker can print anything, including secrets +it read from its environment. Anything persisted or returned to the +coordinator must pass through ``redact_diagnostic`` first. Only diagnostic +channels (error text, warnings, stderr tails) are sanitized — result bodies +and structured event payloads are the product's output and are left alone. +""" + +from __future__ import annotations + +import re + +_REDACT_LIMIT = 4096 + + +def redact_diagnostic(text: str) -> str: + text = re.sub(r"\x1b\[[0-?]*[ -/]*[@-~]", "", text) + text = re.sub(r"(?im)^.*(?:authorization|(?:set-)?cookie)\s*[:=].*$", "[redacted]", text) + text = re.sub( + r"""(?i)(\b(?:[\w-]*(?:token|secret|password|api[_-]?key)|authorization|cookie)\b["']?\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;]+)""", + r"\1[redacted]", + text, + ) + text = re.sub(r"(?i)\b(?:bearer|basic)\s+\S+", "[redacted]", text) + text = re.sub(r"""(?i)\b(?:https?|wss?)://[^\s<>"']+""", "[redacted URL]", text) + text = re.sub(r"\b(?:sk-[\w-]+|gh[pousr]_\w+|tp-[A-Za-z0-9_-]{16,})\b", "[redacted]", text) + return text[:_REDACT_LIMIT] diff --git a/src/agent_bridge/dsh_home.py b/src/agent_bridge/dsh_home.py index c432ad3..b9626b8 100644 --- a/src/agent_bridge/dsh_home.py +++ b/src/agent_bridge/dsh_home.py @@ -7,10 +7,12 @@ from collections.abc import Mapping from pathlib import Path +from agent_bridge.config import EnvConfig from agent_bridge.models import dsh_effort from agent_bridge.paths import bridge_home, bundled_dsh_cordis from agent_bridge.processes import resolve_command from agent_bridge.worker_env import ( + denied_by_policy, pick_env_keys, read_windows_machine_env, read_windows_user_env, @@ -477,11 +479,14 @@ def apply_dsh_worker_env( effort: str | None = None, user_env: Mapping[str, str] | None = None, machine_env: Mapping[str, str] | None = None, + env_cfg: EnvConfig | None = None, ) -> dict[str, str]: """Attach DSH home, the user's saved default model, and credential env refs. No provider is required. Official DeepSeek is only one of the routes DSH already knows; users configure providers in ``$DSH_HOME/settings.yaml``. + ``env_cfg`` re-applies the env deny policy to keys filled from the host's + user/machine env so a denied credential cannot re-enter here. """ out = dict(env) home = dsh_home(out) @@ -498,6 +503,8 @@ def apply_dsh_worker_env( user = user_env if user_env is not None else read_windows_user_env() for incoming in (machine, user): for key, value in pick_env_keys(incoming, extra_keys).items(): + if key not in out and env_cfg is not None and denied_by_policy(key, env_cfg): + continue out.setdefault(key, value) roots = _node_module_roots(command or []) if roots: @@ -535,6 +542,7 @@ def prepare_dsh_launch( effort: str | None = None, user_env: Mapping[str, str] | None = None, machine_env: Mapping[str, str] | None = None, + env_cfg: EnvConfig | None = None, ) -> tuple[list[str], dict[str, str]]: return with_bridge_cordis(command), apply_dsh_worker_env( env, @@ -544,4 +552,5 @@ def prepare_dsh_launch( effort=effort, user_env=user_env, machine_env=machine_env, + env_cfg=env_cfg, ) diff --git a/src/agent_bridge/registry.py b/src/agent_bridge/registry.py index 4bcf685..f18b06f 100644 --- a/src/agent_bridge/registry.py +++ b/src/agent_bridge/registry.py @@ -25,6 +25,7 @@ normalize_coordinator_mode, write_coordinator_overlay, ) +from agent_bridge.diagnostics import redact_diagnostic from agent_bridge.grok_observe import observe_grok_session from agent_bridge.kimi_observe import observe_kimi_session from agent_bridge.models import ( @@ -98,8 +99,9 @@ STATE_WRITE_ATTEMPTS = 5 STATE_WRITE_RETRY_BASE_SEC = 0.05 STATE_LOCK_TIMEOUT_SEC = 5.0 -# flush_state() waits for the saves issued at call time; write failures -# degrade to a logged warning instead of raising into the caller. +# flush_state() waits for the saves issued at call time and returns whether +# that generation reached disk; start()/stop() raise on False, wait_task +# reports it as ``persisted``. STATE_FLUSH_ATTEMPTS = 3 # Poll cadence while flush_state() waits on the shared flusher; small so a # terminal wait_task does not add up to a full second under save traffic. @@ -832,7 +834,9 @@ async def _run_task(self, task_id: str) -> None: if result.native_session_id: session.native_session_id = result.native_session_id task.result_chars = len(result.text) - task.warnings = list(result.warnings) + # Worker-derived text crosses the trust boundary here: scrub + # before it lands in state.json/transcripts/MCP replies. + task.warnings = [redact_diagnostic(w) for w in result.warnings] try: atomic_write_text(result_path(task.task_id, self.home), result.text) task.result_text = _tail(result.text) @@ -859,7 +863,8 @@ async def _run_task(self, task_id: str) -> None: # Kimi answered end_turn, so nothing above this line knows # the turn failed. Say so where the coordinator looks. task.warnings.append( - f"kimi reported end_turn but the turn failed: {observed['failure']}" + "kimi reported end_turn but the turn failed: " + + redact_diagnostic(str(observed["failure"])) ) else: # OpenCode (and any later ACP worker) has no on-disk sampler @@ -876,7 +881,7 @@ async def _run_task(self, task_id: str) -> None: task.stop_reason = "cancelled" else: task.status = TaskStatus.failed - task.error = result.error + task.error = redact_diagnostic(result.error) elif result.stop_reason == "cancelled": task.status = TaskStatus.cancelled else: @@ -899,7 +904,7 @@ async def _run_task(self, task_id: str) -> None: task.failure = None else: task.status = TaskStatus.failed - task.error = str(exc) + task.error = redact_diagnostic(str(exc)) task.failure = exc.failure if isinstance(exc, AcpError) else None task.stop_reason = "error" finally: diff --git a/src/agent_bridge/worker_env.py b/src/agent_bridge/worker_env.py index 7790e2e..a048b3b 100644 --- a/src/agent_bridge/worker_env.py +++ b/src/agent_bridge/worker_env.py @@ -1,5 +1,6 @@ from __future__ import annotations +import fnmatch import logging import os import re @@ -507,6 +508,41 @@ def install_host_env(config: EnvConfig, *, base: Mapping[str, str] | None = None return status +def denied_by_policy(key: str, cfg: EnvConfig, explicit: set[str] | None = None) -> bool: + """True when the user's ``env.deny`` globs would strip ``key`` from a worker env. + + There is no built-in denylist: a default deny hid AWS_*/SSH_*/etc. from + workers that legitimately need them (Bedrock/Vertex auth, git-over-ssh), + so only the operator's configured globs strip keys. Shared by + _apply_env_deny and injection points downstream of it (e.g. the DSH + launch helper pulling credential refs from Windows env) so a denied key + cannot re-enter through another code path. + """ + if explicit and key in explicit: + return False + user_deny = [str(pat) for pat in (cfg.deny or []) if str(pat).strip()] + return any(fnmatch.fnmatchcase(key, pat) for pat in user_deny) + + +def _apply_env_deny( + env: dict[str, str], + origin: dict[str, str], + cfg: EnvConfig, + explicit: set[str], +) -> None: + """Strip env keys matching the user's ``env.deny`` globs. + + Explicit intent always wins: a key assigned through ``env.set`` or the + agent's own ``env`` block survives any pattern. Denied keys are recorded + as ``origin[key] = "denied"`` so describe_env can tell withheld from + absent. + """ + for key in list(env): + if denied_by_policy(key, cfg, explicit): + env.pop(key, None) + origin[key] = "denied" + + def build_worker_env( overrides: Mapping[str, str] | None = None, *, @@ -529,6 +565,9 @@ def build_worker_env( user_env=user_env, machine_env=machine_env, ) + cfg = config or EnvConfig() + explicit = set(cfg.set) | set(overrides or {}) + _apply_env_deny(env, origin, cfg, explicit) # After every merge so agents.toml / inherited env cannot clear the mark. # Also pin a nested data dir: if the worker inherits this MCP server, the # nested Bridge must not share the coordinator's state.json. A host MCP diff --git a/tests/test_config.py b/tests/test_config.py index e842f75..49484d3 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -381,3 +381,36 @@ def test_load_config_reports_overlay_path_on_bad_toml(tmp_path): load_config(tmp_path) assert str(path) in str(exc_info.value) assert "Fix or delete the file" in str(exc_info.value) + + +def test_env_deny_overlay(tmp_path): + (tmp_path / "agents.toml").write_text( + """ +[env] +deny = ["APP_*"] +""", + encoding="utf-8", + ) + cfg = load_config(tmp_path) + assert "APP_*" in cfg.env.deny + + +def test_merge_env_unions_deny_lists(): + from agent_bridge.config import _merge_env + + merged = _merge_env({"deny": ["A_*"]}, {"deny": ["B_*"]}) + assert merged["deny"] == ["A_*", "B_*"] + + +def test_permission_policy_default_and_overlay(tmp_path): + cfg = load_config(tmp_path) + assert cfg.agents["claude"].permission_policy == "allow_once" + (tmp_path / "agents.toml").write_text( + """ +[agents.claude] +permission_policy = "deny" +""", + encoding="utf-8", + ) + cfg = load_config(tmp_path) + assert cfg.agents["claude"].permission_policy == "deny" diff --git a/tests/test_diagnostics.py b/tests/test_diagnostics.py new file mode 100644 index 0000000..2e0f370 --- /dev/null +++ b/tests/test_diagnostics.py @@ -0,0 +1,77 @@ +from __future__ import annotations + +from types import SimpleNamespace + +from acp.schema import PermissionOption + +from agent_bridge.adapters.acp import _pick_permission_option +from agent_bridge.diagnostics import redact_diagnostic + + +def _opt(kind: str, name: str = "") -> PermissionOption: + return PermissionOption(optionId=f"{kind}-id", name=name or kind, kind=kind) # type: ignore[arg-type] + + +def test_redact_diagnostic_scrubs_key_value_secrets(): + text = "auth failed\napi_key=tp-abcdef0123456789\nAuthorization: Bearer tp-abcdef0123456789" + out = redact_diagnostic(text) + assert "tp-abcdef0123456789" not in out + assert "[redacted]" in out + + +def test_redact_diagnostic_scrubs_bare_tokens_and_urls(): + text = "leak sk-proj-abc123ghp_xyz789 then https://api.example.com/v1?k=secret" + out = redact_diagnostic(text) + assert "sk-proj-abc123" not in out + assert "ghp_xyz789" not in out + assert "api.example.com" not in out + + +def test_redact_diagnostic_strips_ansi_and_caps(): + assert "\x1b[31m" not in redact_diagnostic("\x1b[31mred\x1b[0m") + assert len(redact_diagnostic("x" * 100_000)) <= 4096 + + +def test_redact_diagnostic_keeps_plain_errors(): + assert redact_diagnostic("codex exited with code 1") == "codex exited with code 1" + + +def test_permission_default_policy_prefers_allow_once(): + options = [_opt("reject_once"), _opt("allow_always"), _opt("allow_once")] + picked = _pick_permission_option(options) + assert picked is not None and picked.kind == "allow_once" + + +def test_permission_allow_always_policy_picks_allow_always(): + options = [_opt("allow_once"), _opt("reject_once"), _opt("allow_always")] + picked = _pick_permission_option(options, "allow_always") + assert picked is not None and picked.kind == "allow_always" + + +def test_permission_allow_always_falls_back_to_allow_once(): + options = [_opt("reject_once"), _opt("allow_once")] + picked = _pick_permission_option(options, "allow_always") + assert picked is not None and picked.kind == "allow_once" + + +def test_permission_deny_policy_returns_none(): + options = [_opt("allow_once"), _opt("allow_always")] + assert _pick_permission_option(options, "deny") is None + + +def test_permission_allow_once_never_picks_allow_always(): + # A persistent grant must not satisfy a one-time policy — review finding: + # falling back to allow_always made allow_once lie. + options = [_opt("reject_once"), _opt("allow_always")] + picked = _pick_permission_option(options, "allow_once") + assert picked is not None and picked.kind == "reject_once" + assert _pick_permission_option([_opt("allow_always")], "allow_once") is None + + +def test_permission_unknown_policy_behaves_like_allow_once(): + options = [ + SimpleNamespace(kind="allow_always", option_id="always"), + SimpleNamespace(kind="allow_once", option_id="once"), + ] + picked = _pick_permission_option(options, "bogus") + assert picked is not None and picked.option_id == "once" diff --git a/tests/test_docs.py b/tests/test_docs.py index d545f9c..1c12475 100644 --- a/tests/test_docs.py +++ b/tests/test_docs.py @@ -74,7 +74,7 @@ def test_setup_zcode_points_at_mcp_settings_not_plugin_marketplace(): def test_orchestration_english_stays_under_char_budget(): text = _read("ORCHESTRATION.md") - assert len(text) <= 9500 + assert len(text) <= 10500 def test_readme_explains_coordinator_modes(): diff --git a/tests/test_registry.py b/tests/test_registry.py index 8569e5d..e0be3d0 100644 --- a/tests/test_registry.py +++ b/tests/test_registry.py @@ -1985,6 +1985,38 @@ async def slow_cancel(self, session): await registry.stop() +@pytest.mark.asyncio +async def test_worker_error_and_warnings_are_sanitized_before_persisting( + bridge_home, tmp_path, monkeypatch +): + """H-04: worker-derived text crosses into state.json/transcripts — scrub it.""" + secret = "tp-leak0123456789abcdef" + + async def leaky_turn(self, session, task): + return TurnResult( + text="", + stop_reason="error", + error=f"worker boom: Authorization: Bearer {secret} api_key={secret}", + warnings=[f"Set-Cookie: session={secret}"], + ) + + monkeypatch.setattr(FakeAdapter, "run_turn", leaky_turn) + registry = Registry.create(bridge_home) + await registry.start() + try: + dispatched = await registry.dispatch_task("fake", "leak", cwd=str(tmp_path)) + waited = await registry.wait_task(dispatched["task_id"], timeout_sec=5) + assert waited["status"] == "failed" + assert secret not in (waited["error"] or "") + assert "[redacted]" in (waited["error"] or "") + assert secret not in json.dumps(waited["warnings"]) + registry.save() + state = json.loads(state_path(bridge_home).read_text(encoding="utf-8")) + assert secret not in json.dumps(state) + finally: + await registry.stop() + + @pytest.mark.asyncio async def test_turn_timeout_sec_caps_chatty_turn(bridge_home, tmp_path, monkeypatch): """H-16: a worker emitting worker-type events forever still hits the cap.""" diff --git a/tests/test_worker_env.py b/tests/test_worker_env.py index c952443..d180afd 100644 --- a/tests/test_worker_env.py +++ b/tests/test_worker_env.py @@ -204,3 +204,64 @@ def test_is_worker_context_strict_value(): assert is_worker_context({WORKER_CONTEXT_ENV: "coordinator"}) is False assert is_worker_context({}) is False assert is_worker_context({WORKER_CONTEXT_ENV: "Worker"}) is False + + +def _env(base, *, config=None, overrides=None): + return build_worker_env( + overrides, + config=config, + base=base, + fallbacks={}, + user_env={}, + machine_env={}, + log_fill=False, + ) + + +def test_worker_env_no_default_deny_but_user_deny_applies(): + env = _env( + { + "AWS_REGION": "us-east-1", + "SSH_AUTH_SOCK": "/tmp/agent.sock", + "DATABASE_URL": "postgres://u:p@db", + "HOME": "/h", + } + ) + assert env["AWS_REGION"] == "us-east-1" + assert env["SSH_AUTH_SOCK"] == "/tmp/agent.sock" + assert env["DATABASE_URL"] == "postgres://u:p@db" + cfg = EnvConfig(deny=["AWS_*"]) + env = _env( + {"AWS_REGION": "us-east-1", "SSH_AUTH_SOCK": "/tmp/agent.sock"}, config=cfg + ) + assert "AWS_REGION" not in env + assert env["SSH_AUTH_SOCK"] == "/tmp/agent.sock" + + +def test_worker_env_explicit_set_and_agent_env_survive_deny(): + cfg = EnvConfig(set={"AWS_SECRET_ACCESS_KEY": "configured"}, deny=["AWS_*"]) + env = _env({}, config=cfg) + assert env["AWS_SECRET_ACCESS_KEY"] == "configured" + env = _env( + {"GITHUB_TOKEN": "agent-wants"}, + overrides={"GITHUB_TOKEN": "agent-wants"}, + config=EnvConfig(deny=["GITHUB_*"]), + ) + assert env["GITHUB_TOKEN"] == "agent-wants" + + +def test_worker_env_inherit_does_not_exempt_user_deny(): + # Both keys arrive via the process env; naming one in ``inherit`` does + # not exempt it from the user's deny globs. + cfg = EnvConfig(inherit=["AWS_SECRET_ACCESS_KEY"], deny=["AWS_*"]) + env = _env({"AWS_SECRET_ACCESS_KEY": "s3cr3t", "AWS_REGION": "us"}, config=cfg) + assert "AWS_SECRET_ACCESS_KEY" not in env + assert "AWS_REGION" not in env + + +def test_worker_env_user_deny_patterns(): + cfg = EnvConfig(deny=["*_DEBUG", "CUSTOM*"]) + env = _env({"APP_DEBUG": "1", "CUSTOM_FLAG": "x", "KEEP": "y"}, config=cfg) + assert "APP_DEBUG" not in env + assert "CUSTOM_FLAG" not in env + assert env["KEEP"] == "y"