Skip to content

Commit 23da04b

Browse files
fix(sessions): require durable final reply evidence (#126075)
* fix(sessions): require durable final reply evidence * fix(sessions): enforce durable terminal reply evidence --------- Co-authored-by: Jason (Json) <[email protected]>
1 parent 64776a0 commit 23da04b

14 files changed

Lines changed: 232 additions & 65 deletions

‎src/agents/agent-run-terminal-reply.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ export function buildAgentRunTerminalReplySnapshot(params: {
3535
}): AgentRunTerminalReplySnapshot {
3636
if (
3737
params.terminalReplyKind === "silent-empty" ||
38-
isSilentReplyText(params.rawText, SILENT_REPLY_TOKEN)
38+
isSilentReplyText(params.rawText ?? params.visibleText, SILENT_REPLY_TOKEN)
3939
) {
4040
return { disposition: "silent" };
4141
}

‎src/agents/embedded-agent-runner/run-entry.test.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -839,6 +839,11 @@ describe("runEmbeddedAgentEntry", () => {
839839
meta: { finalAssistantVisibleText: "NO_REPLY...", finalAssistantRawText: "NO_REPLY..." },
840840
expected: { disposition: "silent" },
841841
},
842+
{
843+
name: "normalized silence without raw text",
844+
meta: { finalAssistantVisibleText: "no_reply" },
845+
expected: { disposition: "silent" },
846+
},
842847
{
843848
name: "clean empty reply",
844849
meta: {},

‎src/agents/run-wait.test.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -716,6 +716,28 @@ describe("waitForAgentRunAndReadUpdatedAssistantReply", () => {
716716
});
717717
expect(callGatewayMock.mock.calls.map(([request]) => request.method)).toEqual(["agent.wait"]);
718718
});
719+
720+
it.each(["silent", "empty"] as const)(
721+
"does not resurrect transcript text after an authoritative %s terminal reply",
722+
async (disposition) => {
723+
callGatewayMock.mockImplementation(async (request) => {
724+
if (request.method === "agent.wait") {
725+
return { status: "ok", terminalReply: { disposition } };
726+
}
727+
throw new Error("history must not override terminal reply evidence");
728+
});
729+
730+
const result = await waitForAgentRunAndReadUpdatedAssistantReply({
731+
runId: `run-${disposition}-terminal-reply`,
732+
sessionKey: "agent:main:child",
733+
timeoutMs: 1_000,
734+
baseline: { text: "older reply" },
735+
});
736+
737+
expect(result).toEqual({ status: "ok", terminalReply: { disposition } });
738+
expect(callGatewayMock.mock.calls.map(([request]) => request.method)).toEqual(["agent.wait"]);
739+
},
740+
);
719741
});
720742

721743
describe("waitForAgentRunsToDrain", () => {

‎src/agents/run-wait.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -428,8 +428,10 @@ export async function waitForAgentRunAndReadUpdatedAssistantReply(params: {
428428
if (wait.status !== "ok") {
429429
return wait;
430430
}
431-
if (wait.terminalReply?.disposition === "visible") {
432-
return { ...wait, replyText: wait.terminalReply.text };
431+
if (wait.terminalReply) {
432+
return wait.terminalReply.disposition === "visible"
433+
? { ...wait, replyText: wait.terminalReply.text }
434+
: wait;
433435
}
434436

435437
const latestReply = await readLatestAssistantReplySnapshot({

‎src/agents/subagents/announce/subagent-announce-output.test.ts‎

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -226,7 +226,7 @@ describe("readSubagentOutput", () => {
226226
);
227227
});
228228

229-
it("returns only the latest assistant turn, not trailing tool output", async () => {
229+
it("does not reuse assistant progress that issued a trailing tool call", async () => {
230230
installOutputDeps({
231231
messages: [
232232
{
@@ -244,12 +244,10 @@ describe("readSubagentOutput", () => {
244244
],
245245
});
246246

247-
await expect(readSubagentOutput("agent:main:subagent:child")).resolves.toBe(
248-
"Mapped the code path.",
249-
);
247+
await expect(readSubagentOutput("agent:main:subagent:child")).resolves.toBeUndefined();
250248
});
251249

252-
it("keeps earlier visible assistant text across a trailing empty assistant turn", async () => {
250+
it("does not keep earlier visible progress across a trailing tool-only turn", async () => {
253251
installOutputDeps({
254252
messages: [
255253
{
@@ -268,8 +266,30 @@ describe("readSubagentOutput", () => {
268266
],
269267
});
270268

269+
await expect(readSubagentOutput("agent:main:subagent:child")).resolves.toBeUndefined();
270+
});
271+
272+
it("returns a final assistant reply emitted after trailing tool activity", async () => {
273+
installOutputDeps({
274+
messages: [
275+
{
276+
role: "assistant",
277+
content: [
278+
{ type: "text", text: "Mapped the code path." },
279+
{ type: "toolCall", id: "call-read", name: "read", arguments: {} },
280+
],
281+
},
282+
{ role: "toolResult", content: "tool result" },
283+
{
284+
role: "assistant",
285+
stopReason: "stop",
286+
content: [{ type: "text", text: "The fix is complete." }],
287+
},
288+
],
289+
});
290+
271291
await expect(readSubagentOutput("agent:main:subagent:child")).resolves.toBe(
272-
"Mapped the code path.",
292+
"The fix is complete.",
273293
);
274294
});
275295

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

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -188,10 +188,20 @@ function summarizeSubagentOutputHistory(messages: Array<unknown>): SubagentOutpu
188188
previousAssistantCalledYield = true;
189189
continue;
190190
}
191+
const toolCallCount = countAssistantToolCalls(message);
192+
if (toolCallCount > 0) {
193+
// Any assistant tool call proves this was an intermediate turn. Do not
194+
// retain commentary from this message or an earlier assistant message
195+
// as the run's final result if execution ends before the next reply.
196+
snapshot.latestAssistantText = undefined;
197+
snapshot.latestSilentText = undefined;
198+
snapshot.latestToolCallCount = (snapshot.latestToolCallCount ?? 0) + toolCallCount;
199+
snapshot.waitingForContinuation = false;
200+
previousAssistantCalledYield = false;
201+
continue;
202+
}
191203
const text = extractSubagentAssistantText(message).trim();
192204
if (!text) {
193-
snapshot.latestToolCallCount =
194-
(snapshot.latestToolCallCount ?? 0) + countAssistantToolCalls(message);
195205
snapshot.waitingForContinuation = false;
196206
previousAssistantCalledYield = false;
197207
continue;

‎src/agents/subagents/announce/subagent-announce.timeout.test.ts‎

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -589,7 +589,7 @@ describe("subagent announce timeout config", () => {
589589
expect(directAgentCall?.params?.message).not.toContain("older fallback");
590590
});
591591

592-
it("preserves NO_REPLY when timeout history ends with silence after earlier progress", async () => {
592+
it("does not let pre-tool NO_REPLY hide a later timeout", async () => {
593593
chatHistoryMessages = [
594594
{
595595
role: "assistant",
@@ -613,7 +613,10 @@ describe("subagent announce timeout config", () => {
613613
roundOneReply: undefined,
614614
});
615615

616-
expect(findFinalDirectAgentCall()).toBeUndefined();
616+
const directAgentCall = findFinalDirectAgentCall();
617+
const internalEvents =
618+
(directAgentCall?.params?.internalEvents as Array<{ result?: string }>) ?? [];
619+
expect(internalEvents[0]?.result).toBe("2 tool call(s) made without visible output.");
617620
});
618621

619622
it("prefers visible assistant progress over a later raw tool result", async () => {
@@ -640,7 +643,7 @@ describe("subagent announce timeout config", () => {
640643
expect(internalEvents[0]?.result).not.toContain("grep output");
641644
});
642645

643-
it("preserves NO_REPLY when timeout partial-progress history mixes prior text and later silence", async () => {
646+
it("reports tool progress when a later tool invalidates timeout silence", async () => {
644647
chatHistoryMessages = [
645648
...createTimeoutHistoryWithNoReply(),
646649
{
@@ -654,9 +657,12 @@ describe("subagent announce timeout config", () => {
654657
roundOneReply: undefined,
655658
});
656659

657-
expect(
658-
findGatewayCall((call) => call.method === "agent" && call.expectFinal === true),
659-
).toBeUndefined();
660+
const directAgentCall = findGatewayCall(
661+
(call) => call.method === "agent" && call.expectFinal === true,
662+
);
663+
const internalEvents =
664+
(directAgentCall?.params?.internalEvents as Array<{ result?: string }>) ?? [];
665+
expect(internalEvents[0]?.result).toBe("2 tool call(s) made without visible output.");
660666
});
661667

662668
it("prefers later visible assistant progress over an earlier NO_REPLY marker", async () => {

‎src/agents/subagents/registry/subagent-registry-lifecycle-completion.ts‎

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,8 @@ import {
3636
type BrowserCleanupModule = typeof import("../../../browser-lifecycle-cleanup.js");
3737
type BrowserCleanup = BrowserCleanupModule["cleanupBrowserSessionsForLifecycleEnd"];
3838

39+
const MISSING_REQUIRED_FINAL_REPLY_ERROR = "subagent run ended before producing a final reply";
40+
3941
const browserCleanupLoader = createLazyImportLoader<BrowserCleanupModule>(
4042
() => import("../../../browser-lifecycle-cleanup.js"),
4143
);
@@ -413,6 +415,20 @@ export async function completeSubagentRunAttempt(
413415
mutated = true;
414416
}
415417
}
418+
const terminalReply = mergeAgentRunTerminalReplySnapshot(
419+
entry.completion?.terminalReply,
420+
completeParams.terminalReply,
421+
);
422+
// Lifecycle events and agent.wait both settle here. A required success
423+
// needs producer evidence before any transcript fallback can freeze it.
424+
if (
425+
entry.expectsCompletionMessage === true &&
426+
completionOutcome.status === "ok" &&
427+
!terminalReply
428+
) {
429+
completionOutcome = { status: "error", error: MISSING_REQUIRED_FINAL_REPLY_ERROR };
430+
completionReason = SUBAGENT_ENDED_REASON_ERROR;
431+
}
416432
const outcome =
417433
recoveryRequested && entry.execution.outcome
418434
? entry.execution.outcome
@@ -466,16 +482,9 @@ export async function completeSubagentRunAttempt(
466482
}
467483
}
468484

469-
if (completeParams.terminalReply) {
485+
if (terminalReply) {
470486
const completion = ensureCompletionState(entry);
471-
const terminalReply = mergeAgentRunTerminalReplySnapshot(
472-
completion.terminalReply,
473-
completeParams.terminalReply,
474-
);
475-
if (
476-
terminalReply &&
477-
JSON.stringify(terminalReply) !== JSON.stringify(completion.terminalReply)
478-
) {
487+
if (JSON.stringify(terminalReply) !== JSON.stringify(completion.terminalReply)) {
479488
completion.terminalReply = terminalReply;
480489
completion.resultText =
481490
terminalReply.disposition === "visible"

0 commit comments

Comments
 (0)