Skip to content

feat(labs): add experimental Advisor that steers agents off avoidable work - #169564

Merged
obviyus merged 30 commits into
mainfrom
feat/progress-review-labs
Oct 14, 2026
Merged

obviyus merged 30 commits into
mainfrom
feat/progress-review-labs

Conversation

@obviyus

@obviyus obviyus commented Oct 12, 2026 •

Copy link
Copy Markdown
Collaborator

Built on #170146 (forkSession), #170152 (steerActiveRun), #171307 (shared api.runContext), #171534 (event phases), #171580 (forks show in-flight calls as pending) and #171610 (payload: "metadata"), #171651 (internal skill-workshop reviews are not user turns) and #171661 (Codex outer tool-call lifecycle), all on main. Related: #169558.

What Problem This Solves

Agents sometimes spend turns on work nobody asked for, repeat failing or stalled tool calls, or report results the tools do not support. Nothing notices until the user does.

User Impact

Operators can turn on Settings → Agents & Tools → Labs → Advisor (default off). While the agent works, Advisor reviews the conversation every few tool calls or minutes, on the session's own model. If it finds avoidable work, it steers the running turn with one short correction, or queues the correction for the next turn when steering is unavailable. Otherwise nothing happens. It never runs tools, delays, stops or approves anything. Configure beside the switch opens the plugin settings page:

  • everyToolCalls (default 10) and everyMinutes (default 20); 0 turns a trigger off.
  • Review instructions (reviewInstructions, optional, at most 4,000 characters): edits what Advisor looks for and when it stays quiet. A blank field uses the evaluated built-in guidance, which is shown as placeholder text. Changes apply on the next review without a restart. The output format, the safety rules and the verify step stay fixed, so custom guidance cannot bypass fail-closed parsing or verification. Custom guidance is not covered by the evaluation below.

Why This Change Was Made

A default-off bundled plugin (advisor) built only on public SDK seams:

  • Admission: the history-free before_agent_reply hook (eligibleTriggers: ["user"]) records each user-triggered run in api.runContext and never claims the turn. Advisor does not subscribe to llm_input, agent_end or after_tool_call, because subscribing makes the host copy the conversation history or tool results on every turn.
  • Trigger: the service's single subscription to the agent-event stream counts tool starts, so stalled and backgrounded commands count too. Every N tool starts or M minutes, a review becomes due. It uses phases and payload: "metadata", so the host never clones tool results, updates or arguments for Advisor.
  • Safe boundary: a due review (and its verify step) dispatches only when no tool call is in flight. Built-in calls settle on their result event; Codex calls settle on native item completion (codex_app_server.item completed, which fires after codex-rs records the output), including outer code-mode calls. Run end is always a safe boundary. Forking mid-call would show the open call as aborted (codex-rs normalization). Live, before this rule, that led to a false "retry it" correction that made an agent repeat successful commands. Run timing starts at lifecycle start, and end or error closes the run.
  • Review, stage 1: api.runtime.subagent.forkSession runs on the plugin service scheduler. The review sees the full live context at cached-input prices and runs no tools. The reply's first line must be NO_CHANGE or CORRECTION.
  • Verify, stage 2: runs only after a CORRECTION. A second fork of the same cached context checks the draft against the conversation. The problem must be shown by tool results or user messages, not by pending work. The advice must keep every user requirement (prohibitions, scope, ordering, timing, environment), and its next step must be cheaper and still complete the request. The fork replies APPROVE (with the final text) or REJECT.
  • Fail closed: both replies are parsed structurally. A malformed reply, a reserved decision word inside the body, a timeout or an error means no steering. The warning is bounded and content-free; it never contains model or provider text.
  • Delivery: api.session.workflow.steerActiveRun, falling back to enqueueNextTurnInjection (24 h TTL).
  • One review in flight per session, covering both stages under one deadline. Reviews are cancelled on reset, disable and service stop. The interval counter restarts when a review finishes. Tool events from channel runs, which carry no sessionKey, are routed through the admitted run's key.

An earlier version reviewed a bounded text excerpt with a separately configured model. In a real-API evaluation it made 2 false corrections in 5 runs: it misread polled background commands as extra launches. The full-context fork made none, so the excerpt reviewer and the model setting were removed.

Settings UI: a new generic, optional multiline hint in plugin manifest uiHints (manifest types, normalizer, and an additive optional field in the Gateway protocol config schema) renders a string field as a textarea in the existing config form. Fields without the hint render exactly as before. Advisor is its first user.

Labs: Configure follows the settings-row control slot (a ghost action beside the switch), through a new optional actions slot on SettingsToggleRow. The shared toggle-row click handler now ignores clicks on links, buttons and fields. Before, clicking a Labs "Documentation" link also toggled the lab; a regression test fails on the old handler.

Evidence

Labs before (current main, no Advisor row):

Labs before

Labs after, with Advisor enabled:

Labs after

Plugin settings page opened by Configure, with the multiline Review instructions field:

Advisor plugin settings

Ordinary-turn overhead, with Advisor enabled and no review due. Clones were counted per call site with an instrumented structuredClone across 10 real Gateway turns per workload, in a pinned Linux container (mock provider). The table shows serialized bytes the host clones for Advisor per turn:

Workload Before this change (llm_input + unfiltered events) This PR Advisor disabled
Short turn 2,988 1,375 0
200 KiB history 209,377 1,380 0
1 MiB history 1,053,153 1,380 0
5 tools × 256 KiB results 1,326,523 2,899 0

Hot-path CPU, measured as interleaved microbenchmarks (median per turn): the history copy at 1 MiB costs 0.28 ms before and 0 ms now; the event dispatch on a tool-heavy turn costs 0.90 ms before and 0.14 ms now. Latency on whole turns was not resolvable on the shared host: block drift reached 35%. That pilot is recorded as exploratory and makes no p95 claim. A review itself (two forks at most) runs only when a trigger fires.

Review-decision evaluation, real APIs. Each scenario's conversation is replayed in the provider's native format (tool calls, tool results, tool schemas with tool_choice: none), with the review message appended, as the fork sends it. Corrections were graded by a model judge with a written rubric: evidence, a cheaper step that still completes the request, user instructions kept, at most 120 words. Final numbers come from a blind holdout: 40 new scenarios written by a separate agent that never saw the prompt, frozen before the run, 3 runs per model.

Model Variant False corrections Recall Correction quality
gpt-5.6-luna single pass 3/60 60/60 87.3%
gpt-5.6-luna with verify step 0/60 60/60 95.0%
gpt-6.1-sol (Codex default) with verify step 0/60 60/60 95.0%
claude-sonnet-5-5 with verify step 3/60 (one scenario) 60/60 84.1%

The original prompt corrected 9–16 of 24 legitimate runs per model on the first scenario set. Its live failure: told an agent to run a requested wait loop in parallel. The verify step costs about 1.4–2.1 s and well under a cent, and it runs only when stage 1 proposes a correction.

Live on this branch (isolated Gateway, Codex and built-in luna, review every 3 tool calls):

  • Requested polling (8 checks, 2 s apart): Codex reviewed 4 times, NO_CHANGE each time (4.2–5.3 s, about 15–16k cached tokens, input 75). Luna drafted 2 corrections; stage 2 rejected both. No steering, and every requested check ran.
  • Search task: both agents broadened the search after one miss, so there was no waste to correct. Codex said NO_CHANGE; luna drafted a correction and stage 2 rejected it.
  • Steering delivery: shown live on an earlier head of this branch (luna, steered: true, guidance in the next provider request, the agent changed course). On this head, the approve-then-steer path is covered by the tests below.

Known limits:

  • claude-sonnet-5-5 falsely corrects one hard negative scenario in all 3 runs, and its correction quality is below 95%.
  • On Codex with a restricted tool profile (for example tools.profile: coding), the existing /btw native-tool rule refuses forks, so Advisor cannot review those sessions. It logs the refusal once per review interval.

Tests:

  • Plugin: 46 tests. The default guidance composes to the byte-identical evaluated prompt; custom guidance replaces only the guidance part; whitespace-only means default; the verify message is unaffected; config edits apply on the next review. Earlier coverage: through the real plugin API surface. They cover: hook and service as separate registrations; channel tool events without sessionKey; approve then steer and the next-turn fallback; reject, malformed, conflicting-token, empty and timed-out stage 1 or 2 replies, each with zero deliveries and one bounded, content-free warning; the interval restarting after a slow or failed review; cancellation on reset, disable and stop.
  • Config form: the textarea renders and edits save for multiline fields; manifest hint normalization is tested.
  • Labs page: 65 tests, covering on/off writes, the Configure link and in-app navigation under a base path, and no toggle on link click.

Merge danger: two-way door; default off. A revert removes the plugin, its Labs row and the Configure link. A saved plugins.entries.advisor entry would remain in config.

@clawsweeper

clawsweeper Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation app: web-ui App: web-ui size: L labels Oct 12, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. proof: 📸 screenshot Contributor real behavior proof includes screenshot evidence. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Oct 12, 2026
@clawsweeper

clawsweeper Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Adds a default-off Advisor plugin that reviews ongoing agent work, verifies proposed corrections, and delivers approved advice through active steering or next-turn context.

Example: Advisor is enabled with everyToolCalls set to 3 while an agent fixes a README typo.

  • Before: The agent can continue editing unrelated CI files without automatic feedback.
  • After: After settled tool calls, Advisor can verify the scope drift and advise the agent to return to the README typo.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Coherent, useful implementation with inspected UI proof, reported live review behavior, focused contract coverage, and no actionable findings.
Proof confidence 🐚 platinum hermit (4/6) ✨ media proof bonus Sufficient (screenshot): Inspected before/after Labs and plugin-settings screenshots; the body records isolated-Gateway Codex and built-in live reviews preserving requested polling and rejecting false corrections, plus earlier-head steering delivery. Current approval-to-delivery is supported by plugin tests; a fresh positive live case remains optional for this maintainer-authored PR.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Feature · Worth it: Yes · Fix scope: Complete
User problem: Users must notice when agents drift beyond requests, repeat unproductive work, or make claims unsupported by tool results.
Reason: The maintainer-authored experiment provides bounded, verified advice through existing owners, with explicit opt-in, cost disclosure, and documented model limitations.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: it adds distinct, maintainer-approved experimental functionality, and the reviewed patch has no actionable findings. The previous conflict is resolved and the current head’s CI gate passes.

Priority: P2
Reviewed head: e29d04b4e3cefe6e07b48316ef6c2ce993821b34

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: A live current-verifier approval followed by steering or next-turn delivery would strengthen coverage; the body identifies earlier-head live delivery and current mocked approval-path coverage.
Agent review details

How this fits together

Labs saves the plugin opt-in through the existing config owner; the plugin consumes admitted user-run events, forks session context for model review, and sends verified advice through existing session workflow APIs.

flowchart TD
  A[Labs and plugin settings] --> B[Gateway config owner]
  B --> C[Advisor service]
  D[Admitted user run events] --> C
  C --> E[Session review fork]
  E --> F[Verification fork]
  F --> G[Steering or next turn context]
Loading

Technical review

Best possible solution:

Ship Advisor as the opt-in plugin using the existing session review, steering, and config owners.

Do we have a high-confidence way to reproduce the issue?

This is a new capability rather than a reproducible upstream bug; source inspection confirms the trigger, verification, and delivery paths without executing target code.

Is this the best way to solve the issue?

The plugin placement fits the existing architecture, reuses merged SDK capabilities, and keeps model judgment and optional configuration out of core agent policy.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against a97192d2556b.

Provenance checked

  • Scalar input rendering and edit preservation keeps the original intent (fix(control-ui): config form save corrupts 64-bit id strings in string|number fields #126402: Preserve primitive string identity and prevent rounded 64-bit identifiers; later Solid and ownership refactors retained that contract.)
  • Labs toggles and settings ownership keeps the original intent (feat(ui): Labs settings page for experimental feature toggles #110359: Provide a discoverable registry-driven home for experimental gates, subsequently using canonical default restoration and config patching.)
  • Interactive elements inside toggle rows changes intended behavior with a stated reason (eca633a: Share presentation primitives across renderers; the previous handler excluded the switch but also toggled when nested links were clicked.)
  • Plugin manifest hint normalization keeps the original intent (589f28b: Keep manifest metadata normalization in the shared plugin owner; the new optional hint extends that owner without changing existing hints.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Introduced patch and current main: Reviewed the pinned introduced diff. Current main contains the supporting SDK capabilities but has no Advisor plugin or Labs row, so those merged prerequisites do not supersede this PR. (extensions/advisor/index.ts:46, e29d04b4e3ce)
  • Current merge state: GitHub reports the reviewed head as mergeable with clean merge state; the preceding review’s conflict blocker no longer applies. (e29d04b4e3ce)
  • Exact-head CI: The current head’s openclaw/ci-gate succeeds; the complete paginated check-run response contains no failed or unfinished checks. (e29d04b4e3ce)
  • Existing authority owners: The merged fork owner checks conversation access, session visibility, execution lifetime, and cancellation; steering checks plugin lifetime and adds hidden guidance without sender-owner authority. The contracts and live evidence are recorded in feat(plugins): fork a session's live context for background side questions #170146 and feat(plugins): let plugins steer a session's active run #170152. (src/gateway/server-plugin-subagent-runtime.ts:208, e29d04b4e3ce)
  • Inspected visual proof: Inspected all three prepared screenshots: Labs before, Labs with Advisor enabled and Configure available, and the plugin settings page with the multiline Review instructions field. (e29d04b4e3ce)
  • Approved additive contract and experimental tradeoff: The collaborator-authored direction includes three plugin settings and an optional multiline manifest hint. Existing hints and saved preferences retain their behavior; the author explicitly records default-off operation, additional model calls, model-dependent false corrections, and restricted-profile fork limitations. (extensions/advisor/openclaw.plugin.json:11, e29d04b4e3ce)

Likely related people:

  • Ayaan Zaidi: Raw commit ae2be85 adds src/plugins/host-hook-steering.ts:12 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: ae2be85a5197; files: src/plugins/host-hook-steering.ts)
  • Peter Steinberger: Raw commit bf58e95 adds ui/src/components/config-form.scalar-edit.ts:8 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: bf58e95ee3f5; files: ui/src/components/config-form.scalar-edit.ts)
  • Hiroshi Tanaka: Raw commit 55f1738 adds ui/src/components/config-form.scalar-edit.ts:2 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 55f1738d50fb; files: ui/src/components/config-form.scalar-edit.ts)

PR surface

Source +756, Tests +1138, Docs +236, Config +18, Generated 0, Other +6. Total +2154 across 31 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 15 854 98 +756
Tests 4 1143 5 +1138
Docs 7 240 4 +236
Config 2 18 0 +18
Generated 2 3 3 0
Other 1 6 0 +6
Total 31 2264 110 +2154

Review metrics

Metric Value Why it matters
Plugin configuration 3 settings Adds everyToolCalls, everyMinutes, and optional reviewInstructions under the default-off Advisor plugin.
Public manifest metadata 1 optional hint Adds multiline across manifest normalization, protocol serialization, and the existing scalar form renderer.

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: Useful agent-work improvement with limited blast radius because the plugin is experimental and disabled by default.
  • merge-risk: 🚨 compatibility: Extends the public plugin manifest and Gateway hint contract with optional multiline metadata; the maintainer-authored direction accepts this additive expansion, and existing fields retain their rendering.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.
  • proof: 📸 screenshot: Contributor real behavior proof includes screenshot evidence.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Optionally capture a redacted live run where the current verifier approves a correction and the agent receives it through steering or next-turn fallback.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (12 earlier review cycles; latest 8 shown)
  • reviewed 2026-10-12T07:24:59.388Z sha 5b2d9e5 :: needs real behavior proof before merge. :: [P1] Disable hosted search when tool calls are denied | [P2] Preserve tool evidence in non-Codex review context | [P3] Describe the current triggers and delivery behavior in Labs
  • reviewed 2026-10-12T07:42:03.666Z sha 3d0b0aa :: needs real behavior proof before merge. :: [P1] Authorize the requested session before forking its context | [P1] Disable hosted search when tool calls are denied | [P2] Preserve tool evidence in built-in review context | [P3] Describe the current triggers and delivery behavior in Labs
  • reviewed 2026-10-12T08:43:40.424Z sha 4591b5a :: needs real behavior proof before merge. :: [P1] Authorize the requested session before reading its context | [P1] Disable inherited hosted search in denied forks | [P2] Support reviews after the parent turn releases its inference context | [P2] Preserve tool evidence for built-in Advisor reviews | [P3] Describe tool-start triggers and active steering in Labs
  • reviewed 2026-10-12T17:38:26.861Z sha 57008e9 :: needs real behavior proof before merge. :: [P1] Authorize the requested session before reading its context | [P1] Disable inherited hosted search in denied Codex forks | [P1] Remove hosted tools from built-in review requests before dispatch | [P2] Support Codex reviews started after parent cleanup | [P3] Describe the current triggers and delivery behavior in Labs
  • reviewed 2026-10-12T18:05:46.077Z sha 57008e9 :: needs real behavior proof before merge. :: [P1] Authorize the requested session before reading its context | [P1] Disable inherited hosted search in denied Codex forks | [P1] Remove hosted tools from built-in review requests before dispatch | [P2] Support Codex reviews started after parent cleanup | [P3] Describe the current triggers and delivery behavior in Labs
  • reviewed 2026-10-12T19:26:43.943Z sha 57008e9 :: needs real behavior proof before merge. :: [P1] Authorize the requested session before reading its context | [P1] Disable inherited hosted search in denied Codex forks | [P1] Remove hosted tools from built-in review requests before dispatch | [P2] Support Codex reviews started after parent cleanup | [P2] Preserve ordinary Responses side questions when disabling tools | [P3] Describe tool-start triggers and active steering in Labs
  • reviewed 2026-10-14T02:33:29.243Z sha 1b75f3a :: needs maintainer review before merge. :: none
  • reviewed 2026-10-14T08:11:49.154Z sha f693101 :: needs changes before merge. :: none

Reviewed October 14, 2026, 5:02 AM ET / 09:02 UTC (Revision 13).

@obviyus obviyus changed the title feat(labs): review agent progress and correct avoidable work feat(labs): add experimental Advisor that corrects avoidable agent work Oct 12, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. proof: 📸 screenshot Contributor real behavior proof includes screenshot evidence. labels Oct 12, 2026
@clawsweeper clawsweeper Bot added proof: 📸 screenshot Contributor real behavior proof includes screenshot evidence. and removed proof: 📸 screenshot Contributor real behavior proof includes screenshot evidence. labels Oct 12, 2026
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime extensions: memory-core Extension: memory-core agents Agent runtime and tooling extensions: codex plugin: file-transfer size: XL and removed size: L labels Oct 12, 2026
@clawsweeper clawsweeper Bot removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. labels Oct 12, 2026
…labs

# Conflicts:
#	docs/.generated/config-baseline.sha256
obviyus added a commit that referenced this pull request Oct 14, 2026
## What Problem This Solves

The Codex harness projects native app-server items (`commandExecution`, `dynamicToolCall`, and so on) to the `codex_app_server.item` agent-event stream with `started`/`completed` phases. Outer model tool calls that Codex records as raw response items have no projected lifecycle: function calls, custom tool calls (for example the code-mode JS `exec` wrapper), local shell calls and tool-search calls. A plugin that must know whether any tool call is still running therefore sees the run as idle while an outer code-mode call is still open, because its child shell commands have already completed.

This was found live with the Advisor plugin (#169564). It must not fork a session while a call is still open, because codex-rs normalization then fabricates an `aborted` output for the open call.

## Fix

`handleRawResponseItemCompleted` now also projects raw call receipts as `codex_app_server.item` `{ phase: "started", itemId: call_id, type }`, and their recorded outputs as `{ phase: "completed", itemId: call_id, type }`. Only phase, id and type are copied, never arguments or results. The app-server forwards raw response items after codex-rs records them in history, so `completed` means the output is persisted. Call and output receipts share `call_id` (codex-rs `protocol/src/models.rs`).

## User Impact

None by itself. Plugins that track in-flight work on Codex runs (with `payload: "metadata"`) can now see outer tool calls start and finish. The existing subscriber (`run-attempt.steering-settlement`) is unaffected.

## Evidence

- Projector test: raw function, custom, local-shell and tool-search calls produce paired started/completed events with ids and types only.
- The steering-settlement subscriber tests still pass.
- Live (Advisor, Codex runtime): before this change, a review boundary was reached while the outer code-mode call was open, and the Gateway logged a missing custom-tool output. Advisor's regression, an outer call open while its children are complete, holds the review until the outer output is recorded.

Co-authored-by: Ayaan Zaidi <[email protected]>
…labs

# Conflicts:
#	src/skills/workshop/experience-review.test.ts
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]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 14, 2026
)

Related: openclaw#170146 (session fork), openclaw#169564 (Advisor, the first consumer)

## What Problem This Solves

Plugins that notice a problem while an agent is still working can only queue context for the agent's next turn (`api.session.workflow.enqueueNextTurnInjection`). By then the run has already finished, so the agent spends the rest of the turn on the wasteful path. Core already lets users and `sessions_send` steer an active run; plugins have no access to it.

## Fix

Adds `api.session.workflow.steerActiveRun({ sessionKey, text, idempotencyKey? })`, returning `{ steered: true, runId? }` or `{ steered: false, reason }`.

- Uses the existing steering owner (`queueEmbeddedAgentMessageWithOutcomeAsync`) with the same call shape as `sessions_send` steer mode, so the built-in runner injects before the next model step and Codex receives native `turn/steer`.
- Plugin-authored and hidden: `internal_system` provenance with `sourceTool: "plugin:<id>"`, no sender or owner authority, never answers a pending user question.
- Requires the existing prompt-injection grant (`plugins.entries.<id>.hooks.allowPromptInjection`).
- Never throws for "no run accepts it": no active run, not streaming, backend rejection and missing grant return `steered: false` with the reason, so callers can fall back to `enqueueNextTurnInjection`.
- Respects plugin lifetime: the caller's plugin instance is revalidated after the lazy import and immediately before dispatch.

## User Impact

None by default; no core feature calls it. Plugins that opt in can correct an agent mid-run instead of after it finishes.

## Evidence

- Contract tests through the real plugin API factory and embedded steering queue: an active run receives the steer with plugin provenance and no sender/owner authority and does not answer a pending question; no active run returns `steered: false`; a plugin with `allowPromptInjection=false` is refused; an expired plugin instance cannot dispatch.
- Live (Codex runtime, real OpenAI API, isolated Gateway, via the Advisor plugin in openclaw#169564): a plugin steer issued mid-run was accepted (`steered: true`) and appears in the running turn's native rollout as a user item before the turn's next model request. Not observed live: the built-in runtime path, and whether the agent then changed course.
- Plugin revocation reaches final native admission (fix: `message-injection-target.ts` now composes the plugin lifetime assertion into the guard handed to V2 sinks; Codex already rechecks that guard after recorder persistence and right before the physical write, `attempt-steering.ts:302-304,350-359`). Real Codex client against a synthetic native app-server (`run-attempt.plugin-steering.test.ts`):
  - allowed guidance reaches the native server;
  - plugin disposed after the recorder persisted the item, before dispatch: rejected, `{ steered: false, reason: "runtime_rejected" }`, nothing written. Before the fix this returned `{ steered: true, runId: "run-1" }`;
  - an already-disabled plugin is rejected before queueing.
  - Totals: 3 native + 6 steering contract + 21 API lifecycle tests pass.
- Only source-guarded (V2) sinks accept plugin steering: `steerActiveRun` uses `queueGuardedEmbeddedAgentMessageWithOutcomeAsync`, so the plugin-lifetime assertion is checked up to native dispatch. A run whose runtime only has a legacy V1 sink (for example Copilot) returns `{ steered: false, reason: "active runtime does not support guarded steering" }` and nothing is queued; the caller can use next-turn injection instead. Regression: before the fix, a V1 run returned `{ steered: true }`. Totals: 62 tests across steering contract (7), `runs.steering` (31), API lifecycle (21), Codex plugin steering (3).
- Live at `0e6acc4`, real APIs, isolated Gateway, throwaway plugin that steers on the 2nd tool start (`"Also run 'echo STEERED' before you answer."`):

| Agent | Allowed steer | Effect | Plugin disabled mid-run (config hot reload) |
|---|---|---|---|
| Codex, OpenAI | `{ steered: true, runId }` | native rollout has the injected guidance, then `echo STEERED` and output `STEERED` | `{ steered: false, reason: 'Plugin "steer-probe" is no longer loaded' }`; no injected item in the rollout |
| Built-in, OpenAI `gpt-5.6-luna` | `{ steered: true, runId }` | transcript has hidden `internal_system` guidance from `plugin:steer-probe`, then `echo STEERED` output | same rejection; no injected item in the transcript |

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 14, 2026
)

## What Problem This Solves

`api.runContext` is the documented way for a plugin to share per-run data between its agent hooks and its Gateway service. In a running Gateway, agent-run hooks (`llm_input`, `agent_end`, …) dispatch from the agent's prepared, scoped plugin registry. That registry is loaded without global side effects, so `setRunContext` returned `stored: false` and `getRunContext` returned `undefined` there. The plugin's service runs in the root registry and never saw anything the hooks recorded.

Found while proving the Advisor plugin (openclaw#169564) live. Its `llm_input` hook records which runs are user-triggered, and its service counts tool starts for those runs. On a real Gateway, `setRunContext` from the hook returned `stored: false` on both Codex and the built-in runtime, so Advisor never reviewed anything.

## Fix

`setRunContext`, `getRunContext` and `clearRunContext` now require the plugin's existing lifecycle authority: `registration` plus `admittedRuntime`. They no longer use the blanket `activateGlobalSideEffects` denial.

- Allowed: active root registrations, and scoped hook registrations while their invocation is admitted.
- Still denied: plugins loaded only for inspection, and retired registrations.
- Unchanged: steering, prompt injection, agent-event emission and session attachments keep the old gate.

Run context is plugin-owned scratch data keyed by run ID, plugin ID and namespace. This change lets separate registrations of the same plugin exchange it; it grants no new authority.

## User Impact

Plugins that pair agent hooks with a service can share per-run data, as the SDK docs describe. No new API, config or protocol field.

## Evidence

- New contract regression in `src/plugins/contracts/host-hooks.contract.test.ts` uses real registries. A hook in the scoped agent-prepared registry writes run context, and the plugin's root service reads it. A registry loaded only for inspection is denied, and so is a retired registration. Before the fix the scoped write returned `false`.
- `host-hooks.contract.test.ts`: 53/53 pass. Scoped typecheck, oxlint and the import-cycle check are clean.
- Live, isolated Gateway: before the fix, the hook's `setRunContext` returned `stored: false` on both Codex and built-in runs. The live run after the fix is in openclaw#169564.
- Docs: `docs/plugins/sdk-overview/host-hooks.md` states what run context allows and does not allow.

Co-authored-by: Ayaan Zaidi <[email protected]>
@obviyus

obviyus commented Oct 14, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper review

@clawsweeper

clawsweeper Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

…labs

# Conflicts:
#	docs/.generated/config-baseline.sha256
@obviyus

obviyus commented Oct 14, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper review

@clawsweeper

clawsweeper Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@obviyus

obviyus commented Oct 14, 2026

Copy link
Copy Markdown
Collaborator Author

Landed as a77bf04.

  • What: Advisor, an experimental Labs plugin (default off). It reviews an agent's ongoing work every N tool calls or M minutes, by forking the session's own context at cached-input prices. When it finds clearly avoidable work, it steers the run with one short correction, after a second fork verifies it.
  • Safety: decisions fail closed. A review never runs while a tool call is in flight: built-in calls settle on their result event, and Codex calls on native item completion, including outer code-mode calls. Only user-triggered runs are admitted. Review guidance can be edited on the settings page; the output contract and the verify step stay fixed.
  • Cost: no history-carrying hooks, and events are filtered by phase with metadata-only payloads. On ordinary turns the host clones about 1.4 KB for Advisor, where the earlier design cloned up to about 1.3 MB.
  • Proof: blind-holdout evaluation (luna and sol: 0 false corrections, 100% recall, 95% quality); live runs on Codex and built-in (exact call counts, safe-boundary dispatch); 77 plugin tests; exact-head CI green.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

app: web-ui App: web-ui dependencies-changed PR changes dependency-related files docs Improvements or additions to documentation gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: 📸 screenshot Contributor real behavior proof includes screenshot evidence. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant