Skip to content

fix: prevent queued agent failures after the sending turn ends - #177296

Merged
obviyus merged 4 commits into
openclaw:mainfrom
johan-eilertsen:fix/accepted-agent-preflight-caller
Nov 17, 2026
Merged

obviyus merged 4 commits into
openclaw:mainfrom
johan-eilertsen:fix/accepted-agent-preflight-caller

Conversation

@johan-eilertsen

@johan-eilertsen johan-eilertsen commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

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).

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
@clawsweeper

clawsweeper Bot commented Oct 19, 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 gateway Gateway runtime size: S labels Oct 19, 2026
@johan-eilertsen
johan-eilertsen marked this pull request as ready for review October 19, 2026 11:53
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 19, 2026
@clawsweeper

clawsweeper Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This 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.

  • Before: B’s compaction fails with “agent tool caller authority is no longer active,” preventing the accepted message from running.
  • After: B compacts and processes the queued message under its own admitted execution.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A useful, focused repair with production-entry-point evidence and no actionable correctness finding; exact-head broad CI remains in progress.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (logs): Published Gateway traces exercise accepted queued sessions_send, sender completion, required token compaction, and successful recipient execution through source and built Node entry points. Earlier real-model evidence also reaches successful recipient settlement; its interrupted return cleanup does not invalidate this recipient-boundary result, and a later synthetic-endpoint run separately verifies return settlement and graceful teardown. Production dispatch is exercised with real transport clients; deterministic model responses are disclosed.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: A nonblocking inter-session message is accepted but never processed because required recipient compaction depends on the finished sender.
Reason: The narrowly scoped repair restores independent execution of accepted agent turns and addresses repeated production reports.

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
Reviewed head: dab2a3aaa62b1f72046a6af160b869b156052dbc

Before merge

None.

Findings

None.

Agent review details

How this fits together

In-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]
Loading

Technical review

Best 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

  • Independent launched-turn context keeps the original intent (6b2bfd1: Separate launched turns from the initiating session’s transcript writer and tool invocation lifetime.)
  • Selected-person authority keeps the original intent (d0dcc9d: Use the selected person’s permissions for session tools and child work while retaining authority independently of the originating turn.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 6b2bfd1 adds src/gateway/server-plugin-in-process-dispatch.ts:174 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 6b2bfd1d63bb; files: src/gateway/server-plugin-in-process-dispatch.ts)

PR surface

Source +5, Tests +96. Total +101 across 2 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 1 7 2 +5
Tests 1 96 0 +96
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 103 2 +101

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🧂 unranked krab: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove status: 📣 needs proof: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P1: Accepted inter-session messages can fail before execution when recipient compaction inherits an ended sender’s authority, breaking an actively reported agent workflow.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (4 earlier review cycles)
  • reviewed 2026-10-19T12:11:05.635Z sha cacfa20 :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-19T12:51:18.223Z sha cacfa20 :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-19T12:58:56.616Z sha cacfa20 :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-28T22:48:26.591Z sha cacfa20 :: needs maintainer review before merge. :: none

Reviewed November 17, 2026, 12:22 PM ET / 17:22 UTC (Revision 5).

@johan-eilertsen

Copy link
Copy Markdown
Contributor Author

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 cacfa20bc2d430bdbbc38c67f4d55153c5e3fb55.

Provenance and boundary. The full-flow source was official 1b58cb9a1b4f4353e1add63c8506db4d890962e8, with frozen matching dependencies, the original compiled Gateway test runner and a private HOME/temp/cache namespace. The green run adds only the equivalent production handoff fix. This starts the real Gateway server/kernel and enters its native in-process agent dispatch, then real sessions_send, admission, preflight/plugin construction, transcript persistence, settlement and original return handling. The agent/compaction mocks in the common Gateway fixture were explicitly removed. Observers call through to native owners; model discovery and external model transport are synthetic. This is source-level Gateway integration evidence, not an installed npm-package/CLI or live-provider claim, and not a full-flow run on the PR head.

The exact dispatched production file on the PR head has SHA-256 f26801d72662ccdd213754c7a02653c6aff8b026a2cbb6aaba48d8ed80a376c4, matching the executed main regression input. The release fix has patch SHA-256 d4c29f970a313efab1a84f501947d8f73e99377aa16fd36df9354fbcebb6c008 and resulting production-file SHA-256 e9c4a2658da4e1a1b1f34001c7e750857ba24fecb10102320ef80f5d21ddfd57; patch replay matched the executed compiler input. Main's focused 125 tests remain the separate head-specific proof.

Recorded terminal output (ANSI formatting removed; private paths omitted):

Before, unpatched 2026.10.5:
Test Files  1 failed (1)
Tests  1 failed | 3 skipped (4)
Duration  180.22s
outer runner: exitCode=1, seconds=189.3108565409202

After, same fixture + one-file fix:
Test Files  1 passed (1)
Tests  3 passed | 1 skipped (4)
Duration  463.09s
outer runner: exitCode=0, seconds=479.12825799989514

The fourth case (model-error-after-compaction-commit) was explicitly not selected. These are terminal completed runs; earlier failed/timeout harness attempts are not counted as passing evidence.

Before: 120000/128000 recorded input tokens; 118555 transcript bytes, below the 4 MiB byte threshold. Projection of the saved DRIFT138_CHECKPOINT JSON, with session/run IDs omitted. callerIsRequester compares the two recorded run IDs:

{
  "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 (This turn has ended), before the receipt/signal guard that emits agent tool caller authority is no longer active. The committed native regression independently reproduces that exact receipt/signal error. This does not uniquely reconstruct the first invalidator in the original incident.

After: The following are projections of the saved JSON, not new runs. persistedReadback counts the recorded native transcript events and compares entry IDs (excluding the session header); byte lengths use the same UTF-8 JSON serialization as the fixture. Each final event array also exactly matches the separately recorded durable read after native execution/return joins. returnRunAdmitted tests presence of the recorded original-return run ID. Synthetic input IDs are redacted.

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 executionParams.get(childRunId).prepared.operatorAuthority, commits the real users.setRole operation through a separate admin client, reads the profile role back as reader, and calls that same retained authority's assertCurrent(). The thrown error and authority signal reason are the same object. Its recorded throw stack starts at operator-run-authority.ts:434, through invalidateOperatorRolePolicy, server-methods/users.ts:370 and committed profile writes. The native recipient is then cancelled before model entry. The terminal projection is timeout / input_withdrawn_before_turn; it is not misreported as a successful completion or the original guard's error string.

The Gateway case calls the real kernel.gatewayInstanceRuntime.close(): availability changes true→false, the unchanged resolver stops returning the context, and the recipient throws Gateway instance dispatch unavailable for agent turn at server-instance-runtime.ts:89, through assertContextCurrent and agent-run-execution-phase.ts:421.

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 (cancelled / interrupted respectively); this is not a claim of zero writes anywhere. Normal completion records one compaction, one recipient input, one foreground model call and an independently completed original return, with both pending queues empty. Plugin construction during normal preflight has no sender caller; the later foreground construction has the recipient's own caller.

Limits and remaining review responsibility. The revoked profile is the authenticated requester in this fixture, initially carrying synthetic operator.admin scopes with no explicit stored role assignment. It is not a separate test of selecting a different person, nor of revocation during/after model I/O. There is no external channel delivery in this fixture (deliver: false); the demonstrated delivery is the original inter-session result return. The no-new-entry/count/byte checks do not claim a separately captured pre-run content hash. Please assess this evidence against the security gate with those limits intact; packaged CLI, different-selected-person and later-revocation proof must not be inferred from it. Human maintainer approval of the authority boundary is still required.

Recorded command and evidence digests

Run 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):

release-red.log.gz    fc8e44a4e3aa4568145f4003879de1a3262e8f6b26eaf95ff71a9cd5b746342b
release-green.log.gz  b5b9e61ea2adcfe36eae188b25462a9b93ab983786604ae547d740e601c54c1c
full-flow fixture    d0346f8c130f7769f23c0a12b2a41718184358f4e3ef37f81a91a110bdd61cb8

The 97 previously retained evidence files passed their saved digest check before this extraction. Generated logs are kept outside the source change.

@johan-eilertsen

Copy link
Copy Markdown
Contributor Author

@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 (cacfa20bc2d430bdbbc38c67f4d55153c5e3fb55). Please reassess the proof/security request using this newly published evidence; the source-level fixture does not claim packaged CLI, a different selected person, later revocation during model I/O, or external-channel delivery. Human maintainer review remains required.

@clawsweeper

clawsweeper Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. and removed merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 19, 2026
@clawsweeper clawsweeper Bot added the clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. label Oct 28, 2026
@johan-eilertsen

Copy link
Copy Markdown
Contributor Author

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 agent.wait with terminal waiting after dispatch. In this trace the driver declared its sequence observed at20:51:05.361Z, started shutdown at20:51:05.725Z, and caused the logged shutdown rejection while return work was still active. No matching durable original-return completion/trajectory/cache receipt was found in the preserved scratch DB. The model's stopReason:stop and persisted return response do not replace that terminal receipt. Independent post-final failures cannot be excluded without it.

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 passed from overallPassed, which also requires exit0/no signal and no reply-flow-failed warning. These offline tests are not new live proof. The historical report and its SHA-256, passed:true, SIGKILL and warning remain unchanged.

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.

@johan-eilertsen

Copy link
Copy Markdown
Contributor Author

Exact-head synthetic Gateway return settlement — 7 November

A 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.

@obviyus
obviyus requested a review from a team as a code owner November 17, 2026 17:10
@obviyus

obviyus commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator

Gateway reproduction on main and this head (source tier, ocx src; plus the full Node build). Deterministic local OpenAI Responses fixture, real agents, no real provider. Fixture times are UTC; Gateway log times are UTC+05:30.

== E2E harness ==
run.sh + provider.mjs. Tier: source (ocx src Gateway, pinned Bun), deterministic local OpenAI Responses fixture, openclaw runtime, real agents.
Flow: chat.send HELLO_B -> chat.send BUSY_B (fixture holds the reply 40 s, reports 118000 input tokens of a 128000 window) -> chat.send START_A:
A calls sessions_send {sessionKey: B, timeoutSeconds: 0} -> "accepted / targetDisposition: queued", A's turn ends -> B finishes BUSY_B -> B's queued run needs token preflight compaction.

base main 9122a49bd8a12baf734ec7bb78337bd556fcbef8 (run main2):
  16:24:19 A:sessions_send accepted queued (run 9d6a27e8); 16:24:22 A final
  21:55:04 [compaction-diag] end ... trigger=budget provider=mock-openai/gpt-5.4 outcome=failed reason=unknown durationMs=610
  21:55:04 [auto-reply/preflight-compaction] preflight compaction failed: agent tool caller authority is no longer active
  run 9d6a27e8 never ends with stopReason. RESULT main2: caller-authority failure
  (main2's fixture re-sent from A's reply-back turns; later sends after B compacted succeeded. Fixed in the fixture for base2.)
base main 9122a49bd8a1 (run base2, one send only):
  16:37:03 A:sessions_send accepted queued (run d9bee87a); 16:37:04 A final
  22:07:35 [compaction-diag] end ... trigger=budget outcome=failed reason=unknown durationMs=1157
  22:07:35 [auto-reply/preflight-compaction] preflight compaction failed: agent tool caller authority is no longer active
  no B:queued-send-turn request. RESULT base2: caller-authority failure
control, main 9122a49bd8a1 (ocx base scratch, dist-nodts), SEND_WAIT_S=120 (sender's tool call/turn stays alive):
  16:55:57 A:sessions_send; 16:56:33 compaction summary requests; 16:56:35 B:queued-send-turn; A gets {"status":"ok","reply":"B_HANDLED"}
  RESULT base-control-waited: queued send reached the model (no authority line)
candidate 392983822776 (main + #177296 cacfa20bc2d4; production diff identical at final head) (run cand1):
  16:42:16 A:sessions_send accepted queued (run 100855ca); 16:42:17 A final
  16:42:51 compaction summary requests (preflight compaction succeeds); 16:42:57 B:queued-send-turn
  22:12:57 [agent] run 100855ca-... ended with stopReason=stop; no authority line. RESULT cand1: queued send reached the model

== Regression test ==
src/gateway/server-plugin-in-process-dispatch.caller-lifetime.test.ts (contributor's; trimmed to the red case):
  base 9122a49bd8a1 (ocx base scratch, node scripts/run-vitest.mjs): 2 failed - "promise rejected 'Error: agent tool caller authority is no longer active'" for host and admission cases
  candidate 718b663a425f (ocx test): 2 passed

candidate 718b663a425f, full build (ocx build --dts), node dist/entry.js Gateway (run cand2-dist):
  17:07:42 A:sessions_send accepted queued (run a7afde28); 17:08:24 compaction summary requests; 17:08:38 B:queued-send-turn; no authority line
  RESULT cand2-dist: queued send reached the model

@openclaw-barnacle openclaw-barnacle Bot added size: XL and removed gateway Gateway runtime size: S labels Nov 17, 2026
@obviyus

obviyus commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

@openclaw-barnacle openclaw-barnacle Bot added the gateway Gateway runtime label Nov 17, 2026
@clawsweeper

clawsweeper Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 17, 2026
@obviyus
obviyus merged commit 5e6bbed into openclaw:main Nov 17, 2026
213 of 219 checks passed
@obviyus

obviyus commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator

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 sessions_send) no longer carries the sender's tool caller identity, so preflight compaction in the receiving session no longer fails with "agent tool caller authority is no longer active" after the sender's turn has ended. The sender is still checked before the turn is accepted.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 18, 2026
…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]>
RomneyDa added a commit that referenced this pull request Nov 19, 2026
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

2 participants