Skip to content

fix(agents): route /btw through provider stream fn for correct URLs - #70413

Merged
steipete merged 2 commits into
openclaw:mainfrom
suboss87:fix/btw-use-provider-stream-fn
Apr 23, 2026
Merged

steipete merged 2 commits into
openclaw:mainfrom
suboss87:fix/btw-use-provider-stream-fn

Conversation

@suboss87

Copy link
Copy Markdown
Contributor

Summary

Fixes #68336. /btw was calling streamSimple directly and bypassing the provider's createStreamFn / wrapStreamFn hooks. For Ollama Cloud with api: "openai-completions", that meant requests went to https://ollama.com/ (marketing site, 404 HTML) instead of https://ollama.com/v1/chat/completions.

Root cause

src/agents/btw.ts built a runtimeModel from config and auth prep, then handed it straight to streamSimple. The regular (non-/btw) streaming path goes through registerProviderStreamForModel which 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. /btw skipped this step entirely.

Fix

Call registerProviderStreamForModel after the runtime model is finalized and pass the returned stream fn into streamWithPayloadPatch, falling back to streamSimple when the provider doesn't register one. Matches the pattern already used in src/agents/simple-completion-transport.ts.

Evidence

  • Symptom: reporter's log in [Bug]: /btw Side Channel Fails with Ollama Cloud (404 Error) #68336 shows 404 with marketing-site HTML response when hitting https://ollama.com directly.
  • Root cause in code: src/agents/btw.ts:462 called streamSimple with the runtime model; no call to registerProviderStreamForModel.
  • Fix touches the implicated path: change is at the same call site (src/agents/btw.ts), adding the provider stream fn resolution before the streamWithPayloadPatch call.
  • Regression test: src/agents/btw.test.ts now asserts that for a model with provider: "ollama", api: "openai-completions", baseUrl: "https://ollama.com/", /btw uses the provider's stream fn and never falls through to streamSimple.

Test plan

Closes #68336.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S labels Apr 23, 2026
@suboss87

Copy link
Copy Markdown
Contributor Author

@drobison00 @steipete small provider-routing fix for the /btw 404 on Ollama Cloud. root cause is /btw skipped registerProviderStreamForModel so the ollama plugin never got a chance to build the right path (/v1/chat/completions for openai-compat, /api/chat for native). 14-line code diff, regression test covers the exact config from the bug report. would appreciate a look when you have a minute.

@greptile-apps

greptile-apps Bot commented Apr 23, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes a URL-routing bug in /btw where streamSimple was called directly, bypassing registerProviderStreamForModel. For providers like Ollama Cloud (api: "openai-completions"), this caused requests to land on the marketing-site root instead of /v1/chat/completions. The fix mirrors the pattern already used in simple-completion-transport.ts: call registerProviderStreamForModel after the runtime model is finalized, then pass the returned stream fn (falling back to streamSimple) into streamWithPayloadPatch. Two targeted regression tests cover both the Ollama Cloud path and the fallback path.

Confidence Score: 5/5

Safe 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

@SeashoreShi

Copy link
Copy Markdown

自动巡检路过:这个 PR 看起来是高性价比修复项。若 maintainer 需要,我可以继续补一轮最小验证(冲突/关键检查/回归点)并协助推进到可合并状态。

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

💡 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".

Comment thread src/agents/btw.ts Resolved
@steipete
steipete force-pushed the fix/btw-use-provider-stream-fn branch from 8574946 to 67f33b3 Compare April 23, 2026 02:55
@aisle-research-bot

aisle-research-bot Bot commented Apr 23, 2026 •

Copy link
Copy Markdown

🔒 Aisle Security Analysis

We found 2 potential security issue(s) in this PR:

# Severity Title
1 🟠 High Agent/workspace selection derived from untrusted sessionKey enables cross-workspace access in BTW provider hooks
2 🟠 High Untrusted workspace provider plugin code can execute during /btw side-question streaming
1. 🟠 Agent/workspace selection derived from untrusted sessionKey enables cross-workspace access in BTW provider hooks
Property Value
Severity High
CWE CWE-639
Location src/agents/btw.ts:401-446

Description

runBtwSideQuestion() derives sessionAgentId from params.sessionKey and then computes workspaceDir from that agent id. After this change, this happens unconditionally (even when no API key is used), and workspaceDir is passed into registerProviderStreamForModel(), which resolves provider runtime hooks/plugins.

If an attacker can influence params.sessionKey (e.g., via an HTTP/gateway request parameter), they can supply an agent:-scoped session key containing another agent id (e.g., agent:other:...). Because resolveSessionAgentId() trusts the parsed agent id from the session key, the BTW call will run provider hook resolution with the other agent’s workspaceDir.

Impact depends on installed provider plugins/hooks, but can include:

  • Cross-workspace data exposure (plugins reading config/files from the wrong agent workspace)
  • Cross-workspace writes (plugins persisting artifacts/logs/cache into another agent’s workspace)
  • Potential SSRF/credential misuse if provider hooks load secrets/config from that workspace and use them for outbound requests

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,
});

Recommendation

Treat sessionKey as an opaque identifier and do not allow it to directly select an agent/workspace unless it is authenticated/authorized.

Options (pick one consistent with your security model):

  1. Bind agent/workspace to authenticated session state

    • Look up the session record by sessionKey and read the agent/workspace from stored server-side state.
    • Reject requests where the authenticated user is not allowed to access that agent.
  2. Ignore embedded agent id from request-supplied session keys for BTW

    • Use the already-authenticated agent context (or default agent) rather than parsing it from params.sessionKey.
  3. Enforce authorization when resolving agent/workspace

    • Add an authorization check like assertAgentAccess(user, sessionAgentId) before resolveAgentWorkspaceDir().

Additionally, consider hardening resolveAgentWorkspaceDir() for configured paths:

  • Canonicalize (realpath) and enforce containment under an expected per-install root if workspaces must be isolated.

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
Property Value
Severity High
CWE CWE-94
Location src/agents/btw.ts:436-476

Description

The /btw side-question path now registers and uses a provider-specific stream function via registerProviderStreamForModel(...). That registration resolves provider runtime plugins using workspaceDir/agentDir context.

If workspace-scoped plugins (or provider hook implementations) can be discovered/loaded from workspaceDir (e.g., via repo-local plugin manifests or enabled plugin IDs), then running a side-question can execute workspace-controlled JavaScript/TypeScript in-process:

  • Input/control: workspaceDir is derived from the session/agent workspace (resolveAgentWorkspaceDir(...)).
  • Execution sink: registerProviderStreamForModel calls resolveProviderStreamFn(...), which delegates to resolveProviderRuntimePlugin(...).createStreamFn(...) (plugin-provided code).
  • Impact: An attacker who can influence workspace contents or plugin enablement could trigger arbitrary code execution, unauthorized network calls, or data exfiltration when /btw runs.

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,
  ...
);

Recommendation

Prevent /btw from loading/executing workspace-scoped provider plugins unless the workspace is explicitly trusted.

Options:

  1. Disable workspace plugin resolution for /btw by not passing workspaceDir (or by adding a flag that forces bundled-only providers):
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,
});
  1. Add an explicit allowlist / trust gate inside registerProviderStreamForModel / resolveProviderStreamFn (preferred):
  • e.g., require cfg.plugins.trustWorkspace === true (or similar) before resolving plugins from workspaceDir.
  • otherwise only use createTransportAwareStreamFnForModel.
  1. If workspace plugins must be supported, sandbox plugin execution (separate process with constrained env/network/fs) and strongly validate the resolved workspace path and session ownership.

Analyzed PR: #70413 at commit 67f33b3

Last updated on: 2026-04-23T02:58:24Z

@steipete
steipete merged commit 1c91f3f into openclaw:main Apr 23, 2026
73 checks passed
@steipete

Copy link
Copy Markdown
Contributor

Reviewed, fixed up, and landed.

Follow-up commit: 67f33b3
Merge commit: 1c91f3f

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:

  • pnpm test src/agents/btw.test.ts
  • pnpm check:changed
  • CI green on 67f33b3
  • Ollama local live sanity: gemma4:31b via native /api/chat with think:false returned the exact sentinel RIVER-714

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.

@suboss87

Copy link
Copy Markdown
Contributor Author

@steipete thanks for the fixup and the live smoke run. threading workspaceDir through registerProviderStreamForModel is the cleaner shape, good catch. appreciate the merge.

medikoo pushed a commit to medikoo/openclaw that referenced this pull request Apr 24, 2026
ogt-redknie pushed a commit to ogt-redknie/OPENX that referenced this pull request May 2, 2026
globalcaos pushed a commit to globalcaos/tinkerclaw that referenced this pull request May 13, 2026
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request May 24, 2026
jameslcowan pushed a commit to jameslcowan/openclaw that referenced this pull request Jun 2, 2026
sablehead pushed a commit to sablehead/openclaw that referenced this pull request Jun 10, 2026
vixco pushed a commit to vixco/openclaw that referenced this pull request Aug 16, 2026
Heetisk pushed a commit to Heetisk/openclaw that referenced this pull request Sep 28, 2026
obviyus added a commit that referenced this pull request Oct 13, 2026
…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]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 14, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling size: S

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: /btw Side Channel Fails with Ollama Cloud (404 Error)

3 participants