Skip to content

Commit a19e156

Browse files
fix(agents): ensure wrapAnthropicStreamWithRecovery works with async streamFn
Previously, when agent.streamFn returns a Promise (async function), the recovery wrapper only caught Promise rejections but did NOT pump the resolved stream to detect mid-stream error events like Anthropic's "Invalid signature in thinking block". This caused recovery to fail silently for async streams. The fix unifies sync and async handling: - Always create an outer stream for consistent event pumping - Await the inner stream (if it's a Promise) to get the actual stream - Pump the resolved stream through pumpStreamWithRecovery to catch mid-stream errors - Handle initial Promise rejection by retrying with cleaned messages - Removed unused wrapRetryStreamWithRecoveryNotification helper This ensures Anthropic thinking signature recovery works correctly regardless of whether the embedded agent's streamFn is sync or async. Fixes #95429
1 parent c47cd52 commit a19e156

2 files changed

Lines changed: 27 additions & 48 deletions

File tree

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

Lines changed: 19 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -602,34 +602,6 @@ function isSuccessfulRecoveryRetryResult(message: AssistantMessage | undefined):
602602
return message.stopReason !== "error" && message.stopReason !== "aborted";
603603
}
604604

605-
function wrapRetryStreamWithRecoveryNotification(
606-
retryStream: ReturnType<StreamFn>,
607-
notify: () => Promise<void>,
608-
): ReturnType<StreamFn> {
609-
if (retryStream instanceof Promise) {
610-
return retryStream.then((resolved) =>
611-
wrapRetryStreamWithRecoveryNotification(resolved as ReturnType<StreamFn>, notify),
612-
) as ReturnType<StreamFn>;
613-
}
614-
const streamWithResult = retryStream as unknown as {
615-
result?: () => Promise<AssistantMessage>;
616-
};
617-
if (typeof streamWithResult.result !== "function") {
618-
return retryStream;
619-
}
620-
const result = streamWithResult.result.bind(streamWithResult);
621-
let notified = false;
622-
streamWithResult.result = async () => {
623-
const message = await result();
624-
if (!notified && isSuccessfulRecoveryRetryResult(message)) {
625-
notified = true;
626-
await notify();
627-
}
628-
return message;
629-
};
630-
return retryStream;
631-
}
632-
633605
async function retryStreamWithoutThinking(
634606
outer: ReturnType<typeof createAssistantMessageEventStream>,
635607
retry: () => ReturnType<StreamFn>,
@@ -724,29 +696,34 @@ export function wrapAnthropicStreamWithRecovery(
724696
cleanedMessages: stripAllThinkingBlocks(originalMessages),
725697
});
726698

727-
const stream = innerStreamFn(model, context, options);
728-
if (stream instanceof Promise) {
729-
return stream.catch((error: unknown) => {
699+
// Unified handling for both sync and async streamFn: always use outer stream
700+
// and pump the resolved stream through recovery logic, ensuring mid-stream
701+
// errors are caught even when streamFn returns a Promise.
702+
const maybePromise = innerStreamFn(model, context, options);
703+
const outer = createAssistantMessageEventStream();
704+
705+
const finalResultPromise = (async () => {
706+
try {
707+
// Await the inner stream (promise or direct)
708+
const resolvedStream = await maybePromise;
709+
// Pump the resolved stream through recovery, handling mid-stream errors
710+
return await pumpStreamWithRecovery(outer, resolvedStream, requestMeta, retry, notify);
711+
} catch (error: unknown) {
730712
if (!shouldRecoverAnthropicThinkingError(error, requestMeta)) {
731713
throw error;
732714
}
733715
requestMeta.recoveredAnthropicThinking = true;
734716
log.warn(
735717
`[session-recovery] Anthropic thinking request rejected; retrying once without thinking blocks: sessionId=${requestMeta.id}`,
736718
);
737-
return wrapRetryStreamWithRecoveryNotification(retry(), notify);
738-
}) as ReturnType<StreamFn>;
739-
}
740-
const outer = createAssistantMessageEventStream();
741-
const finalResultPromise = pumpStreamWithRecovery(
742-
outer,
743-
stream,
744-
requestMeta,
745-
retry,
746-
notify,
747-
).finally(() => {
719+
// On initial rejection, retry with cleaned messages
720+
const retryInner = retry();
721+
return await pumpStreamWithRecovery(outer, retryInner, requestMeta, retry, notify);
722+
}
723+
})().finally(() => {
748724
outer.end();
749725
});
726+
750727
outer.result = () => finalResultPromise;
751728
return outer as unknown as ReturnType<StreamFn>;
752729
};

‎src/infra/state-migrations.ts‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4480,7 +4480,7 @@ async function migrateLegacyMemoryStore(params: {
44804480
}): Promise<{ changes: string[]; warnings: string[] }> {
44814481
const changes: string[] = [];
44824482
const warnings: string[] = [];
4483-
const { detected } = params;
4483+
const { detected, now } = params;
44844484

44854485
if (!detected.memoryStore.hasLegacy) {
44864486
return { changes, warnings };
@@ -4498,7 +4498,8 @@ async function migrateLegacyMemoryStore(params: {
44984498
if (targetExists) {
44994499
try {
45004500
// Use same agent DB opening logic as runtime
4501-
const db = requireNodeSqlite().Database.open(targetPath);
4501+
const sqlite = requireNodeSqlite();
4502+
const db = new sqlite.DatabaseSync(targetPath);
45024503
const result = db.prepare("SELECT COUNT(*) as count FROM memory_index_chunks").get() as {
45034504
count: number;
45044505
};
@@ -4516,8 +4517,9 @@ async function migrateLegacyMemoryStore(params: {
45164517

45174518
try {
45184519
// Verify legacy schema exists (meta, files, chunks)
4519-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
4520-
const checkLegacySchema = (db: any): boolean => {
4520+
const sqlite = requireNodeSqlite();
4521+
4522+
const checkLegacySchema = (db: typeof sqlite.DatabaseSync.prototype): boolean => {
45214523
const hasMeta =
45224524
db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='meta'").get() !=
45234525
null;
@@ -4530,7 +4532,7 @@ async function migrateLegacyMemoryStore(params: {
45304532
return hasMeta && hasFiles && hasChunks;
45314533
};
45324534

4533-
const legacyDb = requireNodeSqlite().Database.open(legacyPath, { readonly: true });
4535+
const legacyDb = new sqlite.DatabaseSync(legacyPath, { readOnly: true });
45344536
if (!checkLegacySchema(legacyDb)) {
45354537
warnings.push(
45364538
`Legacy memory store at ${legacyPath} does not have expected schema (meta, files, chunks). Skipping migration.`,
@@ -4551,7 +4553,7 @@ async function migrateLegacyMemoryStore(params: {
45514553
fs.copyFileSync(legacyPath, targetPath);
45524554

45534555
// Open target for in-place migration
4554-
const db = requireNodeSqlite().Database.open(targetPath);
4556+
const db = new sqlite.DatabaseSync(targetPath);
45554557

45564558
// Begin transaction
45574559
db.exec("SAVEPOINT migrate_legacy_memory_index_tables");

0 commit comments

Comments
 (0)