Skip to content

feat(plugins): let plugins steer a session's active run - #170152

Merged
obviyus merged 7 commits into
mainfrom
feat/plugin-active-run-steering
Oct 13, 2026
Merged

obviyus merged 7 commits into
mainfrom
feat/plugin-active-run-steering

Conversation

@obviyus

@obviyus obviyus commented Oct 12, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #170146 (session fork), #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 feat(labs): add experimental Advisor that steers agents off avoidable work #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

@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 size: M labels Oct 12, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. 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

This PR lets plugins send hidden guidance to a session’s active run through the existing guarded steering API.

Example: A plugin sends “Also run 'echo STEERED' before you answer.” to agent:main:main during a run.

  • Before: The plugin can queue guidance only for the next turn.
  • After: The active Codex or built-in run accepts the guidance and executes echo STEERED before answering.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Useful, focused, and supported by live results plus final-admission coverage; no actionable defect remains.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The supplied isolated-Gateway live results at 0e6acc4 exercise the plugin workflow API on Codex and the built-in runtime: accepted guidance produces STEERED, while hot-reload disablement prevents injection. The production Codex client harness additionally rejects disposal after persistence before native I/O. These implementation paths are unchanged at the reviewed head; inspected Advisor screenshots provide only companion UI context.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Feature · Worth it: Yes · Fix scope: Complete
User problem: Plugins cannot correct an agent’s ongoing work until its next turn.
Reason: The collaborator-authored direction supplies a concrete consumer and uses a small generic capability behind the existing prompt-injection grant.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: it adds a useful plugin capability absent from current main, has maintainer-authored direction, and addresses both earlier authority findings without a new actionable defect.

Priority: P2
Reviewed head: 6391cca338ea0db4bf763680051815b7c0395953

Before merge

None.

Findings

None.

Agent review details

How this fits together

The plugin workflow facade accepts a session key and guidance, checks the existing prompt-injection grant and plugin lifetime, and passes hidden internal context to the active runtime’s steering owner.

flowchart TD
  A[Plugin workflow caller] --> B[Grant and lifetime checks]
  B --> C[Active session lookup]
  C --> D[Guarded steering owner]
  D --> E[Built-in runtime]
  D --> F[Codex native transport]
  E --> G[Active turn context]
  F --> G
Loading

Technical review

Best possible solution:

Land the narrow workflow capability with its existing grant, guarded runtime admission, and documented explicit next-turn fallback.

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

This is a capability addition rather than a bug report; current main exposes next-turn injection but no plugin workflow method for active-run steering.

Is this the best way to solve the issue?

The implementation fits the existing workflow facade and shared steering owner, preserves hidden plugin provenance, and avoids a competing delivery mechanism.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Shared steering authority binding keeps the original intent (9cbcd21: Prepare steering authority through session readers while retaining independent caller guards, final admission, and released legacy adapters.)
  • Grouped session workflow facade keeps the original intent (50ee68c: Consolidate host workflow seams into grouped Plugin SDK namespaces while retaining the underlying flat implementation surface.)
  • Late-callable registration policy keeps the original intent (416057e: Keep runtime-callable methods available after registration using one typed policy set.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 9cbcd21 adds src/agents/embedded-agent-runner/message-injection-target.ts:352 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 9cbcd2108052; files: src/agents/embedded-agent-runner/message-injection-target.ts)
  • Eva: Raw commit 50ee68c adds src/plugins/api-facades.ts:34 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 50ee68cdf43d; files: src/plugins/api-facades.ts)

PR surface

Source +119, Tests +355, Docs +38. Total +512 across 14 files. Added test files: 2.

View PR surface stats
Area Files Added Removed Net
Source 8 119 0 +119
Tests 5 355 0 +355
Docs 1 38 0 +38
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 14 512 0 +512

Review metrics

Metric Value Why it matters
Production versus tests Production +118/-0; tests +354/-0 Production growth exposes the generic workflow contract and its lazy host adapter; tests cover registration lifetime, provenance, legacy refusal, and native revocation.

Labels

Label changes:

  • 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: This is an optional plugin capability with a concrete consumer and no default user behavior change.
  • merge-risk: 🚨 compatibility: This expands the public plugin API; the maintainer-authored direction documents guarded-runtime support and preserves existing V1 steering and next-turn APIs.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

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 (4 earlier review cycles)
  • reviewed 2026-10-12T19:31:21.790Z sha 85ddc54 :: needs real behavior proof before merge. :: [P1] Bind plugin lifetime to the guarded queue’s final assertion
  • reviewed 2026-10-13T01:10:41.856Z sha 98f8a54 :: needs real behavior proof before merge. :: [P1] Require source-bound admission before steering a legacy sink
  • reviewed 2026-10-13T03:11:24.819Z sha 3b22a62 :: needs real behavior proof before merge. :: [P1] Require source-bound admission before steering a legacy sink
  • reviewed 2026-10-13T03:27:57.904Z sha 0e6acc4 :: needs changes before merge. :: none

Reviewed October 13, 2026, 12:56 PM ET / 16:56 UTC (Revision 5).

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling extensions: codex labels Oct 13, 2026
@obviyus

obviyus commented Oct 13, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@obviyus

obviyus commented Oct 13, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 13, 2026
@obviyus
obviyus marked this pull request as ready for review October 13, 2026 15:08
@clawsweeper

clawsweeper Bot commented Oct 13, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper reviews are opt-in for maintainers. If a review is required, finish the work and validation first, then comment @clawsweeper review. Please avoid repeated requests while a review is queued or running; agents should not request reviews automatically.

@obviyus

obviyus commented Oct 13, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper review

@clawsweeper

clawsweeper Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 13, 2026
@obviyus
obviyus merged commit ae2be85 into main Oct 13, 2026
295 of 297 checks passed
@obviyus
obviyus deleted the feat/plugin-active-run-steering branch October 13, 2026 16:58
@obviyus

obviyus commented Oct 13, 2026

Copy link
Copy Markdown
Collaborator Author

Landed as ae2be85.

  • Problem: a plugin could add guidance for a session's next turn, but could not steer the run in progress.
  • Fix: api.session.workflow.steerActiveRun sends hidden guidance (internal_system, plugin:<id>) into the active run, using only source-guarded (V2) sinks. The plugin-lifetime check runs again just before native dispatch. Runtimes with only a legacy V1 sink return steered: false and nothing is queued.
  • Proof: live with real APIs on Codex and built-in OpenAI. An allowed steer made the agent run echo STEERED. A plugin disabled mid-run was rejected, with no injected item. Regressions cover disposal after recorder persistence and V1 sink refusal. The native admission test now uses the controlled clock, so a slow CI host cannot spend its execution budget. Exact-head CI is green.

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]>
obviyus added a commit that referenced this pull request Oct 14, 2026
… work (#169564)

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](https://github.com/user-attachments/assets/3d5234db-8b6f-43b9-aec4-d32db7e6ca0a)

Labs after, with Advisor enabled:

![Labs after](https://github.com/user-attachments/assets/bc894ba5-30e6-407b-8296-51c57e8a07e5)

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

![Advisor plugin settings](https://github.com/user-attachments/assets/549bc02c-54c7-419e-98c4-3bccb7911843)

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.

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

Built on openclaw#170146 (`forkSession`), openclaw#170152 (`steerActiveRun`), openclaw#171307 (shared `api.runContext`), openclaw#171534 (event `phases`), openclaw#171580 (forks show in-flight calls as pending) and openclaw#171610 (`payload: "metadata"`), openclaw#171651 (internal skill-workshop reviews are not user turns) and openclaw#171661 (Codex outer tool-call lifecycle), all on `main`. Related: openclaw#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](https://github.com/user-attachments/assets/3d5234db-8b6f-43b9-aec4-d32db7e6ca0a)

Labs after, with Advisor enabled:

![Labs after](https://github.com/user-attachments/assets/bc894ba5-30e6-407b-8296-51c57e8a07e5)

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

![Advisor plugin settings](https://github.com/user-attachments/assets/549bc02c-54c7-419e-98c4-3bccb7911843)

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.

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 docs Improvements or additions to documentation extensions: codex merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M 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