Skip to content

fix(agents): deliver plugin next-turn context on Codex and other harness runtimes - #169558

Merged
obviyus merged 3 commits into
mainfrom
fix/harness-next-turn-injections
Oct 13, 2026
Merged

obviyus merged 3 commits into
mainfrom
fix/harness-next-turn-injections

Conversation

@obviyus

@obviyus obviyus commented Oct 12, 2026 •

Copy link
Copy Markdown
Collaborator

What Problem This Solves

Fixes: context a plugin queues for a conversation's next turn (api.session.workflow.enqueueNextTurnInjection) is silently dropped when that turn runs on a harness runtime (Codex app-server, ACPX, Agents API, Copilot). OpenAI models use the Codex runtime by default, so most installs never receive these injections.

User Impact

Plugins that queue next-turn context now reach the agent on every runtime, not only the built-in one. Turns with nothing queued produce byte-identical prompts, so prompt caching is unchanged.

Why This Change Was Made

Only the built-in runner drained the durable injection queue and ran agent_turn_prepare. The harness prompt builder skipped both, and returned early when no prompt hooks were registered. One module now owns queue draining, the per-run retry cache, and agent_turn_prepare. The built-in runner and the harness prompt builder both use it, in the existing order: queued injections, agent_turn_prepare, heartbeat contribution, before_prompt_build. Harness runs release the retry cache when the run ends. History is still loaded only when a prompt hook needs it.

Evidence

  • Live, real OpenAI API, isolated Gateway, Codex runtime (default for openai/gpt-6.1-sol): a plugin queued a correction after a turn, and the next turn was asked to quote any note it received.
    • Before (current main): the agent answered "No, my context for this turn does not include a note starting with 'Progress review (OpenClaw Labs)'."
    • After: the agent quoted the queued note verbatim.
  • Regression test: src/agents/harness/prompt-compaction-hook-helpers.test.ts "delivers queued injections". With a real enqueued injection and no prompt hooks registered, the prompt contains the text once, a same-run retry reuses it, and the queue is drained. It fails on main (prompt.match(...) is null) and passes with this change.
  • Focused tests: harness helper 12/12, embedded prompt helpers 6/6, host-hook contract injection cases 7/7.
  • Maintainer-intent check: refactor(harness): share prompt preparation and context policies #159779 and fix(agentsapi): include plugin context in agent prompts #159375 shaped this helper and the Agents API hooks. This change keeps their contract: no-hook and heartbeat-only attempts still do not read history, and the Agents API config move only places it in the shared host-side context (buildAgentHookContext does not forward config to plugins).
  • Not run locally: full lint (the plugin-SDK boundary declaration prep timed out on a loaded host). Left to hosted CI.

Merge danger: two-way door; a revert restores the old behavior. Blast radius: harness runtimes now drain the injection queue, so plugins that already queue next-turn context (for example on Codex) will start seeing it delivered.

@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 agents Agent runtime and tooling extensions: codex extensions: agentsapi 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: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. 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

Shares queued plugin context and turn-preparation hooks across embedded and harness runtimes.

Example: A plugin queues “queued workflow context” for agent:main:main before a Codex turn.

  • Before: The harness prompt contains only “hello”; the queued context is omitted.
  • After: The prompt includes the queued context once, and a retry within the same run retains it.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Focused, coherent repair with no identified defect and successful current-head gates; direct evidence of the reported live model delivery remains limited.
Proof confidence 🦐 gold shrimp (3/6) The collaborator-authored PR is outside the ordinary contributor-proof gate; its body reports real-API Codex delivery, while directly inspectable coverage is the shared prompt-builder integration test and unrelated Advisor settings screenshots.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Plugin-authored next-turn guidance never reaches agents using harness runtimes.
Reason: Repairs an established plugin contract through one shared implementation; collaborator authorship supplies the direction decision.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored PR fixes a current harness integration gap, preserves retry behavior, and has no identified blocking defect.

Priority: P2
Reviewed head: b14328b639e8848792dd13da6421689c0c83268c

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The reported isolated-Gateway Codex run has no attached delivery trace; the inspected screenshots show Advisor settings rather than context consumption.
Agent review details

How this fits together

Plugin workflow APIs persist next-turn context in session state; shared prompt preparation consumes that context and passes the assembled prompt to the selected agent runtime.

flowchart LR
  A[Plugin workflow API] --> B[Session injection queue]
  B --> C[Shared turn context]
  C --> D[Embedded prompt builder]
  C --> E[Harness prompt builder]
  D --> F[Model turn]
  E --> F
  G[Logical run settlement] --> C
Loading

Technical review

Best possible solution:

Land the shared turn-context owner while preserving existing queue policy, lazy history loading, and logical-run retry retention.

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

Current main demonstrably omits queue draining from the harness helper; the added integration test exercises a real queued injection with no prompt hooks and a failed-attempt retry, but no target code was executed during this read-only review.

Is this the best way to solve the issue?

The shared owner fixes the missing integration directly, removes the embedded implementation it replaces, and preserves the existing order and cleanup contract.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Queued injection draining, retry cache, and agent_turn_prepare keeps the original intent (1adaa28: Generic host hooks supplied durable next-turn context and turn preparation so workflow plugins could operate without bespoke core patches.)
  • Shared harness prompt preparation and lazy history keeps the original intent (42e53a4: Agents API needed plugin context while avoiding history reads when no message-consuming prompt hook required them.)
  • Harness heartbeat ordering keeps the original intent (cf86a97: Restore heartbeat hook parity with the embedded runner and collect heartbeat contributions before ordinary prompt-build hooks.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

  • Current main still lacks harness delivery: The fetched main harness helper returns early without prompt hooks and never invokes queued-injection draining or agent_turn_prepare. (src/agents/harness/prompt-compaction-hook-helpers.ts:62, 8cc27997ca63)
  • Introduced change uses one shared owner: The pinned introduction diff moves existing drain/cache/prepare behavior into plugin-turn-context and makes both prompt builders consume it; all existing cleanup imports move with the owner. (src/agents/plugin-turn-context.ts:28, b14328b639e8)
  • Retry retention and terminal cleanup: The cache survives attempt-end hooks and is cleared in the logical run owner's finally block, addressing the earlier drained-injection finding without clearing context before fallback retries. (src/agents/embedded-agent-runner/run-entry.ts:636, b14328b639e8)
  • Existing policy and storage contracts preserved: Consumption still uses the existing session-state owner, active-plugin filter, prompt-injection policy, expiry handling, and serialized injection records; this PR adds no persisted format or migration. (src/plugins/host-hook-state.ts:131, b14328b639e8)
  • Maintainer-approved behavioral expansion: The collaborator-authored body explicitly accepts delivery of previously queued harness context; prior shared-prompt contracts retain lazy history loading and keep raw config local to host construction. (src/agents/harness/prompt-compaction-hook-helpers.ts:80, b14328b639e8)
  • Current-head CI and merge state: GitHub reports a clean merge and successful CI, dependency-review, and security-sensitive-review gates for the reviewed head; cancelled review/dispatch checks do not establish a patch-caused failure. (b14328b639e8)

Likely related people:

  • Sarah Fortune: Raw commit 71bd3de adds src/agents/harness/prompt-compaction-hook-helpers.ts:66 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 71bd3ded986b; files: src/agents/harness/prompt-compaction-hook-helpers.ts)

PR surface

Source +35, Tests +58, Docs 0. Total +93 across 14 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 7 105 70 +35
Tests 6 71 13 +58
Docs 1 7 7 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 14 183 90 +93

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: Queued workflow context is silently omitted on harness turns, affecting plugins using an existing supported API.
  • merge-risk: 🚨 compatibility: Existing queued injections and agent_turn_prepare registrations begin affecting harness prompts; the collaborator-authored PR explicitly accepts this behavioral expansion.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rank-up moves

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

  • Optionally attach a redacted Codex request/response trace showing queued context reaching the next turn.

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 (3 earlier review cycles)
  • reviewed 2026-10-12T03:03:24.620Z sha 7da5371 :: needs changes before merge. :: [P1] Preserve drained injections until the logical run finishes
  • reviewed 2026-10-12T06:10:19.180Z sha 59a4e68 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-12T18:03:32.471Z sha 59a4e68 :: needs changes before merge. :: none

Reviewed October 13, 2026, 2:58 PM ET / 18:58 UTC (Revision 4).

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 12, 2026
…-injections

# Conflicts:
#	src/agents/embedded-agent-runner/run/attempt-prompt-helpers.ts
#	src/agents/embedded-agent-runner/run/attempt.prompt-helpers.test.ts
@obviyus
obviyus marked this pull request as ready for review October 13, 2026 18:19
@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 closed this Oct 13, 2026
@obviyus obviyus reopened this Oct 13, 2026
@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 removed the status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. label Oct 13, 2026
@clawsweeper clawsweeper Bot added the status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. label Oct 13, 2026
@obviyus
obviyus merged commit 8118777 into main Oct 13, 2026
208 of 210 checks passed
@obviyus
obviyus deleted the fix/harness-next-turn-injections branch October 13, 2026 19:02
@obviyus

obviyus commented Oct 13, 2026

Copy link
Copy Markdown
Collaborator Author

Landed as 8118777.

  • Problem: plugin next-turn context (for example a queued note) was dropped on Codex and other harness runtimes, and a failed attempt lost context that had already been drained.
  • Fix: harness runtimes now use the same turn-preparation and next-turn-injection path as the embedded runner. Drained injections are kept across failed-attempt retries.
  • Proof: the regression fails on the base and passes on the head. The failed-attempt retry case is covered. Focused prompt-build tests pass. Exact-head CI is green.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 14, 2026
…ess runtimes (openclaw#169558)

## What Problem This Solves

Fixes: context a plugin queues for a conversation's next turn (`api.session.workflow.enqueueNextTurnInjection`) is silently dropped when that turn runs on a harness runtime (Codex app-server, ACPX, Agents API, Copilot). OpenAI models use the Codex runtime by default, so most installs never receive these injections.

## User Impact

Plugins that queue next-turn context now reach the agent on every runtime, not only the built-in one. Turns with nothing queued produce byte-identical prompts, so prompt caching is unchanged.

## Why This Change Was Made

Only the built-in runner drained the durable injection queue and ran `agent_turn_prepare`. The harness prompt builder skipped both, and returned early when no prompt hooks were registered. One module now owns queue draining, the per-run retry cache, and `agent_turn_prepare`. The built-in runner and the harness prompt builder both use it, in the existing order: queued injections, `agent_turn_prepare`, heartbeat contribution, `before_prompt_build`. Harness runs release the retry cache when the run ends. History is still loaded only when a prompt hook needs it.

## Evidence

- **Live, real OpenAI API, isolated Gateway, Codex runtime (default for `openai/gpt-6.1-sol`):** a plugin queued a correction after a turn, and the next turn was asked to quote any note it received.
  - Before (current `main`): the agent answered "No, my context for this turn does not include a note starting with 'Progress review (OpenClaw Labs)'."
  - After: the agent quoted the queued note verbatim.
- **Regression test:** `src/agents/harness/prompt-compaction-hook-helpers.test.ts` "delivers queued injections". With a real enqueued injection and no prompt hooks registered, the prompt contains the text once, a same-run retry reuses it, and the queue is drained. It fails on `main` (`prompt.match(...)` is null) and passes with this change.
- **Focused tests:** harness helper 12/12, embedded prompt helpers 6/6, host-hook contract injection cases 7/7.
- Maintainer-intent check: openclaw#159779 and openclaw#159375 shaped this helper and the Agents API hooks. This change keeps their contract: no-hook and heartbeat-only attempts still do not read history, and the Agents API `config` move only places it in the shared host-side context (`buildAgentHookContext` does not forward `config` to plugins).
- Not run locally: full lint (the plugin-SDK boundary declaration prep timed out on a loaded host). Left to hosted CI.

**Merge danger:** two-way door; a revert restores the old behavior. Blast radius: harness runtimes now drain the injection queue, so plugins that already queue next-turn context (for example on Codex) will start seeing it delivered.

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: agentsapi extensions: codex merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. 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