@cloudflare/think 0.6.1 → 0.7.1

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.js CHANGED
@@ -1,4 +1,4 @@
1
- import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldSet2, t as _classPrivateFieldGet2 } from "./classPrivateFieldGet2-CCiYk1x3.js";
1
+ import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldSet2, t as _classPrivateFieldGet2 } from "./classPrivateFieldGet2-BP1jgEfY.js";
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";
@@ -40,6 +40,7 @@ var Think = class Think extends Agent {
40
40
  this.waitForMcpConnections = false;
41
41
  this.messageConcurrency = "queue";
42
42
  this.chatRecovery = true;
43
+ this._cachedMessages = [];
43
44
  this._aborts = new AbortRegistry();
44
45
  this._turnQueue = new TurnQueue();
45
46
  this._pendingResumeConnections = /* @__PURE__ */ new Set();
@@ -72,7 +73,25 @@ var Think = class Think extends Agent {
72
73
  });
73
74
  const baseSession = Session$1.create(this);
74
75
  this.session = await this.configureSession(baseSession);
75
- this.session.getHistory();
76
+ this.session.internal_onMessagesChanged(async (event) => {
77
+ switch (event.type) {
78
+ case "append":
79
+ if (!event.inserted || event.parentId !== void 0) await this._syncMessages();
80
+ else this._upsertCachedMessage(event.message);
81
+ break;
82
+ case "update":
83
+ this._patchCachedMessage(event.message);
84
+ break;
85
+ case "clear":
86
+ this._replaceCachedMessages([]);
87
+ break;
88
+ case "delete":
89
+ case "compact":
90
+ await this._syncMessages();
91
+ break;
92
+ }
93
+ });
94
+ await this._syncMessages();
76
95
  if (this.extensionLoader) await this._initializeExtensions();
77
96
  this._resumableStream = new ResumableStream(this.sql.bind(this));
78
97
  this._restoreClientTools();
@@ -84,11 +103,70 @@ var Think = class Think extends Agent {
84
103
  };
85
104
  }
86
105
  /**
87
- * Conversation history. Computed from the active session.
88
- * Always fresh — reads from Session's tree-structured storage.
106
+ * Conversation history as Think's live in-memory view.
107
+ *
108
+ * Storage remains the durable source of truth, but runtime logic should read
109
+ * through this cache so in-flight turns, tool updates, and recovery state all
110
+ * observe the same message list. Use `_syncMessages()` only at safe
111
+ * boundaries where a full storage reread cannot drop in-flight state.
89
112
  */
90
113
  get messages() {
91
- return this.session.getHistory();
114
+ return this._cachedMessages;
115
+ }
116
+ /** Read the durable message path from session storage. */
117
+ async _readMessagesFromStorage() {
118
+ return await this.session.getHistory();
119
+ }
120
+ /** Replace the live cache with a durable storage snapshot. */
121
+ _replaceCachedMessages(messages) {
122
+ this._cachedMessages = messages;
123
+ return this._cachedMessages;
124
+ }
125
+ /** Refresh the live cache from durable storage at a safe boundary. */
126
+ async _syncMessages() {
127
+ return this._replaceCachedMessages(await this._readMessagesFromStorage());
128
+ }
129
+ /** Patch or append one message in the live cache after a durable write. */
130
+ _upsertCachedMessage(message) {
131
+ const index = this._cachedMessages.findIndex((m) => m.id === message.id);
132
+ if (index === -1) this._cachedMessages.push(message);
133
+ else this._cachedMessages[index] = message;
134
+ }
135
+ /** Patch a message that is already present in the live cache. */
136
+ _patchCachedMessage(message) {
137
+ const index = this._cachedMessages.findIndex((m) => m.id === message.id);
138
+ if (index !== -1) this._cachedMessages[index] = message;
139
+ }
140
+ async _appendMessageToHistory(message, parentId) {
141
+ const safe = enforceRowSizeLimit(sanitizeMessage(message));
142
+ await this.session.appendMessage(safe, parentId);
143
+ return safe;
144
+ }
145
+ async _updateMessageInHistory(message) {
146
+ const safe = enforceRowSizeLimit(sanitizeMessage(message));
147
+ await this.session.updateMessage(safe);
148
+ return safe;
149
+ }
150
+ async _upsertMessageInHistory(message, parentId) {
151
+ const safe = enforceRowSizeLimit(sanitizeMessage(message));
152
+ if (await this.session.getMessage(safe.id)) await this.session.updateMessage(safe);
153
+ else await this.session.appendMessage(safe, parentId);
154
+ return safe;
155
+ }
156
+ async _clearHistory() {
157
+ await this.session.clearMessages();
158
+ }
159
+ /** Append a message while keeping Think's live message cache coherent. */
160
+ appendMessageToHistory(message, parentId) {
161
+ return this._appendMessageToHistory(message, parentId);
162
+ }
163
+ /** Update a message while keeping Think's live message cache coherent. */
164
+ updateMessageInHistory(message) {
165
+ return this._updateMessageInHistory(message);
166
+ }
167
+ /** Refresh Think's live message cache from the durable session path. */
168
+ async syncMessagesFromStorage() {
169
+ return (await this._syncMessages()).slice();
92
170
  }
93
171
  broadcast(msg, without) {
94
172
  if (this._agentToolForwarders.size > 0 && typeof msg === "string") try {
@@ -434,8 +512,8 @@ var Think = class Think extends Agent {
434
512
  return error;
435
513
  }
436
514
  async _initializeExtensions() {
437
- const { ExtensionManager } = await import("./manager-BypfrNX0.js").then((n) => n.n);
438
- const { sanitizeName } = await import("./manager-BypfrNX0.js").then((n) => n.n);
515
+ const { ExtensionManager } = await import("./manager-px912SoZ.js").then((n) => n.n);
516
+ const { sanitizeName } = await import("./manager-px912SoZ.js").then((n) => n.n);
439
517
  const agentClassName = this.constructor.name;
440
518
  const agentId = this.ctx.id.toString();
441
519
  const ctxExports = this.ctx.exports;
@@ -495,7 +573,8 @@ var Think = class Think extends Agent {
495
573
  };
496
574
  const baseSystem = await this.session.freezeSystemPrompt() || this.getSystemPrompt();
497
575
  const system = this._systemPromptForTurn(baseSystem, tools);
498
- const messages = await convertToModelMessages(truncateOlderMessages(this.session.getHistory()), { tools });
576
+ const history = this.messages;
577
+ const messages = await convertToModelMessages(truncateOlderMessages(history), { tools });
499
578
  if (messages.length === 0) throw new Error("No messages to send to the model. This usually means the chat request arrived before any messages were persisted.");
500
579
  const model = this.getModel();
501
580
  const ctx = {
@@ -521,6 +600,7 @@ var Think = class Think extends Agent {
521
600
  const finalTools = this._wrapToolsWithDecision(mergedTools);
522
601
  const finalMaxSteps = config.maxSteps ?? this.maxSteps;
523
602
  const finalSendReasoning = config.sendReasoning ?? this.sendReasoning;
603
+ const finalStopWhen = [stepCountIs(finalMaxSteps), ...Array.isArray(config.stopWhen) ? config.stopWhen : config.stopWhen ? [config.stopWhen] : []];
524
604
  const result = streamText({
525
605
  model: finalModel,
526
606
  system: finalSystem,
@@ -539,7 +619,7 @@ var Think = class Think extends Agent {
539
619
  maxRetries: config.maxRetries,
540
620
  timeout: config.timeout,
541
621
  headers: config.headers,
542
- stopWhen: stepCountIs(finalMaxSteps),
622
+ stopWhen: finalStopWhen,
543
623
  providerOptions: config.providerOptions,
544
624
  experimental_telemetry: config.experimental_telemetry,
545
625
  output: config.output,
@@ -814,7 +894,7 @@ var Think = class Think extends Agent {
814
894
  await this.session.replaceContextBlock(label, content);
815
895
  }
816
896
  async _hostGetMessages(limit) {
817
- const history = this.session.getHistory();
897
+ const history = this.messages;
818
898
  return (limit !== void 0 && limit !== null ? limit <= 0 ? [] : history.slice(-limit) : history).map((m) => ({
819
899
  id: m.id,
820
900
  role: m.role,
@@ -830,10 +910,10 @@ var Think = class Think extends Agent {
830
910
  text: content
831
911
  }]
832
912
  };
833
- await this.session.appendMessage(msg);
913
+ await this._appendMessageToHistory(msg);
834
914
  }
835
915
  async _hostGetSessionInfo() {
836
- return { messageCount: this.session.getHistory().length };
916
+ return { messageCount: this.messages.length };
837
917
  }
838
918
  /**
839
919
  * Run a chat turn: persist the user message, run the agentic loop,
@@ -846,22 +926,23 @@ var Think = class Think extends Agent {
846
926
  */
847
927
  async chat(userMessage, callback, options) {
848
928
  const requestId = crypto.randomUUID();
929
+ const abortSignal = this._aborts.getSignal(requestId);
930
+ const detachExternal = this._aborts.linkExternal(requestId, options?.signal);
849
931
  const ignoredTools = options?.tools;
850
932
  if (ignoredTools != null && typeof ignoredTools === "object" && Object.keys(ignoredTools).length > 0) console.warn("[Think] chat() no longer accepts options.tools. Define durable tools on the child agent with getTools(), or use runAgentTool()/agentTool() for parent-child orchestration.");
851
- await this.keepAliveWhile(async () => {
852
- await this._turnQueue.enqueue(requestId, async () => {
853
- const userMsg = typeof userMessage === "string" ? {
854
- id: crypto.randomUUID(),
855
- role: "user",
856
- parts: [{
857
- type: "text",
858
- text: userMessage
859
- }]
860
- } : userMessage;
861
- await this.session.appendMessage(userMsg);
862
- const abortSignal = this._aborts.getSignal(requestId);
863
- const detachExternal = this._aborts.linkExternal(requestId, options?.signal);
864
- try {
933
+ try {
934
+ await callback.onStart?.({ requestId });
935
+ await this.keepAliveWhile(async () => {
936
+ await this._turnQueue.enqueue(requestId, async () => {
937
+ const userMsg = typeof userMessage === "string" ? {
938
+ id: crypto.randomUUID(),
939
+ role: "user",
940
+ parts: [{
941
+ type: "text",
942
+ text: userMessage
943
+ }]
944
+ } : userMessage;
945
+ await this._appendMessageToHistory(userMsg);
865
946
  const chatBody = async () => {
866
947
  let result;
867
948
  try {
@@ -889,21 +970,21 @@ var Think = class Think extends Agent {
889
970
  await chatBody();
890
971
  });
891
972
  else await chatBody();
892
- } finally {
893
- detachExternal();
894
- this._aborts.remove(requestId);
895
- }
973
+ });
896
974
  });
897
- });
975
+ } finally {
976
+ detachExternal();
977
+ this._aborts.remove(requestId);
978
+ }
898
979
  }
899
980
  /** Get the conversation history as UIMessage[]. */
900
- getMessages() {
901
- return this.messages;
981
+ async getMessages() {
982
+ return this.messages.slice();
902
983
  }
903
984
  /** Clear all messages from storage. */
904
- clearMessages() {
985
+ async clearMessages() {
905
986
  this.resetTurnState();
906
- this.session.clearMessages();
987
+ await this._clearHistory();
907
988
  }
908
989
  _ensureAgentToolChildRunTable() {
909
990
  this.sql`
@@ -1526,7 +1607,7 @@ var Think = class Think extends Agent {
1526
1607
  if (row.messages_applied_at === null) {
1527
1608
  let appliedState;
1528
1609
  try {
1529
- appliedState = this._getSubmissionMessagesAppliedState(row);
1610
+ appliedState = await this._getSubmissionMessagesAppliedState(row);
1530
1611
  } catch (error) {
1531
1612
  this.sql`
1532
1613
  UPDATE cf_think_submissions
@@ -1577,11 +1658,11 @@ var Think = class Think extends Agent {
1577
1658
  if (updated?.status === "error") await this._emitSubmissionStatus(updated);
1578
1659
  }
1579
1660
  }
1580
- _getSubmissionMessagesAppliedState(row) {
1661
+ async _getSubmissionMessagesAppliedState(row) {
1581
1662
  const messages = this._parseSubmissionMessages(row.messages_json);
1582
1663
  if (messages.length === 0) return "all";
1583
1664
  let applied = 0;
1584
- for (const message of messages) if (this.session.getMessage(message.id)) applied++;
1665
+ for (const message of messages) if (await this.session.getMessage(message.id)) applied++;
1585
1666
  if (applied === 0) return "none";
1586
1667
  return applied === messages.length ? "all" : "partial";
1587
1668
  }
@@ -1690,7 +1771,7 @@ var Think = class Think extends Agent {
1690
1771
  status = "skipped";
1691
1772
  return;
1692
1773
  }
1693
- for (const msg of resolved) await this.session.appendMessage(msg);
1774
+ for (const msg of resolved) await this._appendMessageToHistory(msg);
1694
1775
  options?.onMessagesApplied?.();
1695
1776
  this._broadcastMessages();
1696
1777
  if (this._turnQueue.generation !== epoch) {
@@ -1750,7 +1831,7 @@ var Think = class Think extends Agent {
1750
1831
  * matches the {@link saveMessages} contract.
1751
1832
  */
1752
1833
  async continueLastTurn(body, options) {
1753
- const lastLeaf = this.session.getLatestLeaf();
1834
+ const lastLeaf = await this.session.getLatestLeaf();
1754
1835
  if (!lastLeaf || lastLeaf.role !== "assistant") return {
1755
1836
  requestId: "",
1756
1837
  status: "skipped"
@@ -1846,7 +1927,7 @@ var Think = class Think extends Agent {
1846
1927
  this._handleStreamResumeRequest(connection);
1847
1928
  break;
1848
1929
  case "stream-resume-ack":
1849
- this._handleStreamResumeAck(connection, event.id);
1930
+ await this._handleStreamResumeAck(connection, event.id);
1850
1931
  break;
1851
1932
  case "chat-request":
1852
1933
  if (event.init?.method === "POST") await this._handleChatRequest(connection, event);
@@ -1856,8 +1937,8 @@ var Think = class Think extends Agent {
1856
1937
  this._lastClientTools = event.clientTools;
1857
1938
  this._persistClientTools();
1858
1939
  }
1859
- const resultPromise = Promise.resolve().then(() => {
1860
- this._applyToolResult(event.toolCallId, event.output, event.state, event.errorText);
1940
+ const resultPromise = Promise.resolve().then(async () => {
1941
+ await this._applyToolResult(event.toolCallId, event.output, event.state, event.errorText);
1861
1942
  return true;
1862
1943
  });
1863
1944
  this._pendingInteractionPromise = resultPromise;
@@ -1868,8 +1949,8 @@ var Think = class Think extends Agent {
1868
1949
  break;
1869
1950
  }
1870
1951
  case "tool-approval": {
1871
- const approvalPromise = Promise.resolve().then(() => {
1872
- this._applyToolApproval(event.toolCallId, event.approved);
1952
+ const approvalPromise = Promise.resolve().then(async () => {
1953
+ await this._applyToolApproval(event.toolCallId, event.approved);
1873
1954
  return true;
1874
1955
  });
1875
1956
  this._pendingInteractionPromise = approvalPromise;
@@ -1880,7 +1961,7 @@ var Think = class Think extends Agent {
1880
1961
  break;
1881
1962
  }
1882
1963
  case "clear":
1883
- this._handleClear(connection);
1964
+ await this._handleClear(connection);
1884
1965
  break;
1885
1966
  case "cancel":
1886
1967
  this._aborts.cancel(event.id);
@@ -1894,11 +1975,11 @@ var Think = class Think extends Agent {
1894
1975
  else if (this._continuation.pending !== null && this._continuation.pending.connectionId === connection.id) this._continuation.awaitingConnections.set(connection.id, connection);
1895
1976
  else sendIfOpen(connection, JSON.stringify({ type: MSG_STREAM_RESUME_NONE }));
1896
1977
  }
1897
- _handleStreamResumeAck(connection, requestId) {
1978
+ async _handleStreamResumeAck(connection, requestId) {
1898
1979
  this._pendingResumeConnections.delete(connection.id);
1899
1980
  if (this._resumableStream.hasActiveStream() && this._resumableStream.activeRequestId === requestId) {
1900
1981
  const orphanedStreamId = this._resumableStream.replayChunks(connection, this._resumableStream.activeRequestId);
1901
- if (orphanedStreamId) this._persistOrphanedStream(orphanedStreamId);
1982
+ if (orphanedStreamId) await this._persistOrphanedStream(orphanedStreamId);
1902
1983
  } else if (this._resumableStream.hasActiveStream()) {} else if (!this._resumableStream.replayCompletedChunksByRequestId(connection, requestId)) sendIfOpen(connection, JSON.stringify({
1903
1984
  body: "",
1904
1985
  done: true,
@@ -1948,7 +2029,7 @@ var Think = class Think extends Agent {
1948
2029
  this._persistBody();
1949
2030
  const clientToolsForTurn = this._lastClientTools;
1950
2031
  const bodyForTurn = this._lastBody;
1951
- const serverMessages = this.session.getHistory();
2032
+ const serverMessages = await this._readMessagesFromStorage();
1952
2033
  const reconciled = reconcileMessages(incomingMessages, serverMessages, sanitizeMessage);
1953
2034
  let branchParentId;
1954
2035
  if (isRegeneration && reconciled.length > 0) branchParentId = reconciled[reconciled.length - 1].id;
@@ -1967,6 +2048,7 @@ var Think = class Think extends Agent {
1967
2048
  this._completeSkippedRequest(connection, requestId);
1968
2049
  return;
1969
2050
  }
2051
+ await this._syncMessages();
1970
2052
  this._broadcastMessages([connection.id]);
1971
2053
  const abortSignal = this._aborts.getSignal(requestId);
1972
2054
  await this.keepAliveWhile(async () => {
@@ -2070,16 +2152,21 @@ var Think = class Think extends Agent {
2070
2152
  * No-op if no controller exists for `requestId` (the turn already
2071
2153
  * completed, was never started, or used a different id).
2072
2154
  *
2073
- * Most callers don't have the request id and want
2074
- * {@link abortAllRequests} instead. This method is here for
2075
- * symmetry with the WebSocket cancel surface and for callers that
2076
- * happen to know the id (e.g. via a stash from an earlier
2077
- * `saveMessages` return).
2155
+ * `chat()` callers can read the request id from
2156
+ * {@link StreamCallback.onStart} and later pass it here from another
2157
+ * RPC call.
2078
2158
  *
2079
2159
  * Prefer {@link SaveMessagesOptions.signal} when driving a turn
2080
2160
  * programmatically — it threads the abort intent in from the start
2081
2161
  * without requiring the caller to know the id.
2082
2162
  */
2163
+ cancelChat(requestId, reason) {
2164
+ this._aborts.cancel(requestId, reason);
2165
+ }
2166
+ /** Abort every in-flight chat turn on this agent. */
2167
+ cancelAllChats() {
2168
+ this._aborts.destroyAll();
2169
+ }
2083
2170
  abortRequest(requestId, reason) {
2084
2171
  this._aborts.cancel(requestId, reason);
2085
2172
  }
@@ -2098,7 +2185,7 @@ var Think = class Think extends Agent {
2098
2185
  abortAllRequests() {
2099
2186
  this._aborts.destroyAll();
2100
2187
  }
2101
- _handleClear(connection) {
2188
+ async _handleClear(connection) {
2102
2189
  this.resetTurnState();
2103
2190
  this._resumableStream.clearAll();
2104
2191
  this._pendingResumeConnections.clear();
@@ -2106,7 +2193,7 @@ var Think = class Think extends Agent {
2106
2193
  this._persistClientTools();
2107
2194
  this._lastBody = void 0;
2108
2195
  this._persistBody();
2109
- this.session.clearMessages();
2196
+ await this._clearHistory();
2110
2197
  this._broadcast({ type: MSG_CHAT_CLEAR }, connection ? [connection.id] : void 0);
2111
2198
  }
2112
2199
  async _streamResultToRpcCallback(requestId, result, callback, abortSignal) {
@@ -2143,7 +2230,7 @@ var Think = class Think extends Agent {
2143
2230
  this._resumableStream.complete(streamId);
2144
2231
  streamFinalized = true;
2145
2232
  assistantMsg = accumulator.toMessage();
2146
- this._persistAssistantMessage(assistantMsg);
2233
+ await this._persistAssistantMessage(assistantMsg);
2147
2234
  if (!aborted) {
2148
2235
  await callback.onDone();
2149
2236
  await this._fireResponseHook({
@@ -2165,7 +2252,7 @@ var Think = class Think extends Agent {
2165
2252
  }
2166
2253
  if (!assistantMsg && accumulator.parts.length > 0) {
2167
2254
  assistantMsg = accumulator.toMessage();
2168
- this._persistAssistantMessage(assistantMsg);
2255
+ await this._persistAssistantMessage(assistantMsg);
2169
2256
  }
2170
2257
  const wrapped = this.onChatError(error);
2171
2258
  const errorMessage = wrapped instanceof Error ? wrapped.message : String(wrapped);
@@ -2265,7 +2352,7 @@ var Think = class Think extends Agent {
2265
2352
  }
2266
2353
  if (accumulator.parts.length > 0 && this._turnQueue.generation === clearGen) try {
2267
2354
  const assistantMsg = accumulator.toMessage();
2268
- this._persistAssistantMessage(assistantMsg, parentId);
2355
+ await this._persistAssistantMessage(assistantMsg, parentId);
2269
2356
  this._broadcastMessages();
2270
2357
  await this._fireResponseHook({
2271
2358
  message: assistantMsg,
@@ -2278,10 +2365,8 @@ var Think = class Think extends Agent {
2278
2365
  console.error("Failed to persist assistant message:", e);
2279
2366
  }
2280
2367
  }
2281
- _persistAssistantMessage(msg, parentId) {
2282
- const safe = enforceRowSizeLimit(sanitizeMessage(msg));
2283
- if (this.session.getMessage(safe.id)) this.session.updateMessage(safe);
2284
- else this.session.appendMessage(safe, parentId);
2368
+ async _persistAssistantMessage(msg, parentId) {
2369
+ await this._upsertMessageInHistory(msg, parentId);
2285
2370
  }
2286
2371
  /**
2287
2372
  * Persist an incoming message after reconciliation. For assistant
@@ -2290,12 +2375,8 @@ var Think = class Think extends Agent {
2290
2375
  * instead of inserting an orphan duplicate.
2291
2376
  */
2292
2377
  async _persistIncomingMessage(msg, serverMessages) {
2293
- const safe = enforceRowSizeLimit(sanitizeMessage(msg.role === "assistant" ? resolveToolMergeId(msg, serverMessages) : msg));
2294
- if (this.session.getMessage(safe.id)) {
2295
- this.session.updateMessage(safe);
2296
- return;
2297
- }
2298
- await this.session.appendMessage(safe);
2378
+ const resolved = msg.role === "assistant" ? resolveToolMergeId(msg, serverMessages) : msg;
2379
+ await this._upsertMessageInHistory(resolved);
2299
2380
  }
2300
2381
  _persistClientTools() {
2301
2382
  if (this._lastClientTools) this._configSet("lastClientTools", JSON.stringify(this._lastClientTools));
@@ -2321,24 +2402,25 @@ var Think = class Think extends Agent {
2321
2402
  this._lastBody = void 0;
2322
2403
  }
2323
2404
  }
2324
- _applyToolResult(toolCallId, output, overrideState, errorText) {
2405
+ async _applyToolResult(toolCallId, output, overrideState, errorText) {
2325
2406
  const update = toolResultUpdate(toolCallId, output, overrideState, errorText);
2326
- this._applyToolUpdateToMessages(update);
2407
+ await this._applyToolUpdateToMessages(update);
2327
2408
  }
2328
- _applyToolApproval(toolCallId, approved) {
2409
+ async _applyToolApproval(toolCallId, approved) {
2329
2410
  const update = toolApprovalUpdate(toolCallId, approved);
2330
- this._applyToolUpdateToMessages(update);
2411
+ await this._applyToolUpdateToMessages(update);
2331
2412
  }
2332
- _applyToolUpdateToMessages(update) {
2333
- const history = this.messages;
2334
- for (const msg of history) {
2413
+ async _applyToolUpdateToMessages(update) {
2414
+ const history = await this._readMessagesFromStorage();
2415
+ for (let i = 0; i < history.length; i++) {
2416
+ const msg = history[i];
2335
2417
  const result = applyToolUpdate(msg.parts, update);
2336
2418
  if (result) {
2337
- const safe = enforceRowSizeLimit(sanitizeMessage({
2419
+ const updatedMsg = {
2338
2420
  ...msg,
2339
2421
  parts: result.parts
2340
- }));
2341
- this.session.updateMessage(safe);
2422
+ };
2423
+ const safe = await this._updateMessageInHistory(updatedMsg);
2342
2424
  this._broadcast({
2343
2425
  type: MSG_MESSAGE_UPDATED,
2344
2426
  message: safe
@@ -2418,14 +2500,14 @@ var Think = class Think extends Agent {
2418
2500
  });
2419
2501
  const streamStillActive = streamId && this._resumableStream.hasActiveStream() && this._resumableStream.activeStreamId === streamId;
2420
2502
  const streamIsTerminal = streamStatus === "completed" || streamStatus === "error";
2421
- if (options.persist !== false && (streamStillActive || streamIsTerminal)) this._persistOrphanedStream(streamId);
2503
+ if (options.persist !== false && streamId && (streamStillActive || streamIsTerminal)) await this._persistOrphanedStream(streamId);
2422
2504
  if (streamStillActive) this._resumableStream.complete(streamId);
2423
2505
  const canContinue = options.continue !== false && !streamIsTerminal;
2424
2506
  const hasRunningSubmission = this._hasRunningSubmission(requestId);
2425
2507
  if (streamIsTerminal && hasRunningSubmission) await this._completeRecoveredSubmission(requestId, streamStatus === "completed" ? "completed" : "error", requestId, streamStatus === "completed" ? null : "Recovered chat stream had already errored.");
2426
2508
  const recoveredRequestId = canContinue && hasRunningSubmission ? requestId : void 0;
2427
2509
  if (canContinue) {
2428
- const lastLeaf = this.session.getLatestLeaf();
2510
+ const lastLeaf = await this.session.getLatestLeaf();
2429
2511
  const targetId = lastLeaf?.role === "assistant" ? lastLeaf.id : void 0;
2430
2512
  await this.schedule(0, "_chatRecoveryContinue", {
2431
2513
  ...targetId ? { targetAssistantId: targetId } : {},
@@ -2512,7 +2594,7 @@ var Think = class Think extends Agent {
2512
2594
  return;
2513
2595
  }
2514
2596
  const targetId = data?.targetAssistantId;
2515
- const lastLeaf = this.session.getLatestLeaf();
2597
+ const lastLeaf = await this.session.getLatestLeaf();
2516
2598
  if (targetId && lastLeaf?.id !== targetId) {
2517
2599
  if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, "error", null, "Recovered chat continuation was skipped because the conversation changed.");
2518
2600
  return;
@@ -2661,7 +2743,7 @@ var Think = class Think extends Agent {
2661
2743
  id: this._resumableStream.activeRequestId
2662
2744
  }))) this._pendingResumeConnections.add(connection.id);
2663
2745
  }
2664
- _persistOrphanedStream(streamId) {
2746
+ async _persistOrphanedStream(streamId) {
2665
2747
  this._resumableStream.flushBuffer();
2666
2748
  const chunks = this._resumableStream.getStreamChunks(streamId);
2667
2749
  if (chunks.length === 0) return;
@@ -2670,7 +2752,7 @@ var Think = class Think extends Agent {
2670
2752
  accumulator.applyChunk(JSON.parse(chunk.body));
2671
2753
  } catch {}
2672
2754
  if (accumulator.parts.length > 0) {
2673
- this._persistAssistantMessage(accumulator.toMessage());
2755
+ await this._persistAssistantMessage(accumulator.toMessage());
2674
2756
  this._broadcastMessages();
2675
2757
  }
2676
2758
  }