@cloudflare/think 0.1.1 → 0.1.2

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,142 +1,26 @@
1
- import { t as SessionManager } from "./session-C6ZU_1zM.js";
2
- import { applyChunkToParts } from "./message-builder.js";
3
- import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldGet2, t as _classPrivateFieldSet2 } from "./classPrivateFieldSet2-q3BTMj1l.js";
1
+ import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldGet2, t as _classPrivateFieldSet2 } from "./classPrivateFieldSet2-D-GfNNJe.js";
4
2
  import { convertToModelMessages, pruneMessages, stepCountIs, streamText } from "ai";
5
3
  import { Agent, __DO_NOT_USE_WILL_BREAK__agentContext } from "agents";
6
4
  import { withFibers } from "agents/experimental/forever";
7
- //#region src/sanitize.ts
8
- /** Shared encoder for UTF-8 byte length measurement */
9
- const textEncoder = new TextEncoder();
10
- /** Maximum serialized message size before compaction (bytes). 1.8MB with headroom below SQLite's 2MB limit. */
11
- const ROW_MAX_BYTES = 18e5;
12
- /** Measure UTF-8 byte length of a string. */
13
- function byteLength(s) {
14
- return textEncoder.encode(s).byteLength;
15
- }
16
- /**
17
- * Sanitize a message for persistence by removing ephemeral provider-specific
18
- * data that should not be stored or sent back in subsequent requests.
19
- *
20
- * 1. Strips OpenAI ephemeral fields (itemId, reasoningEncryptedContent)
21
- * 2. Filters truly empty reasoning parts (no text, no remaining providerMetadata)
22
- */
23
- function sanitizeMessage(message) {
24
- const sanitizedParts = message.parts.map((part) => {
25
- let sanitizedPart = part;
26
- if ("providerMetadata" in sanitizedPart && sanitizedPart.providerMetadata && typeof sanitizedPart.providerMetadata === "object" && "openai" in sanitizedPart.providerMetadata) sanitizedPart = stripOpenAIMetadata(sanitizedPart, "providerMetadata");
27
- if ("callProviderMetadata" in sanitizedPart && sanitizedPart.callProviderMetadata && typeof sanitizedPart.callProviderMetadata === "object" && "openai" in sanitizedPart.callProviderMetadata) sanitizedPart = stripOpenAIMetadata(sanitizedPart, "callProviderMetadata");
28
- return sanitizedPart;
29
- }).filter((part) => {
30
- if (part.type === "reasoning") {
31
- const reasoningPart = part;
32
- if (!reasoningPart.text || reasoningPart.text.trim() === "") {
33
- if ("providerMetadata" in reasoningPart && reasoningPart.providerMetadata && typeof reasoningPart.providerMetadata === "object" && Object.keys(reasoningPart.providerMetadata).length > 0) return true;
34
- return false;
35
- }
36
- }
37
- return true;
38
- });
39
- return {
40
- ...message,
41
- parts: sanitizedParts
42
- };
43
- }
44
- /**
45
- * Strip OpenAI-specific ephemeral fields from a metadata object.
46
- */
47
- function stripOpenAIMetadata(part, metadataKey) {
48
- const metadata = part[metadataKey];
49
- if (!metadata?.openai) return part;
50
- const { itemId: _itemId, reasoningEncryptedContent: _rec, ...restOpenai } = metadata.openai;
51
- const hasOtherOpenaiFields = Object.keys(restOpenai).length > 0;
52
- const { openai: _openai, ...restMetadata } = metadata;
53
- let newMetadata;
54
- if (hasOtherOpenaiFields) newMetadata = {
55
- ...restMetadata,
56
- openai: restOpenai
57
- };
58
- else if (Object.keys(restMetadata).length > 0) newMetadata = restMetadata;
59
- const { [metadataKey]: _oldMeta, ...restPart } = part;
60
- if (newMetadata) return {
61
- ...restPart,
62
- [metadataKey]: newMetadata
63
- };
64
- return restPart;
65
- }
66
- /**
67
- * Enforce SQLite row size limits by compacting tool outputs and text parts
68
- * when a serialized message exceeds the safety threshold (1.8MB).
69
- *
70
- * Compaction strategy:
71
- * 1. Compact tool outputs over 1KB (replace with summary)
72
- * 2. If still too big, truncate text parts from oldest to newest
73
- */
74
- function enforceRowSizeLimit(message) {
75
- let json = JSON.stringify(message);
76
- let size = byteLength(json);
77
- if (size <= ROW_MAX_BYTES) return message;
78
- if (message.role !== "assistant") return truncateTextParts(message);
79
- const compactedParts = message.parts.map((part) => {
80
- if ("output" in part && "toolCallId" in part && "state" in part && part.state === "output-available") {
81
- const outputJson = JSON.stringify(part.output);
82
- if (outputJson.length > 1e3) return {
83
- ...part,
84
- output: `This tool output was too large to persist in storage (${outputJson.length} bytes). If the user asks about this data, suggest re-running the tool. Preview: ${outputJson.slice(0, 500)}...`
85
- };
86
- }
87
- return part;
88
- });
89
- let result = {
90
- ...message,
91
- parts: compactedParts
92
- };
93
- json = JSON.stringify(result);
94
- size = byteLength(json);
95
- if (size <= ROW_MAX_BYTES) return result;
96
- return truncateTextParts(result);
97
- }
98
- /**
99
- * Truncate text parts to fit within the row size limit.
100
- */
101
- function truncateTextParts(message) {
102
- const parts = [...message.parts];
103
- for (let i = 0; i < parts.length; i++) {
104
- const part = parts[i];
105
- if (part.type === "text" && "text" in part) {
106
- const text = part.text;
107
- if (text.length > 1e3) {
108
- parts[i] = {
109
- ...part,
110
- text: `[Text truncated for storage (${text.length} chars). First 500 chars: ${text.slice(0, 500)}...]`
111
- };
112
- const candidate = {
113
- ...message,
114
- parts
115
- };
116
- if (byteLength(JSON.stringify(candidate)) <= ROW_MAX_BYTES) break;
117
- }
118
- }
119
- }
120
- return {
121
- ...message,
122
- parts
123
- };
124
- }
125
- //#endregion
5
+ import { CHAT_MESSAGE_TYPES, ContinuationState, ResumableStream, StreamAccumulator, TurnQueue, createToolsFromClientSchemas, enforceRowSizeLimit, sanitizeMessage } from "agents/chat";
126
6
  //#region src/think.ts
127
7
  const ThinkBase = withFibers(Agent);
128
- const MSG_CHAT_MESSAGES = "cf_agent_chat_messages";
129
- const MSG_CHAT_REQUEST = "cf_agent_use_chat_request";
130
- const MSG_CHAT_RESPONSE = "cf_agent_use_chat_response";
131
- const MSG_CHAT_CLEAR = "cf_agent_chat_clear";
132
- const MSG_CHAT_CANCEL = "cf_agent_chat_request_cancel";
8
+ const MSG_CHAT_MESSAGES = CHAT_MESSAGE_TYPES.CHAT_MESSAGES;
9
+ const MSG_CHAT_REQUEST = CHAT_MESSAGE_TYPES.USE_CHAT_REQUEST;
10
+ const MSG_CHAT_RESPONSE = CHAT_MESSAGE_TYPES.USE_CHAT_RESPONSE;
11
+ const MSG_CHAT_CLEAR = CHAT_MESSAGE_TYPES.CHAT_CLEAR;
12
+ const MSG_CHAT_CANCEL = CHAT_MESSAGE_TYPES.CHAT_REQUEST_CANCEL;
13
+ const MSG_STREAM_RESUMING = CHAT_MESSAGE_TYPES.STREAM_RESUMING;
14
+ const MSG_STREAM_RESUME_ACK = CHAT_MESSAGE_TYPES.STREAM_RESUME_ACK;
15
+ const MSG_STREAM_RESUME_REQUEST = CHAT_MESSAGE_TYPES.STREAM_RESUME_REQUEST;
16
+ const MSG_STREAM_RESUME_NONE = CHAT_MESSAGE_TYPES.STREAM_RESUME_NONE;
17
+ const MSG_TOOL_RESULT = CHAT_MESSAGE_TYPES.TOOL_RESULT;
18
+ const MSG_TOOL_APPROVAL = CHAT_MESSAGE_TYPES.TOOL_APPROVAL;
19
+ const MSG_MESSAGE_UPDATED = CHAT_MESSAGE_TYPES.MESSAGE_UPDATED;
133
20
  var _configTableReady = /* @__PURE__ */ new WeakMap();
134
21
  var _configCache = /* @__PURE__ */ new WeakMap();
135
22
  /**
136
- * A unified Agent base class for chat sessions.
137
- *
138
- * Works as both a top-level agent (WebSocket chat protocol) and a
139
- * sub-agent (RPC streaming via `chat()`).
23
+ * An opinionated chat agent base class.
140
24
  *
141
25
  * @experimental Requires the `"experimental"` compatibility flag.
142
26
  */
@@ -145,11 +29,15 @@ var Think = class extends ThinkBase {
145
29
  super(..._args);
146
30
  this.messages = [];
147
31
  this.fibers = false;
32
+ this.waitForMcpConnections = false;
148
33
  this.maxPersistedMessages = void 0;
149
34
  this._persistedMessageCache = /* @__PURE__ */ new Map();
150
- this._sessionId = null;
35
+ this._storageReady = false;
151
36
  this._abortControllers = /* @__PURE__ */ new Map();
152
- this._clearGeneration = 0;
37
+ this._turnQueue = new TurnQueue();
38
+ this._pendingResumeConnections = /* @__PURE__ */ new Set();
39
+ this._continuation = new ContinuationState();
40
+ this._continuationTimer = null;
153
41
  _classPrivateFieldInitSpec(this, _configTableReady, false);
154
42
  _classPrivateFieldInitSpec(this, _configCache, null);
155
43
  }
@@ -190,15 +78,11 @@ var Think = class extends ThinkBase {
190
78
  return null;
191
79
  }
192
80
  onStart() {
193
- this.sessions = new SessionManager(this, { exec: (query, ...values) => {
194
- this.ctx.storage.sql.exec(query, ...values);
195
- } });
196
- const existing = this.sessions.list();
197
- if (existing.length > 0) {
198
- this._sessionId = existing[0].id;
199
- this.messages = this.sessions.getHistory(this._sessionId);
200
- this._rebuildPersistenceCache();
201
- }
81
+ this._initStorage();
82
+ this._resumableStream = new ResumableStream(this.sql.bind(this));
83
+ this.messages = this._loadMessages();
84
+ this._rebuildPersistenceCache();
85
+ this._restoreClientTools();
202
86
  this._setupProtocolHandlers();
203
87
  if (this.fibers) this.checkFibers();
204
88
  }
@@ -210,56 +94,19 @@ var Think = class extends ThinkBase {
210
94
  getModel() {
211
95
  throw new Error("Override getModel() to return a LanguageModel, or override onChatMessage() for full control.");
212
96
  }
213
- /**
214
- * Return the system prompt for the assistant.
215
- * Override to customize instructions.
216
- */
97
+ /** Return the system prompt for the assistant. */
217
98
  getSystemPrompt() {
218
99
  return "You are a helpful assistant.";
219
100
  }
220
- /**
221
- * Return the tools available to the assistant.
222
- * Override to provide workspace tools, custom tools, etc.
223
- */
101
+ /** Return the tools available to the assistant. */
224
102
  getTools() {
225
103
  return {};
226
104
  }
227
- /**
228
- * Return the maximum number of tool-call steps per turn.
229
- */
105
+ /** Return the maximum number of tool-call steps per turn. */
230
106
  getMaxSteps() {
231
107
  return 10;
232
108
  }
233
109
  /**
234
- * Return the workspace instance for this session, or null if none.
235
- *
236
- * Override in subclasses that create a Workspace. Used by
237
- * HostBridgeLoopback to provide workspace access to extension Workers.
238
- */
239
- getWorkspace() {
240
- return null;
241
- }
242
- async _hostReadFile(path) {
243
- const ws = this.getWorkspace();
244
- if (!ws) throw new Error("No workspace available on this agent");
245
- return ws.readFile(path);
246
- }
247
- async _hostWriteFile(path, content) {
248
- const ws = this.getWorkspace();
249
- if (!ws) throw new Error("No workspace available on this agent");
250
- await ws.writeFile(path, content);
251
- }
252
- async _hostDeleteFile(path) {
253
- const ws = this.getWorkspace();
254
- if (!ws) throw new Error("No workspace available on this agent");
255
- return ws.deleteFile(path);
256
- }
257
- async _hostListFiles(dir) {
258
- const ws = this.getWorkspace();
259
- if (!ws) throw new Error("No workspace available on this agent");
260
- return ws.readDir(dir);
261
- }
262
- /**
263
110
  * Assemble the model messages from the current conversation history.
264
111
  * Override to customize context assembly (e.g. inject memory,
265
112
  * project context, or apply compaction).
@@ -277,25 +124,25 @@ var Think = class extends ThinkBase {
277
124
  * 1. Assemble context from `this.messages`
278
125
  * 2. Call `streamText` with the model, system prompt, tools, and step limit
279
126
  *
280
- * Override for full control over inference (e.g. different models per turn,
281
- * RAG pipelines, routing to specialized sub-agents, etc.).
282
- *
283
- * When this is called, `this.messages` already contains the user's
284
- * latest message persisted to the current session.
127
+ * Override for full control over inference.
285
128
  *
286
129
  * @returns A result with `toUIMessageStream()` — AI SDK's `streamText()`
287
130
  * return value satisfies this interface.
288
131
  */
289
132
  async onChatMessage(options) {
290
133
  const baseTools = this.getTools();
291
- const tools = options?.tools ? {
134
+ const clientToolSet = createToolsFromClientSchemas(options?.clientTools);
135
+ const tools = {
292
136
  ...baseTools,
293
- ...options.tools
294
- } : baseTools;
137
+ ...clientToolSet,
138
+ ...options?.tools
139
+ };
140
+ const messages = await this.assembleContext();
141
+ 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.");
295
142
  return streamText({
296
143
  model: this.getModel(),
297
144
  system: this.getSystemPrompt(),
298
- messages: await this.assembleContext(),
145
+ messages,
299
146
  tools,
300
147
  stopWhen: stepCountIs(this.getMaxSteps()),
301
148
  abortSignal: options?.signal
@@ -304,9 +151,6 @@ var Think = class extends ThinkBase {
304
151
  /**
305
152
  * Handle an error that occurred during a chat turn.
306
153
  * Override to customize error handling (e.g. logging, metrics).
307
- *
308
- * @param error The error that occurred
309
- * @returns The error (or a wrapped version) to propagate
310
154
  */
311
155
  onChatError(error) {
312
156
  return error;
@@ -316,123 +160,77 @@ var Think = class extends ThinkBase {
316
160
  * stream UIMessageChunk events via callback, and persist the
317
161
  * assistant's response.
318
162
  *
319
- * On error or abort, the partial assistant message is still persisted
320
- * so the user doesn't lose context.
321
- *
322
- * @param userMessage The user's message (string or UIMessage for multi-modal)
163
+ * @param userMessage The user's message (string or UIMessage)
323
164
  * @param callback Streaming callback (typically an RpcTarget from the parent)
324
165
  * @param options Optional chat options (e.g. AbortSignal)
325
166
  */
326
167
  async chat(userMessage, callback, options) {
327
- if (!this._sessionId) this._sessionId = this.sessions.create("default").id;
328
- const userMsg = typeof userMessage === "string" ? {
329
- id: crypto.randomUUID(),
330
- role: "user",
331
- parts: [{
332
- type: "text",
333
- text: userMessage
334
- }]
335
- } : userMessage;
336
- this.sessions.append(this._sessionId, userMsg);
337
- this.messages = this.sessions.getHistory(this._sessionId);
338
- const assistantMsg = {
339
- id: crypto.randomUUID(),
340
- role: "assistant",
341
- parts: []
342
- };
343
- try {
344
- const result = await this.onChatMessage({
345
- signal: options?.signal,
346
- tools: options?.tools
347
- });
348
- let aborted = false;
349
- for await (const chunk of result.toUIMessageStream()) {
350
- if (options?.signal?.aborted) {
351
- aborted = true;
352
- break;
168
+ const requestId = crypto.randomUUID();
169
+ await this._turnQueue.enqueue(requestId, async () => {
170
+ const userMsg = typeof userMessage === "string" ? {
171
+ id: crypto.randomUUID(),
172
+ role: "user",
173
+ parts: [{
174
+ type: "text",
175
+ text: userMessage
176
+ }]
177
+ } : userMessage;
178
+ this._appendMessage(userMsg);
179
+ this.messages = this._loadMessages();
180
+ const accumulator = new StreamAccumulator({ messageId: crypto.randomUUID() });
181
+ try {
182
+ const result = await this.onChatMessage({
183
+ signal: options?.signal,
184
+ tools: options?.tools
185
+ });
186
+ let aborted = false;
187
+ for await (const chunk of result.toUIMessageStream()) {
188
+ if (options?.signal?.aborted) {
189
+ aborted = true;
190
+ break;
191
+ }
192
+ accumulator.applyChunk(chunk);
193
+ await callback.onEvent(JSON.stringify(chunk));
353
194
  }
354
- applyChunkToParts(assistantMsg.parts, chunk);
355
- await callback.onEvent(JSON.stringify(chunk));
195
+ this._persistAssistantMessage(accumulator.toMessage());
196
+ if (!aborted) await callback.onDone();
197
+ } catch (error) {
198
+ if (accumulator.parts.length > 0) this._persistAssistantMessage(accumulator.toMessage());
199
+ const wrapped = this.onChatError(error);
200
+ const errorMessage = wrapped instanceof Error ? wrapped.message : String(wrapped);
201
+ if (callback.onError) await callback.onError(errorMessage);
202
+ else throw wrapped;
356
203
  }
357
- this._persistAssistantMessage(assistantMsg);
358
- if (!aborted) await callback.onDone();
359
- } catch (error) {
360
- if (assistantMsg.parts.length > 0) this._persistAssistantMessage(assistantMsg);
361
- const wrapped = this.onChatError(error);
362
- const errorMessage = wrapped instanceof Error ? wrapped.message : String(wrapped);
363
- if (callback.onError) await callback.onError(errorMessage);
364
- else throw wrapped;
365
- }
366
- }
367
- getSessions() {
368
- return this.sessions.list();
204
+ });
369
205
  }
370
- createSession(name) {
371
- const session = this.sessions.create(name);
372
- this._sessionId = session.id;
373
- this.messages = [];
374
- this._broadcastMessages();
375
- return session;
376
- }
377
- switchSession(sessionId) {
378
- if (!this.sessions.get(sessionId)) throw new Error(`Session not found: ${sessionId}`);
379
- this._sessionId = sessionId;
380
- this.messages = this.sessions.getHistory(sessionId);
381
- this._broadcastMessages();
206
+ /** Get the conversation history as UIMessage[]. */
207
+ getMessages() {
382
208
  return this.messages;
383
209
  }
384
- deleteSession(sessionId) {
385
- if (!this.sessions.get(sessionId)) throw new Error(`Session not found: ${sessionId}`);
386
- this.sessions.delete(sessionId);
387
- if (this._sessionId === sessionId) {
388
- this._sessionId = null;
389
- this.messages = [];
390
- this._broadcastMessages();
391
- }
392
- }
393
- renameSession(sessionId, name) {
394
- if (!this.sessions.get(sessionId)) throw new Error(`Session not found: ${sessionId}`);
395
- this.sessions.rename(sessionId, name);
396
- }
397
- getCurrentSessionId() {
398
- return this._sessionId;
399
- }
400
- /**
401
- * Get the current session info, or null if no session exists yet.
402
- */
403
- getSession() {
404
- if (!this._sessionId) return null;
405
- return this.sessions.get(this._sessionId);
406
- }
407
- /**
408
- * Get the conversation history as UIMessage[].
409
- */
410
- getHistory() {
411
- if (!this._sessionId) return [];
412
- return this.sessions.getHistory(this._sessionId);
413
- }
414
- /**
415
- * Get the total message count for this session.
416
- */
417
- getMessageCount() {
418
- if (!this._sessionId) return 0;
419
- return this.sessions.getMessageCount(this._sessionId);
420
- }
421
- /**
422
- * Clear all messages from this session (preserves the session itself).
423
- */
210
+ /** Clear all messages from storage and memory. */
424
211
  clearMessages() {
425
- if (!this._sessionId) return;
426
- this.sessions.clearMessages(this._sessionId);
212
+ this._clearMessages();
427
213
  this.messages = [];
428
214
  this._persistedMessageCache.clear();
429
215
  }
430
- /**
431
- * Wrap onMessage and onRequest to intercept the chat protocol.
432
- * Unrecognized messages are forwarded to the user's handlers.
433
- * @internal
434
- */
435
216
  _setupProtocolHandlers() {
217
+ const _onConnect = this.onConnect.bind(this);
218
+ this.onConnect = async (connection, ctx) => {
219
+ if (this._resumableStream.hasActiveStream()) this._notifyStreamResuming(connection);
220
+ connection.send(JSON.stringify({
221
+ type: MSG_CHAT_MESSAGES,
222
+ messages: this.messages
223
+ }));
224
+ return _onConnect(connection, ctx);
225
+ };
226
+ const _onClose = this.onClose.bind(this);
227
+ this.onClose = async (connection, code, reason, wasClean) => {
228
+ this._pendingResumeConnections.delete(connection.id);
229
+ this._continuation.awaitingConnections.delete(connection.id);
230
+ if (this._continuation.pending?.connectionId === connection.id) this._continuation.pending = null;
231
+ if (this._continuation.activeConnectionId === connection.id) this._continuation.activeConnectionId = null;
232
+ return _onClose(connection, code, reason, wasClean);
233
+ };
436
234
  const _onMessage = this.onMessage.bind(this);
437
235
  this.onMessage = async (connection, message) => {
438
236
  if (typeof message === "string") try {
@@ -444,30 +242,49 @@ var Think = class extends ThinkBase {
444
242
  const _onRequest = this.onRequest.bind(this);
445
243
  this.onRequest = async (request) => {
446
244
  const url = new URL(request.url);
447
- if (url.pathname === "/get-messages" || url.pathname.endsWith("/get-messages")) {
448
- const sessionId = url.searchParams.get("sessionId");
449
- if (sessionId) {
450
- if (!this.sessions.get(sessionId)) return Response.json({ error: "Session not found" }, { status: 404 });
451
- return Response.json(this.sessions.getHistory(sessionId));
452
- }
453
- return Response.json(this.messages);
454
- }
245
+ if (url.pathname === "/get-messages" || url.pathname.endsWith("/get-messages")) return Response.json(this.messages);
455
246
  return _onRequest(request);
456
247
  };
457
248
  }
458
- /**
459
- * Route an incoming WebSocket message to the appropriate handler.
460
- * Returns true if the message was handled by the protocol.
461
- * @internal
462
- */
463
249
  async _handleProtocol(connection, data) {
464
250
  const type = data.type;
251
+ if (type === MSG_STREAM_RESUME_REQUEST) {
252
+ if (this._resumableStream.hasActiveStream()) if (this._continuation.activeRequestId === this._resumableStream.activeRequestId && this._continuation.activeConnectionId !== null && this._continuation.activeConnectionId !== connection.id) connection.send(JSON.stringify({ type: MSG_STREAM_RESUME_NONE }));
253
+ else this._notifyStreamResuming(connection);
254
+ else if (this._continuation.pending !== null && this._continuation.pending.connectionId === connection.id) this._continuation.awaitingConnections.set(connection.id, connection);
255
+ else connection.send(JSON.stringify({ type: MSG_STREAM_RESUME_NONE }));
256
+ return true;
257
+ }
258
+ if (type === MSG_STREAM_RESUME_ACK) {
259
+ this._pendingResumeConnections.delete(connection.id);
260
+ if (this._resumableStream.hasActiveStream() && this._resumableStream.activeRequestId === data.id) {
261
+ const orphanedStreamId = this._resumableStream.replayChunks(connection, this._resumableStream.activeRequestId);
262
+ if (orphanedStreamId) this._persistOrphanedStream(orphanedStreamId);
263
+ }
264
+ return true;
265
+ }
465
266
  if (type === MSG_CHAT_REQUEST) {
466
267
  if (data.init?.method === "POST") {
467
268
  await this._handleChatRequest(connection, data);
468
269
  return true;
469
270
  }
470
271
  }
272
+ if (type === MSG_TOOL_RESULT) {
273
+ const { toolCallId, toolName: _toolName, output, state, errorText, autoContinue, clientTools } = data;
274
+ if (clientTools && Array.isArray(clientTools) && clientTools.length > 0) {
275
+ this._lastClientTools = clientTools;
276
+ this._persistClientTools();
277
+ }
278
+ this._applyToolResult(toolCallId, output, state, errorText);
279
+ if (autoContinue) this._scheduleAutoContinuation(connection);
280
+ return true;
281
+ }
282
+ if (type === MSG_TOOL_APPROVAL) {
283
+ const { toolCallId, approved, autoContinue } = data;
284
+ this._applyToolApproval(toolCallId, approved);
285
+ if (autoContinue) this._scheduleAutoContinuation(connection);
286
+ return true;
287
+ }
471
288
  if (type === MSG_CHAT_CLEAR) {
472
289
  this._handleClear();
473
290
  return true;
@@ -478,16 +295,6 @@ var Think = class extends ThinkBase {
478
295
  }
479
296
  return false;
480
297
  }
481
- /**
482
- * Handle CF_AGENT_USE_CHAT_REQUEST:
483
- * 1. Parse incoming messages
484
- * 2. Ensure a session exists
485
- * 3. Persist user messages to session
486
- * 4. Call onChatMessage
487
- * 5. Stream response back to clients
488
- * 6. Persist assistant message to session
489
- * @internal
490
- */
491
298
  async _handleChatRequest(connection, data) {
492
299
  const init = data.init;
493
300
  if (!init?.body) return;
@@ -499,31 +306,54 @@ var Think = class extends ThinkBase {
499
306
  }
500
307
  const incomingMessages = parsed.messages;
501
308
  if (!Array.isArray(incomingMessages)) return;
502
- if (!this._sessionId) this._sessionId = this.sessions.create("New Chat").id;
503
- this.sessions.appendAll(this._sessionId, incomingMessages);
504
- this.messages = this.sessions.getHistory(this._sessionId);
309
+ const requestClientTools = parsed.clientTools?.length ? parsed.clientTools : void 0;
310
+ if (requestClientTools) {
311
+ this._lastClientTools = requestClientTools;
312
+ this._persistClientTools();
313
+ } else if (parsed.clientTools !== void 0) {
314
+ this._lastClientTools = void 0;
315
+ this._persistClientTools();
316
+ }
317
+ const clientToolsForTurn = this._lastClientTools;
318
+ for (const msg of incomingMessages) this._appendMessage(msg);
319
+ this.messages = this._loadMessages();
505
320
  this._broadcastMessages([connection.id]);
506
321
  const requestId = data.id;
507
322
  const abortController = new AbortController();
508
323
  this._abortControllers.set(requestId, abortController);
509
324
  try {
510
325
  await this.keepAliveWhile(async () => {
511
- const result = await __DO_NOT_USE_WILL_BREAK__agentContext.run({
512
- agent: this,
513
- connection,
514
- request: void 0,
515
- email: void 0
516
- }, () => this.onChatMessage({ signal: abortController.signal }));
517
- if (result) await this._streamResult(requestId, result, abortController.signal);
518
- else this._broadcast({
326
+ if ((await this._turnQueue.enqueue(requestId, async () => {
327
+ if (this.waitForMcpConnections) {
328
+ const timeout = typeof this.waitForMcpConnections === "object" ? this.waitForMcpConnections.timeout : 1e4;
329
+ await this.mcp.waitForConnections({ timeout });
330
+ }
331
+ this.messages = this._loadMessages();
332
+ const result = await __DO_NOT_USE_WILL_BREAK__agentContext.run({
333
+ agent: this,
334
+ connection,
335
+ request: void 0,
336
+ email: void 0
337
+ }, () => this.onChatMessage({
338
+ signal: abortController.signal,
339
+ clientTools: clientToolsForTurn
340
+ }));
341
+ if (result) await this._streamResult(requestId, result, abortController.signal);
342
+ else this._broadcastChat({
343
+ type: MSG_CHAT_RESPONSE,
344
+ id: requestId,
345
+ body: "No response was generated.",
346
+ done: true
347
+ });
348
+ })).status === "stale") this._broadcastChat({
519
349
  type: MSG_CHAT_RESPONSE,
520
350
  id: requestId,
521
- body: "No response was generated.",
351
+ body: "",
522
352
  done: true
523
353
  });
524
354
  });
525
355
  } catch (error) {
526
- this._broadcast({
356
+ this._broadcastChat({
527
357
  type: MSG_CHAT_RESPONSE,
528
358
  id: requestId,
529
359
  body: error instanceof Error ? error.message : "Error",
@@ -534,77 +364,64 @@ var Think = class extends ThinkBase {
534
364
  this._abortControllers.delete(requestId);
535
365
  }
536
366
  }
537
- /**
538
- * Handle CF_AGENT_CHAT_CLEAR: abort streams, clear current session messages.
539
- * @internal
540
- */
541
367
  _handleClear() {
368
+ this._turnQueue.reset();
542
369
  for (const controller of this._abortControllers.values()) controller.abort();
543
370
  this._abortControllers.clear();
544
- if (this._sessionId) this.sessions.clearMessages(this._sessionId);
371
+ this._resumableStream.clearAll();
372
+ this._pendingResumeConnections.clear();
373
+ this._lastClientTools = void 0;
374
+ this._persistClientTools();
375
+ if (this._continuationTimer) {
376
+ clearTimeout(this._continuationTimer);
377
+ this._continuationTimer = null;
378
+ }
379
+ this._continuation.sendResumeNone();
380
+ this._continuation.clearAll();
381
+ this._clearMessages();
545
382
  this.messages = [];
546
383
  this._persistedMessageCache.clear();
547
- this._clearGeneration++;
548
384
  this._broadcast({ type: MSG_CHAT_CLEAR });
549
385
  }
550
- /**
551
- * Handle CF_AGENT_CHAT_REQUEST_CANCEL: abort a specific request.
552
- * @internal
553
- */
554
386
  _handleCancel(requestId) {
555
387
  const controller = this._abortControllers.get(requestId);
556
388
  if (controller) controller.abort();
557
389
  }
558
- /**
559
- * Iterate a StreamableResult, broadcast chunks to clients,
560
- * build a UIMessage, and persist it to the session.
561
- * @internal
562
- */
563
390
  async _streamResult(requestId, result, abortSignal) {
564
- const clearGen = this._clearGeneration;
565
- const message = {
566
- id: crypto.randomUUID(),
567
- role: "assistant",
568
- parts: []
569
- };
391
+ const clearGen = this._turnQueue.generation;
392
+ const streamId = this._resumableStream.start(requestId);
393
+ if (this._continuation.pending?.requestId === requestId) {
394
+ this._continuation.activatePending();
395
+ this._continuation.flushAwaitingConnections((c) => this._notifyStreamResuming(c));
396
+ }
397
+ const accumulator = new StreamAccumulator({ messageId: crypto.randomUUID() });
570
398
  let doneSent = false;
571
399
  try {
572
400
  for await (const chunk of result.toUIMessageStream()) {
573
401
  if (abortSignal?.aborted) break;
574
- const data = chunk;
575
- if (!applyChunkToParts(message.parts, data)) switch (data.type) {
576
- case "start":
577
- if (data.messageId != null) message.id = data.messageId;
578
- if (data.messageMetadata != null) message.metadata = message.metadata ? {
579
- ...message.metadata,
580
- ...data.messageMetadata
581
- } : data.messageMetadata;
582
- break;
583
- case "finish":
584
- case "message-metadata":
585
- if (data.messageMetadata != null) message.metadata = message.metadata ? {
586
- ...message.metadata,
587
- ...data.messageMetadata
588
- } : data.messageMetadata;
589
- break;
590
- case "error":
591
- this._broadcast({
592
- type: MSG_CHAT_RESPONSE,
593
- id: requestId,
594
- body: data.errorText ?? JSON.stringify(data),
595
- done: false,
596
- error: true
597
- });
598
- continue;
402
+ const { action } = accumulator.applyChunk(chunk);
403
+ if (action?.type === "error") {
404
+ this._broadcastChat({
405
+ type: MSG_CHAT_RESPONSE,
406
+ id: requestId,
407
+ body: action.error,
408
+ done: false,
409
+ error: true
410
+ });
411
+ continue;
599
412
  }
600
- this._broadcast({
413
+ const chunkBody = JSON.stringify(chunk);
414
+ this._resumableStream.storeChunk(streamId, chunkBody);
415
+ this._broadcastChat({
601
416
  type: MSG_CHAT_RESPONSE,
602
417
  id: requestId,
603
- body: JSON.stringify(chunk),
418
+ body: chunkBody,
604
419
  done: false
605
420
  });
606
421
  }
607
- this._broadcast({
422
+ this._resumableStream.complete(streamId);
423
+ this._pendingResumeConnections.clear();
424
+ this._broadcastChat({
608
425
  type: MSG_CHAT_RESPONSE,
609
426
  id: requestId,
610
427
  body: "",
@@ -612,8 +429,10 @@ var Think = class extends ThinkBase {
612
429
  });
613
430
  doneSent = true;
614
431
  } catch (error) {
432
+ this._resumableStream.markError(streamId);
433
+ this._pendingResumeConnections.clear();
615
434
  if (!doneSent) {
616
- this._broadcast({
435
+ this._broadcastChat({
617
436
  type: MSG_CHAT_RESPONSE,
618
437
  id: requestId,
619
438
  body: error instanceof Error ? error.message : "Stream error",
@@ -623,71 +442,269 @@ var Think = class extends ThinkBase {
623
442
  doneSent = true;
624
443
  }
625
444
  } finally {
626
- if (!doneSent) this._broadcast({
627
- type: MSG_CHAT_RESPONSE,
628
- id: requestId,
629
- body: "",
630
- done: true
631
- });
445
+ if (!doneSent) {
446
+ this._resumableStream.markError(streamId);
447
+ this._pendingResumeConnections.clear();
448
+ this._broadcastChat({
449
+ type: MSG_CHAT_RESPONSE,
450
+ id: requestId,
451
+ body: "",
452
+ done: true
453
+ });
454
+ }
632
455
  }
633
- if (message.parts.length > 0 && this._sessionId && this._clearGeneration === clearGen) try {
634
- this._persistAssistantMessage(message);
456
+ if (accumulator.parts.length > 0 && this._turnQueue.generation === clearGen) try {
457
+ this._persistAssistantMessage(accumulator.toMessage());
635
458
  this._broadcastMessages();
636
459
  } catch (e) {
637
460
  console.error("Failed to persist assistant message:", e);
638
461
  }
639
462
  }
640
- /**
641
- * Persist an assistant message with sanitization, size enforcement,
642
- * and incremental persistence.
643
- * @internal
644
- */
463
+ _initStorage() {
464
+ if (this._storageReady) return;
465
+ this.sql`
466
+ CREATE TABLE IF NOT EXISTS assistant_messages (
467
+ id TEXT PRIMARY KEY,
468
+ role TEXT NOT NULL,
469
+ content TEXT NOT NULL,
470
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
471
+ )
472
+ `;
473
+ this.sql`
474
+ CREATE TABLE IF NOT EXISTS think_request_context (
475
+ key TEXT PRIMARY KEY,
476
+ value TEXT NOT NULL
477
+ )
478
+ `;
479
+ this._storageReady = true;
480
+ }
481
+ _loadMessages() {
482
+ return this.sql`
483
+ SELECT content FROM assistant_messages ORDER BY created_at ASC
484
+ `.map((row) => JSON.parse(row.content));
485
+ }
486
+ _appendMessage(msg) {
487
+ const json = JSON.stringify(msg);
488
+ this.sql`
489
+ INSERT OR IGNORE INTO assistant_messages (id, role, content)
490
+ VALUES (${msg.id}, ${msg.role}, ${json})
491
+ `;
492
+ this._persistedMessageCache.set(msg.id, json);
493
+ }
494
+ _upsertMessage(msg) {
495
+ const json = JSON.stringify(msg);
496
+ this.sql`
497
+ INSERT INTO assistant_messages (id, role, content)
498
+ VALUES (${msg.id}, ${msg.role}, ${json})
499
+ ON CONFLICT(id) DO UPDATE SET content = excluded.content
500
+ `;
501
+ this._persistedMessageCache.set(msg.id, json);
502
+ }
503
+ _clearMessages() {
504
+ this.sql`DELETE FROM assistant_messages`;
505
+ }
506
+ _deleteMessages(ids) {
507
+ for (const id of ids) this.sql`DELETE FROM assistant_messages WHERE id = ${id}`;
508
+ }
509
+ _persistClientTools() {
510
+ if (this._lastClientTools) this.sql`
511
+ INSERT OR REPLACE INTO think_request_context (key, value)
512
+ VALUES ('lastClientTools', ${JSON.stringify(this._lastClientTools)})
513
+ `;
514
+ else this.sql`DELETE FROM think_request_context WHERE key = 'lastClientTools'`;
515
+ }
516
+ _restoreClientTools() {
517
+ const rows = this.sql`
518
+ SELECT value FROM think_request_context WHERE key = 'lastClientTools'
519
+ ` || [];
520
+ if (rows.length > 0) try {
521
+ this._lastClientTools = JSON.parse(rows[0].value);
522
+ } catch {
523
+ this._lastClientTools = void 0;
524
+ }
525
+ }
645
526
  _persistAssistantMessage(msg) {
646
- if (!this._sessionId) return;
647
527
  const safe = enforceRowSizeLimit(sanitizeMessage(msg));
648
528
  const json = JSON.stringify(safe);
649
- if (this._persistedMessageCache.get(safe.id) !== json) {
650
- this.sessions.upsert(this._sessionId, safe);
651
- this._persistedMessageCache.set(safe.id, json);
652
- }
529
+ if (this._persistedMessageCache.get(safe.id) !== json) this._upsertMessage(safe);
653
530
  if (this.maxPersistedMessages != null) this._enforceMaxPersistedMessages();
654
- this.messages = this.sessions.getHistory(this._sessionId);
531
+ this.messages = this._loadMessages();
655
532
  }
656
- /**
657
- * Rebuild the persistence cache from current messages.
658
- * Called on startup to enable incremental persistence.
659
- * @internal
660
- */
661
533
  _rebuildPersistenceCache() {
662
534
  this._persistedMessageCache.clear();
663
535
  for (const msg of this.messages) this._persistedMessageCache.set(msg.id, JSON.stringify(msg));
664
536
  }
665
- /**
666
- * Delete oldest messages on the current branch when count exceeds
667
- * maxPersistedMessages. Uses path-based count (not total across all
668
- * branches) and individual deletes to preserve branch structure.
669
- * @internal
670
- */
671
537
  _enforceMaxPersistedMessages() {
672
- if (this.maxPersistedMessages == null || !this._sessionId) return;
673
- const history = this.sessions.getHistory(this._sessionId);
538
+ if (this.maxPersistedMessages == null) return;
539
+ const history = this._loadMessages();
674
540
  if (history.length <= this.maxPersistedMessages) return;
675
541
  const excess = history.length - this.maxPersistedMessages;
676
542
  const toRemove = history.slice(0, excess);
677
- this.sessions.deleteMessages(toRemove.map((m) => m.id));
543
+ this._deleteMessages(toRemove.map((m) => m.id));
678
544
  for (const msg of toRemove) this._persistedMessageCache.delete(msg.id);
679
545
  }
680
- /**
681
- * Broadcast a JSON message to all connected clients.
682
- * @internal
683
- */
546
+ _applyToolResult(toolCallId, output, overrideState, errorText) {
547
+ const validStates = [
548
+ "input-available",
549
+ "approval-requested",
550
+ "approval-responded"
551
+ ];
552
+ for (const msg of this.messages) for (let i = 0; i < msg.parts.length; i++) {
553
+ const part = msg.parts[i];
554
+ if ("toolCallId" in part && part.toolCallId === toolCallId && "state" in part && validStates.includes(part.state)) {
555
+ if (overrideState === "output-error") msg.parts[i] = {
556
+ ...part,
557
+ state: "output-error",
558
+ errorText: errorText ?? "Tool execution denied by user"
559
+ };
560
+ else msg.parts[i] = {
561
+ ...part,
562
+ state: "output-available",
563
+ output,
564
+ preliminary: false
565
+ };
566
+ const safe = enforceRowSizeLimit(sanitizeMessage(msg));
567
+ this._upsertMessage(safe);
568
+ this.messages = this._loadMessages();
569
+ this._broadcast({
570
+ type: MSG_MESSAGE_UPDATED,
571
+ message: safe
572
+ });
573
+ return;
574
+ }
575
+ }
576
+ }
577
+ _applyToolApproval(toolCallId, approved) {
578
+ const validStates = ["input-available", "approval-requested"];
579
+ for (const msg of this.messages) for (let i = 0; i < msg.parts.length; i++) {
580
+ const part = msg.parts[i];
581
+ if ("toolCallId" in part && part.toolCallId === toolCallId && "state" in part && validStates.includes(part.state)) {
582
+ msg.parts[i] = {
583
+ ...part,
584
+ state: approved ? "approval-responded" : "output-denied",
585
+ approval: {
586
+ ...part.approval,
587
+ approved
588
+ }
589
+ };
590
+ const safe = enforceRowSizeLimit(sanitizeMessage(msg));
591
+ this._upsertMessage(safe);
592
+ this.messages = this._loadMessages();
593
+ this._broadcast({
594
+ type: MSG_MESSAGE_UPDATED,
595
+ message: safe
596
+ });
597
+ return;
598
+ }
599
+ }
600
+ }
601
+ _scheduleAutoContinuation(connection) {
602
+ if (this._continuation.pending?.pastCoalesce) {
603
+ this._continuation.deferred = {
604
+ connection,
605
+ connectionId: connection.id,
606
+ clientTools: this._lastClientTools,
607
+ body: void 0,
608
+ errorPrefix: "[Think] Auto-continuation failed:",
609
+ prerequisite: null
610
+ };
611
+ return;
612
+ }
613
+ if (this._continuation.pending) {
614
+ this._continuation.pending.connection = connection;
615
+ this._continuation.pending.connectionId = connection.id;
616
+ this._continuation.pending.clientTools = this._lastClientTools;
617
+ this._continuation.awaitingConnections.set(connection.id, connection);
618
+ return;
619
+ }
620
+ if (this._continuationTimer) clearTimeout(this._continuationTimer);
621
+ this._continuationTimer = setTimeout(() => {
622
+ this._continuationTimer = null;
623
+ this._fireAutoContinuation(connection);
624
+ }, 50);
625
+ }
626
+ _fireAutoContinuation(connection) {
627
+ if (!this._continuation.pending) {
628
+ const requestId = crypto.randomUUID();
629
+ this._continuation.pending = {
630
+ connection,
631
+ connectionId: connection.id,
632
+ requestId,
633
+ clientTools: this._lastClientTools,
634
+ body: void 0,
635
+ errorPrefix: "[Think] Auto-continuation failed:",
636
+ prerequisite: null,
637
+ pastCoalesce: false
638
+ };
639
+ this._continuation.awaitingConnections.set(connection.id, connection);
640
+ }
641
+ const { requestId, clientTools } = this._continuation.pending;
642
+ const abortController = new AbortController();
643
+ this._abortControllers.set(requestId, abortController);
644
+ this.keepAliveWhile(async () => {
645
+ await this._turnQueue.enqueue(requestId, async () => {
646
+ if (this._continuation.pending) this._continuation.pending.pastCoalesce = true;
647
+ let streamed = false;
648
+ try {
649
+ this.messages = this._loadMessages();
650
+ const result = await __DO_NOT_USE_WILL_BREAK__agentContext.run({
651
+ agent: this,
652
+ connection,
653
+ request: void 0,
654
+ email: void 0
655
+ }, () => this.onChatMessage({
656
+ signal: abortController.signal,
657
+ clientTools
658
+ }));
659
+ if (result) {
660
+ await this._streamResult(requestId, result, abortController.signal);
661
+ streamed = true;
662
+ }
663
+ } finally {
664
+ this._abortControllers.delete(requestId);
665
+ if (!streamed) this._continuation.sendResumeNone();
666
+ this._continuation.clearPending();
667
+ this._activateDeferredContinuation();
668
+ }
669
+ });
670
+ }).catch((error) => {
671
+ console.error("[Think] Auto-continuation failed:", error);
672
+ this._abortControllers.delete(requestId);
673
+ });
674
+ }
675
+ _activateDeferredContinuation() {
676
+ const pending = this._continuation.activateDeferred(() => crypto.randomUUID());
677
+ if (!pending) return;
678
+ this._fireAutoContinuation(pending.connection);
679
+ }
680
+ _notifyStreamResuming(connection) {
681
+ if (!this._resumableStream.hasActiveStream()) return;
682
+ this._pendingResumeConnections.add(connection.id);
683
+ connection.send(JSON.stringify({
684
+ type: MSG_STREAM_RESUMING,
685
+ id: this._resumableStream.activeRequestId
686
+ }));
687
+ }
688
+ _persistOrphanedStream(streamId) {
689
+ this._resumableStream.flushBuffer();
690
+ const chunks = this._resumableStream.getStreamChunks(streamId);
691
+ if (chunks.length === 0) return;
692
+ const accumulator = new StreamAccumulator({ messageId: crypto.randomUUID() });
693
+ for (const chunk of chunks) try {
694
+ accumulator.applyChunk(JSON.parse(chunk.body));
695
+ } catch {}
696
+ if (accumulator.parts.length > 0) {
697
+ this._persistAssistantMessage(accumulator.toMessage());
698
+ this._broadcastMessages();
699
+ }
700
+ }
701
+ _broadcastChat(message, exclude) {
702
+ const allExclusions = [...exclude || [], ...this._pendingResumeConnections];
703
+ this.broadcast(JSON.stringify(message), allExclusions);
704
+ }
684
705
  _broadcast(message, exclude) {
685
706
  this.broadcast(JSON.stringify(message), exclude);
686
707
  }
687
- /**
688
- * Broadcast the current message list to all connected clients.
689
- * @internal
690
- */
691
708
  _broadcastMessages(exclude) {
692
709
  this._broadcast({
693
710
  type: MSG_CHAT_MESSAGES,