@cloudflare/think 0.6.1 → 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 {
@@ -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 = {
@@ -814,7 +893,7 @@ var Think = class Think extends Agent {
814
893
  await this.session.replaceContextBlock(label, content);
815
894
  }
816
895
  async _hostGetMessages(limit) {
817
- const history = this.session.getHistory();
896
+ const history = this.messages;
818
897
  return (limit !== void 0 && limit !== null ? limit <= 0 ? [] : history.slice(-limit) : history).map((m) => ({
819
898
  id: m.id,
820
899
  role: m.role,
@@ -830,10 +909,10 @@ var Think = class Think extends Agent {
830
909
  text: content
831
910
  }]
832
911
  };
833
- await this.session.appendMessage(msg);
912
+ await this._appendMessageToHistory(msg);
834
913
  }
835
914
  async _hostGetSessionInfo() {
836
- return { messageCount: this.session.getHistory().length };
915
+ return { messageCount: this.messages.length };
837
916
  }
838
917
  /**
839
918
  * Run a chat turn: persist the user message, run the agentic loop,
@@ -858,7 +937,7 @@ var Think = class Think extends Agent {
858
937
  text: userMessage
859
938
  }]
860
939
  } : userMessage;
861
- await this.session.appendMessage(userMsg);
940
+ await this._appendMessageToHistory(userMsg);
862
941
  const abortSignal = this._aborts.getSignal(requestId);
863
942
  const detachExternal = this._aborts.linkExternal(requestId, options?.signal);
864
943
  try {
@@ -897,13 +976,13 @@ var Think = class Think extends Agent {
897
976
  });
898
977
  }
899
978
  /** Get the conversation history as UIMessage[]. */
900
- getMessages() {
901
- return this.messages;
979
+ async getMessages() {
980
+ return this.messages.slice();
902
981
  }
903
982
  /** Clear all messages from storage. */
904
- clearMessages() {
983
+ async clearMessages() {
905
984
  this.resetTurnState();
906
- this.session.clearMessages();
985
+ await this._clearHistory();
907
986
  }
908
987
  _ensureAgentToolChildRunTable() {
909
988
  this.sql`
@@ -1526,7 +1605,7 @@ var Think = class Think extends Agent {
1526
1605
  if (row.messages_applied_at === null) {
1527
1606
  let appliedState;
1528
1607
  try {
1529
- appliedState = this._getSubmissionMessagesAppliedState(row);
1608
+ appliedState = await this._getSubmissionMessagesAppliedState(row);
1530
1609
  } catch (error) {
1531
1610
  this.sql`
1532
1611
  UPDATE cf_think_submissions
@@ -1577,11 +1656,11 @@ var Think = class Think extends Agent {
1577
1656
  if (updated?.status === "error") await this._emitSubmissionStatus(updated);
1578
1657
  }
1579
1658
  }
1580
- _getSubmissionMessagesAppliedState(row) {
1659
+ async _getSubmissionMessagesAppliedState(row) {
1581
1660
  const messages = this._parseSubmissionMessages(row.messages_json);
1582
1661
  if (messages.length === 0) return "all";
1583
1662
  let applied = 0;
1584
- 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++;
1585
1664
  if (applied === 0) return "none";
1586
1665
  return applied === messages.length ? "all" : "partial";
1587
1666
  }
@@ -1690,7 +1769,7 @@ var Think = class Think extends Agent {
1690
1769
  status = "skipped";
1691
1770
  return;
1692
1771
  }
1693
- for (const msg of resolved) await this.session.appendMessage(msg);
1772
+ for (const msg of resolved) await this._appendMessageToHistory(msg);
1694
1773
  options?.onMessagesApplied?.();
1695
1774
  this._broadcastMessages();
1696
1775
  if (this._turnQueue.generation !== epoch) {
@@ -1750,7 +1829,7 @@ var Think = class Think extends Agent {
1750
1829
  * matches the {@link saveMessages} contract.
1751
1830
  */
1752
1831
  async continueLastTurn(body, options) {
1753
- const lastLeaf = this.session.getLatestLeaf();
1832
+ const lastLeaf = await this.session.getLatestLeaf();
1754
1833
  if (!lastLeaf || lastLeaf.role !== "assistant") return {
1755
1834
  requestId: "",
1756
1835
  status: "skipped"
@@ -1846,7 +1925,7 @@ var Think = class Think extends Agent {
1846
1925
  this._handleStreamResumeRequest(connection);
1847
1926
  break;
1848
1927
  case "stream-resume-ack":
1849
- this._handleStreamResumeAck(connection, event.id);
1928
+ await this._handleStreamResumeAck(connection, event.id);
1850
1929
  break;
1851
1930
  case "chat-request":
1852
1931
  if (event.init?.method === "POST") await this._handleChatRequest(connection, event);
@@ -1856,8 +1935,8 @@ var Think = class Think extends Agent {
1856
1935
  this._lastClientTools = event.clientTools;
1857
1936
  this._persistClientTools();
1858
1937
  }
1859
- const resultPromise = Promise.resolve().then(() => {
1860
- 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);
1861
1940
  return true;
1862
1941
  });
1863
1942
  this._pendingInteractionPromise = resultPromise;
@@ -1868,8 +1947,8 @@ var Think = class Think extends Agent {
1868
1947
  break;
1869
1948
  }
1870
1949
  case "tool-approval": {
1871
- const approvalPromise = Promise.resolve().then(() => {
1872
- this._applyToolApproval(event.toolCallId, event.approved);
1950
+ const approvalPromise = Promise.resolve().then(async () => {
1951
+ await this._applyToolApproval(event.toolCallId, event.approved);
1873
1952
  return true;
1874
1953
  });
1875
1954
  this._pendingInteractionPromise = approvalPromise;
@@ -1880,7 +1959,7 @@ var Think = class Think extends Agent {
1880
1959
  break;
1881
1960
  }
1882
1961
  case "clear":
1883
- this._handleClear(connection);
1962
+ await this._handleClear(connection);
1884
1963
  break;
1885
1964
  case "cancel":
1886
1965
  this._aborts.cancel(event.id);
@@ -1894,11 +1973,11 @@ var Think = class Think extends Agent {
1894
1973
  else if (this._continuation.pending !== null && this._continuation.pending.connectionId === connection.id) this._continuation.awaitingConnections.set(connection.id, connection);
1895
1974
  else sendIfOpen(connection, JSON.stringify({ type: MSG_STREAM_RESUME_NONE }));
1896
1975
  }
1897
- _handleStreamResumeAck(connection, requestId) {
1976
+ async _handleStreamResumeAck(connection, requestId) {
1898
1977
  this._pendingResumeConnections.delete(connection.id);
1899
1978
  if (this._resumableStream.hasActiveStream() && this._resumableStream.activeRequestId === requestId) {
1900
1979
  const orphanedStreamId = this._resumableStream.replayChunks(connection, this._resumableStream.activeRequestId);
1901
- if (orphanedStreamId) this._persistOrphanedStream(orphanedStreamId);
1980
+ if (orphanedStreamId) await this._persistOrphanedStream(orphanedStreamId);
1902
1981
  } else if (this._resumableStream.hasActiveStream()) {} else if (!this._resumableStream.replayCompletedChunksByRequestId(connection, requestId)) sendIfOpen(connection, JSON.stringify({
1903
1982
  body: "",
1904
1983
  done: true,
@@ -1948,7 +2027,7 @@ var Think = class Think extends Agent {
1948
2027
  this._persistBody();
1949
2028
  const clientToolsForTurn = this._lastClientTools;
1950
2029
  const bodyForTurn = this._lastBody;
1951
- const serverMessages = this.session.getHistory();
2030
+ const serverMessages = await this._readMessagesFromStorage();
1952
2031
  const reconciled = reconcileMessages(incomingMessages, serverMessages, sanitizeMessage);
1953
2032
  let branchParentId;
1954
2033
  if (isRegeneration && reconciled.length > 0) branchParentId = reconciled[reconciled.length - 1].id;
@@ -1967,6 +2046,7 @@ var Think = class Think extends Agent {
1967
2046
  this._completeSkippedRequest(connection, requestId);
1968
2047
  return;
1969
2048
  }
2049
+ await this._syncMessages();
1970
2050
  this._broadcastMessages([connection.id]);
1971
2051
  const abortSignal = this._aborts.getSignal(requestId);
1972
2052
  await this.keepAliveWhile(async () => {
@@ -2098,7 +2178,7 @@ var Think = class Think extends Agent {
2098
2178
  abortAllRequests() {
2099
2179
  this._aborts.destroyAll();
2100
2180
  }
2101
- _handleClear(connection) {
2181
+ async _handleClear(connection) {
2102
2182
  this.resetTurnState();
2103
2183
  this._resumableStream.clearAll();
2104
2184
  this._pendingResumeConnections.clear();
@@ -2106,7 +2186,7 @@ var Think = class Think extends Agent {
2106
2186
  this._persistClientTools();
2107
2187
  this._lastBody = void 0;
2108
2188
  this._persistBody();
2109
- this.session.clearMessages();
2189
+ await this._clearHistory();
2110
2190
  this._broadcast({ type: MSG_CHAT_CLEAR }, connection ? [connection.id] : void 0);
2111
2191
  }
2112
2192
  async _streamResultToRpcCallback(requestId, result, callback, abortSignal) {
@@ -2143,7 +2223,7 @@ var Think = class Think extends Agent {
2143
2223
  this._resumableStream.complete(streamId);
2144
2224
  streamFinalized = true;
2145
2225
  assistantMsg = accumulator.toMessage();
2146
- this._persistAssistantMessage(assistantMsg);
2226
+ await this._persistAssistantMessage(assistantMsg);
2147
2227
  if (!aborted) {
2148
2228
  await callback.onDone();
2149
2229
  await this._fireResponseHook({
@@ -2165,7 +2245,7 @@ var Think = class Think extends Agent {
2165
2245
  }
2166
2246
  if (!assistantMsg && accumulator.parts.length > 0) {
2167
2247
  assistantMsg = accumulator.toMessage();
2168
- this._persistAssistantMessage(assistantMsg);
2248
+ await this._persistAssistantMessage(assistantMsg);
2169
2249
  }
2170
2250
  const wrapped = this.onChatError(error);
2171
2251
  const errorMessage = wrapped instanceof Error ? wrapped.message : String(wrapped);
@@ -2265,7 +2345,7 @@ var Think = class Think extends Agent {
2265
2345
  }
2266
2346
  if (accumulator.parts.length > 0 && this._turnQueue.generation === clearGen) try {
2267
2347
  const assistantMsg = accumulator.toMessage();
2268
- this._persistAssistantMessage(assistantMsg, parentId);
2348
+ await this._persistAssistantMessage(assistantMsg, parentId);
2269
2349
  this._broadcastMessages();
2270
2350
  await this._fireResponseHook({
2271
2351
  message: assistantMsg,
@@ -2278,10 +2358,8 @@ var Think = class Think extends Agent {
2278
2358
  console.error("Failed to persist assistant message:", e);
2279
2359
  }
2280
2360
  }
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);
2361
+ async _persistAssistantMessage(msg, parentId) {
2362
+ await this._upsertMessageInHistory(msg, parentId);
2285
2363
  }
2286
2364
  /**
2287
2365
  * Persist an incoming message after reconciliation. For assistant
@@ -2290,12 +2368,8 @@ var Think = class Think extends Agent {
2290
2368
  * instead of inserting an orphan duplicate.
2291
2369
  */
2292
2370
  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);
2371
+ const resolved = msg.role === "assistant" ? resolveToolMergeId(msg, serverMessages) : msg;
2372
+ await this._upsertMessageInHistory(resolved);
2299
2373
  }
2300
2374
  _persistClientTools() {
2301
2375
  if (this._lastClientTools) this._configSet("lastClientTools", JSON.stringify(this._lastClientTools));
@@ -2321,24 +2395,25 @@ var Think = class Think extends Agent {
2321
2395
  this._lastBody = void 0;
2322
2396
  }
2323
2397
  }
2324
- _applyToolResult(toolCallId, output, overrideState, errorText) {
2398
+ async _applyToolResult(toolCallId, output, overrideState, errorText) {
2325
2399
  const update = toolResultUpdate(toolCallId, output, overrideState, errorText);
2326
- this._applyToolUpdateToMessages(update);
2400
+ await this._applyToolUpdateToMessages(update);
2327
2401
  }
2328
- _applyToolApproval(toolCallId, approved) {
2402
+ async _applyToolApproval(toolCallId, approved) {
2329
2403
  const update = toolApprovalUpdate(toolCallId, approved);
2330
- this._applyToolUpdateToMessages(update);
2404
+ await this._applyToolUpdateToMessages(update);
2331
2405
  }
2332
- _applyToolUpdateToMessages(update) {
2333
- const history = this.messages;
2334
- 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];
2335
2410
  const result = applyToolUpdate(msg.parts, update);
2336
2411
  if (result) {
2337
- const safe = enforceRowSizeLimit(sanitizeMessage({
2412
+ const updatedMsg = {
2338
2413
  ...msg,
2339
2414
  parts: result.parts
2340
- }));
2341
- this.session.updateMessage(safe);
2415
+ };
2416
+ const safe = await this._updateMessageInHistory(updatedMsg);
2342
2417
  this._broadcast({
2343
2418
  type: MSG_MESSAGE_UPDATED,
2344
2419
  message: safe
@@ -2418,14 +2493,14 @@ var Think = class Think extends Agent {
2418
2493
  });
2419
2494
  const streamStillActive = streamId && this._resumableStream.hasActiveStream() && this._resumableStream.activeStreamId === streamId;
2420
2495
  const streamIsTerminal = streamStatus === "completed" || streamStatus === "error";
2421
- if (options.persist !== false && (streamStillActive || streamIsTerminal)) this._persistOrphanedStream(streamId);
2496
+ if (options.persist !== false && streamId && (streamStillActive || streamIsTerminal)) await this._persistOrphanedStream(streamId);
2422
2497
  if (streamStillActive) this._resumableStream.complete(streamId);
2423
2498
  const canContinue = options.continue !== false && !streamIsTerminal;
2424
2499
  const hasRunningSubmission = this._hasRunningSubmission(requestId);
2425
2500
  if (streamIsTerminal && hasRunningSubmission) await this._completeRecoveredSubmission(requestId, streamStatus === "completed" ? "completed" : "error", requestId, streamStatus === "completed" ? null : "Recovered chat stream had already errored.");
2426
2501
  const recoveredRequestId = canContinue && hasRunningSubmission ? requestId : void 0;
2427
2502
  if (canContinue) {
2428
- const lastLeaf = this.session.getLatestLeaf();
2503
+ const lastLeaf = await this.session.getLatestLeaf();
2429
2504
  const targetId = lastLeaf?.role === "assistant" ? lastLeaf.id : void 0;
2430
2505
  await this.schedule(0, "_chatRecoveryContinue", {
2431
2506
  ...targetId ? { targetAssistantId: targetId } : {},
@@ -2512,7 +2587,7 @@ var Think = class Think extends Agent {
2512
2587
  return;
2513
2588
  }
2514
2589
  const targetId = data?.targetAssistantId;
2515
- const lastLeaf = this.session.getLatestLeaf();
2590
+ const lastLeaf = await this.session.getLatestLeaf();
2516
2591
  if (targetId && lastLeaf?.id !== targetId) {
2517
2592
  if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, "error", null, "Recovered chat continuation was skipped because the conversation changed.");
2518
2593
  return;
@@ -2661,7 +2736,7 @@ var Think = class Think extends Agent {
2661
2736
  id: this._resumableStream.activeRequestId
2662
2737
  }))) this._pendingResumeConnections.add(connection.id);
2663
2738
  }
2664
- _persistOrphanedStream(streamId) {
2739
+ async _persistOrphanedStream(streamId) {
2665
2740
  this._resumableStream.flushBuffer();
2666
2741
  const chunks = this._resumableStream.getStreamChunks(streamId);
2667
2742
  if (chunks.length === 0) return;
@@ -2670,7 +2745,7 @@ var Think = class Think extends Agent {
2670
2745
  accumulator.applyChunk(JSON.parse(chunk.body));
2671
2746
  } catch {}
2672
2747
  if (accumulator.parts.length > 0) {
2673
- this._persistAssistantMessage(accumulator.toMessage());
2748
+ await this._persistAssistantMessage(accumulator.toMessage());
2674
2749
  this._broadcastMessages();
2675
2750
  }
2676
2751
  }