Skip to content

Commit 10b2956

Browse files
roboclaw-botVACInc
andauthored
fix(agents): settle yielded CLI session spawns (#134974)
Co-authored-by: roboclaw-bot <[email protected]> Co-authored-by: Vito Cappello <[email protected]>
1 parent c6a2bce commit 10b2956

21 files changed

Lines changed: 378 additions & 143 deletions

‎extensions/copilot/src/attempt-config.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ export { toCopilotError };
3333
export function createResult(
3434
params: AttemptParamsLike,
3535
state: {
36+
acceptedSessionSpawns?: AgentHarnessAttemptResult["acceptedSessionSpawns"];
3637
aborted?: boolean;
3738
assistantTranscriptOwned?: boolean;
3839
assistantTranscriptIdempotencyKey?: string;
@@ -100,6 +101,9 @@ export function createResult(
100101
promptError !== undefined ? withPromptFailure(interruption, promptError) : interruption;
101102
return {
102103
terminal,
104+
...(state.acceptedSessionSpawns?.length
105+
? { acceptedSessionSpawns: state.acceptedSessionSpawns }
106+
: {}),
103107
...(state.assistantTranscriptOwned
104108
? {
105109
assistantTranscriptOwned: true,

‎extensions/copilot/src/attempt-execution.ts‎

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,10 @@ import {
1212
runAgentHarnessBeforeCompactionHook,
1313
clearActiveEmbeddedRun,
1414
} from "openclaw/plugin-sdk/agent-harness-runtime";
15+
import {
16+
asOptionalRecord,
17+
normalizeOptionalString,
18+
} from "openclaw/plugin-sdk/string-coerce-runtime";
1519
import { registerCopilotActiveRun } from "./attempt-active-run.js";
1620
import { deferBackgroundCompactionCleanup } from "./attempt-cleanup.js";
1721
import {
@@ -121,6 +125,7 @@ export async function runCopilotExecution(context: {
121125
let resumeFailureRecovered = false;
122126
let yieldDetected = false;
123127
let yieldAcknowledgment: string | undefined;
128+
const acceptedSessionSpawns: NonNullable<AgentHarnessAttemptResult["acceptedSessionSpawns"]> = [];
124129
let lastToolError: AgentHarnessAttemptResult["lastToolError"];
125130
const hostObserveToolTerminal = input.observeToolTerminal;
126131
const observeToolTerminal = hostObserveToolTerminal
@@ -278,8 +283,24 @@ export async function runCopilotExecution(context: {
278283
yieldDetected = true;
279284
yieldAcknowledgment = acknowledgment;
280285
},
281-
onToolCompleted: ({ args, error, result, startedAt, toolCallId, toolName }) =>
282-
runAgentHarnessAfterToolCallHook({
286+
onToolCompleted: async ({ args, error, result, startedAt, toolCallId, toolName }) => {
287+
const acceptedSessionSpawnDetails =
288+
toolName === "sessions_spawn" && !error
289+
? asOptionalRecord(asOptionalRecord(result)?.details)
290+
: undefined;
291+
const runId = normalizeOptionalString(acceptedSessionSpawnDetails?.runId);
292+
const childSessionKey = normalizeOptionalString(
293+
acceptedSessionSpawnDetails?.childSessionKey,
294+
);
295+
if (acceptedSessionSpawnDetails?.status === "accepted" && runId && childSessionKey) {
296+
acceptedSessionSpawns.push({
297+
runId,
298+
childSessionKey,
299+
expectsCompletionMessage:
300+
acceptedSessionSpawnDetails.expectsCompletionMessage === true,
301+
});
302+
}
303+
await runAgentHarnessAfterToolCallHook({
283304
toolName,
284305
toolCallId,
285306
runId: input.runId,
@@ -291,7 +312,8 @@ export async function runCopilotExecution(context: {
291312
...(result !== undefined ? { result } : {}),
292313
...(error ? { error } : {}),
293314
startedAt,
294-
}),
315+
});
316+
},
295317
});
296318
cleanupToolBridge = toolBridge.cleanup;
297319
codeModeEngaged = toolBridge.codeModeEngaged;
@@ -635,6 +657,7 @@ export async function runCopilotExecution(context: {
635657
}
636658
}
637659
return await completeCopilotAttempt({
660+
acceptedSessionSpawns,
638661
aborted,
639662
attemptStartedAt,
640663
bridge,

‎extensions/copilot/src/attempt-finalize.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import type {
1515
} from "./attempt-types.js";
1616
import { attachEventBridge } from "./event-bridge.js";
1717
export async function completeCopilotAttempt(params: {
18+
acceptedSessionSpawns: NonNullable<AgentHarnessAttemptResult["acceptedSessionSpawns"]>;
1819
aborted: boolean;
1920
attemptStartedAt: number;
2021
bridge: ReturnType<typeof attachEventBridge> | undefined;
@@ -47,6 +48,7 @@ export async function completeCopilotAttempt(params: {
4748
yieldAcknowledgment?: string;
4849
}): Promise<AgentHarnessAttemptResult> {
4950
const {
51+
acceptedSessionSpawns,
5052
aborted,
5153
attemptStartedAt,
5254
bridge,
@@ -93,6 +95,7 @@ export async function completeCopilotAttempt(params: {
9395
currentRunUserKey,
9496
));
9597
const result = createResult(input, {
98+
acceptedSessionSpawns,
9699
aborted,
97100
assistantTexts,
98101
codeModeEngaged,

‎extensions/copilot/src/attempt.test.ts‎

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1885,11 +1885,34 @@ describe("runCopilotAttempt", () => {
18851885
expect(capturedParams).toBe(params);
18861886
});
18871887

1888-
it("F7: result.yieldDetected is true when the tool bridge fires onYieldDetected during the attempt", async () => {
1888+
it("F7: preserves an accepted session spawn when the tool bridge yields the attempt", async () => {
18891889
const sdk = makeFakeSdk();
18901890
const pool = makeFakePool(sdk);
18911891
const createToolBridge = vi.fn(
1892-
async (input: { onYieldDetected?: (message?: string, acknowledgment?: string) => void }) => {
1892+
async (input: {
1893+
onToolCompleted?: (completion: {
1894+
args: Record<string, unknown>;
1895+
result: unknown;
1896+
startedAt: number;
1897+
toolCallId: string;
1898+
toolName: string;
1899+
}) => void | Promise<void>;
1900+
onYieldDetected?: (message?: string, acknowledgment?: string) => void;
1901+
}) => {
1902+
await input.onToolCompleted?.({
1903+
args: { task: "review" },
1904+
result: {
1905+
details: {
1906+
status: "accepted",
1907+
runId: "run-copilot-child",
1908+
childSessionKey: "agent:main:subagent:copilot-child",
1909+
expectsCompletionMessage: true,
1910+
},
1911+
},
1912+
startedAt: Date.now(),
1913+
toolCallId: "spawn-1",
1914+
toolName: "sessions_spawn",
1915+
});
18931916
// Simulate a wrapped tool invoking sessions_yield before the
18941917
// attempt settles. The bridge is responsible for notifying the
18951918
// caller via onYieldDetected so the final result can carry the
@@ -1907,6 +1930,13 @@ describe("runCopilotAttempt", () => {
19071930

19081931
expect(result.yieldDetected).toBe(true);
19091932
expect(result.yieldAcknowledgment).toBe("Research started; results will follow.");
1933+
expect(result.acceptedSessionSpawns).toEqual([
1934+
{
1935+
runId: "run-copilot-child",
1936+
childSessionKey: "agent:main:subagent:copilot-child",
1937+
expectsCompletionMessage: true,
1938+
},
1939+
]);
19101940
});
19111941

19121942
it("F7: result.yieldDetected is false on a clean attempt (no sessions_yield fired)", async () => {

‎src/agents/cli-output-contracts.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import type {
33
CliBackendJsonlUsage,
44
CliBackendParseJsonlEvent,
55
} from "../plugins/cli-backend.types.js";
6+
import type { AcceptedSessionSpawn } from "./accepted-session-spawn.js";
67
import type {
78
MessagingToolSend,
89
MessagingToolSourceReplyPayload,
@@ -64,6 +65,8 @@ export type CliOutput = {
6465
toolMediaUrls?: string[];
6566
toolAudioAsVoice?: boolean;
6667
toolTrustedLocalMedia?: boolean;
68+
/** Child sessions accepted by the turn-scoped loopback tool capture. */
69+
acceptedSessionSpawns?: AcceptedSessionSpawn[];
6770
yielded?: true;
6871
yieldAcknowledgment?: string;
6972
};

‎src/agents/cli-runner.reliability.test.ts‎

Lines changed: 83 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2497,32 +2497,106 @@ describe("runCliAgent reliability", () => {
24972497
expect(result.meta.agentMeta?.contextTokens).toBe(150_000);
24982498
});
24992499

2500-
it("marks CLI runs as paused after sessions_yield", async () => {
2500+
it("returns accepted CLI session spawns when sessions_yield pauses the requester", async () => {
2501+
const requesterTurnRunId = "run-cli-yield";
2502+
const childRunId = "run-cli-child";
2503+
const childSessionKey = "agent:main:subagent:cli-child";
25012504
supervisorSpawnMock.mockImplementationOnce(async (...args: unknown[]) => {
25022505
const input = args[0] as Parameters<ReturnType<typeof getProcessSupervisor>["spawn"]>[0];
2506+
const spawnCapture = markMcpLoopbackToolCallStarted({
2507+
captureKey: input.env?.OPENCLAW_MCP_CLI_CAPTURE_KEY,
2508+
toolName: "sessions_spawn",
2509+
args: { task: "review" },
2510+
});
2511+
if (!spawnCapture) {
2512+
throw new Error("missing sessions_spawn capture");
2513+
}
2514+
recordMcpLoopbackToolCallResult({
2515+
captureHandle: spawnCapture,
2516+
toolName: "sessions_spawn",
2517+
args: { task: "review" },
2518+
outcome: "completed",
2519+
result: {
2520+
details: {
2521+
status: "accepted",
2522+
runId: childRunId,
2523+
childSessionKey,
2524+
expectsCompletionMessage: true,
2525+
},
2526+
},
2527+
});
2528+
markMcpLoopbackToolCallFinished(spawnCapture);
25032529
const captureHandle = markMcpLoopbackRequestStarted(input.env?.OPENCLAW_MCP_CLI_CAPTURE_KEY);
25042530
await resolveMcpLoopbackYieldContext(captureHandle)?.onYield("waiting on subagents");
25052531
markMcpLoopbackRequestFinished(captureHandle);
25062532
input.onStdout?.("yield acknowledged");
25072533
return makeManagedRun();
25082534
});
2509-
const context = buildPreparedContext();
2535+
const context = buildPreparedContext({
2536+
sessionKey: "agent:main:main",
2537+
runId: requesterTurnRunId,
2538+
});
25102539
context.mcpDeliveryCapture = true;
25112540

25122541
const result = await runPreparedCliAgent(context);
25132542

2514-
expect(result.meta).toMatchObject({
2515-
yielded: true,
2516-
livenessState: "paused",
2517-
stopReason: "end_turn",
2518-
completion: {
2519-
finishReason: "end_turn",
2543+
expect(result).toMatchObject({
2544+
acceptedSessionSpawns: [
2545+
{ runId: childRunId, childSessionKey, expectsCompletionMessage: true },
2546+
],
2547+
meta: {
2548+
yielded: true,
2549+
livenessState: "paused",
25202550
stopReason: "end_turn",
2521-
refusal: false,
2551+
completion: {
2552+
finishReason: "end_turn",
2553+
stopReason: "end_turn",
2554+
refusal: false,
2555+
},
25222556
},
25232557
});
25242558
});
25252559

2560+
it.each([
2561+
["rejected", { details: { status: "rejected", error: "not accepted" } }],
2562+
["malformed accepted", { details: { status: "accepted", runId: "run-without-session" } }],
2563+
] as const)("does not retain a %s CLI session spawn", async (_label, spawnResult) => {
2564+
supervisorSpawnMock.mockImplementationOnce(async (...args: unknown[]) => {
2565+
const input = args[0] as Parameters<ReturnType<typeof getProcessSupervisor>["spawn"]>[0];
2566+
const spawnCapture = markMcpLoopbackToolCallStarted({
2567+
captureKey: input.env?.OPENCLAW_MCP_CLI_CAPTURE_KEY,
2568+
toolName: "sessions_spawn",
2569+
args: { task: "review" },
2570+
});
2571+
if (!spawnCapture) {
2572+
throw new Error("missing sessions_spawn capture");
2573+
}
2574+
recordMcpLoopbackToolCallResult({
2575+
captureHandle: spawnCapture,
2576+
toolName: "sessions_spawn",
2577+
args: { task: "review" },
2578+
outcome: "completed",
2579+
result: spawnResult,
2580+
});
2581+
markMcpLoopbackToolCallFinished(spawnCapture);
2582+
const yieldCapture = markMcpLoopbackRequestStarted(input.env?.OPENCLAW_MCP_CLI_CAPTURE_KEY);
2583+
await resolveMcpLoopbackYieldContext(yieldCapture)?.onYield("waiting on subagents");
2584+
markMcpLoopbackRequestFinished(yieldCapture);
2585+
input.onStdout?.("yield acknowledged");
2586+
return makeManagedRun();
2587+
});
2588+
const context = buildPreparedContext({
2589+
sessionKey: "agent:main:main",
2590+
runId: "run-cli-unproven-spawn",
2591+
});
2592+
context.mcpDeliveryCapture = true;
2593+
2594+
const result = await runPreparedCliAgent(context);
2595+
2596+
expect(result.acceptedSessionSpawns).toBeUndefined();
2597+
expect(result.meta).toMatchObject({ yielded: true, livenessState: "paused" });
2598+
});
2599+
25262600
it("seeds fresh CLI sessions from the OpenClaw transcript", async () => {
25272601
supervisorSpawnMock.mockResolvedValueOnce(makeManagedRun({ stdout: "hello from cli" }));
25282602

‎src/agents/cli-runner/cli-run-settlement.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -663,6 +663,9 @@ export function buildCliRunResult(params: {
663663
...(output.messagingToolSourceReplyPayloads?.length
664664
? { messagingToolSourceReplyPayloads: output.messagingToolSourceReplyPayloads }
665665
: {}),
666+
...(output.acceptedSessionSpawns?.length
667+
? { acceptedSessionSpawns: output.acceptedSessionSpawns }
668+
: {}),
666669
};
667670
}
668671

‎src/agents/cli-runner/execute-tool-tracking.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,10 @@ import {
77
waitForMcpLoopbackToolCallCaptureIdle,
88
} from "../../gateway/mcp-http.loopback-runtime.js";
99
import { shouldUseInternalSourceReplySink } from "../../infra/outbound/internal-source-reply.js";
10+
import {
11+
normalizeAcceptedSessionSpawnResult,
12+
type AcceptedSessionSpawn,
13+
} from "../accepted-session-spawn.js";
1014
import type { CliOutput, CliToolUseStartDelta } from "../cli-output-contracts.js";
1115
import { readEmbeddedMessageDeliveryFact } from "../embedded-agent-message-delivery.js";
1216
import {
@@ -98,6 +102,7 @@ export function createCliToolTracking(context: PreparedCliRunContext) {
98102
const toolMediaUrlKeys = new Set<string>();
99103
let toolAudioAsVoice = false;
100104
let toolTrustedLocalMedia = false;
105+
const acceptedSessionSpawns: AcceptedSessionSpawn[] = [];
101106
const matchesCliLoopbackCall = (
102107
toolName: string,
103108
toolArgs: Record<string, unknown>,
@@ -449,6 +454,16 @@ export function createCliToolTracking(context: PreparedCliRunContext) {
449454
markCliLoopbackCallsAmbiguous(candidates);
450455
}
451456
const toolName = normalizeCliMessagingToolName(call.toolName);
457+
const acceptedSessionSpawn =
458+
toolName === "sessions_spawn" && call.outcome === "completed" && "result" in call
459+
? normalizeAcceptedSessionSpawnResult(call.result)
460+
: null;
461+
if (
462+
acceptedSessionSpawn &&
463+
acceptedSessionSpawns.length < CLI_LOOPBACK_CORRELATION_MAX_CALLS
464+
) {
465+
acceptedSessionSpawns.push(acceptedSessionSpawn);
466+
}
452467
if (isMessagingToolDeliveryAction(toolName, call.args)) {
453468
commitMessagingToolResult({
454469
toolName,
@@ -641,6 +656,7 @@ export function createCliToolTracking(context: PreparedCliRunContext) {
641656
toolMediaUrls,
642657
toolAudioAsVoice,
643658
toolTrustedLocalMedia,
659+
acceptedSessionSpawns,
644660
});
645661
return {
646662
beginGatewayCapture,
@@ -676,6 +692,9 @@ export function createCliToolTracking(context: PreparedCliRunContext) {
676692
: {}),
677693
...(current.toolAudioAsVoice ? { toolAudioAsVoice: true } : {}),
678694
...(current.toolTrustedLocalMedia ? { toolTrustedLocalMedia: true } : {}),
695+
...(current.acceptedSessionSpawns.length > 0
696+
? { acceptedSessionSpawns: current.acceptedSessionSpawns.slice() }
697+
: {}),
679698
};
680699
},
681700
attachDeliveryEvidence(error: unknown) {

‎src/agents/command/attempt-execution.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ import { resolveAgentRunAbortLifecycleFields } from "../run-termination.js";
102102
import { buildAgentRuntimeAuthPlan } from "../runtime-plan/auth.js";
103103
import type { AgentMessage } from "../runtime/index.js";
104104
import { resolveSandboxRuntimeStatus } from "../sandbox/runtime-status.js";
105-
import { withLocalSessionPlacementTurnAdmission } from "../session-placement-admission.js";
105+
import { withLocalSessionPlacementTurnSettlement } from "../session-placement-admission.js";
106106
import { buildUsageWithNoCost } from "../stream-message-shared.js";
107107
import {
108108
isSubagentAnnounceCompletionHandoff,
@@ -978,7 +978,7 @@ export function runAgentAttempt(params: {
978978
...mutableCliSessionStore,
979979
}
980980
: undefined;
981-
return withLocalSessionPlacementTurnAdmission(
981+
return withLocalSessionPlacementTurnSettlement(
982982
{
983983
sessionId: params.sessionId,
984984
sessionKey: params.sessionKey ?? params.sessionId,

0 commit comments

Comments
 (0)