@cloudflare/think 0.1.2 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/think.js CHANGED
@@ -1,65 +1,77 @@
1
- import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldGet2, t as _classPrivateFieldSet2 } from "./classPrivateFieldSet2-D-GfNNJe.js";
1
+ import { createWorkspaceTools } from "./tools/workspace.js";
2
+ import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldSet2, t as _classPrivateFieldGet2 } from "./classPrivateFieldGet2-DZKvdPZj.js";
2
3
  import { convertToModelMessages, pruneMessages, stepCountIs, streamText } from "ai";
3
4
  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";
5
+ import { AbortRegistry, CHAT_MESSAGE_TYPES, ContinuationState, ResumableStream, StreamAccumulator, TurnQueue, applyChunkToParts, applyToolUpdate, createToolsFromClientSchemas, enforceRowSizeLimit, parseProtocolMessage, sanitizeMessage, toolApprovalUpdate, toolResultUpdate } from "agents/chat";
6
+ import { Session, Session as Session$1 } from "agents/experimental/memory/session";
7
+ import { truncateOlderMessages } from "agents/experimental/memory/utils";
8
+ import { Workspace, Workspace as Workspace$1 } from "@cloudflare/shell";
6
9
  //#region src/think.ts
7
- const ThinkBase = withFibers(Agent);
8
10
  const MSG_CHAT_MESSAGES = CHAT_MESSAGE_TYPES.CHAT_MESSAGES;
9
- const MSG_CHAT_REQUEST = CHAT_MESSAGE_TYPES.USE_CHAT_REQUEST;
10
11
  const MSG_CHAT_RESPONSE = CHAT_MESSAGE_TYPES.USE_CHAT_RESPONSE;
11
12
  const MSG_CHAT_CLEAR = CHAT_MESSAGE_TYPES.CHAT_CLEAR;
12
- const MSG_CHAT_CANCEL = CHAT_MESSAGE_TYPES.CHAT_REQUEST_CANCEL;
13
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
14
  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
15
  const MSG_MESSAGE_UPDATED = CHAT_MESSAGE_TYPES.MESSAGE_UPDATED;
20
- var _configTableReady = /* @__PURE__ */ new WeakMap();
16
+ const TIMED_OUT = Symbol("timed-out");
21
17
  var _configCache = /* @__PURE__ */ new WeakMap();
22
18
  /**
23
19
  * An opinionated chat agent base class.
24
20
  *
25
21
  * @experimental Requires the `"experimental"` compatibility flag.
26
22
  */
27
- var Think = class extends ThinkBase {
28
- constructor(..._args) {
29
- super(..._args);
30
- this.messages = [];
31
- this.fibers = false;
23
+ var Think = class Think extends Agent {
24
+ constructor(ctx, env) {
25
+ super(ctx, env);
32
26
  this.waitForMcpConnections = false;
33
- this.maxPersistedMessages = void 0;
34
- this._persistedMessageCache = /* @__PURE__ */ new Map();
35
- this._storageReady = false;
36
- this._abortControllers = /* @__PURE__ */ new Map();
27
+ this.messageConcurrency = "queue";
28
+ this.unstable_chatRecovery = false;
29
+ this._aborts = new AbortRegistry();
37
30
  this._turnQueue = new TurnQueue();
38
31
  this._pendingResumeConnections = /* @__PURE__ */ new Set();
39
32
  this._continuation = new ContinuationState();
40
33
  this._continuationTimer = null;
41
- _classPrivateFieldInitSpec(this, _configTableReady, false);
34
+ this._insideResponseHook = false;
35
+ this._insideInferenceLoop = false;
36
+ this._pendingInteractionPromise = null;
37
+ this._submitSequence = 0;
38
+ this._latestOverlappingSubmitSequence = 0;
39
+ this._activeDebounceTimer = null;
40
+ this._activeDebounceResolve = null;
42
41
  _classPrivateFieldInitSpec(this, _configCache, null);
42
+ this.maxSteps = 10;
43
+ this.hookTimeout = 5e3;
44
+ const _onStart = this.onStart.bind(this);
45
+ this.onStart = async () => {
46
+ if (!this.workspace) this.workspace = new Workspace$1({
47
+ sql: this.ctx.storage.sql,
48
+ name: () => this.name
49
+ });
50
+ const baseSession = Session$1.create(this);
51
+ this.session = await this.configureSession(baseSession);
52
+ this.session.getHistory();
53
+ if (this.extensionLoader) await this._initializeExtensions();
54
+ this._resumableStream = new ResumableStream(this.sql.bind(this));
55
+ this._restoreClientTools();
56
+ this._restoreBody();
57
+ this._setupProtocolHandlers();
58
+ await _onStart();
59
+ };
43
60
  }
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);
61
+ /**
62
+ * Conversation history. Computed from the active session.
63
+ * Always fresh — reads from Session's tree-structured storage.
64
+ */
65
+ get messages() {
66
+ return this.session.getHistory();
52
67
  }
53
68
  /**
54
69
  * Persist a typed configuration object.
55
- * Stored in SQLite so it survives restarts and hibernation.
70
+ * Stored in Session's assistant_config table — survives restarts and hibernation.
56
71
  */
57
72
  configure(config) {
58
- this._ensureConfigTable();
59
73
  const json = JSON.stringify(config);
60
- this.sql`
61
- INSERT OR REPLACE INTO _think_config (key, value) VALUES ('config', ${json})
62
- `;
74
+ this._configSet("_think_config", json);
63
75
  _classPrivateFieldSet2(_configCache, this, config);
64
76
  }
65
77
  /**
@@ -67,34 +79,48 @@ var Think = class extends ThinkBase {
67
79
  */
68
80
  getConfig() {
69
81
  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));
82
+ const raw = this._configGet("_think_config");
83
+ if (raw !== void 0) {
84
+ _classPrivateFieldSet2(_configCache, this, JSON.parse(raw));
76
85
  return _classPrivateFieldGet2(_configCache, this);
77
86
  }
78
87
  return null;
79
88
  }
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();
89
+ _configSet(key, value) {
90
+ const sessionId = this._sessionId();
91
+ this.sql`
92
+ INSERT OR REPLACE INTO assistant_config (session_id, key, value)
93
+ VALUES (${sessionId}, ${key}, ${value})
94
+ `;
95
+ }
96
+ _configGet(key) {
97
+ const sessionId = this._sessionId();
98
+ return this.sql`
99
+ SELECT value FROM assistant_config
100
+ WHERE session_id = ${sessionId} AND key = ${key}
101
+ `[0]?.value;
102
+ }
103
+ _configDelete(key) {
104
+ const sessionId = this._sessionId();
105
+ this.sql`
106
+ DELETE FROM assistant_config
107
+ WHERE session_id = ${sessionId} AND key = ${key}
108
+ `;
109
+ }
110
+ _sessionId() {
111
+ return "";
88
112
  }
89
113
  /**
90
114
  * Return the language model to use for inference.
91
- * Must be overridden by subclasses that rely on the default
92
- * `onChatMessage` implementation (the agentic loop).
115
+ * Must be overridden by subclasses.
93
116
  */
94
117
  getModel() {
95
- throw new Error("Override getModel() to return a LanguageModel, or override onChatMessage() for full control.");
118
+ throw new Error("Override getModel() to return a LanguageModel.");
96
119
  }
97
- /** Return the system prompt for the assistant. */
120
+ /**
121
+ * Return the system prompt for the assistant.
122
+ * Used as fallback when no context blocks are configured via `configureSession`.
123
+ */
98
124
  getSystemPrompt() {
99
125
  return "You are a helpful assistant.";
100
126
  }
@@ -102,58 +128,346 @@ var Think = class extends ThinkBase {
102
128
  getTools() {
103
129
  return {};
104
130
  }
105
- /** Return the maximum number of tool-call steps per turn. */
106
- getMaxSteps() {
107
- return 10;
131
+ /**
132
+ * Configure the session. Called once during `onStart`.
133
+ * Override to add context blocks, compaction, search, skills.
134
+ *
135
+ * @example
136
+ * ```typescript
137
+ * configureSession(session: Session) {
138
+ * return session
139
+ * .withContext("memory", { description: "Learned facts", maxTokens: 2000 })
140
+ * .withCachedPrompt();
141
+ * }
142
+ * ```
143
+ */
144
+ configureSession(session) {
145
+ return session;
108
146
  }
109
147
  /**
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).
148
+ * Return sandboxed extension configurations. Defines load order,
149
+ * which determines hook execution order.
150
+ * Requires `extensionLoader` to be set.
113
151
  */
114
- async assembleContext() {
115
- return pruneMessages({
116
- messages: await convertToModelMessages(this.messages),
117
- toolCalls: "before-last-2-messages"
118
- });
152
+ getExtensions() {
153
+ return [];
119
154
  }
120
155
  /**
121
- * Handle a chat turn and return the streaming result.
156
+ * Called before `streamText` — inspect the assembled context and
157
+ * return overrides. Think assembles tools, system prompt, and messages
158
+ * internally; this hook sees the result and can override any part.
159
+ *
160
+ * Return `void` to accept all defaults.
161
+ *
162
+ * @example Switch model for continuations
163
+ * ```typescript
164
+ * beforeTurn(ctx: TurnContext) {
165
+ * if (ctx.continuation) return { model: this.cheapModel };
166
+ * }
167
+ * ```
168
+ *
169
+ * @example Restrict active tools
170
+ * ```typescript
171
+ * beforeTurn(ctx: TurnContext) {
172
+ * return { activeTools: ["read", "write"] };
173
+ * }
174
+ * ```
175
+ */
176
+ beforeTurn(_ctx) {}
177
+ /**
178
+ * Called when the model produces a tool call. Currently fires
179
+ * **after** tool execution (via `onStepFinish` data) — observation only.
180
+ *
181
+ * **Known limitation:** `block` and `substitute` actions in the returned
182
+ * `ToolCallDecision` are not yet functional. The AI SDK's `streamText`
183
+ * does not expose a pre-execution interception point for tool calls
184
+ * in the Workers runtime. The types are in place for when this becomes
185
+ * possible (see plan: "Known limitations — Phase 1").
186
+ *
187
+ * Only fires for server-side tools (tools with `execute`).
188
+ * Client tools are handled on the client — Think can't intercept them.
189
+ *
190
+ * Return `void` to accept default behavior.
191
+ *
192
+ * @example Log tool calls
193
+ * ```typescript
194
+ * beforeToolCall(ctx: ToolCallContext) {
195
+ * console.log(`Tool called: ${ctx.toolName}`, ctx.args);
196
+ * }
197
+ * ```
198
+ */
199
+ beforeToolCall(_ctx) {}
200
+ /**
201
+ * Called after a tool executes (or a substitute result is provided).
202
+ * Does NOT fire when `beforeToolCall` blocks with no substitute result.
122
203
  *
123
- * 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
204
+ * Override for logging, metrics, or result inspection.
205
+ */
206
+ afterToolCall(_ctx) {}
207
+ /**
208
+ * Called after each step completes (initial, continue, tool-result).
209
+ * Override for step-level logging or analytics.
210
+ */
211
+ onStepFinish(_ctx) {}
212
+ /**
213
+ * Called for each streaming chunk. High-frequency — fires per token.
214
+ * Override for streaming analytics, progress indicators, or token counting.
215
+ * Observational only (void return).
216
+ */
217
+ onChunk(_ctx) {}
218
+ /**
219
+ * Called after a chat turn completes and the assistant message has been
220
+ * persisted. The turn lock is released before this hook runs, so it is
221
+ * safe to call other methods from inside.
126
222
  *
127
- * Override for full control over inference.
223
+ * Fires for all turn completion paths: WebSocket chat requests,
224
+ * sub-agent RPC, and auto-continuation.
128
225
  *
129
- * @returns A result with `toUIMessageStream()` — AI SDK's `streamText()`
130
- * return value satisfies this interface.
226
+ * Override for logging, chaining, analytics, usage tracking.
131
227
  */
132
- async onChatMessage(options) {
228
+ onChatResponse(_result) {}
229
+ /**
230
+ * Handle an error that occurred during a chat turn.
231
+ * Override to customize error handling (e.g. logging, metrics).
232
+ */
233
+ onChatError(error) {
234
+ return error;
235
+ }
236
+ async _initializeExtensions() {
237
+ const { ExtensionManager } = await import("./manager-dtoAI3A6.js").then((n) => n.n);
238
+ const { sanitizeName } = await import("./manager-dtoAI3A6.js").then((n) => n.n);
239
+ const agentClassName = this.constructor.name;
240
+ const agentId = this.ctx.id.toString();
241
+ const ctxExports = this.ctx.exports;
242
+ const hasBridge = ctxExports && typeof ctxExports.HostBridgeLoopback === "function";
243
+ this.extensionManager = new ExtensionManager({
244
+ loader: this.extensionLoader,
245
+ storage: this.ctx.storage,
246
+ ...hasBridge ? { createHostBinding: (permissions, ownContextLabels) => ctxExports.HostBridgeLoopback({ props: {
247
+ agentClassName,
248
+ agentId,
249
+ permissions,
250
+ ownContextLabels
251
+ } }) } : {}
252
+ });
253
+ const configs = this.getExtensions();
254
+ for (const config of configs) await this.extensionManager.load(config.manifest, config.source);
255
+ await this.extensionManager.restore();
256
+ for (const ext of this.extensionManager.list()) {
257
+ const manifest = this.extensionManager.getManifest(ext.name);
258
+ if (!manifest?.context) continue;
259
+ const prefix = sanitizeName(ext.name);
260
+ for (const ctxDef of manifest.context) {
261
+ const namespacedLabel = `${prefix}_${ctxDef.label}`;
262
+ await this.session.addContext(namespacedLabel, {
263
+ description: ctxDef.description,
264
+ maxTokens: ctxDef.maxTokens
265
+ });
266
+ }
267
+ }
268
+ this.extensionManager.onUnload(async (_name, contextLabels) => {
269
+ for (const label of contextLabels) this.session.removeContext(label);
270
+ await this.session.refreshSystemPrompt();
271
+ });
272
+ }
273
+ /**
274
+ * The single convergence point for all chat turn entry paths.
275
+ * Merges tools, assembles context, fires lifecycle hooks, wraps tools
276
+ * for interception, and calls streamText.
277
+ */
278
+ async _runInferenceLoop(input) {
279
+ if (this.waitForMcpConnections) {
280
+ const timeout = typeof this.waitForMcpConnections === "object" ? this.waitForMcpConnections.timeout : 1e4;
281
+ await this.mcp.waitForConnections({ timeout });
282
+ }
283
+ const workspaceTools = createWorkspaceTools(this.workspace);
133
284
  const baseTools = this.getTools();
134
- const clientToolSet = createToolsFromClientSchemas(options?.clientTools);
285
+ const extensionTools = this.extensionManager?.getTools() ?? {};
286
+ const contextTools = await this.session.tools();
287
+ const clientToolSet = createToolsFromClientSchemas(input.clientTools);
135
288
  const tools = {
289
+ ...workspaceTools,
136
290
  ...baseTools,
291
+ ...extensionTools,
292
+ ...contextTools,
293
+ ...this.mcp?.getAITools?.() ?? {},
137
294
  ...clientToolSet,
138
- ...options?.tools
295
+ ...input.callerTools
139
296
  };
140
- const messages = await this.assembleContext();
297
+ const system = await this.session.freezeSystemPrompt() || this.getSystemPrompt();
298
+ const messages = pruneMessages({
299
+ messages: await convertToModelMessages(truncateOlderMessages(this.session.getHistory())),
300
+ toolCalls: "before-last-2-messages"
301
+ });
141
302
  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
- return streamText({
143
- model: this.getModel(),
144
- system: this.getSystemPrompt(),
303
+ const model = this.getModel();
304
+ const ctx = {
305
+ system,
145
306
  messages,
146
307
  tools,
147
- stopWhen: stepCountIs(this.getMaxSteps()),
148
- abortSignal: options?.signal
308
+ model,
309
+ continuation: input.continuation,
310
+ body: input.body
311
+ };
312
+ const subclassConfig = await this.beforeTurn(ctx) ?? {};
313
+ const config = await this._pipelineExtensionBeforeTurn(ctx, subclassConfig);
314
+ const finalModel = config.model ?? model;
315
+ const finalSystem = config.system ?? system;
316
+ const finalMessages = config.messages ?? messages;
317
+ const finalTools = config.tools ? {
318
+ ...tools,
319
+ ...config.tools
320
+ } : tools;
321
+ const finalMaxSteps = config.maxSteps ?? this.maxSteps;
322
+ const result = streamText({
323
+ model: finalModel,
324
+ system: finalSystem,
325
+ messages: finalMessages,
326
+ tools: finalTools,
327
+ activeTools: config.activeTools,
328
+ toolChoice: config.toolChoice,
329
+ stopWhen: stepCountIs(finalMaxSteps),
330
+ providerOptions: config.providerOptions,
331
+ abortSignal: input.signal,
332
+ onChunk: async (event) => {
333
+ await this.onChunk({ chunk: event.chunk });
334
+ },
335
+ onStepFinish: async (event) => {
336
+ const toolCalls = event.toolCalls ?? [];
337
+ const toolResults = event.toolResults ?? [];
338
+ for (let i = 0; i < toolCalls.length; i++) {
339
+ const tc = toolCalls[i];
340
+ if (tc) await this.beforeToolCall({
341
+ toolName: tc.toolName ?? tc.name ?? "",
342
+ args: tc.args ?? {}
343
+ });
344
+ }
345
+ for (let i = 0; i < toolResults.length; i++) {
346
+ const tr = toolResults[i];
347
+ const tc = toolCalls[i];
348
+ if (tr) await this.afterToolCall({
349
+ toolName: tc?.toolName ?? tc?.name ?? tr?.toolName ?? "",
350
+ args: tc?.args ?? {},
351
+ result: tr.result
352
+ });
353
+ }
354
+ await this.onStepFinish({
355
+ stepType: event.stepType ?? "initial",
356
+ text: event.text ?? "",
357
+ toolCalls,
358
+ toolResults,
359
+ finishReason: event.finishReason ?? "stop",
360
+ usage: {
361
+ inputTokens: event.usage?.inputTokens ?? 0,
362
+ outputTokens: event.usage?.outputTokens ?? 0
363
+ }
364
+ });
365
+ }
149
366
  });
367
+ return this._transformInferenceResult(result);
368
+ }
369
+ /** @internal Test seam — override in test agents to wrap the stream (e.g. error injection). */
370
+ _transformInferenceResult(result) {
371
+ return result;
150
372
  }
151
373
  /**
152
- * Handle an error that occurred during a chat turn.
153
- * Override to customize error handling (e.g. logging, metrics).
374
+ * Pipeline beforeTurn through sandboxed extensions in load order.
375
+ * Each extension sees the accumulated state from prior extensions
376
+ * (snapshot is rebuilt after each extension's modifications).
377
+ * Results are merged with last-write-wins for scalar fields.
378
+ * Extensions that don't subscribe to beforeTurn are skipped.
154
379
  */
155
- onChatError(error) {
156
- return error;
380
+ async _pipelineExtensionBeforeTurn(ctx, subclassConfig) {
381
+ if (!this.extensionManager) return subclassConfig;
382
+ const subscribers = this.extensionManager.getHookSubscribers("beforeTurn");
383
+ if (subscribers.length === 0) return subclassConfig;
384
+ const { createTurnContextSnapshot, parseHookResult } = await import("./hook-proxy-f_DqtJ9u.js");
385
+ let snapshot = createTurnContextSnapshot(ctx);
386
+ let accumulated = { ...subclassConfig };
387
+ if (accumulated.system !== void 0) snapshot.system = accumulated.system;
388
+ if (accumulated.maxSteps !== void 0) snapshot.messageCount = ctx.messages.length;
389
+ for (const sub of subscribers) {
390
+ let timer;
391
+ try {
392
+ const parsed = parseHookResult(await Promise.race([sub.entrypoint.hook("beforeTurn", snapshot), new Promise((_, reject) => {
393
+ timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`Hook timeout: ${sub.name}`)), this.hookTimeout);
394
+ })]));
395
+ if ("config" in parsed) {
396
+ if (parsed.config.system !== void 0) accumulated.system = parsed.config.system;
397
+ if (parsed.config.messages !== void 0) accumulated.messages = parsed.config.messages;
398
+ if (parsed.config.activeTools !== void 0) accumulated.activeTools = parsed.config.activeTools;
399
+ if (parsed.config.toolChoice !== void 0) accumulated.toolChoice = parsed.config.toolChoice;
400
+ if (parsed.config.maxSteps !== void 0) accumulated.maxSteps = parsed.config.maxSteps;
401
+ if (parsed.config.providerOptions !== void 0) accumulated.providerOptions = {
402
+ ...accumulated.providerOptions ?? {},
403
+ ...parsed.config.providerOptions
404
+ };
405
+ if (accumulated.system !== void 0) snapshot = {
406
+ ...snapshot,
407
+ system: accumulated.system
408
+ };
409
+ if (accumulated.activeTools !== void 0) snapshot = {
410
+ ...snapshot,
411
+ toolNames: accumulated.activeTools
412
+ };
413
+ } else if ("error" in parsed) console.warn(`[Think] Extension "${sub.name}" beforeTurn error:`, parsed.error);
414
+ } catch (err) {
415
+ console.warn(`[Think] Extension "${sub.name}" beforeTurn failed:`, err instanceof Error ? err.message : err);
416
+ } finally {
417
+ if (timer !== void 0) clearTimeout(timer);
418
+ }
419
+ }
420
+ return accumulated;
421
+ }
422
+ async _hostReadFile(path) {
423
+ return await this.workspace.readFile(path) ?? null;
424
+ }
425
+ async _hostWriteFile(path, content) {
426
+ await this.workspace.writeFile(path, content);
427
+ }
428
+ async _hostDeleteFile(path) {
429
+ try {
430
+ await this.workspace.rm(path);
431
+ return true;
432
+ } catch {
433
+ return false;
434
+ }
435
+ }
436
+ async _hostListFiles(dir) {
437
+ return (await this.workspace.readDir(dir)).map((e) => ({
438
+ name: e.name,
439
+ type: e.type,
440
+ size: e.size ?? 0,
441
+ path: e.path ?? `${dir}/${e.name}`
442
+ }));
443
+ }
444
+ async _hostGetContext(label) {
445
+ return this.session.getContextBlock(label)?.content ?? null;
446
+ }
447
+ async _hostSetContext(label, content) {
448
+ await this.session.replaceContextBlock(label, content);
449
+ }
450
+ async _hostGetMessages(limit) {
451
+ const history = this.session.getHistory();
452
+ return (limit !== void 0 && limit !== null ? limit <= 0 ? [] : history.slice(-limit) : history).map((m) => ({
453
+ id: m.id,
454
+ role: m.role,
455
+ content: m.parts.filter((p) => p.type === "text").map((p) => p.text).join("")
456
+ }));
457
+ }
458
+ async _hostSendMessage(content) {
459
+ const msg = {
460
+ id: crypto.randomUUID(),
461
+ role: "user",
462
+ parts: [{
463
+ type: "text",
464
+ text: content
465
+ }]
466
+ };
467
+ await this.session.appendMessage(msg);
468
+ }
469
+ async _hostGetSessionInfo() {
470
+ return { messageCount: this.session.getHistory().length };
157
471
  }
158
472
  /**
159
473
  * Run a chat turn: persist the user message, run the agentic loop,
@@ -175,29 +489,61 @@ var Think = class extends ThinkBase {
175
489
  text: userMessage
176
490
  }]
177
491
  } : userMessage;
178
- this._appendMessage(userMsg);
179
- this.messages = this._loadMessages();
492
+ await this.session.appendMessage(userMsg);
180
493
  const accumulator = new StreamAccumulator({ messageId: crypto.randomUUID() });
181
494
  try {
182
- const result = await this.onChatMessage({
495
+ const result = await __DO_NOT_USE_WILL_BREAK__agentContext.run({
496
+ agent: this,
497
+ connection: void 0,
498
+ request: void 0,
499
+ email: void 0
500
+ }, () => this._runInferenceLoop({
183
501
  signal: options?.signal,
184
- tools: options?.tools
185
- });
502
+ callerTools: options?.tools,
503
+ continuation: false
504
+ }));
505
+ this._insideInferenceLoop = true;
186
506
  let aborted = false;
187
- for await (const chunk of result.toUIMessageStream()) {
188
- if (options?.signal?.aborted) {
189
- aborted = true;
190
- break;
507
+ try {
508
+ for await (const chunk of result.toUIMessageStream()) {
509
+ if (options?.signal?.aborted) {
510
+ aborted = true;
511
+ break;
512
+ }
513
+ accumulator.applyChunk(chunk);
514
+ await callback.onEvent(JSON.stringify(chunk));
191
515
  }
192
- accumulator.applyChunk(chunk);
193
- await callback.onEvent(JSON.stringify(chunk));
516
+ } finally {
517
+ this._insideInferenceLoop = false;
194
518
  }
195
- this._persistAssistantMessage(accumulator.toMessage());
196
- if (!aborted) await callback.onDone();
519
+ const assistantMsg = accumulator.toMessage();
520
+ this._persistAssistantMessage(assistantMsg);
521
+ if (!aborted) {
522
+ await callback.onDone();
523
+ await this._fireResponseHook({
524
+ message: assistantMsg,
525
+ requestId,
526
+ continuation: false,
527
+ status: "completed"
528
+ });
529
+ } else await this._fireResponseHook({
530
+ message: assistantMsg,
531
+ requestId,
532
+ continuation: false,
533
+ status: "aborted"
534
+ });
197
535
  } catch (error) {
198
- if (accumulator.parts.length > 0) this._persistAssistantMessage(accumulator.toMessage());
536
+ const assistantMsg = accumulator.parts.length > 0 ? accumulator.toMessage() : null;
537
+ if (assistantMsg) this._persistAssistantMessage(assistantMsg);
199
538
  const wrapped = this.onChatError(error);
200
539
  const errorMessage = wrapped instanceof Error ? wrapped.message : String(wrapped);
540
+ if (assistantMsg) await this._fireResponseHook({
541
+ message: assistantMsg,
542
+ requestId,
543
+ continuation: false,
544
+ status: "error",
545
+ error: errorMessage
546
+ });
201
547
  if (callback.onError) await callback.onError(errorMessage);
202
548
  else throw wrapped;
203
549
  }
@@ -207,11 +553,150 @@ var Think = class extends ThinkBase {
207
553
  getMessages() {
208
554
  return this.messages;
209
555
  }
210
- /** Clear all messages from storage and memory. */
556
+ /** Clear all messages from storage. */
211
557
  clearMessages() {
212
- this._clearMessages();
213
- this.messages = [];
214
- this._persistedMessageCache.clear();
558
+ this.session.clearMessages();
559
+ }
560
+ /**
561
+ * Inject messages and trigger a model turn — without a WebSocket request.
562
+ *
563
+ * Use for scheduled responses, webhook-triggered turns, proactive agents,
564
+ * or chaining from `onChatResponse`.
565
+ *
566
+ * Accepts static messages or a callback that derives messages from the
567
+ * current state (useful when multiple calls queue up — the callback runs
568
+ * with the latest messages when the turn actually starts).
569
+ *
570
+ * @example Scheduled follow-up
571
+ * ```typescript
572
+ * async onScheduled() {
573
+ * await this.saveMessages([{
574
+ * id: crypto.randomUUID(),
575
+ * role: "user",
576
+ * parts: [{ type: "text", text: "Time for your daily summary." }]
577
+ * }]);
578
+ * }
579
+ * ```
580
+ *
581
+ * @example Function form
582
+ * ```typescript
583
+ * await this.saveMessages((current) => [
584
+ * ...current,
585
+ * { id: crypto.randomUUID(), role: "user", parts: [{ type: "text", text: "Continue." }] }
586
+ * ]);
587
+ * ```
588
+ */
589
+ async saveMessages(messages) {
590
+ const requestId = crypto.randomUUID();
591
+ const clientTools = this._lastClientTools;
592
+ const body = this._lastBody;
593
+ const epoch = this._turnQueue.generation;
594
+ let status = "completed";
595
+ await this.keepAliveWhile(async () => {
596
+ await this._turnQueue.enqueue(requestId, async () => {
597
+ const resolved = typeof messages === "function" ? await messages(this.messages) : messages;
598
+ if (this._turnQueue.generation !== epoch) {
599
+ status = "skipped";
600
+ return;
601
+ }
602
+ for (const msg of resolved) await this.session.appendMessage(msg);
603
+ this._broadcastMessages();
604
+ if (this._turnQueue.generation !== epoch) {
605
+ status = "skipped";
606
+ return;
607
+ }
608
+ const abortSignal = this._aborts.getSignal(requestId);
609
+ try {
610
+ const programmaticBody = async () => {
611
+ const result = await __DO_NOT_USE_WILL_BREAK__agentContext.run({
612
+ agent: this,
613
+ connection: void 0,
614
+ request: void 0,
615
+ email: void 0
616
+ }, () => this._runInferenceLoop({
617
+ signal: abortSignal,
618
+ clientTools,
619
+ body,
620
+ continuation: false
621
+ }));
622
+ if (result) await this._streamResult(requestId, result, abortSignal);
623
+ };
624
+ if (this.unstable_chatRecovery) await this.runFiber(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => {
625
+ await programmaticBody();
626
+ });
627
+ else await programmaticBody();
628
+ } finally {
629
+ this._aborts.remove(requestId);
630
+ }
631
+ });
632
+ });
633
+ if (this._turnQueue.generation !== epoch && status === "completed") status = "skipped";
634
+ return {
635
+ requestId,
636
+ status
637
+ };
638
+ }
639
+ /**
640
+ * Run a new LLM call following the last assistant message.
641
+ *
642
+ * The model sees the full conversation (including the last assistant
643
+ * response) and generates a new response. The new response is persisted
644
+ * as a separate assistant message. Building block for chat recovery
645
+ * (Phase 4), "generate more" buttons, and self-correction.
646
+ *
647
+ * Note: this creates a new message, not an append to the existing one.
648
+ * True continuation-as-append (chunk rewriting) is planned for Phase 4.
649
+ *
650
+ * Returns early with `status: "skipped"` if there is no assistant message
651
+ * to continue from.
652
+ */
653
+ async continueLastTurn(body) {
654
+ const lastLeaf = this.session.getLatestLeaf();
655
+ if (!lastLeaf || lastLeaf.role !== "assistant") return {
656
+ requestId: "",
657
+ status: "skipped"
658
+ };
659
+ const requestId = crypto.randomUUID();
660
+ const clientTools = this._lastClientTools;
661
+ const resolvedBody = body ?? this._lastBody;
662
+ const epoch = this._turnQueue.generation;
663
+ let status = "completed";
664
+ await this.keepAliveWhile(async () => {
665
+ await this._turnQueue.enqueue(requestId, async () => {
666
+ if (this._turnQueue.generation !== epoch) {
667
+ status = "skipped";
668
+ return;
669
+ }
670
+ const abortSignal = this._aborts.getSignal(requestId);
671
+ try {
672
+ const continueTurnBody = async () => {
673
+ const result = await __DO_NOT_USE_WILL_BREAK__agentContext.run({
674
+ agent: this,
675
+ connection: void 0,
676
+ request: void 0,
677
+ email: void 0
678
+ }, () => this._runInferenceLoop({
679
+ signal: abortSignal,
680
+ clientTools,
681
+ body: resolvedBody,
682
+ continuation: true
683
+ }));
684
+ if (result) await this._streamResult(requestId, result, abortSignal, { continuation: true });
685
+ };
686
+ if (this.unstable_chatRecovery) await this.runFiber(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => {
687
+ await continueTurnBody();
688
+ });
689
+ else await continueTurnBody();
690
+ } finally {
691
+ this._aborts.remove(requestId);
692
+ }
693
+ });
694
+ });
695
+ if (this._turnQueue.generation !== epoch && status === "completed") status = "skipped";
696
+ return {
697
+ requestId,
698
+ status
699
+ };
215
700
  }
216
701
  _setupProtocolHandlers() {
217
702
  const _onConnect = this.onConnect.bind(this);
@@ -233,10 +718,13 @@ var Think = class extends ThinkBase {
233
718
  };
234
719
  const _onMessage = this.onMessage.bind(this);
235
720
  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 {}
721
+ if (typeof message === "string") {
722
+ const event = parseProtocolMessage(message);
723
+ if (event) {
724
+ await this._handleProtocolEvent(connection, event);
725
+ return;
726
+ }
727
+ }
240
728
  return _onMessage(connection, message);
241
729
  };
242
730
  const _onRequest = this.onRequest.bind(this);
@@ -246,105 +734,146 @@ var Think = class extends ThinkBase {
246
734
  return _onRequest(request);
247
735
  };
248
736
  }
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;
737
+ async _handleProtocolEvent(connection, event) {
738
+ switch (event.type) {
739
+ case "stream-resume-request":
740
+ this._handleStreamResumeRequest(connection);
741
+ break;
742
+ case "stream-resume-ack":
743
+ this._handleStreamResumeAck(connection, event.id);
744
+ break;
745
+ case "chat-request":
746
+ if (event.init?.method === "POST") await this._handleChatRequest(connection, event);
747
+ break;
748
+ case "tool-result": {
749
+ if (event.clientTools && Array.isArray(event.clientTools) && event.clientTools.length > 0) {
750
+ this._lastClientTools = event.clientTools;
751
+ this._persistClientTools();
752
+ }
753
+ const resultPromise = Promise.resolve().then(() => {
754
+ this._applyToolResult(event.toolCallId, event.output, event.state, event.errorText);
755
+ return true;
756
+ });
757
+ this._pendingInteractionPromise = resultPromise;
758
+ resultPromise.finally(() => {
759
+ if (this._pendingInteractionPromise === resultPromise) this._pendingInteractionPromise = null;
760
+ }).catch(() => {});
761
+ if (event.autoContinue) this._scheduleAutoContinuation(connection);
762
+ break;
270
763
  }
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();
764
+ case "tool-approval": {
765
+ const approvalPromise = Promise.resolve().then(() => {
766
+ this._applyToolApproval(event.toolCallId, event.approved);
767
+ return true;
768
+ });
769
+ this._pendingInteractionPromise = approvalPromise;
770
+ approvalPromise.finally(() => {
771
+ if (this._pendingInteractionPromise === approvalPromise) this._pendingInteractionPromise = null;
772
+ }).catch(() => {});
773
+ if (event.autoContinue) this._scheduleAutoContinuation(connection);
774
+ break;
277
775
  }
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;
776
+ case "clear":
777
+ this._handleClear(connection);
778
+ break;
779
+ case "cancel":
780
+ this._aborts.cancel(event.id);
781
+ break;
782
+ case "messages": break;
287
783
  }
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;
784
+ }
785
+ _handleStreamResumeRequest(connection) {
786
+ 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 }));
787
+ else this._notifyStreamResuming(connection);
788
+ else if (this._continuation.pending !== null && this._continuation.pending.connectionId === connection.id) this._continuation.awaitingConnections.set(connection.id, connection);
789
+ else connection.send(JSON.stringify({ type: MSG_STREAM_RESUME_NONE }));
790
+ }
791
+ _handleStreamResumeAck(connection, requestId) {
792
+ this._pendingResumeConnections.delete(connection.id);
793
+ if (this._resumableStream.hasActiveStream() && this._resumableStream.activeRequestId === requestId) {
794
+ const orphanedStreamId = this._resumableStream.replayChunks(connection, this._resumableStream.activeRequestId);
795
+ if (orphanedStreamId) this._persistOrphanedStream(orphanedStreamId);
295
796
  }
296
- return false;
297
797
  }
298
- async _handleChatRequest(connection, data) {
299
- const init = data.init;
300
- if (!init?.body) return;
301
- let parsed;
798
+ async _handleChatRequest(connection, event) {
799
+ if (!event.init?.body) return;
800
+ let rawParsed;
302
801
  try {
303
- parsed = JSON.parse(init.body);
802
+ rawParsed = JSON.parse(event.init.body);
304
803
  } catch {
305
804
  return;
306
805
  }
307
- const incomingMessages = parsed.messages;
806
+ const { messages: incomingMessages, clientTools: rawClientTools, trigger: rawTrigger, ...customBody } = rawParsed;
308
807
  if (!Array.isArray(incomingMessages)) return;
309
- const requestClientTools = parsed.clientTools?.length ? parsed.clientTools : void 0;
808
+ const isRegeneration = rawTrigger === "regenerate-message";
809
+ const isSubmitMessage = !isRegeneration;
810
+ const requestId = event.id;
811
+ const concurrencyDecision = this._getSubmitConcurrencyDecision(isSubmitMessage);
812
+ if (concurrencyDecision.action === "drop") {
813
+ this._rollbackDroppedSubmit(connection);
814
+ this._completeSkippedRequest(connection, requestId);
815
+ return;
816
+ }
817
+ const requestClientTools = rawClientTools && rawClientTools.length > 0 ? rawClientTools : void 0;
310
818
  if (requestClientTools) {
311
819
  this._lastClientTools = requestClientTools;
312
820
  this._persistClientTools();
313
- } else if (parsed.clientTools !== void 0) {
821
+ } else if (rawClientTools !== void 0) {
314
822
  this._lastClientTools = void 0;
315
823
  this._persistClientTools();
316
824
  }
825
+ this._lastBody = Object.keys(customBody).length > 0 ? customBody : void 0;
826
+ this._persistBody();
317
827
  const clientToolsForTurn = this._lastClientTools;
318
- for (const msg of incomingMessages) this._appendMessage(msg);
319
- this.messages = this._loadMessages();
828
+ const bodyForTurn = this._lastBody;
829
+ let branchParentId;
830
+ if (isRegeneration && incomingMessages.length > 0) branchParentId = incomingMessages[incomingMessages.length - 1].id;
831
+ for (const msg of incomingMessages) await this.session.appendMessage(msg);
320
832
  this._broadcastMessages([connection.id]);
321
- const requestId = data.id;
322
- const abortController = new AbortController();
323
- this._abortControllers.set(requestId, abortController);
833
+ const abortSignal = this._aborts.getSignal(requestId);
834
+ const epoch = this._turnQueue.generation;
324
835
  try {
325
836
  await this.keepAliveWhile(async () => {
326
837
  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 });
838
+ if (this._isSupersededSubmit(concurrencyDecision.submitSequence)) {
839
+ this._completeSkippedRequest(connection, requestId);
840
+ return;
330
841
  }
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
842
+ if (concurrencyDecision.debounceUntilMs !== null) {
843
+ await this._waitForTimestamp(concurrencyDecision.debounceUntilMs);
844
+ if (this._turnQueue.generation !== epoch) {
845
+ this._completeSkippedRequest(connection, requestId);
846
+ return;
847
+ }
848
+ if (this._isSupersededSubmit(concurrencyDecision.submitSequence)) {
849
+ this._completeSkippedRequest(connection, requestId);
850
+ return;
851
+ }
852
+ }
853
+ const chatTurnBody = async () => {
854
+ const result = await __DO_NOT_USE_WILL_BREAK__agentContext.run({
855
+ agent: this,
856
+ connection,
857
+ request: void 0,
858
+ email: void 0
859
+ }, () => this._runInferenceLoop({
860
+ signal: abortSignal,
861
+ clientTools: clientToolsForTurn,
862
+ body: bodyForTurn,
863
+ continuation: false
864
+ }));
865
+ if (result) await this._streamResult(requestId, result, abortSignal, { parentId: branchParentId });
866
+ else this._broadcastChat({
867
+ type: MSG_CHAT_RESPONSE,
868
+ id: requestId,
869
+ body: "No response was generated.",
870
+ done: true
871
+ });
872
+ };
873
+ if (this.unstable_chatRecovery) await this.runFiber(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => {
874
+ await chatTurnBody();
347
875
  });
876
+ else await chatTurnBody();
348
877
  })).status === "stale") this._broadcastChat({
349
878
  type: MSG_CHAT_RESPONSE,
350
879
  id: requestId,
@@ -361,63 +890,83 @@ var Think = class extends ThinkBase {
361
890
  error: true
362
891
  });
363
892
  } finally {
364
- this._abortControllers.delete(requestId);
893
+ this._aborts.remove(requestId);
365
894
  }
366
895
  }
367
- _handleClear() {
896
+ /**
897
+ * Abort the active turn, invalidate queued turns, and reset
898
+ * concurrency/continuation state. Call this when intercepting
899
+ * clear events or implementing custom reset logic.
900
+ *
901
+ * Does NOT clear messages, streams, or persisted state —
902
+ * only turn execution state.
903
+ */
904
+ resetTurnState() {
368
905
  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();
906
+ this._aborts.destroyAll();
375
907
  if (this._continuationTimer) {
376
908
  clearTimeout(this._continuationTimer);
377
909
  this._continuationTimer = null;
378
910
  }
911
+ this._cancelActiveDebounce();
912
+ this._pendingInteractionPromise = null;
379
913
  this._continuation.sendResumeNone();
380
914
  this._continuation.clearAll();
381
- this._clearMessages();
382
- this.messages = [];
383
- this._persistedMessageCache.clear();
384
- this._broadcast({ type: MSG_CHAT_CLEAR });
385
915
  }
386
- _handleCancel(requestId) {
387
- const controller = this._abortControllers.get(requestId);
388
- if (controller) controller.abort();
916
+ _handleClear(connection) {
917
+ this.resetTurnState();
918
+ this._resumableStream.clearAll();
919
+ this._pendingResumeConnections.clear();
920
+ this._lastClientTools = void 0;
921
+ this._persistClientTools();
922
+ this._lastBody = void 0;
923
+ this._persistBody();
924
+ this.session.clearMessages();
925
+ this._broadcast({ type: MSG_CHAT_CLEAR }, connection ? [connection.id] : void 0);
389
926
  }
390
- async _streamResult(requestId, result, abortSignal) {
927
+ async _streamResult(requestId, result, abortSignal, options) {
391
928
  const clearGen = this._turnQueue.generation;
392
929
  const streamId = this._resumableStream.start(requestId);
930
+ const continuation = options?.continuation ?? false;
931
+ const parentId = options?.parentId;
393
932
  if (this._continuation.pending?.requestId === requestId) {
394
933
  this._continuation.activatePending();
395
934
  this._continuation.flushAwaitingConnections((c) => this._notifyStreamResuming(c));
396
935
  }
397
936
  const accumulator = new StreamAccumulator({ messageId: crypto.randomUUID() });
398
937
  let doneSent = false;
938
+ let streamAborted = false;
939
+ let streamError;
399
940
  try {
400
- for await (const chunk of result.toUIMessageStream()) {
401
- if (abortSignal?.aborted) break;
402
- const { action } = accumulator.applyChunk(chunk);
403
- if (action?.type === "error") {
941
+ this._insideInferenceLoop = true;
942
+ try {
943
+ for await (const chunk of result.toUIMessageStream()) {
944
+ if (abortSignal?.aborted) {
945
+ streamAborted = true;
946
+ break;
947
+ }
948
+ const { action } = accumulator.applyChunk(chunk);
949
+ if (action?.type === "error") {
950
+ this._broadcastChat({
951
+ type: MSG_CHAT_RESPONSE,
952
+ id: requestId,
953
+ body: action.error,
954
+ done: false,
955
+ error: true
956
+ });
957
+ continue;
958
+ }
959
+ const chunkBody = JSON.stringify(chunk);
960
+ this._resumableStream.storeChunk(streamId, chunkBody);
404
961
  this._broadcastChat({
405
962
  type: MSG_CHAT_RESPONSE,
406
963
  id: requestId,
407
- body: action.error,
408
- done: false,
409
- error: true
964
+ body: chunkBody,
965
+ done: false
410
966
  });
411
- continue;
412
967
  }
413
- const chunkBody = JSON.stringify(chunk);
414
- this._resumableStream.storeChunk(streamId, chunkBody);
415
- this._broadcastChat({
416
- type: MSG_CHAT_RESPONSE,
417
- id: requestId,
418
- body: chunkBody,
419
- done: false
420
- });
968
+ } finally {
969
+ this._insideInferenceLoop = false;
421
970
  }
422
971
  this._resumableStream.complete(streamId);
423
972
  this._pendingResumeConnections.clear();
@@ -429,13 +978,14 @@ var Think = class extends ThinkBase {
429
978
  });
430
979
  doneSent = true;
431
980
  } catch (error) {
981
+ streamError = error instanceof Error ? error.message : "Stream error";
432
982
  this._resumableStream.markError(streamId);
433
983
  this._pendingResumeConnections.clear();
434
984
  if (!doneSent) {
435
985
  this._broadcastChat({
436
986
  type: MSG_CHAT_RESPONSE,
437
987
  id: requestId,
438
- body: error instanceof Error ? error.message : "Stream error",
988
+ body: streamError,
439
989
  done: true,
440
990
  error: true
441
991
  });
@@ -454,142 +1004,67 @@ var Think = class extends ThinkBase {
454
1004
  }
455
1005
  }
456
1006
  if (accumulator.parts.length > 0 && this._turnQueue.generation === clearGen) try {
457
- this._persistAssistantMessage(accumulator.toMessage());
1007
+ const assistantMsg = accumulator.toMessage();
1008
+ this._persistAssistantMessage(assistantMsg, parentId);
458
1009
  this._broadcastMessages();
1010
+ await this._fireResponseHook({
1011
+ message: assistantMsg,
1012
+ requestId,
1013
+ continuation,
1014
+ status: streamAborted ? "aborted" : streamError ? "error" : "completed",
1015
+ error: streamError
1016
+ });
459
1017
  } catch (e) {
460
1018
  console.error("Failed to persist assistant message:", e);
461
1019
  }
462
1020
  }
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}`;
1021
+ _persistAssistantMessage(msg, parentId) {
1022
+ const safe = enforceRowSizeLimit(sanitizeMessage(msg));
1023
+ if (this.session.getMessage(safe.id)) this.session.updateMessage(safe);
1024
+ else this.session.appendMessage(safe, parentId);
508
1025
  }
509
1026
  _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'`;
1027
+ if (this._lastClientTools) this._configSet("lastClientTools", JSON.stringify(this._lastClientTools));
1028
+ else this._configDelete("lastClientTools");
515
1029
  }
516
1030
  _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);
1031
+ const raw = this._configGet("lastClientTools");
1032
+ if (raw) try {
1033
+ this._lastClientTools = JSON.parse(raw);
522
1034
  } catch {
523
1035
  this._lastClientTools = void 0;
524
1036
  }
525
1037
  }
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);
1038
+ _persistBody() {
1039
+ if (this._lastBody) this._configSet("lastBody", JSON.stringify(this._lastBody));
1040
+ else this._configDelete("lastBody");
545
1041
  }
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
- }
1042
+ _restoreBody() {
1043
+ const raw = this._configGet("lastBody");
1044
+ if (raw) try {
1045
+ this._lastBody = JSON.parse(raw);
1046
+ } catch {
1047
+ this._lastBody = void 0;
575
1048
  }
576
1049
  }
1050
+ _applyToolResult(toolCallId, output, overrideState, errorText) {
1051
+ const update = toolResultUpdate(toolCallId, output, overrideState, errorText);
1052
+ this._applyToolUpdateToMessages(update);
1053
+ }
577
1054
  _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();
1055
+ const update = toolApprovalUpdate(toolCallId, approved);
1056
+ this._applyToolUpdateToMessages(update);
1057
+ }
1058
+ _applyToolUpdateToMessages(update) {
1059
+ const history = this.messages;
1060
+ for (const msg of history) {
1061
+ const result = applyToolUpdate(msg.parts, update);
1062
+ if (result) {
1063
+ const safe = enforceRowSizeLimit(sanitizeMessage({
1064
+ ...msg,
1065
+ parts: result.parts
1066
+ }));
1067
+ this.session.updateMessage(safe);
593
1068
  this._broadcast({
594
1069
  type: MSG_MESSAGE_UPDATED,
595
1070
  message: safe
@@ -598,6 +1073,179 @@ var Think = class extends ThinkBase {
598
1073
  }
599
1074
  }
600
1075
  }
1076
+ hasPendingInteraction() {
1077
+ return this.messages.some((message) => message.role === "assistant" && this._messageHasPendingInteraction(message));
1078
+ }
1079
+ async waitUntilStable(options) {
1080
+ const deadline = options?.timeout != null ? Date.now() + options.timeout : null;
1081
+ while (true) {
1082
+ if (await this._awaitWithDeadline(this._turnQueue.waitForIdle(), deadline) === TIMED_OUT) return false;
1083
+ if (!this.hasPendingInteraction()) return true;
1084
+ const pending = this._pendingInteractionPromise;
1085
+ if (pending) {
1086
+ let result;
1087
+ try {
1088
+ result = await this._awaitWithDeadline(pending, deadline);
1089
+ } catch {
1090
+ continue;
1091
+ }
1092
+ if (result === TIMED_OUT) return false;
1093
+ } else if (await this._awaitWithDeadline(new Promise((resolve) => setTimeout(resolve, 100)), deadline) === TIMED_OUT) return false;
1094
+ }
1095
+ }
1096
+ async _awaitWithDeadline(promise, deadline) {
1097
+ if (deadline == null) return promise;
1098
+ const remainingMs = Math.max(0, deadline - Date.now());
1099
+ let timer;
1100
+ const result = await Promise.race([promise, new Promise((resolve) => {
1101
+ timer = setTimeout(() => resolve(TIMED_OUT), remainingMs);
1102
+ })]);
1103
+ clearTimeout(timer);
1104
+ return result;
1105
+ }
1106
+ _messageHasPendingInteraction(message) {
1107
+ return message.parts.some((part) => "state" in part && (part.state === "input-available" || part.state === "approval-requested"));
1108
+ }
1109
+ async _handleInternalFiberRecovery(ctx) {
1110
+ const chatPrefix = this.constructor.CHAT_FIBER_NAME + ":";
1111
+ if (!ctx.name.startsWith(chatPrefix)) return false;
1112
+ const requestId = ctx.name.slice(chatPrefix.length);
1113
+ let streamId = "";
1114
+ if (requestId) {
1115
+ const rows = this.sql`
1116
+ SELECT id FROM cf_ai_chat_stream_metadata
1117
+ WHERE request_id = ${requestId}
1118
+ ORDER BY created_at DESC LIMIT 1
1119
+ `;
1120
+ if (rows.length > 0) streamId = rows[0].id;
1121
+ }
1122
+ if (!streamId && this._resumableStream.hasActiveStream()) streamId = this._resumableStream.activeStreamId ?? "";
1123
+ const partial = streamId ? this._getPartialStreamText(streamId) : {
1124
+ text: "",
1125
+ parts: []
1126
+ };
1127
+ const options = await this.onChatRecovery({
1128
+ streamId: streamId ?? "",
1129
+ requestId,
1130
+ partialText: partial.text,
1131
+ partialParts: partial.parts,
1132
+ recoveryData: ctx.snapshot,
1133
+ messages: [...this.messages],
1134
+ lastBody: this._lastBody,
1135
+ lastClientTools: this._lastClientTools
1136
+ });
1137
+ const streamStillActive = streamId && this._resumableStream.hasActiveStream() && this._resumableStream.activeStreamId === streamId;
1138
+ if (options.persist !== false && streamStillActive) this._persistOrphanedStream(streamId);
1139
+ if (streamStillActive) this._resumableStream.complete(streamId);
1140
+ if (options.continue !== false) {
1141
+ const lastLeaf = this.session.getLatestLeaf();
1142
+ const targetId = lastLeaf?.role === "assistant" ? lastLeaf.id : void 0;
1143
+ await this.schedule(0, "_chatRecoveryContinue", targetId ? { targetAssistantId: targetId } : void 0, { idempotent: true });
1144
+ }
1145
+ return true;
1146
+ }
1147
+ async onChatRecovery(_ctx) {
1148
+ return {};
1149
+ }
1150
+ async _chatRecoveryContinue(data) {
1151
+ if (!await this.waitUntilStable({ timeout: 1e4 })) {
1152
+ console.warn("[Think] _chatRecoveryContinue timed out waiting for stable state, skipping continuation");
1153
+ return;
1154
+ }
1155
+ const targetId = data?.targetAssistantId;
1156
+ const lastLeaf = this.session.getLatestLeaf();
1157
+ if (targetId && lastLeaf?.id !== targetId) return;
1158
+ await this.continueLastTurn();
1159
+ }
1160
+ _getPartialStreamText(streamId) {
1161
+ const chunks = this._resumableStream.getStreamChunks(streamId);
1162
+ const parts = [];
1163
+ for (const chunk of chunks) try {
1164
+ applyChunkToParts(parts, JSON.parse(chunk.body));
1165
+ } catch {}
1166
+ return {
1167
+ text: parts.filter((p) => p.type === "text" && "text" in p).map((p) => p.text).join(""),
1168
+ parts
1169
+ };
1170
+ }
1171
+ _normalizeMessageConcurrency() {
1172
+ if (typeof this.messageConcurrency === "string") return this.messageConcurrency;
1173
+ const debounceMs = this.messageConcurrency.debounceMs;
1174
+ return {
1175
+ strategy: "debounce",
1176
+ debounceMs: typeof debounceMs === "number" && Number.isFinite(debounceMs) && debounceMs >= 0 ? debounceMs : Think.MESSAGE_DEBOUNCE_MS
1177
+ };
1178
+ }
1179
+ _getSubmitConcurrencyDecision(isSubmitMessage) {
1180
+ const queuedTurns = this._turnQueue.queuedCount();
1181
+ if (!isSubmitMessage || queuedTurns === 0) return {
1182
+ action: "execute",
1183
+ submitSequence: null,
1184
+ debounceUntilMs: null
1185
+ };
1186
+ const concurrency = this._normalizeMessageConcurrency();
1187
+ if (concurrency === "queue") return {
1188
+ action: "execute",
1189
+ submitSequence: null,
1190
+ debounceUntilMs: null
1191
+ };
1192
+ if (concurrency === "drop") return {
1193
+ action: "drop",
1194
+ submitSequence: null,
1195
+ debounceUntilMs: null
1196
+ };
1197
+ const submitSequence = ++this._submitSequence;
1198
+ this._latestOverlappingSubmitSequence = submitSequence;
1199
+ if (concurrency === "latest" || concurrency === "merge") return {
1200
+ action: "execute",
1201
+ submitSequence,
1202
+ debounceUntilMs: null
1203
+ };
1204
+ return {
1205
+ action: "execute",
1206
+ submitSequence,
1207
+ debounceUntilMs: Date.now() + concurrency.debounceMs
1208
+ };
1209
+ }
1210
+ _isSupersededSubmit(submitSequence) {
1211
+ return submitSequence !== null && submitSequence < this._latestOverlappingSubmitSequence;
1212
+ }
1213
+ async _waitForTimestamp(timestampMs) {
1214
+ const remainingMs = timestampMs - Date.now();
1215
+ if (remainingMs <= 0) return;
1216
+ await new Promise((resolve) => {
1217
+ this._activeDebounceResolve = resolve;
1218
+ this._activeDebounceTimer = setTimeout(() => {
1219
+ this._activeDebounceTimer = null;
1220
+ this._activeDebounceResolve = null;
1221
+ resolve();
1222
+ }, remainingMs);
1223
+ });
1224
+ }
1225
+ _cancelActiveDebounce() {
1226
+ if (this._activeDebounceTimer !== null) {
1227
+ clearTimeout(this._activeDebounceTimer);
1228
+ this._activeDebounceTimer = null;
1229
+ }
1230
+ if (this._activeDebounceResolve !== null) {
1231
+ this._activeDebounceResolve();
1232
+ this._activeDebounceResolve = null;
1233
+ }
1234
+ }
1235
+ _completeSkippedRequest(connection, requestId) {
1236
+ connection.send(JSON.stringify({
1237
+ type: MSG_CHAT_RESPONSE,
1238
+ id: requestId,
1239
+ body: "",
1240
+ done: true
1241
+ }));
1242
+ }
1243
+ _rollbackDroppedSubmit(connection) {
1244
+ connection.send(JSON.stringify({
1245
+ type: MSG_CHAT_MESSAGES,
1246
+ messages: this.messages
1247
+ }));
1248
+ }
601
1249
  _scheduleAutoContinuation(connection) {
602
1250
  if (this._continuation.pending?.pastCoalesce) {
603
1251
  this._continuation.deferred = {
@@ -639,29 +1287,35 @@ var Think = class extends ThinkBase {
639
1287
  this._continuation.awaitingConnections.set(connection.id, connection);
640
1288
  }
641
1289
  const { requestId, clientTools } = this._continuation.pending;
642
- const abortController = new AbortController();
643
- this._abortControllers.set(requestId, abortController);
1290
+ const abortSignal = this._aborts.getSignal(requestId);
644
1291
  this.keepAliveWhile(async () => {
645
1292
  await this._turnQueue.enqueue(requestId, async () => {
646
1293
  if (this._continuation.pending) this._continuation.pending.pastCoalesce = true;
647
1294
  let streamed = false;
648
1295
  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
- }
1296
+ const continuationBody = async () => {
1297
+ const result = await __DO_NOT_USE_WILL_BREAK__agentContext.run({
1298
+ agent: this,
1299
+ connection,
1300
+ request: void 0,
1301
+ email: void 0
1302
+ }, () => this._runInferenceLoop({
1303
+ signal: abortSignal,
1304
+ clientTools,
1305
+ body: this._lastBody,
1306
+ continuation: true
1307
+ }));
1308
+ if (result) {
1309
+ await this._streamResult(requestId, result, abortSignal, { continuation: true });
1310
+ streamed = true;
1311
+ }
1312
+ };
1313
+ if (this.unstable_chatRecovery) await this.runFiber(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => {
1314
+ await continuationBody();
1315
+ });
1316
+ else await continuationBody();
663
1317
  } finally {
664
- this._abortControllers.delete(requestId);
1318
+ this._aborts.remove(requestId);
665
1319
  if (!streamed) this._continuation.sendResumeNone();
666
1320
  this._continuation.clearPending();
667
1321
  this._activateDeferredContinuation();
@@ -669,7 +1323,7 @@ var Think = class extends ThinkBase {
669
1323
  });
670
1324
  }).catch((error) => {
671
1325
  console.error("[Think] Auto-continuation failed:", error);
672
- this._abortControllers.delete(requestId);
1326
+ this._aborts.remove(requestId);
673
1327
  });
674
1328
  }
675
1329
  _activateDeferredContinuation() {
@@ -677,6 +1331,17 @@ var Think = class extends ThinkBase {
677
1331
  if (!pending) return;
678
1332
  this._fireAutoContinuation(pending.connection);
679
1333
  }
1334
+ async _fireResponseHook(result) {
1335
+ if (this._insideResponseHook) return;
1336
+ this._insideResponseHook = true;
1337
+ try {
1338
+ await this.onChatResponse(result);
1339
+ } catch (err) {
1340
+ console.error("[Think] onChatResponse error:", err);
1341
+ } finally {
1342
+ this._insideResponseHook = false;
1343
+ }
1344
+ }
680
1345
  _notifyStreamResuming(connection) {
681
1346
  if (!this._resumableStream.hasActiveStream()) return;
682
1347
  this._pendingResumeConnections.add(connection.id);
@@ -712,7 +1377,9 @@ var Think = class extends ThinkBase {
712
1377
  }, exclude);
713
1378
  }
714
1379
  };
1380
+ Think.CHAT_FIBER_NAME = "__cf_internal_chat_turn";
1381
+ Think.MESSAGE_DEBOUNCE_MS = 750;
715
1382
  //#endregion
716
- export { Think };
1383
+ export { Session, Think, Workspace };
717
1384
 
718
1385
  //# sourceMappingURL=think.js.map