@cloudflare/think 0.7.2 → 0.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/think.d.ts CHANGED
@@ -52,6 +52,20 @@ import {
52
52
  import { Workspace } from "@cloudflare/shell";
53
53
 
54
54
  //#region src/think.d.ts
55
+ type ChatRecoveryRetryData = {
56
+ targetUserId?: string;
57
+ originalRequestId?: string;
58
+ lastBody?: Record<string, unknown> | null;
59
+ lastClientTools?: ClientToolSchema[] | null;
60
+ recoveredRequestId?: string;
61
+ };
62
+ type ChatRecoveryContinueData = {
63
+ targetAssistantId?: string;
64
+ originalRequestId?: string;
65
+ lastBody?: Record<string, unknown> | null;
66
+ lastClientTools?: ClientToolSchema[] | null;
67
+ recoveredRequestId?: string;
68
+ };
55
69
  /**
56
70
  * Callback interface for streaming chat events from a Think sub-agent.
57
71
  *
@@ -591,6 +605,7 @@ declare class Think<
591
605
  getSystemPrompt(): string;
592
606
  /** Return the tools available to the assistant. */
593
607
  getTools(): ToolSet;
608
+ private _runChatRecoveryFiber;
594
609
  private _systemPromptForTurn;
595
610
  private _buildThinkCapabilityBlock;
596
611
  /** Maximum number of tool-call steps per turn. Override via property or per-turn via TurnConfig. */
@@ -1038,6 +1053,7 @@ declare class Think<
1038
1053
  body?: Record<string, unknown>,
1039
1054
  options?: SaveMessagesOptions$1
1040
1055
  ): Promise<SaveMessagesResult$1>;
1056
+ private _retryLastUserTurn;
1041
1057
  private _setupProtocolHandlers;
1042
1058
  private _handleProtocolEvent;
1043
1059
  private _handleStreamResumeRequest;
@@ -1115,17 +1131,17 @@ declare class Think<
1115
1131
  protected _handleInternalFiberRecovery(
1116
1132
  ctx: FiberRecoveryContext$1
1117
1133
  ): Promise<boolean>;
1134
+ private _recoverablePreStreamUserId;
1135
+ _chatRecoveryRetry(data?: ChatRecoveryRetryData): Promise<void>;
1118
1136
  private _hasRunningSubmission;
1119
1137
  private _readRunningSubmissionByRequestId;
1120
1138
  private _markRecoveredSubmissionInterrupted;
1121
1139
  private _completeRecoveredSubmission;
1122
1140
  protected onChatRecovery(
1123
1141
  _ctx: ChatRecoveryContext$1
1124
- ): Promise<ChatRecoveryOptions$1>;
1125
- _chatRecoveryContinue(data?: {
1126
- targetAssistantId?: string;
1127
- recoveredRequestId?: string;
1128
- }): Promise<void>;
1142
+ ): Promise<ChatRecoveryOptions$1 | void>;
1143
+ _chatRecoveryContinue(data?: ChatRecoveryContinueData): Promise<void>;
1144
+ private _applyRecoveredRequestContext;
1129
1145
  private _getPartialStreamText;
1130
1146
  private _getSubmitConcurrencyDecision;
1131
1147
  private _completeSkippedRequest;
package/dist/think.js CHANGED
@@ -2,7 +2,7 @@ import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldSet2, t as _cla
2
2
  import { createWorkspaceTools } from "./tools/workspace.js";
3
3
  import { convertToModelMessages, stepCountIs, streamText } from "ai";
4
4
  import { Agent, __DO_NOT_USE_WILL_BREAK__agentContext } from "agents";
5
- import { AbortRegistry, CHAT_MESSAGE_TYPES, ContinuationState, ResumableStream, StreamAccumulator, SubmitConcurrencyController, TurnQueue, applyChunkToParts, applyToolUpdate, createToolsFromClientSchemas, enforceRowSizeLimit, parseProtocolMessage, reconcileMessages, resolveToolMergeId, sanitizeMessage, toolApprovalUpdate, toolResultUpdate } from "agents/chat";
5
+ import { AbortRegistry, CHAT_MESSAGE_TYPES, ContinuationState, ResumableStream, StreamAccumulator, SubmitConcurrencyController, TurnQueue, applyChunkToParts, applyToolUpdate, createChatFiberSnapshot, createToolsFromClientSchemas, enforceRowSizeLimit, parseProtocolMessage, reconcileMessages, resolveToolMergeId, sanitizeMessage, toolApprovalUpdate, toolResultUpdate, unwrapChatFiberSnapshot, wrapChatFiberSnapshot } from "agents/chat";
6
6
  import { Session, Session as Session$1 } from "agents/experimental/memory/session";
7
7
  import { truncateOlderMessages } from "agents/experimental/memory/utils";
8
8
  import { Workspace, Workspace as Workspace$1 } from "@cloudflare/shell";
@@ -26,6 +26,9 @@ function sendIfOpen(connection, message) {
26
26
  function isWebSocketClosedSendError(error) {
27
27
  return error instanceof TypeError && error.message.includes("WebSocket send() after close");
28
28
  }
29
+ function shouldMarkSkippedAfterGenerationChange(status) {
30
+ return status === "completed";
31
+ }
29
32
  const TIMED_OUT = Symbol("timed-out");
30
33
  var _configCache = /* @__PURE__ */ new WeakMap();
31
34
  var _configTableReady = /* @__PURE__ */ new WeakMap();
@@ -295,6 +298,20 @@ var Think = class Think extends Agent {
295
298
  getTools() {
296
299
  return {};
297
300
  }
301
+ async _runChatRecoveryFiber(requestId, continuation, fn) {
302
+ const snapshot = createChatFiberSnapshot({
303
+ kind: "think-chat-turn",
304
+ requestId,
305
+ continuation,
306
+ messages: this.messages,
307
+ lastBody: this._lastBody,
308
+ lastClientTools: this._lastClientTools
309
+ });
310
+ return this._runFiberWithStashWrapper(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => fn(), {
311
+ initialSnapshot: wrapChatFiberSnapshot("__cfThinkChatFiberSnapshot", snapshot, null),
312
+ wrapStash: (data) => wrapChatFiberSnapshot("__cfThinkChatFiberSnapshot", snapshot, data)
313
+ });
314
+ }
298
315
  _systemPromptForTurn(baseSystem, tools) {
299
316
  if (baseSystem.includes("You are running inside a Think agent.")) return baseSystem;
300
317
  return `${baseSystem.trimEnd()}\n\n${this._buildThinkCapabilityBlock(tools)}`;
@@ -967,9 +984,7 @@ var Think = class Think extends Agent {
967
984
  }
968
985
  await this._streamResultToRpcCallback(requestId, result, callback, abortSignal);
969
986
  };
970
- if (this.chatRecovery) await this.runFiber(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => {
971
- await chatBody();
972
- });
987
+ if (this.chatRecovery) await this._runChatRecoveryFiber(requestId, false, chatBody);
973
988
  else await chatBody();
974
989
  });
975
990
  });
@@ -1070,6 +1085,7 @@ var Think = class Think extends Agent {
1070
1085
  this._agentToolAbortControllers.set(options.runId, controller);
1071
1086
  this._agentToolLiveSequences.set(options.runId, 0);
1072
1087
  this._agentToolPreTurnAssistantIds.set(options.runId, new Set(this.messages.filter((m) => m.role === "assistant").map((m) => m.id)));
1088
+ const epoch = this._turnQueue.generation;
1073
1089
  this.keepAliveWhile(async () => {
1074
1090
  try {
1075
1091
  this.sql`
@@ -1081,9 +1097,9 @@ var Think = class Think extends Agent {
1081
1097
  const streamId = this._resumableStream.getAllStreamMetadata().find((m) => m.request_id === result.requestId)?.id ?? null;
1082
1098
  const output = this.getAgentToolOutput(options.runId);
1083
1099
  const summary = this.getAgentToolSummary(options.runId, output);
1084
- const streamError = this._agentToolLastErrors.get(options.runId);
1085
- const skipped = result.status === "skipped";
1086
- const status = result.status === "aborted" ? "aborted" : skipped || streamError ? "error" : "completed";
1100
+ const streamError = result.error ?? this._agentToolLastErrors.get(options.runId);
1101
+ const skipped = result.status === "skipped" || result.status === "aborted" && this._turnQueue.generation !== epoch;
1102
+ const status = result.status === "error" || skipped || streamError ? "error" : result.status === "aborted" ? "aborted" : "completed";
1087
1103
  const error = status === "error" ? streamError ?? "Agent tool run was skipped before the child could finish." : null;
1088
1104
  this.sql`
1089
1105
  UPDATE cf_agent_tool_child_runs
@@ -1095,6 +1111,7 @@ var Think = class Think extends Agent {
1095
1111
  error_message = ${error},
1096
1112
  completed_at = ${Date.now()}
1097
1113
  WHERE run_id = ${options.runId}
1114
+ AND completed_at IS NULL
1098
1115
  `;
1099
1116
  } catch (error) {
1100
1117
  this.sql`
@@ -1103,6 +1120,7 @@ var Think = class Think extends Agent {
1103
1120
  error_message = ${error instanceof Error ? error.message : String(error)},
1104
1121
  completed_at = ${Date.now()}
1105
1122
  WHERE run_id = ${options.runId}
1123
+ AND completed_at IS NULL
1106
1124
  `;
1107
1125
  } finally {
1108
1126
  this._agentToolAbortControllers.delete(options.runId);
@@ -1542,13 +1560,14 @@ var Think = class Think extends Agent {
1542
1560
  });
1543
1561
  const streamId = this._resumableStream.getAllStreamMetadata().find((metadata) => metadata.request_id === result.requestId)?.id ?? null;
1544
1562
  const streamError = this._programmaticStreamErrors.get(result.requestId);
1545
- const finalStatus = this._getSubmissionFinalStatus(result.status, streamError);
1563
+ const finalStatus = this._getSubmissionFinalStatus(result.status, result.error ?? streamError);
1564
+ const errorMessage = result.error ?? streamError ?? null;
1546
1565
  this.sql`
1547
1566
  UPDATE cf_think_submissions
1548
1567
  SET status = ${finalStatus},
1549
1568
  request_id = ${result.requestId},
1550
1569
  stream_id = ${streamId},
1551
- error_message = ${finalStatus === "error" ? streamError ?? null : null},
1570
+ error_message = ${finalStatus === "error" ? errorMessage : null},
1552
1571
  completed_at = ${Date.now()}
1553
1572
  WHERE submission_id = ${row.submission_id}
1554
1573
  AND status = 'running'
@@ -1765,6 +1784,7 @@ var Think = class Think extends Agent {
1765
1784
  const body = this._lastBody;
1766
1785
  const epoch = this._turnQueue.generation;
1767
1786
  let status = "completed";
1787
+ let error;
1768
1788
  let wasAborted = false;
1769
1789
  await this.keepAliveWhile(async () => {
1770
1790
  await this._turnQueue.enqueue(requestId, async () => {
@@ -1795,11 +1815,13 @@ var Think = class Think extends Agent {
1795
1815
  body,
1796
1816
  continuation: false
1797
1817
  }));
1798
- if (result) await this._streamResult(requestId, result, abortSignal, { captureProgrammaticStreamError: options?.captureProgrammaticStreamError });
1818
+ if (result) {
1819
+ const streamResult = await this._streamResult(requestId, result, abortSignal, { captureProgrammaticStreamError: options?.captureProgrammaticStreamError });
1820
+ status = streamResult.status;
1821
+ error = streamResult.error;
1822
+ }
1799
1823
  };
1800
- if (this.chatRecovery) await this.runFiber(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => {
1801
- await programmaticBody();
1802
- });
1824
+ if (this.chatRecovery) await this._runChatRecoveryFiber(requestId, false, programmaticBody);
1803
1825
  else await programmaticBody();
1804
1826
  } finally {
1805
1827
  if (abortSignal?.aborted) wasAborted = true;
@@ -1808,11 +1830,12 @@ var Think = class Think extends Agent {
1808
1830
  }
1809
1831
  });
1810
1832
  });
1811
- if (this._turnQueue.generation !== epoch && status === "completed") status = "skipped";
1833
+ if (this._turnQueue.generation !== epoch && shouldMarkSkippedAfterGenerationChange(status)) status = "skipped";
1812
1834
  else if (wasAborted && status === "completed") status = "aborted";
1813
1835
  return {
1814
1836
  requestId,
1815
- status
1837
+ status,
1838
+ ...error !== void 0 && { error }
1816
1839
  };
1817
1840
  }
1818
1841
  /**
@@ -1843,6 +1866,7 @@ var Think = class Think extends Agent {
1843
1866
  const resolvedBody = body ?? this._lastBody;
1844
1867
  const epoch = this._turnQueue.generation;
1845
1868
  let status = "completed";
1869
+ let error;
1846
1870
  let wasAborted = false;
1847
1871
  await this.keepAliveWhile(async () => {
1848
1872
  await this._turnQueue.enqueue(requestId, async () => {
@@ -1865,11 +1889,13 @@ var Think = class Think extends Agent {
1865
1889
  body: resolvedBody,
1866
1890
  continuation: true
1867
1891
  }));
1868
- if (result) await this._streamResult(requestId, result, abortSignal, { continuation: true });
1892
+ if (result) {
1893
+ const streamResult = await this._streamResult(requestId, result, abortSignal, { continuation: true });
1894
+ status = streamResult.status;
1895
+ error = streamResult.error;
1896
+ }
1869
1897
  };
1870
- if (this.chatRecovery) await this.runFiber(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => {
1871
- await continueTurnBody();
1872
- });
1898
+ if (this.chatRecovery) await this._runChatRecoveryFiber(requestId, true, continueTurnBody);
1873
1899
  else await continueTurnBody();
1874
1900
  } finally {
1875
1901
  if (abortSignal?.aborted) wasAborted = true;
@@ -1878,11 +1904,67 @@ var Think = class Think extends Agent {
1878
1904
  }
1879
1905
  });
1880
1906
  });
1881
- if (this._turnQueue.generation !== epoch && status === "completed") status = "skipped";
1907
+ if (this._turnQueue.generation !== epoch && shouldMarkSkippedAfterGenerationChange(status)) status = "skipped";
1908
+ else if (wasAborted && status === "completed") status = "aborted";
1909
+ return {
1910
+ requestId,
1911
+ status,
1912
+ ...error !== void 0 && { error }
1913
+ };
1914
+ }
1915
+ async _retryLastUserTurn(clientTools, body, options) {
1916
+ const lastLeaf = await this.session.getLatestLeaf();
1917
+ if (!lastLeaf || lastLeaf.role !== "user") return {
1918
+ requestId: "",
1919
+ status: "skipped"
1920
+ };
1921
+ const requestId = crypto.randomUUID();
1922
+ const epoch = this._turnQueue.generation;
1923
+ let status = "completed";
1924
+ let error;
1925
+ let wasAborted = false;
1926
+ await this.keepAliveWhile(async () => {
1927
+ await this._turnQueue.enqueue(requestId, async () => {
1928
+ if (this._turnQueue.generation !== epoch) {
1929
+ status = "skipped";
1930
+ return;
1931
+ }
1932
+ const abortSignal = this._aborts.getSignal(requestId);
1933
+ const detachExternal = this._aborts.linkExternal(requestId, options?.signal);
1934
+ try {
1935
+ const retryTurnBody = async () => {
1936
+ const result = await __DO_NOT_USE_WILL_BREAK__agentContext.run({
1937
+ agent: this,
1938
+ connection: void 0,
1939
+ request: void 0,
1940
+ email: void 0
1941
+ }, () => this._runInferenceLoop({
1942
+ signal: abortSignal,
1943
+ clientTools,
1944
+ body,
1945
+ continuation: false
1946
+ }));
1947
+ if (result) {
1948
+ const streamResult = await this._streamResult(requestId, result, abortSignal);
1949
+ status = streamResult.status;
1950
+ error = streamResult.error;
1951
+ }
1952
+ };
1953
+ if (this.chatRecovery) await this._runChatRecoveryFiber(requestId, false, retryTurnBody);
1954
+ else await retryTurnBody();
1955
+ } finally {
1956
+ if (abortSignal?.aborted) wasAborted = true;
1957
+ detachExternal();
1958
+ this._aborts.remove(requestId);
1959
+ }
1960
+ });
1961
+ });
1962
+ if (this._turnQueue.generation !== epoch && shouldMarkSkippedAfterGenerationChange(status)) status = "skipped";
1882
1963
  else if (wasAborted && status === "completed") status = "aborted";
1883
1964
  return {
1884
1965
  requestId,
1885
- status
1966
+ status,
1967
+ ...error !== void 0 && { error }
1886
1968
  };
1887
1969
  }
1888
1970
  _setupProtocolHandlers() {
@@ -2090,9 +2172,7 @@ var Think = class Think extends Agent {
2090
2172
  done: true
2091
2173
  });
2092
2174
  };
2093
- if (this.chatRecovery) await this.runFiber(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => {
2094
- await chatTurnBody();
2095
- });
2175
+ if (this.chatRecovery) await this._runChatRecoveryFiber(requestId, false, chatTurnBody);
2096
2176
  else await chatTurnBody();
2097
2177
  }, { generation: epoch });
2098
2178
  releaseIfPending();
@@ -2205,6 +2285,8 @@ var Think = class Think extends Agent {
2205
2285
  let assistantMsg = null;
2206
2286
  let aborted = false;
2207
2287
  let doneSent = false;
2288
+ let streamError;
2289
+ let pendingRpcError;
2208
2290
  try {
2209
2291
  this._insideInferenceLoop = true;
2210
2292
  let chunksSinceFlush = 0;
@@ -2218,6 +2300,8 @@ var Think = class Think extends Agent {
2218
2300
  const streamChunk = chunk;
2219
2301
  const { action } = accumulator.applyChunk(streamChunk);
2220
2302
  if (action?.type === "error") {
2303
+ streamError = action.error;
2304
+ this._emit("message:error", { error: streamError });
2221
2305
  this._broadcastChat({
2222
2306
  type: MSG_CHAT_RESPONSE,
2223
2307
  id: requestId,
@@ -2225,7 +2309,7 @@ var Think = class Think extends Agent {
2225
2309
  done: false,
2226
2310
  error: true
2227
2311
  });
2228
- continue;
2312
+ break;
2229
2313
  }
2230
2314
  const chunkBody = JSON.stringify(chunk);
2231
2315
  this._resumableStream.storeChunk(streamId, chunkBody);
@@ -2246,7 +2330,8 @@ var Think = class Think extends Agent {
2246
2330
  } finally {
2247
2331
  this._insideInferenceLoop = false;
2248
2332
  }
2249
- this._resumableStream.complete(streamId);
2333
+ if (streamError) this._resumableStream.markError(streamId);
2334
+ else this._resumableStream.complete(streamId);
2250
2335
  streamFinalized = true;
2251
2336
  this._broadcastChat({
2252
2337
  type: MSG_CHAT_RESPONSE,
@@ -2256,9 +2341,20 @@ var Think = class Think extends Agent {
2256
2341
  });
2257
2342
  doneSent = true;
2258
2343
  assistantMsg = accumulator.toMessage();
2259
- await this._persistAssistantMessage(assistantMsg);
2260
- this._broadcastMessages();
2261
- if (!aborted) {
2344
+ if (accumulator.parts.length > 0) {
2345
+ await this._persistAssistantMessage(assistantMsg);
2346
+ this._broadcastMessages();
2347
+ }
2348
+ if (streamError) {
2349
+ await this._fireResponseHook({
2350
+ message: assistantMsg,
2351
+ requestId,
2352
+ continuation: false,
2353
+ status: "error",
2354
+ error: streamError
2355
+ });
2356
+ pendingRpcError = streamError;
2357
+ } else if (!aborted) {
2262
2358
  await callback.onDone();
2263
2359
  await this._fireResponseHook({
2264
2360
  message: assistantMsg,
@@ -2305,6 +2401,8 @@ var Think = class Think extends Agent {
2305
2401
  if (callback.onError) await callback.onError(errorMessage);
2306
2402
  else throw wrapped;
2307
2403
  }
2404
+ if (pendingRpcError) if (callback.onError) await callback.onError(pendingRpcError);
2405
+ else throw new Error(pendingRpcError);
2308
2406
  }
2309
2407
  _shouldFlushRpcStreamChunk(chunk, chunksSinceFlush, hasFlushedContent) {
2310
2408
  return (chunk.type === "text-delta" || chunk.type === "reasoning-delta" || chunk.type === "tool-input-available" || chunk.type === "tool-output-available" || chunk.type === "tool-output-error") && (!hasFlushedContent || chunksSinceFlush >= 10);
@@ -2332,6 +2430,9 @@ var Think = class Think extends Agent {
2332
2430
  }
2333
2431
  const { action } = accumulator.applyChunk(chunk);
2334
2432
  if (action?.type === "error") {
2433
+ streamError = action.error;
2434
+ if (options?.captureProgrammaticStreamError) this._programmaticStreamErrors.set(requestId, streamError);
2435
+ this._emit("message:error", { error: streamError });
2335
2436
  this._broadcastChat({
2336
2437
  type: MSG_CHAT_RESPONSE,
2337
2438
  id: requestId,
@@ -2339,7 +2440,7 @@ var Think = class Think extends Agent {
2339
2440
  done: false,
2340
2441
  error: true
2341
2442
  });
2342
- continue;
2443
+ break;
2343
2444
  }
2344
2445
  const chunkBody = JSON.stringify(chunk);
2345
2446
  this._resumableStream.storeChunk(streamId, chunkBody);
@@ -2353,7 +2454,8 @@ var Think = class Think extends Agent {
2353
2454
  } finally {
2354
2455
  this._insideInferenceLoop = false;
2355
2456
  }
2356
- this._resumableStream.complete(streamId);
2457
+ if (streamError) this._resumableStream.markError(streamId);
2458
+ else this._resumableStream.complete(streamId);
2357
2459
  this._pendingResumeConnections.clear();
2358
2460
  this._broadcastChat({
2359
2461
  type: MSG_CHAT_RESPONSE,
@@ -2389,20 +2491,26 @@ var Think = class Think extends Agent {
2389
2491
  });
2390
2492
  }
2391
2493
  }
2392
- if (accumulator.parts.length > 0 && this._turnQueue.generation === clearGen) try {
2494
+ if (this._turnQueue.generation === clearGen) try {
2393
2495
  const assistantMsg = accumulator.toMessage();
2394
- await this._persistAssistantMessage(assistantMsg, parentId);
2395
- this._broadcastMessages();
2496
+ if (accumulator.parts.length > 0) {
2497
+ await this._persistAssistantMessage(assistantMsg, parentId);
2498
+ this._broadcastMessages();
2499
+ }
2396
2500
  await this._fireResponseHook({
2397
2501
  message: assistantMsg,
2398
2502
  requestId,
2399
2503
  continuation,
2400
- status: streamAborted ? "aborted" : streamError ? "error" : "completed",
2504
+ status: streamError ? "error" : streamAborted ? "aborted" : "completed",
2401
2505
  error: streamError
2402
2506
  });
2403
2507
  } catch (e) {
2404
2508
  console.error("Failed to persist assistant message:", e);
2405
2509
  }
2510
+ return streamError ? {
2511
+ status: "error",
2512
+ error: streamError
2513
+ } : { status: streamAborted ? "aborted" : "completed" };
2406
2514
  }
2407
2515
  async _persistAssistantMessage(msg, parentId) {
2408
2516
  await this._upsertMessageInHistory(msg, parentId);
@@ -2505,6 +2613,7 @@ var Think = class Think extends Agent {
2505
2613
  const chatPrefix = this.constructor.CHAT_FIBER_NAME + ":";
2506
2614
  if (!ctx.name.startsWith(chatPrefix)) return false;
2507
2615
  const requestId = ctx.name.slice(chatPrefix.length);
2616
+ const { snapshot: recoverySnapshot, user: recoveryData } = unwrapChatFiberSnapshot("__cfThinkChatFiberSnapshot", ctx.snapshot, "think-chat-turn");
2508
2617
  let streamId = "";
2509
2618
  let streamStatus;
2510
2619
  if (requestId) {
@@ -2531,30 +2640,78 @@ var Think = class Think extends Agent {
2531
2640
  requestId,
2532
2641
  partialText: partial.text,
2533
2642
  partialParts: partial.parts,
2534
- recoveryData: ctx.snapshot,
2643
+ recoveryData,
2535
2644
  messages: [...this.messages],
2536
- lastBody: this._lastBody,
2537
- lastClientTools: this._lastClientTools,
2645
+ lastBody: recoverySnapshot?.lastBody ?? this._lastBody,
2646
+ lastClientTools: recoverySnapshot?.lastClientTools ?? this._lastClientTools,
2538
2647
  createdAt: ctx.createdAt
2539
- });
2648
+ }) ?? {};
2540
2649
  const streamStillActive = streamId && this._resumableStream.hasActiveStream() && this._resumableStream.activeStreamId === streamId;
2541
2650
  const streamIsTerminal = streamStatus === "completed" || streamStatus === "error";
2542
2651
  if (options.persist !== false && streamId && (streamStillActive || streamIsTerminal)) await this._persistOrphanedStream(streamId);
2543
2652
  if (streamStillActive) this._resumableStream.complete(streamId);
2544
- const canContinue = options.continue !== false && !streamIsTerminal;
2653
+ const retryTargetUserId = await this._recoverablePreStreamUserId(recoverySnapshot, streamId ?? "", partial);
2654
+ const shouldRetry = retryTargetUserId !== null && options.continue !== false && !streamIsTerminal;
2655
+ const canContinue = !shouldRetry && options.continue !== false && !streamIsTerminal;
2545
2656
  const hasRunningSubmission = this._hasRunningSubmission(requestId);
2546
2657
  if (streamIsTerminal && hasRunningSubmission) await this._completeRecoveredSubmission(requestId, streamStatus === "completed" ? "completed" : "error", requestId, streamStatus === "completed" ? null : "Recovered chat stream had already errored.");
2547
- const recoveredRequestId = canContinue && hasRunningSubmission ? requestId : void 0;
2548
- if (canContinue) {
2658
+ const recoveredRequestId = (canContinue || shouldRetry) && hasRunningSubmission ? requestId : void 0;
2659
+ if (shouldRetry) await this.schedule(0, "_chatRecoveryRetry", {
2660
+ targetUserId: retryTargetUserId,
2661
+ originalRequestId: requestId,
2662
+ lastBody: recoverySnapshot?.lastBody ?? null,
2663
+ lastClientTools: recoverySnapshot?.lastClientTools ?? null,
2664
+ ...recoveredRequestId ? { recoveredRequestId } : {}
2665
+ }, { idempotent: true });
2666
+ else if (canContinue) {
2549
2667
  const lastLeaf = await this.session.getLatestLeaf();
2550
2668
  const targetId = lastLeaf?.role === "assistant" ? lastLeaf.id : void 0;
2551
2669
  await this.schedule(0, "_chatRecoveryContinue", {
2552
2670
  ...targetId ? { targetAssistantId: targetId } : {},
2671
+ originalRequestId: requestId,
2672
+ ...recoverySnapshot ? {
2673
+ lastBody: recoverySnapshot.lastBody ?? null,
2674
+ lastClientTools: recoverySnapshot.lastClientTools ?? null
2675
+ } : {},
2553
2676
  ...recoveredRequestId ? { recoveredRequestId } : {}
2554
2677
  }, { idempotent: true });
2555
2678
  } else if (options.continue === false && !streamIsTerminal) await this._markRecoveredSubmissionInterrupted(requestId, "Submission was interrupted and chat recovery was disabled.");
2556
2679
  return true;
2557
2680
  }
2681
+ async _recoverablePreStreamUserId(snapshot, streamId, partial) {
2682
+ if (!snapshot || snapshot.continuation || !snapshot.latestUserMessageId || streamId || partial.text || partial.parts.length > 0) return null;
2683
+ const lastLeaf = await this.session.getLatestLeaf();
2684
+ return lastLeaf?.role === "user" && lastLeaf.id === snapshot.latestUserMessageId ? snapshot.latestUserMessageId : null;
2685
+ }
2686
+ async _chatRecoveryRetry(data) {
2687
+ const recoveredSubmission = data?.recoveredRequestId ? this._readRunningSubmissionByRequestId(data.recoveredRequestId) : null;
2688
+ if (data?.recoveredRequestId && !recoveredSubmission) return;
2689
+ const controller = recoveredSubmission ? new AbortController() : null;
2690
+ if (recoveredSubmission && controller) this._submissionAbortControllers.set(recoveredSubmission.submission_id, controller);
2691
+ try {
2692
+ if (!await this.waitUntilStable({ timeout: 1e4 })) {
2693
+ if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, "error", null, "Recovered chat retry timed out waiting for stable state.");
2694
+ return;
2695
+ }
2696
+ const lastLeaf = await this.session.getLatestLeaf();
2697
+ if (!lastLeaf || lastLeaf.role !== "user") {
2698
+ if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, "error", null, "Recovered chat retry was skipped because there is no unanswered user message.");
2699
+ return;
2700
+ }
2701
+ if (data?.targetUserId && lastLeaf.id !== data.targetUserId) {
2702
+ if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, "error", null, "Recovered chat retry was skipped because the conversation changed.");
2703
+ return;
2704
+ }
2705
+ this._applyRecoveredRequestContext(data);
2706
+ const result = await this._retryLastUserTurn(this._lastClientTools, this._lastBody, controller ? { signal: controller.signal } : void 0);
2707
+ if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, result.status, result.requestId || null, result.status === "completed" ? null : result.error ?? `Recovery retry ${result.status}.`);
2708
+ } catch (error) {
2709
+ if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, "error", null, error instanceof Error ? error.message : String(error));
2710
+ throw error;
2711
+ } finally {
2712
+ if (recoveredSubmission) this._submissionAbortControllers.delete(recoveredSubmission.submission_id);
2713
+ }
2714
+ }
2558
2715
  _hasRunningSubmission(requestId) {
2559
2716
  return this._readRunningSubmissionByRequestId(requestId) !== null;
2560
2717
  }
@@ -2638,8 +2795,9 @@ var Think = class Think extends Agent {
2638
2795
  if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, "error", null, "Recovered chat continuation was skipped because the conversation changed.");
2639
2796
  return;
2640
2797
  }
2798
+ this._applyRecoveredRequestContext(data);
2641
2799
  const result = await this.continueLastTurn(void 0, controller ? { signal: controller.signal } : void 0);
2642
- if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, result.status, result.requestId || null, result.status === "completed" ? null : `Recovery ${result.status}.`);
2800
+ if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, result.status, result.requestId || null, result.status === "completed" ? null : result.error ?? `Recovery ${result.status}.`);
2643
2801
  } catch (error) {
2644
2802
  if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, "error", null, error instanceof Error ? error.message : String(error));
2645
2803
  throw error;
@@ -2647,6 +2805,17 @@ var Think = class Think extends Agent {
2647
2805
  if (recoveredSubmission) this._submissionAbortControllers.delete(recoveredSubmission.submission_id);
2648
2806
  }
2649
2807
  }
2808
+ _applyRecoveredRequestContext(data) {
2809
+ if (!data) return;
2810
+ if ("lastClientTools" in data) {
2811
+ this._lastClientTools = data.lastClientTools ?? void 0;
2812
+ this._persistClientTools();
2813
+ }
2814
+ if ("lastBody" in data) {
2815
+ this._lastBody = data.lastBody ?? void 0;
2816
+ this._persistBody();
2817
+ }
2818
+ }
2650
2819
  _getPartialStreamText(streamId) {
2651
2820
  const chunks = this._resumableStream.getStreamChunks(streamId);
2652
2821
  const parts = [];
@@ -2743,9 +2912,7 @@ var Think = class Think extends Agent {
2743
2912
  streamed = true;
2744
2913
  }
2745
2914
  };
2746
- if (this.chatRecovery) await this.runFiber(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => {
2747
- await continuationBody();
2748
- });
2915
+ if (this.chatRecovery) await this._runChatRecoveryFiber(requestId, true, continuationBody);
2749
2916
  else await continuationBody();
2750
2917
  } finally {
2751
2918
  this._aborts.remove(requestId);