Repository navigation
fix(agents): plugin agent_end hooks fail after a turn that called dispatch_action - #197990
Conversation
Turns that called dispatch_action hydrate nested tool activity for agent_end with an off-thread transcript read. The bundled path started that hydration in a detached launcher, so the run released its plugin invocation scope first and every handler was refused with "Plugin invocation scope is closed". runAgentEndSideEffectsAsync now awaits hydration before it resolves and then starts handlers without waiting for them, so they are admitted while the scope is open.
|
🦞👀 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 finishes agent_end message hydration before releasing the turn’s plugin scope while keeping handler completion asynchronous. Example: A Gateway turn calls dispatch_action(openclaw:core:session_status).
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review Keep this PR: it repairs a current plugin lifecycle bug with a focused change, a meaningful regression test, supplied Gateway proof, and passing exact-head CI; no actionable introduced defect was found. Priority: P1 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherThe agent harness prepares completed-turn facts and transcript messages for plugin hooks, then dispatches handlers through the existing plugin admission owner. flowchart TD
A[Embedded turn completes] --> B[Prepare completed turn]
B --> C[Hydrate transcript messages]
C --> D[Admit plugin handlers]
D --> E[Release turn scope]
D --> F[Handlers finish asynchronously]
Technical reviewBest possible solution: Keep message preparation within the existing turn scope, then admit handlers through the existing hook runner without waiting for their completion. Do we have a high-confidence way to reproduce the issue? Current source exposes the delayed-hydration admission failure, and the contributor supplies base/head Gateway results plus a base-red/head-green regression; this read-only review executed no target code. Is this the best way to solve the issue? This is a focused repair at the existing lifecycle owner: the internal preparation helper preserves public launcher semantics, existing admission checks, and asynchronous handler completion without adding state or configuration. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 28d20f9532f4. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +24, Tests +44, Other -1. Total +67 across 5 files. Added test files: 0. 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. Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. LabelsLabel changes: No label 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 November 12, 2026, 7:48 PM ET / November 13, 2026, 00:48 UTC. |
|
Merged via squash.
|
…198732) * fix(subagents): preserve completion hooks after the requester turn ends Re-admit subagent_ended and subagent_delivery_target through the shared dispatch owner after leaving finished-turn scope. Keep exact plugin lifecycle rejection and explicitly closed callbacks. Preserve the separate agent_end fix in #197990. Regression proof reproduces lost Discord thread overrides through the real hook runner and completion-origin resolver. Focused tests and corrected typechecks pass; Codex autoreview is clean. Full changed checks retain unrelated dead-export failures under exact-parent investigation. * fix(plugins): share post-turn scope exit below the agent layer
…claw#197990) Hydrate agent_end messages before foreground finalization releases the turn's plugin invocation scope, then admit handlers while keeping their completion asynchronous. Preserve existing SDK dispatch semantics and unref timeouts. Validation: independent isolated exact-head focused tests passed (2 files, 19 tests); complete-range independent review and PR-simplify found no actionable changes; exact-head ClawSweeper had no findings. Real Gateway base/head dispatch and direct-tool controls reuse the contributor-supplied exact-head E2E evidence, not a newly executed maintainer Gateway run. Co-authored-by: Mitchell Etzel <[email protected]> Co-authored-by: obviyus <[email protected]> Co-authored-by: steipete <[email protected]>
…penclaw#198732) * fix(subagents): preserve completion hooks after the requester turn ends Re-admit subagent_ended and subagent_delivery_target through the shared dispatch owner after leaving finished-turn scope. Keep exact plugin lifecycle rejection and explicitly closed callbacks. Preserve the separate agent_end fix in openclaw#197990. Regression proof reproduces lost Discord thread overrides through the real hook runner and completion-origin resolver. Focused tests and corrected typechecks pass; Codex autoreview is clean. Full changed checks retain unrelated dead-export failures under exact-parent investigation. * fix(plugins): share post-turn scope exit below the agent layer
… refusing late calls (#199618) ## Problem A plugin invocation scope had a "closed" state. When a scope was released, every later call that still carried the scope in its async context threw `Plugin invocation scope is closed`. That happens often: post-turn hooks, subagent completion, deferred delivery, access checks and shutdown all run after the turn that started them has ended. Each failing path got its own patch that left the scope (`pluginInvocationContext.exit(...)` or `runOutsidePluginInvocationScope`), for example #196700, #196750, #197658, #197990, #198652, #198732 and #198844. The bug class stays open. One production Gateway still logs 46 of these errors in 6 hours, on a release that already includes all of those patches: - 37 × `context-engine onSubagentEnded failed (best-effort) … Plugin invocation scope is closed` (phase `registry`) - 9 × `subagent_ended hook failed (best-effort) … PluginInvocationScope.assertOpen ← lookup ← PluginInstance.run` ## Fix A released scope stops routing. It no longer refuses calls. - `PluginInvocationScope.lookup` returns `undefined` after release. `run` runs the operation directly. A late call therefore takes ordinary counted admission on the plugin instance: it runs while the instance accepts calls, and it is refused (`… was reloaded or disabled`) only while the instance is quiesced, replaced or retired. Hook dispatch then switches to the new instance, as before. - `assertOpen` and both "closed" errors are removed. The cleanup scope (`runPluginCleanupScope`) and the teardown views from `beginCleanup` give up teardown authority when their owner finishes; later calls take ordinary admission. - A released scope drops its instance views, so a stale async context does not retain them. - Hot reload is unchanged. While a scope is live, it still routes calls, so reload still waits for turns that used a plugin, and `generationOverlap` turns keep their old generation. `prepared-model-runtime.plugin-drain.test.ts` passes unchanged. - The per-hook workarounds are reverted: - #198732: `subagent_ended` / `subagent_delivery_target` scope exit in `hook-dispatch-replacement.ts` - #198844: `runAccessPolicy` scope exit in `gateway-access-policy-registration.ts` - #197990: `startAgentHarnessAgentEndHook` (agent_end evidence was loaded early only to finish inside the scope) - #196700: activity recap scope exit in `session-activity-summaries.ts` - #196750: session-event delivery scope exit - #197658: lifecycle Gateway call scope exit in `server-lifecycle-runtime-context.ts` - #198652: Gateway close scope exit in `server-lifecycle-close.ts` - their two perf scripts (`hook-post-turn-measure.ts`, `access-policy-scope-measure.ts`) and the duplicate `subagent-announce-origin.hook-scope.test.ts` - Kept on purpose: `runInDetachedAsyncContext` for auth publication (#197960) and the generation-scope exits. They also detach other async state, not only the plugin scope. - `docs/plugins/sdk-runtime.md` now describes the single rule in place of the two per-hook paragraphs. This is option A of design E3 (step E-2). The full design (an explicit `runId` threaded through every capability call, then delete the scope) needs a new design pass first. The ambient scope also carries two documented hot-reload contracts for tools, providers and context engines, not only hooks. ## Proof | Claim | Tier | Base (`5d5ca9d2ba8c`) | Head | |---|---|---|---| | Context-engine `onSubagentEnded` after the requesting turn's scope is released (new regression test, `subagent-registry-context-cleanup.test.ts`) | vitest-source | **fails**: warns `Plugin invocation scope is closed` | passes, delivered once | | `subagent_ended` hook after the requesting turn's scope is released (same file) | vitest-source | **fails**: warns `Plugin invocation scope is closed` | passes, delivered once, persisted | | `agent_end` handler after the turn's scope is released (`lifecycle-hook-helpers.test.ts`, with the #197990 helper removed) | vitest-source | — | passes | | Reload drain and `generationOverlap` custody (`prepared-model-runtime.plugin-drain.test.ts`, unchanged) | vitest-source | passes | passes (8/8) | | All 50 test files that reference the scope, the instance-unavailable error, or the reverted paths | vitest-source | — | pass (26 + 24 files) | | `rg 'Plugin (invocation\|cleanup) scope is closed' src scripts test extensions docs` | — | many hits | 0 | | Real Gateway (`ocx src -- gateway run`, isolated HOME, stand-in Responses model, a workspace plugin with a `subagent_ended` hook and a context engine with `onSubagentEnded`). One turn spawns a child that answers 15 s after the parent turn ends. | source | hooks fire once each, 0 scope errors | hooks fire once each, 0 scope errors, `agent_end` ×3 | | `pnpm tsgo:core`, `pnpm check:test-types`, `pnpm tsgo:scripts`, oxlint and oxfmt on the changed files | — | — | pass | | `ocx build --dts` | full | — | pass | | Packed install smoke (`scripts/release-check.ts`) | full | — | pass: tarball contents, packed install, doctor, SDK type consumers, bundled channel entries | The real Gateway run shows that late hooks and context-engine notifications still work end to end after this change. It does not reproduce the production error on base: the CLI `agent` route does not leave a released scope in the child-completion context. The production Gateway reaches it through dashboard and channel ingress. The base failure is reproduced at the vitest-source tier with the exact production log lines. Note: one full run of `server-plugin-reload.recovery.test.ts` failed while the host load was about 55. The same file passes on head alone, with and without a filter. ## Net lines `28 files changed, 200 insertions(+), 579 deletions(-)`: source +54/−115, tests, docs and perf scripts +146/−464. Co-authored-by: Ayaan Zaidi <[email protected]>
… refusing late calls (openclaw#199618) ## Problem A plugin invocation scope had a "closed" state. When a scope was released, every later call that still carried the scope in its async context threw `Plugin invocation scope is closed`. That happens often: post-turn hooks, subagent completion, deferred delivery, access checks and shutdown all run after the turn that started them has ended. Each failing path got its own patch that left the scope (`pluginInvocationContext.exit(...)` or `runOutsidePluginInvocationScope`), for example openclaw#196700, openclaw#196750, openclaw#197658, openclaw#197990, openclaw#198652, openclaw#198732 and openclaw#198844. The bug class stays open. One production Gateway still logs 46 of these errors in 6 hours, on a release that already includes all of those patches: - 37 × `context-engine onSubagentEnded failed (best-effort) … Plugin invocation scope is closed` (phase `registry`) - 9 × `subagent_ended hook failed (best-effort) … PluginInvocationScope.assertOpen ← lookup ← PluginInstance.run` ## Fix A released scope stops routing. It no longer refuses calls. - `PluginInvocationScope.lookup` returns `undefined` after release. `run` runs the operation directly. A late call therefore takes ordinary counted admission on the plugin instance: it runs while the instance accepts calls, and it is refused (`… was reloaded or disabled`) only while the instance is quiesced, replaced or retired. Hook dispatch then switches to the new instance, as before. - `assertOpen` and both "closed" errors are removed. The cleanup scope (`runPluginCleanupScope`) and the teardown views from `beginCleanup` give up teardown authority when their owner finishes; later calls take ordinary admission. - A released scope drops its instance views, so a stale async context does not retain them. - Hot reload is unchanged. While a scope is live, it still routes calls, so reload still waits for turns that used a plugin, and `generationOverlap` turns keep their old generation. `prepared-model-runtime.plugin-drain.test.ts` passes unchanged. - The per-hook workarounds are reverted: - openclaw#198732: `subagent_ended` / `subagent_delivery_target` scope exit in `hook-dispatch-replacement.ts` - openclaw#198844: `runAccessPolicy` scope exit in `gateway-access-policy-registration.ts` - openclaw#197990: `startAgentHarnessAgentEndHook` (agent_end evidence was loaded early only to finish inside the scope) - openclaw#196700: activity recap scope exit in `session-activity-summaries.ts` - openclaw#196750: session-event delivery scope exit - openclaw#197658: lifecycle Gateway call scope exit in `server-lifecycle-runtime-context.ts` - openclaw#198652: Gateway close scope exit in `server-lifecycle-close.ts` - their two perf scripts (`hook-post-turn-measure.ts`, `access-policy-scope-measure.ts`) and the duplicate `subagent-announce-origin.hook-scope.test.ts` - Kept on purpose: `runInDetachedAsyncContext` for auth publication (openclaw#197960) and the generation-scope exits. They also detach other async state, not only the plugin scope. - `docs/plugins/sdk-runtime.md` now describes the single rule in place of the two per-hook paragraphs. This is option A of design E3 (step E-2). The full design (an explicit `runId` threaded through every capability call, then delete the scope) needs a new design pass first. The ambient scope also carries two documented hot-reload contracts for tools, providers and context engines, not only hooks. ## Proof | Claim | Tier | Base (`5a640d63290f`) | Head | |---|---|---|---| | Context-engine `onSubagentEnded` after the requesting turn's scope is released (new regression test, `subagent-registry-context-cleanup.test.ts`) | vitest-source | **fails**: warns `Plugin invocation scope is closed` | passes, delivered once | | `subagent_ended` hook after the requesting turn's scope is released (same file) | vitest-source | **fails**: warns `Plugin invocation scope is closed` | passes, delivered once, persisted | | `agent_end` handler after the turn's scope is released (`lifecycle-hook-helpers.test.ts`, with the openclaw#197990 helper removed) | vitest-source | — | passes | | Reload drain and `generationOverlap` custody (`prepared-model-runtime.plugin-drain.test.ts`, unchanged) | vitest-source | passes | passes (8/8) | | All 50 test files that reference the scope, the instance-unavailable error, or the reverted paths | vitest-source | — | pass (26 + 24 files) | | `rg 'Plugin (invocation\|cleanup) scope is closed' src scripts test extensions docs` | — | many hits | 0 | | Real Gateway (`ocx src -- gateway run`, isolated HOME, stand-in Responses model, a workspace plugin with a `subagent_ended` hook and a context engine with `onSubagentEnded`). One turn spawns a child that answers 15 s after the parent turn ends. | source | hooks fire once each, 0 scope errors | hooks fire once each, 0 scope errors, `agent_end` ×3 | | `pnpm tsgo:core`, `pnpm check:test-types`, `pnpm tsgo:scripts`, oxlint and oxfmt on the changed files | — | — | pass | | `ocx build --dts` | full | — | pass | | Packed install smoke (`scripts/release-check.ts`) | full | — | pass: tarball contents, packed install, doctor, SDK type consumers, bundled channel entries | The real Gateway run shows that late hooks and context-engine notifications still work end to end after this change. It does not reproduce the production error on base: the CLI `agent` route does not leave a released scope in the child-completion context. The production Gateway reaches it through dashboard and channel ingress. The base failure is reproduced at the vitest-source tier with the exact production log lines. Note: one full run of `server-plugin-reload.recovery.test.ts` failed while the host load was about 55. The same file passes on head alone, with and without a filter. ## Net lines `28 files changed, 200 insertions(+), 579 deletions(-)`: source +54/−115, tests, docs and perf scripts +146/−464. Co-authored-by: Ayaan Zaidi <[email protected]>
Closes #197940
Related: #197947 is an open draft for the same issue; this PR carries the regression test and Gateway proof.
What Problem This Solves
Fixes: every plugin
agent_endhandler fails withPlugin invocation scope is closedafter an embedded turn in which the model called a tool through Tool Searchdispatch_action.User Impact
User impact: plugins that keep memory, logs or telemetry at
agent_end(including bundledskill-workshop) run again after Tool Search dispatch turns, which is the default tool surface. Turns that call tools directly already worked and behave the same.Risk: low. Only the bundled asynchronous
agent_endpath changes ordering, and only when a message loader is bound. A slow transcript read now delays the end of the run instead of losing every handler.Why This Change Was Made
A turn with nested tool activity (only
dispatch_actionrecords it) handsagent_endits messages through a loader that reads that activity back from the transcript store.runAgentEndSideEffectsAsyncstarted hook delivery in a detached launcher, so it returned before the read finished. The run then released its prepared plugin invocation scope, and when the read completed, each handler's admission hit the closed scope and threw. Turns without nested activity got their messages after one microtask, before the release, which is why direct tool calls were fine.runAgentEndSideEffectsAsyncnow awaits the message hydration (new internalstartAgentHarnessAgentEndHook) and then starts handlers without waiting for them, so they are admitted while the turn's scope is still open. Handler execution stays fire-and-forget with unref timeouts, as before. The closed-scope check, caller context, the SDK-exportedrunAgentHarnessAgentEndHookandawaitAgentHarnessAgentEndHook, and the deprecated synchronousrunAgentEndSideEffectsare unchanged.Cost: on a dispatch turn with an
agent_endsubscriber, finalization now waits for that one transcript read, which previously ran right after it.before_agent_finalizealready awaits the same read in the foreground. No read happens when no plugin subscribes.config/test-mock-exports-baseline.txtloses theagent-end-side-effects.test.tsentry because that mock now carries a// mock-isolation:reason; the mock export ratchet requires the stale entry to be removed.Evidence
Regression test, real plugin admission (
src/agents/harness/lifecycle-hook-helpers.test.ts): a real plugin instance, a retainedPluginInvocationScopeand a real hook runner with a wrappedagent_endhandler. The message loader resolves after a macrotask, and the scope is released as soon asrunAgentEndSideEffectsAsyncreturns, as the embedded run does.4efd662cc2cwith only the new test: 1 failed, 9 passed. The handler is refused with[hooks] agent_end handler from agent-end-probe failed: Plugin invocation scope is closed.Tests on head (
pnpm test <files>, 18 files, 312 tests passed): harness lifecycle helpers, agent-end side effects, plugin invocation scope, embedded-runner nested tool activity, phase lifecycle, stream finalize/settle/prepare, execution and session settle, attempt result, Tool Search executor, code-mode continuation and bridge lifecycle, and CLIagent_endpaths. The suggestedvitest.unit.config.tsinvocation matches none of these files, so they were run throughpnpm test, which routes them to the agents and plugins configs.pnpm check:changed --base 4efd662cc2c: typecheck (core and core tests), lint, format, mock export ratchet, import cycles and the other lanes pass. The dead export scan reportssrc/gateway/trusted-proxy-git-coauthor.ts: resolveTrustedProxyGitCoauthor, which this change does not touch;pnpm deadcode:exportsreports the same on clean4efd662cc2c.Real Gateway run: one fresh isolated Gateway per row (
/v1/chat/completions, loopback, local OpenAI-compatible model). Twoagent_endhandlers were registered: a fixture plugin and bundledskill-workshop.The dispatch rows use Tool Search at its default. The direct rows set
tools.toolSearch: falseand callsession_statusdirectly. On base, both handlers logfailed: Plugin invocation scope is closed. On head there are no handler failure lines, and the fixture recordsagent_endwith 8 messages.skill-workshopdoes not log on success, so on head its result is shown only by the absence of a failure line.