Skip to content

Commit db0d133

Browse files
authored
fix(agents): deliver token-limited partial replies instead of discarding them (#123546)
* fix(agents): deliver token-limited partial replies instead of discarding them `isIncompleteTerminalAssistantTurn` accepted `hasAssistantVisibleText` but the `length` branch never read it, so a turn that stopped at the output token limit after emitting visible text was classified incomplete. The whole reply was then replaced with "Agent couldn't generate a response" and the run was marked abandoned. Respect the flag: a `length` stop is incomplete only when there is no visible text and no terminal tool output. A length stop that did produce text now delivers that text with a truncation notice appended, so a cut-off answer is not mistaken for a complete one. * fix(agents): scope the truncation notice and align trajectory status Review follow-up on the token-limited partial reply fix. The truncation notice keyed only on stopReason, so a length stop that also produced terminal output (tool media, a committed source reply) gained an extra text reply telling the user to ask for a continuation. Those turns were already complete before this fix, so the notice now uses the same predicate as the classifier: a length stop with no terminal output. resolveAttemptTrajectoryTerminal() also still recorded a delivered partial reply as non_deliverable_terminal_turn, so durable trajectory state contradicted what the user received. It now uses the same payload-count evidence the terminal owner uses, so a length stop is only non-deliverable when nothing was delivered. A length stop with visible text but no synthesized payload stays an error. * test(agents): flip the lifecycle expectation for delivered length partials handleAgentEnd() no longer marks a length stop with visible text as abandoned and replay-invalid, because that turn is now delivered as a partial reply. The lifecycle test still pinned the old outcome. The sibling case that has pending tool media is unchanged: it still has terminal output, so it stays abandoned. * fix(agents): key length trajectory status on visible text, not payload count The previous guard used synthesizedPayloadCount, which does not include ordinary final assistant text: attempt-result.ts computes it from block replies, tool media, source-reply payloads, and silent-tool payloads, and finalization runs before terminal-preparation.ts turns assistant text into payloads. So an ordinary text-only truncated reply — the case this PR exists to fix — still recorded non_deliverable_terminal_turn while the reply was delivered. Key on visible assistant text instead, which is the fact the delivery owner also keys on and is already resolved at finalization. A length stop with nothing visible to show stays non-deliverable, whitespace-only text included. * test(agents): flip the finalization trajectory case for delivered length partials The attempt-finalize table row for a length stop expected finalStatus "error". Its fixture assistant carries visible text, which resolveTerminalAssistantTexts() promotes to terminal assistant text for a length stop, so that row is a delivered partial reply and must now record success. Renamed to say so. * fix(agents): use the completed assistant message for lifecycle visibility The lifecycle handler derived assistant-visible text only from streamed assistant texts, while terminal payload building falls back to the completed assistant message's visible text when the streamed texts are empty. A non-streamed length stop was therefore delivered to the user and, at the same time, recorded as an abandoned, replay-invalid turn. Give the classifier call site the same canonical fact, keeping the streamed-only view for error and abort stop reasons whose raw text can describe an interrupted generation rather than a reply. * fix(agents): require partial text before appending the truncation notice A cron turn can end with a length stop whose only payload is the synthesized silent result of a successful tool. Gating the notice on terminal-state absence alone appended a visible truncation message to that intentionally silent result. Require nonblank assistant text — streamed or from the terminal assistant message — so the notice only labels prose the user actually received. Also drops .rev3.md, a review transcript committed by accident.
1 parent f69226b commit db0d133

11 files changed

Lines changed: 304 additions & 17 deletions

‎src/agents/embedded-agent-runner/run.incomplete-turn.delivery-resolution.test.ts‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -397,7 +397,7 @@ describe("incomplete-turn delivery resolution", () => {
397397
expect(incompleteTurnText).toContain("couldn't generate a response");
398398
});
399399

400-
it("surfaces incomplete-turn text for token-limited partial answers", () => {
400+
it("keeps token-limited partial answers deliverable", () => {
401401
const incompleteTurnText = resolveIncompleteTurnPayloadText(
402402
makeIncompleteTurnParams(
403403
{
@@ -413,6 +413,25 @@ describe("incomplete-turn delivery resolution", () => {
413413
),
414414
);
415415

416+
expect(incompleteTurnText).toBeNull();
417+
});
418+
419+
it("surfaces incomplete-turn text for token-limited turns with no visible text", () => {
420+
const incompleteTurnText = resolveIncompleteTurnPayloadText(
421+
makeIncompleteTurnParams(
422+
{
423+
assistantTexts: [],
424+
lastAssistant: makeLastAssistant({
425+
stopReason: "length",
426+
provider: "ollama",
427+
model: "qwen3.5",
428+
content: [],
429+
}),
430+
},
431+
{ payloadCount: 0 },
432+
),
433+
);
434+
416435
expect(incompleteTurnText).toContain("couldn't generate a response");
417436
});
418437

‎src/agents/embedded-agent-runner/run/attempt-finalize.media.test.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,10 @@ describe("finalizeEmbeddedAttempt trajectory capture", () => {
5656
it.each<TerminalCase>([
5757
["current over stale", { kind: "ok" }, "stop", "stop", "success", { last: "aborted" }],
5858
["normal completion", { kind: "ok" }, "length", "stop", "success", { completed: "stop" }],
59-
["length truncation", { kind: "ok" }, "length", "length", "error", {}],
59+
// The fixture assistant carries visible text, which resolveTerminalAssistantTexts
60+
// promotes to terminal text for a length stop, so this is a delivered partial
61+
// reply and the trajectory must record it as success.
62+
["length truncation with visible text", { kind: "ok" }, "length", "length", "success", {}],
6063
[
6164
"yield plus prompt timeout",
6265
{ kind: "timeout", phase: "prompt", source: "runtime" },

‎src/agents/embedded-agent-runner/run/attempt-trajectory-status.test.ts‎

Lines changed: 36 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -46,11 +46,30 @@ describe("attempt trajectory status", () => {
4646
).toEqual({ status: "success" });
4747
});
4848

49-
it("marks length-limited visible text as non-deliverable without terminal output", () => {
49+
it("records length-limited visible text as success with no synthesized payload", () => {
50+
// The headline case: an ordinary text-only truncated reply. Finalization runs
51+
// before terminal preparation converts assistant text into payloads, so
52+
// synthesizedPayloadCount is still 0 here while the reply is delivered. The
53+
// durable record must not contradict that.
5054
expect(
5155
resolveAttemptTrajectoryTerminal(
5256
baseParams({
5357
assistantTexts: ["Partial answer."],
58+
synthesizedPayloadCount: 0,
59+
lastAssistantStopReason: "length",
60+
}),
61+
),
62+
).toEqual({ status: "success" });
63+
});
64+
65+
it("keeps a length-limited turn with nothing to show non-deliverable", () => {
66+
// No visible text, no payload, no terminal output: nothing reached the user,
67+
// so this stays the incomplete-turn error the runner still surfaces.
68+
expect(
69+
resolveAttemptTrajectoryTerminal(
70+
baseParams({
71+
assistantTexts: [],
72+
synthesizedPayloadCount: 0,
5473
lastAssistantStopReason: "length",
5574
}),
5675
),
@@ -60,12 +79,11 @@ describe("attempt trajectory status", () => {
6079
});
6180
});
6281

63-
it("does not treat streamed partial payloads as completed length-limited output", () => {
82+
it("keeps whitespace-only length-limited text non-deliverable", () => {
6483
expect(
6584
resolveAttemptTrajectoryTerminal(
6685
baseParams({
67-
assistantTexts: ["Partial answer."],
68-
synthesizedPayloadCount: 1,
86+
assistantTexts: [" \n "],
6987
lastAssistantStopReason: "length",
7088
}),
7189
),
@@ -75,6 +93,20 @@ describe("attempt trajectory status", () => {
7593
});
7694
});
7795

96+
it("records a delivered length-limited partial payload as success", () => {
97+
// The terminal owner delivers this turn as a partial reply, so the durable
98+
// trajectory record must agree instead of reporting a non-deliverable error.
99+
expect(
100+
resolveAttemptTrajectoryTerminal(
101+
baseParams({
102+
assistantTexts: ["Partial answer."],
103+
synthesizedPayloadCount: 1,
104+
lastAssistantStopReason: "length",
105+
}),
106+
),
107+
).toEqual({ status: "success" });
108+
});
109+
78110
it("keeps length-limited turns successful when terminal output was delivered", () => {
79111
expect(
80112
resolveAttemptTrajectoryTerminal(

‎src/agents/embedded-agent-runner/run/attempt-trajectory-status.ts‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -129,10 +129,20 @@ export function resolveAttemptTrajectoryTerminal(
129129
terminalError: NON_DELIVERABLE_TERMINAL_TURN_REASON,
130130
};
131131
}
132+
// A length stop with visible assistant text is delivered as a partial reply by
133+
// the terminal owner, so recording it as non-deliverable here would contradict
134+
// what the user received. Visible text is the canonical fact to key on:
135+
// finalization runs before terminal preparation turns assistant text into
136+
// payloads, so synthesizedPayloadCount is still 0 for an ordinary text-only
137+
// reply and cannot stand in for "nothing was delivered".
138+
const hasVisibleAssistantOutput =
139+
hasNonEmptyAssistantText(params.assistantTexts) || params.synthesizedPayloadCount > 0;
140+
132141
if (
133142
params.lastAssistantStopReason === "length" &&
134143
!params.hasTerminalOutput &&
135-
!hasExplicitTerminalDelivery
144+
!hasExplicitTerminalDelivery &&
145+
!hasVisibleAssistantOutput
136146
) {
137147
return {
138148
status: "error",
@@ -143,8 +153,7 @@ export function resolveAttemptTrajectoryTerminal(
143153
const hasDeliverableOrProgress =
144154
hasExplicitTerminalDelivery ||
145155
params.hasTerminalOutput ||
146-
params.synthesizedPayloadCount > 0 ||
147-
hasNonEmptyAssistantText(params.assistantTexts) ||
156+
hasVisibleAssistantOutput ||
148157
params.successfulCronAdds > 0;
149158

150159
if (hasDeliverableOrProgress) {

‎src/agents/embedded-agent-runner/run/incomplete-turn-classification.ts‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -58,9 +58,14 @@ export function isIncompleteTerminalAssistantTurn(params: {
5858
lastAssistant?: { stopReason?: string } | null;
5959
}): boolean {
6060
const stopReason = params.lastAssistant?.stopReason;
61-
// Tool-use expects a post-tool continuation; length means the output budget
62-
// ended before a complete final answer. Partial visible text completes neither.
63-
return stopReason === "toolUse" || (stopReason === "length" && !params.hasTerminalOutput);
61+
// Tool-use expects a post-tool continuation, so partial visible text completes
62+
// nothing. Length is different: the output budget ended, no continuation is
63+
// pending, and any visible text the model did emit is the answer so far. Only
64+
// a length stop with nothing to show is an incomplete turn.
65+
return (
66+
stopReason === "toolUse" ||
67+
(stopReason === "length" && !params.hasTerminalOutput && !params.hasAssistantVisibleText)
68+
);
6469
}
6570

6671
const GEMINI_INCOMPLETE_TURN_PROVIDER_IDS = new Set([

‎src/agents/embedded-agent-runner/run/incomplete-turn-resolution.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,8 +54,9 @@ export function resolveIncompleteTurnPayloadText(params: {
5454
const assistantState = classifyAssistantTurn(params);
5555
const assistant = assistantState.assistant;
5656
const hasTerminalOutput = hasAttemptTerminalState(params.attempt);
57-
// Tool-use expects a post-tool continuation, while length means the output
58-
// budget ended. Partial visible text completes neither. (#76477)
57+
// Tool-use expects a post-tool continuation, so partial visible text completes
58+
// nothing. A length stop that did produce visible text is a partial answer and
59+
// is delivered with a truncation notice instead. (#76477)
5960
const incompleteTerminalAssistant = isIncompleteTerminalAssistantTurn({
6061
hasAssistantVisibleText: params.payloadCount > 0,
6162
hasTerminalOutput,
@@ -211,6 +212,9 @@ export function hasYieldContinuationEvidence(attempt: YieldContinuationAttempt):
211212
export const YIELD_DIAGNOSTIC_TEXT =
212213
"⚠️ Turn yielded without a continuation source. Send a message to resume.";
213214

215+
export const TRUNCATED_REPLY_NOTICE_TEXT =
216+
"⚠️ Reply truncated at the model's output token limit. The text above is partial — ask to continue it.";
217+
214218
function isToolResultRole(role: string): boolean {
215219
return role === "toolresult" || role === "tool_result" || role === "tool";
216220
}

‎src/agents/embedded-agent-runner/run/settled-tool-evidence.test.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,12 @@ describe("runEmbeddedAgent incomplete-turn safety", () => {
120120
hasAssistantVisibleText: true,
121121
lastAssistant: { stopReason: "length" },
122122
}),
123+
).toBe(false);
124+
expect(
125+
isIncompleteTerminalAssistantTurn({
126+
hasAssistantVisibleText: false,
127+
lastAssistant: { stopReason: "length" },
128+
}),
123129
).toBe(true);
124130
expect(
125131
isIncompleteTerminalAssistantTurn({

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

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
makeEmbeddedRunnerAttempt,
66
} from "../../test-helpers/embedded-agent-runner-e2e-fixtures.js";
77
import { createEmbeddedRunContextRecoveryState } from "./context-recovery-state.js";
8+
import { TRUNCATED_REPLY_NOTICE_TEXT } from "./incomplete-turn-resolution.js";
89
import { resolveEmbeddedRunAttemptTerminalState } from "./terminal-outcome.js";
910
import {
1011
copyAttemptDeliveryState,
@@ -247,6 +248,40 @@ describe("terminal resolution", () => {
247248
expect(activateInternalPrompt).not.toHaveBeenCalled();
248249
});
249250

251+
it("keeps a length-stopped silent cron result silent", async () => {
252+
// The only payload is the synthesized silent result of a successful tool and
253+
// the assistant produced no prose, so there is no partial reply to label; a
254+
// truncation notice here would turn intentional silence into a message.
255+
const assistant = emptyAssistant({ stopReason: "length" });
256+
const attempt = makeEmbeddedRunnerAttempt({
257+
assistantTexts: [],
258+
toolMetas: [{ toolName: "exec" }],
259+
messagesSnapshot: [
260+
{
261+
role: "toolResult",
262+
content: [{ type: "text", text: SILENT_REPLY_TOKEN }],
263+
details: { aggregated: SILENT_REPLY_TOKEN },
264+
} as never,
265+
assistant,
266+
],
267+
lastAssistant: assistant,
268+
currentAttemptAssistant: assistant,
269+
});
270+
const input = makeTerminalInput({
271+
attempt,
272+
attemptAssistant: assistant,
273+
runParams: { trigger: "cron", terminalReplyExpectation: "required" },
274+
});
275+
276+
const resolved = await resolveEmbeddedRunTerminal(input);
277+
278+
expect(resolved.action).toBe("complete");
279+
if (resolved.action !== "complete") {
280+
return;
281+
}
282+
expect(resolved.result.payloads).toEqual([{ text: SILENT_REPLY_TOKEN }]);
283+
});
284+
250285
it("completes a reply-optional side-effecting turn as intentional silence", async () => {
251286
const assistant = emptyAssistant();
252287
const attempt = makeEmbeddedRunnerAttempt({
@@ -575,4 +610,85 @@ describe("terminal resolution", () => {
575610
expect(resolved.action).toBe("complete");
576611
expect(activateInternalPrompt).not.toHaveBeenCalled();
577612
});
613+
614+
it("delivers partial text with a truncation notice when the output budget ends", async () => {
615+
const assistant = buildEmbeddedRunnerAssistant({
616+
stopReason: "length",
617+
content: [{ type: "text", text: "Here is the first half of the answer" }],
618+
});
619+
const attempt = makeEmbeddedRunnerAttempt({
620+
assistantTexts: ["Here is the first half of the answer"],
621+
lastAssistant: assistant,
622+
currentAttemptAssistant: assistant,
623+
currentAttemptReplayMetadata: { hadPotentialSideEffects: false, replaySafe: true },
624+
});
625+
const resolved = await resolveEmbeddedRunTerminal(
626+
makeTerminalInput({
627+
attempt,
628+
attemptAssistant: assistant,
629+
payloadsWithToolMedia: [{ text: "Here is the first half of the answer" }],
630+
}),
631+
);
632+
633+
expect(resolved.action).toBe("complete");
634+
if (resolved.action !== "complete") {
635+
return;
636+
}
637+
expect(resolved.result.payloads).toEqual([
638+
{ text: "Here is the first half of the answer" },
639+
{ text: TRUNCATED_REPLY_NOTICE_TEXT },
640+
]);
641+
expect(resolved.result.meta.error).toBeUndefined();
642+
expect(resolved.result.meta.livenessState).toBe("working");
643+
});
644+
645+
it("does not add a truncation notice to a length stop that already has terminal output", async () => {
646+
// Terminal tool media was already a complete outcome before this fix, so it
647+
// must not gain a notice telling the user to ask for a continuation.
648+
const assistant = buildEmbeddedRunnerAssistant({
649+
stopReason: "length",
650+
content: [{ type: "text", text: "Chart attached" }],
651+
});
652+
const attempt = makeEmbeddedRunnerAttempt({
653+
assistantTexts: ["Chart attached"],
654+
lastAssistant: assistant,
655+
currentAttemptAssistant: assistant,
656+
toolMediaUrls: ["https://example.invalid/chart.png"],
657+
currentAttemptReplayMetadata: { hadPotentialSideEffects: false, replaySafe: true },
658+
});
659+
const resolved = await resolveEmbeddedRunTerminal(
660+
makeTerminalInput({
661+
attempt,
662+
attemptAssistant: assistant,
663+
payloadsWithToolMedia: [{ text: "Chart attached" }],
664+
}),
665+
);
666+
667+
expect(resolved.action).toBe("complete");
668+
if (resolved.action !== "complete") {
669+
return;
670+
}
671+
expect(resolved.result.payloads).toEqual([{ text: "Chart attached" }]);
672+
});
673+
674+
it("still reports an incomplete turn when the output budget ends with no text", async () => {
675+
const assistant = emptyAssistant({ stopReason: "length" });
676+
const attempt = makeEmbeddedRunnerAttempt({
677+
assistantTexts: [],
678+
lastAssistant: assistant,
679+
currentAttemptAssistant: assistant,
680+
currentAttemptReplayMetadata: { hadPotentialSideEffects: false, replaySafe: true },
681+
});
682+
const resolved = await resolveEmbeddedRunTerminal(
683+
makeTerminalInput({ attempt, attemptAssistant: assistant }),
684+
);
685+
686+
expect(resolved.action).toBe("complete");
687+
if (resolved.action !== "complete") {
688+
return;
689+
}
690+
expect(resolved.result.payloads?.[0]).toMatchObject({ isError: true });
691+
expect(resolved.result.meta.error?.kind).toBe("incomplete_turn");
692+
expect(resolved.result.meta.livenessState).toBe("abandoned");
693+
});
578694
});

‎src/agents/embedded-agent-runner/run/terminal-resolution.ts‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import {
2222
reportEmbeddedRunSuccessfulAuthBinding,
2323
} from "./auth-profile-success.js";
2424
import type { EmbeddedRunContextRecoveryState } from "./context-recovery-state.js";
25+
import { resolveFinalAssistantVisibleText } from "./helpers.js";
2526
import {
2627
resolveEmptyResponseRetryInstruction,
2728
resolveReasoningOnlyRetryInstruction,
@@ -34,6 +35,7 @@ import {
3435
resolveRunLivenessState,
3536
resolveSilentToolResultReplyPayload,
3637
shouldRetryMissingAssistantTurn,
38+
TRUNCATED_REPLY_NOTICE_TEXT,
3739
YIELD_DIAGNOSTIC_TEXT,
3840
} from "./incomplete-turn-resolution.js";
3941
import type { RunEmbeddedAgentParams } from "./params.js";
@@ -582,12 +584,28 @@ function completeEmbeddedRun(
582584
: input.attempt.yieldDetected
583585
? "end_turn"
584586
: (input.attemptAssistant?.stopReason as string | undefined);
587+
// The truncation notice belongs to exactly the turns this fix newly delivers:
588+
// a length stop whose only output is partial assistant text. A length stop that
589+
// also produced terminal output (tool media, a committed source reply) was
590+
// already complete before this fix and must not gain a misleading extra reply.
591+
// Nonblank assistant text is also required: a cron turn whose only payload is
592+
// the synthesized silent result of a successful tool has no partial prose to
593+
// label, and appending a notice there would turn intentional silence into a
594+
// visible message.
595+
const hasPartialAssistantText =
596+
input.attempt.assistantTexts.some((text) => text.trim().length > 0) ||
597+
resolveFinalAssistantVisibleText(input.attemptAssistant) !== undefined;
598+
const isTruncatedPartialReply =
599+
stopReason === "length" && !hasAttemptTerminalState(input.attempt) && hasPartialAssistantText;
585600
// Existing visible payloads already avoid the silent-park symptom. The diagnostic
586601
// fills only an otherwise empty yielded turn and must not duplicate visible output.
602+
// A length stop delivers partial text, so it is labeled instead of dropped. (#76477)
587603
const terminalPayloads = input.emptyAssistantReplyIsSilent
588604
? [{ text: SILENT_REPLY_TOKEN }]
589605
: input.payloadsForTerminalPath?.length
590-
? input.payloadsForTerminalPath
606+
? isTruncatedPartialReply
607+
? [...input.payloadsForTerminalPath, { text: TRUNCATED_REPLY_NOTICE_TEXT }]
608+
: input.payloadsForTerminalPath
591609
: input.attempt.yieldDetected && !yieldHasContinuation
592610
? [{ text: YIELD_DIAGNOSTIC_TEXT }]
593611
: input.payloadsForTerminalPath;

0 commit comments

Comments
 (0)