Repository navigation
fix(exec): plugin tools can tell which run started a background exec completion wake - #179816
Conversation
…tools
A background exec completion wake reached plugins as
{ kind: "internal_system", sourceTool: "exec" } with no link to the run
that started the command, and plugin tool factories received neither the
turn's run id nor its input provenance. On claude-cli agents the MCP
loopback grant also dropped internal provenance. A plugin therefore could
not tell the completion of a command its owner started from any other
internal turn.
- exec records the starting run on the process and the completion wake
stamps it as InputProvenance.runId.
- plugin tool contexts expose runId and inputProvenance on both the
embedded runtime and the claude-cli MCP loopback; the CLI grant carries
internal-system provenance, which requester policy does not read.
- the agent RPC reserves exec completion provenance for backend callers,
so a client cannot forge it.
Wakes stay non-owner turns; the new fields are facts, not authority.
|
🦞👀 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 changesThis PR exposes the starting run of background exec completions to plugin tools through embedded and CLI MCP contexts. Example: Run owner-start-turn starts sleep 2; echo WAKE_EXEC_DONE and ends before the command finishes.
Review scores
ProductKind: Feature · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review Keep open: this maintainer-authored PR supplies useful completion correlation that current main lacks, with no concrete production defect found. Priority: P2 Before mergeNone. FindingsNone. Tests
Agent review detailsHow this fits togetherThe exec process registry retains launch facts, session-event admission creates the completion turn, and embedded or MCP tool construction passes its context to plugins. flowchart LR
A[Starting agent turn] --> B[Background exec process]
B --> C[Completion notifier]
C --> D[Session event admission]
D --> E[Embedded tool context]
D --> F[CLI MCP grant]
E --> G[Plugin tool factory]
F --> G
Technical reviewBest possible solution: Carry optional run correlation through the existing exec, session-event, and plugin-context owners while preserving independent live authorization. Do we have a high-confidence way to reproduce the issue? Current-main source omits the originating run from completion provenance and plugin contexts, matching the supplied before traces; no target code was executed during this review. Is this the best way to solve the issue? The patch is a small, complete extension of existing owners, with no parallel policy manager or alternative notification path. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against e76b87421a99. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +35, Tests +105, Docs +11. Total +151 across 16 files. Added test files: 0. View PR surface stats
Review metrics
LabelsLabel changes:
Label justifications:
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 Reviewed October 21, 2026, 5:56 PM ET / 21:56 UTC. |
…tools (openclaw#179816) A background exec completion wake reached plugins as { kind: "internal_system", sourceTool: "exec" } with no link to the run that started the command, and plugin tool factories received neither the turn's run id nor its input provenance. On claude-cli agents the MCP loopback grant also dropped internal provenance. A plugin therefore could not tell the completion of a command its owner started from any other internal turn. - exec records the starting run on the process and the completion wake stamps it as InputProvenance.runId. - plugin tool contexts expose runId and inputProvenance on both the embedded runtime and the claude-cli MCP loopback; the CLI grant carries internal-system provenance, which requester policy does not read. - the agent RPC reserves exec completion provenance for backend callers, so a client cannot forge it. Wakes stay non-owner turns; the new fields are facts, not authority. Co-authored-by: VACInc <[email protected]>
|
Additional downstream plugin-compatibility evidence from Windows x64 / Node 26.12.1, using the official 2026.10.10-beta.3 package at
Please make the first packaged version carrying these optional tool-context fields clear in release notes/SDK compatibility guidance. No claim of a live end-to-end test of this PR is intended; this is release-contract/source verification. In particular, No credentials, transcripts, private identifiers or business data are included. |
…nds exit together (#199113) ## What Problem This Solves Fixes: when several background commands exit close together, the agent gets one wake turn per command, so three exits cost three model turns and three replies. ## User Impact User impact: completions that arrive while an earlier completion turn in the same conversation is still queued or running now reach the agent together in one turn, with each result's process ID, status, exit code and output tail. A single completion starts at once, exactly as before. ## Why This Change Was Made Each exit enqueued its own session event and became its own turn. The session event owner already turns a set of exact queued occurrences into one ordinary turn (`occurrences`, used by session-state notices), and `combineSessionEventTargetsForHost` already checks that a set shares one destination and requester authority. This change reuses both: - New `session-event-batch.ts` in the session event owner keeps one in-flight completion turn per conversation. A completion with nothing in flight starts at once through `enqueueSessionEventForHost`, unchanged. A completion that arrives while that turn is queued or running claims its queued occurrence and waits. One second after the turn settles, every waiting completion that shares the same exec request owners, launching run, route and combinable target starts one turn with all of their occurrences. - `bash-tools.exec-notify.ts` only switches its enqueue import to the batched entry point. Each result keeps the wake format from #199122 (`Exec completed (<id>, code 0, 4m3s):` plus a tail of up to 2,000 chars). - One shared turn carries at most about 8,000 characters of results. Occurrence text must stay byte-exact, so the bound limits membership, not text: results past the budget start the next turn. - The exec completion guidance is count-neutral ("Treat each completion result above as an internal continuation…") so a batched turn no longer says "this completion" for several results. Choices and accepted edges: - **A 1 s settle, only for completions that already waited.** A first or lone completion still starts at once (measured base: its turn starts within about 1 s of the exit, before later exits arrive), so no delay is added to single wakes. Without a settle, exits about 1 s apart sometimes straddle the end of the turn they waited behind: on the intermediate head, 2 of 6 trials split into three turns because the last exit arrived just after the batch started. Waiting completions now start 1 s after that turn settles, so stragglers join. - **Only one request's completions share a turn.** Stop aborts every exec request owner of a turn, so mixing requests would let one Stop retire another request's result. Completions from different requests keep separate turns. - **Only one launching run's completions share a turn.** The completion turn's input provenance names the run that launched the command, which plugins use to correlate a completion with its run (#179816). Request owners carry over into completion turns, so commands launched by a later run can share owners with earlier ones; the batch also requires the same launching run, and each shared turn keeps a truthful `inputProvenance.runId`. - **Cron-run completions never wait.** They check at acceptance that the originating run is still alive; holding them could turn an accepted completion into a refused one. - Removing one member after its shared turn is queued (for example, the model polled that result) leaves the shared prompt as is; the turn is retired only when every member is removed. Before the shared turn is queued, removal drops just that member. - A waiting completion starts after its predecessor settles, so a human message queued in `followup` or `collect` mode meanwhile can run first. - Rebased on #199122 (wake format) and #199085. This PR touches only the import line in `bash-tools.exec-notify.ts` and the guidance wording in `agent-runner-run-params.ts`. ## Evidence **Real-agent E2E** (isolated source Gateway via `ocx src`, real OpenAI model, 6 concurrent trial sessions per arm). Each trial asks the agent to start three background waiters with `yieldMs`, waits until the session is idle with all three running, then releases them 1 s apart. Base = current `main` (`afeadf1c4fe0`, includes #199122); fix = this PR rebased on it. | Arm | Wake turns (6 trials) | Results acknowledged | Wake-turn tokens (total) | Wake-turn cost | | --- | --- | --- | --- | --- | | base, 3 exits | 18 (3 per trial) | 18/18 | 501,233 | $1.152 | | fix, 3 exits | 12 (2 per trial) | 18/18 | 326,362 (-35%) | $0.930 | | base, 1 exit | 6 | 6/6 | 153,377 | $0.402 | | fix, 1 exit | 6 | 6/6 | 153,934 | $0.403 | Single-exit wake latency (release to wake message, median of 6): base 0.85 s, fix 0.85 s. A single completion never waits for the settle. Time from release to the last reply in the 3-exit arm: base median 9.2 s, fix median 7.3 s. Every fix trial: the first exit starts its turn at once; the two later exits arrive during it and share the next turn, each keeping its own id, exit code, duration and tail. Results from earlier runs before the rebase (same arms, older wake format) matched: 12 turns vs 18. <details><summary>Redacted trace, trial 1 (times relative to release of the first waiter)</summary> Base (before the rebase, old wake format): ``` +8.8s USER: Exec completed (gentle-c, code 0) :: job 1 result: r11-1603127358 +11.7s reply (26930 tok): job 1 result: r11-1603127358 +19.1s USER: Exec completed (dawn-gla, code 0) :: job 2 result: r12-78193628 +22.0s reply (27407 tok): job 2 result: r12-78193628 +26.5s USER: Exec completed (kind-sum, code 0) :: job 3 result: r13-1811516849 +29.2s reply (27885 tok): job 3 result: r13-1811516849 ``` Fix (rebased head): ``` +1.2s USER: Exec completed (tide-cov, code 0, 34s): job 1 result: r11-1383216 +3.7s reply (26761 tok): job 1 result: r11-1383216 +5.1s USER: Exec completed (tidy-com, code 0, 32s): job 2 result: r12-262323306 Exec completed (rapid-bi, code 0, 29s): job 3 result: r13-179203848 +7.7s reply (27281 tok): job 2 result: r12-262323306 / job 3 result: r13-179203848 ``` </details> **Regression tests:** `bash-tools.exec-background-followup.test.ts` runs three real background commands through the exec tool and the real session event owner with a held first model turn. Same launching run: base starts three completion turns (red); the fix starts two, the second carrying both later results and naming their run. Different launching runs with shared request owners: the later results keep separate turns, each naming its own run (red without the launch-run check). Five results of ~2,000 chars: the shared turn takes three and the fifth starts its own turn (size bound). **Focused suites (`ocx test`, rebased head, 14 files):** `bash-tools.exec-background-followup`, `bash-tools.test`, `bash-tools.exec-runtime`, `bash-tools.exec-runtime.cleanup`, `bash-tools.visible-subagent-notify`, `bash-tools.exec-request-stop`, `bash-tools.exec.egress-lifecycle`, `bash-tools.notify-on-exit-ack`, `bash-tools.process.e2e`, `bash-tools.exec-notify.requester`, `bash-tools.exec-notify.queue-full`, `infra/exec-session-event`, `session-event-handoff`, `agent-runner-execution-session-events`: all pass. `exec-session-event`'s chained-completion case now waits for the second receipt, which starts after the 1 s settle. **Full tier:** `ocx build --dts` (full profile) built `92847fc`; the self-contained source package passed its tarball integrity check, installed with npm into a scratch prefix, and the packed CLI reported `OpenClaw 2026.11.3 (92847fc)` with `gateway --help` exit 0. The later head commit only changes a test type. **Gaps:** E2E covers exits from one request in an idle Control UI-style session; completions from different requests and channel-delivered sessions are covered by the shared owner's existing tests, not by a new live run. Co-authored-by: Ayaan Zaidi <[email protected]>
…nds exit together (openclaw#199113) ## What Problem This Solves Fixes: when several background commands exit close together, the agent gets one wake turn per command, so three exits cost three model turns and three replies. ## User Impact User impact: completions that arrive while an earlier completion turn in the same conversation is still queued or running now reach the agent together in one turn, with each result's process ID, status, exit code and output tail. A single completion starts at once, exactly as before. ## Why This Change Was Made Each exit enqueued its own session event and became its own turn. The session event owner already turns a set of exact queued occurrences into one ordinary turn (`occurrences`, used by session-state notices), and `combineSessionEventTargetsForHost` already checks that a set shares one destination and requester authority. This change reuses both: - New `session-event-batch.ts` in the session event owner keeps one in-flight completion turn per conversation. A completion with nothing in flight starts at once through `enqueueSessionEventForHost`, unchanged. A completion that arrives while that turn is queued or running claims its queued occurrence and waits. One second after the turn settles, every waiting completion that shares the same exec request owners, launching run, route and combinable target starts one turn with all of their occurrences. - `bash-tools.exec-notify.ts` only switches its enqueue import to the batched entry point. Each result keeps the wake format from openclaw#199122 (`Exec completed (<id>, code 0, 4m3s):` plus a tail of up to 2,000 chars). - One shared turn carries at most about 8,000 characters of results. Occurrence text must stay byte-exact, so the bound limits membership, not text: results past the budget start the next turn. - The exec completion guidance is count-neutral ("Treat each completion result above as an internal continuation…") so a batched turn no longer says "this completion" for several results. Choices and accepted edges: - **A 1 s settle, only for completions that already waited.** A first or lone completion still starts at once (measured base: its turn starts within about 1 s of the exit, before later exits arrive), so no delay is added to single wakes. Without a settle, exits about 1 s apart sometimes straddle the end of the turn they waited behind: on the intermediate head, 2 of 6 trials split into three turns because the last exit arrived just after the batch started. Waiting completions now start 1 s after that turn settles, so stragglers join. - **Only one request's completions share a turn.** Stop aborts every exec request owner of a turn, so mixing requests would let one Stop retire another request's result. Completions from different requests keep separate turns. - **Only one launching run's completions share a turn.** The completion turn's input provenance names the run that launched the command, which plugins use to correlate a completion with its run (openclaw#179816). Request owners carry over into completion turns, so commands launched by a later run can share owners with earlier ones; the batch also requires the same launching run, and each shared turn keeps a truthful `inputProvenance.runId`. - **Cron-run completions never wait.** They check at acceptance that the originating run is still alive; holding them could turn an accepted completion into a refused one. - Removing one member after its shared turn is queued (for example, the model polled that result) leaves the shared prompt as is; the turn is retired only when every member is removed. Before the shared turn is queued, removal drops just that member. - A waiting completion starts after its predecessor settles, so a human message queued in `followup` or `collect` mode meanwhile can run first. - Rebased on openclaw#199122 (wake format) and openclaw#199085. This PR touches only the import line in `bash-tools.exec-notify.ts` and the guidance wording in `agent-runner-run-params.ts`. ## Evidence **Real-agent E2E** (isolated source Gateway via `ocx src`, real OpenAI model, 6 concurrent trial sessions per arm). Each trial asks the agent to start three background waiters with `yieldMs`, waits until the session is idle with all three running, then releases them 1 s apart. Base = current `main` (`faf88178b453`, includes openclaw#199122); fix = this PR rebased on it. | Arm | Wake turns (6 trials) | Results acknowledged | Wake-turn tokens (total) | Wake-turn cost | | --- | --- | --- | --- | --- | | base, 3 exits | 18 (3 per trial) | 18/18 | 501,233 | $1.152 | | fix, 3 exits | 12 (2 per trial) | 18/18 | 326,362 (-35%) | $0.930 | | base, 1 exit | 6 | 6/6 | 153,377 | $0.402 | | fix, 1 exit | 6 | 6/6 | 153,934 | $0.403 | Single-exit wake latency (release to wake message, median of 6): base 0.85 s, fix 0.85 s. A single completion never waits for the settle. Time from release to the last reply in the 3-exit arm: base median 9.2 s, fix median 7.3 s. Every fix trial: the first exit starts its turn at once; the two later exits arrive during it and share the next turn, each keeping its own id, exit code, duration and tail. Results from earlier runs before the rebase (same arms, older wake format) matched: 12 turns vs 18. <details><summary>Redacted trace, trial 1 (times relative to release of the first waiter)</summary> Base (before the rebase, old wake format): ``` +8.8s USER: Exec completed (gentle-c, code 0) :: job 1 result: r11-1603127358 +11.7s reply (26930 tok): job 1 result: r11-1603127358 +19.1s USER: Exec completed (dawn-gla, code 0) :: job 2 result: r12-78193628 +22.0s reply (27407 tok): job 2 result: r12-78193628 +26.5s USER: Exec completed (kind-sum, code 0) :: job 3 result: r13-1811516849 +29.2s reply (27885 tok): job 3 result: r13-1811516849 ``` Fix (rebased head): ``` +1.2s USER: Exec completed (tide-cov, code 0, 34s): job 1 result: r11-1383216 +3.7s reply (26761 tok): job 1 result: r11-1383216 +5.1s USER: Exec completed (tidy-com, code 0, 32s): job 2 result: r12-262323306 Exec completed (rapid-bi, code 0, 29s): job 3 result: r13-179203848 +7.7s reply (27281 tok): job 2 result: r12-262323306 / job 3 result: r13-179203848 ``` </details> **Regression tests:** `bash-tools.exec-background-followup.test.ts` runs three real background commands through the exec tool and the real session event owner with a held first model turn. Same launching run: base starts three completion turns (red); the fix starts two, the second carrying both later results and naming their run. Different launching runs with shared request owners: the later results keep separate turns, each naming its own run (red without the launch-run check). Five results of ~2,000 chars: the shared turn takes three and the fifth starts its own turn (size bound). **Focused suites (`ocx test`, rebased head, 14 files):** `bash-tools.exec-background-followup`, `bash-tools.test`, `bash-tools.exec-runtime`, `bash-tools.exec-runtime.cleanup`, `bash-tools.visible-subagent-notify`, `bash-tools.exec-request-stop`, `bash-tools.exec.egress-lifecycle`, `bash-tools.notify-on-exit-ack`, `bash-tools.process.e2e`, `bash-tools.exec-notify.requester`, `bash-tools.exec-notify.queue-full`, `infra/exec-session-event`, `session-event-handoff`, `agent-runner-execution-session-events`: all pass. `exec-session-event`'s chained-completion case now waits for the second receipt, which starts after the 1 s settle. **Full tier:** `ocx build --dts` (full profile) built `92847fc`; the self-contained source package passed its tarball integrity check, installed with npm into a scratch prefix, and the packed CLI reported `OpenClaw 2026.11.3 (92847fc)` with `gateway --help` exit 0. The later head commit only changes a test type. **Gaps:** E2E covers exits from one request in an idle Control UI-style session; completions from different requests and channel-delivered sessions are covered by the shared owner's existing tests, not by a new live run. Co-authored-by: Ayaan Zaidi <[email protected]>
…#200097) ## What Problem This Solves Background commands, `sessions_yield` waits and exec-exit wakes were owned by the run that started them. A run id names one attempt, and a chat gets a new one on every turn. So every follow-up run lost the commands of the earlier runs: - A later turn could not yield on a command that an earlier turn started. `listYieldAwaitableExecs(runId)` matched `originRunId === runId`, so `sessions_yield` returned `nothing_pending` and the model started to poll. - A paused subagent task continued only when the wake named the paused run. #200046 patched one caller of this: it moved the running commands to the new run (`moveRunningSessionsToRun`). - Child completions compared the captured requester session id and lifecycle revision. After a reset or a compaction successor, a private completion was withheld with "Subagent results from the previous session were not delivered". ## Why This Change Was Made The bug class is "address work by an id that changes". The chat's session key is the only id that survives edits, resets, compaction and follow-up runs. This PR makes the key the owner: - `listYieldAwaitableExecs`, `awaitExecsForYield` and `openExecYieldResume` are keyed by the chat: agent id plus session key, so a raw shared key such as `global` stays separate per agent. A yield awaits every wake-armed command of the chat, including commands from earlier runs. - Reply admission continues the task that is paused in the chat, whichever run paused it (`continuesPausedTask` replaces `pausedRunId`). - Child and harness completions, and the failure notice of a required completion, go to the requester chat as it is now. The reads of `completionRequesterSessionId` / `LifecycleRevision`, the settle-receipt exact compare, the collector and `agents_wait` incarnation filters, and the reset replacement notice are deleted. - Deleted: `ProcessSession.originRunId`, `moveRunningSessionsToRun` (the #200046 patch), `matchesSubagentRequesterSession`, `recordRequesterReplacementNotice`, `listCollectorRunsForRequesterIncarnation` (now `listCollectorRunsForRequester`). - Kept as a fact only: an exec wake still names the starting run in `inputProvenance.runId` (`ProcessSession.startedByRunId`), because plugins use it (#179816). It routes nothing. - The requester id fields are still written for one release, so a downgrade keeps working. No schema, stored-row or protocol change. Production delta: −227 lines in `src` (+127 / −354); whole PR −427. ## User Impact - A chat can start a background command in one turn and wait for it with `sessions_yield` in a later turn. The exit continues the chat. - A yielded subagent always continues its paused task when one of its commands exits, also after a follow-up run. - A subagent result reaches the parent chat after `/new` or compaction instead of being withheld. ## Evidence Real agent on an isolated source Gateway (`ocx src`, scratch state, port and HOME, scrubbed env), Claude Opus through the shared Claude proxy. base = merge base `96ad377596ca`, head = this PR. | Journey | base | head | |---|---|---| | J1: #200046 incident (paused child, A's exit continues the task in run 2, then B, started by run 1, exits) | parent got `child-final` (with the #200046 patch) | parent got `child-final` (patch deleted); registry `generation=4 delivery=delivered` | | J2: run 1 starts a background command; run 2 calls `sessions_yield` | `{"status":"nothing_pending"}` | `{"status":"yielded"}`; the exit wakes the chat, which replies `j2-woke` | | J3: parent spawns a child and does not yield | ordinary completion (`subagent_announce`) | ordinary completion (`subagent_announce`) | | J1 parent side: parent yields on its child | private completion (`subagent_settle`) | private completion (`subagent_settle`) | Head arms ran on the production code of `3793f6d`; later commits change only tests, docs and the failure-notice path of a required completion, which unit tests cover. A `/new` while the parent is yielded on a running child interrupts the child on both arms, so that journey does not separate them and is not a claim of this PR. Unit: `openclaw-tools.requester-yield.test.ts` now awaits a command with no starting run (fails on base). The delivery tests assert that a private completion reaches a replacement parent session. Gates: oxfmt, oxlint on changed files, `pnpm tsgo:core`, `pnpm check:test-types`, `ocx test` on `src/agents/subagents/`, requester-yield, exec background and notify suites, agents_wait, harness completion, session reactivation and adoption, `src/cron/isolated-agent`. Build, full suites and cross-OS checks: hosted CI on this head. `src/gateway/server-startup-post-attach.test.ts` fails the same way on the merge base `059db8a`; this PR does not touch it. Co-authored-by: Ayaan Zaidi <[email protected]>
…openclaw#200097) ## What Problem This Solves Background commands, `sessions_yield` waits and exec-exit wakes were owned by the run that started them. A run id names one attempt, and a chat gets a new one on every turn. So every follow-up run lost the commands of the earlier runs: - A later turn could not yield on a command that an earlier turn started. `listYieldAwaitableExecs(runId)` matched `originRunId === runId`, so `sessions_yield` returned `nothing_pending` and the model started to poll. - A paused subagent task continued only when the wake named the paused run. openclaw#200046 patched one caller of this: it moved the running commands to the new run (`moveRunningSessionsToRun`). - Child completions compared the captured requester session id and lifecycle revision. After a reset or a compaction successor, a private completion was withheld with "Subagent results from the previous session were not delivered". ## Why This Change Was Made The bug class is "address work by an id that changes". The chat's session key is the only id that survives edits, resets, compaction and follow-up runs. This PR makes the key the owner: - `listYieldAwaitableExecs`, `awaitExecsForYield` and `openExecYieldResume` are keyed by the chat: agent id plus session key, so a raw shared key such as `global` stays separate per agent. A yield awaits every wake-armed command of the chat, including commands from earlier runs. - Reply admission continues the task that is paused in the chat, whichever run paused it (`continuesPausedTask` replaces `pausedRunId`). - Child and harness completions, and the failure notice of a required completion, go to the requester chat as it is now. The reads of `completionRequesterSessionId` / `LifecycleRevision`, the settle-receipt exact compare, the collector and `agents_wait` incarnation filters, and the reset replacement notice are deleted. - Deleted: `ProcessSession.originRunId`, `moveRunningSessionsToRun` (the openclaw#200046 patch), `matchesSubagentRequesterSession`, `recordRequesterReplacementNotice`, `listCollectorRunsForRequesterIncarnation` (now `listCollectorRunsForRequester`). - Kept as a fact only: an exec wake still names the starting run in `inputProvenance.runId` (`ProcessSession.startedByRunId`), because plugins use it (openclaw#179816). It routes nothing. - The requester id fields are still written for one release, so a downgrade keeps working. No schema, stored-row or protocol change. Production delta: −227 lines in `src` (+127 / −354); whole PR −427. ## User Impact - A chat can start a background command in one turn and wait for it with `sessions_yield` in a later turn. The exit continues the chat. - A yielded subagent always continues its paused task when one of its commands exits, also after a follow-up run. - A subagent result reaches the parent chat after `/new` or compaction instead of being withheld. ## Evidence Real agent on an isolated source Gateway (`ocx src`, scratch state, port and HOME, scrubbed env), Claude Opus through the shared Claude proxy. base = merge base `2baaa3c275a3`, head = this PR. | Journey | base | head | |---|---|---| | J1: openclaw#200046 incident (paused child, A's exit continues the task in run 2, then B, started by run 1, exits) | parent got `child-final` (with the openclaw#200046 patch) | parent got `child-final` (patch deleted); registry `generation=4 delivery=delivered` | | J2: run 1 starts a background command; run 2 calls `sessions_yield` | `{"status":"nothing_pending"}` | `{"status":"yielded"}`; the exit wakes the chat, which replies `j2-woke` | | J3: parent spawns a child and does not yield | ordinary completion (`subagent_announce`) | ordinary completion (`subagent_announce`) | | J1 parent side: parent yields on its child | private completion (`subagent_settle`) | private completion (`subagent_settle`) | Head arms ran on the production code of `3793f6d`; later commits change only tests, docs and the failure-notice path of a required completion, which unit tests cover. A `/new` while the parent is yielded on a running child interrupts the child on both arms, so that journey does not separate them and is not a claim of this PR. Unit: `openclaw-tools.requester-yield.test.ts` now awaits a command with no starting run (fails on base). The delivery tests assert that a private completion reaches a replacement parent session. Gates: oxfmt, oxlint on changed files, `pnpm tsgo:core`, `pnpm check:test-types`, `ocx test` on `src/agents/subagents/`, requester-yield, exec background and notify suites, agents_wait, harness completion, session reactivation and adoption, `src/cron/isolated-agent`. Build, full suites and cross-OS checks: hosted CI on this head. `src/gateway/server-startup-post-attach.test.ts` fails the same way on the merge base `113d415`; this PR does not touch it. Co-authored-by: Ayaan Zaidi <[email protected]>
Summary
High Level TLDR
When an agent starts a background
execand ends its turn, OpenClaw wakes the conversation again when the command finishes. That wake is correctly not an owner turn, but it also carried no link to the run that started the command: plugins only saw{ kind: "internal_system", sourceTool: "exec" }, and plugin tool factories got neither the run id nor the turn's input provenance. A plugin that gates its own tool (for example an owner-only SSH broker) therefore could not tell "the completion of a command my owner started a minute ago in this session" from any other internal turn, and had to refuse it.This change names the starting run on the completion wake (
InputProvenance.runId) and exposesrunIdandinputProvenanceon the plugin tool context, on both the embedded runtime and the claude-cli MCP loopback. It only adds facts: wakes stay non-owner turns, and no plugin gains authority it did not already have. The Gatewayagentmethod now accepts exec completion provenance only from backend callers, so a client cannot forge it.What Problem This Solves
Fixes: a plugin tool cannot recognize the completion wake of a background command that its owner started, so owner-gated plugin tools refuse follow-up work on that wake.
User Impact
Plugin authors can correlate a completion wake with the run that started the command (
toolContext.inputProvenance.runIdagainst thetoolContext.runIdseen on that earlier turn) and decide their own policy. Nothing changes for users without such a plugin. Wakes still run withsenderIsOwnernottrue.Root Cause
src/auto-reply/reply/session-event-context.tsasInputProvenance: { kind: "internal_system", sourceTool: options.source }. The exec process identity travels only as a privateexec:<instance id>source-turn id (source-turn-id.ts), and nothing records which run'sexeccall started the process (ProcessSessionhas no run field).OpenClawPluginToolContext(src/plugins/tool-types.ts), which hassessionKey,sessionId, andsenderIsOwner, but norunIdorinputProvenance, even though agent hooks already receiveinputProvenance(PluginHookAgentContext).mcp-http.ts,runInDetachedAsyncContext). The run-bound grant (buildCliMcpGrantContext) copiedinputProvenanceonly for verified subagent handoffs, so even an internal wake's provenance never reached loopback tools.main.Why This Change Was Made
ProcessSession.originRunId, from the exec tool's run) and the completion wake stamps it asInputProvenance.runId, using the existing field, so the persisted transcript provenance shape and the Gateway protocol schema are unchanged.resolveOpenClawPluginToolInputsforwardsrunIdandinputProvenance(embedded path).resolveGatewayScopedToolsforwards the grant'sinputProvenanceto plugin tools (loopback path), and the CLI grant now carriesinternal_systemprovenance. Loopback requester policy reads provenance only forexternal_userand verified handoffs (requester-tool-policy.ts), so this does not change any tool surface. External-user and inter-session provenance stay off the grant as before.prepareAgentRequestPreflightrejects client-suppliedinternal_system/execprovenance unless the caller is a backend client, mirroring the existing progress-refresh reservation directly above it.Behavior matrix
inputProvenance{ internal_system, exec, runId: R }runId= wake run,inputProvenance.runId= R{ internal_system, exec }(unchanged)inputProvenancewithoutrunId{ internal_system, exec }(persisted fact has no run)runId, plugins fail closedagentRPC withinternal_system/execprovenance, non-backend clientexternal_userorinter_sessionprovenance, no handoffsenderIsOwnernottrue(unchanged)Session-event turns are admitted exclusively (
turnAdoptionLifecycle.admission: "exclusive"), one exec occurrence per turn, so the stamped run is the run of that turn's command.Real behavior proof
Both runtimes were proved through a real isolated Gateway process (
createOpenClawTestInstance, builtdist), with a local plugin that registers a version 2 tool factorywake_probeand records the factory context. A scripted model (embedded: mock OpenAI Responses provider; claude-cli: a fakeclaudebinary onPATHthat speaks the stream-json protocol and calls the real MCP loopback from the generated--mcp-config) does: owner turn viachat.sendcallsexec {"command":"sleep 2; echo WAKE_EXEC_DONE","background":true}and ends; the real completion wake callswake_probe. The harness files are scratch and not part of this PR.After (this branch), embedded runtime, plugin trace:
After, claude-cli runtime (tool call arrived over the MCP loopback,
toolCallIdmcp-...):Before (same harness on base
e8977af441a): the wake's tool context has norunIdand noinputProvenance, on both runtimes:In both runtimes the wake's own run id differs from the owner run, the session key and id match, and
senderIsOwnerisfalse.Performance
Microbenchmark of the three touched per-turn paths, base vs head, same host and Node 24.19.0, 20k warmup, 9 samples x 50k iterations, two runs per side (median ns/op):
The wake context gains one conditional property spread (about 15 to 30 ns once per wake); the other two paths are within noise. No per-token or per-tool-call work was added.
What was not tested
claudethat drives the real CLI runner, grant, and MCP loopback.chat.sendon an internal session; the wake path and plugin context are channel-independent.runIdadded (listed in the matrix).runId; not exercised end to end here.Verification
src/agents/bash-tools.exec-background-followup.test.ts: real background exec, real session-event handoff and dispatch; the completion turn'sinputProvenanceis exactly{ kind, sourceTool, runId }with a starting run, and has norunIdwithout one; wake stays non-owner.src/agents/openclaw-tools.plugin-context.test.ts: embedded plugin tool inputs forwardrunIdandinputProvenance.src/agents/cli-runner/mcp-grant-context.test.ts: grant carriesinternal_systemprovenance, still omitsexternal_userandinter_sessionwithout a handoff.src/gateway/tool-resolution.memory-audience.test.ts: loopback plugin tools receive the run id and the grant's provenance.src/gateway/agent-turn/agent-request-preflight.test.ts: non-backend exec provenance rejected, backend admitted.agent-tools.prefix-stability.pnpm check:changed: format, lint, typecheck core and core tests, line-cap ratchet, and all guards pass. Three checks fail identically on basee8977af441aand are not caused by this PR: max-lines suppression ratchet (ui/src/pages/config/config-page-state.ts,ui/src/pages/sessions/sessions-page-state.ts), core test shard root budget (agents-root 722, gateway-root 730, infra 749 on both), and the production unused-export scan (19 unrelated exports; none in touched files).pnpm plugin-sdk:api:diff --base e8977af441a --head HEAD: additive optional fields only (runId,inputProvenanceon the tool context;sourceRunIdon session event options;originRunIdonProcessSession).$autoreview(branch mode, P1, Claude engine): scoped-clean. Its open questions were checked in source: requester policy reads onlyexternal_userprovenance and verified handoffs; no non-backend caller sends exec provenance; session-event turns are admitted exclusively, so one wake carries one command's run.