Repository navigation
fix(agents): route /btw through provider stream fn for correct URLs - #70413
Conversation
|
@drobison00 @steipete small provider-routing fix for the |
Greptile SummaryThis PR fixes a URL-routing bug in Confidence Score: 5/5Safe to merge — the fix is minimal, well-targeted, and covered by new regression tests. The change is a narrow, correct fix at the exact call site implicated in the bug report. It follows an established pattern already used elsewhere in the codebase (simple-completion-transport.ts), the fallback to streamSimple preserves existing behaviour for providers without a registered stream fn, and all 25 prior tests plus 2 new regression tests pass. No P0/P1 issues were found. No files require special attention. Reviews (1): Last reviewed commit: "fix(agents): route /btw through the prov..." | Re-trigger Greptile |
|
自动巡检路过:这个 PR 看起来是高性价比修复项。若 maintainer 需要,我可以继续补一轮最小验证(冲突/关键检查/回归点)并协助推进到可合并状态。 |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8574946568
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
8574946 to
67f33b3
Compare
🔒 Aisle Security AnalysisWe found 2 potential security issue(s) in this PR:
1. 🟠 Agent/workspace selection derived from untrusted sessionKey enables cross-workspace access in BTW provider hooks
Description
If an attacker can influence Impact depends on installed provider plugins/hooks, but can include:
Vulnerable code (new data flow): const sessionAgentId = resolveSessionAgentId({ sessionKey: params.sessionKey, config: params.cfg });
const workspaceDir = resolveAgentWorkspaceDir(params.cfg, sessionAgentId);
const providerStreamFn = registerProviderStreamForModel({
model: runtimeModel,
cfg: params.cfg,
agentDir: params.agentDir,
workspaceDir,
env: process.env,
});RecommendationTreat Options (pick one consistent with your security model):
Additionally, consider hardening
Example sketch: const session = await sessions.getByKey(params.sessionKey); // server-side lookup
assertAgentAccess(params.authenticatedUser, session.agentId);
const workspaceDir = resolveAgentWorkspaceDir(params.cfg, session.agentId);2. 🟠 Untrusted workspace provider plugin code can execute during /btw side-question streaming
DescriptionThe If workspace-scoped plugins (or provider hook implementations) can be discovered/loaded from
Vulnerable code (new behavior): const providerStreamFn = registerProviderStreamForModel({
model: runtimeModel,
cfg: params.cfg,
agentDir: params.agentDir,
workspaceDir,
env: process.env,
});
...
const stream = await streamWithPayloadPatch(
providerStreamFn ?? streamSimple,
runtimeModel,
...
);RecommendationPrevent Options:
const providerStreamFn = registerProviderStreamForModel({
model: runtimeModel,
cfg: params.cfg,
agentDir: params.agentDir,
// Do not allow workspace-scoped plugin/provider hooks for /btw
workspaceDir: undefined,
env: process.env,
});
Analyzed PR: #70413 at commit Last updated on: 2026-04-23T02:58:24Z |
|
Reviewed, fixed up, and landed. Follow-up commit: 67f33b3 Fixup: passed the session workspace into provider stream registration and added regression coverage in src/agents/btw.test.ts. Changelog entry includes thanks to @suboss87. Validation:
I also attempted a direct source-mode /btw live smoke; local source-mode module/plugin startup blocked before an Ollama request, so I did not count that path as a pass. The regression test covers the /btw provider-routing path, and the native Ollama smoke confirms the requested Gemma 4 model endpoint. |
|
@steipete thanks for the fixup and the live smoke run. threading workspaceDir through registerProviderStreamForModel is the cleaner shape, good catch. appreciate the merge. |
…tions (#170146) Related: #169564 (Advisor, the first consumer) ## What Problem This Solves Plugins that review or summarize an ongoing conversation in the background can only see what they rebuild themselves: a bounded excerpt sent through `api.runtime.subagent.complete`. That loses detail and costs a fresh, uncached prompt every time. In a real-API evaluation, an excerpt-based reviewer produced 2 false corrections in 5 runs (it misread polled background commands as extra launches), while a review that saw the session's full context was correct in all 5. ## Fix Adds `api.runtime.subagent.forkSession({ sessionKey, message, signal?, timeoutMs? })`. It asks one question against an ephemeral fork of the session's current context and returns `{ text, usage }`. It works mid-run, at `agent_end`, and after the parent turn has finished. - **Same prefix, warm cache.** The fork reuses the parent's exact request prefix, so the provider prompt cache hits: - Codex runtime: ephemeral `thread/fork` on the parent's own app-server client, replaying the parent's recorded developer instructions, private persona/skills context, tool surface and turn settings. The parent's last tool declarations are kept in a bounded in-memory LRU (32 MiB global) and restored into the fork request byte for byte. When the parent used a WebSocket continuation (`previous_response_id`), history comes from native Codex reconstruction; no response output is buffered or rebuilt. - Built-in runtime: the embedded runner records the exact request it sent at the model-call boundary (bounded, in memory, cleared with session cleanup) and replays it with one appended user message through the same stream function and payload hooks. Anthropic cache breakpoints and the OpenAI `prompt_cache_key` stay where they were. The parent's one-shot continuation `onPayload` callback is not replayed. - **No tool execution.** Tool definitions stay byte-identical, but every call is denied: - dynamic and native Codex tools are denied at dispatch (this also fixes a fail-open path: the native hook relay dropped `PreToolUse` when no global hook was installed); - hosted tools: `tool_choice: "none"` on OpenAI and `{ type: "none" }` on Anthropic for every fork request; unsupported APIs fail before dispatch; - Codex native `web_search` stays disabled. Its `web.run` declaration is still sent (copied from the parent), so the cache prefix matches but nothing can execute it. - **No side effects.** Nothing is written to the transcript, delivered, counted as a turn, or drained from queued next-turn context. - **Authority.** Same background admission as `subagent.complete` (plugin lifetime, cancellation, revalidation after awaits), plus the conversation-access grant, `sessions.get` session visibility, and live Gateway caller authority. These are checked right before every physical send through the guarded-fetch request authority, including DNS/proxy setup, retries and redirects; native ChatGPT WebSocket and SSE sends check them through the existing Responses request lifecycle. Ordinary parent settlement and usage updates (including a briefly unmaterialized session row) do not revoke a fork. A session reset or deletion, a replaced Codex client or thread, withdrawn conversation access, or a retired plugin still revokes it. - **Same network policy as the parent.** Built-in replay takes the current proxy, TLS and local-service settings (including the local-service reconciler) from the existing transport owner, not from the snapshot. Native ChatGPT forks open their own transient WebSocket and never change the parent's socket, continuation or SSE fallback state. - **Supported APIs.** OpenAI Completions, OpenAI Responses (including native ChatGPT), Anthropic Messages, and Codex. APIs whose sends the fork cannot fence (for example Bedrock) fail closed before dispatch with `Session forks do not support provider API <api>`. - **Runtimes.** CLI runtimes (for example `claude-cli`) have no prepared context to fork, so a fork fails closed before any CLI or provider I/O. Ordinary `/btw` on CLI is unchanged. - **Concurrency.** Forks run on the same subagent lane as `subagent.complete` (`CommandLane.Subagent`), so `agents.defaults.subagents.maxConcurrent` caps both together. - **Fails closed** with an actionable error when no parent request was prepared by this runtime (for example after a Gateway restart). - Fixes forked-turn usage reporting on Codex (forks only emit `thread/tokenUsage/updated`) and admits forked requests through the private inference proxy. Ordinary `/btw` is unchanged from `main`. An earlier revision rejected `/btw` when tools were present, and rejected CLI backends with `nativeToolMode: "none"` and no `sideQuestionToolMode`; both are restored, and CLI admission stays with `prepareCliRunContext` (this answers the review note about #70413). The provider-review continuation callback from #155214 is not replayed by forks. ## User Impact None by default: no core feature calls `forkSession` yet. Plugins that opt in get full-context side questions at cached-input prices. ## Evidence Live, real provider APIs, isolated Gateway at the PR head, a throwaway plugin that calls `forkSession` from its service scheduler on each `agent_end`: one fork immediately (parent still settling), then two forks 8 s later (summary, plus a "use web search now" bait). Each parent turn makes 3 tool calls. | Runtime / provider | Parent last input | Fork at `agent_end`: cache read | Late fork: cache read | Search bait | |---|---|---|---|---| | Codex, OpenAI (API key, WebSocket continuation) | ~19.7k | 19,642 | 19,967, cacheWrite 0 | `NO_SEARCH` | | Built-in, OpenAI `gpt-5.6-luna` | — | 15,660 (input 566) | 15,660 (input 608) | `NO_SEARCH` | | Built-in, Anthropic `claude-sonnet-5-5` | — | 19,595 (input 73) | 19,595 (input 73) | `NO_SEARCH` | - Codex wire check: the fork's `additional_tools` item (51,233 bytes) has the same SHA-256 as the parent's, and `prompt_cache_key` matches. Before this fix, the late fork read 0 cached tokens because disabling `web_search` removed `web.run` from the `exec` catalog (10,831 bytes). - Before the admission fix, a fork started at `agent_end` failed with `agent harness host capability is no longer active`: the session-read fence required a fully materialized row while the parent was settling. - Ordinary Codex `/btw` on the same session: `I ran echo one, then echo two, then echo three.` Not proven against a real provider: the session-visibility rejection needs an identified Gateway client, and the live probe plugin runs as a service with no caller identity. The composed test below covers it against a real local HTTP provider. Tests (regressions fail before their fix): - byte identity of the replayed request through the real transport seam (OpenAI Completions, OpenAI Responses, Anthropic); - Codex tool-declaration parity after continuation, and child `previous_response_id` cleared on full-prefix replay; - tool denial for dynamic, native and hosted tools with no global hooks installed; - fork admission during parent settlement and row rematerialization; revocation on reset, deletion, lifecycle replacement, access withdrawal and visibility change; - authority withdrawal during preparation, during guarded DNS/proxy setup (no request leaves), during native WebSocket acquisition (no `response.create`), and before an SSE redirect hop (redirect body not sent); rejection of callers outside session visibility; - current explicit-proxy and TLS policy and the local-service reconciler applied to the replay; native fork failures leave the parent's socket and SSE fallback state unchanged; Bedrock rejected before dispatch; - a deny fork on a `claude-cli` session is rejected with no CLI spawn or provider call; with `maxConcurrent: 1`, three forks run one at a time and wait while a completion holds the lane; - composed visibility proof: an identified caller outside session visibility gets `Session not found` with zero requests at a real local provider server (real guarded-fetch transport, no inference mock); the session owner reaches it and gets the prepared-context answer; - ordinary CLI `/btw` with `nativeToolMode: "none"` and no `sideQuestionToolMode` works as on `main`; - fork usage from thread token updates, real inference-proxy owner admission, parent→fork on the parent's exact client, snapshot release on committed session reset, and the restart fail-closed path. Separate observation, not changed here: with an explicit multi-agent config, `/btw` on the system agent fails with `prepared model runtime owner was not published` unless `agents.entries.main.workspace` is set. The published owner uses the startup workspace (`/…/workspace`), but `/btw` asks for `/…/workspace/main`. Co-authored-by: Ayaan Zaidi <[email protected]>
…tions (openclaw#170146) Related: openclaw#169564 (Advisor, the first consumer) ## What Problem This Solves Plugins that review or summarize an ongoing conversation in the background can only see what they rebuild themselves: a bounded excerpt sent through `api.runtime.subagent.complete`. That loses detail and costs a fresh, uncached prompt every time. In a real-API evaluation, an excerpt-based reviewer produced 2 false corrections in 5 runs (it misread polled background commands as extra launches), while a review that saw the session's full context was correct in all 5. ## Fix Adds `api.runtime.subagent.forkSession({ sessionKey, message, signal?, timeoutMs? })`. It asks one question against an ephemeral fork of the session's current context and returns `{ text, usage }`. It works mid-run, at `agent_end`, and after the parent turn has finished. - **Same prefix, warm cache.** The fork reuses the parent's exact request prefix, so the provider prompt cache hits: - Codex runtime: ephemeral `thread/fork` on the parent's own app-server client, replaying the parent's recorded developer instructions, private persona/skills context, tool surface and turn settings. The parent's last tool declarations are kept in a bounded in-memory LRU (32 MiB global) and restored into the fork request byte for byte. When the parent used a WebSocket continuation (`previous_response_id`), history comes from native Codex reconstruction; no response output is buffered or rebuilt. - Built-in runtime: the embedded runner records the exact request it sent at the model-call boundary (bounded, in memory, cleared with session cleanup) and replays it with one appended user message through the same stream function and payload hooks. Anthropic cache breakpoints and the OpenAI `prompt_cache_key` stay where they were. The parent's one-shot continuation `onPayload` callback is not replayed. - **No tool execution.** Tool definitions stay byte-identical, but every call is denied: - dynamic and native Codex tools are denied at dispatch (this also fixes a fail-open path: the native hook relay dropped `PreToolUse` when no global hook was installed); - hosted tools: `tool_choice: "none"` on OpenAI and `{ type: "none" }` on Anthropic for every fork request; unsupported APIs fail before dispatch; - Codex native `web_search` stays disabled. Its `web.run` declaration is still sent (copied from the parent), so the cache prefix matches but nothing can execute it. - **No side effects.** Nothing is written to the transcript, delivered, counted as a turn, or drained from queued next-turn context. - **Authority.** Same background admission as `subagent.complete` (plugin lifetime, cancellation, revalidation after awaits), plus the conversation-access grant, `sessions.get` session visibility, and live Gateway caller authority. These are checked right before every physical send through the guarded-fetch request authority, including DNS/proxy setup, retries and redirects; native ChatGPT WebSocket and SSE sends check them through the existing Responses request lifecycle. Ordinary parent settlement and usage updates (including a briefly unmaterialized session row) do not revoke a fork. A session reset or deletion, a replaced Codex client or thread, withdrawn conversation access, or a retired plugin still revokes it. - **Same network policy as the parent.** Built-in replay takes the current proxy, TLS and local-service settings (including the local-service reconciler) from the existing transport owner, not from the snapshot. Native ChatGPT forks open their own transient WebSocket and never change the parent's socket, continuation or SSE fallback state. - **Supported APIs.** OpenAI Completions, OpenAI Responses (including native ChatGPT), Anthropic Messages, and Codex. APIs whose sends the fork cannot fence (for example Bedrock) fail closed before dispatch with `Session forks do not support provider API <api>`. - **Runtimes.** CLI runtimes (for example `claude-cli`) have no prepared context to fork, so a fork fails closed before any CLI or provider I/O. Ordinary `/btw` on CLI is unchanged. - **Concurrency.** Forks run on the same subagent lane as `subagent.complete` (`CommandLane.Subagent`), so `agents.defaults.subagents.maxConcurrent` caps both together. - **Fails closed** with an actionable error when no parent request was prepared by this runtime (for example after a Gateway restart). - Fixes forked-turn usage reporting on Codex (forks only emit `thread/tokenUsage/updated`) and admits forked requests through the private inference proxy. Ordinary `/btw` is unchanged from `main`. An earlier revision rejected `/btw` when tools were present, and rejected CLI backends with `nativeToolMode: "none"` and no `sideQuestionToolMode`; both are restored, and CLI admission stays with `prepareCliRunContext` (this answers the review note about openclaw#70413). The provider-review continuation callback from openclaw#155214 is not replayed by forks. ## User Impact None by default: no core feature calls `forkSession` yet. Plugins that opt in get full-context side questions at cached-input prices. ## Evidence Live, real provider APIs, isolated Gateway at the PR head, a throwaway plugin that calls `forkSession` from its service scheduler on each `agent_end`: one fork immediately (parent still settling), then two forks 8 s later (summary, plus a "use web search now" bait). Each parent turn makes 3 tool calls. | Runtime / provider | Parent last input | Fork at `agent_end`: cache read | Late fork: cache read | Search bait | |---|---|---|---|---| | Codex, OpenAI (API key, WebSocket continuation) | ~19.7k | 19,642 | 19,967, cacheWrite 0 | `NO_SEARCH` | | Built-in, OpenAI `gpt-5.6-luna` | — | 15,660 (input 566) | 15,660 (input 608) | `NO_SEARCH` | | Built-in, Anthropic `claude-sonnet-5-5` | — | 19,595 (input 73) | 19,595 (input 73) | `NO_SEARCH` | - Codex wire check: the fork's `additional_tools` item (51,233 bytes) has the same SHA-256 as the parent's, and `prompt_cache_key` matches. Before this fix, the late fork read 0 cached tokens because disabling `web_search` removed `web.run` from the `exec` catalog (10,831 bytes). - Before the admission fix, a fork started at `agent_end` failed with `agent harness host capability is no longer active`: the session-read fence required a fully materialized row while the parent was settling. - Ordinary Codex `/btw` on the same session: `I ran echo one, then echo two, then echo three.` Not proven against a real provider: the session-visibility rejection needs an identified Gateway client, and the live probe plugin runs as a service with no caller identity. The composed test below covers it against a real local HTTP provider. Tests (regressions fail before their fix): - byte identity of the replayed request through the real transport seam (OpenAI Completions, OpenAI Responses, Anthropic); - Codex tool-declaration parity after continuation, and child `previous_response_id` cleared on full-prefix replay; - tool denial for dynamic, native and hosted tools with no global hooks installed; - fork admission during parent settlement and row rematerialization; revocation on reset, deletion, lifecycle replacement, access withdrawal and visibility change; - authority withdrawal during preparation, during guarded DNS/proxy setup (no request leaves), during native WebSocket acquisition (no `response.create`), and before an SSE redirect hop (redirect body not sent); rejection of callers outside session visibility; - current explicit-proxy and TLS policy and the local-service reconciler applied to the replay; native fork failures leave the parent's socket and SSE fallback state unchanged; Bedrock rejected before dispatch; - a deny fork on a `claude-cli` session is rejected with no CLI spawn or provider call; with `maxConcurrent: 1`, three forks run one at a time and wait while a completion holds the lane; - composed visibility proof: an identified caller outside session visibility gets `Session not found` with zero requests at a real local provider server (real guarded-fetch transport, no inference mock); the session owner reaches it and gets the prepared-context answer; - ordinary CLI `/btw` with `nativeToolMode: "none"` and no `sideQuestionToolMode` works as on `main`; - fork usage from thread token updates, real inference-proxy owner admission, parent→fork on the parent's exact client, snapshot release on committed session reset, and the restart fail-closed path. Separate observation, not changed here: with an explicit multi-agent config, `/btw` on the system agent fails with `prepared model runtime owner was not published` unless `agents.entries.main.workspace` is set. The published owner uses the startup workspace (`/…/workspace`), but `/btw` asks for `/…/workspace/main`. Co-authored-by: Ayaan Zaidi <[email protected]>
Summary
Fixes #68336.
/btwwas callingstreamSimpledirectly and bypassing the provider'screateStreamFn/wrapStreamFnhooks. For Ollama Cloud withapi: "openai-completions", that meant requests went tohttps://ollama.com/(marketing site, 404 HTML) instead ofhttps://ollama.com/v1/chat/completions.Root cause
src/agents/btw.tsbuilt aruntimeModelfrom config and auth prep, then handed it straight tostreamSimple. The regular (non-/btw) streaming path goes throughregisterProviderStreamForModelwhich resolves the provider-specific stream fn and registers it with the custom API registry. That registration is what the Ollama plugin uses to build/v1/chat/completions(openai-compat) or/api/chat(native) paths for each model./btwskipped this step entirely.Fix
Call
registerProviderStreamForModelafter the runtime model is finalized and pass the returned stream fn intostreamWithPayloadPatch, falling back tostreamSimplewhen the provider doesn't register one. Matches the pattern already used insrc/agents/simple-completion-transport.ts.Evidence
404with marketing-site HTML response when hittinghttps://ollama.comdirectly.src/agents/btw.ts:462calledstreamSimplewith the runtime model; no call toregisterProviderStreamForModel.src/agents/btw.ts), adding the provider stream fn resolution before thestreamWithPayloadPatchcall.src/agents/btw.test.tsnow asserts that for a model withprovider: "ollama",api: "openai-completions",baseUrl: "https://ollama.com/",/btwuses the provider's stream fn and never falls through tostreamSimple.Test plan
streamSimpleis still used when no provider stream fn registers/btwtests pass unchangedCloses #68336.