Repository navigation
fix: prevent queued agent failures after the sending turn ends - #177296
Conversation
Clear the ambient Gateway caller identity at the existing in-process agent handoff after current caller and operator validation. Keep captured source guards and non-agent caller scopes intact. Related: openclaw#158070
|
🦞👀 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 clears the sending tool’s ambient Gateway caller identity when launching an independent agent turn. Example: Session A sends to busy session B with timeoutSeconds: 0, then finishes before B performs required compaction.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review Keep this PR open: it repairs a demonstrated sender-lifetime leak at the shared agent-dispatch boundary, with no introduced defect identified. Priority: P1 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherIn-process Gateway dispatch receives agent launches from session tools and plugins, validates the initiating authority, and hands execution to the recipient’s turn owner. flowchart LR
A[Sending session tool] --> B[Gateway dispatch]
B --> C[Capture and validate authority]
C --> D[Clear ambient caller identity]
D --> E[Recipient admission and queue]
E --> F[Compaction and recipient execution]
Technical reviewBest possible solution: Keep the focused detach at the existing shared agent handoff while preserving admission checks and the recipient’s own execution authority. Do we have a high-confidence way to reproduce the issue? Yes: obviyus published failing main Gateway traces and a waited-send control, and source inspection confirms the same handoff on fetched main; this review executed no target code. Is this the best way to solve the issue? The patch fixes the producer of the leaked context using an existing operation at the shared dispatch owner, without adding parallel policy, state, or consumer-specific workarounds. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 802e3f74d2c0. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +5, Tests +96. Total +101 across 2 files. Added test files: 1. View PR surface stats
Preflight sourceSource unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified. 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 HistoryReview history (4 earlier review cycles)
Reviewed November 17, 2026, 12:22 PM ET / 17:22 UTC (Revision 5). |
|
In response to the proof request in #177296 (comment), here is inspectable output from the already completed isolated 2026.10.5 run. No source change or test rerun is being claimed. PR head remains Provenance and boundary. The full-flow source was official The exact dispatched production file on the PR head has SHA-256 Recorded terminal output (ANSI formatting removed; private paths omitted): The fourth case ( Before: 120000/128000 recorded input tokens; 118555 transcript bytes, below the 4 MiB byte threshold. Projection of the saved {
"actualSendResult": {
"status": "accepted",
"targetDisposition": "queued",
"delivery": {
"status": "pending"
}
},
"custodyAfterRequesterFinal": {
"requesterFinalJoined": true,
"requesterRegistrationPresent": false,
"entryCurrent": true,
"sessionAdmissionActive": true,
"abortSignalAborted": false,
"kernelResolverCurrent": true
},
"pluginConstruction": {
"afterRequesterFinal": true,
"callerIsRequester": true,
"signals": [
true
],
"error": "This turn has ended; ask again in a new turn."
},
"peerTerminal": {
"status": "error",
"summary": "Preflight compaction required but failed: This turn has ended; ask again in a new turn."
},
"cleanup": {
"execution": [
"fulfilled",
"fulfilled",
"fulfilled"
],
"detached": [
"fulfilled"
],
"root": [
"fulfilled"
],
"activeRunIds": []
}
}The first failing guard in this full flow is the sender's personal-selection lifetime ( After: The following are projections of the saved JSON, not new runs. normal{
"case": "normal",
"actualSendResult": {
"status": "accepted",
"targetDisposition": "queued",
"delivery": {
"status": "pending"
}
},
"custodyAfterRequesterFinal": {
"requesterFinalJoined": true,
"requesterRegistrationPresent": false,
"entryCurrent": true,
"sessionAdmissionActive": true,
"abortSignalAborted": false,
"kernelResolverCurrent": true
},
"after": {
"summaryCalls": 1,
"foregroundCalls": 1,
"childTerminal": {
"status": "ok",
"summary": "completed"
},
"returnTerminal": {
"status": "ok",
"summary": "completed"
},
"returnRunAdmitted": true,
"pendingTotal": 0,
"pendingStates": [],
"requesterPendingTotal": 0
},
"persistedReadback": {
"eventsBefore": 17,
"eventsAfter": 23,
"serializedBytesBefore": 118555,
"serializedBytesAfter": 121502,
"entryIdsExcludingSessionHeaderUnchanged": false,
"compactionEntries": 1,
"childInputRecords": 1
},
"cleanup": {
"execution": [
"fulfilled",
"fulfilled",
"fulfilled"
],
"detached": [
"fulfilled"
],
"root": [
"fulfilled"
],
"activeRunIds": []
},
"observationFailures": []
}role-revocation{
"case": "role-revocation",
"actualSendResult": {
"status": "accepted",
"targetDisposition": "queued",
"delivery": {
"status": "pending"
}
},
"custodyAfterRequesterFinal": {
"requesterFinalJoined": true,
"requesterRegistrationPresent": false,
"entryCurrent": true,
"sessionAdmissionActive": true,
"abortSignalAborted": true,
"kernelResolverCurrent": true
},
"after": {
"summaryCalls": 0,
"foregroundCalls": 0,
"childTerminal": {
"status": "timeout",
"summary": "Input <synthetic-input-id> was withdrawn before its turn started and was not delivered. Resend it when ready.",
"providerStarted": false,
"reason": "input_withdrawn_before_turn"
},
"returnTerminal": {},
"returnRunAdmitted": false,
"pendingTotal": 1,
"pendingStates": [
"cancelled"
],
"requesterPendingTotal": 0
},
"persistedReadback": {
"eventsBefore": 17,
"eventsAfter": 17,
"serializedBytesBefore": 118555,
"serializedBytesAfter": 118555,
"entryIdsExcludingSessionHeaderUnchanged": true,
"compactionEntries": 0,
"childInputRecords": 0
},
"cleanup": {
"execution": [
"fulfilled",
"fulfilled"
],
"detached": [
"fulfilled"
],
"root": [
"fulfilled"
],
"activeRunIds": []
},
"observationFailures": [],
"revocation": {
"originalRole": null,
"originalAuthorityRole": null,
"readbackRole": "reader",
"realGuardError": {
"name": "Error",
"message": "Your operator role changed; reconnect before continuing."
},
"sameErrorAsAuthoritySignal": true
}
}kernel-retirement{
"case": "kernel-retirement",
"actualSendResult": {
"status": "accepted",
"targetDisposition": "queued",
"delivery": {
"status": "pending"
}
},
"custodyAfterRequesterFinal": {
"requesterFinalJoined": true,
"requesterRegistrationPresent": false,
"entryCurrent": true,
"sessionAdmissionActive": true,
"abortSignalAborted": false,
"kernelResolverCurrent": false
},
"after": {
"summaryCalls": 0,
"foregroundCalls": 0,
"childTerminal": {
"status": "error",
"summary": "Gateway instance dispatch unavailable for agent turn"
},
"returnTerminal": {},
"returnRunAdmitted": false,
"pendingTotal": 1,
"pendingStates": [
"interrupted"
],
"requesterPendingTotal": 0
},
"persistedReadback": {
"eventsBefore": 17,
"eventsAfter": 17,
"serializedBytesBefore": 118555,
"serializedBytesAfter": 118555,
"entryIdsExcludingSessionHeaderUnchanged": true,
"compactionEntries": 0,
"childInputRecords": 0
},
"cleanup": {
"execution": [
"fulfilled",
"fulfilled"
],
"detached": [
"fulfilled"
],
"root": [
"fulfilled"
],
"activeRunIds": []
},
"observationFailures": []
}Authority intervention and observed effects. The role case captures The Gateway case calls the real In both negative cases, the observed recipient model calls are zero, there is no compaction, no child input in the transcript, no new transcript entries, and no original return run. The accepted pending-input bookkeeping still exists ( Limits and remaining review responsibility. The revoked profile is the authenticated requester in this fixture, initially carrying synthetic Recorded command and evidence digestsRun in the isolated source checkout with a cleared environment and private HOME/temp/cache roots: node scripts/run-vitest.mjs run --config test/vitest/vitest.gateway-server.config.ts --configLoader native src/gateway/server.peer-plugin-token-preflight-authority.test.ts -t ' normal$'
node scripts/run-vitest.mjs run --config test/vitest/vitest.gateway-server.config.ts --configLoader native src/gateway/server.peer-plugin-token-preflight-authority.test.ts -t ' (normal|role-revocation|kernel-retirement)$'Retained input/output SHA-256 (provenance identifiers, not substitutes for the inspectable excerpts above): The 97 previously retained evidence files passed their saved digest check before this extraction. Generated logs are kept outside the source change. |
|
@clawsweeper re-review Added inspectable redacted terminal/checkpoint output, native authority interventions and persisted transcript readbacks in #177296 (comment), and linked the proof and its limits from the PR body. Head is unchanged ( |
|
🦞👀 Re-review progress:
|
|
Follow-up diagnosis of the preserved run; no model rerun or PR-source change. The harness terminated on a persisted assistant text marker rather than waiting for the original-return turn owner's terminal result. The native return owner in agent-step.ts separately calls This is a harness waiting/cleanup deficiency, not evidence that PR177296's recipient compaction failed: the recipient has real-model token compaction, successful native terminal wait and durable input-completion success. Requester return ownership also relates to #173026; this separate PR177296-head run does not establish a defect in #173026. Only the scratch harness is repaired: it now correlates the return assistant event with the original source session and a distinct return run, waits for that exact run's successful native terminal receipt, and verifies receipt run/session/text before cleanup. The marker-only behavior was reproduced offline and rejected; four focused waiting regressions pass, along with syntax/schema/preparation/sequence validation. Future reports distinguish flow If stronger terminal-return/clean-teardown evidence is required, its exact missing criterion is the matching original-return terminal receipt plus graceful child exit and absence of replyflow failure; another marker-only run would not help. No new run has been started or requested here. This limitation is not automatically a new merge blocker: maintainers and the requested re-review must assess the recipient-boundary evidence already supplied, separately from broader return/teardown coverage. Human authority-boundary acceptance remains their decision. |
Exact-head synthetic Gateway return settlement — 7 NovemberA new isolated, credential-free Gateway probe reused the existing built head cacfa20 and its pinned build inputs. It completed with exit 0, overallPassed:true, Gateway child exit 0/no signal, no forced kill, and no sessions_send reply-flow failure warning. No product source or built file on disk was changed. The original waiting/cleanup assertions were retained: exactly one sessions_send; accepted queued peer held at the native after-ACK gate; sender completed successfully before peer release; one native token compaction after release (not byte compaction); successful peer terminal wait; then original-return agent.wait status ok with matching runId, original source sessionId, terminal receipt, and exact visible PR177296_RETURN_OK. The observed original-return run was36516e7b-5e93-4927-802e-a14a2d701ff0. The result was read back from the completed report, not inferred from a persisted text marker. Scope: all six model requests went to an explicitly configured loopback synthetic OpenAI-compatible endpoint through the existing OpenRouter adapter. Responses and seed token usage were authored test data; the configured model label is NOT a real-model claim. No real credential was read/copied, no paid provider was used, and no external channel delivery was attempted. The two previously disclosed in-memory timing/preflight observation transforms were retained; the changed dispatch module remained untransformed in this head lane. This adds exact-head native return-settlement and graceful-teardown evidence under synthetic transport. It does not repair or rewrite the historical real-model run, qualify real-model return settlement, prove negative authority controls, or grant human authority-boundary/merge acceptance. The first synthetic setup attempt stopped before the peer acceptance gate because its scripted responder selected the trailing runtime-context user message instead of the marked test request. It had clean teardown but was not counted as product failure or acceptance. Only the scratch responder selection was corrected; assertions, timeouts, guards, package and source were unchanged. The corrected probe finished in27.7s. Original live-driver scripts, historical reports, credential WIP and worktree source were preserved. Private evidence: tmp/pr177296-runtime/openrouter-smoke/head-1794069332250/report.json, observations.jsonl and process-output.log; scratch driver .openclaw/tmp/pr177296-secretless-flow-40548.mjs and synthetic responder pr177296-secretless-server-40548.mjs. No new source commit or CI retry accompanies this evidence. |
|
Gateway reproduction on main and this head (source tier, |
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Thanks @johan-eilertsen for the fix and @Angelojiang11 for the report. This is merged in 5e6bbed: a turn that one agent starts in another session (for example with |
…law#177296) Root cause: src/gateway/server-plugin-in-process-dispatch.ts:187 hands an accepted in-process `agent` turn off outside the caller's operator authority and transcript writer, but leaves the sending tool's Gateway caller identity in place. The recipient's required preflight compaction later captures that identity while building its tools, and fails with `agent tool caller authority is no longer active` once the sending turn has ended. Fixes openclaw#158070 ## What Problem This Solves When one agent sends a message to another session with `sessions_send` and does not wait for the reply, the message can be lost. If the receiving session is busy or close to its context limit, it has to compact before it can run the queued message, and by then the sender's turn is usually over. The compaction then fails with `Preflight compaction required but failed: agent tool caller authority is no longer active`, and the message has to be resent by hand. ## User Impact Fire-and-forget messages between sessions are delivered even when the receiving session needs to compact first. ## Why This Change Was Made The handoff that starts the receiving turn already drops the sender's operator authority and transcript writer, so the new turn runs under its own admitted authority. It still carried the sender's tool caller identity, and compaction picked that up. The handoff now drops that identity too. Admission still checks the sender: a sender whose authority is gone is refused before the turn is accepted. ## Evidence Real Gateway with real agents and a deterministic local OpenAI Responses fixture. Session B is busy on a slow turn that reports near-window usage; session A sends to B with `timeoutSeconds: 0` and finishes; B's queued turn needs token preflight compaction. - main `b51df39ce0c9`, two runs: `preflight compaction failed: agent tool caller authority is no longer active`; the queued message never reaches the model. - Control on main with `timeoutSeconds: 120` (the sender's turn stays alive): the same compaction succeeds and the message reaches the model, so the failure follows the sender's lifetime. - This branch, from source and from the full Node build: compaction succeeds and the queued message reaches the model, no authority error. - `server-plugin-in-process-dispatch.caller-lifetime.test.ts` fails on main for both the host-close and admission-close cases and passes here. - The same error appears in production logs on a 2026.11.4 Gateway (19 lines in the last 14 days). Observed lines: openclaw#177296 (comment). The author's earlier allowed and revoked authority runs are in the comments above. Fix and regression test by @johan-eilertsen. Reported by @Angelojiang11, with further traces from @LachieFREEDOM, @nosugarx, @SamuelThornburg, @roboclaw-bot and @jaxonparrott. Merge danger: two-way door. A revert restores the old behavior; no state, config or contract changes. Blast radius: in-process `agent` launches (`sessions_send`, plugin agent launches). Co-authored-by: Ayaan Zaidi <[email protected]>
Root cause: src/gateway/server-plugin-in-process-dispatch.ts:187 hands an accepted in-process `agent` turn off outside the caller's operator authority and transcript writer, but leaves the sending tool's Gateway caller identity in place. The recipient's required preflight compaction later captures that identity while building its tools, and fails with `agent tool caller authority is no longer active` once the sending turn has ended. Fixes #158070 ## What Problem This Solves When one agent sends a message to another session with `sessions_send` and does not wait for the reply, the message can be lost. If the receiving session is busy or close to its context limit, it has to compact before it can run the queued message, and by then the sender's turn is usually over. The compaction then fails with `Preflight compaction required but failed: agent tool caller authority is no longer active`, and the message has to be resent by hand. ## User Impact Fire-and-forget messages between sessions are delivered even when the receiving session needs to compact first. ## Why This Change Was Made The handoff that starts the receiving turn already drops the sender's operator authority and transcript writer, so the new turn runs under its own admitted authority. It still carried the sender's tool caller identity, and compaction picked that up. The handoff now drops that identity too. Admission still checks the sender: a sender whose authority is gone is refused before the turn is accepted. ## Evidence Real Gateway with real agents and a deterministic local OpenAI Responses fixture. Session B is busy on a slow turn that reports near-window usage; session A sends to B with `timeoutSeconds: 0` and finishes; B's queued turn needs token preflight compaction. - main `9122a49bd8a1`, two runs: `preflight compaction failed: agent tool caller authority is no longer active`; the queued message never reaches the model. - Control on main with `timeoutSeconds: 120` (the sender's turn stays alive): the same compaction succeeds and the message reaches the model, so the failure follows the sender's lifetime. - This branch, from source and from the full Node build: compaction succeeds and the queued message reaches the model, no authority error. - `server-plugin-in-process-dispatch.caller-lifetime.test.ts` fails on main for both the host-close and admission-close cases and passes here. - The same error appears in production logs on a 2026.11.4 Gateway (19 lines in the last 14 days). Observed lines: #177296 (comment). The author's earlier allowed and revoked authority runs are in the comments above. Fix and regression test by @johan-eilertsen. Reported by @Angelojiang11, with further traces from @LachieFREEDOM, @nosugarx, @SamuelThornburg, @roboclaw-bot and @jaxonparrott. Merge danger: two-way door. A revert restores the old behavior; no state, config or contract changes. Blast radius: in-process `agent` launches (`sessions_send`, plugin agent launches). Co-authored-by: Ayaan Zaidi <[email protected]> (cherry picked from commit 5e6bbed) Co-authored-by: RomneyDa <[email protected]> (cherry picked from commit 9c8e8a1c92a4f2a34ddb56a5c488cae8aa2980f4)
Root cause: src/gateway/server-plugin-in-process-dispatch.ts:187 hands an accepted in-process
agentturn off outside the caller's operator authority and transcript writer, but leaves the sending tool's Gateway caller identity in place. The recipient's required preflight compaction later captures that identity while building its tools, and fails withagent tool caller authority is no longer activeonce the sending turn has ended.Fixes #158070
What Problem This Solves
When one agent sends a message to another session with
sessions_sendand does not wait for the reply, the message can be lost. If the receiving session is busy or close to its context limit, it has to compact before it can run the queued message, and by then the sender's turn is usually over. The compaction then fails withPreflight compaction required but failed: agent tool caller authority is no longer active, and the message has to be resent by hand.User Impact
Fire-and-forget messages between sessions are delivered even when the receiving session needs to compact first.
Why This Change Was Made
The handoff that starts the receiving turn already drops the sender's operator authority and transcript writer, so the new turn runs under its own admitted authority. It still carried the sender's tool caller identity, and compaction picked that up. The handoff now drops that identity too. Admission still checks the sender: a sender whose authority is gone is refused before the turn is accepted.
Evidence
Real Gateway with real agents and a deterministic local OpenAI Responses fixture. Session B is busy on a slow turn that reports near-window usage; session A sends to B with
timeoutSeconds: 0and finishes; B's queued turn needs token preflight compaction.9122a49bd8a1, two runs:preflight compaction failed: agent tool caller authority is no longer active; the queued message never reaches the model.timeoutSeconds: 120(the sender's turn stays alive): the same compaction succeeds and the message reaches the model, so the failure follows the sender's lifetime.server-plugin-in-process-dispatch.caller-lifetime.test.tsfails on main for both the host-close and admission-close cases and passes here.Observed lines: #177296 (comment). The author's earlier allowed and revoked authority runs are in the comments above.
Fix and regression test by @johan-eilertsen. Reported by @Angelojiang11, with further traces from @LachieFREEDOM, @nosugarx, @SamuelThornburg, @roboclaw-bot and @jaxonparrott.
Merge danger: two-way door. A revert restores the old behavior; no state, config or contract changes. Blast radius: in-process
agentlaunches (sessions_send, plugin agent launches).