@cloudflare/think 0.7.1 → 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)}`;
@@ -943,6 +960,7 @@ var Think = class Think extends Agent {
943
960
  }]
944
961
  } : userMessage;
945
962
  await this._appendMessageToHistory(userMsg);
963
+ this._broadcastMessages();
946
964
  const chatBody = async () => {
947
965
  let result;
948
966
  try {
@@ -966,9 +984,7 @@ var Think = class Think extends Agent {
966
984
  }
967
985
  await this._streamResultToRpcCallback(requestId, result, callback, abortSignal);
968
986
  };
969
- if (this.chatRecovery) await this.runFiber(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => {
970
- await chatBody();
971
- });
987
+ if (this.chatRecovery) await this._runChatRecoveryFiber(requestId, false, chatBody);
972
988
  else await chatBody();
973
989
  });
974
990
  });
@@ -985,6 +1001,7 @@ var Think = class Think extends Agent {
985
1001
  async clearMessages() {
986
1002
  this.resetTurnState();
987
1003
  await this._clearHistory();
1004
+ this._broadcast({ type: MSG_CHAT_CLEAR });
988
1005
  }
989
1006
  _ensureAgentToolChildRunTable() {
990
1007
  this.sql`
@@ -1068,6 +1085,7 @@ var Think = class Think extends Agent {
1068
1085
  this._agentToolAbortControllers.set(options.runId, controller);
1069
1086
  this._agentToolLiveSequences.set(options.runId, 0);
1070
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;
1071
1089
  this.keepAliveWhile(async () => {
1072
1090
  try {
1073
1091
  this.sql`
@@ -1079,9 +1097,9 @@ var Think = class Think extends Agent {
1079
1097
  const streamId = this._resumableStream.getAllStreamMetadata().find((m) => m.request_id === result.requestId)?.id ?? null;
1080
1098
  const output = this.getAgentToolOutput(options.runId);
1081
1099
  const summary = this.getAgentToolSummary(options.runId, output);
1082
- const streamError = this._agentToolLastErrors.get(options.runId);
1083
- const skipped = result.status === "skipped";
1084
- 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";
1085
1103
  const error = status === "error" ? streamError ?? "Agent tool run was skipped before the child could finish." : null;
1086
1104
  this.sql`
1087
1105
  UPDATE cf_agent_tool_child_runs
@@ -1093,6 +1111,7 @@ var Think = class Think extends Agent {
1093
1111
  error_message = ${error},
1094
1112
  completed_at = ${Date.now()}
1095
1113
  WHERE run_id = ${options.runId}
1114
+ AND completed_at IS NULL
1096
1115
  `;
1097
1116
  } catch (error) {
1098
1117
  this.sql`
@@ -1101,6 +1120,7 @@ var Think = class Think extends Agent {
1101
1120
  error_message = ${error instanceof Error ? error.message : String(error)},
1102
1121
  completed_at = ${Date.now()}
1103
1122
  WHERE run_id = ${options.runId}
1123
+ AND completed_at IS NULL
1104
1124
  `;
1105
1125
  } finally {
1106
1126
  this._agentToolAbortControllers.delete(options.runId);
@@ -1540,13 +1560,14 @@ var Think = class Think extends Agent {
1540
1560
  });
1541
1561
  const streamId = this._resumableStream.getAllStreamMetadata().find((metadata) => metadata.request_id === result.requestId)?.id ?? null;
1542
1562
  const streamError = this._programmaticStreamErrors.get(result.requestId);
1543
- const finalStatus = this._getSubmissionFinalStatus(result.status, streamError);
1563
+ const finalStatus = this._getSubmissionFinalStatus(result.status, result.error ?? streamError);
1564
+ const errorMessage = result.error ?? streamError ?? null;
1544
1565
  this.sql`
1545
1566
  UPDATE cf_think_submissions
1546
1567
  SET status = ${finalStatus},
1547
1568
  request_id = ${result.requestId},
1548
1569
  stream_id = ${streamId},
1549
- error_message = ${finalStatus === "error" ? streamError ?? null : null},
1570
+ error_message = ${finalStatus === "error" ? errorMessage : null},
1550
1571
  completed_at = ${Date.now()}
1551
1572
  WHERE submission_id = ${row.submission_id}
1552
1573
  AND status = 'running'
@@ -1763,6 +1784,7 @@ var Think = class Think extends Agent {
1763
1784
  const body = this._lastBody;
1764
1785
  const epoch = this._turnQueue.generation;
1765
1786
  let status = "completed";
1787
+ let error;
1766
1788
  let wasAborted = false;
1767
1789
  await this.keepAliveWhile(async () => {
1768
1790
  await this._turnQueue.enqueue(requestId, async () => {
@@ -1793,11 +1815,13 @@ var Think = class Think extends Agent {
1793
1815
  body,
1794
1816
  continuation: false
1795
1817
  }));
1796
- 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
+ }
1797
1823
  };
1798
- if (this.chatRecovery) await this.runFiber(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => {
1799
- await programmaticBody();
1800
- });
1824
+ if (this.chatRecovery) await this._runChatRecoveryFiber(requestId, false, programmaticBody);
1801
1825
  else await programmaticBody();
1802
1826
  } finally {
1803
1827
  if (abortSignal?.aborted) wasAborted = true;
@@ -1806,11 +1830,12 @@ var Think = class Think extends Agent {
1806
1830
  }
1807
1831
  });
1808
1832
  });
1809
- if (this._turnQueue.generation !== epoch && status === "completed") status = "skipped";
1833
+ if (this._turnQueue.generation !== epoch && shouldMarkSkippedAfterGenerationChange(status)) status = "skipped";
1810
1834
  else if (wasAborted && status === "completed") status = "aborted";
1811
1835
  return {
1812
1836
  requestId,
1813
- status
1837
+ status,
1838
+ ...error !== void 0 && { error }
1814
1839
  };
1815
1840
  }
1816
1841
  /**
@@ -1841,6 +1866,7 @@ var Think = class Think extends Agent {
1841
1866
  const resolvedBody = body ?? this._lastBody;
1842
1867
  const epoch = this._turnQueue.generation;
1843
1868
  let status = "completed";
1869
+ let error;
1844
1870
  let wasAborted = false;
1845
1871
  await this.keepAliveWhile(async () => {
1846
1872
  await this._turnQueue.enqueue(requestId, async () => {
@@ -1863,11 +1889,13 @@ var Think = class Think extends Agent {
1863
1889
  body: resolvedBody,
1864
1890
  continuation: true
1865
1891
  }));
1866
- 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
+ }
1867
1897
  };
1868
- if (this.chatRecovery) await this.runFiber(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => {
1869
- await continueTurnBody();
1870
- });
1898
+ if (this.chatRecovery) await this._runChatRecoveryFiber(requestId, true, continueTurnBody);
1871
1899
  else await continueTurnBody();
1872
1900
  } finally {
1873
1901
  if (abortSignal?.aborted) wasAborted = true;
@@ -1876,11 +1904,67 @@ var Think = class Think extends Agent {
1876
1904
  }
1877
1905
  });
1878
1906
  });
1879
- 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";
1880
1963
  else if (wasAborted && status === "completed") status = "aborted";
1881
1964
  return {
1882
1965
  requestId,
1883
- status
1966
+ status,
1967
+ ...error !== void 0 && { error }
1884
1968
  };
1885
1969
  }
1886
1970
  _setupProtocolHandlers() {
@@ -2088,9 +2172,7 @@ var Think = class Think extends Agent {
2088
2172
  done: true
2089
2173
  });
2090
2174
  };
2091
- if (this.chatRecovery) await this.runFiber(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => {
2092
- await chatTurnBody();
2093
- });
2175
+ if (this.chatRecovery) await this._runChatRecoveryFiber(requestId, false, chatTurnBody);
2094
2176
  else await chatTurnBody();
2095
2177
  }, { generation: epoch });
2096
2178
  releaseIfPending();
@@ -2202,6 +2284,9 @@ var Think = class Think extends Agent {
2202
2284
  let streamFinalized = false;
2203
2285
  let assistantMsg = null;
2204
2286
  let aborted = false;
2287
+ let doneSent = false;
2288
+ let streamError;
2289
+ let pendingRpcError;
2205
2290
  try {
2206
2291
  this._insideInferenceLoop = true;
2207
2292
  let chunksSinceFlush = 0;
@@ -2213,7 +2298,19 @@ var Think = class Think extends Agent {
2213
2298
  break;
2214
2299
  }
2215
2300
  const streamChunk = chunk;
2216
- accumulator.applyChunk(streamChunk);
2301
+ const { action } = accumulator.applyChunk(streamChunk);
2302
+ if (action?.type === "error") {
2303
+ streamError = action.error;
2304
+ this._emit("message:error", { error: streamError });
2305
+ this._broadcastChat({
2306
+ type: MSG_CHAT_RESPONSE,
2307
+ id: requestId,
2308
+ body: action.error,
2309
+ done: false,
2310
+ error: true
2311
+ });
2312
+ break;
2313
+ }
2217
2314
  const chunkBody = JSON.stringify(chunk);
2218
2315
  this._resumableStream.storeChunk(streamId, chunkBody);
2219
2316
  chunksSinceFlush++;
@@ -2222,16 +2319,42 @@ var Think = class Think extends Agent {
2222
2319
  chunksSinceFlush = 0;
2223
2320
  hasFlushedContent = true;
2224
2321
  }
2322
+ this._broadcastChat({
2323
+ type: MSG_CHAT_RESPONSE,
2324
+ id: requestId,
2325
+ body: chunkBody,
2326
+ done: false
2327
+ });
2225
2328
  await callback.onEvent(chunkBody);
2226
2329
  }
2227
2330
  } finally {
2228
2331
  this._insideInferenceLoop = false;
2229
2332
  }
2230
- this._resumableStream.complete(streamId);
2333
+ if (streamError) this._resumableStream.markError(streamId);
2334
+ else this._resumableStream.complete(streamId);
2231
2335
  streamFinalized = true;
2336
+ this._broadcastChat({
2337
+ type: MSG_CHAT_RESPONSE,
2338
+ id: requestId,
2339
+ body: "",
2340
+ done: true
2341
+ });
2342
+ doneSent = true;
2232
2343
  assistantMsg = accumulator.toMessage();
2233
- await this._persistAssistantMessage(assistantMsg);
2234
- 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) {
2235
2358
  await callback.onDone();
2236
2359
  await this._fireResponseHook({
2237
2360
  message: assistantMsg,
@@ -2250,9 +2373,21 @@ var Think = class Think extends Agent {
2250
2373
  this._resumableStream.markError(streamId);
2251
2374
  streamFinalized = true;
2252
2375
  }
2376
+ if (!doneSent) {
2377
+ const streamError = error instanceof Error ? error.message : "Stream error";
2378
+ this._broadcastChat({
2379
+ type: MSG_CHAT_RESPONSE,
2380
+ id: requestId,
2381
+ body: streamError,
2382
+ done: true,
2383
+ error: true
2384
+ });
2385
+ doneSent = true;
2386
+ }
2253
2387
  if (!assistantMsg && accumulator.parts.length > 0) {
2254
2388
  assistantMsg = accumulator.toMessage();
2255
2389
  await this._persistAssistantMessage(assistantMsg);
2390
+ this._broadcastMessages();
2256
2391
  }
2257
2392
  const wrapped = this.onChatError(error);
2258
2393
  const errorMessage = wrapped instanceof Error ? wrapped.message : String(wrapped);
@@ -2266,6 +2401,8 @@ var Think = class Think extends Agent {
2266
2401
  if (callback.onError) await callback.onError(errorMessage);
2267
2402
  else throw wrapped;
2268
2403
  }
2404
+ if (pendingRpcError) if (callback.onError) await callback.onError(pendingRpcError);
2405
+ else throw new Error(pendingRpcError);
2269
2406
  }
2270
2407
  _shouldFlushRpcStreamChunk(chunk, chunksSinceFlush, hasFlushedContent) {
2271
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);
@@ -2293,6 +2430,9 @@ var Think = class Think extends Agent {
2293
2430
  }
2294
2431
  const { action } = accumulator.applyChunk(chunk);
2295
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 });
2296
2436
  this._broadcastChat({
2297
2437
  type: MSG_CHAT_RESPONSE,
2298
2438
  id: requestId,
@@ -2300,7 +2440,7 @@ var Think = class Think extends Agent {
2300
2440
  done: false,
2301
2441
  error: true
2302
2442
  });
2303
- continue;
2443
+ break;
2304
2444
  }
2305
2445
  const chunkBody = JSON.stringify(chunk);
2306
2446
  this._resumableStream.storeChunk(streamId, chunkBody);
@@ -2314,7 +2454,8 @@ var Think = class Think extends Agent {
2314
2454
  } finally {
2315
2455
  this._insideInferenceLoop = false;
2316
2456
  }
2317
- this._resumableStream.complete(streamId);
2457
+ if (streamError) this._resumableStream.markError(streamId);
2458
+ else this._resumableStream.complete(streamId);
2318
2459
  this._pendingResumeConnections.clear();
2319
2460
  this._broadcastChat({
2320
2461
  type: MSG_CHAT_RESPONSE,
@@ -2350,20 +2491,26 @@ var Think = class Think extends Agent {
2350
2491
  });
2351
2492
  }
2352
2493
  }
2353
- if (accumulator.parts.length > 0 && this._turnQueue.generation === clearGen) try {
2494
+ if (this._turnQueue.generation === clearGen) try {
2354
2495
  const assistantMsg = accumulator.toMessage();
2355
- await this._persistAssistantMessage(assistantMsg, parentId);
2356
- this._broadcastMessages();
2496
+ if (accumulator.parts.length > 0) {
2497
+ await this._persistAssistantMessage(assistantMsg, parentId);
2498
+ this._broadcastMessages();
2499
+ }
2357
2500
  await this._fireResponseHook({
2358
2501
  message: assistantMsg,
2359
2502
  requestId,
2360
2503
  continuation,
2361
- status: streamAborted ? "aborted" : streamError ? "error" : "completed",
2504
+ status: streamError ? "error" : streamAborted ? "aborted" : "completed",
2362
2505
  error: streamError
2363
2506
  });
2364
2507
  } catch (e) {
2365
2508
  console.error("Failed to persist assistant message:", e);
2366
2509
  }
2510
+ return streamError ? {
2511
+ status: "error",
2512
+ error: streamError
2513
+ } : { status: streamAborted ? "aborted" : "completed" };
2367
2514
  }
2368
2515
  async _persistAssistantMessage(msg, parentId) {
2369
2516
  await this._upsertMessageInHistory(msg, parentId);
@@ -2466,6 +2613,7 @@ var Think = class Think extends Agent {
2466
2613
  const chatPrefix = this.constructor.CHAT_FIBER_NAME + ":";
2467
2614
  if (!ctx.name.startsWith(chatPrefix)) return false;
2468
2615
  const requestId = ctx.name.slice(chatPrefix.length);
2616
+ const { snapshot: recoverySnapshot, user: recoveryData } = unwrapChatFiberSnapshot("__cfThinkChatFiberSnapshot", ctx.snapshot, "think-chat-turn");
2469
2617
  let streamId = "";
2470
2618
  let streamStatus;
2471
2619
  if (requestId) {
@@ -2492,30 +2640,78 @@ var Think = class Think extends Agent {
2492
2640
  requestId,
2493
2641
  partialText: partial.text,
2494
2642
  partialParts: partial.parts,
2495
- recoveryData: ctx.snapshot,
2643
+ recoveryData,
2496
2644
  messages: [...this.messages],
2497
- lastBody: this._lastBody,
2498
- lastClientTools: this._lastClientTools,
2645
+ lastBody: recoverySnapshot?.lastBody ?? this._lastBody,
2646
+ lastClientTools: recoverySnapshot?.lastClientTools ?? this._lastClientTools,
2499
2647
  createdAt: ctx.createdAt
2500
- });
2648
+ }) ?? {};
2501
2649
  const streamStillActive = streamId && this._resumableStream.hasActiveStream() && this._resumableStream.activeStreamId === streamId;
2502
2650
  const streamIsTerminal = streamStatus === "completed" || streamStatus === "error";
2503
2651
  if (options.persist !== false && streamId && (streamStillActive || streamIsTerminal)) await this._persistOrphanedStream(streamId);
2504
2652
  if (streamStillActive) this._resumableStream.complete(streamId);
2505
- 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;
2506
2656
  const hasRunningSubmission = this._hasRunningSubmission(requestId);
2507
2657
  if (streamIsTerminal && hasRunningSubmission) await this._completeRecoveredSubmission(requestId, streamStatus === "completed" ? "completed" : "error", requestId, streamStatus === "completed" ? null : "Recovered chat stream had already errored.");
2508
- const recoveredRequestId = canContinue && hasRunningSubmission ? requestId : void 0;
2509
- 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) {
2510
2667
  const lastLeaf = await this.session.getLatestLeaf();
2511
2668
  const targetId = lastLeaf?.role === "assistant" ? lastLeaf.id : void 0;
2512
2669
  await this.schedule(0, "_chatRecoveryContinue", {
2513
2670
  ...targetId ? { targetAssistantId: targetId } : {},
2671
+ originalRequestId: requestId,
2672
+ ...recoverySnapshot ? {
2673
+ lastBody: recoverySnapshot.lastBody ?? null,
2674
+ lastClientTools: recoverySnapshot.lastClientTools ?? null
2675
+ } : {},
2514
2676
  ...recoveredRequestId ? { recoveredRequestId } : {}
2515
2677
  }, { idempotent: true });
2516
2678
  } else if (options.continue === false && !streamIsTerminal) await this._markRecoveredSubmissionInterrupted(requestId, "Submission was interrupted and chat recovery was disabled.");
2517
2679
  return true;
2518
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
+ }
2519
2715
  _hasRunningSubmission(requestId) {
2520
2716
  return this._readRunningSubmissionByRequestId(requestId) !== null;
2521
2717
  }
@@ -2599,8 +2795,9 @@ var Think = class Think extends Agent {
2599
2795
  if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, "error", null, "Recovered chat continuation was skipped because the conversation changed.");
2600
2796
  return;
2601
2797
  }
2798
+ this._applyRecoveredRequestContext(data);
2602
2799
  const result = await this.continueLastTurn(void 0, controller ? { signal: controller.signal } : void 0);
2603
- 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}.`);
2604
2801
  } catch (error) {
2605
2802
  if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, "error", null, error instanceof Error ? error.message : String(error));
2606
2803
  throw error;
@@ -2608,6 +2805,17 @@ var Think = class Think extends Agent {
2608
2805
  if (recoveredSubmission) this._submissionAbortControllers.delete(recoveredSubmission.submission_id);
2609
2806
  }
2610
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
+ }
2611
2819
  _getPartialStreamText(streamId) {
2612
2820
  const chunks = this._resumableStream.getStreamChunks(streamId);
2613
2821
  const parts = [];
@@ -2704,9 +2912,7 @@ var Think = class Think extends Agent {
2704
2912
  streamed = true;
2705
2913
  }
2706
2914
  };
2707
- if (this.chatRecovery) await this.runFiber(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => {
2708
- await continuationBody();
2709
- });
2915
+ if (this.chatRecovery) await this._runChatRecoveryFiber(requestId, true, continuationBody);
2710
2916
  else await continuationBody();
2711
2917
  } finally {
2712
2918
  this._aborts.remove(requestId);