@cloudflare/think 0.3.0 → 0.4.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/README.md +6 -4
- package/dist/think.d.ts +46 -87
- package/dist/think.js +18 -3
- package/dist/think.js.map +1 -1
- package/dist/tools/browser.d.ts +1 -1
- package/dist/tools/browser.js +1 -1
- package/dist/tools/browser.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -15,7 +15,7 @@ import { createWorkersAI } from "workers-ai-provider";
|
|
|
15
15
|
export class MyAgent extends Think<Env> {
|
|
16
16
|
getModel() {
|
|
17
17
|
return createWorkersAI({ binding: this.env.AI })(
|
|
18
|
-
"@cf/moonshotai/kimi-k2.
|
|
18
|
+
"@cf/moonshotai/kimi-k2.6"
|
|
19
19
|
);
|
|
20
20
|
}
|
|
21
21
|
|
|
@@ -284,19 +284,21 @@ await agent.chat("Summarize the project", relay, {
|
|
|
284
284
|
|
|
285
285
|
### Dynamic configuration
|
|
286
286
|
|
|
287
|
-
|
|
287
|
+
`configure()` and `getConfig()` persist a JSON-serializable config blob in SQLite — useful for private server-side settings that should survive hibernation and restarts. Pass the config shape as a method generic for typed call sites:
|
|
288
288
|
|
|
289
289
|
```ts
|
|
290
290
|
type MyConfig = { modelTier: "fast" | "capable"; systemPrompt: string };
|
|
291
291
|
|
|
292
|
-
export class MyAgent extends Think<Env
|
|
292
|
+
export class MyAgent extends Think<Env> {
|
|
293
293
|
getModel() {
|
|
294
|
-
const tier = this.getConfig()?.modelTier ?? "fast";
|
|
294
|
+
const tier = this.getConfig<MyConfig>()?.modelTier ?? "fast";
|
|
295
295
|
return createWorkersAI({ binding: this.env.AI })(MODEL_IDS[tier]);
|
|
296
296
|
}
|
|
297
297
|
}
|
|
298
298
|
```
|
|
299
299
|
|
|
300
|
+
For values you want broadcast to connected clients, use `state` / `setState` from `Agent` instead.
|
|
301
|
+
|
|
300
302
|
### Production features
|
|
301
303
|
|
|
302
304
|
- **WebSocket protocol** — wire-compatible with `useAgentChat` from `@cloudflare/ai-chat`
|
package/dist/think.d.ts
CHANGED
|
@@ -22,7 +22,19 @@ import {
|
|
|
22
22
|
FiberRecoveryContext,
|
|
23
23
|
FiberRecoveryContext as FiberRecoveryContext$1
|
|
24
24
|
} from "agents";
|
|
25
|
-
import {
|
|
25
|
+
import {
|
|
26
|
+
ChatRecoveryContext,
|
|
27
|
+
ChatRecoveryContext as ChatRecoveryContext$1,
|
|
28
|
+
ChatRecoveryOptions,
|
|
29
|
+
ChatRecoveryOptions as ChatRecoveryOptions$1,
|
|
30
|
+
ChatResponseResult,
|
|
31
|
+
ChatResponseResult as ChatResponseResult$1,
|
|
32
|
+
ClientToolSchema,
|
|
33
|
+
MessageConcurrency,
|
|
34
|
+
MessageConcurrency as MessageConcurrency$1,
|
|
35
|
+
SaveMessagesResult,
|
|
36
|
+
SaveMessagesResult as SaveMessagesResult$1
|
|
37
|
+
} from "agents/chat";
|
|
26
38
|
import {
|
|
27
39
|
Session,
|
|
28
40
|
Session as Session$1
|
|
@@ -55,40 +67,6 @@ interface ChatOptions {
|
|
|
55
67
|
signal?: AbortSignal;
|
|
56
68
|
tools?: ToolSet;
|
|
57
69
|
}
|
|
58
|
-
/**
|
|
59
|
-
* Result returned by `saveMessages()` and `continueLastTurn()`.
|
|
60
|
-
*/
|
|
61
|
-
type SaveMessagesResult = {
|
|
62
|
-
requestId: string;
|
|
63
|
-
status: "completed" | "skipped";
|
|
64
|
-
};
|
|
65
|
-
/**
|
|
66
|
-
* Context passed to `onChatRecovery` when an interrupted chat stream
|
|
67
|
-
* is detected after DO restart.
|
|
68
|
-
*/
|
|
69
|
-
type ChatRecoveryContext = {
|
|
70
|
-
streamId: string;
|
|
71
|
-
requestId: string;
|
|
72
|
-
partialText: string;
|
|
73
|
-
partialParts: MessagePart[];
|
|
74
|
-
recoveryData: unknown | null;
|
|
75
|
-
messages: UIMessage[];
|
|
76
|
-
lastBody?: Record<string, unknown>;
|
|
77
|
-
lastClientTools?: ClientToolSchema[];
|
|
78
|
-
/**
|
|
79
|
-
* Epoch milliseconds when the underlying fiber was started. Compare against
|
|
80
|
-
* `Date.now()` to suppress continuations for turns that have been orphaned
|
|
81
|
-
* too long to safely replay.
|
|
82
|
-
*/
|
|
83
|
-
createdAt: number;
|
|
84
|
-
};
|
|
85
|
-
/**
|
|
86
|
-
* Options returned from `onChatRecovery` to control recovery behavior.
|
|
87
|
-
*/
|
|
88
|
-
type ChatRecoveryOptions = {
|
|
89
|
-
persist?: boolean;
|
|
90
|
-
continue?: boolean;
|
|
91
|
-
};
|
|
92
70
|
/**
|
|
93
71
|
* A chat turn request. Built automatically by each entry path
|
|
94
72
|
* (WebSocket, chat(), saveMessages, auto-continuation) and passed
|
|
@@ -290,41 +268,6 @@ interface ExtensionConfig {
|
|
|
290
268
|
/** JavaScript source code defining the extension's tools. */
|
|
291
269
|
source: string;
|
|
292
270
|
}
|
|
293
|
-
/**
|
|
294
|
-
* Controls how overlapping user submit requests behave while another
|
|
295
|
-
* chat turn is already active or queued.
|
|
296
|
-
*
|
|
297
|
-
* - `"queue"` (default) — queue every submit and process them in order.
|
|
298
|
-
* - `"latest"` — keep only the latest overlapping submit; superseded submits
|
|
299
|
-
* still persist their user messages, but do not start their own model turn.
|
|
300
|
-
* - `"merge"` — like latest, but all overlapping user messages remain in
|
|
301
|
-
* the conversation history. The model sees them all in one turn.
|
|
302
|
-
* - `"drop"` — ignore overlapping submits entirely (messages not persisted).
|
|
303
|
-
* - `{ strategy: "debounce" }` — trailing-edge latest with a quiet window.
|
|
304
|
-
*
|
|
305
|
-
* Only applies to `submit-message` requests. Regenerations, tool
|
|
306
|
-
* continuations, approvals, clears, `saveMessages`, and `continueLastTurn`
|
|
307
|
-
* keep their existing serialized behavior.
|
|
308
|
-
*/
|
|
309
|
-
type MessageConcurrency =
|
|
310
|
-
| "queue"
|
|
311
|
-
| "latest"
|
|
312
|
-
| "merge"
|
|
313
|
-
| "drop"
|
|
314
|
-
| {
|
|
315
|
-
strategy: "debounce";
|
|
316
|
-
debounceMs?: number;
|
|
317
|
-
};
|
|
318
|
-
/**
|
|
319
|
-
* Result passed to `onChatResponse` after a chat turn completes.
|
|
320
|
-
*/
|
|
321
|
-
type ChatResponseResult = {
|
|
322
|
-
message: UIMessage;
|
|
323
|
-
requestId: string;
|
|
324
|
-
continuation: boolean;
|
|
325
|
-
status: "completed" | "error" | "aborted";
|
|
326
|
-
error?: string;
|
|
327
|
-
};
|
|
328
271
|
/**
|
|
329
272
|
* An opinionated chat agent base class.
|
|
330
273
|
*
|
|
@@ -332,8 +275,9 @@ type ChatResponseResult = {
|
|
|
332
275
|
*/
|
|
333
276
|
declare class Think<
|
|
334
277
|
Env extends Cloudflare.Env = Cloudflare.Env,
|
|
335
|
-
|
|
336
|
-
|
|
278
|
+
State = unknown,
|
|
279
|
+
Props extends Record<string, unknown> = Record<string, unknown>
|
|
280
|
+
> extends Agent<Env, State, Props> {
|
|
337
281
|
#private;
|
|
338
282
|
/**
|
|
339
283
|
* Wait for MCP server connections to be ready before the inference
|
|
@@ -353,7 +297,7 @@ declare class Think<
|
|
|
353
297
|
*
|
|
354
298
|
* @default "queue"
|
|
355
299
|
*/
|
|
356
|
-
messageConcurrency: MessageConcurrency;
|
|
300
|
+
messageConcurrency: MessageConcurrency$1;
|
|
357
301
|
/**
|
|
358
302
|
* When true, chat turns are wrapped in `runFiber` for durable execution.
|
|
359
303
|
* Enables `onChatRecovery` hook and `this.stash()` during streaming.
|
|
@@ -409,14 +353,29 @@ declare class Think<
|
|
|
409
353
|
private _activeDebounceResolve;
|
|
410
354
|
private static MESSAGE_DEBOUNCE_MS;
|
|
411
355
|
/**
|
|
412
|
-
* Persist
|
|
413
|
-
* Stored in
|
|
356
|
+
* Persist an arbitrary JSON-serializable configuration object for this
|
|
357
|
+
* agent instance. Stored in the assistant_config table — survives
|
|
358
|
+
* restarts and hibernation. Pass the config shape as a method generic
|
|
359
|
+
* for typed call sites:
|
|
360
|
+
*
|
|
361
|
+
* ```ts
|
|
362
|
+
* this.configure<MyConfig>({ modelTier: "fast" });
|
|
363
|
+
* ```
|
|
364
|
+
*
|
|
365
|
+
* Prefer `state` / `setState` from `Agent` when you want the value
|
|
366
|
+
* broadcast to connected clients. Use `configure` for private
|
|
367
|
+
* per-instance config that should stay server-side.
|
|
414
368
|
*/
|
|
415
|
-
configure(config:
|
|
369
|
+
configure<T = Record<string, unknown>>(config: T): void;
|
|
416
370
|
/**
|
|
417
371
|
* Read the persisted configuration, or null if never configured.
|
|
372
|
+
* Pass the config shape as a method generic for a typed result:
|
|
373
|
+
*
|
|
374
|
+
* ```ts
|
|
375
|
+
* const cfg = this.getConfig<MyConfig>();
|
|
376
|
+
* ```
|
|
418
377
|
*/
|
|
419
|
-
getConfig():
|
|
378
|
+
getConfig<T = Record<string, unknown>>(): T | null;
|
|
420
379
|
private _ensureConfigTable;
|
|
421
380
|
private _configSet;
|
|
422
381
|
private _configGet;
|
|
@@ -573,7 +532,7 @@ declare class Think<
|
|
|
573
532
|
*
|
|
574
533
|
* Override for logging, chaining, analytics, usage tracking.
|
|
575
534
|
*/
|
|
576
|
-
onChatResponse(_result: ChatResponseResult): void | Promise<void>;
|
|
535
|
+
onChatResponse(_result: ChatResponseResult$1): void | Promise<void>;
|
|
577
536
|
/**
|
|
578
537
|
* Handle an error that occurred during a chat turn.
|
|
579
538
|
* Override to customize error handling (e.g. logging, metrics).
|
|
@@ -727,7 +686,7 @@ declare class Think<
|
|
|
727
686
|
messages:
|
|
728
687
|
| UIMessage[]
|
|
729
688
|
| ((currentMessages: UIMessage[]) => UIMessage[] | Promise<UIMessage[]>)
|
|
730
|
-
): Promise<SaveMessagesResult>;
|
|
689
|
+
): Promise<SaveMessagesResult$1>;
|
|
731
690
|
/**
|
|
732
691
|
* Run a new LLM call following the last assistant message.
|
|
733
692
|
*
|
|
@@ -744,7 +703,7 @@ declare class Think<
|
|
|
744
703
|
*/
|
|
745
704
|
protected continueLastTurn(
|
|
746
705
|
body?: Record<string, unknown>
|
|
747
|
-
): Promise<SaveMessagesResult>;
|
|
706
|
+
): Promise<SaveMessagesResult$1>;
|
|
748
707
|
private _setupProtocolHandlers;
|
|
749
708
|
private _handleProtocolEvent;
|
|
750
709
|
private _handleStreamResumeRequest;
|
|
@@ -777,8 +736,8 @@ declare class Think<
|
|
|
777
736
|
ctx: FiberRecoveryContext$1
|
|
778
737
|
): Promise<boolean>;
|
|
779
738
|
protected onChatRecovery(
|
|
780
|
-
_ctx: ChatRecoveryContext
|
|
781
|
-
): Promise<ChatRecoveryOptions>;
|
|
739
|
+
_ctx: ChatRecoveryContext$1
|
|
740
|
+
): Promise<ChatRecoveryOptions$1>;
|
|
782
741
|
_chatRecoveryContinue(data?: { targetAssistantId?: string }): Promise<void>;
|
|
783
742
|
private _getPartialStreamText;
|
|
784
743
|
private _normalizeMessageConcurrency;
|
|
@@ -801,16 +760,16 @@ declare class Think<
|
|
|
801
760
|
//#endregion
|
|
802
761
|
export {
|
|
803
762
|
ChatOptions,
|
|
804
|
-
ChatRecoveryContext,
|
|
805
|
-
ChatRecoveryOptions,
|
|
806
|
-
ChatResponseResult,
|
|
763
|
+
type ChatRecoveryContext,
|
|
764
|
+
type ChatRecoveryOptions,
|
|
765
|
+
type ChatResponseResult,
|
|
807
766
|
ChunkContext,
|
|
808
767
|
ChunkPart,
|
|
809
768
|
ExtensionConfig,
|
|
810
769
|
type FiberContext,
|
|
811
770
|
type FiberRecoveryContext,
|
|
812
|
-
MessageConcurrency,
|
|
813
|
-
SaveMessagesResult,
|
|
771
|
+
type MessageConcurrency,
|
|
772
|
+
type SaveMessagesResult,
|
|
814
773
|
Session,
|
|
815
774
|
StepContext,
|
|
816
775
|
type StepResult,
|
package/dist/think.js
CHANGED
|
@@ -68,8 +68,18 @@ var Think = class Think extends Agent {
|
|
|
68
68
|
return this.session.getHistory();
|
|
69
69
|
}
|
|
70
70
|
/**
|
|
71
|
-
* Persist
|
|
72
|
-
* Stored in
|
|
71
|
+
* Persist an arbitrary JSON-serializable configuration object for this
|
|
72
|
+
* agent instance. Stored in the assistant_config table — survives
|
|
73
|
+
* restarts and hibernation. Pass the config shape as a method generic
|
|
74
|
+
* for typed call sites:
|
|
75
|
+
*
|
|
76
|
+
* ```ts
|
|
77
|
+
* this.configure<MyConfig>({ modelTier: "fast" });
|
|
78
|
+
* ```
|
|
79
|
+
*
|
|
80
|
+
* Prefer `state` / `setState` from `Agent` when you want the value
|
|
81
|
+
* broadcast to connected clients. Use `configure` for private
|
|
82
|
+
* per-instance config that should stay server-side.
|
|
73
83
|
*/
|
|
74
84
|
configure(config) {
|
|
75
85
|
const json = JSON.stringify(config);
|
|
@@ -78,9 +88,14 @@ var Think = class Think extends Agent {
|
|
|
78
88
|
}
|
|
79
89
|
/**
|
|
80
90
|
* Read the persisted configuration, or null if never configured.
|
|
91
|
+
* Pass the config shape as a method generic for a typed result:
|
|
92
|
+
*
|
|
93
|
+
* ```ts
|
|
94
|
+
* const cfg = this.getConfig<MyConfig>();
|
|
95
|
+
* ```
|
|
81
96
|
*/
|
|
82
97
|
getConfig() {
|
|
83
|
-
if (_classPrivateFieldGet2(_configCache, this)) return _classPrivateFieldGet2(_configCache, this);
|
|
98
|
+
if (_classPrivateFieldGet2(_configCache, this) !== null) return _classPrivateFieldGet2(_configCache, this);
|
|
84
99
|
const raw = this._configGet("_think_config");
|
|
85
100
|
if (raw !== void 0) {
|
|
86
101
|
_classPrivateFieldSet2(_configCache, this, JSON.parse(raw));
|
package/dist/think.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"think.js","names":["Workspace","Session","agentContext"],"sources":["../src/think.ts"],"sourcesContent":["/**\n * Think — an opinionated chat agent base class.\n *\n * Works as both a **top-level agent** (speaking the `cf_agent_chat_*`\n * WebSocket protocol to browser clients) and a **sub-agent** (called\n * via `chat()` over RPC from a parent agent).\n *\n * Each instance gets its own SQLite storage backed by Session — providing\n * tree-structured messages, context blocks, compaction, FTS5 search, and\n * multi-session support.\n *\n * Configuration overrides:\n * - getModel() — return the LanguageModel to use\n * - getSystemPrompt() — return the system prompt (fallback when no context blocks)\n * - getTools() — return the ToolSet for the agentic loop\n * - maxSteps — max tool-call rounds per turn (default: 10)\n * - configureSession() — add context blocks, compaction, search, skills\n *\n * Lifecycle hooks:\n * - beforeTurn() — inspect/override context, tools, model before inference\n * - beforeToolCall() — intercept tool calls (block, modify args, substitute result)\n * - afterToolCall() — inspect tool results after execution\n * - onStepFinish() — per-step callback (logging, analytics)\n * - onChunk() — per-chunk callback (streaming analytics)\n * - onChatResponse() — post-turn lifecycle hook (logging, chaining, analytics)\n * - onChatError() — customize error handling\n *\n * Production features:\n * - WebSocket chat protocol (compatible with useAgentChat / useChat)\n * - Sub-agent RPC streaming via StreamCallback\n * - Session-backed storage with tree-structured messages\n * - Context blocks with LLM-writable persistent memory\n * - Non-destructive compaction (summaries replace ranges at read time)\n * - FTS5 full-text search across conversation history\n * - Abort/cancel support via AbortRegistry\n * - Error handling with partial message persistence\n * - Message sanitization (strips OpenAI ephemeral metadata)\n * - Row size enforcement (compacts large tool outputs)\n * - Resumable streams (replay on reconnect)\n *\n * @experimental The API surface may change before stabilizing.\n *\n * @example\n * ```typescript\n * import { Think } from \"@cloudflare/think\";\n * import { createWorkersAI } from \"workers-ai-provider\";\n *\n * export class MyAgent extends Think<Env> {\n * getModel() {\n * return createWorkersAI({ binding: this.env.AI })(\"@cf/moonshotai/kimi-k2.5\");\n * }\n *\n * getSystemPrompt() {\n * return \"You are a helpful coding assistant.\";\n * }\n * }\n * ```\n *\n * @example With context blocks and self-updating memory\n * ```typescript\n * import { Think } from \"@cloudflare/think\";\n * import type { Session } from \"@cloudflare/think\";\n *\n * export class MemoryAgent extends Think<Env> {\n * getModel() { ... }\n *\n * configureSession(session: Session) {\n * return session\n * .withContext(\"soul\", {\n * provider: { get: async () => \"You are a helpful coding assistant.\" }\n * })\n * .withContext(\"memory\", {\n * description: \"Important facts learned during conversation.\",\n * maxTokens: 2000\n * })\n * .withCachedPrompt();\n * }\n * }\n * ```\n */\n\nimport type {\n LanguageModel,\n ModelMessage,\n StreamTextOnChunkCallback,\n StreamTextOnStepFinishCallback,\n StreamTextOnToolCallFinishCallback,\n TextStreamPart,\n ToolSet,\n TypedToolCall,\n TypedToolResult,\n UIMessage\n} from \"ai\";\nimport {\n convertToModelMessages,\n pruneMessages,\n stepCountIs,\n streamText\n} from \"ai\";\n\n// Re-export AI SDK types that appear on Think's public lifecycle hooks\n// so users can import them from a single place.\nexport type {\n StepResult,\n TextStreamPart,\n TypedToolCall,\n TypedToolResult\n} from \"ai\";\nimport {\n Agent,\n __DO_NOT_USE_WILL_BREAK__agentContext as agentContext\n} from \"agents\";\nimport type { Connection, WSMessage } from \"agents\";\nimport type { FiberContext, FiberRecoveryContext } from \"agents\";\nimport {\n sanitizeMessage,\n enforceRowSizeLimit,\n StreamAccumulator,\n CHAT_MESSAGE_TYPES,\n TurnQueue,\n ResumableStream,\n ContinuationState,\n createToolsFromClientSchemas,\n AbortRegistry,\n applyToolUpdate,\n toolResultUpdate,\n toolApprovalUpdate,\n parseProtocolMessage,\n applyChunkToParts\n} from \"agents/chat\";\nimport type {\n StreamChunkData,\n ClientToolSchema,\n MessagePart\n} from \"agents/chat\";\nimport { Session } from \"agents/experimental/memory/session\";\nimport { truncateOlderMessages } from \"agents/experimental/memory/utils\";\nimport { Workspace } from \"@cloudflare/shell\";\nimport { createWorkspaceTools } from \"./tools/workspace\";\n\nexport { Session } from \"agents/experimental/memory/session\";\nexport { Workspace } from \"@cloudflare/shell\";\nexport type { FiberContext, FiberRecoveryContext } from \"agents\";\n\n// ── Wire protocol constants ────────────────────────────────────────\nconst MSG_CHAT_MESSAGES = CHAT_MESSAGE_TYPES.CHAT_MESSAGES;\nconst MSG_CHAT_RESPONSE = CHAT_MESSAGE_TYPES.USE_CHAT_RESPONSE;\nconst MSG_CHAT_CLEAR = CHAT_MESSAGE_TYPES.CHAT_CLEAR;\nconst MSG_STREAM_RESUMING = CHAT_MESSAGE_TYPES.STREAM_RESUMING;\nconst MSG_STREAM_RESUME_NONE = CHAT_MESSAGE_TYPES.STREAM_RESUME_NONE;\nconst MSG_MESSAGE_UPDATED = CHAT_MESSAGE_TYPES.MESSAGE_UPDATED;\n\n/**\n * Callback interface for streaming chat events from a Think sub-agent.\n *\n * Designed to work across the sub-agent RPC boundary — implement as\n * an RpcTarget in the parent agent and pass to `chat()`.\n */\nexport interface StreamCallback {\n onEvent(json: string): void | Promise<void>;\n onDone(): void | Promise<void>;\n onError?(error: string): void | Promise<void>;\n}\n\n/**\n * Minimal interface for the result of the inference loop.\n * The AI SDK's `streamText()` result satisfies this interface.\n */\nexport interface StreamableResult {\n toUIMessageStream(): AsyncIterable<unknown>;\n}\n\n/**\n * Options for a chat turn (sub-agent RPC entry point).\n */\nexport interface ChatOptions {\n signal?: AbortSignal;\n tools?: ToolSet;\n}\n\n/**\n * Result returned by `saveMessages()` and `continueLastTurn()`.\n */\nexport type SaveMessagesResult = {\n requestId: string;\n status: \"completed\" | \"skipped\";\n};\n\n/**\n * Context passed to `onChatRecovery` when an interrupted chat stream\n * is detected after DO restart.\n */\nexport type ChatRecoveryContext = {\n streamId: string;\n requestId: string;\n partialText: string;\n partialParts: MessagePart[];\n recoveryData: unknown | null;\n messages: UIMessage[];\n lastBody?: Record<string, unknown>;\n lastClientTools?: ClientToolSchema[];\n /**\n * Epoch milliseconds when the underlying fiber was started. Compare against\n * `Date.now()` to suppress continuations for turns that have been orphaned\n * too long to safely replay.\n */\n createdAt: number;\n};\n\n/**\n * Options returned from `onChatRecovery` to control recovery behavior.\n */\nexport type ChatRecoveryOptions = {\n persist?: boolean;\n continue?: boolean;\n};\n\n// ── Lifecycle hook types ────────────────────────────────────────\n\n/**\n * A chat turn request. Built automatically by each entry path\n * (WebSocket, chat(), saveMessages, auto-continuation) and passed\n * to Think's inference loop.\n */\nexport interface TurnInput {\n signal?: AbortSignal;\n /** Extra tools from the caller (e.g. chat() options) — highest merge priority. */\n callerTools?: ToolSet;\n /** Client-provided tool schemas for dynamic tool registration. */\n clientTools?: ClientToolSchema[];\n /** Custom body fields from the client request. */\n body?: Record<string, unknown>;\n /** Whether this is a continuation turn (auto-continue after tool result, recovery). */\n continuation: boolean;\n}\n\n/**\n * Context passed to the `beforeTurn` hook.\n * Contains everything Think assembled — the hook can inspect and override.\n */\nexport interface TurnContext {\n /** Assembled system prompt (from context blocks or getSystemPrompt fallback). */\n system: string;\n /** Assembled model messages (truncated, pruned). */\n messages: ModelMessage[];\n /** Merged tool set (workspace + getTools + session + MCP + client + caller). */\n tools: ToolSet;\n /** The language model from getModel(). */\n model: LanguageModel;\n /** Whether this is a continuation turn. */\n continuation: boolean;\n /** Custom body fields from the client request. */\n body?: Record<string, unknown>;\n}\n\n/**\n * Configuration returned by the `beforeTurn` hook to override defaults.\n * All fields are optional — return only what you want to change.\n */\nexport interface TurnConfig {\n /** Override the model for this turn (e.g. cheap model for continuations). */\n model?: LanguageModel;\n /** Override the assembled system prompt. */\n system?: string;\n /** Override the assembled messages. */\n messages?: ModelMessage[];\n /** Extra tools to merge (additive — spread on top of existing tools). */\n tools?: ToolSet;\n /** Limit which tools the model can call (AI SDK activeTools). */\n activeTools?: string[];\n /** Force a specific tool call (AI SDK toolChoice). */\n toolChoice?: Parameters<typeof streamText>[0][\"toolChoice\"];\n /** Override maxSteps for this turn. */\n maxSteps?: number;\n /** Provider-specific options (AI SDK providerOptions). */\n providerOptions?: Record<string, unknown>;\n}\n\n/**\n * Context passed to the `beforeToolCall` hook **before** the tool's\n * `execute` function runs.\n *\n * Backed by the AI SDK's `OnToolCallStartEvent` (the parameter of\n * `experimental_onToolCallStart`). The full `TypedToolCall<TOOLS>`\n * fields (`toolName`, `toolCallId`, `input`, `providerMetadata`, the\n * dynamic/invalid/error discriminators) are spread at the top level for\n * convenience, with the per-call event extras attached:\n *\n * - `stepNumber` — index of the current step\n * - `messages` — conversation messages visible at tool execution time\n * - `abortSignal` — signal that aborts if the turn is cancelled\n *\n * Pass an explicit `TOOLS` generic for full input typing:\n *\n * ```ts\n * import type { ToolCallContext } from \"@cloudflare/think\";\n * import type { tools } from \"./my-tools\";\n *\n * beforeToolCall(ctx: ToolCallContext<typeof tools>) {\n * if (ctx.toolName === \"search\") {\n * ctx.input.query; // typed\n * }\n * }\n * ```\n */\nexport type ToolCallContext<TOOLS extends ToolSet = ToolSet> =\n TypedToolCall<TOOLS> & {\n /** Zero-based index of the current step where this tool call occurs. */\n readonly stepNumber: number | undefined;\n /** The conversation messages available at tool execution time. */\n readonly messages: ReadonlyArray<ModelMessage>;\n /** Signal for cancelling the operation. */\n readonly abortSignal: AbortSignal | undefined;\n };\n\n/**\n * Decision returned by `beforeToolCall` to control tool execution.\n * Return void/undefined to allow execution with original input.\n *\n * Discriminated union — each action has a clear, non-overlapping meaning:\n * - `allow` — execute the tool (optionally with modified input)\n * - `block` — don't execute; return `reason` as the tool result so the model can adjust\n * - `substitute` — don't execute; return `output` as the tool result (afterToolCall still fires)\n */\nexport type ToolCallDecision =\n | {\n action: \"allow\";\n /** Modified input — tool executes with this instead of the original. */\n input?: Record<string, unknown>;\n }\n | {\n action: \"block\";\n /** Returned as the tool result so the model can adjust. */\n reason?: string;\n }\n | {\n action: \"substitute\";\n /** The substitute tool output — model sees this instead of real execution. */\n output: unknown;\n /** Optional input attribution for the afterToolCall log. */\n input?: Record<string, unknown>;\n };\n\n/**\n * Context passed to the `afterToolCall` hook after a tool executes.\n *\n * Backed by the AI SDK's `OnToolCallFinishEvent` (the parameter of\n * `experimental_onToolCallFinish`). The full `TypedToolCall<TOOLS>`\n * fields (`toolName`, `toolCallId`, `input`, …) are spread at the top\n * level, plus the per-call event extras:\n *\n * - `stepNumber` — index of the current step\n * - `messages` — conversation messages visible at tool execution time\n * - `durationMs` — wall-clock execution time in milliseconds\n * - `success`/`output`/`error` — discriminated outcome:\n * - on success: `success: true`, `output: unknown`\n * - on failure: `success: false`, `error: unknown`\n *\n * Pass an explicit `TOOLS` generic for full input typing:\n *\n * ```ts\n * import type { ToolCallResultContext } from \"@cloudflare/think\";\n * import type { tools } from \"./my-tools\";\n *\n * afterToolCall(ctx: ToolCallResultContext<typeof tools>) {\n * if (ctx.success) {\n * console.log(`${ctx.toolName} took ${ctx.durationMs}ms`, ctx.output);\n * } else {\n * console.error(`${ctx.toolName} failed:`, ctx.error);\n * }\n * }\n * ```\n */\nexport type ToolCallResultContext<TOOLS extends ToolSet = ToolSet> =\n TypedToolCall<TOOLS> & {\n readonly stepNumber: number | undefined;\n readonly messages: ReadonlyArray<ModelMessage>;\n /** Wall-clock execution time in milliseconds. */\n readonly durationMs: number;\n } & (\n | {\n readonly success: true;\n readonly output: unknown;\n readonly error?: never;\n }\n | {\n readonly success: false;\n readonly output?: never;\n readonly error: unknown;\n }\n );\n\n/**\n * Context passed to the `onStepFinish` hook after each step completes.\n *\n * This is the AI SDK's `StepResult<TOOLS>` (= `OnStepFinishEvent<TOOLS>`) —\n * the full step record including `text`, `reasoning`, `toolCalls`,\n * `toolResults`, `files`, `sources`, `usage` (with `cachedInputTokens`,\n * `reasoningTokens`, `totalTokens`), `finishReason`, `warnings`, `request`,\n * `response`, and `providerMetadata` (where provider-specific cache\n * accounting like `cacheCreationInputTokens` lives).\n *\n * Pass an explicit `TOOLS` generic for typed `toolCalls`/`toolResults`.\n */\nexport type StepContext<TOOLS extends ToolSet = ToolSet> = Parameters<\n StreamTextOnStepFinishCallback<TOOLS>\n>[0];\n\n/**\n * Context passed to the `onChunk` hook for each streaming chunk.\n *\n * This is the AI SDK's `StreamTextOnChunkCallback` event — `{ chunk }`\n * where `chunk` is a discriminated union of `TextStreamPart` variants\n * (text-delta, reasoning-delta, source, tool-call, tool-input-start,\n * tool-input-delta, tool-result, raw).\n */\nexport type ChunkContext<TOOLS extends ToolSet = ToolSet> = Parameters<\n StreamTextOnChunkCallback<TOOLS>\n>[0];\n\n/**\n * @internal Re-export of the chunk variant union for consumers that need\n * to narrow on `chunk.type` without importing `TextStreamPart` directly.\n */\nexport type ChunkPart<TOOLS extends ToolSet = ToolSet> =\n ChunkContext<TOOLS>[\"chunk\"];\n\n/**\n * Configuration for a sandboxed extension, returned by getExtensions().\n */\nexport interface ExtensionConfig {\n /** Extension manifest (name, version, permissions, contributions). */\n manifest: import(\"./extensions/types\").ExtensionManifest;\n /** JavaScript source code defining the extension's tools. */\n source: string;\n}\n\nconst TIMED_OUT = Symbol(\"timed-out\");\n\n/**\n * Controls how overlapping user submit requests behave while another\n * chat turn is already active or queued.\n *\n * - `\"queue\"` (default) — queue every submit and process them in order.\n * - `\"latest\"` — keep only the latest overlapping submit; superseded submits\n * still persist their user messages, but do not start their own model turn.\n * - `\"merge\"` — like latest, but all overlapping user messages remain in\n * the conversation history. The model sees them all in one turn.\n * - `\"drop\"` — ignore overlapping submits entirely (messages not persisted).\n * - `{ strategy: \"debounce\" }` — trailing-edge latest with a quiet window.\n *\n * Only applies to `submit-message` requests. Regenerations, tool\n * continuations, approvals, clears, `saveMessages`, and `continueLastTurn`\n * keep their existing serialized behavior.\n */\nexport type MessageConcurrency =\n | \"queue\"\n | \"latest\"\n | \"merge\"\n | \"drop\"\n | { strategy: \"debounce\"; debounceMs?: number };\n\ntype NormalizedMessageConcurrency =\n | \"queue\"\n | \"latest\"\n | \"merge\"\n | \"drop\"\n | { strategy: \"debounce\"; debounceMs: number };\n\ntype SubmitConcurrencyDecision = {\n action: \"execute\" | \"drop\";\n submitSequence: number | null;\n debounceUntilMs: number | null;\n};\n\n/**\n * Result passed to `onChatResponse` after a chat turn completes.\n */\nexport type ChatResponseResult = {\n message: UIMessage;\n requestId: string;\n continuation: boolean;\n status: \"completed\" | \"error\" | \"aborted\";\n error?: string;\n};\n\n/**\n * An opinionated chat agent base class.\n *\n * @experimental The API surface may change before stabilizing.\n */\nexport class Think<\n Env extends Cloudflare.Env = Cloudflare.Env,\n Config = Record<string, unknown>\n> extends Agent<Env> {\n /**\n * Wait for MCP server connections to be ready before the inference\n * loop. MCP tools are auto-merged into the tool set.\n *\n * Set to `true` for a default 10s timeout, or `{ timeout: ms }`\n * for a custom timeout. Defaults to `false` (no waiting).\n */\n waitForMcpConnections: boolean | { timeout: number } = false;\n\n /**\n * Controls how overlapping user submit requests behave while another\n * chat turn is already active or queued.\n *\n * @default \"queue\"\n */\n messageConcurrency: MessageConcurrency = \"queue\";\n\n /**\n * When true, chat turns are wrapped in `runFiber` for durable execution.\n * Enables `onChatRecovery` hook and `this.stash()` during streaming.\n */\n chatRecovery = true;\n\n static readonly CHAT_FIBER_NAME = \"__cf_internal_chat_turn\";\n\n /** The conversation session — messages, context, compaction, search. */\n session!: Session;\n\n /**\n * WorkerLoader binding for sandboxed extensions.\n * Set this to enable `getExtensions()` and dynamic extension loading.\n */\n extensionLoader?: WorkerLoader;\n\n /**\n * Extension manager — created automatically when `extensionLoader` is set.\n * Use for dynamic `load()` / `unload()` at runtime.\n */\n extensionManager?: import(\"./extensions/manager\").ExtensionManager;\n\n /**\n * Workspace filesystem backed by the DO's SQLite storage.\n * Available in `getTools()` and lifecycle hooks.\n *\n * Override to add R2 spillover for large files:\n * ```typescript\n * override workspace = new Workspace({\n * sql: this.ctx.storage.sql,\n * r2: this.env.R2,\n * name: () => this.name\n * });\n * ```\n */\n workspace!: Workspace;\n\n constructor(ctx: DurableObjectState, env: Env) {\n super(ctx, env);\n\n const _onStart = this.onStart.bind(this);\n this.onStart = async () => {\n // 1. Workspace initialization\n if (!this.workspace) {\n this.workspace = new Workspace({\n sql: this.ctx.storage.sql,\n name: () => this.name\n });\n }\n\n // 2. Session configuration (builder phase — context blocks, compaction, skills)\n const baseSession = Session.create(this);\n this.session = await this.configureSession(baseSession);\n\n // Force Session to initialize its tables (assistant_messages,\n // assistant_config, etc.) so that subsequent config reads work.\n this.session.getHistory();\n\n // 3-6. Extension initialization (if extensionLoader is set)\n if (this.extensionLoader) {\n await this._initializeExtensions();\n }\n\n // 7. Protocol handlers\n this._resumableStream = new ResumableStream(this.sql.bind(this));\n this._restoreClientTools();\n this._restoreBody();\n this._setupProtocolHandlers();\n\n // 8. User's onStart\n await _onStart();\n };\n }\n\n /**\n * Conversation history. Computed from the active session.\n * Always fresh — reads from Session's tree-structured storage.\n */\n get messages(): UIMessage[] {\n return this.session.getHistory() as UIMessage[];\n }\n\n private _aborts = new AbortRegistry();\n private _turnQueue = new TurnQueue();\n private _resumableStream!: ResumableStream;\n private _pendingResumeConnections: Set<string> = new Set();\n private _lastClientTools: ClientToolSchema[] | undefined;\n private _lastBody: Record<string, unknown> | undefined;\n private _continuation = new ContinuationState();\n private _continuationTimer: ReturnType<typeof setTimeout> | null = null;\n private _insideResponseHook = false;\n private _insideInferenceLoop = false;\n private _pendingInteractionPromise: Promise<boolean> | null = null;\n private _submitSequence = 0;\n private _latestOverlappingSubmitSequence = 0;\n private _activeDebounceTimer: ReturnType<typeof setTimeout> | null = null;\n private _activeDebounceResolve: (() => void) | null = null;\n private static MESSAGE_DEBOUNCE_MS = 750;\n\n // ── Dynamic config ──────────────────────────────────────────────\n\n #configCache: Config | null = null;\n\n /**\n * Persist a typed configuration object.\n * Stored in Session's assistant_config table — survives restarts and hibernation.\n */\n configure(config: Config): void {\n const json = JSON.stringify(config);\n this._configSet(\"_think_config\", json);\n this.#configCache = config;\n }\n\n /**\n * Read the persisted configuration, or null if never configured.\n */\n getConfig(): Config | null {\n if (this.#configCache) return this.#configCache;\n const raw = this._configGet(\"_think_config\");\n if (raw !== undefined) {\n this.#configCache = JSON.parse(raw) as Config;\n return this.#configCache;\n }\n return null;\n }\n\n // ── Config storage helpers (assistant_config table) ─────────────\n\n #configTableReady = false;\n\n private _ensureConfigTable(): void {\n if (this.#configTableReady) return;\n this.sql`\n CREATE TABLE IF NOT EXISTS assistant_config (\n session_id TEXT NOT NULL,\n key TEXT NOT NULL,\n value TEXT NOT NULL,\n PRIMARY KEY (session_id, key)\n )\n `;\n this.#configTableReady = true;\n }\n\n private _configSet(key: string, value: string): void {\n this._ensureConfigTable();\n const sessionId = this._sessionId();\n this.sql`\n INSERT OR REPLACE INTO assistant_config (session_id, key, value)\n VALUES (${sessionId}, ${key}, ${value})\n `;\n }\n\n private _configGet(key: string): string | undefined {\n this._ensureConfigTable();\n const sessionId = this._sessionId();\n const rows = this.sql<{ value: string }>`\n SELECT value FROM assistant_config\n WHERE session_id = ${sessionId} AND key = ${key}\n `;\n return rows[0]?.value;\n }\n\n private _configDelete(key: string): void {\n this._ensureConfigTable();\n const sessionId = this._sessionId();\n this.sql`\n DELETE FROM assistant_config\n WHERE session_id = ${sessionId} AND key = ${key}\n `;\n }\n\n private _sessionId(): string {\n return \"\";\n }\n\n // ── Configuration overrides ─────────────────────────────────────\n\n /**\n * Return the language model to use for inference.\n * Must be overridden by subclasses.\n */\n getModel(): LanguageModel {\n throw new Error(\"Override getModel() to return a LanguageModel.\");\n }\n\n /**\n * Return the system prompt for the assistant.\n * Used as fallback when no context blocks are configured via `configureSession`.\n */\n getSystemPrompt(): string {\n return \"You are a helpful assistant.\";\n }\n\n /** Return the tools available to the assistant. */\n getTools(): ToolSet {\n return {};\n }\n\n /** Maximum number of tool-call steps per turn. Override via property or per-turn via TurnConfig. */\n maxSteps = 10;\n\n /**\n * Configure the session. Called once during `onStart`.\n * Override to add context blocks, compaction, search, skills.\n *\n * @example\n * ```typescript\n * configureSession(session: Session) {\n * return session\n * .withContext(\"memory\", { description: \"Learned facts\", maxTokens: 2000 })\n * .withCachedPrompt();\n * }\n * ```\n */\n configureSession(session: Session): Session | Promise<Session> {\n return session;\n }\n\n /**\n * Return sandboxed extension configurations. Defines load order,\n * which determines hook execution order.\n * Requires `extensionLoader` to be set.\n */\n getExtensions(): ExtensionConfig[] {\n return [];\n }\n\n // ── Lifecycle hooks ───────────────────────────────────────────\n\n /**\n * Called before `streamText` — inspect the assembled context and\n * return overrides. Think assembles tools, system prompt, and messages\n * internally; this hook sees the result and can override any part.\n *\n * Return `void` to accept all defaults.\n *\n * @example Switch model for continuations\n * ```typescript\n * beforeTurn(ctx: TurnContext) {\n * if (ctx.continuation) return { model: this.cheapModel };\n * }\n * ```\n *\n * @example Restrict active tools\n * ```typescript\n * beforeTurn(ctx: TurnContext) {\n * return { activeTools: [\"read\", \"write\"] };\n * }\n * ```\n */\n beforeTurn(\n _ctx: TurnContext\n ): TurnConfig | void | Promise<TurnConfig | void> {}\n\n /**\n * Called **before** the tool's `execute` function runs. Think wraps\n * every tool's `execute` so it can consult this hook and act on the\n * returned `ToolCallDecision`:\n *\n * - `void` (or `{ action: \"allow\" }` with no `input`) — run the\n * original `execute` with the original input.\n * - `{ action: \"allow\", input }` — run the original `execute` with\n * the substituted input.\n * - `{ action: \"block\", reason }` — skip `execute`; the model sees\n * `reason` as the tool's output.\n * - `{ action: \"substitute\", output }` — skip `execute`; the model\n * sees `output` as the tool's output.\n *\n * Only fires for server-side tools (tools with `execute`). Client\n * tools are handled on the client — Think can't intercept them.\n *\n * `afterToolCall` always fires after this hook (or after the original\n * `execute` when `allow`). For `block`/`substitute`, the substituted\n * value flows through `afterToolCall` as `success: true, output: ...`.\n *\n * @example Log tool calls\n * ```typescript\n * beforeToolCall(ctx: ToolCallContext) {\n * console.log(`Tool called: ${ctx.toolName}`, ctx.input);\n * }\n * ```\n *\n * @example Block a tool the model shouldn't be calling here\n * ```typescript\n * beforeToolCall(ctx: ToolCallContext): ToolCallDecision | void {\n * if (ctx.toolName === \"delete\" && this.isReadOnlyMode) {\n * return { action: \"block\", reason: \"delete is disabled in read-only mode\" };\n * }\n * }\n * ```\n *\n * @example Substitute a cached result\n * ```typescript\n * async beforeToolCall(ctx: ToolCallContext): Promise<ToolCallDecision | void> {\n * if (ctx.toolName === \"weather\") {\n * const cached = await this.cache.get(JSON.stringify(ctx.input));\n * if (cached) return { action: \"substitute\", output: cached };\n * }\n * }\n * ```\n */\n beforeToolCall(\n _ctx: ToolCallContext\n ): ToolCallDecision | void | Promise<ToolCallDecision | void> {}\n\n /**\n * Called **after** a tool's outcome is known — for real executions, for\n * `block` (carries the `reason` as `output`), and for `substitute`\n * (carries the substituted `output`). Backed by the AI SDK's\n * `experimental_onToolCallFinish`, so `durationMs` and the discriminated\n * `success`/`output`/`error` outcome reflect what the model actually\n * sees: a thrown error from the original `execute` becomes\n * `success: false, error: ...`; everything else (including blocked /\n * substituted calls) is `success: true, output: ...`.\n *\n * Override for logging, metrics, or result inspection.\n *\n * @example\n * ```typescript\n * afterToolCall(ctx: ToolCallResultContext) {\n * if (ctx.success) {\n * console.log(`${ctx.toolName} ok in ${ctx.durationMs}ms`);\n * } else {\n * console.error(`${ctx.toolName} failed:`, ctx.error);\n * }\n * }\n * ```\n */\n afterToolCall(_ctx: ToolCallResultContext): void | Promise<void> {}\n\n /**\n * Called after each step completes (initial, continue, tool-result).\n * Override for step-level logging or analytics.\n */\n onStepFinish(_ctx: StepContext): void | Promise<void> {}\n\n /**\n * Called for each streaming chunk. High-frequency — fires per token.\n * Override for streaming analytics, progress indicators, or token counting.\n * Observational only (void return).\n */\n onChunk(_ctx: ChunkContext): void | Promise<void> {}\n\n /**\n * Called after a chat turn completes and the assistant message has been\n * persisted. The turn lock is released before this hook runs, so it is\n * safe to call other methods from inside.\n *\n * Fires for all turn completion paths: WebSocket chat requests,\n * sub-agent RPC, and auto-continuation.\n *\n * Override for logging, chaining, analytics, usage tracking.\n */\n onChatResponse(_result: ChatResponseResult): void | Promise<void> {}\n\n /**\n * Handle an error that occurred during a chat turn.\n * Override to customize error handling (e.g. logging, metrics).\n */\n onChatError(error: unknown): unknown {\n return error;\n }\n\n // ── Extension initialization ───────────────────────────────────\n\n private async _initializeExtensions(): Promise<void> {\n const { ExtensionManager } = await import(\"./extensions/manager\");\n const { sanitizeName } = await import(\"./extensions/manager\");\n\n // 3. Create ExtensionManager with host binding if HostBridgeLoopback\n // is re-exported from the worker entry point.\n const agentClassName = this.constructor.name;\n const agentId = this.ctx.id.toString();\n const ctxExports = (this.ctx as unknown as Record<string, unknown>)\n .exports as Record<string, unknown> | undefined;\n const hasBridge =\n ctxExports && typeof ctxExports.HostBridgeLoopback === \"function\";\n\n this.extensionManager = new ExtensionManager({\n loader: this.extensionLoader!,\n storage: this.ctx.storage,\n ...(hasBridge\n ? {\n createHostBinding: (\n permissions: import(\"./extensions/types\").ExtensionPermissions,\n ownContextLabels: string[]\n ) =>\n (\n ctxExports.HostBridgeLoopback as (opts: {\n props: Record<string, unknown>;\n }) => Fetcher\n )({\n props: {\n agentClassName,\n agentId,\n permissions,\n ownContextLabels\n }\n })\n }\n : {})\n });\n\n // 4. Load static extensions from getExtensions()\n const configs = this.getExtensions();\n for (const config of configs) {\n await this.extensionManager.load(config.manifest, config.source);\n }\n\n // 5. Restore dynamic extensions from DO storage\n await this.extensionManager.restore();\n\n // 6. Register extension context blocks in Session (mutation phase).\n // Context blocks use SQLite-backed AgentContextProvider (no bridge\n // delegation to the extension Worker). Extensions write to their\n // blocks via host.setContext() (Phase 3). Bridge providers that\n // delegate to extension Worker RPC methods are Phase 4.\n for (const ext of this.extensionManager.list()) {\n const manifest = this.extensionManager.getManifest(ext.name);\n if (!manifest?.context) continue;\n\n const prefix = sanitizeName(ext.name);\n for (const ctxDef of manifest.context) {\n const namespacedLabel = `${prefix}_${ctxDef.label}`;\n await this.session.addContext(namespacedLabel, {\n description: ctxDef.description,\n maxTokens: ctxDef.maxTokens\n });\n }\n }\n\n // Wire unload callback to clean up context blocks\n this.extensionManager.onUnload(async (_name, contextLabels) => {\n for (const label of contextLabels) {\n this.session.removeContext(label);\n }\n await this.session.refreshSystemPrompt();\n });\n }\n\n // ── Inference loop (Think owns this) ──────────────────────────\n\n /**\n * The single convergence point for all chat turn entry paths.\n * Merges tools, assembles context, fires lifecycle hooks, wraps tools\n * for interception, and calls streamText.\n */\n private async _runInferenceLoop(input: TurnInput): Promise<StreamableResult> {\n if (this.waitForMcpConnections) {\n const timeout =\n typeof this.waitForMcpConnections === \"object\"\n ? this.waitForMcpConnections.timeout\n : 10_000;\n await this.mcp.waitForConnections({ timeout });\n }\n\n const workspaceTools = createWorkspaceTools(this.workspace);\n const baseTools = this.getTools();\n const extensionTools = this.extensionManager?.getTools() ?? {};\n const contextTools = await this.session.tools();\n const clientToolSet = createToolsFromClientSchemas(input.clientTools);\n const tools: ToolSet = {\n ...workspaceTools,\n ...baseTools,\n ...extensionTools,\n ...contextTools,\n ...(this.mcp?.getAITools?.() ?? {}),\n ...clientToolSet,\n ...input.callerTools\n };\n\n const frozenPrompt = await this.session.freezeSystemPrompt();\n const system = frozenPrompt || this.getSystemPrompt();\n\n const history = this.session.getHistory();\n const truncated = truncateOlderMessages(history) as UIMessage[];\n const messages = pruneMessages({\n messages: await convertToModelMessages(truncated),\n toolCalls: \"before-last-2-messages\"\n });\n\n if (messages.length === 0) {\n throw new Error(\n \"No messages to send to the model. This usually means the chat request \" +\n \"arrived before any messages were persisted.\"\n );\n }\n\n const model = this.getModel();\n const ctx: TurnContext = {\n system,\n messages,\n tools,\n model,\n continuation: input.continuation,\n body: input.body\n };\n\n const subclassConfig = (await this.beforeTurn(ctx)) ?? {};\n const config = await this._pipelineExtensionBeforeTurn(ctx, subclassConfig);\n\n const finalModel = config.model ?? model;\n const finalSystem = config.system ?? system;\n const finalMessages = config.messages ?? messages;\n const mergedTools: ToolSet = config.tools\n ? { ...tools, ...config.tools }\n : tools;\n // Wrap each tool's `execute` so `beforeToolCall` is consulted before\n // the tool actually runs. The wrapped `execute` honors the returned\n // `ToolCallDecision` — `block` short-circuits with `reason`,\n // `substitute` returns `output` directly, `allow` runs the original\n // (optionally with modified `input`).\n const finalTools: ToolSet = this._wrapToolsWithDecision(mergedTools);\n const finalMaxSteps = config.maxSteps ?? this.maxSteps;\n\n const result = streamText({\n model: finalModel,\n system: finalSystem,\n messages: finalMessages,\n tools: finalTools,\n activeTools: config.activeTools,\n toolChoice: config.toolChoice,\n stopWhen: stepCountIs(finalMaxSteps),\n providerOptions: config.providerOptions as\n | Parameters<typeof streamText>[0][\"providerOptions\"]\n | undefined,\n abortSignal: input.signal,\n onChunk: async (event) => {\n // Pass the AI SDK's chunk event through unchanged — gives users\n // access to the discriminated `TextStreamPart` chunk with all\n // provider metadata.\n await this.onChunk(event);\n await this._pipelineExtensionChunk(event);\n },\n onStepFinish: async (event) => {\n // Pass the full StepResult through — gives users access to\n // reasoning, sources, files, providerMetadata (cache tokens),\n // request/response, warnings, and the full LanguageModelUsage\n // that the AI SDK provides.\n await this.onStepFinish(event);\n await this._pipelineExtensionStepFinish(event);\n },\n // `beforeToolCall` is dispatched from the wrapped `execute` (see\n // `_wrapToolsWithDecision` above) so the returned `ToolCallDecision`\n // can actually intercept the call. `afterToolCall` is wired through\n // the AI SDK's `experimental_onToolCallFinish` callback so we get\n // accurate `durationMs` and the discriminated `success`/`error`\n // outcome — including failures that propagate out of `execute`.\n experimental_onToolCallFinish: (async (event) => {\n const base = {\n ...event.toolCall,\n stepNumber: event.stepNumber,\n messages: event.messages,\n durationMs: event.durationMs\n };\n const ctx = (\n event.success\n ? { ...base, success: true as const, output: event.output }\n : { ...base, success: false as const, error: event.error }\n ) as ToolCallResultContext;\n await this.afterToolCall(ctx);\n await this._pipelineExtensionToolCallFinish(event);\n }) satisfies StreamTextOnToolCallFinishCallback<ToolSet>\n });\n\n return this._transformInferenceResult(result);\n }\n\n /** @internal Test seam — override in test agents to wrap the stream (e.g. error injection). */\n protected _transformInferenceResult(\n result: StreamableResult\n ): StreamableResult {\n return result;\n }\n\n /** Default hook timeout in milliseconds. */\n hookTimeout = 5000;\n\n /**\n * Pipeline beforeTurn through sandboxed extensions in load order.\n * Each extension sees the accumulated state from prior extensions\n * (snapshot is rebuilt after each extension's modifications).\n * Results are merged with last-write-wins for scalar fields.\n * Extensions that don't subscribe to beforeTurn are skipped.\n */\n private async _pipelineExtensionBeforeTurn(\n ctx: TurnContext,\n subclassConfig: TurnConfig\n ): Promise<TurnConfig> {\n if (!this.extensionManager) return subclassConfig;\n\n const subscribers = this.extensionManager.getHookSubscribers(\"beforeTurn\");\n if (subscribers.length === 0) return subclassConfig;\n\n const { createTurnContextSnapshot, parseHookResult } =\n await import(\"./extensions/hook-proxy\");\n\n let snapshot = createTurnContextSnapshot(ctx);\n let accumulated = { ...subclassConfig };\n\n // Apply subclass config to the initial snapshot so extensions\n // see the subclass overrides\n if (accumulated.system !== undefined) snapshot.system = accumulated.system;\n if (accumulated.maxSteps !== undefined)\n snapshot.messageCount = ctx.messages.length;\n\n for (const sub of subscribers) {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n const resultJson = await Promise.race([\n sub.entrypoint.hook(\"beforeTurn\", snapshot),\n new Promise<string>((_, reject) => {\n timer = setTimeout(\n () => reject(new Error(`Hook timeout: ${sub.name}`)),\n this.hookTimeout\n );\n })\n ]);\n\n const parsed = parseHookResult(resultJson);\n if (\"config\" in parsed) {\n // Merge serializable scalars only. model and tools are skipped —\n // sandboxed extensions can't return LanguageModel or AI SDK Tool\n // objects (not serializable across RPC). Use activeTools to\n // control which tools the model can call.\n if (parsed.config.system !== undefined)\n accumulated.system = parsed.config.system;\n if (parsed.config.messages !== undefined)\n accumulated.messages = parsed.config.messages;\n if (parsed.config.activeTools !== undefined)\n accumulated.activeTools = parsed.config.activeTools;\n if (parsed.config.toolChoice !== undefined)\n accumulated.toolChoice = parsed.config.toolChoice;\n if (parsed.config.maxSteps !== undefined)\n accumulated.maxSteps = parsed.config.maxSteps;\n if (parsed.config.providerOptions !== undefined) {\n accumulated.providerOptions = {\n ...(accumulated.providerOptions ?? {}),\n ...parsed.config.providerOptions\n };\n }\n // Update snapshot so next extension sees this extension's changes\n if (accumulated.system !== undefined)\n snapshot = { ...snapshot, system: accumulated.system };\n if (accumulated.activeTools !== undefined)\n snapshot = { ...snapshot, toolNames: accumulated.activeTools };\n } else if (\"error\" in parsed) {\n console.warn(\n `[Think] Extension \"${sub.name}\" beforeTurn error:`,\n parsed.error\n );\n }\n } catch (err) {\n console.warn(\n `[Think] Extension \"${sub.name}\" beforeTurn failed:`,\n err instanceof Error ? err.message : err\n );\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n }\n\n return accumulated;\n }\n\n /**\n * Dispatch an observation hook to all extensions that subscribe to it.\n *\n * Used by `_pipelineExtensionToolCallStart`, `_pipelineExtensionToolCallFinish`,\n * `_pipelineExtensionStepFinish`, and `_pipelineExtensionChunk`. Unlike\n * `beforeTurn`, these hooks are observation-only — extensions can't\n * influence the turn — so we ignore return values, log errors, and\n * apply a per-extension timeout.\n *\n * `onChunk` is high-frequency (per token) — extensions that subscribe\n * to it pay an RPC cost per chunk and should be used sparingly.\n */\n private async _dispatchExtensionObservation(\n hookName: \"beforeToolCall\" | \"afterToolCall\" | \"onStepFinish\" | \"onChunk\",\n snapshot: unknown\n ): Promise<void> {\n if (!this.extensionManager) return;\n const subscribers = this.extensionManager.getHookSubscribers(hookName);\n if (subscribers.length === 0) return;\n\n for (const sub of subscribers) {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n await Promise.race([\n sub.entrypoint.hook(hookName, snapshot),\n new Promise<string>((_, reject) => {\n timer = setTimeout(\n () => reject(new Error(`Hook timeout: ${sub.name}`)),\n this.hookTimeout\n );\n })\n ]);\n } catch (err) {\n console.warn(\n `[Think] Extension \"${sub.name}\" ${hookName} failed:`,\n err instanceof Error ? err.message : err\n );\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n }\n }\n\n /**\n * Wrap each tool's `execute` function so the agent's `beforeToolCall`\n * hook is consulted before the tool runs. The hook can return a\n * `ToolCallDecision` to:\n *\n * - `allow` (default if `void` is returned) — run the original\n * `execute`, optionally with a substituted `input`.\n * - `block` — skip `execute` and return `reason` (or a default string)\n * as the tool result. The model sees this as the tool's output.\n * - `substitute` — skip `execute` and return `output` directly. The\n * model sees this as the tool's output.\n *\n * The wrapped `execute` also dispatches the `beforeToolCall`\n * observation snapshot to subscribed extensions. `afterToolCall` is\n * still wired through the AI SDK's `experimental_onToolCallFinish`\n * callback so we get accurate `durationMs` and proper success/error\n * discrimination — `block` and `substitute` outcomes show up as\n * `success: true` with the substituted output; uncaught throws from\n * the original `execute` show up as `success: false` with the error.\n *\n * Tools without an `execute` (output-schema-only tools, client tools\n * routed via `needsApproval`) are left untouched.\n *\n * **Streaming tools (AsyncIterable):** the AI SDK supports tools whose\n * `execute` returns `AsyncIterable<output>` to emit preliminary\n * results before a final value. This works whether the iterator is\n * returned directly (sync function, `async function*`) or wrapped in\n * a Promise (`async function execute(...) { return makeIter(); }`).\n * Because the wrapper must `await beforeToolCall` first, preliminary\n * chunks are collapsed — only the *final* yielded value reaches the\n * model. If you need true preliminary streaming, override\n * `getTools()` to provide such tools and avoid using `beforeToolCall`\n * for them (or accept the collapse).\n */\n private _wrapToolsWithDecision(tools: ToolSet): ToolSet {\n const wrapped: ToolSet = {};\n for (const [toolName, originalTool] of Object.entries(tools)) {\n const t = originalTool as Record<string, unknown>;\n const originalExecute = t.execute as\n | ((input: unknown, options: unknown) => unknown | Promise<unknown>)\n | undefined;\n if (typeof originalExecute !== \"function\") {\n wrapped[toolName] = originalTool;\n continue;\n }\n\n const isDynamic = t.type === \"dynamic\";\n\n const wrappedExecute = async (\n input: unknown,\n options: {\n toolCallId: string;\n messages: ModelMessage[];\n abortSignal?: AbortSignal;\n experimental_context?: unknown;\n }\n ): Promise<unknown> => {\n // Build the discriminated `TypedToolCall`-shaped context.\n const toolCallBase = {\n type: \"tool-call\" as const,\n toolCallId: options.toolCallId,\n toolName,\n input,\n ...(isDynamic ? { dynamic: true as const } : {})\n };\n\n const ctx = {\n ...toolCallBase,\n stepNumber: undefined,\n messages: options.messages,\n abortSignal: options.abortSignal\n } as ToolCallContext;\n\n // Subclass decision first.\n const decision = await this.beforeToolCall(ctx);\n\n // Extension observation dispatch — runs after the subclass so\n // extensions see whatever effect the subclass had on the\n // decision shape (input substitution shows up in the snapshot).\n const dispatchInput =\n decision && decision.action === \"allow\" && decision.input\n ? decision.input\n : input;\n await this._pipelineExtensionToolCallStart({\n toolCall: {\n ...toolCallBase,\n input: dispatchInput\n } as TypedToolCall<ToolSet>,\n stepNumber: undefined\n });\n\n // Resolve the decision.\n if (!decision || decision.action === \"allow\") {\n const finalInput = decision?.input ?? input;\n // Await before inspecting so we detect AsyncIterable returns\n // whether the original `execute` returned them directly (sync\n // function or `async function*`) or wrapped in a Promise (a\n // plain async function that returns an iterator). Without the\n // await, `Symbol.asyncIterator in result` would be false for\n // any `Promise<AsyncIterable>`, the collapse below would be\n // skipped, and the AI SDK would treat the iterator instance\n // itself as the final output value (broken).\n const result = await originalExecute(finalInput, options);\n // If the resolved value is an AsyncIterable (streaming tool\n // emitting preliminary outputs), collapse to the last yielded\n // value. We trade preliminary streaming for `beforeToolCall`\n // interception support.\n if (\n result != null &&\n typeof result === \"object\" &&\n Symbol.asyncIterator in (result as object)\n ) {\n let last: unknown;\n for await (const part of result as AsyncIterable<unknown>) {\n last = part;\n }\n return last;\n }\n return result;\n }\n if (decision.action === \"block\") {\n return (\n decision.reason ??\n `Tool \"${toolName}\" was blocked by beforeToolCall.`\n );\n }\n // substitute\n return decision.output;\n };\n\n wrapped[toolName] = {\n ...(originalTool as object),\n execute: wrappedExecute\n } as ToolSet[string];\n }\n return wrapped;\n }\n\n private async _pipelineExtensionToolCallStart(event: {\n toolCall: TypedToolCall<ToolSet>;\n stepNumber: number | undefined;\n }): Promise<void> {\n if (!this.extensionManager) return;\n if (this.extensionManager.getHookSubscribers(\"beforeToolCall\").length === 0)\n return;\n const { createToolCallStartSnapshot } =\n await import(\"./extensions/hook-proxy\");\n await this._dispatchExtensionObservation(\n \"beforeToolCall\",\n createToolCallStartSnapshot(event)\n );\n }\n\n private async _pipelineExtensionToolCallFinish(event: {\n toolCall: TypedToolCall<ToolSet>;\n stepNumber: number | undefined;\n durationMs: number;\n success: boolean;\n output?: unknown;\n error?: unknown;\n }): Promise<void> {\n if (!this.extensionManager) return;\n if (this.extensionManager.getHookSubscribers(\"afterToolCall\").length === 0)\n return;\n const { createToolCallFinishSnapshot } =\n await import(\"./extensions/hook-proxy\");\n await this._dispatchExtensionObservation(\n \"afterToolCall\",\n createToolCallFinishSnapshot(event)\n );\n }\n\n private async _pipelineExtensionStepFinish(\n event: StepContext\n ): Promise<void> {\n if (!this.extensionManager) return;\n if (this.extensionManager.getHookSubscribers(\"onStepFinish\").length === 0)\n return;\n const { createStepFinishSnapshot } =\n await import(\"./extensions/hook-proxy\");\n await this._dispatchExtensionObservation(\n \"onStepFinish\",\n createStepFinishSnapshot(event)\n );\n }\n\n private async _pipelineExtensionChunk(event: ChunkContext): Promise<void> {\n if (!this.extensionManager) return;\n if (this.extensionManager.getHookSubscribers(\"onChunk\").length === 0)\n return;\n const { createChunkSnapshot } = await import(\"./extensions/hook-proxy\");\n await this._dispatchExtensionObservation(\n \"onChunk\",\n createChunkSnapshot(event as { chunk: { type: string } })\n );\n }\n\n // ── Host bridge methods (called by HostBridgeLoopback via DO RPC) ──\n\n async _hostReadFile(path: string): Promise<string | null> {\n return (await this.workspace.readFile(path)) ?? null;\n }\n\n async _hostWriteFile(path: string, content: string): Promise<void> {\n await this.workspace.writeFile(path, content);\n }\n\n async _hostDeleteFile(path: string): Promise<boolean> {\n try {\n await this.workspace.rm(path);\n return true;\n } catch {\n return false;\n }\n }\n\n async _hostListFiles(\n dir: string\n ): Promise<\n Array<{ name: string; type: string; size: number; path: string }>\n > {\n const entries = await this.workspace.readDir(dir);\n return entries.map((e) => ({\n name: e.name,\n type: e.type,\n size: e.size ?? 0,\n path: e.path ?? `${dir}/${e.name}`\n }));\n }\n\n async _hostGetContext(label: string): Promise<string | null> {\n const block = this.session.getContextBlock(label);\n return block?.content ?? null;\n }\n\n async _hostSetContext(label: string, content: string): Promise<void> {\n await this.session.replaceContextBlock(label, content);\n }\n\n async _hostGetMessages(\n limit?: number\n ): Promise<Array<{ id: string; role: string; content: string }>> {\n const history = this.session.getHistory();\n const sliced =\n limit !== undefined && limit !== null\n ? limit <= 0\n ? []\n : history.slice(-limit)\n : history;\n return sliced.map((m) => ({\n id: m.id,\n role: m.role,\n content: m.parts\n .filter((p): p is { type: \"text\"; text: string } => p.type === \"text\")\n .map((p) => p.text)\n .join(\"\")\n }));\n }\n\n async _hostSendMessage(content: string): Promise<void> {\n const msg = {\n id: crypto.randomUUID(),\n role: \"user\" as const,\n parts: [{ type: \"text\" as const, text: content }]\n };\n // Append directly to session — do NOT route through saveMessages,\n // which enqueues a full turn via TurnQueue and would deadlock if\n // called during an active turn (tool execution → host.sendMessage\n // → saveMessages → TurnQueue.enqueue → awaits current turn → deadlock).\n // The injected message is visible in the next turn's history.\n await this.session.appendMessage(msg);\n }\n\n async _hostGetSessionInfo(): Promise<{\n messageCount: number;\n }> {\n return {\n messageCount: this.session.getHistory().length\n };\n }\n\n // ── Sub-agent RPC entry point ───────────────────────────────────\n\n /**\n * Run a chat turn: persist the user message, run the agentic loop,\n * stream UIMessageChunk events via callback, and persist the\n * assistant's response.\n *\n * @param userMessage The user's message (string or UIMessage)\n * @param callback Streaming callback (typically an RpcTarget from the parent)\n * @param options Optional chat options (e.g. AbortSignal)\n */\n async chat(\n userMessage: string | UIMessage,\n callback: StreamCallback,\n options?: ChatOptions\n ): Promise<void> {\n const requestId = crypto.randomUUID();\n\n await this._turnQueue.enqueue(requestId, async () => {\n const userMsg: UIMessage =\n typeof userMessage === \"string\"\n ? {\n id: crypto.randomUUID(),\n role: \"user\",\n parts: [{ type: \"text\", text: userMessage }]\n }\n : userMessage;\n\n await this.session.appendMessage(userMsg);\n\n const accumulator = new StreamAccumulator({\n messageId: crypto.randomUUID()\n });\n\n try {\n const result = await agentContext.run(\n {\n agent: this,\n connection: undefined,\n request: undefined,\n email: undefined\n },\n () =>\n this._runInferenceLoop({\n signal: options?.signal,\n callerTools: options?.tools,\n continuation: false\n })\n );\n\n this._insideInferenceLoop = true;\n let aborted = false;\n try {\n for await (const chunk of result.toUIMessageStream()) {\n if (options?.signal?.aborted) {\n aborted = true;\n break;\n }\n accumulator.applyChunk(chunk as unknown as StreamChunkData);\n await callback.onEvent(JSON.stringify(chunk));\n }\n } finally {\n this._insideInferenceLoop = false;\n }\n\n const assistantMsg = accumulator.toMessage();\n this._persistAssistantMessage(assistantMsg);\n\n if (!aborted) {\n await callback.onDone();\n await this._fireResponseHook({\n message: assistantMsg,\n requestId,\n continuation: false,\n status: \"completed\"\n });\n } else {\n await this._fireResponseHook({\n message: assistantMsg,\n requestId,\n continuation: false,\n status: \"aborted\"\n });\n }\n } catch (error) {\n const assistantMsg =\n accumulator.parts.length > 0 ? accumulator.toMessage() : null;\n if (assistantMsg) {\n this._persistAssistantMessage(assistantMsg);\n }\n\n const wrapped = this.onChatError(error);\n const errorMessage =\n wrapped instanceof Error ? wrapped.message : String(wrapped);\n\n if (assistantMsg) {\n await this._fireResponseHook({\n message: assistantMsg,\n requestId,\n continuation: false,\n status: \"error\",\n error: errorMessage\n });\n }\n\n if (callback.onError) {\n await callback.onError(errorMessage);\n } else {\n throw wrapped;\n }\n }\n });\n }\n\n // ── Message access ──────────────────────────────────────────────\n\n /** Get the conversation history as UIMessage[]. */\n getMessages(): UIMessage[] {\n return this.messages;\n }\n\n /** Clear all messages from storage. */\n clearMessages(): void {\n this.session.clearMessages();\n }\n\n // ── Programmatic API ───────────────────────────────────────────\n\n /**\n * Inject messages and trigger a model turn — without a WebSocket request.\n *\n * Use for scheduled responses, webhook-triggered turns, proactive agents,\n * or chaining from `onChatResponse`.\n *\n * Accepts static messages or a callback that derives messages from the\n * current state (useful when multiple calls queue up — the callback runs\n * with the latest messages when the turn actually starts).\n *\n * @example Scheduled follow-up\n * ```typescript\n * async onScheduled() {\n * await this.saveMessages([{\n * id: crypto.randomUUID(),\n * role: \"user\",\n * parts: [{ type: \"text\", text: \"Time for your daily summary.\" }]\n * }]);\n * }\n * ```\n *\n * @example Function form\n * ```typescript\n * await this.saveMessages((current) => [\n * ...current,\n * { id: crypto.randomUUID(), role: \"user\", parts: [{ type: \"text\", text: \"Continue.\" }] }\n * ]);\n * ```\n */\n async saveMessages(\n messages:\n | UIMessage[]\n | ((currentMessages: UIMessage[]) => UIMessage[] | Promise<UIMessage[]>)\n ): Promise<SaveMessagesResult> {\n const requestId = crypto.randomUUID();\n const clientTools = this._lastClientTools;\n const body = this._lastBody;\n const epoch = this._turnQueue.generation;\n let status: SaveMessagesResult[\"status\"] = \"completed\";\n\n await this.keepAliveWhile(async () => {\n await this._turnQueue.enqueue(requestId, async () => {\n const resolved =\n typeof messages === \"function\"\n ? await messages(this.messages)\n : messages;\n\n if (this._turnQueue.generation !== epoch) {\n status = \"skipped\";\n return;\n }\n\n for (const msg of resolved) {\n await this.session.appendMessage(msg);\n }\n this._broadcastMessages();\n\n if (this._turnQueue.generation !== epoch) {\n status = \"skipped\";\n return;\n }\n\n const abortSignal = this._aborts.getSignal(requestId);\n try {\n const programmaticBody = async () => {\n const result = await agentContext.run(\n {\n agent: this,\n connection: undefined,\n request: undefined,\n email: undefined\n },\n () =>\n this._runInferenceLoop({\n signal: abortSignal,\n clientTools,\n body,\n continuation: false\n })\n );\n\n if (result) {\n await this._streamResult(requestId, result, abortSignal);\n }\n };\n\n if (this.chatRecovery) {\n await this.runFiber(\n `${(this.constructor as typeof Think).CHAT_FIBER_NAME}:${requestId}`,\n async () => {\n await programmaticBody();\n }\n );\n } else {\n await programmaticBody();\n }\n } finally {\n this._aborts.remove(requestId);\n }\n });\n });\n\n if (this._turnQueue.generation !== epoch && status === \"completed\") {\n status = \"skipped\";\n }\n\n return { requestId, status };\n }\n\n /**\n * Run a new LLM call following the last assistant message.\n *\n * The model sees the full conversation (including the last assistant\n * response) and generates a new response. The new response is persisted\n * as a separate assistant message. Building block for chat recovery\n * (Phase 4), \"generate more\" buttons, and self-correction.\n *\n * Note: this creates a new message, not an append to the existing one.\n * True continuation-as-append (chunk rewriting) is planned for Phase 4.\n *\n * Returns early with `status: \"skipped\"` if there is no assistant message\n * to continue from.\n */\n protected async continueLastTurn(\n body?: Record<string, unknown>\n ): Promise<SaveMessagesResult> {\n const lastLeaf = this.session.getLatestLeaf();\n if (!lastLeaf || lastLeaf.role !== \"assistant\") {\n return { requestId: \"\", status: \"skipped\" };\n }\n\n const requestId = crypto.randomUUID();\n const clientTools = this._lastClientTools;\n const resolvedBody = body ?? this._lastBody;\n const epoch = this._turnQueue.generation;\n let status: SaveMessagesResult[\"status\"] = \"completed\";\n\n await this.keepAliveWhile(async () => {\n await this._turnQueue.enqueue(requestId, async () => {\n if (this._turnQueue.generation !== epoch) {\n status = \"skipped\";\n return;\n }\n\n const abortSignal = this._aborts.getSignal(requestId);\n try {\n const continueTurnBody = async () => {\n const result = await agentContext.run(\n {\n agent: this,\n connection: undefined,\n request: undefined,\n email: undefined\n },\n () =>\n this._runInferenceLoop({\n signal: abortSignal,\n clientTools,\n body: resolvedBody,\n continuation: true\n })\n );\n\n if (result) {\n await this._streamResult(requestId, result, abortSignal, {\n continuation: true\n });\n }\n };\n\n if (this.chatRecovery) {\n await this.runFiber(\n `${(this.constructor as typeof Think).CHAT_FIBER_NAME}:${requestId}`,\n async () => {\n await continueTurnBody();\n }\n );\n } else {\n await continueTurnBody();\n }\n } finally {\n this._aborts.remove(requestId);\n }\n });\n });\n\n if (this._turnQueue.generation !== epoch && status === \"completed\") {\n status = \"skipped\";\n }\n\n return { requestId, status };\n }\n\n // ── WebSocket protocol ──────────────────────────────────────────\n\n private _setupProtocolHandlers() {\n const _onConnect = this.onConnect.bind(this);\n this.onConnect = async (\n connection: Connection,\n ctx: { request: Request }\n ) => {\n if (this._resumableStream.hasActiveStream()) {\n this._notifyStreamResuming(connection);\n }\n connection.send(\n JSON.stringify({\n type: MSG_CHAT_MESSAGES,\n messages: this.messages\n })\n );\n return _onConnect(connection, ctx);\n };\n\n const _onClose = this.onClose.bind(this);\n this.onClose = async (\n connection: Connection,\n code: number,\n reason: string,\n wasClean: boolean\n ) => {\n this._pendingResumeConnections.delete(connection.id);\n this._continuation.awaitingConnections.delete(connection.id);\n if (this._continuation.pending?.connectionId === connection.id) {\n this._continuation.pending = null;\n }\n if (this._continuation.activeConnectionId === connection.id) {\n this._continuation.activeConnectionId = null;\n }\n return _onClose(connection, code, reason, wasClean);\n };\n\n const _onMessage = this.onMessage.bind(this);\n this.onMessage = async (connection: Connection, message: WSMessage) => {\n if (typeof message === \"string\") {\n const event = parseProtocolMessage(message);\n if (event) {\n await this._handleProtocolEvent(connection, event);\n return;\n }\n }\n return _onMessage(connection, message);\n };\n\n const _onRequest = this.onRequest.bind(this);\n this.onRequest = async (request: Request) => {\n const url = new URL(request.url);\n if (\n url.pathname === \"/get-messages\" ||\n url.pathname.endsWith(\"/get-messages\")\n ) {\n return Response.json(this.messages);\n }\n return _onRequest(request);\n };\n }\n\n private async _handleProtocolEvent(\n connection: Connection,\n event: NonNullable<ReturnType<typeof parseProtocolMessage>>\n ): Promise<void> {\n switch (event.type) {\n case \"stream-resume-request\":\n this._handleStreamResumeRequest(connection);\n break;\n\n case \"stream-resume-ack\":\n this._handleStreamResumeAck(connection, event.id);\n break;\n\n case \"chat-request\":\n if (event.init?.method === \"POST\") {\n await this._handleChatRequest(connection, event);\n }\n break;\n\n case \"tool-result\": {\n if (\n event.clientTools &&\n Array.isArray(event.clientTools) &&\n event.clientTools.length > 0\n ) {\n this._lastClientTools = event.clientTools as ClientToolSchema[];\n this._persistClientTools();\n }\n const resultPromise = Promise.resolve().then(() => {\n this._applyToolResult(\n event.toolCallId,\n event.output,\n event.state as \"output-error\" | undefined,\n event.errorText\n );\n return true;\n });\n this._pendingInteractionPromise = resultPromise;\n resultPromise\n .finally(() => {\n if (this._pendingInteractionPromise === resultPromise) {\n this._pendingInteractionPromise = null;\n }\n })\n .catch(() => {});\n if (event.autoContinue) {\n this._scheduleAutoContinuation(connection);\n }\n break;\n }\n\n case \"tool-approval\": {\n const approvalPromise = Promise.resolve().then(() => {\n this._applyToolApproval(event.toolCallId, event.approved);\n return true;\n });\n this._pendingInteractionPromise = approvalPromise;\n approvalPromise\n .finally(() => {\n if (this._pendingInteractionPromise === approvalPromise) {\n this._pendingInteractionPromise = null;\n }\n })\n .catch(() => {});\n if (event.autoContinue) {\n this._scheduleAutoContinuation(connection);\n }\n break;\n }\n\n case \"clear\":\n this._handleClear(connection);\n break;\n\n case \"cancel\":\n this._aborts.cancel(event.id);\n break;\n\n case \"messages\":\n break;\n }\n }\n\n private _handleStreamResumeRequest(connection: Connection): void {\n if (this._resumableStream.hasActiveStream()) {\n if (\n this._continuation.activeRequestId ===\n this._resumableStream.activeRequestId &&\n this._continuation.activeConnectionId !== null &&\n this._continuation.activeConnectionId !== connection.id\n ) {\n connection.send(JSON.stringify({ type: MSG_STREAM_RESUME_NONE }));\n } else {\n this._notifyStreamResuming(connection);\n }\n } else if (\n this._continuation.pending !== null &&\n this._continuation.pending.connectionId === connection.id\n ) {\n this._continuation.awaitingConnections.set(connection.id, connection);\n } else {\n connection.send(JSON.stringify({ type: MSG_STREAM_RESUME_NONE }));\n }\n }\n\n private _handleStreamResumeAck(\n connection: Connection,\n requestId: string\n ): void {\n this._pendingResumeConnections.delete(connection.id);\n if (\n this._resumableStream.hasActiveStream() &&\n this._resumableStream.activeRequestId === requestId\n ) {\n const orphanedStreamId = this._resumableStream.replayChunks(\n connection,\n this._resumableStream.activeRequestId\n );\n if (orphanedStreamId) {\n this._persistOrphanedStream(orphanedStreamId);\n }\n }\n }\n\n private async _handleChatRequest(\n connection: Connection,\n event: Extract<\n NonNullable<ReturnType<typeof parseProtocolMessage>>,\n { type: \"chat-request\" }\n >\n ) {\n if (!event.init?.body) return;\n\n let rawParsed: Record<string, unknown>;\n try {\n rawParsed = JSON.parse(event.init.body) as Record<string, unknown>;\n } catch {\n return;\n }\n\n const {\n messages: incomingMessages,\n clientTools: rawClientTools,\n trigger: rawTrigger,\n ...customBody\n } = rawParsed as {\n messages?: UIMessage[];\n clientTools?: ClientToolSchema[];\n trigger?: string;\n [key: string]: unknown;\n };\n if (!Array.isArray(incomingMessages)) return;\n\n const isRegeneration = rawTrigger === \"regenerate-message\";\n const isSubmitMessage = !isRegeneration;\n const requestId = event.id;\n\n // ── Concurrency decision (before persisting anything) ────────\n const concurrencyDecision =\n this._getSubmitConcurrencyDecision(isSubmitMessage);\n\n if (concurrencyDecision.action === \"drop\") {\n this._rollbackDroppedSubmit(connection);\n this._completeSkippedRequest(connection, requestId);\n return;\n }\n\n // ── Persist client tools and body (only for accepted requests) ──\n const requestClientTools =\n rawClientTools && rawClientTools.length > 0 ? rawClientTools : undefined;\n if (requestClientTools) {\n this._lastClientTools = requestClientTools;\n this._persistClientTools();\n } else if (rawClientTools !== undefined) {\n this._lastClientTools = undefined;\n this._persistClientTools();\n }\n\n const requestBody =\n Object.keys(customBody).length > 0 ? customBody : undefined;\n this._lastBody = requestBody;\n this._persistBody();\n\n // ── Persist and broadcast user messages ──────────────────────\n const clientToolsForTurn = this._lastClientTools;\n const bodyForTurn = this._lastBody;\n\n let branchParentId: string | undefined;\n if (isRegeneration && incomingMessages.length > 0) {\n branchParentId = incomingMessages[incomingMessages.length - 1].id;\n }\n\n for (const msg of incomingMessages) {\n await this.session.appendMessage(msg);\n }\n\n this._broadcastMessages([connection.id]);\n\n // ── Enter turn queue ────────────────────────────────────────\n const abortSignal = this._aborts.getSignal(requestId);\n const epoch = this._turnQueue.generation;\n\n try {\n await this.keepAliveWhile(async () => {\n const turnResult = await this._turnQueue.enqueue(\n requestId,\n async () => {\n // Superseded by a later overlapping submit (latest/merge/debounce)\n if (this._isSupersededSubmit(concurrencyDecision.submitSequence)) {\n this._completeSkippedRequest(connection, requestId);\n return;\n }\n\n // Debounce: wait for quiet period\n if (concurrencyDecision.debounceUntilMs !== null) {\n await this._waitForTimestamp(concurrencyDecision.debounceUntilMs);\n\n if (this._turnQueue.generation !== epoch) {\n this._completeSkippedRequest(connection, requestId);\n return;\n }\n if (\n this._isSupersededSubmit(concurrencyDecision.submitSequence)\n ) {\n this._completeSkippedRequest(connection, requestId);\n return;\n }\n }\n\n const chatTurnBody = async () => {\n const result = await agentContext.run(\n {\n agent: this,\n connection,\n request: undefined,\n email: undefined\n },\n () =>\n this._runInferenceLoop({\n signal: abortSignal,\n clientTools: clientToolsForTurn,\n body: bodyForTurn,\n continuation: false\n })\n );\n\n if (result) {\n await this._streamResult(requestId, result, abortSignal, {\n parentId: branchParentId\n });\n } else {\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"No response was generated.\",\n done: true\n });\n }\n };\n\n if (this.chatRecovery) {\n await this.runFiber(\n `${(this.constructor as typeof Think).CHAT_FIBER_NAME}:${requestId}`,\n async () => {\n await chatTurnBody();\n }\n );\n } else {\n await chatTurnBody();\n }\n }\n );\n\n if (turnResult.status === \"stale\") {\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"\",\n done: true\n });\n }\n });\n } catch (error) {\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: error instanceof Error ? error.message : \"Error\",\n done: true,\n error: true\n });\n } finally {\n this._aborts.remove(requestId);\n }\n }\n\n /**\n * Abort the active turn, invalidate queued turns, and reset\n * concurrency/continuation state. Call this when intercepting\n * clear events or implementing custom reset logic.\n *\n * Does NOT clear messages, streams, or persisted state —\n * only turn execution state.\n */\n protected resetTurnState(): void {\n this._turnQueue.reset();\n this._aborts.destroyAll();\n if (this._continuationTimer) {\n clearTimeout(this._continuationTimer);\n this._continuationTimer = null;\n }\n this._cancelActiveDebounce();\n this._pendingInteractionPromise = null;\n this._continuation.sendResumeNone();\n this._continuation.clearAll();\n }\n\n private _handleClear(connection?: Connection) {\n this.resetTurnState();\n\n this._resumableStream.clearAll();\n this._pendingResumeConnections.clear();\n this._lastClientTools = undefined;\n this._persistClientTools();\n this._lastBody = undefined;\n this._persistBody();\n this.session.clearMessages();\n this._broadcast(\n { type: MSG_CHAT_CLEAR },\n connection ? [connection.id] : undefined\n );\n }\n\n private async _streamResult(\n requestId: string,\n result: StreamableResult,\n abortSignal?: AbortSignal,\n options?: { continuation?: boolean; parentId?: string }\n ) {\n const clearGen = this._turnQueue.generation;\n const streamId = this._resumableStream.start(requestId);\n const continuation = options?.continuation ?? false;\n const parentId = options?.parentId;\n\n if (this._continuation.pending?.requestId === requestId) {\n this._continuation.activatePending();\n this._continuation.flushAwaitingConnections((c) =>\n this._notifyStreamResuming(c as Connection)\n );\n }\n\n const accumulator = new StreamAccumulator({\n messageId: crypto.randomUUID()\n });\n\n let doneSent = false;\n let streamAborted = false;\n let streamError: string | undefined;\n\n try {\n this._insideInferenceLoop = true;\n try {\n for await (const chunk of result.toUIMessageStream()) {\n if (abortSignal?.aborted) {\n streamAborted = true;\n break;\n }\n\n const { action } = accumulator.applyChunk(\n chunk as unknown as StreamChunkData\n );\n\n if (action?.type === \"error\") {\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: action.error,\n done: false,\n error: true\n });\n continue;\n }\n\n const chunkBody = JSON.stringify(chunk);\n this._resumableStream.storeChunk(streamId, chunkBody);\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: chunkBody,\n done: false\n });\n }\n } finally {\n this._insideInferenceLoop = false;\n }\n\n this._resumableStream.complete(streamId);\n this._pendingResumeConnections.clear();\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"\",\n done: true\n });\n doneSent = true;\n } catch (error) {\n streamError = error instanceof Error ? error.message : \"Stream error\";\n this._resumableStream.markError(streamId);\n this._pendingResumeConnections.clear();\n if (!doneSent) {\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: streamError,\n done: true,\n error: true\n });\n doneSent = true;\n }\n } finally {\n if (!doneSent) {\n this._resumableStream.markError(streamId);\n this._pendingResumeConnections.clear();\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"\",\n done: true\n });\n }\n }\n\n if (\n accumulator.parts.length > 0 &&\n this._turnQueue.generation === clearGen\n ) {\n try {\n const assistantMsg = accumulator.toMessage();\n this._persistAssistantMessage(assistantMsg, parentId);\n this._broadcastMessages();\n\n await this._fireResponseHook({\n message: assistantMsg,\n requestId,\n continuation,\n status: streamAborted\n ? \"aborted\"\n : streamError\n ? \"error\"\n : \"completed\",\n error: streamError\n });\n } catch (e) {\n console.error(\"Failed to persist assistant message:\", e);\n }\n }\n }\n\n // ── Session-backed persistence ──────────────────────────────────\n\n private _persistAssistantMessage(msg: UIMessage, parentId?: string): void {\n const sanitized = sanitizeMessage(msg);\n const safe = enforceRowSizeLimit(sanitized);\n\n const existing = this.session.getMessage(safe.id);\n if (existing) {\n this.session.updateMessage(safe);\n } else {\n // appendMessage is async due to potential auto-compaction, but\n // we fire-and-forget here since the message write itself is synchronous\n // in AgentSessionProvider — only the optional compaction is async.\n // parentId is set for regeneration — the new response branches from\n // the same parent as the old one rather than appending to the latest leaf.\n void this.session.appendMessage(safe, parentId);\n }\n }\n\n private _persistClientTools(): void {\n if (this._lastClientTools) {\n this._configSet(\"lastClientTools\", JSON.stringify(this._lastClientTools));\n } else {\n this._configDelete(\"lastClientTools\");\n }\n }\n\n private _restoreClientTools(): void {\n const raw = this._configGet(\"lastClientTools\");\n if (raw) {\n try {\n this._lastClientTools = JSON.parse(raw);\n } catch {\n this._lastClientTools = undefined;\n }\n }\n }\n\n private _persistBody(): void {\n if (this._lastBody) {\n this._configSet(\"lastBody\", JSON.stringify(this._lastBody));\n } else {\n this._configDelete(\"lastBody\");\n }\n }\n\n private _restoreBody(): void {\n const raw = this._configGet(\"lastBody\");\n if (raw) {\n try {\n this._lastBody = JSON.parse(raw);\n } catch {\n this._lastBody = undefined;\n }\n }\n }\n\n // ── Tool state updates (shared primitives from agents/chat) ─────\n\n private _applyToolResult(\n toolCallId: string,\n output: unknown,\n overrideState?: \"output-error\",\n errorText?: string\n ): void {\n const update = toolResultUpdate(\n toolCallId,\n output,\n overrideState,\n errorText\n );\n this._applyToolUpdateToMessages(update);\n }\n\n private _applyToolApproval(toolCallId: string, approved: boolean): void {\n const update = toolApprovalUpdate(toolCallId, approved);\n this._applyToolUpdateToMessages(update);\n }\n\n private _applyToolUpdateToMessages(update: {\n toolCallId: string;\n matchStates: string[];\n apply: (part: Record<string, unknown>) => Record<string, unknown>;\n }): void {\n const history = this.messages;\n for (const msg of history) {\n const result = applyToolUpdate(\n msg.parts as Array<Record<string, unknown>>,\n update\n );\n if (result) {\n const updatedMsg = {\n ...msg,\n parts: result.parts as UIMessage[\"parts\"]\n };\n const safe = enforceRowSizeLimit(sanitizeMessage(updatedMsg));\n this.session.updateMessage(safe);\n this._broadcast({ type: MSG_MESSAGE_UPDATED, message: safe });\n return;\n }\n }\n }\n\n // ── Stability + pending interactions ─────────────────────────────\n\n protected hasPendingInteraction(): boolean {\n return this.messages.some(\n (message) =>\n message.role === \"assistant\" &&\n this._messageHasPendingInteraction(message)\n );\n }\n\n protected async waitUntilStable(options?: {\n timeout?: number;\n }): Promise<boolean> {\n const deadline =\n options?.timeout != null ? Date.now() + options.timeout : null;\n\n while (true) {\n if (\n (await this._awaitWithDeadline(\n this._turnQueue.waitForIdle(),\n deadline\n )) === TIMED_OUT\n ) {\n return false;\n }\n\n if (!this.hasPendingInteraction()) {\n return true;\n }\n\n const pending = this._pendingInteractionPromise;\n if (pending) {\n let result: boolean | typeof TIMED_OUT;\n try {\n result = await this._awaitWithDeadline(pending, deadline);\n } catch {\n continue;\n }\n if (result === TIMED_OUT) {\n return false;\n }\n } else {\n if (\n (await this._awaitWithDeadline(\n new Promise<void>((resolve) => setTimeout(resolve, 100)),\n deadline\n )) === TIMED_OUT\n ) {\n return false;\n }\n }\n }\n }\n\n private async _awaitWithDeadline<T>(\n promise: Promise<T>,\n deadline: number | null\n ): Promise<T | typeof TIMED_OUT> {\n if (deadline == null) {\n return promise;\n }\n const remainingMs = Math.max(0, deadline - Date.now());\n let timer: ReturnType<typeof setTimeout>;\n const result = await Promise.race([\n promise,\n new Promise<typeof TIMED_OUT>((resolve) => {\n timer = setTimeout(() => resolve(TIMED_OUT), remainingMs);\n })\n ]);\n clearTimeout(timer!);\n return result;\n }\n\n private _messageHasPendingInteraction(message: UIMessage): boolean {\n return message.parts.some(\n (part) =>\n \"state\" in part &&\n ((part as Record<string, unknown>).state === \"input-available\" ||\n (part as Record<string, unknown>).state === \"approval-requested\")\n );\n }\n\n // ── Chat recovery via fibers ───────────────────────────────────\n\n protected override async _handleInternalFiberRecovery(\n ctx: FiberRecoveryContext\n ): Promise<boolean> {\n const chatPrefix = (this.constructor as typeof Think).CHAT_FIBER_NAME + \":\";\n if (!ctx.name.startsWith(chatPrefix)) {\n return false;\n }\n\n const requestId = ctx.name.slice(chatPrefix.length);\n\n let streamId = \"\";\n if (requestId) {\n const rows = this.sql<{ id: string }>`\n SELECT id FROM cf_ai_chat_stream_metadata\n WHERE request_id = ${requestId}\n ORDER BY created_at DESC LIMIT 1\n `;\n if (rows.length > 0) {\n streamId = rows[0].id;\n }\n }\n if (!streamId && this._resumableStream.hasActiveStream()) {\n streamId = this._resumableStream.activeStreamId ?? \"\";\n }\n\n const partial = streamId\n ? this._getPartialStreamText(streamId)\n : { text: \"\", parts: [] as MessagePart[] };\n\n const options = await this.onChatRecovery({\n streamId: streamId ?? \"\",\n requestId,\n partialText: partial.text,\n partialParts: partial.parts,\n recoveryData: ctx.snapshot,\n messages: [...this.messages],\n lastBody: this._lastBody,\n lastClientTools: this._lastClientTools,\n createdAt: ctx.createdAt\n });\n\n const streamStillActive =\n streamId &&\n this._resumableStream.hasActiveStream() &&\n this._resumableStream.activeStreamId === streamId;\n\n if (options.persist !== false && streamStillActive) {\n this._persistOrphanedStream(streamId);\n }\n\n if (streamStillActive) {\n this._resumableStream.complete(streamId);\n }\n\n if (options.continue !== false) {\n const lastLeaf = this.session.getLatestLeaf();\n const targetId = lastLeaf?.role === \"assistant\" ? lastLeaf.id : undefined;\n await this.schedule(\n 0,\n \"_chatRecoveryContinue\",\n targetId ? { targetAssistantId: targetId } : undefined,\n { idempotent: true }\n );\n }\n\n return true;\n }\n\n protected async onChatRecovery(\n _ctx: ChatRecoveryContext\n ): Promise<ChatRecoveryOptions> {\n return {};\n }\n\n async _chatRecoveryContinue(data?: {\n targetAssistantId?: string;\n }): Promise<void> {\n const ready = await this.waitUntilStable({ timeout: 10_000 });\n if (!ready) {\n console.warn(\n \"[Think] _chatRecoveryContinue timed out waiting for stable state, skipping continuation\"\n );\n return;\n }\n\n const targetId = data?.targetAssistantId;\n const lastLeaf = this.session.getLatestLeaf();\n if (targetId && lastLeaf?.id !== targetId) {\n return;\n }\n\n await this.continueLastTurn();\n }\n\n private _getPartialStreamText(streamId: string): {\n text: string;\n parts: MessagePart[];\n } {\n const chunks = this._resumableStream.getStreamChunks(streamId);\n const parts: MessagePart[] = [];\n\n for (const chunk of chunks) {\n try {\n const data = JSON.parse(chunk.body);\n applyChunkToParts(parts, data);\n } catch {\n // skip malformed chunks\n }\n }\n\n const text = parts\n .filter(\n (p): p is MessagePart & { type: \"text\"; text: string } =>\n p.type === \"text\" && \"text\" in p\n )\n .map((p) => p.text)\n .join(\"\");\n\n return { text, parts };\n }\n\n // ── Concurrency strategies ──────────────────────────────────────\n\n private _normalizeMessageConcurrency(): NormalizedMessageConcurrency {\n if (typeof this.messageConcurrency === \"string\") {\n return this.messageConcurrency;\n }\n const debounceMs = this.messageConcurrency.debounceMs;\n return {\n strategy: \"debounce\",\n debounceMs:\n typeof debounceMs === \"number\" &&\n Number.isFinite(debounceMs) &&\n debounceMs >= 0\n ? debounceMs\n : Think.MESSAGE_DEBOUNCE_MS\n };\n }\n\n private _getSubmitConcurrencyDecision(\n isSubmitMessage: boolean\n ): SubmitConcurrencyDecision {\n const queuedTurns = this._turnQueue.queuedCount();\n\n if (!isSubmitMessage || queuedTurns === 0) {\n return {\n action: \"execute\",\n submitSequence: null,\n debounceUntilMs: null\n };\n }\n\n const concurrency = this._normalizeMessageConcurrency();\n\n if (concurrency === \"queue\") {\n return {\n action: \"execute\",\n submitSequence: null,\n debounceUntilMs: null\n };\n }\n\n if (concurrency === \"drop\") {\n return {\n action: \"drop\",\n submitSequence: null,\n debounceUntilMs: null\n };\n }\n\n const submitSequence = ++this._submitSequence;\n this._latestOverlappingSubmitSequence = submitSequence;\n\n if (concurrency === \"latest\" || concurrency === \"merge\") {\n return {\n action: \"execute\",\n submitSequence,\n debounceUntilMs: null\n };\n }\n\n return {\n action: \"execute\",\n submitSequence,\n debounceUntilMs: Date.now() + concurrency.debounceMs\n };\n }\n\n private _isSupersededSubmit(submitSequence: number | null): boolean {\n return (\n submitSequence !== null &&\n submitSequence < this._latestOverlappingSubmitSequence\n );\n }\n\n private async _waitForTimestamp(timestampMs: number): Promise<void> {\n const remainingMs = timestampMs - Date.now();\n if (remainingMs <= 0) return;\n\n await new Promise<void>((resolve) => {\n this._activeDebounceResolve = resolve;\n this._activeDebounceTimer = setTimeout(() => {\n this._activeDebounceTimer = null;\n this._activeDebounceResolve = null;\n resolve();\n }, remainingMs);\n });\n }\n\n private _cancelActiveDebounce(): void {\n if (this._activeDebounceTimer !== null) {\n clearTimeout(this._activeDebounceTimer);\n this._activeDebounceTimer = null;\n }\n if (this._activeDebounceResolve !== null) {\n this._activeDebounceResolve();\n this._activeDebounceResolve = null;\n }\n }\n\n private _completeSkippedRequest(\n connection: Connection,\n requestId: string\n ): void {\n connection.send(\n JSON.stringify({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"\",\n done: true\n })\n );\n }\n\n private _rollbackDroppedSubmit(connection: Connection): void {\n connection.send(\n JSON.stringify({\n type: MSG_CHAT_MESSAGES,\n messages: this.messages\n })\n );\n }\n\n // ── Auto-continuation ──────────────────────────────────────────\n\n private _scheduleAutoContinuation(connection: Connection): void {\n if (this._continuation.pending?.pastCoalesce) {\n this._continuation.deferred = {\n connection,\n connectionId: connection.id,\n clientTools: this._lastClientTools,\n body: undefined,\n errorPrefix: \"[Think] Auto-continuation failed:\",\n prerequisite: null\n };\n return;\n }\n\n if (this._continuation.pending) {\n this._continuation.pending.connection = connection;\n this._continuation.pending.connectionId = connection.id;\n this._continuation.pending.clientTools = this._lastClientTools;\n this._continuation.awaitingConnections.set(connection.id, connection);\n return;\n }\n\n if (this._continuationTimer) {\n clearTimeout(this._continuationTimer);\n }\n this._continuationTimer = setTimeout(() => {\n this._continuationTimer = null;\n this._fireAutoContinuation(connection);\n }, 50);\n }\n\n private _fireAutoContinuation(connection: Connection): void {\n if (!this._continuation.pending) {\n const requestId = crypto.randomUUID();\n this._continuation.pending = {\n connection,\n connectionId: connection.id,\n requestId,\n clientTools: this._lastClientTools,\n body: undefined,\n errorPrefix: \"[Think] Auto-continuation failed:\",\n prerequisite: null,\n pastCoalesce: false\n };\n this._continuation.awaitingConnections.set(connection.id, connection);\n }\n\n const { requestId, clientTools } = this._continuation.pending!;\n const abortSignal = this._aborts.getSignal(requestId);\n\n this.keepAliveWhile(async () => {\n await this._turnQueue.enqueue(requestId, async () => {\n if (this._continuation.pending) {\n this._continuation.pending.pastCoalesce = true;\n }\n let streamed = false;\n try {\n const continuationBody = async () => {\n const result = await agentContext.run(\n {\n agent: this,\n connection,\n request: undefined,\n email: undefined\n },\n () =>\n this._runInferenceLoop({\n signal: abortSignal,\n clientTools,\n body: this._lastBody,\n continuation: true\n })\n );\n if (result) {\n await this._streamResult(requestId, result, abortSignal, {\n continuation: true\n });\n streamed = true;\n }\n };\n\n if (this.chatRecovery) {\n await this.runFiber(\n `${(this.constructor as typeof Think).CHAT_FIBER_NAME}:${requestId}`,\n async () => {\n await continuationBody();\n }\n );\n } else {\n await continuationBody();\n }\n } finally {\n this._aborts.remove(requestId);\n if (!streamed) {\n this._continuation.sendResumeNone();\n }\n this._continuation.clearPending();\n this._activateDeferredContinuation();\n }\n });\n }).catch((error) => {\n console.error(\"[Think] Auto-continuation failed:\", error);\n this._aborts.remove(requestId);\n });\n }\n\n private _activateDeferredContinuation(): void {\n const pending = this._continuation.activateDeferred(() =>\n crypto.randomUUID()\n );\n if (!pending) return;\n\n this._fireAutoContinuation(pending.connection as Connection);\n }\n\n // ── Response hook ──────────────────────────────────────────────\n\n private async _fireResponseHook(result: ChatResponseResult): Promise<void> {\n if (this._insideResponseHook) return;\n this._insideResponseHook = true;\n try {\n await this.onChatResponse(result);\n } catch (err) {\n console.error(\"[Think] onChatResponse error:\", err);\n } finally {\n this._insideResponseHook = false;\n }\n }\n\n // ── Resume helpers ──────────────────────────────────────────────\n\n private _notifyStreamResuming(connection: Connection): void {\n if (!this._resumableStream.hasActiveStream()) return;\n this._pendingResumeConnections.add(connection.id);\n connection.send(\n JSON.stringify({\n type: MSG_STREAM_RESUMING,\n id: this._resumableStream.activeRequestId\n })\n );\n }\n\n private _persistOrphanedStream(streamId: string): void {\n this._resumableStream.flushBuffer();\n const chunks = this._resumableStream.getStreamChunks(streamId);\n if (chunks.length === 0) return;\n\n const accumulator = new StreamAccumulator({\n messageId: crypto.randomUUID()\n });\n for (const chunk of chunks) {\n try {\n accumulator.applyChunk(JSON.parse(chunk.body) as StreamChunkData);\n } catch {\n // skip malformed chunks\n }\n }\n\n if (accumulator.parts.length > 0) {\n this._persistAssistantMessage(accumulator.toMessage());\n this._broadcastMessages();\n }\n }\n\n private _broadcastChat(message: Record<string, unknown>, exclude?: string[]) {\n const allExclusions = [\n ...(exclude || []),\n ...this._pendingResumeConnections\n ];\n this.broadcast(JSON.stringify(message), allExclusions);\n }\n\n private _broadcast(message: Record<string, unknown>, exclude?: string[]) {\n this.broadcast(JSON.stringify(message), exclude);\n }\n\n private _broadcastMessages(exclude?: string[]) {\n this._broadcast(\n { type: MSG_CHAT_MESSAGES, messages: this.messages },\n exclude\n );\n }\n}\n"],"mappings":";;;;;;;;;AAiJA,MAAM,oBAAoB,mBAAmB;AAC7C,MAAM,oBAAoB,mBAAmB;AAC7C,MAAM,iBAAiB,mBAAmB;AAC1C,MAAM,sBAAsB,mBAAmB;AAC/C,MAAM,yBAAyB,mBAAmB;AAClD,MAAM,sBAAsB,mBAAmB;AA+R/C,MAAM,YAAY,OAAO,YAAY;;;;;;;;AAsDrC,IAAa,QAAb,MAAa,cAGH,MAAW;CAwDnB,YAAY,KAAyB,KAAU;AAC7C,QAAM,KAA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AAK,iBAAiB,gBAAgB,SAAS;AAC9D,MAAI,OAAO,WAAW,EAAG;EAEzB,MAAM,cAAc,IAAI,kBAAkB,EACxC,WAAW,OAAO,YAAY,EAC/B,CAAC;AACF,OAAK,MAAM,SAAS,OAClB,KAAI;AACF,eAAY,WAAW,KAAK,MAAM,MAAM,KAAK,CAAoB;UAC3D;AAKV,MAAI,YAAY,MAAM,SAAS,GAAG;AAChC,QAAK,yBAAyB,YAAY,WAAW,CAAC;AACtD,QAAK,oBAAoB;;;CAI7B,eAAuB,SAAkC,SAAoB;EAC3E,MAAM,gBAAgB,CACpB,GAAI,WAAW,EAAE,EACjB,GAAG,KAAK,0BACT;AACD,OAAK,UAAU,KAAK,UAAU,QAAQ,EAAE,cAAc;;CAGxD,WAAmB,SAAkC,SAAoB;AACvE,OAAK,UAAU,KAAK,UAAU,QAAQ,EAAE,QAAQ;;CAGlD,mBAA2B,SAAoB;AAC7C,OAAK,WACH;GAAE,MAAM;GAAmB,UAAU,KAAK;GAAU,EACpD,QACD;;;AAp4EH,MAAgB,kBAAkB;AA4FlC,MAAe,sBAAsB"}
|
|
1
|
+
{"version":3,"file":"think.js","names":["Workspace","Session","agentContext"],"sources":["../src/think.ts"],"sourcesContent":["/**\n * Think — an opinionated chat agent base class.\n *\n * Works as both a **top-level agent** (speaking the `cf_agent_chat_*`\n * WebSocket protocol to browser clients) and a **sub-agent** (called\n * via `chat()` over RPC from a parent agent).\n *\n * Each instance gets its own SQLite storage backed by Session — providing\n * tree-structured messages, context blocks, compaction, FTS5 search, and\n * multi-session support.\n *\n * Configuration overrides:\n * - getModel() — return the LanguageModel to use\n * - getSystemPrompt() — return the system prompt (fallback when no context blocks)\n * - getTools() — return the ToolSet for the agentic loop\n * - maxSteps — max tool-call rounds per turn (default: 10)\n * - configureSession() — add context blocks, compaction, search, skills\n *\n * Lifecycle hooks:\n * - beforeTurn() — inspect/override context, tools, model before inference\n * - beforeToolCall() — intercept tool calls (block, modify args, substitute result)\n * - afterToolCall() — inspect tool results after execution\n * - onStepFinish() — per-step callback (logging, analytics)\n * - onChunk() — per-chunk callback (streaming analytics)\n * - onChatResponse() — post-turn lifecycle hook (logging, chaining, analytics)\n * - onChatError() — customize error handling\n *\n * Production features:\n * - WebSocket chat protocol (compatible with useAgentChat / useChat)\n * - Sub-agent RPC streaming via StreamCallback\n * - Session-backed storage with tree-structured messages\n * - Context blocks with LLM-writable persistent memory\n * - Non-destructive compaction (summaries replace ranges at read time)\n * - FTS5 full-text search across conversation history\n * - Abort/cancel support via AbortRegistry\n * - Error handling with partial message persistence\n * - Message sanitization (strips OpenAI ephemeral metadata)\n * - Row size enforcement (compacts large tool outputs)\n * - Resumable streams (replay on reconnect)\n *\n * @experimental The API surface may change before stabilizing.\n *\n * @example\n * ```typescript\n * import { Think } from \"@cloudflare/think\";\n * import { createWorkersAI } from \"workers-ai-provider\";\n *\n * export class MyAgent extends Think<Env> {\n * getModel() {\n * return createWorkersAI({ binding: this.env.AI })(\"@cf/moonshotai/kimi-k2.6\");\n * }\n *\n * getSystemPrompt() {\n * return \"You are a helpful coding assistant.\";\n * }\n * }\n * ```\n *\n * @example With context blocks and self-updating memory\n * ```typescript\n * import { Think } from \"@cloudflare/think\";\n * import type { Session } from \"@cloudflare/think\";\n *\n * export class MemoryAgent extends Think<Env> {\n * getModel() { ... }\n *\n * configureSession(session: Session) {\n * return session\n * .withContext(\"soul\", {\n * provider: { get: async () => \"You are a helpful coding assistant.\" }\n * })\n * .withContext(\"memory\", {\n * description: \"Important facts learned during conversation.\",\n * maxTokens: 2000\n * })\n * .withCachedPrompt();\n * }\n * }\n * ```\n */\n\nimport type {\n LanguageModel,\n ModelMessage,\n StreamTextOnChunkCallback,\n StreamTextOnStepFinishCallback,\n StreamTextOnToolCallFinishCallback,\n TextStreamPart,\n ToolSet,\n TypedToolCall,\n TypedToolResult,\n UIMessage\n} from \"ai\";\nimport {\n convertToModelMessages,\n pruneMessages,\n stepCountIs,\n streamText\n} from \"ai\";\n\n// Re-export AI SDK types that appear on Think's public lifecycle hooks\n// so users can import them from a single place.\nexport type {\n StepResult,\n TextStreamPart,\n TypedToolCall,\n TypedToolResult\n} from \"ai\";\nimport {\n Agent,\n __DO_NOT_USE_WILL_BREAK__agentContext as agentContext\n} from \"agents\";\nimport type { Connection, WSMessage } from \"agents\";\nimport type { FiberContext, FiberRecoveryContext } from \"agents\";\nimport {\n sanitizeMessage,\n enforceRowSizeLimit,\n StreamAccumulator,\n CHAT_MESSAGE_TYPES,\n TurnQueue,\n ResumableStream,\n ContinuationState,\n createToolsFromClientSchemas,\n AbortRegistry,\n applyToolUpdate,\n toolResultUpdate,\n toolApprovalUpdate,\n parseProtocolMessage,\n applyChunkToParts\n} from \"agents/chat\";\nimport type {\n StreamChunkData,\n ClientToolSchema,\n MessagePart\n} from \"agents/chat\";\nimport { Session } from \"agents/experimental/memory/session\";\nimport { truncateOlderMessages } from \"agents/experimental/memory/utils\";\nimport { Workspace } from \"@cloudflare/shell\";\nimport { createWorkspaceTools } from \"./tools/workspace\";\n\nexport { Session } from \"agents/experimental/memory/session\";\nexport { Workspace } from \"@cloudflare/shell\";\nexport type { FiberContext, FiberRecoveryContext } from \"agents\";\n\n// ── Wire protocol constants ────────────────────────────────────────\nconst MSG_CHAT_MESSAGES = CHAT_MESSAGE_TYPES.CHAT_MESSAGES;\nconst MSG_CHAT_RESPONSE = CHAT_MESSAGE_TYPES.USE_CHAT_RESPONSE;\nconst MSG_CHAT_CLEAR = CHAT_MESSAGE_TYPES.CHAT_CLEAR;\nconst MSG_STREAM_RESUMING = CHAT_MESSAGE_TYPES.STREAM_RESUMING;\nconst MSG_STREAM_RESUME_NONE = CHAT_MESSAGE_TYPES.STREAM_RESUME_NONE;\nconst MSG_MESSAGE_UPDATED = CHAT_MESSAGE_TYPES.MESSAGE_UPDATED;\n\n/**\n * Callback interface for streaming chat events from a Think sub-agent.\n *\n * Designed to work across the sub-agent RPC boundary — implement as\n * an RpcTarget in the parent agent and pass to `chat()`.\n */\nexport interface StreamCallback {\n onEvent(json: string): void | Promise<void>;\n onDone(): void | Promise<void>;\n onError?(error: string): void | Promise<void>;\n}\n\n/**\n * Minimal interface for the result of the inference loop.\n * The AI SDK's `streamText()` result satisfies this interface.\n */\nexport interface StreamableResult {\n toUIMessageStream(): AsyncIterable<unknown>;\n}\n\n/**\n * Options for a chat turn (sub-agent RPC entry point).\n */\nexport interface ChatOptions {\n signal?: AbortSignal;\n tools?: ToolSet;\n}\n\n// Lifecycle / result types are shared with `@cloudflare/ai-chat` via\n// `agents/chat`. Re-exported from Think so subclasses can import them\n// from `@cloudflare/think` directly.\nexport type {\n ChatResponseResult,\n ChatRecoveryContext,\n ChatRecoveryOptions,\n MessageConcurrency,\n SaveMessagesResult\n} from \"agents/chat\";\nimport type {\n ChatResponseResult,\n ChatRecoveryContext,\n ChatRecoveryOptions,\n MessageConcurrency,\n SaveMessagesResult\n} from \"agents/chat\";\n\n// ── Lifecycle hook types ────────────────────────────────────────\n\n/**\n * A chat turn request. Built automatically by each entry path\n * (WebSocket, chat(), saveMessages, auto-continuation) and passed\n * to Think's inference loop.\n */\nexport interface TurnInput {\n signal?: AbortSignal;\n /** Extra tools from the caller (e.g. chat() options) — highest merge priority. */\n callerTools?: ToolSet;\n /** Client-provided tool schemas for dynamic tool registration. */\n clientTools?: ClientToolSchema[];\n /** Custom body fields from the client request. */\n body?: Record<string, unknown>;\n /** Whether this is a continuation turn (auto-continue after tool result, recovery). */\n continuation: boolean;\n}\n\n/**\n * Context passed to the `beforeTurn` hook.\n * Contains everything Think assembled — the hook can inspect and override.\n */\nexport interface TurnContext {\n /** Assembled system prompt (from context blocks or getSystemPrompt fallback). */\n system: string;\n /** Assembled model messages (truncated, pruned). */\n messages: ModelMessage[];\n /** Merged tool set (workspace + getTools + session + MCP + client + caller). */\n tools: ToolSet;\n /** The language model from getModel(). */\n model: LanguageModel;\n /** Whether this is a continuation turn. */\n continuation: boolean;\n /** Custom body fields from the client request. */\n body?: Record<string, unknown>;\n}\n\n/**\n * Configuration returned by the `beforeTurn` hook to override defaults.\n * All fields are optional — return only what you want to change.\n */\nexport interface TurnConfig {\n /** Override the model for this turn (e.g. cheap model for continuations). */\n model?: LanguageModel;\n /** Override the assembled system prompt. */\n system?: string;\n /** Override the assembled messages. */\n messages?: ModelMessage[];\n /** Extra tools to merge (additive — spread on top of existing tools). */\n tools?: ToolSet;\n /** Limit which tools the model can call (AI SDK activeTools). */\n activeTools?: string[];\n /** Force a specific tool call (AI SDK toolChoice). */\n toolChoice?: Parameters<typeof streamText>[0][\"toolChoice\"];\n /** Override maxSteps for this turn. */\n maxSteps?: number;\n /** Provider-specific options (AI SDK providerOptions). */\n providerOptions?: Record<string, unknown>;\n}\n\n/**\n * Context passed to the `beforeToolCall` hook **before** the tool's\n * `execute` function runs.\n *\n * Backed by the AI SDK's `OnToolCallStartEvent` (the parameter of\n * `experimental_onToolCallStart`). The full `TypedToolCall<TOOLS>`\n * fields (`toolName`, `toolCallId`, `input`, `providerMetadata`, the\n * dynamic/invalid/error discriminators) are spread at the top level for\n * convenience, with the per-call event extras attached:\n *\n * - `stepNumber` — index of the current step\n * - `messages` — conversation messages visible at tool execution time\n * - `abortSignal` — signal that aborts if the turn is cancelled\n *\n * Pass an explicit `TOOLS` generic for full input typing:\n *\n * ```ts\n * import type { ToolCallContext } from \"@cloudflare/think\";\n * import type { tools } from \"./my-tools\";\n *\n * beforeToolCall(ctx: ToolCallContext<typeof tools>) {\n * if (ctx.toolName === \"search\") {\n * ctx.input.query; // typed\n * }\n * }\n * ```\n */\nexport type ToolCallContext<TOOLS extends ToolSet = ToolSet> =\n TypedToolCall<TOOLS> & {\n /** Zero-based index of the current step where this tool call occurs. */\n readonly stepNumber: number | undefined;\n /** The conversation messages available at tool execution time. */\n readonly messages: ReadonlyArray<ModelMessage>;\n /** Signal for cancelling the operation. */\n readonly abortSignal: AbortSignal | undefined;\n };\n\n/**\n * Decision returned by `beforeToolCall` to control tool execution.\n * Return void/undefined to allow execution with original input.\n *\n * Discriminated union — each action has a clear, non-overlapping meaning:\n * - `allow` — execute the tool (optionally with modified input)\n * - `block` — don't execute; return `reason` as the tool result so the model can adjust\n * - `substitute` — don't execute; return `output` as the tool result (afterToolCall still fires)\n */\nexport type ToolCallDecision =\n | {\n action: \"allow\";\n /** Modified input — tool executes with this instead of the original. */\n input?: Record<string, unknown>;\n }\n | {\n action: \"block\";\n /** Returned as the tool result so the model can adjust. */\n reason?: string;\n }\n | {\n action: \"substitute\";\n /** The substitute tool output — model sees this instead of real execution. */\n output: unknown;\n /** Optional input attribution for the afterToolCall log. */\n input?: Record<string, unknown>;\n };\n\n/**\n * Context passed to the `afterToolCall` hook after a tool executes.\n *\n * Backed by the AI SDK's `OnToolCallFinishEvent` (the parameter of\n * `experimental_onToolCallFinish`). The full `TypedToolCall<TOOLS>`\n * fields (`toolName`, `toolCallId`, `input`, …) are spread at the top\n * level, plus the per-call event extras:\n *\n * - `stepNumber` — index of the current step\n * - `messages` — conversation messages visible at tool execution time\n * - `durationMs` — wall-clock execution time in milliseconds\n * - `success`/`output`/`error` — discriminated outcome:\n * - on success: `success: true`, `output: unknown`\n * - on failure: `success: false`, `error: unknown`\n *\n * Pass an explicit `TOOLS` generic for full input typing:\n *\n * ```ts\n * import type { ToolCallResultContext } from \"@cloudflare/think\";\n * import type { tools } from \"./my-tools\";\n *\n * afterToolCall(ctx: ToolCallResultContext<typeof tools>) {\n * if (ctx.success) {\n * console.log(`${ctx.toolName} took ${ctx.durationMs}ms`, ctx.output);\n * } else {\n * console.error(`${ctx.toolName} failed:`, ctx.error);\n * }\n * }\n * ```\n */\nexport type ToolCallResultContext<TOOLS extends ToolSet = ToolSet> =\n TypedToolCall<TOOLS> & {\n readonly stepNumber: number | undefined;\n readonly messages: ReadonlyArray<ModelMessage>;\n /** Wall-clock execution time in milliseconds. */\n readonly durationMs: number;\n } & (\n | {\n readonly success: true;\n readonly output: unknown;\n readonly error?: never;\n }\n | {\n readonly success: false;\n readonly output?: never;\n readonly error: unknown;\n }\n );\n\n/**\n * Context passed to the `onStepFinish` hook after each step completes.\n *\n * This is the AI SDK's `StepResult<TOOLS>` (= `OnStepFinishEvent<TOOLS>`) —\n * the full step record including `text`, `reasoning`, `toolCalls`,\n * `toolResults`, `files`, `sources`, `usage` (with `cachedInputTokens`,\n * `reasoningTokens`, `totalTokens`), `finishReason`, `warnings`, `request`,\n * `response`, and `providerMetadata` (where provider-specific cache\n * accounting like `cacheCreationInputTokens` lives).\n *\n * Pass an explicit `TOOLS` generic for typed `toolCalls`/`toolResults`.\n */\nexport type StepContext<TOOLS extends ToolSet = ToolSet> = Parameters<\n StreamTextOnStepFinishCallback<TOOLS>\n>[0];\n\n/**\n * Context passed to the `onChunk` hook for each streaming chunk.\n *\n * This is the AI SDK's `StreamTextOnChunkCallback` event — `{ chunk }`\n * where `chunk` is a discriminated union of `TextStreamPart` variants\n * (text-delta, reasoning-delta, source, tool-call, tool-input-start,\n * tool-input-delta, tool-result, raw).\n */\nexport type ChunkContext<TOOLS extends ToolSet = ToolSet> = Parameters<\n StreamTextOnChunkCallback<TOOLS>\n>[0];\n\n/**\n * @internal Re-export of the chunk variant union for consumers that need\n * to narrow on `chunk.type` without importing `TextStreamPart` directly.\n */\nexport type ChunkPart<TOOLS extends ToolSet = ToolSet> =\n ChunkContext<TOOLS>[\"chunk\"];\n\n/**\n * Configuration for a sandboxed extension, returned by getExtensions().\n */\nexport interface ExtensionConfig {\n /** Extension manifest (name, version, permissions, contributions). */\n manifest: import(\"./extensions/types\").ExtensionManifest;\n /** JavaScript source code defining the extension's tools. */\n source: string;\n}\n\nconst TIMED_OUT = Symbol(\"timed-out\");\n\ntype NormalizedMessageConcurrency =\n | \"queue\"\n | \"latest\"\n | \"merge\"\n | \"drop\"\n | { strategy: \"debounce\"; debounceMs: number };\n\ntype SubmitConcurrencyDecision = {\n action: \"execute\" | \"drop\";\n submitSequence: number | null;\n debounceUntilMs: number | null;\n};\n\n/**\n * An opinionated chat agent base class.\n *\n * @experimental The API surface may change before stabilizing.\n */\nexport class Think<\n Env extends Cloudflare.Env = Cloudflare.Env,\n State = unknown,\n Props extends Record<string, unknown> = Record<string, unknown>\n> extends Agent<Env, State, Props> {\n /**\n * Wait for MCP server connections to be ready before the inference\n * loop. MCP tools are auto-merged into the tool set.\n *\n * Set to `true` for a default 10s timeout, or `{ timeout: ms }`\n * for a custom timeout. Defaults to `false` (no waiting).\n */\n waitForMcpConnections: boolean | { timeout: number } = false;\n\n /**\n * Controls how overlapping user submit requests behave while another\n * chat turn is already active or queued.\n *\n * @default \"queue\"\n */\n messageConcurrency: MessageConcurrency = \"queue\";\n\n /**\n * When true, chat turns are wrapped in `runFiber` for durable execution.\n * Enables `onChatRecovery` hook and `this.stash()` during streaming.\n */\n chatRecovery = true;\n\n static readonly CHAT_FIBER_NAME = \"__cf_internal_chat_turn\";\n\n /** The conversation session — messages, context, compaction, search. */\n session!: Session;\n\n /**\n * WorkerLoader binding for sandboxed extensions.\n * Set this to enable `getExtensions()` and dynamic extension loading.\n */\n extensionLoader?: WorkerLoader;\n\n /**\n * Extension manager — created automatically when `extensionLoader` is set.\n * Use for dynamic `load()` / `unload()` at runtime.\n */\n extensionManager?: import(\"./extensions/manager\").ExtensionManager;\n\n /**\n * Workspace filesystem backed by the DO's SQLite storage.\n * Available in `getTools()` and lifecycle hooks.\n *\n * Override to add R2 spillover for large files:\n * ```typescript\n * override workspace = new Workspace({\n * sql: this.ctx.storage.sql,\n * r2: this.env.R2,\n * name: () => this.name\n * });\n * ```\n */\n workspace!: Workspace;\n\n constructor(ctx: DurableObjectState, env: Env) {\n super(ctx, env);\n\n const _onStart = this.onStart.bind(this);\n this.onStart = async () => {\n // 1. Workspace initialization\n if (!this.workspace) {\n this.workspace = new Workspace({\n sql: this.ctx.storage.sql,\n name: () => this.name\n });\n }\n\n // 2. Session configuration (builder phase — context blocks, compaction, skills)\n const baseSession = Session.create(this);\n this.session = await this.configureSession(baseSession);\n\n // Force Session to initialize its tables (assistant_messages,\n // assistant_config, etc.) so that subsequent config reads work.\n this.session.getHistory();\n\n // 3-6. Extension initialization (if extensionLoader is set)\n if (this.extensionLoader) {\n await this._initializeExtensions();\n }\n\n // 7. Protocol handlers\n this._resumableStream = new ResumableStream(this.sql.bind(this));\n this._restoreClientTools();\n this._restoreBody();\n this._setupProtocolHandlers();\n\n // 8. User's onStart\n await _onStart();\n };\n }\n\n /**\n * Conversation history. Computed from the active session.\n * Always fresh — reads from Session's tree-structured storage.\n */\n get messages(): UIMessage[] {\n return this.session.getHistory() as UIMessage[];\n }\n\n private _aborts = new AbortRegistry();\n private _turnQueue = new TurnQueue();\n private _resumableStream!: ResumableStream;\n private _pendingResumeConnections: Set<string> = new Set();\n private _lastClientTools: ClientToolSchema[] | undefined;\n private _lastBody: Record<string, unknown> | undefined;\n private _continuation = new ContinuationState();\n private _continuationTimer: ReturnType<typeof setTimeout> | null = null;\n private _insideResponseHook = false;\n private _insideInferenceLoop = false;\n private _pendingInteractionPromise: Promise<boolean> | null = null;\n private _submitSequence = 0;\n private _latestOverlappingSubmitSequence = 0;\n private _activeDebounceTimer: ReturnType<typeof setTimeout> | null = null;\n private _activeDebounceResolve: (() => void) | null = null;\n private static MESSAGE_DEBOUNCE_MS = 750;\n\n // ── Dynamic config ──────────────────────────────────────────────\n\n #configCache: unknown = null;\n\n /**\n * Persist an arbitrary JSON-serializable configuration object for this\n * agent instance. Stored in the assistant_config table — survives\n * restarts and hibernation. Pass the config shape as a method generic\n * for typed call sites:\n *\n * ```ts\n * this.configure<MyConfig>({ modelTier: \"fast\" });\n * ```\n *\n * Prefer `state` / `setState` from `Agent` when you want the value\n * broadcast to connected clients. Use `configure` for private\n * per-instance config that should stay server-side.\n */\n configure<T = Record<string, unknown>>(config: T): void {\n const json = JSON.stringify(config);\n this._configSet(\"_think_config\", json);\n this.#configCache = config;\n }\n\n /**\n * Read the persisted configuration, or null if never configured.\n * Pass the config shape as a method generic for a typed result:\n *\n * ```ts\n * const cfg = this.getConfig<MyConfig>();\n * ```\n */\n getConfig<T = Record<string, unknown>>(): T | null {\n if (this.#configCache !== null) return this.#configCache as T;\n const raw = this._configGet(\"_think_config\");\n if (raw !== undefined) {\n this.#configCache = JSON.parse(raw);\n return this.#configCache as T;\n }\n return null;\n }\n\n // ── Config storage helpers (assistant_config table) ─────────────\n\n #configTableReady = false;\n\n private _ensureConfigTable(): void {\n if (this.#configTableReady) return;\n this.sql`\n CREATE TABLE IF NOT EXISTS assistant_config (\n session_id TEXT NOT NULL,\n key TEXT NOT NULL,\n value TEXT NOT NULL,\n PRIMARY KEY (session_id, key)\n )\n `;\n this.#configTableReady = true;\n }\n\n private _configSet(key: string, value: string): void {\n this._ensureConfigTable();\n const sessionId = this._sessionId();\n this.sql`\n INSERT OR REPLACE INTO assistant_config (session_id, key, value)\n VALUES (${sessionId}, ${key}, ${value})\n `;\n }\n\n private _configGet(key: string): string | undefined {\n this._ensureConfigTable();\n const sessionId = this._sessionId();\n const rows = this.sql<{ value: string }>`\n SELECT value FROM assistant_config\n WHERE session_id = ${sessionId} AND key = ${key}\n `;\n return rows[0]?.value;\n }\n\n private _configDelete(key: string): void {\n this._ensureConfigTable();\n const sessionId = this._sessionId();\n this.sql`\n DELETE FROM assistant_config\n WHERE session_id = ${sessionId} AND key = ${key}\n `;\n }\n\n private _sessionId(): string {\n return \"\";\n }\n\n // ── Configuration overrides ─────────────────────────────────────\n\n /**\n * Return the language model to use for inference.\n * Must be overridden by subclasses.\n */\n getModel(): LanguageModel {\n throw new Error(\"Override getModel() to return a LanguageModel.\");\n }\n\n /**\n * Return the system prompt for the assistant.\n * Used as fallback when no context blocks are configured via `configureSession`.\n */\n getSystemPrompt(): string {\n return \"You are a helpful assistant.\";\n }\n\n /** Return the tools available to the assistant. */\n getTools(): ToolSet {\n return {};\n }\n\n /** Maximum number of tool-call steps per turn. Override via property or per-turn via TurnConfig. */\n maxSteps = 10;\n\n /**\n * Configure the session. Called once during `onStart`.\n * Override to add context blocks, compaction, search, skills.\n *\n * @example\n * ```typescript\n * configureSession(session: Session) {\n * return session\n * .withContext(\"memory\", { description: \"Learned facts\", maxTokens: 2000 })\n * .withCachedPrompt();\n * }\n * ```\n */\n configureSession(session: Session): Session | Promise<Session> {\n return session;\n }\n\n /**\n * Return sandboxed extension configurations. Defines load order,\n * which determines hook execution order.\n * Requires `extensionLoader` to be set.\n */\n getExtensions(): ExtensionConfig[] {\n return [];\n }\n\n // ── Lifecycle hooks ───────────────────────────────────────────\n\n /**\n * Called before `streamText` — inspect the assembled context and\n * return overrides. Think assembles tools, system prompt, and messages\n * internally; this hook sees the result and can override any part.\n *\n * Return `void` to accept all defaults.\n *\n * @example Switch model for continuations\n * ```typescript\n * beforeTurn(ctx: TurnContext) {\n * if (ctx.continuation) return { model: this.cheapModel };\n * }\n * ```\n *\n * @example Restrict active tools\n * ```typescript\n * beforeTurn(ctx: TurnContext) {\n * return { activeTools: [\"read\", \"write\"] };\n * }\n * ```\n */\n beforeTurn(\n _ctx: TurnContext\n ): TurnConfig | void | Promise<TurnConfig | void> {}\n\n /**\n * Called **before** the tool's `execute` function runs. Think wraps\n * every tool's `execute` so it can consult this hook and act on the\n * returned `ToolCallDecision`:\n *\n * - `void` (or `{ action: \"allow\" }` with no `input`) — run the\n * original `execute` with the original input.\n * - `{ action: \"allow\", input }` — run the original `execute` with\n * the substituted input.\n * - `{ action: \"block\", reason }` — skip `execute`; the model sees\n * `reason` as the tool's output.\n * - `{ action: \"substitute\", output }` — skip `execute`; the model\n * sees `output` as the tool's output.\n *\n * Only fires for server-side tools (tools with `execute`). Client\n * tools are handled on the client — Think can't intercept them.\n *\n * `afterToolCall` always fires after this hook (or after the original\n * `execute` when `allow`). For `block`/`substitute`, the substituted\n * value flows through `afterToolCall` as `success: true, output: ...`.\n *\n * @example Log tool calls\n * ```typescript\n * beforeToolCall(ctx: ToolCallContext) {\n * console.log(`Tool called: ${ctx.toolName}`, ctx.input);\n * }\n * ```\n *\n * @example Block a tool the model shouldn't be calling here\n * ```typescript\n * beforeToolCall(ctx: ToolCallContext): ToolCallDecision | void {\n * if (ctx.toolName === \"delete\" && this.isReadOnlyMode) {\n * return { action: \"block\", reason: \"delete is disabled in read-only mode\" };\n * }\n * }\n * ```\n *\n * @example Substitute a cached result\n * ```typescript\n * async beforeToolCall(ctx: ToolCallContext): Promise<ToolCallDecision | void> {\n * if (ctx.toolName === \"weather\") {\n * const cached = await this.cache.get(JSON.stringify(ctx.input));\n * if (cached) return { action: \"substitute\", output: cached };\n * }\n * }\n * ```\n */\n beforeToolCall(\n _ctx: ToolCallContext\n ): ToolCallDecision | void | Promise<ToolCallDecision | void> {}\n\n /**\n * Called **after** a tool's outcome is known — for real executions, for\n * `block` (carries the `reason` as `output`), and for `substitute`\n * (carries the substituted `output`). Backed by the AI SDK's\n * `experimental_onToolCallFinish`, so `durationMs` and the discriminated\n * `success`/`output`/`error` outcome reflect what the model actually\n * sees: a thrown error from the original `execute` becomes\n * `success: false, error: ...`; everything else (including blocked /\n * substituted calls) is `success: true, output: ...`.\n *\n * Override for logging, metrics, or result inspection.\n *\n * @example\n * ```typescript\n * afterToolCall(ctx: ToolCallResultContext) {\n * if (ctx.success) {\n * console.log(`${ctx.toolName} ok in ${ctx.durationMs}ms`);\n * } else {\n * console.error(`${ctx.toolName} failed:`, ctx.error);\n * }\n * }\n * ```\n */\n afterToolCall(_ctx: ToolCallResultContext): void | Promise<void> {}\n\n /**\n * Called after each step completes (initial, continue, tool-result).\n * Override for step-level logging or analytics.\n */\n onStepFinish(_ctx: StepContext): void | Promise<void> {}\n\n /**\n * Called for each streaming chunk. High-frequency — fires per token.\n * Override for streaming analytics, progress indicators, or token counting.\n * Observational only (void return).\n */\n onChunk(_ctx: ChunkContext): void | Promise<void> {}\n\n /**\n * Called after a chat turn completes and the assistant message has been\n * persisted. The turn lock is released before this hook runs, so it is\n * safe to call other methods from inside.\n *\n * Fires for all turn completion paths: WebSocket chat requests,\n * sub-agent RPC, and auto-continuation.\n *\n * Override for logging, chaining, analytics, usage tracking.\n */\n onChatResponse(_result: ChatResponseResult): void | Promise<void> {}\n\n /**\n * Handle an error that occurred during a chat turn.\n * Override to customize error handling (e.g. logging, metrics).\n */\n onChatError(error: unknown): unknown {\n return error;\n }\n\n // ── Extension initialization ───────────────────────────────────\n\n private async _initializeExtensions(): Promise<void> {\n const { ExtensionManager } = await import(\"./extensions/manager\");\n const { sanitizeName } = await import(\"./extensions/manager\");\n\n // 3. Create ExtensionManager with host binding if HostBridgeLoopback\n // is re-exported from the worker entry point.\n const agentClassName = this.constructor.name;\n const agentId = this.ctx.id.toString();\n const ctxExports = (this.ctx as unknown as Record<string, unknown>)\n .exports as Record<string, unknown> | undefined;\n const hasBridge =\n ctxExports && typeof ctxExports.HostBridgeLoopback === \"function\";\n\n this.extensionManager = new ExtensionManager({\n loader: this.extensionLoader!,\n storage: this.ctx.storage,\n ...(hasBridge\n ? {\n createHostBinding: (\n permissions: import(\"./extensions/types\").ExtensionPermissions,\n ownContextLabels: string[]\n ) =>\n (\n ctxExports.HostBridgeLoopback as (opts: {\n props: Record<string, unknown>;\n }) => Fetcher\n )({\n props: {\n agentClassName,\n agentId,\n permissions,\n ownContextLabels\n }\n })\n }\n : {})\n });\n\n // 4. Load static extensions from getExtensions()\n const configs = this.getExtensions();\n for (const config of configs) {\n await this.extensionManager.load(config.manifest, config.source);\n }\n\n // 5. Restore dynamic extensions from DO storage\n await this.extensionManager.restore();\n\n // 6. Register extension context blocks in Session (mutation phase).\n // Context blocks use SQLite-backed AgentContextProvider (no bridge\n // delegation to the extension Worker). Extensions write to their\n // blocks via host.setContext() (Phase 3). Bridge providers that\n // delegate to extension Worker RPC methods are Phase 4.\n for (const ext of this.extensionManager.list()) {\n const manifest = this.extensionManager.getManifest(ext.name);\n if (!manifest?.context) continue;\n\n const prefix = sanitizeName(ext.name);\n for (const ctxDef of manifest.context) {\n const namespacedLabel = `${prefix}_${ctxDef.label}`;\n await this.session.addContext(namespacedLabel, {\n description: ctxDef.description,\n maxTokens: ctxDef.maxTokens\n });\n }\n }\n\n // Wire unload callback to clean up context blocks\n this.extensionManager.onUnload(async (_name, contextLabels) => {\n for (const label of contextLabels) {\n this.session.removeContext(label);\n }\n await this.session.refreshSystemPrompt();\n });\n }\n\n // ── Inference loop (Think owns this) ──────────────────────────\n\n /**\n * The single convergence point for all chat turn entry paths.\n * Merges tools, assembles context, fires lifecycle hooks, wraps tools\n * for interception, and calls streamText.\n */\n private async _runInferenceLoop(input: TurnInput): Promise<StreamableResult> {\n if (this.waitForMcpConnections) {\n const timeout =\n typeof this.waitForMcpConnections === \"object\"\n ? this.waitForMcpConnections.timeout\n : 10_000;\n await this.mcp.waitForConnections({ timeout });\n }\n\n const workspaceTools = createWorkspaceTools(this.workspace);\n const baseTools = this.getTools();\n const extensionTools = this.extensionManager?.getTools() ?? {};\n const contextTools = await this.session.tools();\n const clientToolSet = createToolsFromClientSchemas(input.clientTools);\n const tools: ToolSet = {\n ...workspaceTools,\n ...baseTools,\n ...extensionTools,\n ...contextTools,\n ...(this.mcp?.getAITools?.() ?? {}),\n ...clientToolSet,\n ...input.callerTools\n };\n\n const frozenPrompt = await this.session.freezeSystemPrompt();\n const system = frozenPrompt || this.getSystemPrompt();\n\n const history = this.session.getHistory();\n const truncated = truncateOlderMessages(history) as UIMessage[];\n const messages = pruneMessages({\n messages: await convertToModelMessages(truncated),\n toolCalls: \"before-last-2-messages\"\n });\n\n if (messages.length === 0) {\n throw new Error(\n \"No messages to send to the model. This usually means the chat request \" +\n \"arrived before any messages were persisted.\"\n );\n }\n\n const model = this.getModel();\n const ctx: TurnContext = {\n system,\n messages,\n tools,\n model,\n continuation: input.continuation,\n body: input.body\n };\n\n const subclassConfig = (await this.beforeTurn(ctx)) ?? {};\n const config = await this._pipelineExtensionBeforeTurn(ctx, subclassConfig);\n\n const finalModel = config.model ?? model;\n const finalSystem = config.system ?? system;\n const finalMessages = config.messages ?? messages;\n const mergedTools: ToolSet = config.tools\n ? { ...tools, ...config.tools }\n : tools;\n // Wrap each tool's `execute` so `beforeToolCall` is consulted before\n // the tool actually runs. The wrapped `execute` honors the returned\n // `ToolCallDecision` — `block` short-circuits with `reason`,\n // `substitute` returns `output` directly, `allow` runs the original\n // (optionally with modified `input`).\n const finalTools: ToolSet = this._wrapToolsWithDecision(mergedTools);\n const finalMaxSteps = config.maxSteps ?? this.maxSteps;\n\n const result = streamText({\n model: finalModel,\n system: finalSystem,\n messages: finalMessages,\n tools: finalTools,\n activeTools: config.activeTools,\n toolChoice: config.toolChoice,\n stopWhen: stepCountIs(finalMaxSteps),\n providerOptions: config.providerOptions as\n | Parameters<typeof streamText>[0][\"providerOptions\"]\n | undefined,\n abortSignal: input.signal,\n onChunk: async (event) => {\n // Pass the AI SDK's chunk event through unchanged — gives users\n // access to the discriminated `TextStreamPart` chunk with all\n // provider metadata.\n await this.onChunk(event);\n await this._pipelineExtensionChunk(event);\n },\n onStepFinish: async (event) => {\n // Pass the full StepResult through — gives users access to\n // reasoning, sources, files, providerMetadata (cache tokens),\n // request/response, warnings, and the full LanguageModelUsage\n // that the AI SDK provides.\n await this.onStepFinish(event);\n await this._pipelineExtensionStepFinish(event);\n },\n // `beforeToolCall` is dispatched from the wrapped `execute` (see\n // `_wrapToolsWithDecision` above) so the returned `ToolCallDecision`\n // can actually intercept the call. `afterToolCall` is wired through\n // the AI SDK's `experimental_onToolCallFinish` callback so we get\n // accurate `durationMs` and the discriminated `success`/`error`\n // outcome — including failures that propagate out of `execute`.\n experimental_onToolCallFinish: (async (event) => {\n const base = {\n ...event.toolCall,\n stepNumber: event.stepNumber,\n messages: event.messages,\n durationMs: event.durationMs\n };\n const ctx = (\n event.success\n ? { ...base, success: true as const, output: event.output }\n : { ...base, success: false as const, error: event.error }\n ) as ToolCallResultContext;\n await this.afterToolCall(ctx);\n await this._pipelineExtensionToolCallFinish(event);\n }) satisfies StreamTextOnToolCallFinishCallback<ToolSet>\n });\n\n return this._transformInferenceResult(result);\n }\n\n /** @internal Test seam — override in test agents to wrap the stream (e.g. error injection). */\n protected _transformInferenceResult(\n result: StreamableResult\n ): StreamableResult {\n return result;\n }\n\n /** Default hook timeout in milliseconds. */\n hookTimeout = 5000;\n\n /**\n * Pipeline beforeTurn through sandboxed extensions in load order.\n * Each extension sees the accumulated state from prior extensions\n * (snapshot is rebuilt after each extension's modifications).\n * Results are merged with last-write-wins for scalar fields.\n * Extensions that don't subscribe to beforeTurn are skipped.\n */\n private async _pipelineExtensionBeforeTurn(\n ctx: TurnContext,\n subclassConfig: TurnConfig\n ): Promise<TurnConfig> {\n if (!this.extensionManager) return subclassConfig;\n\n const subscribers = this.extensionManager.getHookSubscribers(\"beforeTurn\");\n if (subscribers.length === 0) return subclassConfig;\n\n const { createTurnContextSnapshot, parseHookResult } =\n await import(\"./extensions/hook-proxy\");\n\n let snapshot = createTurnContextSnapshot(ctx);\n let accumulated = { ...subclassConfig };\n\n // Apply subclass config to the initial snapshot so extensions\n // see the subclass overrides\n if (accumulated.system !== undefined) snapshot.system = accumulated.system;\n if (accumulated.maxSteps !== undefined)\n snapshot.messageCount = ctx.messages.length;\n\n for (const sub of subscribers) {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n const resultJson = await Promise.race([\n sub.entrypoint.hook(\"beforeTurn\", snapshot),\n new Promise<string>((_, reject) => {\n timer = setTimeout(\n () => reject(new Error(`Hook timeout: ${sub.name}`)),\n this.hookTimeout\n );\n })\n ]);\n\n const parsed = parseHookResult(resultJson);\n if (\"config\" in parsed) {\n // Merge serializable scalars only. model and tools are skipped —\n // sandboxed extensions can't return LanguageModel or AI SDK Tool\n // objects (not serializable across RPC). Use activeTools to\n // control which tools the model can call.\n if (parsed.config.system !== undefined)\n accumulated.system = parsed.config.system;\n if (parsed.config.messages !== undefined)\n accumulated.messages = parsed.config.messages;\n if (parsed.config.activeTools !== undefined)\n accumulated.activeTools = parsed.config.activeTools;\n if (parsed.config.toolChoice !== undefined)\n accumulated.toolChoice = parsed.config.toolChoice;\n if (parsed.config.maxSteps !== undefined)\n accumulated.maxSteps = parsed.config.maxSteps;\n if (parsed.config.providerOptions !== undefined) {\n accumulated.providerOptions = {\n ...(accumulated.providerOptions ?? {}),\n ...parsed.config.providerOptions\n };\n }\n // Update snapshot so next extension sees this extension's changes\n if (accumulated.system !== undefined)\n snapshot = { ...snapshot, system: accumulated.system };\n if (accumulated.activeTools !== undefined)\n snapshot = { ...snapshot, toolNames: accumulated.activeTools };\n } else if (\"error\" in parsed) {\n console.warn(\n `[Think] Extension \"${sub.name}\" beforeTurn error:`,\n parsed.error\n );\n }\n } catch (err) {\n console.warn(\n `[Think] Extension \"${sub.name}\" beforeTurn failed:`,\n err instanceof Error ? err.message : err\n );\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n }\n\n return accumulated;\n }\n\n /**\n * Dispatch an observation hook to all extensions that subscribe to it.\n *\n * Used by `_pipelineExtensionToolCallStart`, `_pipelineExtensionToolCallFinish`,\n * `_pipelineExtensionStepFinish`, and `_pipelineExtensionChunk`. Unlike\n * `beforeTurn`, these hooks are observation-only — extensions can't\n * influence the turn — so we ignore return values, log errors, and\n * apply a per-extension timeout.\n *\n * `onChunk` is high-frequency (per token) — extensions that subscribe\n * to it pay an RPC cost per chunk and should be used sparingly.\n */\n private async _dispatchExtensionObservation(\n hookName: \"beforeToolCall\" | \"afterToolCall\" | \"onStepFinish\" | \"onChunk\",\n snapshot: unknown\n ): Promise<void> {\n if (!this.extensionManager) return;\n const subscribers = this.extensionManager.getHookSubscribers(hookName);\n if (subscribers.length === 0) return;\n\n for (const sub of subscribers) {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n await Promise.race([\n sub.entrypoint.hook(hookName, snapshot),\n new Promise<string>((_, reject) => {\n timer = setTimeout(\n () => reject(new Error(`Hook timeout: ${sub.name}`)),\n this.hookTimeout\n );\n })\n ]);\n } catch (err) {\n console.warn(\n `[Think] Extension \"${sub.name}\" ${hookName} failed:`,\n err instanceof Error ? err.message : err\n );\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n }\n }\n\n /**\n * Wrap each tool's `execute` function so the agent's `beforeToolCall`\n * hook is consulted before the tool runs. The hook can return a\n * `ToolCallDecision` to:\n *\n * - `allow` (default if `void` is returned) — run the original\n * `execute`, optionally with a substituted `input`.\n * - `block` — skip `execute` and return `reason` (or a default string)\n * as the tool result. The model sees this as the tool's output.\n * - `substitute` — skip `execute` and return `output` directly. The\n * model sees this as the tool's output.\n *\n * The wrapped `execute` also dispatches the `beforeToolCall`\n * observation snapshot to subscribed extensions. `afterToolCall` is\n * still wired through the AI SDK's `experimental_onToolCallFinish`\n * callback so we get accurate `durationMs` and proper success/error\n * discrimination — `block` and `substitute` outcomes show up as\n * `success: true` with the substituted output; uncaught throws from\n * the original `execute` show up as `success: false` with the error.\n *\n * Tools without an `execute` (output-schema-only tools, client tools\n * routed via `needsApproval`) are left untouched.\n *\n * **Streaming tools (AsyncIterable):** the AI SDK supports tools whose\n * `execute` returns `AsyncIterable<output>` to emit preliminary\n * results before a final value. This works whether the iterator is\n * returned directly (sync function, `async function*`) or wrapped in\n * a Promise (`async function execute(...) { return makeIter(); }`).\n * Because the wrapper must `await beforeToolCall` first, preliminary\n * chunks are collapsed — only the *final* yielded value reaches the\n * model. If you need true preliminary streaming, override\n * `getTools()` to provide such tools and avoid using `beforeToolCall`\n * for them (or accept the collapse).\n */\n private _wrapToolsWithDecision(tools: ToolSet): ToolSet {\n const wrapped: ToolSet = {};\n for (const [toolName, originalTool] of Object.entries(tools)) {\n const t = originalTool as Record<string, unknown>;\n const originalExecute = t.execute as\n | ((input: unknown, options: unknown) => unknown | Promise<unknown>)\n | undefined;\n if (typeof originalExecute !== \"function\") {\n wrapped[toolName] = originalTool;\n continue;\n }\n\n const isDynamic = t.type === \"dynamic\";\n\n const wrappedExecute = async (\n input: unknown,\n options: {\n toolCallId: string;\n messages: ModelMessage[];\n abortSignal?: AbortSignal;\n experimental_context?: unknown;\n }\n ): Promise<unknown> => {\n // Build the discriminated `TypedToolCall`-shaped context.\n const toolCallBase = {\n type: \"tool-call\" as const,\n toolCallId: options.toolCallId,\n toolName,\n input,\n ...(isDynamic ? { dynamic: true as const } : {})\n };\n\n const ctx = {\n ...toolCallBase,\n stepNumber: undefined,\n messages: options.messages,\n abortSignal: options.abortSignal\n } as ToolCallContext;\n\n // Subclass decision first.\n const decision = await this.beforeToolCall(ctx);\n\n // Extension observation dispatch — runs after the subclass so\n // extensions see whatever effect the subclass had on the\n // decision shape (input substitution shows up in the snapshot).\n const dispatchInput =\n decision && decision.action === \"allow\" && decision.input\n ? decision.input\n : input;\n await this._pipelineExtensionToolCallStart({\n toolCall: {\n ...toolCallBase,\n input: dispatchInput\n } as TypedToolCall<ToolSet>,\n stepNumber: undefined\n });\n\n // Resolve the decision.\n if (!decision || decision.action === \"allow\") {\n const finalInput = decision?.input ?? input;\n // Await before inspecting so we detect AsyncIterable returns\n // whether the original `execute` returned them directly (sync\n // function or `async function*`) or wrapped in a Promise (a\n // plain async function that returns an iterator). Without the\n // await, `Symbol.asyncIterator in result` would be false for\n // any `Promise<AsyncIterable>`, the collapse below would be\n // skipped, and the AI SDK would treat the iterator instance\n // itself as the final output value (broken).\n const result = await originalExecute(finalInput, options);\n // If the resolved value is an AsyncIterable (streaming tool\n // emitting preliminary outputs), collapse to the last yielded\n // value. We trade preliminary streaming for `beforeToolCall`\n // interception support.\n if (\n result != null &&\n typeof result === \"object\" &&\n Symbol.asyncIterator in (result as object)\n ) {\n let last: unknown;\n for await (const part of result as AsyncIterable<unknown>) {\n last = part;\n }\n return last;\n }\n return result;\n }\n if (decision.action === \"block\") {\n return (\n decision.reason ??\n `Tool \"${toolName}\" was blocked by beforeToolCall.`\n );\n }\n // substitute\n return decision.output;\n };\n\n wrapped[toolName] = {\n ...(originalTool as object),\n execute: wrappedExecute\n } as ToolSet[string];\n }\n return wrapped;\n }\n\n private async _pipelineExtensionToolCallStart(event: {\n toolCall: TypedToolCall<ToolSet>;\n stepNumber: number | undefined;\n }): Promise<void> {\n if (!this.extensionManager) return;\n if (this.extensionManager.getHookSubscribers(\"beforeToolCall\").length === 0)\n return;\n const { createToolCallStartSnapshot } =\n await import(\"./extensions/hook-proxy\");\n await this._dispatchExtensionObservation(\n \"beforeToolCall\",\n createToolCallStartSnapshot(event)\n );\n }\n\n private async _pipelineExtensionToolCallFinish(event: {\n toolCall: TypedToolCall<ToolSet>;\n stepNumber: number | undefined;\n durationMs: number;\n success: boolean;\n output?: unknown;\n error?: unknown;\n }): Promise<void> {\n if (!this.extensionManager) return;\n if (this.extensionManager.getHookSubscribers(\"afterToolCall\").length === 0)\n return;\n const { createToolCallFinishSnapshot } =\n await import(\"./extensions/hook-proxy\");\n await this._dispatchExtensionObservation(\n \"afterToolCall\",\n createToolCallFinishSnapshot(event)\n );\n }\n\n private async _pipelineExtensionStepFinish(\n event: StepContext\n ): Promise<void> {\n if (!this.extensionManager) return;\n if (this.extensionManager.getHookSubscribers(\"onStepFinish\").length === 0)\n return;\n const { createStepFinishSnapshot } =\n await import(\"./extensions/hook-proxy\");\n await this._dispatchExtensionObservation(\n \"onStepFinish\",\n createStepFinishSnapshot(event)\n );\n }\n\n private async _pipelineExtensionChunk(event: ChunkContext): Promise<void> {\n if (!this.extensionManager) return;\n if (this.extensionManager.getHookSubscribers(\"onChunk\").length === 0)\n return;\n const { createChunkSnapshot } = await import(\"./extensions/hook-proxy\");\n await this._dispatchExtensionObservation(\n \"onChunk\",\n createChunkSnapshot(event as { chunk: { type: string } })\n );\n }\n\n // ── Host bridge methods (called by HostBridgeLoopback via DO RPC) ──\n\n async _hostReadFile(path: string): Promise<string | null> {\n return (await this.workspace.readFile(path)) ?? null;\n }\n\n async _hostWriteFile(path: string, content: string): Promise<void> {\n await this.workspace.writeFile(path, content);\n }\n\n async _hostDeleteFile(path: string): Promise<boolean> {\n try {\n await this.workspace.rm(path);\n return true;\n } catch {\n return false;\n }\n }\n\n async _hostListFiles(\n dir: string\n ): Promise<\n Array<{ name: string; type: string; size: number; path: string }>\n > {\n const entries = await this.workspace.readDir(dir);\n return entries.map((e) => ({\n name: e.name,\n type: e.type,\n size: e.size ?? 0,\n path: e.path ?? `${dir}/${e.name}`\n }));\n }\n\n async _hostGetContext(label: string): Promise<string | null> {\n const block = this.session.getContextBlock(label);\n return block?.content ?? null;\n }\n\n async _hostSetContext(label: string, content: string): Promise<void> {\n await this.session.replaceContextBlock(label, content);\n }\n\n async _hostGetMessages(\n limit?: number\n ): Promise<Array<{ id: string; role: string; content: string }>> {\n const history = this.session.getHistory();\n const sliced =\n limit !== undefined && limit !== null\n ? limit <= 0\n ? []\n : history.slice(-limit)\n : history;\n return sliced.map((m) => ({\n id: m.id,\n role: m.role,\n content: m.parts\n .filter((p): p is { type: \"text\"; text: string } => p.type === \"text\")\n .map((p) => p.text)\n .join(\"\")\n }));\n }\n\n async _hostSendMessage(content: string): Promise<void> {\n const msg = {\n id: crypto.randomUUID(),\n role: \"user\" as const,\n parts: [{ type: \"text\" as const, text: content }]\n };\n // Append directly to session — do NOT route through saveMessages,\n // which enqueues a full turn via TurnQueue and would deadlock if\n // called during an active turn (tool execution → host.sendMessage\n // → saveMessages → TurnQueue.enqueue → awaits current turn → deadlock).\n // The injected message is visible in the next turn's history.\n await this.session.appendMessage(msg);\n }\n\n async _hostGetSessionInfo(): Promise<{\n messageCount: number;\n }> {\n return {\n messageCount: this.session.getHistory().length\n };\n }\n\n // ── Sub-agent RPC entry point ───────────────────────────────────\n\n /**\n * Run a chat turn: persist the user message, run the agentic loop,\n * stream UIMessageChunk events via callback, and persist the\n * assistant's response.\n *\n * @param userMessage The user's message (string or UIMessage)\n * @param callback Streaming callback (typically an RpcTarget from the parent)\n * @param options Optional chat options (e.g. AbortSignal)\n */\n async chat(\n userMessage: string | UIMessage,\n callback: StreamCallback,\n options?: ChatOptions\n ): Promise<void> {\n const requestId = crypto.randomUUID();\n\n await this._turnQueue.enqueue(requestId, async () => {\n const userMsg: UIMessage =\n typeof userMessage === \"string\"\n ? {\n id: crypto.randomUUID(),\n role: \"user\",\n parts: [{ type: \"text\", text: userMessage }]\n }\n : userMessage;\n\n await this.session.appendMessage(userMsg);\n\n const accumulator = new StreamAccumulator({\n messageId: crypto.randomUUID()\n });\n\n try {\n const result = await agentContext.run(\n {\n agent: this,\n connection: undefined,\n request: undefined,\n email: undefined\n },\n () =>\n this._runInferenceLoop({\n signal: options?.signal,\n callerTools: options?.tools,\n continuation: false\n })\n );\n\n this._insideInferenceLoop = true;\n let aborted = false;\n try {\n for await (const chunk of result.toUIMessageStream()) {\n if (options?.signal?.aborted) {\n aborted = true;\n break;\n }\n accumulator.applyChunk(chunk as unknown as StreamChunkData);\n await callback.onEvent(JSON.stringify(chunk));\n }\n } finally {\n this._insideInferenceLoop = false;\n }\n\n const assistantMsg = accumulator.toMessage();\n this._persistAssistantMessage(assistantMsg);\n\n if (!aborted) {\n await callback.onDone();\n await this._fireResponseHook({\n message: assistantMsg,\n requestId,\n continuation: false,\n status: \"completed\"\n });\n } else {\n await this._fireResponseHook({\n message: assistantMsg,\n requestId,\n continuation: false,\n status: \"aborted\"\n });\n }\n } catch (error) {\n const assistantMsg =\n accumulator.parts.length > 0 ? accumulator.toMessage() : null;\n if (assistantMsg) {\n this._persistAssistantMessage(assistantMsg);\n }\n\n const wrapped = this.onChatError(error);\n const errorMessage =\n wrapped instanceof Error ? wrapped.message : String(wrapped);\n\n if (assistantMsg) {\n await this._fireResponseHook({\n message: assistantMsg,\n requestId,\n continuation: false,\n status: \"error\",\n error: errorMessage\n });\n }\n\n if (callback.onError) {\n await callback.onError(errorMessage);\n } else {\n throw wrapped;\n }\n }\n });\n }\n\n // ── Message access ──────────────────────────────────────────────\n\n /** Get the conversation history as UIMessage[]. */\n getMessages(): UIMessage[] {\n return this.messages;\n }\n\n /** Clear all messages from storage. */\n clearMessages(): void {\n this.session.clearMessages();\n }\n\n // ── Programmatic API ───────────────────────────────────────────\n\n /**\n * Inject messages and trigger a model turn — without a WebSocket request.\n *\n * Use for scheduled responses, webhook-triggered turns, proactive agents,\n * or chaining from `onChatResponse`.\n *\n * Accepts static messages or a callback that derives messages from the\n * current state (useful when multiple calls queue up — the callback runs\n * with the latest messages when the turn actually starts).\n *\n * @example Scheduled follow-up\n * ```typescript\n * async onScheduled() {\n * await this.saveMessages([{\n * id: crypto.randomUUID(),\n * role: \"user\",\n * parts: [{ type: \"text\", text: \"Time for your daily summary.\" }]\n * }]);\n * }\n * ```\n *\n * @example Function form\n * ```typescript\n * await this.saveMessages((current) => [\n * ...current,\n * { id: crypto.randomUUID(), role: \"user\", parts: [{ type: \"text\", text: \"Continue.\" }] }\n * ]);\n * ```\n */\n async saveMessages(\n messages:\n | UIMessage[]\n | ((currentMessages: UIMessage[]) => UIMessage[] | Promise<UIMessage[]>)\n ): Promise<SaveMessagesResult> {\n const requestId = crypto.randomUUID();\n const clientTools = this._lastClientTools;\n const body = this._lastBody;\n const epoch = this._turnQueue.generation;\n let status: SaveMessagesResult[\"status\"] = \"completed\";\n\n await this.keepAliveWhile(async () => {\n await this._turnQueue.enqueue(requestId, async () => {\n const resolved =\n typeof messages === \"function\"\n ? await messages(this.messages)\n : messages;\n\n if (this._turnQueue.generation !== epoch) {\n status = \"skipped\";\n return;\n }\n\n for (const msg of resolved) {\n await this.session.appendMessage(msg);\n }\n this._broadcastMessages();\n\n if (this._turnQueue.generation !== epoch) {\n status = \"skipped\";\n return;\n }\n\n const abortSignal = this._aborts.getSignal(requestId);\n try {\n const programmaticBody = async () => {\n const result = await agentContext.run(\n {\n agent: this,\n connection: undefined,\n request: undefined,\n email: undefined\n },\n () =>\n this._runInferenceLoop({\n signal: abortSignal,\n clientTools,\n body,\n continuation: false\n })\n );\n\n if (result) {\n await this._streamResult(requestId, result, abortSignal);\n }\n };\n\n if (this.chatRecovery) {\n await this.runFiber(\n `${(this.constructor as typeof Think).CHAT_FIBER_NAME}:${requestId}`,\n async () => {\n await programmaticBody();\n }\n );\n } else {\n await programmaticBody();\n }\n } finally {\n this._aborts.remove(requestId);\n }\n });\n });\n\n if (this._turnQueue.generation !== epoch && status === \"completed\") {\n status = \"skipped\";\n }\n\n return { requestId, status };\n }\n\n /**\n * Run a new LLM call following the last assistant message.\n *\n * The model sees the full conversation (including the last assistant\n * response) and generates a new response. The new response is persisted\n * as a separate assistant message. Building block for chat recovery\n * (Phase 4), \"generate more\" buttons, and self-correction.\n *\n * Note: this creates a new message, not an append to the existing one.\n * True continuation-as-append (chunk rewriting) is planned for Phase 4.\n *\n * Returns early with `status: \"skipped\"` if there is no assistant message\n * to continue from.\n */\n protected async continueLastTurn(\n body?: Record<string, unknown>\n ): Promise<SaveMessagesResult> {\n const lastLeaf = this.session.getLatestLeaf();\n if (!lastLeaf || lastLeaf.role !== \"assistant\") {\n return { requestId: \"\", status: \"skipped\" };\n }\n\n const requestId = crypto.randomUUID();\n const clientTools = this._lastClientTools;\n const resolvedBody = body ?? this._lastBody;\n const epoch = this._turnQueue.generation;\n let status: SaveMessagesResult[\"status\"] = \"completed\";\n\n await this.keepAliveWhile(async () => {\n await this._turnQueue.enqueue(requestId, async () => {\n if (this._turnQueue.generation !== epoch) {\n status = \"skipped\";\n return;\n }\n\n const abortSignal = this._aborts.getSignal(requestId);\n try {\n const continueTurnBody = async () => {\n const result = await agentContext.run(\n {\n agent: this,\n connection: undefined,\n request: undefined,\n email: undefined\n },\n () =>\n this._runInferenceLoop({\n signal: abortSignal,\n clientTools,\n body: resolvedBody,\n continuation: true\n })\n );\n\n if (result) {\n await this._streamResult(requestId, result, abortSignal, {\n continuation: true\n });\n }\n };\n\n if (this.chatRecovery) {\n await this.runFiber(\n `${(this.constructor as typeof Think).CHAT_FIBER_NAME}:${requestId}`,\n async () => {\n await continueTurnBody();\n }\n );\n } else {\n await continueTurnBody();\n }\n } finally {\n this._aborts.remove(requestId);\n }\n });\n });\n\n if (this._turnQueue.generation !== epoch && status === \"completed\") {\n status = \"skipped\";\n }\n\n return { requestId, status };\n }\n\n // ── WebSocket protocol ──────────────────────────────────────────\n\n private _setupProtocolHandlers() {\n const _onConnect = this.onConnect.bind(this);\n this.onConnect = async (\n connection: Connection,\n ctx: { request: Request }\n ) => {\n if (this._resumableStream.hasActiveStream()) {\n this._notifyStreamResuming(connection);\n }\n connection.send(\n JSON.stringify({\n type: MSG_CHAT_MESSAGES,\n messages: this.messages\n })\n );\n return _onConnect(connection, ctx);\n };\n\n const _onClose = this.onClose.bind(this);\n this.onClose = async (\n connection: Connection,\n code: number,\n reason: string,\n wasClean: boolean\n ) => {\n this._pendingResumeConnections.delete(connection.id);\n this._continuation.awaitingConnections.delete(connection.id);\n if (this._continuation.pending?.connectionId === connection.id) {\n this._continuation.pending = null;\n }\n if (this._continuation.activeConnectionId === connection.id) {\n this._continuation.activeConnectionId = null;\n }\n return _onClose(connection, code, reason, wasClean);\n };\n\n const _onMessage = this.onMessage.bind(this);\n this.onMessage = async (connection: Connection, message: WSMessage) => {\n if (typeof message === \"string\") {\n const event = parseProtocolMessage(message);\n if (event) {\n await this._handleProtocolEvent(connection, event);\n return;\n }\n }\n return _onMessage(connection, message);\n };\n\n const _onRequest = this.onRequest.bind(this);\n this.onRequest = async (request: Request) => {\n const url = new URL(request.url);\n if (\n url.pathname === \"/get-messages\" ||\n url.pathname.endsWith(\"/get-messages\")\n ) {\n return Response.json(this.messages);\n }\n return _onRequest(request);\n };\n }\n\n private async _handleProtocolEvent(\n connection: Connection,\n event: NonNullable<ReturnType<typeof parseProtocolMessage>>\n ): Promise<void> {\n switch (event.type) {\n case \"stream-resume-request\":\n this._handleStreamResumeRequest(connection);\n break;\n\n case \"stream-resume-ack\":\n this._handleStreamResumeAck(connection, event.id);\n break;\n\n case \"chat-request\":\n if (event.init?.method === \"POST\") {\n await this._handleChatRequest(connection, event);\n }\n break;\n\n case \"tool-result\": {\n if (\n event.clientTools &&\n Array.isArray(event.clientTools) &&\n event.clientTools.length > 0\n ) {\n this._lastClientTools = event.clientTools as ClientToolSchema[];\n this._persistClientTools();\n }\n const resultPromise = Promise.resolve().then(() => {\n this._applyToolResult(\n event.toolCallId,\n event.output,\n event.state as \"output-error\" | undefined,\n event.errorText\n );\n return true;\n });\n this._pendingInteractionPromise = resultPromise;\n resultPromise\n .finally(() => {\n if (this._pendingInteractionPromise === resultPromise) {\n this._pendingInteractionPromise = null;\n }\n })\n .catch(() => {});\n if (event.autoContinue) {\n this._scheduleAutoContinuation(connection);\n }\n break;\n }\n\n case \"tool-approval\": {\n const approvalPromise = Promise.resolve().then(() => {\n this._applyToolApproval(event.toolCallId, event.approved);\n return true;\n });\n this._pendingInteractionPromise = approvalPromise;\n approvalPromise\n .finally(() => {\n if (this._pendingInteractionPromise === approvalPromise) {\n this._pendingInteractionPromise = null;\n }\n })\n .catch(() => {});\n if (event.autoContinue) {\n this._scheduleAutoContinuation(connection);\n }\n break;\n }\n\n case \"clear\":\n this._handleClear(connection);\n break;\n\n case \"cancel\":\n this._aborts.cancel(event.id);\n break;\n\n case \"messages\":\n break;\n }\n }\n\n private _handleStreamResumeRequest(connection: Connection): void {\n if (this._resumableStream.hasActiveStream()) {\n if (\n this._continuation.activeRequestId ===\n this._resumableStream.activeRequestId &&\n this._continuation.activeConnectionId !== null &&\n this._continuation.activeConnectionId !== connection.id\n ) {\n connection.send(JSON.stringify({ type: MSG_STREAM_RESUME_NONE }));\n } else {\n this._notifyStreamResuming(connection);\n }\n } else if (\n this._continuation.pending !== null &&\n this._continuation.pending.connectionId === connection.id\n ) {\n this._continuation.awaitingConnections.set(connection.id, connection);\n } else {\n connection.send(JSON.stringify({ type: MSG_STREAM_RESUME_NONE }));\n }\n }\n\n private _handleStreamResumeAck(\n connection: Connection,\n requestId: string\n ): void {\n this._pendingResumeConnections.delete(connection.id);\n if (\n this._resumableStream.hasActiveStream() &&\n this._resumableStream.activeRequestId === requestId\n ) {\n const orphanedStreamId = this._resumableStream.replayChunks(\n connection,\n this._resumableStream.activeRequestId\n );\n if (orphanedStreamId) {\n this._persistOrphanedStream(orphanedStreamId);\n }\n }\n }\n\n private async _handleChatRequest(\n connection: Connection,\n event: Extract<\n NonNullable<ReturnType<typeof parseProtocolMessage>>,\n { type: \"chat-request\" }\n >\n ) {\n if (!event.init?.body) return;\n\n let rawParsed: Record<string, unknown>;\n try {\n rawParsed = JSON.parse(event.init.body) as Record<string, unknown>;\n } catch {\n return;\n }\n\n const {\n messages: incomingMessages,\n clientTools: rawClientTools,\n trigger: rawTrigger,\n ...customBody\n } = rawParsed as {\n messages?: UIMessage[];\n clientTools?: ClientToolSchema[];\n trigger?: string;\n [key: string]: unknown;\n };\n if (!Array.isArray(incomingMessages)) return;\n\n const isRegeneration = rawTrigger === \"regenerate-message\";\n const isSubmitMessage = !isRegeneration;\n const requestId = event.id;\n\n // ── Concurrency decision (before persisting anything) ────────\n const concurrencyDecision =\n this._getSubmitConcurrencyDecision(isSubmitMessage);\n\n if (concurrencyDecision.action === \"drop\") {\n this._rollbackDroppedSubmit(connection);\n this._completeSkippedRequest(connection, requestId);\n return;\n }\n\n // ── Persist client tools and body (only for accepted requests) ──\n const requestClientTools =\n rawClientTools && rawClientTools.length > 0 ? rawClientTools : undefined;\n if (requestClientTools) {\n this._lastClientTools = requestClientTools;\n this._persistClientTools();\n } else if (rawClientTools !== undefined) {\n this._lastClientTools = undefined;\n this._persistClientTools();\n }\n\n const requestBody =\n Object.keys(customBody).length > 0 ? customBody : undefined;\n this._lastBody = requestBody;\n this._persistBody();\n\n // ── Persist and broadcast user messages ──────────────────────\n const clientToolsForTurn = this._lastClientTools;\n const bodyForTurn = this._lastBody;\n\n let branchParentId: string | undefined;\n if (isRegeneration && incomingMessages.length > 0) {\n branchParentId = incomingMessages[incomingMessages.length - 1].id;\n }\n\n for (const msg of incomingMessages) {\n await this.session.appendMessage(msg);\n }\n\n this._broadcastMessages([connection.id]);\n\n // ── Enter turn queue ────────────────────────────────────────\n const abortSignal = this._aborts.getSignal(requestId);\n const epoch = this._turnQueue.generation;\n\n try {\n await this.keepAliveWhile(async () => {\n const turnResult = await this._turnQueue.enqueue(\n requestId,\n async () => {\n // Superseded by a later overlapping submit (latest/merge/debounce)\n if (this._isSupersededSubmit(concurrencyDecision.submitSequence)) {\n this._completeSkippedRequest(connection, requestId);\n return;\n }\n\n // Debounce: wait for quiet period\n if (concurrencyDecision.debounceUntilMs !== null) {\n await this._waitForTimestamp(concurrencyDecision.debounceUntilMs);\n\n if (this._turnQueue.generation !== epoch) {\n this._completeSkippedRequest(connection, requestId);\n return;\n }\n if (\n this._isSupersededSubmit(concurrencyDecision.submitSequence)\n ) {\n this._completeSkippedRequest(connection, requestId);\n return;\n }\n }\n\n const chatTurnBody = async () => {\n const result = await agentContext.run(\n {\n agent: this,\n connection,\n request: undefined,\n email: undefined\n },\n () =>\n this._runInferenceLoop({\n signal: abortSignal,\n clientTools: clientToolsForTurn,\n body: bodyForTurn,\n continuation: false\n })\n );\n\n if (result) {\n await this._streamResult(requestId, result, abortSignal, {\n parentId: branchParentId\n });\n } else {\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"No response was generated.\",\n done: true\n });\n }\n };\n\n if (this.chatRecovery) {\n await this.runFiber(\n `${(this.constructor as typeof Think).CHAT_FIBER_NAME}:${requestId}`,\n async () => {\n await chatTurnBody();\n }\n );\n } else {\n await chatTurnBody();\n }\n }\n );\n\n if (turnResult.status === \"stale\") {\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"\",\n done: true\n });\n }\n });\n } catch (error) {\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: error instanceof Error ? error.message : \"Error\",\n done: true,\n error: true\n });\n } finally {\n this._aborts.remove(requestId);\n }\n }\n\n /**\n * Abort the active turn, invalidate queued turns, and reset\n * concurrency/continuation state. Call this when intercepting\n * clear events or implementing custom reset logic.\n *\n * Does NOT clear messages, streams, or persisted state —\n * only turn execution state.\n */\n protected resetTurnState(): void {\n this._turnQueue.reset();\n this._aborts.destroyAll();\n if (this._continuationTimer) {\n clearTimeout(this._continuationTimer);\n this._continuationTimer = null;\n }\n this._cancelActiveDebounce();\n this._pendingInteractionPromise = null;\n this._continuation.sendResumeNone();\n this._continuation.clearAll();\n }\n\n private _handleClear(connection?: Connection) {\n this.resetTurnState();\n\n this._resumableStream.clearAll();\n this._pendingResumeConnections.clear();\n this._lastClientTools = undefined;\n this._persistClientTools();\n this._lastBody = undefined;\n this._persistBody();\n this.session.clearMessages();\n this._broadcast(\n { type: MSG_CHAT_CLEAR },\n connection ? [connection.id] : undefined\n );\n }\n\n private async _streamResult(\n requestId: string,\n result: StreamableResult,\n abortSignal?: AbortSignal,\n options?: { continuation?: boolean; parentId?: string }\n ) {\n const clearGen = this._turnQueue.generation;\n const streamId = this._resumableStream.start(requestId);\n const continuation = options?.continuation ?? false;\n const parentId = options?.parentId;\n\n if (this._continuation.pending?.requestId === requestId) {\n this._continuation.activatePending();\n this._continuation.flushAwaitingConnections((c) =>\n this._notifyStreamResuming(c as Connection)\n );\n }\n\n const accumulator = new StreamAccumulator({\n messageId: crypto.randomUUID()\n });\n\n let doneSent = false;\n let streamAborted = false;\n let streamError: string | undefined;\n\n try {\n this._insideInferenceLoop = true;\n try {\n for await (const chunk of result.toUIMessageStream()) {\n if (abortSignal?.aborted) {\n streamAborted = true;\n break;\n }\n\n const { action } = accumulator.applyChunk(\n chunk as unknown as StreamChunkData\n );\n\n if (action?.type === \"error\") {\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: action.error,\n done: false,\n error: true\n });\n continue;\n }\n\n const chunkBody = JSON.stringify(chunk);\n this._resumableStream.storeChunk(streamId, chunkBody);\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: chunkBody,\n done: false\n });\n }\n } finally {\n this._insideInferenceLoop = false;\n }\n\n this._resumableStream.complete(streamId);\n this._pendingResumeConnections.clear();\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"\",\n done: true\n });\n doneSent = true;\n } catch (error) {\n streamError = error instanceof Error ? error.message : \"Stream error\";\n this._resumableStream.markError(streamId);\n this._pendingResumeConnections.clear();\n if (!doneSent) {\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: streamError,\n done: true,\n error: true\n });\n doneSent = true;\n }\n } finally {\n if (!doneSent) {\n this._resumableStream.markError(streamId);\n this._pendingResumeConnections.clear();\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"\",\n done: true\n });\n }\n }\n\n if (\n accumulator.parts.length > 0 &&\n this._turnQueue.generation === clearGen\n ) {\n try {\n const assistantMsg = accumulator.toMessage();\n this._persistAssistantMessage(assistantMsg, parentId);\n this._broadcastMessages();\n\n await this._fireResponseHook({\n message: assistantMsg,\n requestId,\n continuation,\n status: streamAborted\n ? \"aborted\"\n : streamError\n ? \"error\"\n : \"completed\",\n error: streamError\n });\n } catch (e) {\n console.error(\"Failed to persist assistant message:\", e);\n }\n }\n }\n\n // ── Session-backed persistence ──────────────────────────────────\n\n private _persistAssistantMessage(msg: UIMessage, parentId?: string): void {\n const sanitized = sanitizeMessage(msg);\n const safe = enforceRowSizeLimit(sanitized);\n\n const existing = this.session.getMessage(safe.id);\n if (existing) {\n this.session.updateMessage(safe);\n } else {\n // appendMessage is async due to potential auto-compaction, but\n // we fire-and-forget here since the message write itself is synchronous\n // in AgentSessionProvider — only the optional compaction is async.\n // parentId is set for regeneration — the new response branches from\n // the same parent as the old one rather than appending to the latest leaf.\n void this.session.appendMessage(safe, parentId);\n }\n }\n\n private _persistClientTools(): void {\n if (this._lastClientTools) {\n this._configSet(\"lastClientTools\", JSON.stringify(this._lastClientTools));\n } else {\n this._configDelete(\"lastClientTools\");\n }\n }\n\n private _restoreClientTools(): void {\n const raw = this._configGet(\"lastClientTools\");\n if (raw) {\n try {\n this._lastClientTools = JSON.parse(raw);\n } catch {\n this._lastClientTools = undefined;\n }\n }\n }\n\n private _persistBody(): void {\n if (this._lastBody) {\n this._configSet(\"lastBody\", JSON.stringify(this._lastBody));\n } else {\n this._configDelete(\"lastBody\");\n }\n }\n\n private _restoreBody(): void {\n const raw = this._configGet(\"lastBody\");\n if (raw) {\n try {\n this._lastBody = JSON.parse(raw);\n } catch {\n this._lastBody = undefined;\n }\n }\n }\n\n // ── Tool state updates (shared primitives from agents/chat) ─────\n\n private _applyToolResult(\n toolCallId: string,\n output: unknown,\n overrideState?: \"output-error\",\n errorText?: string\n ): void {\n const update = toolResultUpdate(\n toolCallId,\n output,\n overrideState,\n errorText\n );\n this._applyToolUpdateToMessages(update);\n }\n\n private _applyToolApproval(toolCallId: string, approved: boolean): void {\n const update = toolApprovalUpdate(toolCallId, approved);\n this._applyToolUpdateToMessages(update);\n }\n\n private _applyToolUpdateToMessages(update: {\n toolCallId: string;\n matchStates: string[];\n apply: (part: Record<string, unknown>) => Record<string, unknown>;\n }): void {\n const history = this.messages;\n for (const msg of history) {\n const result = applyToolUpdate(\n msg.parts as Array<Record<string, unknown>>,\n update\n );\n if (result) {\n const updatedMsg = {\n ...msg,\n parts: result.parts as UIMessage[\"parts\"]\n };\n const safe = enforceRowSizeLimit(sanitizeMessage(updatedMsg));\n this.session.updateMessage(safe);\n this._broadcast({ type: MSG_MESSAGE_UPDATED, message: safe });\n return;\n }\n }\n }\n\n // ── Stability + pending interactions ─────────────────────────────\n\n protected hasPendingInteraction(): boolean {\n return this.messages.some(\n (message) =>\n message.role === \"assistant\" &&\n this._messageHasPendingInteraction(message)\n );\n }\n\n protected async waitUntilStable(options?: {\n timeout?: number;\n }): Promise<boolean> {\n const deadline =\n options?.timeout != null ? Date.now() + options.timeout : null;\n\n while (true) {\n if (\n (await this._awaitWithDeadline(\n this._turnQueue.waitForIdle(),\n deadline\n )) === TIMED_OUT\n ) {\n return false;\n }\n\n if (!this.hasPendingInteraction()) {\n return true;\n }\n\n const pending = this._pendingInteractionPromise;\n if (pending) {\n let result: boolean | typeof TIMED_OUT;\n try {\n result = await this._awaitWithDeadline(pending, deadline);\n } catch {\n continue;\n }\n if (result === TIMED_OUT) {\n return false;\n }\n } else {\n if (\n (await this._awaitWithDeadline(\n new Promise<void>((resolve) => setTimeout(resolve, 100)),\n deadline\n )) === TIMED_OUT\n ) {\n return false;\n }\n }\n }\n }\n\n private async _awaitWithDeadline<T>(\n promise: Promise<T>,\n deadline: number | null\n ): Promise<T | typeof TIMED_OUT> {\n if (deadline == null) {\n return promise;\n }\n const remainingMs = Math.max(0, deadline - Date.now());\n let timer: ReturnType<typeof setTimeout>;\n const result = await Promise.race([\n promise,\n new Promise<typeof TIMED_OUT>((resolve) => {\n timer = setTimeout(() => resolve(TIMED_OUT), remainingMs);\n })\n ]);\n clearTimeout(timer!);\n return result;\n }\n\n private _messageHasPendingInteraction(message: UIMessage): boolean {\n return message.parts.some(\n (part) =>\n \"state\" in part &&\n ((part as Record<string, unknown>).state === \"input-available\" ||\n (part as Record<string, unknown>).state === \"approval-requested\")\n );\n }\n\n // ── Chat recovery via fibers ───────────────────────────────────\n\n protected override async _handleInternalFiberRecovery(\n ctx: FiberRecoveryContext\n ): Promise<boolean> {\n const chatPrefix = (this.constructor as typeof Think).CHAT_FIBER_NAME + \":\";\n if (!ctx.name.startsWith(chatPrefix)) {\n return false;\n }\n\n const requestId = ctx.name.slice(chatPrefix.length);\n\n let streamId = \"\";\n if (requestId) {\n const rows = this.sql<{ id: string }>`\n SELECT id FROM cf_ai_chat_stream_metadata\n WHERE request_id = ${requestId}\n ORDER BY created_at DESC LIMIT 1\n `;\n if (rows.length > 0) {\n streamId = rows[0].id;\n }\n }\n if (!streamId && this._resumableStream.hasActiveStream()) {\n streamId = this._resumableStream.activeStreamId ?? \"\";\n }\n\n const partial = streamId\n ? this._getPartialStreamText(streamId)\n : { text: \"\", parts: [] as MessagePart[] };\n\n const options = await this.onChatRecovery({\n streamId: streamId ?? \"\",\n requestId,\n partialText: partial.text,\n partialParts: partial.parts,\n recoveryData: ctx.snapshot,\n messages: [...this.messages],\n lastBody: this._lastBody,\n lastClientTools: this._lastClientTools,\n createdAt: ctx.createdAt\n });\n\n const streamStillActive =\n streamId &&\n this._resumableStream.hasActiveStream() &&\n this._resumableStream.activeStreamId === streamId;\n\n if (options.persist !== false && streamStillActive) {\n this._persistOrphanedStream(streamId);\n }\n\n if (streamStillActive) {\n this._resumableStream.complete(streamId);\n }\n\n if (options.continue !== false) {\n const lastLeaf = this.session.getLatestLeaf();\n const targetId = lastLeaf?.role === \"assistant\" ? lastLeaf.id : undefined;\n await this.schedule(\n 0,\n \"_chatRecoveryContinue\",\n targetId ? { targetAssistantId: targetId } : undefined,\n { idempotent: true }\n );\n }\n\n return true;\n }\n\n protected async onChatRecovery(\n _ctx: ChatRecoveryContext\n ): Promise<ChatRecoveryOptions> {\n return {};\n }\n\n async _chatRecoveryContinue(data?: {\n targetAssistantId?: string;\n }): Promise<void> {\n const ready = await this.waitUntilStable({ timeout: 10_000 });\n if (!ready) {\n console.warn(\n \"[Think] _chatRecoveryContinue timed out waiting for stable state, skipping continuation\"\n );\n return;\n }\n\n const targetId = data?.targetAssistantId;\n const lastLeaf = this.session.getLatestLeaf();\n if (targetId && lastLeaf?.id !== targetId) {\n return;\n }\n\n await this.continueLastTurn();\n }\n\n private _getPartialStreamText(streamId: string): {\n text: string;\n parts: MessagePart[];\n } {\n const chunks = this._resumableStream.getStreamChunks(streamId);\n const parts: MessagePart[] = [];\n\n for (const chunk of chunks) {\n try {\n const data = JSON.parse(chunk.body);\n applyChunkToParts(parts, data);\n } catch {\n // skip malformed chunks\n }\n }\n\n const text = parts\n .filter(\n (p): p is MessagePart & { type: \"text\"; text: string } =>\n p.type === \"text\" && \"text\" in p\n )\n .map((p) => p.text)\n .join(\"\");\n\n return { text, parts };\n }\n\n // ── Concurrency strategies ──────────────────────────────────────\n\n private _normalizeMessageConcurrency(): NormalizedMessageConcurrency {\n if (typeof this.messageConcurrency === \"string\") {\n return this.messageConcurrency;\n }\n const debounceMs = this.messageConcurrency.debounceMs;\n return {\n strategy: \"debounce\",\n debounceMs:\n typeof debounceMs === \"number\" &&\n Number.isFinite(debounceMs) &&\n debounceMs >= 0\n ? debounceMs\n : Think.MESSAGE_DEBOUNCE_MS\n };\n }\n\n private _getSubmitConcurrencyDecision(\n isSubmitMessage: boolean\n ): SubmitConcurrencyDecision {\n const queuedTurns = this._turnQueue.queuedCount();\n\n if (!isSubmitMessage || queuedTurns === 0) {\n return {\n action: \"execute\",\n submitSequence: null,\n debounceUntilMs: null\n };\n }\n\n const concurrency = this._normalizeMessageConcurrency();\n\n if (concurrency === \"queue\") {\n return {\n action: \"execute\",\n submitSequence: null,\n debounceUntilMs: null\n };\n }\n\n if (concurrency === \"drop\") {\n return {\n action: \"drop\",\n submitSequence: null,\n debounceUntilMs: null\n };\n }\n\n const submitSequence = ++this._submitSequence;\n this._latestOverlappingSubmitSequence = submitSequence;\n\n if (concurrency === \"latest\" || concurrency === \"merge\") {\n return {\n action: \"execute\",\n submitSequence,\n debounceUntilMs: null\n };\n }\n\n return {\n action: \"execute\",\n submitSequence,\n debounceUntilMs: Date.now() + concurrency.debounceMs\n };\n }\n\n private _isSupersededSubmit(submitSequence: number | null): boolean {\n return (\n submitSequence !== null &&\n submitSequence < this._latestOverlappingSubmitSequence\n );\n }\n\n private async _waitForTimestamp(timestampMs: number): Promise<void> {\n const remainingMs = timestampMs - Date.now();\n if (remainingMs <= 0) return;\n\n await new Promise<void>((resolve) => {\n this._activeDebounceResolve = resolve;\n this._activeDebounceTimer = setTimeout(() => {\n this._activeDebounceTimer = null;\n this._activeDebounceResolve = null;\n resolve();\n }, remainingMs);\n });\n }\n\n private _cancelActiveDebounce(): void {\n if (this._activeDebounceTimer !== null) {\n clearTimeout(this._activeDebounceTimer);\n this._activeDebounceTimer = null;\n }\n if (this._activeDebounceResolve !== null) {\n this._activeDebounceResolve();\n this._activeDebounceResolve = null;\n }\n }\n\n private _completeSkippedRequest(\n connection: Connection,\n requestId: string\n ): void {\n connection.send(\n JSON.stringify({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"\",\n done: true\n })\n );\n }\n\n private _rollbackDroppedSubmit(connection: Connection): void {\n connection.send(\n JSON.stringify({\n type: MSG_CHAT_MESSAGES,\n messages: this.messages\n })\n );\n }\n\n // ── Auto-continuation ──────────────────────────────────────────\n\n private _scheduleAutoContinuation(connection: Connection): void {\n if (this._continuation.pending?.pastCoalesce) {\n this._continuation.deferred = {\n connection,\n connectionId: connection.id,\n clientTools: this._lastClientTools,\n body: undefined,\n errorPrefix: \"[Think] Auto-continuation failed:\",\n prerequisite: null\n };\n return;\n }\n\n if (this._continuation.pending) {\n this._continuation.pending.connection = connection;\n this._continuation.pending.connectionId = connection.id;\n this._continuation.pending.clientTools = this._lastClientTools;\n this._continuation.awaitingConnections.set(connection.id, connection);\n return;\n }\n\n if (this._continuationTimer) {\n clearTimeout(this._continuationTimer);\n }\n this._continuationTimer = setTimeout(() => {\n this._continuationTimer = null;\n this._fireAutoContinuation(connection);\n }, 50);\n }\n\n private _fireAutoContinuation(connection: Connection): void {\n if (!this._continuation.pending) {\n const requestId = crypto.randomUUID();\n this._continuation.pending = {\n connection,\n connectionId: connection.id,\n requestId,\n clientTools: this._lastClientTools,\n body: undefined,\n errorPrefix: \"[Think] Auto-continuation failed:\",\n prerequisite: null,\n pastCoalesce: false\n };\n this._continuation.awaitingConnections.set(connection.id, connection);\n }\n\n const { requestId, clientTools } = this._continuation.pending!;\n const abortSignal = this._aborts.getSignal(requestId);\n\n this.keepAliveWhile(async () => {\n await this._turnQueue.enqueue(requestId, async () => {\n if (this._continuation.pending) {\n this._continuation.pending.pastCoalesce = true;\n }\n let streamed = false;\n try {\n const continuationBody = async () => {\n const result = await agentContext.run(\n {\n agent: this,\n connection,\n request: undefined,\n email: undefined\n },\n () =>\n this._runInferenceLoop({\n signal: abortSignal,\n clientTools,\n body: this._lastBody,\n continuation: true\n })\n );\n if (result) {\n await this._streamResult(requestId, result, abortSignal, {\n continuation: true\n });\n streamed = true;\n }\n };\n\n if (this.chatRecovery) {\n await this.runFiber(\n `${(this.constructor as typeof Think).CHAT_FIBER_NAME}:${requestId}`,\n async () => {\n await continuationBody();\n }\n );\n } else {\n await continuationBody();\n }\n } finally {\n this._aborts.remove(requestId);\n if (!streamed) {\n this._continuation.sendResumeNone();\n }\n this._continuation.clearPending();\n this._activateDeferredContinuation();\n }\n });\n }).catch((error) => {\n console.error(\"[Think] Auto-continuation failed:\", error);\n this._aborts.remove(requestId);\n });\n }\n\n private _activateDeferredContinuation(): void {\n const pending = this._continuation.activateDeferred(() =>\n crypto.randomUUID()\n );\n if (!pending) return;\n\n this._fireAutoContinuation(pending.connection as Connection);\n }\n\n // ── Response hook ──────────────────────────────────────────────\n\n private async _fireResponseHook(result: ChatResponseResult): Promise<void> {\n if (this._insideResponseHook) return;\n this._insideResponseHook = true;\n try {\n await this.onChatResponse(result);\n } catch (err) {\n console.error(\"[Think] onChatResponse error:\", err);\n } finally {\n this._insideResponseHook = false;\n }\n }\n\n // ── Resume helpers ──────────────────────────────────────────────\n\n private _notifyStreamResuming(connection: Connection): void {\n if (!this._resumableStream.hasActiveStream()) return;\n this._pendingResumeConnections.add(connection.id);\n connection.send(\n JSON.stringify({\n type: MSG_STREAM_RESUMING,\n id: this._resumableStream.activeRequestId\n })\n );\n }\n\n private _persistOrphanedStream(streamId: string): void {\n this._resumableStream.flushBuffer();\n const chunks = this._resumableStream.getStreamChunks(streamId);\n if (chunks.length === 0) return;\n\n const accumulator = new StreamAccumulator({\n messageId: crypto.randomUUID()\n });\n for (const chunk of chunks) {\n try {\n accumulator.applyChunk(JSON.parse(chunk.body) as StreamChunkData);\n } catch {\n // skip malformed chunks\n }\n }\n\n if (accumulator.parts.length > 0) {\n this._persistAssistantMessage(accumulator.toMessage());\n this._broadcastMessages();\n }\n }\n\n private _broadcastChat(message: Record<string, unknown>, exclude?: string[]) {\n const allExclusions = [\n ...(exclude || []),\n ...this._pendingResumeConnections\n ];\n this.broadcast(JSON.stringify(message), allExclusions);\n }\n\n private _broadcast(message: Record<string, unknown>, exclude?: string[]) {\n this.broad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
*
|
|
59
59
|
* export class MyAgent extends Think<Env> {
|
|
60
60
|
* getModel() {
|
|
61
|
-
* return createWorkersAI({ binding: this.env.AI })("@cf/moonshotai/kimi-k2.
|
|
61
|
+
* return createWorkersAI({ binding: this.env.AI })("@cf/moonshotai/kimi-k2.6");
|
|
62
62
|
* }
|
|
63
63
|
*
|
|
64
64
|
* getTools() {
|
package/dist/tools/browser.js
CHANGED
|
@@ -25,7 +25,7 @@ import { EXECUTE_DESCRIPTION, SEARCH_DESCRIPTION, createBrowserToolHandlers } fr
|
|
|
25
25
|
*
|
|
26
26
|
* export class MyAgent extends Think<Env> {
|
|
27
27
|
* getModel() {
|
|
28
|
-
* return createWorkersAI({ binding: this.env.AI })("@cf/moonshotai/kimi-k2.
|
|
28
|
+
* return createWorkersAI({ binding: this.env.AI })("@cf/moonshotai/kimi-k2.6");
|
|
29
29
|
* }
|
|
30
30
|
*
|
|
31
31
|
* getTools() {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"browser.js","names":[],"sources":["../../src/tools/browser.ts"],"sourcesContent":["import type { ToolSet } from \"ai\";\nimport {\n createBrowserToolHandlers,\n SEARCH_DESCRIPTION,\n EXECUTE_DESCRIPTION\n} from \"agents/browser\";\nimport { tool } from \"ai\";\nimport { z } from \"zod\";\n\nexport interface CreateBrowserToolsOptions {\n /**\n * Browser Rendering binding (Fetcher).\n *\n * This is the primary way to connect — works both locally in\n * `wrangler dev` and when deployed to Cloudflare Workers.\n *\n * Requires `\"browser\": { \"binding\": \"BROWSER\" }` in wrangler.jsonc.\n */\n browser?: Fetcher;\n\n /**\n * Optional CDP base URL override (e.g. `http://localhost:9222`).\n *\n * Use when connecting to a manually managed Chrome instance or\n * a remote CDP endpoint behind a tunnel.\n */\n cdpUrl?: string;\n\n /**\n * Headers to send with CDP URL discovery requests.\n * Useful when the CDP endpoint requires authentication\n * (e.g. Cloudflare Access headers).\n */\n cdpHeaders?: Record<string, string>;\n\n /**\n * WorkerLoader binding for sandboxed code execution.\n *\n * Requires `\"worker_loaders\": [{ \"binding\": \"LOADER\" }]` in wrangler.jsonc.\n */\n loader: WorkerLoader;\n\n /**\n * Execution timeout in milliseconds. Defaults to 30000 (30s).\n */\n timeout?: number;\n}\n\n/**\n * Create browser automation tools for Think agents.\n *\n * Returns a `ToolSet` with two tools:\n *\n * - **`browser_search`** — query the Chrome DevTools Protocol spec\n * to discover commands, events, and types. The LLM writes JavaScript\n * that runs against a cached, normalized copy of the protocol.\n *\n * - **`browser_execute`** — run CDP commands against a live browser\n * session. Each call opens a fresh session, exposes a `cdp` helper,\n * and closes the session on completion.\n *\n * Both tools use the code-mode pattern: the LLM writes JavaScript\n * async arrow functions that execute in a sandboxed Worker isolate.\n *\n * @example\n * ```ts\n * import { Think } from \"@cloudflare/think\";\n * import { createBrowserTools } from \"@cloudflare/think/tools/browser\";\n *\n * export class MyAgent extends Think<Env> {\n * getModel() {\n * return createWorkersAI({ binding: this.env.AI })(\"@cf/moonshotai/kimi-k2.
|
|
1
|
+
{"version":3,"file":"browser.js","names":[],"sources":["../../src/tools/browser.ts"],"sourcesContent":["import type { ToolSet } from \"ai\";\nimport {\n createBrowserToolHandlers,\n SEARCH_DESCRIPTION,\n EXECUTE_DESCRIPTION\n} from \"agents/browser\";\nimport { tool } from \"ai\";\nimport { z } from \"zod\";\n\nexport interface CreateBrowserToolsOptions {\n /**\n * Browser Rendering binding (Fetcher).\n *\n * This is the primary way to connect — works both locally in\n * `wrangler dev` and when deployed to Cloudflare Workers.\n *\n * Requires `\"browser\": { \"binding\": \"BROWSER\" }` in wrangler.jsonc.\n */\n browser?: Fetcher;\n\n /**\n * Optional CDP base URL override (e.g. `http://localhost:9222`).\n *\n * Use when connecting to a manually managed Chrome instance or\n * a remote CDP endpoint behind a tunnel.\n */\n cdpUrl?: string;\n\n /**\n * Headers to send with CDP URL discovery requests.\n * Useful when the CDP endpoint requires authentication\n * (e.g. Cloudflare Access headers).\n */\n cdpHeaders?: Record<string, string>;\n\n /**\n * WorkerLoader binding for sandboxed code execution.\n *\n * Requires `\"worker_loaders\": [{ \"binding\": \"LOADER\" }]` in wrangler.jsonc.\n */\n loader: WorkerLoader;\n\n /**\n * Execution timeout in milliseconds. Defaults to 30000 (30s).\n */\n timeout?: number;\n}\n\n/**\n * Create browser automation tools for Think agents.\n *\n * Returns a `ToolSet` with two tools:\n *\n * - **`browser_search`** — query the Chrome DevTools Protocol spec\n * to discover commands, events, and types. The LLM writes JavaScript\n * that runs against a cached, normalized copy of the protocol.\n *\n * - **`browser_execute`** — run CDP commands against a live browser\n * session. Each call opens a fresh session, exposes a `cdp` helper,\n * and closes the session on completion.\n *\n * Both tools use the code-mode pattern: the LLM writes JavaScript\n * async arrow functions that execute in a sandboxed Worker isolate.\n *\n * @example\n * ```ts\n * import { Think } from \"@cloudflare/think\";\n * import { createBrowserTools } from \"@cloudflare/think/tools/browser\";\n *\n * export class MyAgent extends Think<Env> {\n * getModel() {\n * return createWorkersAI({ binding: this.env.AI })(\"@cf/moonshotai/kimi-k2.6\");\n * }\n *\n * getTools() {\n * return {\n * ...createBrowserTools({\n * browser: this.env.BROWSER,\n * loader: this.env.LOADER,\n * }),\n * };\n * }\n * }\n * ```\n */\nexport function createBrowserTools(\n options: CreateBrowserToolsOptions\n): ToolSet {\n const handlers = createBrowserToolHandlers({\n browser: options.browser,\n cdpUrl: options.cdpUrl,\n cdpHeaders: options.cdpHeaders,\n loader: options.loader,\n timeout: options.timeout\n });\n\n return {\n browser_search: tool({\n description: SEARCH_DESCRIPTION,\n inputSchema: z.object({\n code: z\n .string()\n .describe(\"JavaScript async arrow function that queries the CDP spec\")\n }),\n execute: async ({ code }) => {\n const result = await handlers.search(code);\n if (result.isError) {\n throw new Error(result.text);\n }\n return result.text;\n }\n }),\n\n browser_execute: tool({\n description: EXECUTE_DESCRIPTION,\n inputSchema: z.object({\n code: z\n .string()\n .describe(\"JavaScript async arrow function that uses the cdp helper\")\n }),\n execute: async ({ code }) => {\n const result = await handlers.execute(code);\n if (result.isError) {\n throw new Error(result.text);\n }\n return result.text;\n }\n })\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqFA,SAAgB,mBACd,SACS;CACT,MAAM,WAAW,0BAA0B;EACzC,SAAS,QAAQ;EACjB,QAAQ,QAAQ;EAChB,YAAY,QAAQ;EACpB,QAAQ,QAAQ;EAChB,SAAS,QAAQ;EAClB,CAAC;AAEF,QAAO;EACL,gBAAgB,KAAK;GACnB,aAAa;GACb,aAAa,EAAE,OAAO,EACpB,MAAM,EACH,QAAQ,CACR,SAAS,4DAA4D,EACzE,CAAC;GACF,SAAS,OAAO,EAAE,WAAW;IAC3B,MAAM,SAAS,MAAM,SAAS,OAAO,KAAK;AAC1C,QAAI,OAAO,QACT,OAAM,IAAI,MAAM,OAAO,KAAK;AAE9B,WAAO,OAAO;;GAEjB,CAAC;EAEF,iBAAiB,KAAK;GACpB,aAAa;GACb,aAAa,EAAE,OAAO,EACpB,MAAM,EACH,QAAQ,CACR,SAAS,2DAA2D,EACxE,CAAC;GACF,SAAS,OAAO,EAAE,WAAW;IAC3B,MAAM,SAAS,MAAM,SAAS,QAAQ,KAAK;AAC3C,QAAI,OAAO,QACT,OAAM,IAAI,MAAM,OAAO,KAAK;AAE9B,WAAO,OAAO;;GAEjB,CAAC;EACH"}
|