Skip to content

Commit ee63445

Browse files
committed
fix(gateway): bind detached lifecycle dispatch
1 parent 491dc7f commit ee63445

8 files changed

Lines changed: 161 additions & 12 deletions
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
import { afterEach, describe, expect, it, vi } from "vitest";
2+
import { WRITE_SCOPE } from "../../../gateway/method-scopes.js";
3+
import { createGatewayMethodRegistry } from "../../../gateway/methods/registry.js";
4+
import { createGatewayInstanceRuntime } from "../../../gateway/server-instance-runtime.js";
5+
import type {
6+
GatewayRequestContext,
7+
GatewayRequestHandlers,
8+
} from "../../../gateway/server-methods/types.js";
9+
import { dispatchSubagentAnnounceAgent } from "./subagent-announce-delivery.runtime.js";
10+
11+
function createContext(): GatewayRequestContext {
12+
return {
13+
deps: {},
14+
getRuntimeConfig: () => ({}),
15+
logGateway: {
16+
warn: vi.fn(),
17+
error: vi.fn(),
18+
},
19+
chatAbortControllers: new Map(),
20+
chatQueuedTurns: new Map(),
21+
dedupe: new Map(),
22+
} as unknown as GatewayRequestContext;
23+
}
24+
25+
function createRegistry(handlers: GatewayRequestHandlers) {
26+
return createGatewayMethodRegistry(
27+
Object.entries(handlers).map(([name, handler]) => ({
28+
name,
29+
handler,
30+
owner: { kind: "core" as const, area: "test" },
31+
scope: WRITE_SCOPE,
32+
})),
33+
);
34+
}
35+
36+
describe("subagent announce Gateway instance dispatch", () => {
37+
let closeRuntime: (() => void) | undefined;
38+
39+
afterEach(() => {
40+
closeRuntime?.();
41+
closeRuntime = undefined;
42+
});
43+
44+
it("delivers a detached announce after the originating request scope has ended", async () => {
45+
const context = createContext();
46+
const idempotencyKey = "detached-subagent-announce";
47+
context.dedupe.set(`agent:${idempotencyKey}`, {
48+
ts: Date.now(),
49+
ok: true,
50+
payload: { runId: "announce-run", status: "ok", summary: "delivered" },
51+
});
52+
const runtime = createGatewayInstanceRuntime({
53+
getContext: () => context,
54+
getMethodRegistry: () =>
55+
createRegistry({
56+
agent: ({ respond }) => respond(true, { raw: true }),
57+
}),
58+
isDispatchAvailable: () => true,
59+
});
60+
closeRuntime = runtime.close;
61+
62+
await expect(
63+
dispatchSubagentAnnounceAgent(
64+
{
65+
message: "Process one completed child result.",
66+
idempotencyKey,
67+
},
68+
{ expectFinal: true, forceSyntheticClient: true },
69+
),
70+
).resolves.toEqual({ runId: "announce-run", status: "ok", summary: "delivered" });
71+
});
72+
});

‎src/agents/subagents/announce/subagent-announce-delivery.runtime.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ import { loadSessionEntryReadOnly as loadSessionEntry } from "../../../config/se
1212
import { resolvePersistedSessionStoreOwnerForKey } from "../../../config/sessions/session-store-owner.js";
1313
import type { OpenClawConfig } from "../../../config/types.openclaw.js";
1414
import { callGateway } from "../../../gateway/call.js";
15-
import { dispatchGatewayMethodInProcess } from "../../../gateway/server-plugins.js";
1615
import { resolveExternalBestEffortDeliveryTarget } from "../../../infra/outbound/best-effort-delivery.js";
1716
import { createBoundDeliveryRouter } from "../../../infra/outbound/bound-delivery-router.js";
1817
import { resolveConversationIdFromTargets } from "../../../infra/outbound/conversation-id.js";
@@ -32,6 +31,7 @@ import {
3231
resolveActiveEmbeddedRunSessionId,
3332
type EmbeddedAgentQueueMessageOutcome,
3433
} from "../../embedded-agent-runner/runs.js";
34+
import { dispatchGatewayMethodInProcess } from "./subagent-announce.runtime.js";
3535
import { resolveRequesterStoreKey } from "./subagent-requester-store-key.js";
3636

3737
export {

‎src/agents/subagents/announce/subagent-announce.runtime.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
* IO without changing the announce logic itself.
66
*/
77
import { loadSessionEntry } from "../../../config/sessions/session-accessor.js";
8+
export { dispatchGatewayLifecycleMethod as dispatchGatewayMethodInProcess } from "../../../gateway/server-recovery-runtime-context.js";
89
export { getRuntimeConfig } from "../../../config/config.js";
910
export {
1011
resolveAgentIdFromSessionKey,
@@ -16,7 +17,6 @@ export function readSubagentSessionEntry(storePath: string, sessionKey: string)
1617
}
1718
export { callGateway } from "../../../gateway/call.js";
1819
export { readSessionMessagesAsync } from "../../../gateway/session-transcript-readers.js";
19-
export { dispatchGatewayMethodInProcess } from "../../../gateway/server-plugins.js";
2020
export {
2121
isEmbeddedAgentRunActive,
2222
waitForEmbeddedAgentRunEnd,

‎src/gateway/server-instance-runtime.ts‎

Lines changed: 39 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,18 @@ import { APPROVALS_SCOPE, WRITE_SCOPE } from "./method-scopes.js";
1818
import type { GatewayMethodRegistry } from "./methods/registry.js";
1919
import { dispatchGatewayRequestInProcess } from "./server-in-process-dispatch.js";
2020
import type {
21+
GatewayInstanceAgentDispatchOptions,
2122
GatewayInstanceRuntime,
2223
GatewayRecoveryRuntime,
2324
} from "./server-instance-runtime.types.js";
2425
import type { AgentRunRequest } from "./server-methods/agent-request-types.js";
2526
import type { GatewayRequestContext } from "./server-methods/types.js";
2627
import { createSyntheticPluginRuntimeClient } from "./server-plugin-runtime-client.js";
2728
import { registerGatewayRecoveryRuntime } from "./server-recovery-runtime-context.js";
29+
import {
30+
cancelSubagentCompletionToolHandoff,
31+
registerSubagentCompletionToolHandoff,
32+
} from "./subagent-completion-tool-handoff.js";
2833

2934
const loadOutboundMessageRuntime = createLazyRuntimeModule(
3035
() => import("../infra/outbound/message.js"),
@@ -92,20 +97,49 @@ export function createGatewayInstanceRuntime(
9297
dispatchAgent: async <T>(
9398
payload: AgentRunRequest,
9499
timeoutMs?: number,
95-
dispatchOptions?: { allowModelOverride?: boolean; scopes?: string[] },
100+
dispatchOptions: GatewayInstanceAgentDispatchOptions = {},
96101
) => {
97102
assertDispatchAvailable("agent");
98-
const agentTurns = dispatchOptions
103+
const delegatedToolPolicyHandoffId = dispatchOptions.delegatedToolPolicyHandoff
104+
? registerSubagentCompletionToolHandoff(dispatchOptions.delegatedToolPolicyHandoff)
105+
: undefined;
106+
const needsDedicatedPrincipal = Boolean(
107+
dispatchOptions.allowModelOverride === true ||
108+
dispatchOptions.allowSyntheticModelOverride === true ||
109+
dispatchOptions.allowSyntheticCronRunContinuation === true ||
110+
dispatchOptions.internalDeliveryMediaUrls ||
111+
dispatchOptions.internalDeliverySuppressText === true ||
112+
delegatedToolPolicyHandoffId ||
113+
dispatchOptions.scopes ||
114+
dispatchOptions.syntheticScopes,
115+
);
116+
const agentTurns = needsDedicatedPrincipal
99117
? createInternalAgentTurnFacade({
100118
client: createSyntheticPluginRuntimeClient({
101-
allowModelOverride: dispatchOptions.allowModelOverride,
102-
scopes: dispatchOptions.scopes,
119+
allowModelOverride:
120+
dispatchOptions.allowModelOverride === true ||
121+
dispatchOptions.allowSyntheticModelOverride === true,
122+
cronRunContinuation: dispatchOptions.allowSyntheticCronRunContinuation === true,
123+
internalDeliveryMediaUrls: dispatchOptions.internalDeliveryMediaUrls,
124+
internalDeliverySuppressText: dispatchOptions.internalDeliverySuppressText,
125+
delegatedToolPolicyHandoffId,
126+
scopes: dispatchOptions.scopes ?? dispatchOptions.syntheticScopes,
103127
}),
104128
getContext: options.getContext,
105129
getMethodRegistry: options.getMethodRegistry,
106130
})
107131
: recoveryAgentTurns;
108-
return await agentTurns.dispatch<T>(payload, timeoutMs);
132+
try {
133+
return await agentTurns.dispatch<T>(payload, {
134+
expectFinal: dispatchOptions.expectFinal,
135+
onAccepted: dispatchOptions.onAccepted,
136+
onSignalAbort: dispatchOptions.onSignalAbort,
137+
signal: dispatchOptions.signal,
138+
timeoutMs,
139+
});
140+
} finally {
141+
cancelSubagentCompletionToolHandoff(delegatedToolPolicyHandoffId);
142+
}
109143
},
110144
waitForAgent: async <T>(payload: AgentWaitParams, timeoutMs?: number) => {
111145
assertDispatchAvailable("agent.wait");

‎src/gateway/server-instance-runtime.types.ts‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,30 @@
11
import type { AgentWaitParams } from "../../packages/gateway-protocol/src/index.js";
2+
import type { SubagentCompletionToolHandoffRegistration } from "../agents/subagents/announce/subagent-announce-handoff.js";
23
import type { GatewayNativeApprovalRuntime } from "../infra/approval-gateway-runtime.types.js";
34
import type { ChannelApprovalKind } from "../infra/approval-types.js";
45
import type { AgentRunRequest } from "./server-methods/agent-request-types.js";
56

7+
export type GatewayInstanceAgentDispatchOptions = {
8+
allowModelOverride?: boolean;
9+
allowSyntheticModelOverride?: boolean;
10+
allowSyntheticCronRunContinuation?: boolean;
11+
delegatedToolPolicyHandoff?: SubagentCompletionToolHandoffRegistration;
12+
expectFinal?: boolean;
13+
/** Instance-owned dispatch always uses a synthetic client. */
14+
forceSyntheticClient?: boolean;
15+
internalDeliveryMediaUrls?: string[];
16+
internalDeliverySuppressText?: boolean;
17+
onAccepted?: (payload: unknown) => void;
18+
onSignalAbort?: () => Promise<void> | void;
19+
scopes?: string[];
20+
signal?: AbortSignal;
21+
syntheticScopes?: string[];
22+
};
23+
24+
export type GatewayLifecycleAgentDispatchOptions = GatewayInstanceAgentDispatchOptions & {
25+
timeoutMs?: number;
26+
};
27+
628
export type GatewayApprovalEventPublisher = {
729
publishRequested: (kind: ChannelApprovalKind, request: unknown) => number;
830
publishResolved: (kind: ChannelApprovalKind, resolved: unknown) => void;
@@ -12,7 +34,7 @@ export type GatewayRecoveryRuntime = {
1234
dispatchAgent: <T = unknown>(
1335
params: AgentRunRequest,
1436
timeoutMs?: number,
15-
options?: { allowModelOverride?: boolean; scopes?: string[] },
37+
options?: GatewayInstanceAgentDispatchOptions,
1638
) => Promise<T>;
1739
waitForAgent: <T = unknown>(params: AgentWaitParams, timeoutMs?: number) => Promise<T>;
1840
sendRecoveryNotice: (params: {

‎src/gateway/server-recovery-runtime-context.ts‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
1-
import type { GatewayRecoveryRuntime } from "./server-instance-runtime.types.js";
1+
import type {
2+
GatewayLifecycleAgentDispatchOptions,
3+
GatewayRecoveryRuntime,
4+
} from "./server-instance-runtime.types.js";
5+
import type { AgentRunRequest } from "./server-methods/agent-request-types.js";
26

37
type ActiveGatewayRecoveryRuntime = {
48
owner: symbol;
@@ -28,3 +32,17 @@ export function registerGatewayRecoveryRuntime(runtime: GatewayRecoveryRuntime):
2832
export function getGatewayRecoveryRuntime(): GatewayRecoveryRuntime | undefined {
2933
return activeRuntime?.runtime;
3034
}
35+
36+
/** Dispatches detached Gateway lifecycle work through the active instance principal. */
37+
export async function dispatchGatewayLifecycleMethod<T = unknown>(
38+
method: "agent",
39+
params: Record<string, unknown>,
40+
options: GatewayLifecycleAgentDispatchOptions = {},
41+
): Promise<T> {
42+
const agentParams = params as AgentRunRequest; // SAFETY: the bound facade validates the payload.
43+
const runtime = getGatewayRecoveryRuntime();
44+
if (!runtime) {
45+
throw new Error(`Gateway instance lifecycle dispatch unavailable for ${method}`);
46+
}
47+
return await runtime.dispatchAgent<T>(agentParams, options.timeoutMs, options);
48+
}

‎src/gateway/server-restart-sentinel-agent-delivery.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ import {
3333
import { createSubsystemLogger } from "../logging/subsystem.js";
3434
import { normalizeMediaReferenceForComparison } from "../media/media-reference-comparison.js";
3535
import { INTERNAL_MESSAGE_CHANNEL } from "../utils/message-channel.js";
36-
import { dispatchGatewayMethodInProcess } from "./server-plugins.js";
36+
import { dispatchGatewayLifecycleMethod as dispatchGatewayMethodInProcess } from "./server-recovery-runtime-context.js";
3737
import { loadSessionEntry } from "./session-utils.js";
3838

3939
const log = createSubsystemLogger("gateway/restart-sentinel");

‎src/gateway/server-restart-sentinel.test.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -333,8 +333,11 @@ vi.mock("../channels/turn/lifecycle.js", () => ({
333333
},
334334
}));
335335

336-
vi.mock("./server-plugins.js", () => ({
337-
dispatchGatewayMethodInProcess: mocks.dispatchGatewayMethodInProcess,
336+
vi.mock("./server-recovery-runtime-context.js", async () => ({
337+
...(await vi.importActual<typeof import("./server-recovery-runtime-context.js")>(
338+
"./server-recovery-runtime-context.js",
339+
)),
340+
dispatchGatewayLifecycleMethod: mocks.dispatchGatewayMethodInProcess,
338341
}));
339342

340343
vi.mock("../infra/outbound/targets.js", () => ({

0 commit comments

Comments
 (0)