Repository navigation
fix(agents): deliver plugin next-turn context on Codex and other harness runtimes - #169558
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. What this changesShares 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.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete 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 Before mergeNone. FindingsNone. Tests
Agent review detailsHow this fits togetherPlugin 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
Technical reviewBest 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
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +35, Tests +58, Docs 0. Total +93 across 14 files. Added test files: 0. View PR surface stats
LabelsLabel changes:
Label justifications:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (3 earlier review cycles)
Reviewed October 13, 2026, 2:58 PM ET / 18:58 UTC (Revision 4). |
…-injections # Conflicts: # src/agents/embedded-agent-runner/run/attempt-prompt-helpers.ts # src/agents/embedded-agent-runner/run/attempt.prompt-helpers.test.ts
|
ClawSweeper reviews are opt-in for maintainers. If a review is required, finish the work and validation first, then comment |
|
@clawsweeper review |
|
🦞👀 Re-review progress:
|
|
Landed as 8118777.
|
…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]>
… 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 after, with Advisor enabled:  Plugin settings page opened by **Configure**, with the multiline **Review instructions** field:  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]>
… 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 after, with Advisor enabled:  Plugin settings page opened by **Configure**, with the multiline **Review instructions** field:  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]>
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, andagent_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
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.main): the agent answered "No, my context for this turn does not include a note starting with 'Progress review (OpenClaw Labs)'."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 onmain(prompt.match(...)is null) and passes with this change.configmove only places it in the shared host-side context (buildAgentHookContextdoes not forwardconfigto plugins).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.