Skip to content

Commit 8ef6e76

Browse files
committed
fix(embedded-agent): recover thinking-signature rejection delivered as a terminal result
stripInvalidThinkingSignatures intentionally exempts the latest assistant turn (providers reject a modified latest thinking block), expecting a corrupted latest block to flow through stream recovery instead. But when the provider rejects the replayed signature, the 400 can surface as a resolved result message (stopReason "error" + errorMessage) rather than an in-stream error event or a thrown rejection. pumpStreamWithRecovery only handled the error-event and throw carriers, so recovery never fired and the session was rejected on every replay until a manual restart. Recover this carrier too: when the terminal result is a recoverable thinking error and no content has streamed, retry once without thinking blocks and notify, so the persisted transcript is repaired. Adds a regression test for the result-message carrier.
1 parent beea31a commit 8ef6e76

2 files changed

Lines changed: 89 additions & 0 deletions

File tree

‎src/agents/embedded-agent-runner/thinking.test.ts‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -610,6 +610,74 @@ describe("wrapAnthropicStreamWithRecovery", () => {
610610
});
611611
});
612612

613+
it("recovers a thinking-signature rejection delivered as a terminal result message", async () => {
614+
// Regression: the provider 400 arrives as a resolved result message
615+
// (stopReason "error" + errorMessage), not an error event or a thrown
616+
// rejection, and no content streams first. The wrapper must still retry once
617+
// without thinking blocks and notify so the session is repaired, rather than
618+
// returning the error and wedging on every replay (replay_invalid).
619+
let callCount = 0;
620+
const recovered = vi.fn();
621+
const errorResult = createTestAssistantMessage({
622+
content: [{ type: "text", text: "" }],
623+
stopReason: "error",
624+
errorMessage:
625+
'{"type":"error","error":{"type":"invalid_request_error",' +
626+
'"message":"messages.11.content.12: Invalid `signature` in `thinking` block"}}',
627+
});
628+
const finalMessage = createTestAssistantMessage({
629+
content: [{ type: "text", text: "recovered" }],
630+
stopReason: "stop",
631+
});
632+
const originalMessages = castAgentMessages([
633+
{
634+
role: "assistant",
635+
content: [
636+
{ type: "thinking", thinking: "", thinkingSignature: "" },
637+
{ type: "text", text: "visible answer" },
638+
],
639+
},
640+
]);
641+
const contexts: Array<{ messages?: AgentMessage[] }> = [];
642+
const wrapped = wrapAnthropicStreamWithRecovery(
643+
((_model, context) => {
644+
callCount += 1;
645+
contexts.push(context as { messages?: AgentMessage[] });
646+
const stream = createAssistantMessageEventStream();
647+
if (callCount === 1) {
648+
// Resolve the final result with an error message and stream no chunks,
649+
// i.e. the provider 400 surfaces only via result(), not as an event.
650+
queueMicrotask(() => stream.end(errorResult));
651+
} else {
652+
queueMicrotask(() => {
653+
stream.push({ type: "done", reason: "stop", message: finalMessage });
654+
stream.end();
655+
});
656+
}
657+
return stream;
658+
}) as Parameters<typeof wrapAnthropicStreamWithRecovery>[0],
659+
{ id: "test-session", onRecoveredAnthropicThinking: recovered },
660+
);
661+
662+
const response = (await wrapped(
663+
{} as never,
664+
{ messages: originalMessages } as never,
665+
{} as never,
666+
)) as { result: () => Promise<unknown> } & AsyncIterable<unknown>;
667+
for await (const event of response) {
668+
void event;
669+
}
670+
671+
await expect(response.result()).resolves.toEqual(finalMessage);
672+
expect(callCount).toBe(2);
673+
expect(recovered).toHaveBeenCalledTimes(1);
674+
const retryMessage = contexts[1]?.messages?.[0];
675+
if (!retryMessage || retryMessage.role !== "assistant") {
676+
throw new Error("Expected Anthropic recovery retry to start with an assistant message");
677+
}
678+
expect(retryMessage.content).toEqual([{ type: "text", text: "visible answer" }]);
679+
});
680+
613681
it("does not notify recovery when the stripped-thinking retry also fails", async () => {
614682
const recovered = vi.fn();
615683
let callCount = 0;

‎src/agents/embedded-agent-runner/thinking.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -678,6 +678,27 @@ async function pumpStreamWithRecovery(
678678
outer.push(chunk as Parameters<typeof outer.push>[0]);
679679
}
680680
const result = await (resolved as { result?: () => Promise<AssistantMessage> }).result?.();
681+
// A provider signature rejection can surface as a *terminal result
682+
// message* (stopReason "error" + errorMessage) — not an in-stream error
683+
// event or a thrown rejection — when the stream resolves the 400 instead of
684+
// throwing. The latest-turn exemption in stripInvalidThinkingSignatures
685+
// intentionally lets a corrupted latest thinking block flow through to this
686+
// recovery path, so if recovery does not fire here the session 400s on every
687+
// replay (replay_invalid) and wedges until a manual restart. Recover this
688+
// carrier once, the same as the error-event branch above. Guarded by
689+
// !yieldedOutput because a signature 400 is rejected before any content
690+
// streams, so this only fires for a turn that produced no visible output.
691+
if (
692+
!yieldedOutput &&
693+
result?.stopReason === "error" &&
694+
shouldRecoverAnthropicThinkingError(result, sessionMeta)
695+
) {
696+
sessionMeta.recoveredAnthropicThinking = true;
697+
log.warn(
698+
`[session-recovery] Anthropic thinking error in terminal result; retrying once without thinking blocks: sessionId=${sessionMeta.id}`,
699+
);
700+
return retryStreamWithoutThinking(outer, retry, notify);
701+
}
681702
return result as AssistantMessage;
682703
} catch (error: unknown) {
683704
if (!shouldRecoverAnthropicThinkingError(error, sessionMeta)) {

0 commit comments

Comments
 (0)