@cloudflare/think 0.1.2 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{classPrivateFieldSet2-D-GfNNJe.js → classPrivateFieldGet2-B0jG-d4Z.js} +6 -6
- package/dist/extensions/index.js +2 -2
- package/dist/{manager-UjPxAz2E.js → manager-BY5AZLVa.js} +2 -2
- package/dist/{manager-UjPxAz2E.js.map → manager-BY5AZLVa.js.map} +1 -1
- package/dist/think.d.ts +273 -62
- package/dist/think.js +732 -306
- package/dist/think.js.map +1 -1
- package/dist/tools/extensions.js +1 -1
- package/package.json +6 -6
package/dist/think.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"think.js","names":["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 and runs the full chat\n * lifecycle:\n * store user message → assemble context → call LLM → stream events → persist response\n *\n * Override points:\n * - getModel() — return the LanguageModel to use\n * - getSystemPrompt() — return the system prompt\n * - getTools() — return the ToolSet for the agentic loop\n * - getMaxSteps() — max tool-call rounds per turn (default: 10)\n * - assembleContext() — customize context assembly from this.messages\n * - onChatMessage() — full control over inference (override the agentic loop)\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 * - Abort/cancel support via AbortSignal\n * - Error handling with partial message persistence\n * - Message sanitization (strips OpenAI ephemeral metadata)\n * - Row size enforcement (compacts large tool outputs)\n * - Configurable storage bounds (maxPersistedMessages)\n * - Incremental persistence (skips unchanged messages)\n *\n * @experimental Requires the `\"experimental\"` compatibility flag.\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\nimport type { LanguageModel, ModelMessage, ToolSet, UIMessage } from \"ai\";\nimport {\n convertToModelMessages,\n pruneMessages,\n stepCountIs,\n streamText\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 { withFibers } from \"agents/experimental/forever\";\nimport type { FiberMethods } from \"agents/experimental/forever\";\nimport {\n sanitizeMessage,\n enforceRowSizeLimit,\n StreamAccumulator,\n CHAT_MESSAGE_TYPES,\n TurnQueue,\n ResumableStream,\n ContinuationState,\n createToolsFromClientSchemas\n} from \"agents/chat\";\nimport type { StreamChunkData, ClientToolSchema } from \"agents/chat\";\n\nexport type {\n FiberState,\n FiberRecoveryContext,\n FiberContext,\n FiberCompleteContext,\n FiberMethods\n} from \"agents/experimental/forever\";\n\n// ── Fiber base class ──────────────────────────────────────────────────\ntype ThinkBaseConstructor = {\n new <\n Env extends Cloudflare.Env = Cloudflare.Env,\n State = unknown,\n Props extends Record<string, unknown> = Record<string, unknown>\n >(\n ctx: DurableObjectState,\n env: Env\n ): Agent<Env, State, Props> & FiberMethods;\n};\n\nconst ThinkBase = withFibers(Agent) as unknown as ThinkBaseConstructor;\n\n// ── Wire protocol constants ────────────────────────────────────────\nconst MSG_CHAT_MESSAGES = CHAT_MESSAGE_TYPES.CHAT_MESSAGES;\nconst MSG_CHAT_REQUEST = CHAT_MESSAGE_TYPES.USE_CHAT_REQUEST;\nconst MSG_CHAT_RESPONSE = CHAT_MESSAGE_TYPES.USE_CHAT_RESPONSE;\nconst MSG_CHAT_CLEAR = CHAT_MESSAGE_TYPES.CHAT_CLEAR;\nconst MSG_CHAT_CANCEL = CHAT_MESSAGE_TYPES.CHAT_REQUEST_CANCEL;\nconst MSG_STREAM_RESUMING = CHAT_MESSAGE_TYPES.STREAM_RESUMING;\nconst MSG_STREAM_RESUME_ACK = CHAT_MESSAGE_TYPES.STREAM_RESUME_ACK;\nconst MSG_STREAM_RESUME_REQUEST = CHAT_MESSAGE_TYPES.STREAM_RESUME_REQUEST;\nconst MSG_STREAM_RESUME_NONE = CHAT_MESSAGE_TYPES.STREAM_RESUME_NONE;\nconst MSG_TOOL_RESULT = CHAT_MESSAGE_TYPES.TOOL_RESULT;\nconst MSG_TOOL_APPROVAL = CHAT_MESSAGE_TYPES.TOOL_APPROVAL;\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 `onChatMessage()`.\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 * Options passed to the onChatMessage handler.\n */\nexport interface ChatMessageOptions {\n signal?: AbortSignal;\n tools?: ToolSet;\n /** Client-provided tool schemas for dynamic tool registration. */\n clientTools?: ClientToolSchema[];\n}\n\n/**\n * An opinionated chat agent base class.\n *\n * @experimental Requires the `\"experimental\"` compatibility flag.\n */\nexport class Think<\n Env extends Cloudflare.Env = Cloudflare.Env,\n Config = Record<string, unknown>\n> extends (ThinkBase as ThinkBaseConstructor)<Env> {\n /** In-memory messages for the current conversation. Authoritative after load. */\n messages: UIMessage[] = [];\n\n /**\n * Enable durable fiber recovery on start. Set to `true` to\n * automatically recover interrupted fibers when the DO restarts.\n *\n * @experimental\n */\n fibers = false;\n\n /**\n * Wait for MCP server connections to be ready before calling\n * `onChatMessage`. When enabled, `this.mcp.getAITools()` returns\n * the full set of MCP-discovered tools inside `onChatMessage`.\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 * Maximum number of messages to keep in storage.\n * When exceeded, oldest messages are deleted after each persist.\n * Set to `undefined` (default) for no limit.\n *\n * This controls storage only — it does not affect what's sent to the LLM.\n * Use `pruneMessages()` in `assembleContext()` to control LLM context.\n */\n maxPersistedMessages: number | undefined = undefined;\n\n private _persistedMessageCache: Map<string, string> = new Map();\n private _storageReady = false;\n private _abortControllers = new Map<string, AbortController>();\n private _turnQueue = new TurnQueue();\n private _resumableStream!: ResumableStream;\n private _pendingResumeConnections: Set<string> = new Set();\n private _lastClientTools: ClientToolSchema[] | undefined;\n private _continuation = new ContinuationState();\n private _continuationTimer: ReturnType<typeof setTimeout> | null = null;\n\n // ── Dynamic config ──────────────────────────────────────────────\n\n #configTableReady = false;\n #configCache: Config | null = null;\n\n private _ensureConfigTable(): void {\n if (this.#configTableReady) return;\n this.sql`\n CREATE TABLE IF NOT EXISTS _think_config (\n key TEXT PRIMARY KEY, value TEXT NOT NULL\n )\n `;\n this.#configTableReady = true;\n }\n\n /**\n * Persist a typed configuration object.\n * Stored in SQLite so it survives restarts and hibernation.\n */\n configure(config: Config): void {\n this._ensureConfigTable();\n const json = JSON.stringify(config);\n this.sql`\n INSERT OR REPLACE INTO _think_config (key, value) VALUES ('config', ${json})\n `;\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 this._ensureConfigTable();\n const rows = this.sql<{ value: string }>`\n SELECT value FROM _think_config WHERE key = 'config'\n `;\n if (rows.length > 0) {\n this.#configCache = JSON.parse(rows[0].value) as Config;\n return this.#configCache;\n }\n return null;\n }\n\n // ── Lifecycle ───────────────────────────────────────────────────\n\n onStart() {\n this._initStorage();\n this._resumableStream = new ResumableStream(this.sql.bind(this));\n this.messages = this._loadMessages();\n this._rebuildPersistenceCache();\n this._restoreClientTools();\n this._setupProtocolHandlers();\n\n if (this.fibers) {\n void this.checkFibers();\n }\n }\n\n // ── Override points ──────────────────────────────────────────────\n\n /**\n * Return the language model to use for inference.\n * Must be overridden by subclasses that rely on the default\n * `onChatMessage` implementation (the agentic loop).\n */\n getModel(): LanguageModel {\n throw new Error(\n \"Override getModel() to return a LanguageModel, or override onChatMessage() for full control.\"\n );\n }\n\n /** Return the system prompt for the assistant. */\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 /** Return the maximum number of tool-call steps per turn. */\n getMaxSteps(): number {\n return 10;\n }\n\n /**\n * Assemble the model messages from the current conversation history.\n * Override to customize context assembly (e.g. inject memory,\n * project context, or apply compaction).\n */\n async assembleContext(): Promise<ModelMessage[]> {\n return pruneMessages({\n messages: await convertToModelMessages(this.messages),\n toolCalls: \"before-last-2-messages\"\n });\n }\n\n /**\n * Handle a chat turn and return the streaming result.\n *\n * The default implementation runs the agentic loop:\n * 1. Assemble context from `this.messages`\n * 2. Call `streamText` with the model, system prompt, tools, and step limit\n *\n * Override for full control over inference.\n *\n * @returns A result with `toUIMessageStream()` — AI SDK's `streamText()`\n * return value satisfies this interface.\n */\n async onChatMessage(options?: ChatMessageOptions): Promise<StreamableResult> {\n const baseTools = this.getTools();\n const clientToolSet = createToolsFromClientSchemas(options?.clientTools);\n const tools = { ...baseTools, ...clientToolSet, ...options?.tools };\n const messages = await this.assembleContext();\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 return streamText({\n model: this.getModel(),\n system: this.getSystemPrompt(),\n messages,\n tools,\n stopWhen: stepCountIs(this.getMaxSteps()),\n abortSignal: options?.signal\n });\n }\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 // ── 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 this._appendMessage(userMsg);\n this.messages = this._loadMessages();\n\n const accumulator = new StreamAccumulator({\n messageId: crypto.randomUUID()\n });\n\n try {\n const result = await this.onChatMessage({\n signal: options?.signal,\n tools: options?.tools\n });\n\n let aborted = false;\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\n this._persistAssistantMessage(accumulator.toMessage());\n\n if (!aborted) {\n await callback.onDone();\n }\n } catch (error) {\n if (accumulator.parts.length > 0) {\n this._persistAssistantMessage(accumulator.toMessage());\n }\n\n const wrapped = this.onChatError(error);\n const errorMessage =\n wrapped instanceof Error ? wrapped.message : String(wrapped);\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 and memory. */\n clearMessages(): void {\n this._clearMessages();\n this.messages = [];\n this._persistedMessageCache.clear();\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 try {\n const data = JSON.parse(message) as Record<string, unknown>;\n if (await this._handleProtocol(connection, data)) return;\n } catch {\n // Not JSON — fall through to user handler\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 _handleProtocol(\n connection: Connection,\n data: Record<string, unknown>\n ): Promise<boolean> {\n const type = data.type as string;\n\n if (type === MSG_STREAM_RESUME_REQUEST) {\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 return true;\n }\n\n if (type === MSG_STREAM_RESUME_ACK) {\n this._pendingResumeConnections.delete(connection.id);\n if (\n this._resumableStream.hasActiveStream() &&\n this._resumableStream.activeRequestId === (data.id as string)\n ) {\n const orphanedStreamId = this._resumableStream.replayChunks(\n connection,\n this._resumableStream.activeRequestId\n );\n if (orphanedStreamId) {\n this._persistOrphanedStream(orphanedStreamId);\n }\n }\n return true;\n }\n\n if (type === MSG_CHAT_REQUEST) {\n const init = data.init as { method?: string; body?: string } | undefined;\n if (init?.method === \"POST\") {\n await this._handleChatRequest(connection, data);\n return true;\n }\n }\n\n if (type === MSG_TOOL_RESULT) {\n const {\n toolCallId,\n toolName: _toolName,\n output,\n state,\n errorText,\n autoContinue,\n clientTools\n } = data as Record<string, unknown>;\n if (clientTools && Array.isArray(clientTools) && clientTools.length > 0) {\n this._lastClientTools = clientTools as ClientToolSchema[];\n this._persistClientTools();\n }\n this._applyToolResult(\n toolCallId as string,\n output,\n state as string | undefined,\n errorText as string | undefined\n );\n if (autoContinue) {\n this._scheduleAutoContinuation(connection);\n }\n return true;\n }\n\n if (type === MSG_TOOL_APPROVAL) {\n const { toolCallId, approved, autoContinue } = data as Record<\n string,\n unknown\n >;\n this._applyToolApproval(toolCallId as string, approved as boolean);\n if (autoContinue) {\n this._scheduleAutoContinuation(connection);\n }\n return true;\n }\n\n if (type === MSG_CHAT_CLEAR) {\n this._handleClear();\n return true;\n }\n\n if (type === MSG_CHAT_CANCEL) {\n this._handleCancel(data.id as string);\n return true;\n }\n\n return false;\n }\n\n private async _handleChatRequest(\n connection: Connection,\n data: Record<string, unknown>\n ) {\n const init = data.init as { body?: string };\n if (!init?.body) return;\n\n let parsed: {\n messages?: UIMessage[];\n clientTools?: ClientToolSchema[];\n };\n try {\n parsed = JSON.parse(init.body) as typeof parsed;\n } catch {\n return;\n }\n\n const incomingMessages = parsed.messages;\n if (!Array.isArray(incomingMessages)) return;\n\n const requestClientTools = parsed.clientTools?.length\n ? parsed.clientTools\n : undefined;\n if (requestClientTools) {\n this._lastClientTools = requestClientTools;\n this._persistClientTools();\n } else if (parsed.clientTools !== undefined) {\n this._lastClientTools = undefined;\n this._persistClientTools();\n }\n\n // Capture client tools before entering the turn queue — a concurrent\n // request can overwrite _lastClientTools while this turn awaits.\n const clientToolsForTurn = this._lastClientTools;\n\n for (const msg of incomingMessages) {\n this._appendMessage(msg);\n }\n this.messages = this._loadMessages();\n\n this._broadcastMessages([connection.id]);\n\n const requestId = data.id as string;\n const abortController = new AbortController();\n this._abortControllers.set(requestId, abortController);\n\n try {\n await this.keepAliveWhile(async () => {\n const turnResult = await this._turnQueue.enqueue(\n requestId,\n async () => {\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 // Reload messages to ensure freshness after potential yields\n this.messages = this._loadMessages();\n\n const result = await agentContext.run(\n {\n agent: this,\n connection,\n request: undefined,\n email: undefined\n },\n () =>\n this.onChatMessage({\n signal: abortController.signal,\n clientTools: clientToolsForTurn\n })\n );\n\n if (result) {\n await this._streamResult(\n requestId,\n result,\n abortController.signal\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\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._abortControllers.delete(requestId);\n }\n }\n\n private _handleClear() {\n this._turnQueue.reset();\n\n for (const controller of this._abortControllers.values()) {\n controller.abort();\n }\n this._abortControllers.clear();\n\n this._resumableStream.clearAll();\n this._pendingResumeConnections.clear();\n this._lastClientTools = undefined;\n this._persistClientTools();\n if (this._continuationTimer) {\n clearTimeout(this._continuationTimer);\n this._continuationTimer = null;\n }\n this._continuation.sendResumeNone();\n this._continuation.clearAll();\n this._clearMessages();\n this.messages = [];\n this._persistedMessageCache.clear();\n this._broadcast({ type: MSG_CHAT_CLEAR });\n }\n\n private _handleCancel(requestId: string) {\n const controller = this._abortControllers.get(requestId);\n if (controller) {\n controller.abort();\n }\n }\n\n private async _streamResult(\n requestId: string,\n result: StreamableResult,\n abortSignal?: AbortSignal\n ) {\n const clearGen = this._turnQueue.generation;\n const streamId = this._resumableStream.start(requestId);\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\n try {\n for await (const chunk of result.toUIMessageStream()) {\n if (abortSignal?.aborted) break;\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\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 this._resumableStream.markError(streamId);\n this._pendingResumeConnections.clear();\n if (!doneSent) {\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: error instanceof Error ? error.message : \"Stream error\",\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 this._persistAssistantMessage(accumulator.toMessage());\n this._broadcastMessages();\n } catch (e) {\n console.error(\"Failed to persist assistant message:\", e);\n }\n }\n }\n\n // ── Storage internals ───────────────────────────────────────────\n\n private _initStorage(): void {\n if (this._storageReady) return;\n this.sql`\n CREATE TABLE IF NOT EXISTS assistant_messages (\n id TEXT PRIMARY KEY,\n role TEXT NOT NULL,\n content TEXT NOT NULL,\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP\n )\n `;\n this.sql`\n CREATE TABLE IF NOT EXISTS think_request_context (\n key TEXT PRIMARY KEY,\n value TEXT NOT NULL\n )\n `;\n this._storageReady = true;\n }\n\n private _loadMessages(): UIMessage[] {\n const rows = this.sql<{ content: string }>`\n SELECT content FROM assistant_messages ORDER BY created_at ASC\n `;\n return rows.map((row) => JSON.parse(row.content) as UIMessage);\n }\n\n private _appendMessage(msg: UIMessage): void {\n const json = JSON.stringify(msg);\n this.sql`\n INSERT OR IGNORE INTO assistant_messages (id, role, content)\n VALUES (${msg.id}, ${msg.role}, ${json})\n `;\n this._persistedMessageCache.set(msg.id, json);\n }\n\n private _upsertMessage(msg: UIMessage): void {\n const json = JSON.stringify(msg);\n this.sql`\n INSERT INTO assistant_messages (id, role, content)\n VALUES (${msg.id}, ${msg.role}, ${json})\n ON CONFLICT(id) DO UPDATE SET content = excluded.content\n `;\n this._persistedMessageCache.set(msg.id, json);\n }\n\n private _clearMessages(): void {\n this.sql`DELETE FROM assistant_messages`;\n }\n\n private _deleteMessages(ids: string[]): void {\n for (const id of ids) {\n this.sql`DELETE FROM assistant_messages WHERE id = ${id}`;\n }\n }\n\n private _persistClientTools(): void {\n if (this._lastClientTools) {\n this.sql`\n INSERT OR REPLACE INTO think_request_context (key, value)\n VALUES ('lastClientTools', ${JSON.stringify(this._lastClientTools)})\n `;\n } else {\n this.sql`DELETE FROM think_request_context WHERE key = 'lastClientTools'`;\n }\n }\n\n private _restoreClientTools(): void {\n const rows =\n this.sql<{ value: string }>`\n SELECT value FROM think_request_context WHERE key = 'lastClientTools'\n ` || [];\n if (rows.length > 0) {\n try {\n this._lastClientTools = JSON.parse(rows[0].value);\n } catch {\n this._lastClientTools = undefined;\n }\n }\n }\n\n private _persistAssistantMessage(msg: UIMessage): void {\n const sanitized = sanitizeMessage(msg);\n const safe = enforceRowSizeLimit(sanitized);\n const json = JSON.stringify(safe);\n\n if (this._persistedMessageCache.get(safe.id) !== json) {\n this._upsertMessage(safe);\n }\n\n if (this.maxPersistedMessages != null) {\n this._enforceMaxPersistedMessages();\n }\n\n this.messages = this._loadMessages();\n }\n\n private _rebuildPersistenceCache(): void {\n this._persistedMessageCache.clear();\n for (const msg of this.messages) {\n this._persistedMessageCache.set(msg.id, JSON.stringify(msg));\n }\n }\n\n private _enforceMaxPersistedMessages(): void {\n if (this.maxPersistedMessages == null) return;\n\n const history = this._loadMessages();\n if (history.length <= this.maxPersistedMessages) return;\n\n const excess = history.length - this.maxPersistedMessages;\n const toRemove = history.slice(0, excess);\n\n this._deleteMessages(toRemove.map((m) => m.id));\n for (const msg of toRemove) {\n this._persistedMessageCache.delete(msg.id);\n }\n }\n\n // ── Client tool handling ─────────────────────────────────────────\n\n private _applyToolResult(\n toolCallId: string,\n output: unknown,\n overrideState?: string,\n errorText?: string\n ): void {\n const validStates = [\n \"input-available\",\n \"approval-requested\",\n \"approval-responded\"\n ];\n for (const msg of this.messages) {\n for (let i = 0; i < msg.parts.length; i++) {\n const part = msg.parts[i] as Record<string, unknown>;\n if (\n \"toolCallId\" in part &&\n part.toolCallId === toolCallId &&\n \"state\" in part &&\n validStates.includes(part.state as string)\n ) {\n if (overrideState === \"output-error\") {\n msg.parts[i] = {\n ...part,\n state: \"output-error\",\n errorText: errorText ?? \"Tool execution denied by user\"\n } as UIMessage[\"parts\"][number];\n } else {\n msg.parts[i] = {\n ...part,\n state: \"output-available\",\n output,\n preliminary: false\n } as UIMessage[\"parts\"][number];\n }\n const safe = enforceRowSizeLimit(sanitizeMessage(msg));\n this._upsertMessage(safe);\n this.messages = this._loadMessages();\n this._broadcast({ type: MSG_MESSAGE_UPDATED, message: safe });\n return;\n }\n }\n }\n }\n\n private _applyToolApproval(toolCallId: string, approved: boolean): void {\n const validStates = [\"input-available\", \"approval-requested\"];\n for (const msg of this.messages) {\n for (let i = 0; i < msg.parts.length; i++) {\n const part = msg.parts[i] as Record<string, unknown>;\n if (\n \"toolCallId\" in part &&\n part.toolCallId === toolCallId &&\n \"state\" in part &&\n validStates.includes(part.state as string)\n ) {\n msg.parts[i] = {\n ...part,\n state: approved ? \"approval-responded\" : \"output-denied\",\n approval: {\n ...(part.approval as Record<string, unknown> | undefined),\n approved\n }\n } as UIMessage[\"parts\"][number];\n const safe = enforceRowSizeLimit(sanitizeMessage(msg));\n this._upsertMessage(safe);\n this.messages = this._loadMessages();\n this._broadcast({ type: MSG_MESSAGE_UPDATED, message: safe });\n return;\n }\n }\n }\n }\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 abortController = new AbortController();\n this._abortControllers.set(requestId, abortController);\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 this.messages = this._loadMessages();\n const result = await agentContext.run(\n {\n agent: this,\n connection,\n request: undefined,\n email: undefined\n },\n () =>\n this.onChatMessage({\n signal: abortController.signal,\n clientTools\n })\n );\n if (result) {\n await this._streamResult(requestId, result, abortController.signal);\n streamed = true;\n }\n } finally {\n this._abortControllers.delete(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._abortControllers.delete(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 // ── 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":";;;;;;AA+FA,MAAM,YAAY,WAAW,MAAM;AAGnC,MAAM,oBAAoB,mBAAmB;AAC7C,MAAM,mBAAmB,mBAAmB;AAC5C,MAAM,oBAAoB,mBAAmB;AAC7C,MAAM,iBAAiB,mBAAmB;AAC1C,MAAM,kBAAkB,mBAAmB;AAC3C,MAAM,sBAAsB,mBAAmB;AAC/C,MAAM,wBAAwB,mBAAmB;AACjD,MAAM,4BAA4B,mBAAmB;AACrD,MAAM,yBAAyB,mBAAmB;AAClD,MAAM,kBAAkB,mBAAmB;AAC3C,MAAM,oBAAoB,mBAAmB;AAC7C,MAAM,sBAAsB,mBAAmB;;;;;;;;AA6C/C,IAAa,QAAb,cAGW,UAAwC;;;AAEjD,OAAA,WAAwB,EAAE;AAQ1B,OAAA,SAAS;AAUT,OAAA,wBAAuD;AAUvD,OAAA,uBAA2C,KAAA;AAE3C,OAAQ,yCAA8C,IAAI,KAAK;AAC/D,OAAQ,gBAAgB;AACxB,OAAQ,oCAAoB,IAAI,KAA8B;AAC9D,OAAQ,aAAa,IAAI,WAAW;AAEpC,OAAQ,4CAAyC,IAAI,KAAK;AAE1D,OAAQ,gBAAgB,IAAI,mBAAmB;AAC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AM,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"}
|
|
1
|
+
{"version":3,"file":"think.js","names":["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 * Override points:\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 * - getMaxSteps() — max tool-call rounds per turn (default: 10)\n * - configureSession() — add context blocks, compaction, search, skills\n * - assembleContext() — customize context assembly (system prompt + messages)\n * - onChatMessage() — full control over inference (override the agentic loop)\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 Requires the `\"experimental\"` compatibility flag.\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 { LanguageModel, ModelMessage, ToolSet, UIMessage } from \"ai\";\nimport {\n convertToModelMessages,\n pruneMessages,\n stepCountIs,\n streamText\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\";\n\nexport { Session } from \"agents/experimental/memory/session\";\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 `onChatMessage()`.\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 * Options passed to the onChatMessage handler.\n */\nexport interface ChatMessageOptions {\n signal?: AbortSignal;\n tools?: ToolSet;\n /** Client-provided tool schemas for dynamic tool registration. */\n clientTools?: ClientToolSchema[];\n /** Whether this is a continuation turn (auto-continue after tool result, recovery).\n * Explicitly set to `false` for initial turns and `true` for continuations. */\n continuation?: boolean;\n /** Custom body fields from the client request. Persisted across hibernation. */\n body?: Record<string, unknown>;\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\n/**\n * Options returned from `onChatRecovery` to control recovery behavior.\n */\nexport type ChatRecoveryOptions = {\n persist?: boolean;\n continue?: boolean;\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 Requires the `\"experimental\"` compatibility flag.\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 calling\n * `onChatMessage`. When enabled, `this.mcp.getAITools()` returns\n * the full set of MCP-discovered tools inside `onChatMessage`.\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 unstable_chatRecovery = false;\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 constructor(ctx: DurableObjectState, env: Env) {\n super(ctx, env);\n\n const _onStart = this.onStart.bind(this);\n this.onStart = async () => {\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 this._resumableStream = new ResumableStream(this.sql.bind(this));\n this._restoreClientTools();\n this._restoreBody();\n this._setupProtocolHandlers();\n\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();\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 _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 private _configSet(key: string, value: string): void {\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 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 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 // ── Override points ──────────────────────────────────────────────\n\n /**\n * Return the language model to use for inference.\n * Must be overridden by subclasses that rely on the default\n * `onChatMessage` implementation (the agentic loop).\n */\n getModel(): LanguageModel {\n throw new Error(\n \"Override getModel() to return a LanguageModel, or override onChatMessage() for full control.\"\n );\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 /** Return the maximum number of tool-call steps per turn. */\n getMaxSteps(): number {\n return 10;\n }\n\n /**\n * Configure the session. Called once during `onStart`.\n * Override to add context blocks, compaction, search, skills.\n *\n * The base session is pre-created with `Session.create(this)`.\n * Return it with builder methods chained.\n *\n * Async is supported — use it to read configuration from KV, D1,\n * or R2 before setting up context blocks.\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 * @example Async configuration from KV\n * ```typescript\n * async configureSession(session: Session) {\n * const config = await this.env.KV.get(\"agent-config\", \"json\");\n * return session\n * .withContext(\"memory\", { maxTokens: config.memoryTokens })\n * .withCachedPrompt();\n * }\n * ```\n */\n configureSession(session: Session): Session | Promise<Session> {\n return session;\n }\n\n /**\n * Assemble context for the LLM from the current session state.\n *\n * Default implementation:\n * 1. Freezes the system prompt from context blocks (falls back to getSystemPrompt())\n * 2. Gets history from session\n * 3. Applies read-time truncation (old tool outputs, long text)\n * 4. Converts to model messages with tool call pruning\n *\n * Returns { system, messages } so the caller has both.\n */\n async assembleContext(): Promise<{\n system: string;\n messages: ModelMessage[];\n }> {\n // freezeSystemPrompt() triggers context block loading if needed.\n // It returns \"\" when no blocks are configured or all are empty —\n // in that case, fall back to the simple getSystemPrompt() override.\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);\n const messages = pruneMessages({\n messages: await convertToModelMessages(truncated),\n toolCalls: \"before-last-2-messages\"\n });\n\n return { system, messages };\n }\n\n /**\n * Handle a chat turn and return the streaming result.\n *\n * The default implementation runs the agentic loop:\n * 1. Merge tools: getTools() + clientTools + session context tools + options.tools\n * 2. Assemble context (system prompt + messages) from session state\n * 3. Call `streamText` with the model, system prompt, tools, and step limit\n *\n * Override for full control over inference.\n *\n * @returns A result with `toUIMessageStream()` — AI SDK's `streamText()`\n * return value satisfies this interface.\n */\n async onChatMessage(options?: ChatMessageOptions): Promise<StreamableResult> {\n const baseTools = this.getTools();\n const clientToolSet = createToolsFromClientSchemas(options?.clientTools);\n const contextTools = await this.session.tools();\n const tools = {\n ...baseTools,\n ...clientToolSet,\n ...contextTools,\n ...options?.tools\n };\n\n const { system, messages } = await this.assembleContext();\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 return streamText({\n model: this.getModel(),\n system,\n messages,\n tools,\n stopWhen: stepCountIs(this.getMaxSteps()),\n abortSignal: options?.signal\n });\n }\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 // ── 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 this.onChatMessage({\n signal: options?.signal,\n tools: options?.tools,\n continuation: false\n });\n\n let aborted = false;\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\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.onChatMessage({\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.unstable_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.onChatMessage({\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.unstable_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 /**\n * Override to apply custom transformations to messages before they are\n * persisted to Session storage. Runs after the built-in sanitization\n * (OpenAI metadata stripping, row size enforcement) but before\n * `session.appendMessage` / `session.updateMessage`.\n *\n * Use for redacting PII, stripping internal metadata, or custom compaction.\n */\n protected sanitizeMessageForPersistence(message: UIMessage): UIMessage {\n return message;\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 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 result = await agentContext.run(\n {\n agent: this,\n connection,\n request: undefined,\n email: undefined\n },\n () =>\n this.onChatMessage({\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.unstable_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 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\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 sized = enforceRowSizeLimit(sanitized);\n const safe = this.sanitizeMessageForPersistence(sized);\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 });\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.onChatMessage({\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.unstable_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":";;;;;;;AAqHA,MAAM,oBAAoB,mBAAmB;AAC7C,MAAM,oBAAoB,mBAAmB;AAC7C,MAAM,iBAAiB,mBAAmB;AAC1C,MAAM,sBAAsB,mBAAmB;AAC/C,MAAM,yBAAyB,mBAAmB;AAClD,MAAM,sBAAsB,mBAAmB;AA4E/C,MAAM,YAAY,OAAO,YAAY;;;;;;;AAsDrC,IAAa,QAAb,MAAa,cAGH,MAAW;CA8BnB,YAAY,KAAyB,KAAU;AAC7C,QAAM,KAAK,IAAI;AAtBjB,OAAA,wBAAuD;AAQvD,OAAA,qBAAyC;AAMzC,OAAA,wBAAwB;AAoCxB,OAAQ,UAAU,IAAI,eAAe;AACrC,OAAQ,aAAa,IAAI,WAAW;AAEpC,OAAQ,4CAAyC,IAAI,KAAK;AAG1D,OAAQ,gBAAgB,IAAI,mBAAmB;AAC/C,OAAQ,qBAA2D;AACnE,OAAQ,sBAAsB;AAC9B,OAAQ,6BAAsD;AAC9D,OAAQ,kBAAkB;AAC1B,OAAQ,mCAAmC;AAC3C,OAAQ,uBAA6D;AACrE,OAAQ,yBAA8C;iDAKxB,KAAK;EA5CjC,MAAM,WAAW,KAAK,QAAQ,KAAK,KAAK;AACxC,OAAK,UAAU,YAAY;GACzB,MAAM,cAAcA,UAAQ,OAAO,KAAK;AACxC,QAAK,UAAU,MAAM,KAAK,iBAAiB,YAAY;AAIvD,QAAK,QAAQ,YAAY;AAEzB,QAAK,mBAAmB,IAAI,gBAAgB,KAAK,IAAI,KAAK,KAAK,CAAC;AAChE,QAAK,qBAAqB;AAC1B,QAAK,cAAc;AACnB,QAAK,wBAAwB;AAE7B,SAAM,UAAU;;;;;;;CAQpB,I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AAE,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;;;AArrDH,MAAgB,kBAAkB;AAgDlC,MAAe,sBAAsB"}
|
package/dist/tools/extensions.js
CHANGED
package/package.json
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
"tools"
|
|
10
10
|
],
|
|
11
11
|
"type": "module",
|
|
12
|
-
"version": "0.
|
|
12
|
+
"version": "0.2.0",
|
|
13
13
|
"license": "MIT",
|
|
14
14
|
"repository": {
|
|
15
15
|
"directory": "packages/think",
|
|
@@ -21,14 +21,14 @@
|
|
|
21
21
|
"url": "https://github.com/cloudflare/agents/issues"
|
|
22
22
|
},
|
|
23
23
|
"devDependencies": {
|
|
24
|
-
"@cloudflare/shell": "^0.3.
|
|
25
|
-
"ai": "^6.0.
|
|
24
|
+
"@cloudflare/shell": "^0.3.2",
|
|
25
|
+
"ai": "^6.0.149",
|
|
26
26
|
"zod": "^4.3.6"
|
|
27
27
|
},
|
|
28
28
|
"peerDependencies": {
|
|
29
|
-
"@cloudflare/codemode": "^0.3.
|
|
30
|
-
"@cloudflare/shell": "^0.3.
|
|
31
|
-
"agents": "^0.
|
|
29
|
+
"@cloudflare/codemode": "^0.3.4",
|
|
30
|
+
"@cloudflare/shell": "^0.3.2",
|
|
31
|
+
"agents": "^0.10.0",
|
|
32
32
|
"ai": "^6.0.0",
|
|
33
33
|
"zod": "^4.0.0"
|
|
34
34
|
},
|