Skip to content

Commit 432356a

Browse files
authored
refactor(gateway): migrate internal agent turn callers to the typed facade (#121715)
* refactor(gateway): migrate internal agent turn callers * test(gateway): mock typed subagent turn facade * fix(gateway): preserve typed turn authorization * chore(plugin-sdk): refresh typed facade closure hashes * fix(gateway): validate typed agent turn requests * fix(gateway): preserve typed turn lifecycle parity
1 parent 1220a76 commit 432356a

22 files changed

Lines changed: 1097 additions & 408 deletions

‎docs/.generated/plugin-sdk-api-baseline.jsonl‎

Lines changed: 68 additions & 68 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎src/agents/bash-tools.exec-approval-followup.ts‎

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import {
1010
import { sliceUtf16Safe } from "@openclaw/normalization-core/utf16-slice";
1111
import { resolveStorePath } from "../config/sessions/paths.js";
1212
import { loadSessionEntryReadOnly } from "../config/sessions/session-accessor.js";
13+
import { getGatewayRecoveryRuntime } from "../gateway/server-recovery-runtime-context.js";
1314
import { emitDiagnosticEvent } from "../infra/diagnostic-events.js";
1415
import {
1516
resolveExternalBestEffortDeliveryTarget,
@@ -53,6 +54,26 @@ const AGENT_FOLLOWUP_WAIT_RETRY_DELAY_MS = 1_000;
5354
const AGENT_FOLLOWUP_OBSERVATION_TIMEOUT_MS =
5455
AGENT_FOLLOWUP_RUN_TIMEOUT_SECONDS * 1_000 + AGENT_FOLLOWUP_WAIT_TIMEOUT_MS;
5556

57+
async function callExecApprovalFollowupGateway(
58+
method: "agent" | "agent.wait",
59+
timeoutMs: number,
60+
params: Record<string, unknown>,
61+
): Promise<Record<string, unknown>> {
62+
const gatewayRuntime = getGatewayRecoveryRuntime();
63+
if (gatewayRuntime) {
64+
return method === "agent"
65+
? await gatewayRuntime.dispatchAgent(
66+
params as Parameters<typeof gatewayRuntime.dispatchAgent>[0],
67+
timeoutMs,
68+
)
69+
: await gatewayRuntime.waitForAgent(
70+
params as Parameters<typeof gatewayRuntime.waitForAgent>[0],
71+
timeoutMs,
72+
);
73+
}
74+
return await callGatewayTool(method, { timeoutMs }, params);
75+
}
76+
5677
type ExecApprovalFollowupParams = {
5778
approvalId: string;
5879
sessionKey?: string;
@@ -259,14 +280,10 @@ async function waitForAgentFollowupRun(params: {
259280
const waitTimeoutMs = Math.max(1, Math.min(params.timeoutMs, remainingMs));
260281
let wait: Record<string, unknown>;
261282
try {
262-
wait = await callGatewayTool(
263-
"agent.wait",
264-
{ timeoutMs: waitTimeoutMs + 2_000 },
265-
{
266-
runId: params.runId,
267-
timeoutMs: waitTimeoutMs,
268-
},
269-
);
283+
wait = await callExecApprovalFollowupGateway("agent.wait", waitTimeoutMs + 2_000, {
284+
runId: params.runId,
285+
timeoutMs: waitTimeoutMs,
286+
});
270287
} catch {
271288
// The accepted run remains the sole delivery owner. Keep observing
272289
// across bounded gateway reconnects instead of racing it with direct delivery.
@@ -472,7 +489,7 @@ export async function sendExecApprovalFollowup(
472489
internalRuntimeHandoffId,
473490
idempotencyKey,
474491
});
475-
const accepted = await callGatewayTool("agent", { timeoutMs: 60_000 }, agentArgs);
492+
const accepted = await callExecApprovalFollowupGateway("agent", 60_000, agentArgs);
476493
const status = readGatewayStatus(accepted);
477494
if (isSuccessfulFollowupStatus(status)) {
478495
return true;

‎src/agents/subagents/registry/subagent-control.ts‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import { loadSessionEntry, patchSessionEntry } from "../../../config/sessions/se
1010
import type { SessionEntry } from "../../../config/sessions/types.js";
1111
import type { OpenClawConfig } from "../../../config/types.openclaw.js";
1212
import { callGateway } from "../../../gateway/call.js";
13+
import { getGatewayRecoveryRuntime } from "../../../gateway/server-recovery-runtime-context.js";
1314
import { logVerbose } from "../../../globals.js";
1415
import {
1516
getAgentEventLifecycleGeneration,
@@ -79,8 +80,25 @@ type AbortEmbeddedAgentRun = (sessionId: string) => boolean;
7980
type IsEmbeddedAgentRunActive = (sessionId: string) => boolean;
8081
type ClearSessionQueues = (keys: Array<string | undefined>) => ClearSessionQueueResult;
8182

83+
const callSubagentControlGateway: GatewayCaller = async (request) => {
84+
const gatewayRuntime = getGatewayRecoveryRuntime();
85+
if (gatewayRuntime && request.method === "agent") {
86+
return await gatewayRuntime.dispatchAgent(
87+
request.params as Parameters<typeof gatewayRuntime.dispatchAgent>[0],
88+
request.timeoutMs ?? undefined,
89+
);
90+
}
91+
if (gatewayRuntime && request.method === "agent.wait") {
92+
return await gatewayRuntime.waitForAgent(
93+
request.params as Parameters<typeof gatewayRuntime.waitForAgent>[0],
94+
request.timeoutMs ?? undefined,
95+
);
96+
}
97+
return await callGateway(request);
98+
};
99+
82100
const defaultSubagentControlDeps = {
83-
callGateway,
101+
callGateway: callSubagentControlGateway,
84102
patchSessionEntry,
85103
};
86104

‎src/agents/subagents/registry/subagent-registry-restore.ts‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -245,14 +245,24 @@ export function createSubagentRegistryRestorer(config: {
245245
start: async () => {
246246
await runWithGatewayIndependentRootWorkAdmission(async () => {
247247
launchLifecycleGeneration = getAgentEventLifecycleGeneration();
248-
const response = await deps().callGateway({
248+
const request = {
249249
method: "agent",
250250
params: applySubagentLaunchAuthorization(launch.request, launch.authorization),
251251
// Restart replay must restore the trusted launch capability; otherwise
252252
// the queued child silently falls back to its session/default route.
253253
...(launch.authorization ? { scopes: [ADMIN_SCOPE] } : {}),
254254
timeoutMs: launch.timeoutMs,
255-
});
255+
};
256+
const gatewayRuntime = deps().getGatewayRecoveryRuntime();
257+
const response = gatewayRuntime
258+
? await gatewayRuntime.dispatchAgent(
259+
request.params as Parameters<typeof gatewayRuntime.dispatchAgent>[0],
260+
request.timeoutMs,
261+
launch.authorization
262+
? { allowModelOverride: true, scopes: [ADMIN_SCOPE] }
263+
: undefined,
264+
)
265+
: await deps().callGateway(request);
256266
const gatewayRunId = readGatewayRunId(response) ?? runId;
257267
try {
258268
if (!startQueuedSubagentRun(runId, gatewayRunId, launchLifecycleGeneration)) {

‎src/agents/subagents/registry/subagent-registry.test.ts‎

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,15 @@ async function expectPathMissing(targetPath: string): Promise<void> {
100100
}
101101

102102
const mocks = vi.hoisted(() => ({
103-
callGateway: vi.fn<(request: { method?: string }) => Promise<Record<string, unknown>>>(),
103+
callGateway:
104+
vi.fn<
105+
(request: {
106+
method?: string;
107+
params?: Record<string, unknown>;
108+
scopes?: string[];
109+
timeoutMs?: number | null;
110+
}) => Promise<Record<string, unknown>>
111+
>(),
104112
onAgentEvent: vi.fn<(_handler: (event: AgentEventPayload) => void) => typeof noop>(() => noop),
105113
getAgentRunContext: vi.fn<(_runId: string) => unknown>(() => undefined),
106114
getRuntimeConfig: vi.fn<() => OpenClawConfig>(() => ({
@@ -197,7 +205,7 @@ const mocks = vi.hoisted(() => ({
197205
runSubagentEnded: vi.fn(async () => {}),
198206
removeInternalSessionEffectsSession: vi.fn(async () => {}),
199207
resolveAgentTimeoutMs: vi.fn(() => 1_000),
200-
dispatchRecoveryAgent: vi.fn(async () => ({ runId: "recovered-run" })),
208+
dispatchRecoveryAgent: vi.fn(),
201209
getGatewayRecoveryRuntime: vi.fn(() => ({
202210
dispatchAgent: mocks.dispatchRecoveryAgent as GatewayRecoveryRuntime["dispatchAgent"],
203211
waitForAgent: vi.fn(),
@@ -495,7 +503,7 @@ describe("subagent registry seam flow", () => {
495503
mocks.runSubagentEnded.mockImplementation(async () => {
496504
expect(getPluginRuntimeGatewayRequestScope()?.pluginRegistry).toBe(pluginRegistry);
497505
});
498-
mocks.dispatchRecoveryAgent.mockReset().mockResolvedValue({ runId: "recovered-run" });
506+
mocks.dispatchRecoveryAgent.mockReset();
499507
mocks.resolveAgentTimeoutMs.mockReturnValue(1_000);
500508
mocks.getSubagentRunsSnapshotForChildSession
501509
.mockReset()
@@ -510,6 +518,14 @@ describe("subagent registry seam flow", () => {
510518
endedAt: 222,
511519
},
512520
});
521+
mocks.dispatchRecoveryAgent.mockImplementation(async (params, timeoutMs, options) =>
522+
mocks.callGateway({
523+
method: "agent",
524+
params: params as unknown as Record<string, unknown>,
525+
timeoutMs,
526+
...(options?.scopes ? { scopes: options.scopes } : {}),
527+
}),
528+
);
513529
mod.testing.setDepsForTest({
514530
callGateway: mocks.callGateway as typeof import("../../../gateway/call.js").callGateway,
515531
captureSubagentCompletionReply: mocks.captureSubagentCompletionReply,

‎src/agents/subagents/spawn/acp-spawn.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@ import {
1414
import { buildSessionCreationStamp } from "../../../config/sessions/session-entry-provenance.js";
1515
import type { SessionEntry } from "../../../config/sessions/types.js";
1616
import type { OpenClawConfig } from "../../../config/types.openclaw.js";
17-
import { callGateway } from "../../../gateway/call.js";
1817
import { formatErrorMessage } from "../../../infra/errors.js";
1918
import { resolveEventSessionRoutingPolicy } from "../../../infra/event-session-routing.js";
2019
import {
@@ -92,6 +91,7 @@ import {
9291
isSubagentEnvelopeSession,
9392
resolveSubagentCapabilityStore,
9493
} from "./subagent-capabilities.js";
94+
import { callSubagentGateway, readGatewayRunId } from "./subagent-spawn-gateway.js";
9595
import { resolveSubagentSpawnOwnership } from "./subagent-spawn-ownership.js";
9696
import { resolveConfiguredSubagentRunTimeoutSeconds } from "./subagent-spawn-plan.js";
9797

@@ -594,7 +594,7 @@ export async function spawnAcpDirect(
594594
cfg,
595595
});
596596
}
597-
const response = await callGateway({
597+
const response = await callSubagentGateway({
598598
method: "agent",
599599
params: {
600600
message: params.task,
@@ -613,7 +613,7 @@ export async function spawnAcpDirect(
613613
},
614614
timeoutMs: 10_000,
615615
});
616-
const runId = normalizeOptionalString(response?.runId) ?? childIdem;
616+
const runId = readGatewayRunId(response) ?? childIdem;
617617
if (state.parentRelay && runId !== childIdem && parentSessionKey) {
618618
state.parentRelay.dispose();
619619
state.parentRelay = startAcpSpawnParentStreamRelay({

‎src/agents/tools/in-process-gateway.ts‎

Lines changed: 20 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ type AgentToolGatewayRequest = Pick<
2525
| "onSignalAbort"
2626
| "params"
2727
| "signal"
28+
| "scopes"
2829
| "timeoutMs"
2930
>;
3031

@@ -54,30 +55,32 @@ export const callAgentToolGatewayRequest: AgentToolGatewayRequestCaller = async
5455
const { callGateway } = await import("../../gateway/call.js");
5556
return await callGateway<T>(request);
5657
}
57-
const scopes = resolveLeastPrivilegeOperatorScopesForMethod(request.method, request.params);
58+
const scopes =
59+
request.scopes ?? resolveLeastPrivilegeOperatorScopesForMethod(request.method, request.params);
5860
const timeoutMs =
5961
request.timeoutMs === null
6062
? undefined
6163
: (request.timeoutMs ?? DEFAULT_IN_PROCESS_GATEWAY_REQUEST_TIMEOUT_MS);
64+
const dispatchOptions = {
65+
forceSyntheticClient: true,
66+
syntheticScopes: scopes,
67+
...(request.expectFinal !== undefined ? { expectFinal: request.expectFinal } : {}),
68+
...(request.onAccepted ? { onAccepted: request.onAccepted } : {}),
69+
...(request.onSignalAbort
70+
? {
71+
onSignalAbort: () =>
72+
request.onSignalAbort?.((method, params, options) =>
73+
callAgentToolGatewayRequest({ method, params, ...options }),
74+
),
75+
}
76+
: {}),
77+
...(request.signal ? { signal: request.signal } : {}),
78+
...(timeoutMs !== undefined ? { timeoutMs } : {}),
79+
};
6280
return await dispatchGatewayMethodInProcess<T>(
6381
request.method,
6482
(request.params ?? {}) as Record<string, unknown>,
65-
{
66-
forceSyntheticClient: true,
67-
syntheticScopes: scopes,
68-
...(request.expectFinal !== undefined ? { expectFinal: request.expectFinal } : {}),
69-
...(request.onAccepted ? { onAccepted: request.onAccepted } : {}),
70-
...(request.onSignalAbort
71-
? {
72-
onSignalAbort: () =>
73-
request.onSignalAbort?.((method, params, options) =>
74-
callAgentToolGatewayRequest({ method, params, ...options }),
75-
),
76-
}
77-
: {}),
78-
...(request.signal ? { signal: request.signal } : {}),
79-
...(timeoutMs !== undefined ? { timeoutMs } : {}),
80-
},
83+
dispatchOptions,
8184
);
8285
};
8386

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export { createInternalAgentTurnFacade } from "./internal-facade.js";
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
import { beforeEach, describe, expect, it, vi } from "vitest";
2+
import type { GatewayRequestContext } from "../server-methods/types.js";
3+
import { createSyntheticPluginRuntimeClient } from "../server-plugin-runtime-client.js";
4+
import { createInternalAgentTurnFacade } from "./internal-facade.js";
5+
6+
const startTurn = vi.hoisted(() => vi.fn());
7+
8+
vi.mock("../server-methods.js", () => ({
9+
authorizeGatewayRequestPreDispatch: async () => ({ error: null }),
10+
createRequestGatewayMethodRegistry: () => ({
11+
isControlPlaneWrite: () => false,
12+
}),
13+
runWithGatewayRequestEnvelope: async (
14+
_method: string,
15+
_client: unknown,
16+
run: () => Promise<unknown>,
17+
) => await run(),
18+
}));
19+
20+
vi.mock("./agent-request-preflight.js", () => ({
21+
prepareAgentRequestPreflight: ({ request }: { request: unknown }) => ({ request }),
22+
}));
23+
24+
vi.mock("./agent-turn-service.js", () => ({
25+
createAgentTurnService: () => ({
26+
startTurn,
27+
waitForTurn: vi.fn(),
28+
}),
29+
}));
30+
31+
function createFacade() {
32+
return createInternalAgentTurnFacade({
33+
client: createSyntheticPluginRuntimeClient(),
34+
getContext: () =>
35+
({
36+
dedupe: new Map(),
37+
getRuntimeConfig: () => ({}),
38+
logGateway: { error: vi.fn(), warn: vi.fn() },
39+
}) as unknown as GatewayRequestContext,
40+
});
41+
}
42+
43+
describe("createInternalAgentTurnFacade", () => {
44+
beforeEach(() => {
45+
startTurn.mockReset();
46+
});
47+
48+
it("preserves accepted/final ordering and acceptance metadata without frames", async () => {
49+
let emitFinal!: () => void;
50+
const finalGate = new Promise<void>((resolve) => {
51+
emitFinal = resolve;
52+
});
53+
startTurn.mockImplementation(async ({ io }) => {
54+
io.emitAcceptance([true, { runId: "run-1", status: "accepted" }, undefined], {
55+
runId: "run-1",
56+
});
57+
await finalGate;
58+
io.emitFinal([true, { runId: "run-1", status: "ok", summary: "done" }, undefined], {
59+
runId: "run-1",
60+
terminal: true,
61+
});
62+
});
63+
const onAccepted = vi.fn();
64+
65+
const result = createFacade().dispatchRaw(
66+
{ message: "test", idempotencyKey: "run-1" },
67+
{ expectFinal: true, onAccepted },
68+
);
69+
await vi.waitFor(() =>
70+
expect(onAccepted).toHaveBeenCalledWith({
71+
runId: "run-1",
72+
status: "accepted",
73+
}),
74+
);
75+
emitFinal();
76+
77+
await expect(result).resolves.toEqual({
78+
ok: true,
79+
payload: { runId: "run-1", status: "ok", summary: "done" },
80+
error: undefined,
81+
meta: { runId: "run-1", terminal: true },
82+
});
83+
});
84+
85+
it("returns a single acceptance with its metadata when no final is requested", async () => {
86+
startTurn.mockImplementation(async ({ io }) => {
87+
io.emitAcceptance([true, { runId: "run-2", status: "in_flight" }, undefined], {
88+
cached: true,
89+
runId: "run-2",
90+
});
91+
});
92+
93+
await expect(
94+
createFacade().dispatchRaw({ message: "test", idempotencyKey: "run-2" }),
95+
).resolves.toEqual({
96+
ok: true,
97+
payload: { runId: "run-2", status: "in_flight" },
98+
error: undefined,
99+
meta: { cached: true, runId: "run-2" },
100+
});
101+
});
102+
});

0 commit comments

Comments
 (0)