@cloudflare/think 0.1.2 → 0.2.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,65 +1,67 @@
1
- import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldGet2, t as _classPrivateFieldSet2 } from "./classPrivateFieldSet2-D-GfNNJe.js";
1
+ import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldSet2, t as _classPrivateFieldGet2 } from "./classPrivateFieldGet2-B0jG-d4Z.js";
2
2
  import { convertToModelMessages, pruneMessages, stepCountIs, streamText } from "ai";
3
3
  import { Agent, __DO_NOT_USE_WILL_BREAK__agentContext } from "agents";
4
- import { withFibers } from "agents/experimental/forever";
5
- import { CHAT_MESSAGE_TYPES, ContinuationState, ResumableStream, StreamAccumulator, TurnQueue, createToolsFromClientSchemas, enforceRowSizeLimit, sanitizeMessage } from "agents/chat";
4
+ import { AbortRegistry, CHAT_MESSAGE_TYPES, ContinuationState, ResumableStream, StreamAccumulator, TurnQueue, applyChunkToParts, applyToolUpdate, createToolsFromClientSchemas, enforceRowSizeLimit, parseProtocolMessage, sanitizeMessage, toolApprovalUpdate, toolResultUpdate } from "agents/chat";
5
+ import { Session, Session as Session$1 } from "agents/experimental/memory/session";
6
+ import { truncateOlderMessages } from "agents/experimental/memory/utils";
6
7
  //#region src/think.ts
7
- const ThinkBase = withFibers(Agent);
8
8
  const MSG_CHAT_MESSAGES = CHAT_MESSAGE_TYPES.CHAT_MESSAGES;
9
- const MSG_CHAT_REQUEST = CHAT_MESSAGE_TYPES.USE_CHAT_REQUEST;
10
9
  const MSG_CHAT_RESPONSE = CHAT_MESSAGE_TYPES.USE_CHAT_RESPONSE;
11
10
  const MSG_CHAT_CLEAR = CHAT_MESSAGE_TYPES.CHAT_CLEAR;
12
- const MSG_CHAT_CANCEL = CHAT_MESSAGE_TYPES.CHAT_REQUEST_CANCEL;
13
11
  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
12
  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
13
  const MSG_MESSAGE_UPDATED = CHAT_MESSAGE_TYPES.MESSAGE_UPDATED;
20
- var _configTableReady = /* @__PURE__ */ new WeakMap();
14
+ const TIMED_OUT = Symbol("timed-out");
21
15
  var _configCache = /* @__PURE__ */ new WeakMap();
22
16
  /**
23
17
  * An opinionated chat agent base class.
24
18
  *
25
19
  * @experimental Requires the `"experimental"` compatibility flag.
26
20
  */
27
- var Think = class extends ThinkBase {
28
- constructor(..._args) {
29
- super(..._args);
30
- this.messages = [];
31
- this.fibers = false;
21
+ var Think = class Think extends Agent {
22
+ constructor(ctx, env) {
23
+ super(ctx, env);
32
24
  this.waitForMcpConnections = false;
33
- this.maxPersistedMessages = void 0;
34
- this._persistedMessageCache = /* @__PURE__ */ new Map();
35
- this._storageReady = false;
36
- this._abortControllers = /* @__PURE__ */ new Map();
25
+ this.messageConcurrency = "queue";
26
+ this.unstable_chatRecovery = false;
27
+ this._aborts = new AbortRegistry();
37
28
  this._turnQueue = new TurnQueue();
38
29
  this._pendingResumeConnections = /* @__PURE__ */ new Set();
39
30
  this._continuation = new ContinuationState();
40
31
  this._continuationTimer = null;
41
- _classPrivateFieldInitSpec(this, _configTableReady, false);
32
+ this._insideResponseHook = false;
33
+ this._pendingInteractionPromise = null;
34
+ this._submitSequence = 0;
35
+ this._latestOverlappingSubmitSequence = 0;
36
+ this._activeDebounceTimer = null;
37
+ this._activeDebounceResolve = null;
42
38
  _classPrivateFieldInitSpec(this, _configCache, null);
39
+ const _onStart = this.onStart.bind(this);
40
+ this.onStart = async () => {
41
+ const baseSession = Session$1.create(this);
42
+ this.session = await this.configureSession(baseSession);
43
+ this.session.getHistory();
44
+ this._resumableStream = new ResumableStream(this.sql.bind(this));
45
+ this._restoreClientTools();
46
+ this._restoreBody();
47
+ this._setupProtocolHandlers();
48
+ await _onStart();
49
+ };
43
50
  }
44
- _ensureConfigTable() {
45
- if (_classPrivateFieldGet2(_configTableReady, this)) return;
46
- this.sql`
47
- CREATE TABLE IF NOT EXISTS _think_config (
48
- key TEXT PRIMARY KEY, value TEXT NOT NULL
49
- )
50
- `;
51
- _classPrivateFieldSet2(_configTableReady, this, true);
51
+ /**
52
+ * Conversation history. Computed from the active session.
53
+ * Always fresh — reads from Session's tree-structured storage.
54
+ */
55
+ get messages() {
56
+ return this.session.getHistory();
52
57
  }
53
58
  /**
54
59
  * Persist a typed configuration object.
55
- * Stored in SQLite so it survives restarts and hibernation.
60
+ * Stored in Session's assistant_config table — survives restarts and hibernation.
56
61
  */
57
62
  configure(config) {
58
- this._ensureConfigTable();
59
63
  const json = JSON.stringify(config);
60
- this.sql`
61
- INSERT OR REPLACE INTO _think_config (key, value) VALUES ('config', ${json})
62
- `;
64
+ this._configSet("_think_config", json);
63
65
  _classPrivateFieldSet2(_configCache, this, config);
64
66
  }
65
67
  /**
@@ -67,24 +69,36 @@ var Think = class extends ThinkBase {
67
69
  */
68
70
  getConfig() {
69
71
  if (_classPrivateFieldGet2(_configCache, this)) return _classPrivateFieldGet2(_configCache, this);
70
- this._ensureConfigTable();
71
- const rows = this.sql`
72
- SELECT value FROM _think_config WHERE key = 'config'
73
- `;
74
- if (rows.length > 0) {
75
- _classPrivateFieldSet2(_configCache, this, JSON.parse(rows[0].value));
72
+ const raw = this._configGet("_think_config");
73
+ if (raw !== void 0) {
74
+ _classPrivateFieldSet2(_configCache, this, JSON.parse(raw));
76
75
  return _classPrivateFieldGet2(_configCache, this);
77
76
  }
78
77
  return null;
79
78
  }
80
- onStart() {
81
- this._initStorage();
82
- this._resumableStream = new ResumableStream(this.sql.bind(this));
83
- this.messages = this._loadMessages();
84
- this._rebuildPersistenceCache();
85
- this._restoreClientTools();
86
- this._setupProtocolHandlers();
87
- if (this.fibers) this.checkFibers();
79
+ _configSet(key, value) {
80
+ const sessionId = this._sessionId();
81
+ this.sql`
82
+ INSERT OR REPLACE INTO assistant_config (session_id, key, value)
83
+ VALUES (${sessionId}, ${key}, ${value})
84
+ `;
85
+ }
86
+ _configGet(key) {
87
+ const sessionId = this._sessionId();
88
+ return this.sql`
89
+ SELECT value FROM assistant_config
90
+ WHERE session_id = ${sessionId} AND key = ${key}
91
+ `[0]?.value;
92
+ }
93
+ _configDelete(key) {
94
+ const sessionId = this._sessionId();
95
+ this.sql`
96
+ DELETE FROM assistant_config
97
+ WHERE session_id = ${sessionId} AND key = ${key}
98
+ `;
99
+ }
100
+ _sessionId() {
101
+ return "";
88
102
  }
89
103
  /**
90
104
  * Return the language model to use for inference.
@@ -94,7 +108,10 @@ var Think = class extends ThinkBase {
94
108
  getModel() {
95
109
  throw new Error("Override getModel() to return a LanguageModel, or override onChatMessage() for full control.");
96
110
  }
97
- /** Return the system prompt for the assistant. */
111
+ /**
112
+ * Return the system prompt for the assistant.
113
+ * Used as fallback when no context blocks are configured via `configureSession`.
114
+ */
98
115
  getSystemPrompt() {
99
116
  return "You are a helpful assistant.";
100
117
  }
@@ -107,22 +124,64 @@ var Think = class extends ThinkBase {
107
124
  return 10;
108
125
  }
109
126
  /**
110
- * Assemble the model messages from the current conversation history.
111
- * Override to customize context assembly (e.g. inject memory,
112
- * project context, or apply compaction).
127
+ * Configure the session. Called once during `onStart`.
128
+ * Override to add context blocks, compaction, search, skills.
129
+ *
130
+ * The base session is pre-created with `Session.create(this)`.
131
+ * Return it with builder methods chained.
132
+ *
133
+ * Async is supported — use it to read configuration from KV, D1,
134
+ * or R2 before setting up context blocks.
135
+ *
136
+ * @example
137
+ * ```typescript
138
+ * configureSession(session: Session) {
139
+ * return session
140
+ * .withContext("memory", { description: "Learned facts", maxTokens: 2000 })
141
+ * .withCachedPrompt();
142
+ * }
143
+ * ```
144
+ *
145
+ * @example Async configuration from KV
146
+ * ```typescript
147
+ * async configureSession(session: Session) {
148
+ * const config = await this.env.KV.get("agent-config", "json");
149
+ * return session
150
+ * .withContext("memory", { maxTokens: config.memoryTokens })
151
+ * .withCachedPrompt();
152
+ * }
153
+ * ```
154
+ */
155
+ configureSession(session) {
156
+ return session;
157
+ }
158
+ /**
159
+ * Assemble context for the LLM from the current session state.
160
+ *
161
+ * Default implementation:
162
+ * 1. Freezes the system prompt from context blocks (falls back to getSystemPrompt())
163
+ * 2. Gets history from session
164
+ * 3. Applies read-time truncation (old tool outputs, long text)
165
+ * 4. Converts to model messages with tool call pruning
166
+ *
167
+ * Returns { system, messages } so the caller has both.
113
168
  */
114
169
  async assembleContext() {
115
- return pruneMessages({
116
- messages: await convertToModelMessages(this.messages),
117
- toolCalls: "before-last-2-messages"
118
- });
170
+ return {
171
+ system: await this.session.freezeSystemPrompt() || this.getSystemPrompt(),
172
+ messages: pruneMessages({
173
+ messages: await convertToModelMessages(truncateOlderMessages(this.session.getHistory())),
174
+ toolCalls: "before-last-2-messages"
175
+ })
176
+ };
119
177
  }
120
178
  /**
121
179
  * Handle a chat turn and return the streaming result.
122
180
  *
123
181
  * The default implementation runs the agentic loop:
124
- * 1. Assemble context from `this.messages`
125
- * 2. Call `streamText` with the model, system prompt, tools, and step limit
182
+ * 1. Merge tools: getTools() + clientTools + session context tools + options.tools
183
+ * 2. Assemble context (system prompt + messages) from session state
184
+ * 3. Call `streamText` with the model, system prompt, tools, and step limit
126
185
  *
127
186
  * Override for full control over inference.
128
187
  *
@@ -132,16 +191,18 @@ var Think = class extends ThinkBase {
132
191
  async onChatMessage(options) {
133
192
  const baseTools = this.getTools();
134
193
  const clientToolSet = createToolsFromClientSchemas(options?.clientTools);
194
+ const contextTools = await this.session.tools();
135
195
  const tools = {
136
196
  ...baseTools,
137
197
  ...clientToolSet,
198
+ ...contextTools,
138
199
  ...options?.tools
139
200
  };
140
- const messages = await this.assembleContext();
201
+ const { system, messages } = await this.assembleContext();
141
202
  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.");
142
203
  return streamText({
143
204
  model: this.getModel(),
144
- system: this.getSystemPrompt(),
205
+ system,
145
206
  messages,
146
207
  tools,
147
208
  stopWhen: stepCountIs(this.getMaxSteps()),
@@ -149,6 +210,17 @@ var Think = class extends ThinkBase {
149
210
  });
150
211
  }
151
212
  /**
213
+ * Called after a chat turn completes and the assistant message has been
214
+ * persisted. The turn lock is released before this hook runs, so it is
215
+ * safe to call other methods from inside.
216
+ *
217
+ * Fires for all turn completion paths: WebSocket chat requests,
218
+ * sub-agent RPC, and auto-continuation.
219
+ *
220
+ * Override for logging, chaining, analytics, usage tracking.
221
+ */
222
+ onChatResponse(_result) {}
223
+ /**
152
224
  * Handle an error that occurred during a chat turn.
153
225
  * Override to customize error handling (e.g. logging, metrics).
154
226
  */
@@ -175,13 +247,13 @@ var Think = class extends ThinkBase {
175
247
  text: userMessage
176
248
  }]
177
249
  } : userMessage;
178
- this._appendMessage(userMsg);
179
- this.messages = this._loadMessages();
250
+ await this.session.appendMessage(userMsg);
180
251
  const accumulator = new StreamAccumulator({ messageId: crypto.randomUUID() });
181
252
  try {
182
253
  const result = await this.onChatMessage({
183
254
  signal: options?.signal,
184
- tools: options?.tools
255
+ tools: options?.tools,
256
+ continuation: false
185
257
  });
186
258
  let aborted = false;
187
259
  for await (const chunk of result.toUIMessageStream()) {
@@ -192,12 +264,34 @@ var Think = class extends ThinkBase {
192
264
  accumulator.applyChunk(chunk);
193
265
  await callback.onEvent(JSON.stringify(chunk));
194
266
  }
195
- this._persistAssistantMessage(accumulator.toMessage());
196
- if (!aborted) await callback.onDone();
267
+ const assistantMsg = accumulator.toMessage();
268
+ this._persistAssistantMessage(assistantMsg);
269
+ if (!aborted) {
270
+ await callback.onDone();
271
+ await this._fireResponseHook({
272
+ message: assistantMsg,
273
+ requestId,
274
+ continuation: false,
275
+ status: "completed"
276
+ });
277
+ } else await this._fireResponseHook({
278
+ message: assistantMsg,
279
+ requestId,
280
+ continuation: false,
281
+ status: "aborted"
282
+ });
197
283
  } catch (error) {
198
- if (accumulator.parts.length > 0) this._persistAssistantMessage(accumulator.toMessage());
284
+ const assistantMsg = accumulator.parts.length > 0 ? accumulator.toMessage() : null;
285
+ if (assistantMsg) this._persistAssistantMessage(assistantMsg);
199
286
  const wrapped = this.onChatError(error);
200
287
  const errorMessage = wrapped instanceof Error ? wrapped.message : String(wrapped);
288
+ if (assistantMsg) await this._fireResponseHook({
289
+ message: assistantMsg,
290
+ requestId,
291
+ continuation: false,
292
+ status: "error",
293
+ error: errorMessage
294
+ });
201
295
  if (callback.onError) await callback.onError(errorMessage);
202
296
  else throw wrapped;
203
297
  }
@@ -207,11 +301,161 @@ var Think = class extends ThinkBase {
207
301
  getMessages() {
208
302
  return this.messages;
209
303
  }
210
- /** Clear all messages from storage and memory. */
304
+ /** Clear all messages from storage. */
211
305
  clearMessages() {
212
- this._clearMessages();
213
- this.messages = [];
214
- this._persistedMessageCache.clear();
306
+ this.session.clearMessages();
307
+ }
308
+ /**
309
+ * Inject messages and trigger a model turn — without a WebSocket request.
310
+ *
311
+ * Use for scheduled responses, webhook-triggered turns, proactive agents,
312
+ * or chaining from `onChatResponse`.
313
+ *
314
+ * Accepts static messages or a callback that derives messages from the
315
+ * current state (useful when multiple calls queue up — the callback runs
316
+ * with the latest messages when the turn actually starts).
317
+ *
318
+ * @example Scheduled follow-up
319
+ * ```typescript
320
+ * async onScheduled() {
321
+ * await this.saveMessages([{
322
+ * id: crypto.randomUUID(),
323
+ * role: "user",
324
+ * parts: [{ type: "text", text: "Time for your daily summary." }]
325
+ * }]);
326
+ * }
327
+ * ```
328
+ *
329
+ * @example Function form
330
+ * ```typescript
331
+ * await this.saveMessages((current) => [
332
+ * ...current,
333
+ * { id: crypto.randomUUID(), role: "user", parts: [{ type: "text", text: "Continue." }] }
334
+ * ]);
335
+ * ```
336
+ */
337
+ async saveMessages(messages) {
338
+ const requestId = crypto.randomUUID();
339
+ const clientTools = this._lastClientTools;
340
+ const body = this._lastBody;
341
+ const epoch = this._turnQueue.generation;
342
+ let status = "completed";
343
+ await this.keepAliveWhile(async () => {
344
+ await this._turnQueue.enqueue(requestId, async () => {
345
+ const resolved = typeof messages === "function" ? await messages(this.messages) : messages;
346
+ if (this._turnQueue.generation !== epoch) {
347
+ status = "skipped";
348
+ return;
349
+ }
350
+ for (const msg of resolved) await this.session.appendMessage(msg);
351
+ this._broadcastMessages();
352
+ if (this._turnQueue.generation !== epoch) {
353
+ status = "skipped";
354
+ return;
355
+ }
356
+ const abortSignal = this._aborts.getSignal(requestId);
357
+ try {
358
+ const programmaticBody = async () => {
359
+ const result = await __DO_NOT_USE_WILL_BREAK__agentContext.run({
360
+ agent: this,
361
+ connection: void 0,
362
+ request: void 0,
363
+ email: void 0
364
+ }, () => this.onChatMessage({
365
+ signal: abortSignal,
366
+ clientTools,
367
+ body,
368
+ continuation: false
369
+ }));
370
+ if (result) await this._streamResult(requestId, result, abortSignal);
371
+ };
372
+ if (this.unstable_chatRecovery) await this.runFiber(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => {
373
+ await programmaticBody();
374
+ });
375
+ else await programmaticBody();
376
+ } finally {
377
+ this._aborts.remove(requestId);
378
+ }
379
+ });
380
+ });
381
+ if (this._turnQueue.generation !== epoch && status === "completed") status = "skipped";
382
+ return {
383
+ requestId,
384
+ status
385
+ };
386
+ }
387
+ /**
388
+ * Run a new LLM call following the last assistant message.
389
+ *
390
+ * The model sees the full conversation (including the last assistant
391
+ * response) and generates a new response. The new response is persisted
392
+ * as a separate assistant message. Building block for chat recovery
393
+ * (Phase 4), "generate more" buttons, and self-correction.
394
+ *
395
+ * Note: this creates a new message, not an append to the existing one.
396
+ * True continuation-as-append (chunk rewriting) is planned for Phase 4.
397
+ *
398
+ * Returns early with `status: "skipped"` if there is no assistant message
399
+ * to continue from.
400
+ */
401
+ async continueLastTurn(body) {
402
+ const lastLeaf = this.session.getLatestLeaf();
403
+ if (!lastLeaf || lastLeaf.role !== "assistant") return {
404
+ requestId: "",
405
+ status: "skipped"
406
+ };
407
+ const requestId = crypto.randomUUID();
408
+ const clientTools = this._lastClientTools;
409
+ const resolvedBody = body ?? this._lastBody;
410
+ const epoch = this._turnQueue.generation;
411
+ let status = "completed";
412
+ await this.keepAliveWhile(async () => {
413
+ await this._turnQueue.enqueue(requestId, async () => {
414
+ if (this._turnQueue.generation !== epoch) {
415
+ status = "skipped";
416
+ return;
417
+ }
418
+ const abortSignal = this._aborts.getSignal(requestId);
419
+ try {
420
+ const continueTurnBody = async () => {
421
+ const result = await __DO_NOT_USE_WILL_BREAK__agentContext.run({
422
+ agent: this,
423
+ connection: void 0,
424
+ request: void 0,
425
+ email: void 0
426
+ }, () => this.onChatMessage({
427
+ signal: abortSignal,
428
+ clientTools,
429
+ body: resolvedBody,
430
+ continuation: true
431
+ }));
432
+ if (result) await this._streamResult(requestId, result, abortSignal, { continuation: true });
433
+ };
434
+ if (this.unstable_chatRecovery) await this.runFiber(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => {
435
+ await continueTurnBody();
436
+ });
437
+ else await continueTurnBody();
438
+ } finally {
439
+ this._aborts.remove(requestId);
440
+ }
441
+ });
442
+ });
443
+ if (this._turnQueue.generation !== epoch && status === "completed") status = "skipped";
444
+ return {
445
+ requestId,
446
+ status
447
+ };
448
+ }
449
+ /**
450
+ * Override to apply custom transformations to messages before they are
451
+ * persisted to Session storage. Runs after the built-in sanitization
452
+ * (OpenAI metadata stripping, row size enforcement) but before
453
+ * `session.appendMessage` / `session.updateMessage`.
454
+ *
455
+ * Use for redacting PII, stripping internal metadata, or custom compaction.
456
+ */
457
+ sanitizeMessageForPersistence(message) {
458
+ return message;
215
459
  }
216
460
  _setupProtocolHandlers() {
217
461
  const _onConnect = this.onConnect.bind(this);
@@ -233,10 +477,13 @@ var Think = class extends ThinkBase {
233
477
  };
234
478
  const _onMessage = this.onMessage.bind(this);
235
479
  this.onMessage = async (connection, message) => {
236
- if (typeof message === "string") try {
237
- const data = JSON.parse(message);
238
- if (await this._handleProtocol(connection, data)) return;
239
- } catch {}
480
+ if (typeof message === "string") {
481
+ const event = parseProtocolMessage(message);
482
+ if (event) {
483
+ await this._handleProtocolEvent(connection, event);
484
+ return;
485
+ }
486
+ }
240
487
  return _onMessage(connection, message);
241
488
  };
242
489
  const _onRequest = this.onRequest.bind(this);
@@ -246,105 +493,150 @@ var Think = class extends ThinkBase {
246
493
  return _onRequest(request);
247
494
  };
248
495
  }
249
- async _handleProtocol(connection, data) {
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
- }
266
- if (type === MSG_CHAT_REQUEST) {
267
- if (data.init?.method === "POST") {
268
- await this._handleChatRequest(connection, data);
269
- return true;
496
+ async _handleProtocolEvent(connection, event) {
497
+ switch (event.type) {
498
+ case "stream-resume-request":
499
+ this._handleStreamResumeRequest(connection);
500
+ break;
501
+ case "stream-resume-ack":
502
+ this._handleStreamResumeAck(connection, event.id);
503
+ break;
504
+ case "chat-request":
505
+ if (event.init?.method === "POST") await this._handleChatRequest(connection, event);
506
+ break;
507
+ case "tool-result": {
508
+ if (event.clientTools && Array.isArray(event.clientTools) && event.clientTools.length > 0) {
509
+ this._lastClientTools = event.clientTools;
510
+ this._persistClientTools();
511
+ }
512
+ const resultPromise = Promise.resolve().then(() => {
513
+ this._applyToolResult(event.toolCallId, event.output, event.state, event.errorText);
514
+ return true;
515
+ });
516
+ this._pendingInteractionPromise = resultPromise;
517
+ resultPromise.finally(() => {
518
+ if (this._pendingInteractionPromise === resultPromise) this._pendingInteractionPromise = null;
519
+ }).catch(() => {});
520
+ if (event.autoContinue) this._scheduleAutoContinuation(connection);
521
+ break;
270
522
  }
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();
523
+ case "tool-approval": {
524
+ const approvalPromise = Promise.resolve().then(() => {
525
+ this._applyToolApproval(event.toolCallId, event.approved);
526
+ return true;
527
+ });
528
+ this._pendingInteractionPromise = approvalPromise;
529
+ approvalPromise.finally(() => {
530
+ if (this._pendingInteractionPromise === approvalPromise) this._pendingInteractionPromise = null;
531
+ }).catch(() => {});
532
+ if (event.autoContinue) this._scheduleAutoContinuation(connection);
533
+ break;
277
534
  }
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;
535
+ case "clear":
536
+ this._handleClear(connection);
537
+ break;
538
+ case "cancel":
539
+ this._aborts.cancel(event.id);
540
+ break;
541
+ case "messages": break;
287
542
  }
288
- if (type === MSG_CHAT_CLEAR) {
289
- this._handleClear();
290
- return true;
291
- }
292
- if (type === MSG_CHAT_CANCEL) {
293
- this._handleCancel(data.id);
294
- return true;
543
+ }
544
+ _handleStreamResumeRequest(connection) {
545
+ 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 }));
546
+ else this._notifyStreamResuming(connection);
547
+ else if (this._continuation.pending !== null && this._continuation.pending.connectionId === connection.id) this._continuation.awaitingConnections.set(connection.id, connection);
548
+ else connection.send(JSON.stringify({ type: MSG_STREAM_RESUME_NONE }));
549
+ }
550
+ _handleStreamResumeAck(connection, requestId) {
551
+ this._pendingResumeConnections.delete(connection.id);
552
+ if (this._resumableStream.hasActiveStream() && this._resumableStream.activeRequestId === requestId) {
553
+ const orphanedStreamId = this._resumableStream.replayChunks(connection, this._resumableStream.activeRequestId);
554
+ if (orphanedStreamId) this._persistOrphanedStream(orphanedStreamId);
295
555
  }
296
- return false;
297
556
  }
298
- async _handleChatRequest(connection, data) {
299
- const init = data.init;
300
- if (!init?.body) return;
301
- let parsed;
557
+ async _handleChatRequest(connection, event) {
558
+ if (!event.init?.body) return;
559
+ let rawParsed;
302
560
  try {
303
- parsed = JSON.parse(init.body);
561
+ rawParsed = JSON.parse(event.init.body);
304
562
  } catch {
305
563
  return;
306
564
  }
307
- const incomingMessages = parsed.messages;
565
+ const { messages: incomingMessages, clientTools: rawClientTools, trigger: rawTrigger, ...customBody } = rawParsed;
308
566
  if (!Array.isArray(incomingMessages)) return;
309
- const requestClientTools = parsed.clientTools?.length ? parsed.clientTools : void 0;
567
+ const isRegeneration = rawTrigger === "regenerate-message";
568
+ const isSubmitMessage = !isRegeneration;
569
+ const requestId = event.id;
570
+ const concurrencyDecision = this._getSubmitConcurrencyDecision(isSubmitMessage);
571
+ if (concurrencyDecision.action === "drop") {
572
+ this._rollbackDroppedSubmit(connection);
573
+ this._completeSkippedRequest(connection, requestId);
574
+ return;
575
+ }
576
+ const requestClientTools = rawClientTools && rawClientTools.length > 0 ? rawClientTools : void 0;
310
577
  if (requestClientTools) {
311
578
  this._lastClientTools = requestClientTools;
312
579
  this._persistClientTools();
313
- } else if (parsed.clientTools !== void 0) {
580
+ } else if (rawClientTools !== void 0) {
314
581
  this._lastClientTools = void 0;
315
582
  this._persistClientTools();
316
583
  }
584
+ this._lastBody = Object.keys(customBody).length > 0 ? customBody : void 0;
585
+ this._persistBody();
317
586
  const clientToolsForTurn = this._lastClientTools;
318
- for (const msg of incomingMessages) this._appendMessage(msg);
319
- this.messages = this._loadMessages();
587
+ const bodyForTurn = this._lastBody;
588
+ let branchParentId;
589
+ if (isRegeneration && incomingMessages.length > 0) branchParentId = incomingMessages[incomingMessages.length - 1].id;
590
+ for (const msg of incomingMessages) await this.session.appendMessage(msg);
320
591
  this._broadcastMessages([connection.id]);
321
- const requestId = data.id;
322
- const abortController = new AbortController();
323
- this._abortControllers.set(requestId, abortController);
592
+ const abortSignal = this._aborts.getSignal(requestId);
593
+ const epoch = this._turnQueue.generation;
324
594
  try {
325
595
  await this.keepAliveWhile(async () => {
326
596
  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 });
597
+ if (this._isSupersededSubmit(concurrencyDecision.submitSequence)) {
598
+ this._completeSkippedRequest(connection, requestId);
599
+ return;
330
600
  }
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
601
+ if (concurrencyDecision.debounceUntilMs !== null) {
602
+ await this._waitForTimestamp(concurrencyDecision.debounceUntilMs);
603
+ if (this._turnQueue.generation !== epoch) {
604
+ this._completeSkippedRequest(connection, requestId);
605
+ return;
606
+ }
607
+ if (this._isSupersededSubmit(concurrencyDecision.submitSequence)) {
608
+ this._completeSkippedRequest(connection, requestId);
609
+ return;
610
+ }
611
+ }
612
+ const chatTurnBody = async () => {
613
+ if (this.waitForMcpConnections) {
614
+ const timeout = typeof this.waitForMcpConnections === "object" ? this.waitForMcpConnections.timeout : 1e4;
615
+ await this.mcp.waitForConnections({ timeout });
616
+ }
617
+ const result = await __DO_NOT_USE_WILL_BREAK__agentContext.run({
618
+ agent: this,
619
+ connection,
620
+ request: void 0,
621
+ email: void 0
622
+ }, () => this.onChatMessage({
623
+ signal: abortSignal,
624
+ clientTools: clientToolsForTurn,
625
+ body: bodyForTurn,
626
+ continuation: false
627
+ }));
628
+ if (result) await this._streamResult(requestId, result, abortSignal, { parentId: branchParentId });
629
+ else this._broadcastChat({
630
+ type: MSG_CHAT_RESPONSE,
631
+ id: requestId,
632
+ body: "No response was generated.",
633
+ done: true
634
+ });
635
+ };
636
+ if (this.unstable_chatRecovery) await this.runFiber(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => {
637
+ await chatTurnBody();
347
638
  });
639
+ else await chatTurnBody();
348
640
  })).status === "stale") this._broadcastChat({
349
641
  type: MSG_CHAT_RESPONSE,
350
642
  id: requestId,
@@ -361,44 +653,59 @@ var Think = class extends ThinkBase {
361
653
  error: true
362
654
  });
363
655
  } finally {
364
- this._abortControllers.delete(requestId);
656
+ this._aborts.remove(requestId);
365
657
  }
366
658
  }
367
- _handleClear() {
659
+ /**
660
+ * Abort the active turn, invalidate queued turns, and reset
661
+ * concurrency/continuation state. Call this when intercepting
662
+ * clear events or implementing custom reset logic.
663
+ *
664
+ * Does NOT clear messages, streams, or persisted state —
665
+ * only turn execution state.
666
+ */
667
+ resetTurnState() {
368
668
  this._turnQueue.reset();
369
- for (const controller of this._abortControllers.values()) controller.abort();
370
- this._abortControllers.clear();
371
- this._resumableStream.clearAll();
372
- this._pendingResumeConnections.clear();
373
- this._lastClientTools = void 0;
374
- this._persistClientTools();
669
+ this._aborts.destroyAll();
375
670
  if (this._continuationTimer) {
376
671
  clearTimeout(this._continuationTimer);
377
672
  this._continuationTimer = null;
378
673
  }
674
+ this._cancelActiveDebounce();
675
+ this._pendingInteractionPromise = null;
379
676
  this._continuation.sendResumeNone();
380
677
  this._continuation.clearAll();
381
- this._clearMessages();
382
- this.messages = [];
383
- this._persistedMessageCache.clear();
384
- this._broadcast({ type: MSG_CHAT_CLEAR });
385
678
  }
386
- _handleCancel(requestId) {
387
- const controller = this._abortControllers.get(requestId);
388
- if (controller) controller.abort();
679
+ _handleClear(connection) {
680
+ this.resetTurnState();
681
+ this._resumableStream.clearAll();
682
+ this._pendingResumeConnections.clear();
683
+ this._lastClientTools = void 0;
684
+ this._persistClientTools();
685
+ this._lastBody = void 0;
686
+ this._persistBody();
687
+ this.session.clearMessages();
688
+ this._broadcast({ type: MSG_CHAT_CLEAR }, connection ? [connection.id] : void 0);
389
689
  }
390
- async _streamResult(requestId, result, abortSignal) {
690
+ async _streamResult(requestId, result, abortSignal, options) {
391
691
  const clearGen = this._turnQueue.generation;
392
692
  const streamId = this._resumableStream.start(requestId);
693
+ const continuation = options?.continuation ?? false;
694
+ const parentId = options?.parentId;
393
695
  if (this._continuation.pending?.requestId === requestId) {
394
696
  this._continuation.activatePending();
395
697
  this._continuation.flushAwaitingConnections((c) => this._notifyStreamResuming(c));
396
698
  }
397
699
  const accumulator = new StreamAccumulator({ messageId: crypto.randomUUID() });
398
700
  let doneSent = false;
701
+ let streamAborted = false;
702
+ let streamError;
399
703
  try {
400
704
  for await (const chunk of result.toUIMessageStream()) {
401
- if (abortSignal?.aborted) break;
705
+ if (abortSignal?.aborted) {
706
+ streamAborted = true;
707
+ break;
708
+ }
402
709
  const { action } = accumulator.applyChunk(chunk);
403
710
  if (action?.type === "error") {
404
711
  this._broadcastChat({
@@ -429,13 +736,14 @@ var Think = class extends ThinkBase {
429
736
  });
430
737
  doneSent = true;
431
738
  } catch (error) {
739
+ streamError = error instanceof Error ? error.message : "Stream error";
432
740
  this._resumableStream.markError(streamId);
433
741
  this._pendingResumeConnections.clear();
434
742
  if (!doneSent) {
435
743
  this._broadcastChat({
436
744
  type: MSG_CHAT_RESPONSE,
437
745
  id: requestId,
438
- body: error instanceof Error ? error.message : "Stream error",
746
+ body: streamError,
439
747
  done: true,
440
748
  error: true
441
749
  });
@@ -454,142 +762,68 @@ var Think = class extends ThinkBase {
454
762
  }
455
763
  }
456
764
  if (accumulator.parts.length > 0 && this._turnQueue.generation === clearGen) try {
457
- this._persistAssistantMessage(accumulator.toMessage());
765
+ const assistantMsg = accumulator.toMessage();
766
+ this._persistAssistantMessage(assistantMsg, parentId);
458
767
  this._broadcastMessages();
768
+ await this._fireResponseHook({
769
+ message: assistantMsg,
770
+ requestId,
771
+ continuation,
772
+ status: streamAborted ? "aborted" : streamError ? "error" : "completed",
773
+ error: streamError
774
+ });
459
775
  } catch (e) {
460
776
  console.error("Failed to persist assistant message:", e);
461
777
  }
462
778
  }
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}`;
779
+ _persistAssistantMessage(msg, parentId) {
780
+ const sized = enforceRowSizeLimit(sanitizeMessage(msg));
781
+ const safe = this.sanitizeMessageForPersistence(sized);
782
+ if (this.session.getMessage(safe.id)) this.session.updateMessage(safe);
783
+ else this.session.appendMessage(safe, parentId);
508
784
  }
509
785
  _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'`;
786
+ if (this._lastClientTools) this._configSet("lastClientTools", JSON.stringify(this._lastClientTools));
787
+ else this._configDelete("lastClientTools");
515
788
  }
516
789
  _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);
790
+ const raw = this._configGet("lastClientTools");
791
+ if (raw) try {
792
+ this._lastClientTools = JSON.parse(raw);
522
793
  } catch {
523
794
  this._lastClientTools = void 0;
524
795
  }
525
796
  }
526
- _persistAssistantMessage(msg) {
527
- const safe = enforceRowSizeLimit(sanitizeMessage(msg));
528
- const json = JSON.stringify(safe);
529
- if (this._persistedMessageCache.get(safe.id) !== json) this._upsertMessage(safe);
530
- if (this.maxPersistedMessages != null) this._enforceMaxPersistedMessages();
531
- this.messages = this._loadMessages();
532
- }
533
- _rebuildPersistenceCache() {
534
- this._persistedMessageCache.clear();
535
- for (const msg of this.messages) this._persistedMessageCache.set(msg.id, JSON.stringify(msg));
536
- }
537
- _enforceMaxPersistedMessages() {
538
- if (this.maxPersistedMessages == null) return;
539
- const history = this._loadMessages();
540
- if (history.length <= this.maxPersistedMessages) return;
541
- const excess = history.length - this.maxPersistedMessages;
542
- const toRemove = history.slice(0, excess);
543
- this._deleteMessages(toRemove.map((m) => m.id));
544
- for (const msg of toRemove) this._persistedMessageCache.delete(msg.id);
797
+ _persistBody() {
798
+ if (this._lastBody) this._configSet("lastBody", JSON.stringify(this._lastBody));
799
+ else this._configDelete("lastBody");
545
800
  }
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
- }
801
+ _restoreBody() {
802
+ const raw = this._configGet("lastBody");
803
+ if (raw) try {
804
+ this._lastBody = JSON.parse(raw);
805
+ } catch {
806
+ this._lastBody = void 0;
575
807
  }
576
808
  }
809
+ _applyToolResult(toolCallId, output, overrideState, errorText) {
810
+ const update = toolResultUpdate(toolCallId, output, overrideState, errorText);
811
+ this._applyToolUpdateToMessages(update);
812
+ }
577
813
  _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();
814
+ const update = toolApprovalUpdate(toolCallId, approved);
815
+ this._applyToolUpdateToMessages(update);
816
+ }
817
+ _applyToolUpdateToMessages(update) {
818
+ const history = this.messages;
819
+ for (const msg of history) {
820
+ const result = applyToolUpdate(msg.parts, update);
821
+ if (result) {
822
+ const safe = enforceRowSizeLimit(sanitizeMessage({
823
+ ...msg,
824
+ parts: result.parts
825
+ }));
826
+ this.session.updateMessage(safe);
593
827
  this._broadcast({
594
828
  type: MSG_MESSAGE_UPDATED,
595
829
  message: safe
@@ -598,6 +832,179 @@ var Think = class extends ThinkBase {
598
832
  }
599
833
  }
600
834
  }
835
+ hasPendingInteraction() {
836
+ return this.messages.some((message) => message.role === "assistant" && this._messageHasPendingInteraction(message));
837
+ }
838
+ async waitUntilStable(options) {
839
+ const deadline = options?.timeout != null ? Date.now() + options.timeout : null;
840
+ while (true) {
841
+ if (await this._awaitWithDeadline(this._turnQueue.waitForIdle(), deadline) === TIMED_OUT) return false;
842
+ if (!this.hasPendingInteraction()) return true;
843
+ const pending = this._pendingInteractionPromise;
844
+ if (pending) {
845
+ let result;
846
+ try {
847
+ result = await this._awaitWithDeadline(pending, deadline);
848
+ } catch {
849
+ continue;
850
+ }
851
+ if (result === TIMED_OUT) return false;
852
+ } else if (await this._awaitWithDeadline(new Promise((resolve) => setTimeout(resolve, 100)), deadline) === TIMED_OUT) return false;
853
+ }
854
+ }
855
+ async _awaitWithDeadline(promise, deadline) {
856
+ if (deadline == null) return promise;
857
+ const remainingMs = Math.max(0, deadline - Date.now());
858
+ let timer;
859
+ const result = await Promise.race([promise, new Promise((resolve) => {
860
+ timer = setTimeout(() => resolve(TIMED_OUT), remainingMs);
861
+ })]);
862
+ clearTimeout(timer);
863
+ return result;
864
+ }
865
+ _messageHasPendingInteraction(message) {
866
+ return message.parts.some((part) => "state" in part && (part.state === "input-available" || part.state === "approval-requested"));
867
+ }
868
+ async _handleInternalFiberRecovery(ctx) {
869
+ const chatPrefix = this.constructor.CHAT_FIBER_NAME + ":";
870
+ if (!ctx.name.startsWith(chatPrefix)) return false;
871
+ const requestId = ctx.name.slice(chatPrefix.length);
872
+ let streamId = "";
873
+ if (requestId) {
874
+ const rows = this.sql`
875
+ SELECT id FROM cf_ai_chat_stream_metadata
876
+ WHERE request_id = ${requestId}
877
+ ORDER BY created_at DESC LIMIT 1
878
+ `;
879
+ if (rows.length > 0) streamId = rows[0].id;
880
+ }
881
+ if (!streamId && this._resumableStream.hasActiveStream()) streamId = this._resumableStream.activeStreamId ?? "";
882
+ const partial = streamId ? this._getPartialStreamText(streamId) : {
883
+ text: "",
884
+ parts: []
885
+ };
886
+ const options = await this.onChatRecovery({
887
+ streamId: streamId ?? "",
888
+ requestId,
889
+ partialText: partial.text,
890
+ partialParts: partial.parts,
891
+ recoveryData: ctx.snapshot,
892
+ messages: [...this.messages],
893
+ lastBody: this._lastBody,
894
+ lastClientTools: this._lastClientTools
895
+ });
896
+ const streamStillActive = streamId && this._resumableStream.hasActiveStream() && this._resumableStream.activeStreamId === streamId;
897
+ if (options.persist !== false && streamStillActive) this._persistOrphanedStream(streamId);
898
+ if (streamStillActive) this._resumableStream.complete(streamId);
899
+ if (options.continue !== false) {
900
+ const lastLeaf = this.session.getLatestLeaf();
901
+ const targetId = lastLeaf?.role === "assistant" ? lastLeaf.id : void 0;
902
+ await this.schedule(0, "_chatRecoveryContinue", targetId ? { targetAssistantId: targetId } : void 0, { idempotent: true });
903
+ }
904
+ return true;
905
+ }
906
+ async onChatRecovery(_ctx) {
907
+ return {};
908
+ }
909
+ async _chatRecoveryContinue(data) {
910
+ if (!await this.waitUntilStable({ timeout: 1e4 })) {
911
+ console.warn("[Think] _chatRecoveryContinue timed out waiting for stable state, skipping continuation");
912
+ return;
913
+ }
914
+ const targetId = data?.targetAssistantId;
915
+ const lastLeaf = this.session.getLatestLeaf();
916
+ if (targetId && lastLeaf?.id !== targetId) return;
917
+ await this.continueLastTurn();
918
+ }
919
+ _getPartialStreamText(streamId) {
920
+ const chunks = this._resumableStream.getStreamChunks(streamId);
921
+ const parts = [];
922
+ for (const chunk of chunks) try {
923
+ applyChunkToParts(parts, JSON.parse(chunk.body));
924
+ } catch {}
925
+ return {
926
+ text: parts.filter((p) => p.type === "text" && "text" in p).map((p) => p.text).join(""),
927
+ parts
928
+ };
929
+ }
930
+ _normalizeMessageConcurrency() {
931
+ if (typeof this.messageConcurrency === "string") return this.messageConcurrency;
932
+ const debounceMs = this.messageConcurrency.debounceMs;
933
+ return {
934
+ strategy: "debounce",
935
+ debounceMs: typeof debounceMs === "number" && Number.isFinite(debounceMs) && debounceMs >= 0 ? debounceMs : Think.MESSAGE_DEBOUNCE_MS
936
+ };
937
+ }
938
+ _getSubmitConcurrencyDecision(isSubmitMessage) {
939
+ const queuedTurns = this._turnQueue.queuedCount();
940
+ if (!isSubmitMessage || queuedTurns === 0) return {
941
+ action: "execute",
942
+ submitSequence: null,
943
+ debounceUntilMs: null
944
+ };
945
+ const concurrency = this._normalizeMessageConcurrency();
946
+ if (concurrency === "queue") return {
947
+ action: "execute",
948
+ submitSequence: null,
949
+ debounceUntilMs: null
950
+ };
951
+ if (concurrency === "drop") return {
952
+ action: "drop",
953
+ submitSequence: null,
954
+ debounceUntilMs: null
955
+ };
956
+ const submitSequence = ++this._submitSequence;
957
+ this._latestOverlappingSubmitSequence = submitSequence;
958
+ if (concurrency === "latest" || concurrency === "merge") return {
959
+ action: "execute",
960
+ submitSequence,
961
+ debounceUntilMs: null
962
+ };
963
+ return {
964
+ action: "execute",
965
+ submitSequence,
966
+ debounceUntilMs: Date.now() + concurrency.debounceMs
967
+ };
968
+ }
969
+ _isSupersededSubmit(submitSequence) {
970
+ return submitSequence !== null && submitSequence < this._latestOverlappingSubmitSequence;
971
+ }
972
+ async _waitForTimestamp(timestampMs) {
973
+ const remainingMs = timestampMs - Date.now();
974
+ if (remainingMs <= 0) return;
975
+ await new Promise((resolve) => {
976
+ this._activeDebounceResolve = resolve;
977
+ this._activeDebounceTimer = setTimeout(() => {
978
+ this._activeDebounceTimer = null;
979
+ this._activeDebounceResolve = null;
980
+ resolve();
981
+ }, remainingMs);
982
+ });
983
+ }
984
+ _cancelActiveDebounce() {
985
+ if (this._activeDebounceTimer !== null) {
986
+ clearTimeout(this._activeDebounceTimer);
987
+ this._activeDebounceTimer = null;
988
+ }
989
+ if (this._activeDebounceResolve !== null) {
990
+ this._activeDebounceResolve();
991
+ this._activeDebounceResolve = null;
992
+ }
993
+ }
994
+ _completeSkippedRequest(connection, requestId) {
995
+ connection.send(JSON.stringify({
996
+ type: MSG_CHAT_RESPONSE,
997
+ id: requestId,
998
+ body: "",
999
+ done: true
1000
+ }));
1001
+ }
1002
+ _rollbackDroppedSubmit(connection) {
1003
+ connection.send(JSON.stringify({
1004
+ type: MSG_CHAT_MESSAGES,
1005
+ messages: this.messages
1006
+ }));
1007
+ }
601
1008
  _scheduleAutoContinuation(connection) {
602
1009
  if (this._continuation.pending?.pastCoalesce) {
603
1010
  this._continuation.deferred = {
@@ -639,29 +1046,35 @@ var Think = class extends ThinkBase {
639
1046
  this._continuation.awaitingConnections.set(connection.id, connection);
640
1047
  }
641
1048
  const { requestId, clientTools } = this._continuation.pending;
642
- const abortController = new AbortController();
643
- this._abortControllers.set(requestId, abortController);
1049
+ const abortSignal = this._aborts.getSignal(requestId);
644
1050
  this.keepAliveWhile(async () => {
645
1051
  await this._turnQueue.enqueue(requestId, async () => {
646
1052
  if (this._continuation.pending) this._continuation.pending.pastCoalesce = true;
647
1053
  let streamed = false;
648
1054
  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
- }
1055
+ const continuationBody = async () => {
1056
+ const result = await __DO_NOT_USE_WILL_BREAK__agentContext.run({
1057
+ agent: this,
1058
+ connection,
1059
+ request: void 0,
1060
+ email: void 0
1061
+ }, () => this.onChatMessage({
1062
+ signal: abortSignal,
1063
+ clientTools,
1064
+ body: this._lastBody,
1065
+ continuation: true
1066
+ }));
1067
+ if (result) {
1068
+ await this._streamResult(requestId, result, abortSignal, { continuation: true });
1069
+ streamed = true;
1070
+ }
1071
+ };
1072
+ if (this.unstable_chatRecovery) await this.runFiber(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => {
1073
+ await continuationBody();
1074
+ });
1075
+ else await continuationBody();
663
1076
  } finally {
664
- this._abortControllers.delete(requestId);
1077
+ this._aborts.remove(requestId);
665
1078
  if (!streamed) this._continuation.sendResumeNone();
666
1079
  this._continuation.clearPending();
667
1080
  this._activateDeferredContinuation();
@@ -669,7 +1082,7 @@ var Think = class extends ThinkBase {
669
1082
  });
670
1083
  }).catch((error) => {
671
1084
  console.error("[Think] Auto-continuation failed:", error);
672
- this._abortControllers.delete(requestId);
1085
+ this._aborts.remove(requestId);
673
1086
  });
674
1087
  }
675
1088
  _activateDeferredContinuation() {
@@ -677,6 +1090,17 @@ var Think = class extends ThinkBase {
677
1090
  if (!pending) return;
678
1091
  this._fireAutoContinuation(pending.connection);
679
1092
  }
1093
+ async _fireResponseHook(result) {
1094
+ if (this._insideResponseHook) return;
1095
+ this._insideResponseHook = true;
1096
+ try {
1097
+ await this.onChatResponse(result);
1098
+ } catch (err) {
1099
+ console.error("[Think] onChatResponse error:", err);
1100
+ } finally {
1101
+ this._insideResponseHook = false;
1102
+ }
1103
+ }
680
1104
  _notifyStreamResuming(connection) {
681
1105
  if (!this._resumableStream.hasActiveStream()) return;
682
1106
  this._pendingResumeConnections.add(connection.id);
@@ -712,7 +1136,9 @@ var Think = class extends ThinkBase {
712
1136
  }, exclude);
713
1137
  }
714
1138
  };
1139
+ Think.CHAT_FIBER_NAME = "__cf_internal_chat_turn";
1140
+ Think.MESSAGE_DEBOUNCE_MS = 750;
715
1141
  //#endregion
716
- export { Think };
1142
+ export { Session, Think };
717
1143
 
718
1144
  //# sourceMappingURL=think.js.map