@cloudflare/think 0.6.0 → 0.7.0

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 {
@@ -205,12 +283,53 @@ var Think = class Think extends Agent {
205
283
  * Used as fallback when no context blocks are configured via `configureSession`.
206
284
  */
207
285
  getSystemPrompt() {
208
- return "You are a helpful assistant.";
286
+ return [
287
+ "You are a careful, capable assistant helping the user complete their task.",
288
+ "Use available tools when they materially improve accuracy or let you act on the user's request. Before changing code, understand the relevant context: existing patterns, dependencies, tests, and nearby conventions.",
289
+ "Keep changes focused on the user's request. Prefer small, idiomatic edits over broad rewrites or new abstractions. Do not introduce new dependencies, secrets, destructive actions, or persistent side effects unless the user clearly asks or approves.",
290
+ "When the task is complex, briefly state your approach and keep the user informed with concise progress updates. If you modify code, verify with the smallest relevant test, build, typecheck, lint, or runtime check available, and report any checks you could not run.",
291
+ "Be direct and useful in your final response: summarize the outcome, mention important files or commands, and call out real blockers or risks."
292
+ ].join("\n\n");
209
293
  }
210
294
  /** Return the tools available to the assistant. */
211
295
  getTools() {
212
296
  return {};
213
297
  }
298
+ _systemPromptForTurn(baseSystem, tools) {
299
+ if (baseSystem.includes("You are running inside a Think agent.")) return baseSystem;
300
+ return `${baseSystem.trimEnd()}\n\n${this._buildThinkCapabilityBlock(tools)}`;
301
+ }
302
+ _buildThinkCapabilityBlock(tools) {
303
+ const toolNames = new Set(Object.keys(tools));
304
+ const hasTools = toolNames.size > 0;
305
+ const hasWorkspaceTools = [
306
+ "read",
307
+ "write",
308
+ "edit",
309
+ "list",
310
+ "find",
311
+ "grep",
312
+ "delete"
313
+ ].some((toolName) => toolNames.has(toolName));
314
+ const hasContextTools = toolNames.has("load_context") || toolNames.has("unload_context");
315
+ const hasExtensionTools = toolNames.has("load_extension") || toolNames.has("list_extensions");
316
+ const hasExecuteTool = toolNames.has("execute");
317
+ const lines = [
318
+ "You are running inside a Think agent.",
319
+ "",
320
+ "Capabilities available in this turn:"
321
+ ];
322
+ if (hasWorkspaceTools) lines.push("- You can inspect and edit the agent workspace using the available file tools.");
323
+ if (hasTools) {
324
+ lines.push("- Use the tools exposed in this turn when they materially improve accuracy or let you act on the user's request. Treat tool descriptions and schemas as the source of truth.");
325
+ lines.push("- Some tools may call server code, browser/client code, MCP servers, extensions, or delegated agents. Use them according to their descriptions.");
326
+ }
327
+ if (hasContextTools) lines.push("- If context-loading tools are available, use them to load relevant memory, skills, or project context before acting on incomplete information.");
328
+ if (hasExtensionTools) lines.push("- If extension tools are available, use them only when loading or inspecting extensions directly helps with the task.");
329
+ if (hasExecuteTool) lines.push("- If sandboxed execution is available, prefer it for safe, bounded checks or coordinated multi-step operations.");
330
+ lines.push("- Do not claim access to capabilities that are not exposed as tools in this turn.");
331
+ return lines.join("\n");
332
+ }
214
333
  /**
215
334
  * Configure the session. Called once during `onStart`.
216
335
  * Override to add context blocks, compaction, search, skills.
@@ -393,8 +512,8 @@ var Think = class Think extends Agent {
393
512
  return error;
394
513
  }
395
514
  async _initializeExtensions() {
396
- const { ExtensionManager } = await import("./manager-BypfrNX0.js").then((n) => n.n);
397
- 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);
398
517
  const agentClassName = this.constructor.name;
399
518
  const agentId = this.ctx.id.toString();
400
519
  const ctxExports = this.ctx.exports;
@@ -452,8 +571,10 @@ var Think = class Think extends Agent {
452
571
  ...this.mcp?.getAITools?.() ?? {},
453
572
  ...clientToolSet
454
573
  };
455
- const system = await this.session.freezeSystemPrompt() || this.getSystemPrompt();
456
- const messages = await convertToModelMessages(truncateOlderMessages(this.session.getHistory()), { tools });
574
+ const baseSystem = await this.session.freezeSystemPrompt() || this.getSystemPrompt();
575
+ const system = this._systemPromptForTurn(baseSystem, tools);
576
+ const history = this.messages;
577
+ const messages = await convertToModelMessages(truncateOlderMessages(history), { tools });
457
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.");
458
579
  const model = this.getModel();
459
580
  const ctx = {
@@ -467,7 +588,10 @@ var Think = class Think extends Agent {
467
588
  const subclassConfig = await this.beforeTurn(ctx) ?? {};
468
589
  const config = await this._pipelineExtensionBeforeTurn(ctx, subclassConfig);
469
590
  const finalModel = config.model ?? model;
470
- const finalSystem = config.system ?? system;
591
+ const finalSystem = config.system ?? this._systemPromptForTurn(baseSystem, config.tools ? {
592
+ ...tools,
593
+ ...config.tools
594
+ } : tools);
471
595
  const finalMessages = config.messages ?? messages;
472
596
  const mergedTools = config.tools ? {
473
597
  ...tools,
@@ -769,7 +893,7 @@ var Think = class Think extends Agent {
769
893
  await this.session.replaceContextBlock(label, content);
770
894
  }
771
895
  async _hostGetMessages(limit) {
772
- const history = this.session.getHistory();
896
+ const history = this.messages;
773
897
  return (limit !== void 0 && limit !== null ? limit <= 0 ? [] : history.slice(-limit) : history).map((m) => ({
774
898
  id: m.id,
775
899
  role: m.role,
@@ -785,10 +909,10 @@ var Think = class Think extends Agent {
785
909
  text: content
786
910
  }]
787
911
  };
788
- await this.session.appendMessage(msg);
912
+ await this._appendMessageToHistory(msg);
789
913
  }
790
914
  async _hostGetSessionInfo() {
791
- return { messageCount: this.session.getHistory().length };
915
+ return { messageCount: this.messages.length };
792
916
  }
793
917
  /**
794
918
  * Run a chat turn: persist the user message, run the agentic loop,
@@ -813,7 +937,7 @@ var Think = class Think extends Agent {
813
937
  text: userMessage
814
938
  }]
815
939
  } : userMessage;
816
- await this.session.appendMessage(userMsg);
940
+ await this._appendMessageToHistory(userMsg);
817
941
  const abortSignal = this._aborts.getSignal(requestId);
818
942
  const detachExternal = this._aborts.linkExternal(requestId, options?.signal);
819
943
  try {
@@ -852,13 +976,13 @@ var Think = class Think extends Agent {
852
976
  });
853
977
  }
854
978
  /** Get the conversation history as UIMessage[]. */
855
- getMessages() {
856
- return this.messages;
979
+ async getMessages() {
980
+ return this.messages.slice();
857
981
  }
858
982
  /** Clear all messages from storage. */
859
- clearMessages() {
983
+ async clearMessages() {
860
984
  this.resetTurnState();
861
- this.session.clearMessages();
985
+ await this._clearHistory();
862
986
  }
863
987
  _ensureAgentToolChildRunTable() {
864
988
  this.sql`
@@ -1481,7 +1605,7 @@ var Think = class Think extends Agent {
1481
1605
  if (row.messages_applied_at === null) {
1482
1606
  let appliedState;
1483
1607
  try {
1484
- appliedState = this._getSubmissionMessagesAppliedState(row);
1608
+ appliedState = await this._getSubmissionMessagesAppliedState(row);
1485
1609
  } catch (error) {
1486
1610
  this.sql`
1487
1611
  UPDATE cf_think_submissions
@@ -1532,11 +1656,11 @@ var Think = class Think extends Agent {
1532
1656
  if (updated?.status === "error") await this._emitSubmissionStatus(updated);
1533
1657
  }
1534
1658
  }
1535
- _getSubmissionMessagesAppliedState(row) {
1659
+ async _getSubmissionMessagesAppliedState(row) {
1536
1660
  const messages = this._parseSubmissionMessages(row.messages_json);
1537
1661
  if (messages.length === 0) return "all";
1538
1662
  let applied = 0;
1539
- for (const message of messages) if (this.session.getMessage(message.id)) applied++;
1663
+ for (const message of messages) if (await this.session.getMessage(message.id)) applied++;
1540
1664
  if (applied === 0) return "none";
1541
1665
  return applied === messages.length ? "all" : "partial";
1542
1666
  }
@@ -1645,7 +1769,7 @@ var Think = class Think extends Agent {
1645
1769
  status = "skipped";
1646
1770
  return;
1647
1771
  }
1648
- for (const msg of resolved) await this.session.appendMessage(msg);
1772
+ for (const msg of resolved) await this._appendMessageToHistory(msg);
1649
1773
  options?.onMessagesApplied?.();
1650
1774
  this._broadcastMessages();
1651
1775
  if (this._turnQueue.generation !== epoch) {
@@ -1705,7 +1829,7 @@ var Think = class Think extends Agent {
1705
1829
  * matches the {@link saveMessages} contract.
1706
1830
  */
1707
1831
  async continueLastTurn(body, options) {
1708
- const lastLeaf = this.session.getLatestLeaf();
1832
+ const lastLeaf = await this.session.getLatestLeaf();
1709
1833
  if (!lastLeaf || lastLeaf.role !== "assistant") return {
1710
1834
  requestId: "",
1711
1835
  status: "skipped"
@@ -1801,7 +1925,7 @@ var Think = class Think extends Agent {
1801
1925
  this._handleStreamResumeRequest(connection);
1802
1926
  break;
1803
1927
  case "stream-resume-ack":
1804
- this._handleStreamResumeAck(connection, event.id);
1928
+ await this._handleStreamResumeAck(connection, event.id);
1805
1929
  break;
1806
1930
  case "chat-request":
1807
1931
  if (event.init?.method === "POST") await this._handleChatRequest(connection, event);
@@ -1811,8 +1935,8 @@ var Think = class Think extends Agent {
1811
1935
  this._lastClientTools = event.clientTools;
1812
1936
  this._persistClientTools();
1813
1937
  }
1814
- const resultPromise = Promise.resolve().then(() => {
1815
- this._applyToolResult(event.toolCallId, event.output, event.state, event.errorText);
1938
+ const resultPromise = Promise.resolve().then(async () => {
1939
+ await this._applyToolResult(event.toolCallId, event.output, event.state, event.errorText);
1816
1940
  return true;
1817
1941
  });
1818
1942
  this._pendingInteractionPromise = resultPromise;
@@ -1823,8 +1947,8 @@ var Think = class Think extends Agent {
1823
1947
  break;
1824
1948
  }
1825
1949
  case "tool-approval": {
1826
- const approvalPromise = Promise.resolve().then(() => {
1827
- this._applyToolApproval(event.toolCallId, event.approved);
1950
+ const approvalPromise = Promise.resolve().then(async () => {
1951
+ await this._applyToolApproval(event.toolCallId, event.approved);
1828
1952
  return true;
1829
1953
  });
1830
1954
  this._pendingInteractionPromise = approvalPromise;
@@ -1835,7 +1959,7 @@ var Think = class Think extends Agent {
1835
1959
  break;
1836
1960
  }
1837
1961
  case "clear":
1838
- this._handleClear(connection);
1962
+ await this._handleClear(connection);
1839
1963
  break;
1840
1964
  case "cancel":
1841
1965
  this._aborts.cancel(event.id);
@@ -1849,11 +1973,11 @@ var Think = class Think extends Agent {
1849
1973
  else if (this._continuation.pending !== null && this._continuation.pending.connectionId === connection.id) this._continuation.awaitingConnections.set(connection.id, connection);
1850
1974
  else sendIfOpen(connection, JSON.stringify({ type: MSG_STREAM_RESUME_NONE }));
1851
1975
  }
1852
- _handleStreamResumeAck(connection, requestId) {
1976
+ async _handleStreamResumeAck(connection, requestId) {
1853
1977
  this._pendingResumeConnections.delete(connection.id);
1854
1978
  if (this._resumableStream.hasActiveStream() && this._resumableStream.activeRequestId === requestId) {
1855
1979
  const orphanedStreamId = this._resumableStream.replayChunks(connection, this._resumableStream.activeRequestId);
1856
- if (orphanedStreamId) this._persistOrphanedStream(orphanedStreamId);
1980
+ if (orphanedStreamId) await this._persistOrphanedStream(orphanedStreamId);
1857
1981
  } else if (this._resumableStream.hasActiveStream()) {} else if (!this._resumableStream.replayCompletedChunksByRequestId(connection, requestId)) sendIfOpen(connection, JSON.stringify({
1858
1982
  body: "",
1859
1983
  done: true,
@@ -1903,7 +2027,7 @@ var Think = class Think extends Agent {
1903
2027
  this._persistBody();
1904
2028
  const clientToolsForTurn = this._lastClientTools;
1905
2029
  const bodyForTurn = this._lastBody;
1906
- const serverMessages = this.session.getHistory();
2030
+ const serverMessages = await this._readMessagesFromStorage();
1907
2031
  const reconciled = reconcileMessages(incomingMessages, serverMessages, sanitizeMessage);
1908
2032
  let branchParentId;
1909
2033
  if (isRegeneration && reconciled.length > 0) branchParentId = reconciled[reconciled.length - 1].id;
@@ -1922,6 +2046,7 @@ var Think = class Think extends Agent {
1922
2046
  this._completeSkippedRequest(connection, requestId);
1923
2047
  return;
1924
2048
  }
2049
+ await this._syncMessages();
1925
2050
  this._broadcastMessages([connection.id]);
1926
2051
  const abortSignal = this._aborts.getSignal(requestId);
1927
2052
  await this.keepAliveWhile(async () => {
@@ -2053,7 +2178,7 @@ var Think = class Think extends Agent {
2053
2178
  abortAllRequests() {
2054
2179
  this._aborts.destroyAll();
2055
2180
  }
2056
- _handleClear(connection) {
2181
+ async _handleClear(connection) {
2057
2182
  this.resetTurnState();
2058
2183
  this._resumableStream.clearAll();
2059
2184
  this._pendingResumeConnections.clear();
@@ -2061,7 +2186,7 @@ var Think = class Think extends Agent {
2061
2186
  this._persistClientTools();
2062
2187
  this._lastBody = void 0;
2063
2188
  this._persistBody();
2064
- this.session.clearMessages();
2189
+ await this._clearHistory();
2065
2190
  this._broadcast({ type: MSG_CHAT_CLEAR }, connection ? [connection.id] : void 0);
2066
2191
  }
2067
2192
  async _streamResultToRpcCallback(requestId, result, callback, abortSignal) {
@@ -2098,7 +2223,7 @@ var Think = class Think extends Agent {
2098
2223
  this._resumableStream.complete(streamId);
2099
2224
  streamFinalized = true;
2100
2225
  assistantMsg = accumulator.toMessage();
2101
- this._persistAssistantMessage(assistantMsg);
2226
+ await this._persistAssistantMessage(assistantMsg);
2102
2227
  if (!aborted) {
2103
2228
  await callback.onDone();
2104
2229
  await this._fireResponseHook({
@@ -2120,7 +2245,7 @@ var Think = class Think extends Agent {
2120
2245
  }
2121
2246
  if (!assistantMsg && accumulator.parts.length > 0) {
2122
2247
  assistantMsg = accumulator.toMessage();
2123
- this._persistAssistantMessage(assistantMsg);
2248
+ await this._persistAssistantMessage(assistantMsg);
2124
2249
  }
2125
2250
  const wrapped = this.onChatError(error);
2126
2251
  const errorMessage = wrapped instanceof Error ? wrapped.message : String(wrapped);
@@ -2220,7 +2345,7 @@ var Think = class Think extends Agent {
2220
2345
  }
2221
2346
  if (accumulator.parts.length > 0 && this._turnQueue.generation === clearGen) try {
2222
2347
  const assistantMsg = accumulator.toMessage();
2223
- this._persistAssistantMessage(assistantMsg, parentId);
2348
+ await this._persistAssistantMessage(assistantMsg, parentId);
2224
2349
  this._broadcastMessages();
2225
2350
  await this._fireResponseHook({
2226
2351
  message: assistantMsg,
@@ -2233,10 +2358,8 @@ var Think = class Think extends Agent {
2233
2358
  console.error("Failed to persist assistant message:", e);
2234
2359
  }
2235
2360
  }
2236
- _persistAssistantMessage(msg, parentId) {
2237
- const safe = enforceRowSizeLimit(sanitizeMessage(msg));
2238
- if (this.session.getMessage(safe.id)) this.session.updateMessage(safe);
2239
- else this.session.appendMessage(safe, parentId);
2361
+ async _persistAssistantMessage(msg, parentId) {
2362
+ await this._upsertMessageInHistory(msg, parentId);
2240
2363
  }
2241
2364
  /**
2242
2365
  * Persist an incoming message after reconciliation. For assistant
@@ -2245,12 +2368,8 @@ var Think = class Think extends Agent {
2245
2368
  * instead of inserting an orphan duplicate.
2246
2369
  */
2247
2370
  async _persistIncomingMessage(msg, serverMessages) {
2248
- const safe = enforceRowSizeLimit(sanitizeMessage(msg.role === "assistant" ? resolveToolMergeId(msg, serverMessages) : msg));
2249
- if (this.session.getMessage(safe.id)) {
2250
- this.session.updateMessage(safe);
2251
- return;
2252
- }
2253
- await this.session.appendMessage(safe);
2371
+ const resolved = msg.role === "assistant" ? resolveToolMergeId(msg, serverMessages) : msg;
2372
+ await this._upsertMessageInHistory(resolved);
2254
2373
  }
2255
2374
  _persistClientTools() {
2256
2375
  if (this._lastClientTools) this._configSet("lastClientTools", JSON.stringify(this._lastClientTools));
@@ -2276,24 +2395,25 @@ var Think = class Think extends Agent {
2276
2395
  this._lastBody = void 0;
2277
2396
  }
2278
2397
  }
2279
- _applyToolResult(toolCallId, output, overrideState, errorText) {
2398
+ async _applyToolResult(toolCallId, output, overrideState, errorText) {
2280
2399
  const update = toolResultUpdate(toolCallId, output, overrideState, errorText);
2281
- this._applyToolUpdateToMessages(update);
2400
+ await this._applyToolUpdateToMessages(update);
2282
2401
  }
2283
- _applyToolApproval(toolCallId, approved) {
2402
+ async _applyToolApproval(toolCallId, approved) {
2284
2403
  const update = toolApprovalUpdate(toolCallId, approved);
2285
- this._applyToolUpdateToMessages(update);
2404
+ await this._applyToolUpdateToMessages(update);
2286
2405
  }
2287
- _applyToolUpdateToMessages(update) {
2288
- const history = this.messages;
2289
- for (const msg of history) {
2406
+ async _applyToolUpdateToMessages(update) {
2407
+ const history = await this._readMessagesFromStorage();
2408
+ for (let i = 0; i < history.length; i++) {
2409
+ const msg = history[i];
2290
2410
  const result = applyToolUpdate(msg.parts, update);
2291
2411
  if (result) {
2292
- const safe = enforceRowSizeLimit(sanitizeMessage({
2412
+ const updatedMsg = {
2293
2413
  ...msg,
2294
2414
  parts: result.parts
2295
- }));
2296
- this.session.updateMessage(safe);
2415
+ };
2416
+ const safe = await this._updateMessageInHistory(updatedMsg);
2297
2417
  this._broadcast({
2298
2418
  type: MSG_MESSAGE_UPDATED,
2299
2419
  message: safe
@@ -2373,14 +2493,14 @@ var Think = class Think extends Agent {
2373
2493
  });
2374
2494
  const streamStillActive = streamId && this._resumableStream.hasActiveStream() && this._resumableStream.activeStreamId === streamId;
2375
2495
  const streamIsTerminal = streamStatus === "completed" || streamStatus === "error";
2376
- if (options.persist !== false && (streamStillActive || streamIsTerminal)) this._persistOrphanedStream(streamId);
2496
+ if (options.persist !== false && streamId && (streamStillActive || streamIsTerminal)) await this._persistOrphanedStream(streamId);
2377
2497
  if (streamStillActive) this._resumableStream.complete(streamId);
2378
2498
  const canContinue = options.continue !== false && !streamIsTerminal;
2379
2499
  const hasRunningSubmission = this._hasRunningSubmission(requestId);
2380
2500
  if (streamIsTerminal && hasRunningSubmission) await this._completeRecoveredSubmission(requestId, streamStatus === "completed" ? "completed" : "error", requestId, streamStatus === "completed" ? null : "Recovered chat stream had already errored.");
2381
2501
  const recoveredRequestId = canContinue && hasRunningSubmission ? requestId : void 0;
2382
2502
  if (canContinue) {
2383
- const lastLeaf = this.session.getLatestLeaf();
2503
+ const lastLeaf = await this.session.getLatestLeaf();
2384
2504
  const targetId = lastLeaf?.role === "assistant" ? lastLeaf.id : void 0;
2385
2505
  await this.schedule(0, "_chatRecoveryContinue", {
2386
2506
  ...targetId ? { targetAssistantId: targetId } : {},
@@ -2467,7 +2587,7 @@ var Think = class Think extends Agent {
2467
2587
  return;
2468
2588
  }
2469
2589
  const targetId = data?.targetAssistantId;
2470
- const lastLeaf = this.session.getLatestLeaf();
2590
+ const lastLeaf = await this.session.getLatestLeaf();
2471
2591
  if (targetId && lastLeaf?.id !== targetId) {
2472
2592
  if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, "error", null, "Recovered chat continuation was skipped because the conversation changed.");
2473
2593
  return;
@@ -2616,7 +2736,7 @@ var Think = class Think extends Agent {
2616
2736
  id: this._resumableStream.activeRequestId
2617
2737
  }))) this._pendingResumeConnections.add(connection.id);
2618
2738
  }
2619
- _persistOrphanedStream(streamId) {
2739
+ async _persistOrphanedStream(streamId) {
2620
2740
  this._resumableStream.flushBuffer();
2621
2741
  const chunks = this._resumableStream.getStreamChunks(streamId);
2622
2742
  if (chunks.length === 0) return;
@@ -2625,7 +2745,7 @@ var Think = class Think extends Agent {
2625
2745
  accumulator.applyChunk(JSON.parse(chunk.body));
2626
2746
  } catch {}
2627
2747
  if (accumulator.parts.length > 0) {
2628
- this._persistAssistantMessage(accumulator.toMessage());
2748
+ await this._persistAssistantMessage(accumulator.toMessage());
2629
2749
  this._broadcastMessages();
2630
2750
  }
2631
2751
  }