@cloudflare/think 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/think.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"think.js","names":["agentContext"],"sources":["../src/sanitize.ts","../src/think.ts"],"sourcesContent":["/**\n * Message sanitization and row-size enforcement utilities.\n *\n * Shared by Think to ensure persistence\n * hygiene: stripping ephemeral provider metadata and compacting\n * oversized messages before writing to SQLite.\n */\n\nimport type { ProviderMetadata, ReasoningUIPart, UIMessage } from \"ai\";\n\n/** Shared encoder for UTF-8 byte length measurement */\nconst textEncoder = new TextEncoder();\n\n/** Maximum serialized message size before compaction (bytes). 1.8MB with headroom below SQLite's 2MB limit. */\nconst ROW_MAX_BYTES = 1_800_000;\n\n/** Measure UTF-8 byte length of a string. */\nfunction byteLength(s: string): number {\n return textEncoder.encode(s).byteLength;\n}\n\n/**\n * Sanitize a message for persistence by removing ephemeral provider-specific\n * data that should not be stored or sent back in subsequent requests.\n *\n * 1. Strips OpenAI ephemeral fields (itemId, reasoningEncryptedContent)\n * 2. Filters truly empty reasoning parts (no text, no remaining providerMetadata)\n */\nexport function sanitizeMessage(message: UIMessage): UIMessage {\n // Strip OpenAI-specific ephemeral data from all parts\n const strippedParts = message.parts.map((part) => {\n let sanitizedPart = part;\n\n if (\n \"providerMetadata\" in sanitizedPart &&\n sanitizedPart.providerMetadata &&\n typeof sanitizedPart.providerMetadata === \"object\" &&\n \"openai\" in sanitizedPart.providerMetadata\n ) {\n sanitizedPart = stripOpenAIMetadata(sanitizedPart, \"providerMetadata\");\n }\n\n if (\n \"callProviderMetadata\" in sanitizedPart &&\n sanitizedPart.callProviderMetadata &&\n typeof sanitizedPart.callProviderMetadata === \"object\" &&\n \"openai\" in sanitizedPart.callProviderMetadata\n ) {\n sanitizedPart = stripOpenAIMetadata(\n sanitizedPart,\n \"callProviderMetadata\"\n );\n }\n\n return sanitizedPart;\n }) as UIMessage[\"parts\"];\n\n // Filter out reasoning parts that are truly empty\n const sanitizedParts = strippedParts.filter((part) => {\n if (part.type === \"reasoning\") {\n const reasoningPart = part as ReasoningUIPart;\n if (!reasoningPart.text || reasoningPart.text.trim() === \"\") {\n if (\n \"providerMetadata\" in reasoningPart &&\n reasoningPart.providerMetadata &&\n typeof reasoningPart.providerMetadata === \"object\" &&\n Object.keys(reasoningPart.providerMetadata).length > 0\n ) {\n return true;\n }\n return false;\n }\n }\n return true;\n });\n\n return { ...message, parts: sanitizedParts };\n}\n\n/**\n * Strip OpenAI-specific ephemeral fields from a metadata object.\n */\nfunction stripOpenAIMetadata<T extends UIMessage[\"parts\"][number]>(\n part: T,\n metadataKey: \"providerMetadata\" | \"callProviderMetadata\"\n): T {\n const metadata = (part as Record<string, unknown>)[metadataKey] as {\n openai?: Record<string, unknown>;\n [key: string]: unknown;\n };\n\n if (!metadata?.openai) return part;\n\n const {\n itemId: _itemId,\n reasoningEncryptedContent: _rec,\n ...restOpenai\n } = metadata.openai;\n\n const hasOtherOpenaiFields = Object.keys(restOpenai).length > 0;\n const { openai: _openai, ...restMetadata } = metadata;\n\n let newMetadata: ProviderMetadata | undefined;\n if (hasOtherOpenaiFields) {\n newMetadata = { ...restMetadata, openai: restOpenai } as ProviderMetadata;\n } else if (Object.keys(restMetadata).length > 0) {\n newMetadata = restMetadata as ProviderMetadata;\n }\n\n const { [metadataKey]: _oldMeta, ...restPart } = part as Record<\n string,\n unknown\n >;\n\n if (newMetadata) {\n return { ...restPart, [metadataKey]: newMetadata } as T;\n }\n return restPart as T;\n}\n\n/**\n * Enforce SQLite row size limits by compacting tool outputs and text parts\n * when a serialized message exceeds the safety threshold (1.8MB).\n *\n * Compaction strategy:\n * 1. Compact tool outputs over 1KB (replace with summary)\n * 2. If still too big, truncate text parts from oldest to newest\n */\nexport function enforceRowSizeLimit(message: UIMessage): UIMessage {\n let json = JSON.stringify(message);\n let size = byteLength(json);\n if (size <= ROW_MAX_BYTES) return message;\n\n if (message.role !== \"assistant\") {\n return truncateTextParts(message);\n }\n\n // Pass 1: compact tool outputs\n const compactedParts = message.parts.map((part) => {\n if (\n \"output\" in part &&\n \"toolCallId\" in part &&\n \"state\" in part &&\n part.state === \"output-available\"\n ) {\n const outputJson = JSON.stringify((part as { output: unknown }).output);\n if (outputJson.length > 1000) {\n return {\n ...part,\n output:\n \"This tool output was too large to persist in storage \" +\n `(${outputJson.length} bytes). ` +\n \"If the user asks about this data, suggest re-running the tool. \" +\n `Preview: ${outputJson.slice(0, 500)}...`\n };\n }\n }\n return part;\n }) as UIMessage[\"parts\"];\n\n let result: UIMessage = { ...message, parts: compactedParts };\n\n json = JSON.stringify(result);\n size = byteLength(json);\n if (size <= ROW_MAX_BYTES) return result;\n\n // Pass 2: truncate text parts\n return truncateTextParts(result);\n}\n\n/**\n * Truncate text parts to fit within the row size limit.\n */\nfunction truncateTextParts(message: UIMessage): UIMessage {\n const parts = [...message.parts];\n\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i];\n if (part.type === \"text\" && \"text\" in part) {\n const text = (part as { text: string }).text;\n if (text.length > 1000) {\n parts[i] = {\n ...part,\n text:\n `[Text truncated for storage (${text.length} chars). ` +\n `First 500 chars: ${text.slice(0, 500)}...]`\n } as UIMessage[\"parts\"][number];\n\n const candidate = { ...message, parts };\n if (byteLength(JSON.stringify(candidate)) <= ROW_MAX_BYTES) {\n break;\n }\n }\n }\n }\n\n return { ...message, parts };\n}\n","/**\n * Think — a unified Agent base class for chat sessions.\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 * Uses SessionManager for message persistence, giving you branching and\n * compaction support for free.\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 * - Multi-session management (create, switch, list, delete, rename)\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 * - Richer input (accepts UIMessage or string)\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 * import { createWorkspaceTools } from \"@cloudflare/think/tools/workspace\";\n * import { Workspace } from \"@cloudflare/shell\";\n *\n * export class ChatSession extends Think<Env> {\n * workspace = new Workspace(this);\n *\n * getModel() {\n * return createWorkersAI({ binding: this.env.AI })(\"@cf/moonshotai/kimi-k2.5\");\n * }\n *\n * getTools() {\n * return createWorkspaceTools(this.workspace);\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 { Workspace } from \"@cloudflare/shell\";\nimport { withFibers } from \"agents/experimental/forever\";\nimport type { FiberMethods } from \"agents/experimental/forever\";\nimport { SessionManager } from \"./session/index\";\nimport type { Session } from \"./session/index\";\nimport { applyChunkToParts } from \"./message-builder\";\nimport type { StreamChunkData } from \"./message-builder\";\nimport { sanitizeMessage, enforceRowSizeLimit } from \"./sanitize\";\n\nexport type { Session } from \"./session/index\";\nexport type {\n FiberState,\n FiberRecoveryContext,\n FiberContext,\n FiberCompleteContext,\n FiberMethods\n} from \"agents/experimental/forever\";\n\n// ── Fiber base class ──────────────────────────────────────────────────\n// Think extends withFibers(Agent) so fiber methods (spawnFiber, etc.)\n// are always available on the prototype. The `fibers` flag controls\n// whether interrupted fibers are recovered on start.\n//\n// The type cast preserves Agent's generic constructor while adding\n// FiberMethods to the instance type, avoiding unsafe interface merging.\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 ────────────────────────────────────────\n// These string values are wire-compatible with @cloudflare/ai-chat's\n// MessageType enum. Defined locally to avoid a circular dependency.\nconst MSG_CHAT_MESSAGES = \"cf_agent_chat_messages\";\nconst MSG_CHAT_REQUEST = \"cf_agent_use_chat_request\";\nconst MSG_CHAT_RESPONSE = \"cf_agent_use_chat_response\";\nconst MSG_CHAT_CLEAR = \"cf_agent_chat_clear\";\nconst MSG_CHAT_CANCEL = \"cf_agent_chat_request_cancel\";\n\n/**\n * Callback interface for streaming chat events from a Think.\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 *\n * Methods may return a Promise for async RPC callbacks.\n */\nexport interface StreamCallback {\n /** Called for each UIMessageChunk event during streaming. */\n onEvent(json: string): void | Promise<void>;\n /** Called when the stream completes successfully (not called on abort). */\n onDone(): void | Promise<void>;\n /** Called when an error occurs during streaming. */\n onError?(error: string): void | Promise<void>;\n}\n\n/**\n * Minimal interface for the result of `onChatMessage()`.\n * Must provide a `toUIMessageStream()` method that returns an\n * async-iterable stream of UI message chunks.\n *\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 /** AbortSignal — fires when the caller wants to cancel the turn. */\n signal?: AbortSignal;\n /** Extra tools to merge with getTools() for this turn only. */\n tools?: ToolSet;\n}\n\n/**\n * Options passed to the onChatMessage handler.\n */\nexport interface ChatMessageOptions {\n /** AbortSignal for cancelling the request */\n signal?: AbortSignal;\n /** Extra tools to merge with getTools() for this turn only. */\n tools?: ToolSet;\n}\n\n/**\n * A unified Agent base class for chat sessions.\n *\n * Works as both a top-level agent (WebSocket chat protocol) and a\n * sub-agent (RPC streaming via `chat()`).\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 /** Session manager — persistence layer with branching and compaction. */\n sessions!: SessionManager;\n\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 * Fiber methods (`spawnFiber()`, `stashFiber()`, etc.) are always\n * available — this flag only controls automatic recovery.\n *\n * @experimental\n */\n fibers = false;\n\n /**\n * Maximum number of messages to keep in storage per session.\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 /**\n * Cache of last-persisted JSON for each message ID.\n * Used for incremental persistence: skip SQL writes for unchanged messages.\n * @internal\n */\n private _persistedMessageCache: Map<string, string> = new Map();\n\n private _sessionId: string | null = null;\n private _abortControllers = new Map<string, AbortController>();\n private _clearGeneration = 0;\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 onStart() {\n this.sessions = new SessionManager(this, {\n exec: (query, ...values) => {\n this.ctx.storage.sql.exec(query, ...values);\n }\n });\n const existing = this.sessions.list();\n if (existing.length > 0) {\n this._sessionId = existing[0].id;\n this.messages = this.sessions.getHistory(this._sessionId);\n this._rebuildPersistenceCache();\n }\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 /**\n * Return the system prompt for the assistant.\n * Override to customize instructions.\n */\n getSystemPrompt(): string {\n return \"You are a helpful assistant.\";\n }\n\n /**\n * Return the tools available to the assistant.\n * Override to provide workspace tools, custom tools, etc.\n */\n getTools(): ToolSet {\n return {};\n }\n\n /**\n * Return the maximum number of tool-call steps per turn.\n */\n getMaxSteps(): number {\n return 10;\n }\n\n /**\n * Return the workspace instance for this session, or null if none.\n *\n * Override in subclasses that create a Workspace. Used by\n * HostBridgeLoopback to provide workspace access to extension Workers.\n */\n getWorkspace(): Workspace | null {\n return null;\n }\n\n // ── Workspace proxy methods (called by HostBridgeLoopback via RPC) ──\n\n async _hostReadFile(path: string): Promise<string | null> {\n const ws = this.getWorkspace();\n if (!ws) throw new Error(\"No workspace available on this agent\");\n return ws.readFile(path);\n }\n\n async _hostWriteFile(path: string, content: string): Promise<void> {\n const ws = this.getWorkspace();\n if (!ws) throw new Error(\"No workspace available on this agent\");\n await ws.writeFile(path, content);\n }\n\n async _hostDeleteFile(path: string): Promise<boolean> {\n const ws = this.getWorkspace();\n if (!ws) throw new Error(\"No workspace available on this agent\");\n return ws.deleteFile(path);\n }\n\n async _hostListFiles(\n dir: string\n ): Promise<\n Array<{ name: string; type: string; size: number; path: string }>\n > {\n const ws = this.getWorkspace();\n if (!ws) throw new Error(\"No workspace available on this agent\");\n return ws.readDir(dir);\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 (e.g. different models per turn,\n * RAG pipelines, routing to specialized sub-agents, etc.).\n *\n * When this is called, `this.messages` already contains the user's\n * latest message persisted to the current session.\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 tools = options?.tools\n ? { ...baseTools, ...options.tools }\n : baseTools;\n return streamText({\n model: this.getModel(),\n system: this.getSystemPrompt(),\n messages: await this.assembleContext(),\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 * @param error The error that occurred\n * @returns The error (or a wrapped version) to propagate\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 * On error or abort, the partial assistant message is still persisted\n * so the user doesn't lose context.\n *\n * @param userMessage The user's message (string or UIMessage for multi-modal)\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 // Ensure a session exists\n if (!this._sessionId) {\n const session = this.sessions.create(\"default\");\n this._sessionId = session.id;\n }\n\n // Persist user message\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.sessions.append(this._sessionId, userMsg);\n this.messages = this.sessions.getHistory(this._sessionId);\n\n // Build assistant message from stream chunks\n const assistantMsg: UIMessage = {\n id: crypto.randomUUID(),\n role: \"assistant\",\n parts: []\n };\n\n try {\n // Run the agentic loop (or custom override)\n const result = await this.onChatMessage({\n signal: options?.signal,\n tools: options?.tools\n });\n\n // Stream UIMessageChunk events via callback\n let aborted = false;\n for await (const chunk of result.toUIMessageStream()) {\n if (options?.signal?.aborted) {\n aborted = true;\n break;\n }\n applyChunkToParts(\n assistantMsg.parts,\n chunk as unknown as StreamChunkData\n );\n await callback.onEvent(JSON.stringify(chunk));\n }\n\n // Persist assistant message (sanitized + size-enforced)\n this._persistAssistantMessage(assistantMsg);\n\n // Only signal completion if not aborted\n if (!aborted) {\n await callback.onDone();\n }\n } catch (error) {\n // Persist partial assistant message so context isn't lost\n if (assistantMsg.parts.length > 0) {\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 (callback.onError) {\n await callback.onError(errorMessage);\n } else {\n // Re-throw if no error callback — caller must handle it\n throw wrapped;\n }\n }\n }\n\n // ── Session management ─────────────────────────────────────────\n\n getSessions(): Session[] {\n return this.sessions.list();\n }\n\n createSession(name: string): Session {\n const session = this.sessions.create(name);\n this._sessionId = session.id;\n this.messages = [];\n this._broadcastMessages();\n return session;\n }\n\n switchSession(sessionId: string): UIMessage[] {\n const session = this.sessions.get(sessionId);\n if (!session) {\n throw new Error(`Session not found: ${sessionId}`);\n }\n this._sessionId = sessionId;\n this.messages = this.sessions.getHistory(sessionId);\n this._broadcastMessages();\n return this.messages;\n }\n\n deleteSession(sessionId: string): void {\n const session = this.sessions.get(sessionId);\n if (!session) {\n throw new Error(`Session not found: ${sessionId}`);\n }\n this.sessions.delete(sessionId);\n if (this._sessionId === sessionId) {\n this._sessionId = null;\n this.messages = [];\n this._broadcastMessages();\n }\n }\n\n renameSession(sessionId: string, name: string): void {\n const session = this.sessions.get(sessionId);\n if (!session) {\n throw new Error(`Session not found: ${sessionId}`);\n }\n this.sessions.rename(sessionId, name);\n }\n\n getCurrentSessionId(): string | null {\n return this._sessionId;\n }\n\n // ── Message access ───────────────────────────────────────────────\n\n /**\n * Get the current session info, or null if no session exists yet.\n */\n getSession(): Session | null {\n if (!this._sessionId) return null;\n return this.sessions.get(this._sessionId);\n }\n\n /**\n * Get the conversation history as UIMessage[].\n */\n getHistory(): UIMessage[] {\n if (!this._sessionId) return [];\n return this.sessions.getHistory(this._sessionId);\n }\n\n /**\n * Get the total message count for this session.\n */\n getMessageCount(): number {\n if (!this._sessionId) return 0;\n return this.sessions.getMessageCount(this._sessionId);\n }\n\n /**\n * Clear all messages from this session (preserves the session itself).\n */\n clearMessages(): void {\n if (!this._sessionId) return;\n this.sessions.clearMessages(this._sessionId);\n this.messages = [];\n this._persistedMessageCache.clear();\n }\n\n // ── WebSocket protocol ──────────────────────────────────────────\n\n /**\n * Wrap onMessage and onRequest to intercept the chat protocol.\n * Unrecognized messages are forwarded to the user's handlers.\n * @internal\n */\n private _setupProtocolHandlers() {\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 const sessionId = url.searchParams.get(\"sessionId\");\n if (sessionId) {\n const session = this.sessions.get(sessionId);\n if (!session) {\n return Response.json(\n { error: \"Session not found\" },\n { status: 404 }\n );\n }\n return Response.json(this.sessions.getHistory(sessionId));\n }\n return Response.json(this.messages);\n }\n return _onRequest(request);\n };\n }\n\n /**\n * Route an incoming WebSocket message to the appropriate handler.\n * Returns true if the message was handled by the protocol.\n * @internal\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_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_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 /**\n * Handle CF_AGENT_USE_CHAT_REQUEST:\n * 1. Parse incoming messages\n * 2. Ensure a session exists\n * 3. Persist user messages to session\n * 4. Call onChatMessage\n * 5. Stream response back to clients\n * 6. Persist assistant message to session\n * @internal\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: { messages?: UIMessage[] };\n try {\n parsed = JSON.parse(init.body) as { messages?: UIMessage[] };\n } catch {\n return;\n }\n\n const incomingMessages = parsed.messages;\n if (!Array.isArray(incomingMessages)) return;\n\n // Ensure a session exists\n if (!this._sessionId) {\n const session = this.sessions.create(\"New Chat\");\n this._sessionId = session.id;\n }\n\n // Persist incoming messages to session (idempotent via INSERT OR IGNORE)\n this.sessions.appendAll(this._sessionId, incomingMessages);\n\n // Reload from session (authoritative)\n this.messages = this.sessions.getHistory(this._sessionId);\n\n // Broadcast updated messages to other connections\n this._broadcastMessages([connection.id]);\n\n // Set up abort controller\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 result = await agentContext.run(\n { agent: this, connection, request: undefined, email: undefined },\n () =>\n this.onChatMessage({\n signal: abortController.signal\n })\n );\n\n if (result) {\n await this._streamResult(requestId, result, abortController.signal);\n } else {\n this._broadcast({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"No response was generated.\",\n done: true\n });\n }\n });\n } catch (error) {\n this._broadcast({\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 /**\n * Handle CF_AGENT_CHAT_CLEAR: abort streams, clear current session messages.\n * @internal\n */\n private _handleClear() {\n for (const controller of this._abortControllers.values()) {\n controller.abort();\n }\n this._abortControllers.clear();\n\n if (this._sessionId) {\n this.sessions.clearMessages(this._sessionId);\n }\n\n this.messages = [];\n this._persistedMessageCache.clear();\n this._clearGeneration++;\n this._broadcast({ type: MSG_CHAT_CLEAR });\n }\n\n /**\n * Handle CF_AGENT_CHAT_REQUEST_CANCEL: abort a specific request.\n * @internal\n */\n private _handleCancel(requestId: string) {\n const controller = this._abortControllers.get(requestId);\n if (controller) {\n controller.abort();\n }\n }\n\n /**\n * Iterate a StreamableResult, broadcast chunks to clients,\n * build a UIMessage, and persist it to the session.\n * @internal\n */\n private async _streamResult(\n requestId: string,\n result: StreamableResult,\n abortSignal?: AbortSignal\n ) {\n const clearGen = this._clearGeneration;\n\n const message: UIMessage = {\n id: crypto.randomUUID(),\n role: \"assistant\",\n parts: []\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 data = chunk as StreamChunkData;\n\n // Build UIMessage from stream events\n const handled = applyChunkToParts(message.parts, data);\n\n if (!handled) {\n // Handle metadata events that applyChunkToParts doesn't cover\n switch (data.type) {\n case \"start\": {\n if (data.messageId != null) {\n message.id = data.messageId;\n }\n if (data.messageMetadata != null) {\n message.metadata = message.metadata\n ? { ...message.metadata, ...data.messageMetadata }\n : data.messageMetadata;\n }\n break;\n }\n case \"finish\":\n case \"message-metadata\": {\n if (data.messageMetadata != null) {\n message.metadata = message.metadata\n ? { ...message.metadata, ...data.messageMetadata }\n : data.messageMetadata;\n }\n break;\n }\n case \"error\": {\n this._broadcast({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: data.errorText ?? JSON.stringify(data),\n done: false,\n error: true\n });\n continue;\n }\n }\n }\n\n // Broadcast chunk to clients\n this._broadcast({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: JSON.stringify(chunk),\n done: false\n });\n }\n\n this._broadcast({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"\",\n done: true\n });\n doneSent = true;\n } catch (error) {\n if (!doneSent) {\n this._broadcast({\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._broadcast({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"\",\n done: true\n });\n }\n }\n\n // Persist the assistant message to the session (sanitized + size-enforced).\n // Skip if a clear happened during this stream (clearGeneration changed).\n // Wrapped in try-catch: the stream done message was already sent above,\n // so a persistence error must not propagate to the outer catch (which\n // would broadcast a second done message).\n if (\n message.parts.length > 0 &&\n this._sessionId &&\n this._clearGeneration === clearGen\n ) {\n try {\n this._persistAssistantMessage(message);\n this._broadcastMessages();\n } catch (e) {\n console.error(\"Failed to persist assistant message:\", e);\n }\n }\n }\n\n // ── Persistence internals ────────────────────────────────────────\n\n /**\n * Persist an assistant message with sanitization, size enforcement,\n * and incremental persistence.\n * @internal\n */\n private _persistAssistantMessage(msg: UIMessage): void {\n if (!this._sessionId) return;\n\n const sanitized = sanitizeMessage(msg);\n const safe = enforceRowSizeLimit(sanitized);\n const json = JSON.stringify(safe);\n\n // Skip SQL write if unchanged (incremental persistence)\n if (this._persistedMessageCache.get(safe.id) !== json) {\n this.sessions.upsert(this._sessionId, safe);\n this._persistedMessageCache.set(safe.id, json);\n }\n\n // Enforce storage bounds\n if (this.maxPersistedMessages != null) {\n this._enforceMaxPersistedMessages();\n }\n\n this.messages = this.sessions.getHistory(this._sessionId);\n }\n\n /**\n * Rebuild the persistence cache from current messages.\n * Called on startup to enable incremental persistence.\n * @internal\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 /**\n * Delete oldest messages on the current branch when count exceeds\n * maxPersistedMessages. Uses path-based count (not total across all\n * branches) and individual deletes to preserve branch structure.\n * @internal\n */\n private _enforceMaxPersistedMessages(): void {\n if (this.maxPersistedMessages == null || !this._sessionId) return;\n\n // Use current branch history, not total message count across all branches\n const history = this.sessions.getHistory(this._sessionId);\n if (history.length <= this.maxPersistedMessages) return;\n\n const excess = history.length - this.maxPersistedMessages;\n const toRemove = history.slice(0, excess);\n\n // Delete individual messages — preserves branch structure\n this.sessions.deleteMessages(toRemove.map((m) => m.id));\n for (const msg of toRemove) {\n this._persistedMessageCache.delete(msg.id);\n }\n }\n\n /**\n * Broadcast a JSON message to all connected clients.\n * @internal\n */\n private _broadcast(message: Record<string, unknown>, exclude?: string[]) {\n this.broadcast(JSON.stringify(message), exclude);\n }\n\n /**\n * Broadcast the current message list to all connected clients.\n * @internal\n */\n private _broadcastMessages(exclude?: string[]) {\n this._broadcast(\n { type: MSG_CHAT_MESSAGES, messages: this.messages },\n exclude\n );\n }\n}\n"],"mappings":";;;;;;;;AAWA,MAAM,cAAc,IAAI,aAAa;;AAGrC,MAAM,gBAAgB;;AAGtB,SAAS,WAAW,GAAmB;AACrC,QAAO,YAAY,OAAO,EAAE,CAAC;;;;;;;;;AAU/B,SAAgB,gBAAgB,SAA+B;CA8B7D,MAAM,iBA5BgB,QAAQ,MAAM,KAAK,SAAS;EAChD,IAAI,gBAAgB;AAEpB,MACE,sBAAsB,iBACtB,cAAc,oBACd,OAAO,cAAc,qBAAqB,YAC1C,YAAY,cAAc,iBAE1B,iBAAgB,oBAAoB,eAAe,mBAAmB;AAGxE,MACE,0BAA0B,iBAC1B,cAAc,wBACd,OAAO,cAAc,yBAAyB,YAC9C,YAAY,cAAc,qBAE1B,iBAAgB,oBACd,eACA,uBACD;AAGH,SAAO;GACP,CAGmC,QAAQ,SAAS;AACpD,MAAI,KAAK,SAAS,aAAa;GAC7B,MAAM,gBAAgB;AACtB,OAAI,CAAC,cAAc,QAAQ,cAAc,KAAK,MAAM,KAAK,IAAI;AAC3D,QACE,sBAAsB,iBACtB,cAAc,oBACd,OAAO,cAAc,qBAAqB,YAC1C,OAAO,KAAK,cAAc,iBAAiB,CAAC,SAAS,EAErD,QAAO;AAET,WAAO;;;AAGX,SAAO;GACP;AAEF,QAAO;EAAE,GAAG;EAAS,OAAO;EAAgB;;;;;AAM9C,SAAS,oBACP,MACA,aACG;CACH,MAAM,WAAY,KAAiC;AAKnD,KAAI,CAAC,UAAU,OAAQ,QAAO;CAE9B,MAAM,EACJ,QAAQ,SACR,2BAA2B,MAC3B,GAAG,eACD,SAAS;CAEb,MAAM,uBAAuB,OAAO,KAAK,WAAW,CAAC,SAAS;CAC9D,MAAM,EAAE,QAAQ,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;;;;;;CAOlD,mBAA2B,SAAoB;AAC7C,OAAK,WACH;GAAE,MAAM;GAAmB,UAAU,KAAK;GAAU,EACpD,QACD"}
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/C,OAAQ,qBAA2D;sDAI/C,MAAM;iDACI,KAAK;;CAEnC,qBAAmC;AACjC,MAAA,uBAAA,mBAAI,KAAsB,CAAE;AAC5B,OAAK,GAAG;;;;;AAKR,yBAAA,mBAAA,MAAyB,KAAI;;;;;;CAO/B,UAAU,QAAsB;AAC9B,OAAK,oBAAoB;EACzB,MAAM,OAAO,KAAK,UAAU,OAAO;AACnC,OAAK,GAAG;4EACgE,KAAK;;AAE7E,yBAAA,cAAA,MAAoB,OAAM;;;;;CAM5B,YAA2B;AACzB,MAAA,uBAAA,cAAI,K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K,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,6 +1,6 @@
1
- import * as ai from "ai";
1
+ import * as _$ai from "ai";
2
2
  import { ToolSet } from "ai";
3
- import * as _cloudflare_codemode_ai0 from "@cloudflare/codemode/ai";
3
+ import * as _$_cloudflare_codemode_ai0 from "@cloudflare/codemode/ai";
4
4
  import { Executor, ToolProvider } from "@cloudflare/codemode";
5
5
  import { StateBackend } from "@cloudflare/shell";
6
6
 
@@ -131,9 +131,9 @@ interface CreateExecuteToolOptions {
131
131
  */
132
132
  declare function createExecuteTool(
133
133
  options: CreateExecuteToolOptions
134
- ): ai.Tool<
135
- _cloudflare_codemode_ai0.CodeInput,
136
- _cloudflare_codemode_ai0.CodeOutput
134
+ ): _$ai.Tool<
135
+ _$_cloudflare_codemode_ai0.CodeInput,
136
+ _$_cloudflare_codemode_ai0.CodeOutput
137
137
  >;
138
138
  //#endregion
139
139
  export { CreateExecuteToolOptions, createExecuteTool };
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  r as ExtensionManager,
3
3
  s as ExtensionPermissions
4
- } from "../index-BlcvIdWK.js";
5
- import * as ai from "ai";
4
+ } from "../index-CAMRySsy.js";
5
+ import * as _$ai from "ai";
6
6
 
7
7
  //#region src/tools/extensions.d.ts
8
8
  interface ExtensionToolsOptions {
@@ -30,7 +30,7 @@ interface ExtensionToolsOptions {
30
30
  * ```
31
31
  */
32
32
  declare function createExtensionTools(options: ExtensionToolsOptions): {
33
- load_extension: ai.Tool<
33
+ load_extension: _$ai.Tool<
34
34
  {
35
35
  name: string;
36
36
  version: string;
@@ -48,7 +48,7 @@ declare function createExtensionTools(options: ExtensionToolsOptions): {
48
48
  message: string;
49
49
  }
50
50
  >;
51
- list_extensions: ai.Tool<
51
+ list_extensions: _$ai.Tool<
52
52
  Record<string, never>,
53
53
  {
54
54
  count: number;
@@ -1,4 +1,4 @@
1
- import { n as sanitizeName } from "../manager-DIV0gQf3.js";
1
+ import { n as sanitizeName } from "../manager-UjPxAz2E.js";
2
2
  import { tool } from "ai";
3
3
  import { z } from "zod";
4
4
  //#region src/tools/extensions.ts
@@ -1,4 +1,4 @@
1
- import * as ai from "ai";
1
+ import * as _$ai from "ai";
2
2
  import { FileInfo, Workspace } from "@cloudflare/shell";
3
3
 
4
4
  //#region src/tools/workspace.d.ts
@@ -52,7 +52,7 @@ interface GrepOperations {
52
52
  * import { createWorkspaceTools } from "@cloudflare/think";
53
53
  *
54
54
  * class MyAgent extends Agent<Env> {
55
- * workspace = new Workspace(this);
55
+ * workspace = new Workspace({ sql: this.ctx.storage.sql, name: () => this.name });
56
56
  *
57
57
  * async onChatMessage() {
58
58
  * const tools = createWorkspaceTools(this.workspace);
@@ -63,7 +63,7 @@ interface GrepOperations {
63
63
  * ```
64
64
  */
65
65
  declare function createWorkspaceTools(workspace: Workspace): {
66
- read: ai.Tool<
66
+ read: _$ai.Tool<
67
67
  {
68
68
  path: string;
69
69
  offset?: number | undefined;
@@ -71,7 +71,7 @@ declare function createWorkspaceTools(workspace: Workspace): {
71
71
  },
72
72
  Record<string, unknown>
73
73
  >;
74
- write: ai.Tool<
74
+ write: _$ai.Tool<
75
75
  {
76
76
  path: string;
77
77
  content: string;
@@ -82,7 +82,7 @@ declare function createWorkspaceTools(workspace: Workspace): {
82
82
  lines: number;
83
83
  }
84
84
  >;
85
- edit: ai.Tool<
85
+ edit: _$ai.Tool<
86
86
  {
87
87
  path: string;
88
88
  old_string: string;
@@ -121,7 +121,7 @@ declare function createWorkspaceTools(workspace: Workspace): {
121
121
  fuzzyMatch?: undefined;
122
122
  }
123
123
  >;
124
- list: ai.Tool<
124
+ list: _$ai.Tool<
125
125
  {
126
126
  path: string;
127
127
  limit?: number | undefined;
@@ -133,13 +133,13 @@ declare function createWorkspaceTools(workspace: Workspace): {
133
133
  entries: string[];
134
134
  }
135
135
  >;
136
- find: ai.Tool<
136
+ find: _$ai.Tool<
137
137
  {
138
138
  pattern: string;
139
139
  },
140
140
  Record<string, unknown>
141
141
  >;
142
- grep: ai.Tool<
142
+ grep: _$ai.Tool<
143
143
  {
144
144
  query: string;
145
145
  include?: string | undefined;
@@ -149,7 +149,7 @@ declare function createWorkspaceTools(workspace: Workspace): {
149
149
  },
150
150
  Record<string, unknown>
151
151
  >;
152
- delete: ai.Tool<
152
+ delete: _$ai.Tool<
153
153
  {
154
154
  path: string;
155
155
  recursive?: boolean | undefined;
@@ -162,7 +162,7 @@ declare function createWorkspaceTools(workspace: Workspace): {
162
162
  interface ReadToolOptions {
163
163
  ops: ReadOperations;
164
164
  }
165
- declare function createReadTool(options: ReadToolOptions): ai.Tool<
165
+ declare function createReadTool(options: ReadToolOptions): _$ai.Tool<
166
166
  {
167
167
  path: string;
168
168
  offset?: number | undefined;
@@ -173,7 +173,7 @@ declare function createReadTool(options: ReadToolOptions): ai.Tool<
173
173
  interface WriteToolOptions {
174
174
  ops: WriteOperations;
175
175
  }
176
- declare function createWriteTool(options: WriteToolOptions): ai.Tool<
176
+ declare function createWriteTool(options: WriteToolOptions): _$ai.Tool<
177
177
  {
178
178
  path: string;
179
179
  content: string;
@@ -187,7 +187,7 @@ declare function createWriteTool(options: WriteToolOptions): ai.Tool<
187
187
  interface EditToolOptions {
188
188
  ops: EditOperations;
189
189
  }
190
- declare function createEditTool(options: EditToolOptions): ai.Tool<
190
+ declare function createEditTool(options: EditToolOptions): _$ai.Tool<
191
191
  {
192
192
  path: string;
193
193
  old_string: string;
@@ -229,7 +229,7 @@ declare function createEditTool(options: EditToolOptions): ai.Tool<
229
229
  interface ListToolOptions {
230
230
  ops: ListOperations;
231
231
  }
232
- declare function createListTool(options: ListToolOptions): ai.Tool<
232
+ declare function createListTool(options: ListToolOptions): _$ai.Tool<
233
233
  {
234
234
  path: string;
235
235
  limit?: number | undefined;
@@ -244,7 +244,7 @@ declare function createListTool(options: ListToolOptions): ai.Tool<
244
244
  interface FindToolOptions {
245
245
  ops: FindOperations;
246
246
  }
247
- declare function createFindTool(options: FindToolOptions): ai.Tool<
247
+ declare function createFindTool(options: FindToolOptions): _$ai.Tool<
248
248
  {
249
249
  pattern: string;
250
250
  },
@@ -253,7 +253,7 @@ declare function createFindTool(options: FindToolOptions): ai.Tool<
253
253
  interface GrepToolOptions {
254
254
  ops: GrepOperations;
255
255
  }
256
- declare function createGrepTool(options: GrepToolOptions): ai.Tool<
256
+ declare function createGrepTool(options: GrepToolOptions): _$ai.Tool<
257
257
  {
258
258
  query: string;
259
259
  include?: string | undefined;
@@ -266,7 +266,7 @@ declare function createGrepTool(options: GrepToolOptions): ai.Tool<
266
266
  interface DeleteToolOptions {
267
267
  ops: DeleteOperations;
268
268
  }
269
- declare function createDeleteTool(options: DeleteToolOptions): ai.Tool<
269
+ declare function createDeleteTool(options: DeleteToolOptions): _$ai.Tool<
270
270
  {
271
271
  path: string;
272
272
  recursive?: boolean | undefined;
@@ -42,7 +42,7 @@ function workspaceGrepOps(ws) {
42
42
  * import { createWorkspaceTools } from "@cloudflare/think";
43
43
  *
44
44
  * class MyAgent extends Agent<Env> {
45
- * workspace = new Workspace(this);
45
+ * workspace = new Workspace({ sql: this.ctx.storage.sql, name: () => this.name });
46
46
  *
47
47
  * async onChatMessage() {
48
48
  * const tools = createWorkspaceTools(this.workspace);
@@ -1 +1 @@
1
- {"version":3,"file":"workspace.js","names":[],"sources":["../../src/tools/workspace.ts"],"sourcesContent":["import type { Workspace, FileInfo } from \"@cloudflare/shell\";\nimport { tool } from \"ai\";\nimport { z } from \"zod\";\n\n// ── Operations interfaces ─────────────────────────────────────────\n// Abstractions over file I/O so the same tools can work against\n// Workspace, a local filesystem, or anything else.\n\nexport interface ReadOperations {\n readFile(path: string): Promise<string | null>;\n stat(path: string): Promise<FileInfo | null> | FileInfo | null;\n}\n\nexport interface WriteOperations {\n writeFile(path: string, content: string): Promise<void>;\n mkdir(path: string, opts?: { recursive?: boolean }): Promise<void> | void;\n}\n\nexport interface EditOperations {\n readFile(path: string): Promise<string | null>;\n writeFile(path: string, content: string): Promise<void>;\n}\n\nexport interface ListOperations {\n readDir(\n dir: string,\n opts?: { limit?: number; offset?: number }\n ): Promise<FileInfo[]> | FileInfo[];\n}\n\nexport interface FindOperations {\n glob(pattern: string): Promise<FileInfo[]> | FileInfo[];\n}\n\nexport interface DeleteOperations {\n rm(\n path: string,\n opts?: { recursive?: boolean; force?: boolean }\n ): Promise<void>;\n}\n\nexport interface GrepOperations {\n glob(pattern: string): Promise<FileInfo[]> | FileInfo[];\n readFile(path: string): Promise<string | null>;\n}\n\n// ── Workspace-backed operation factories ──────────────────────────\n\nfunction workspaceReadOps(ws: Workspace): ReadOperations {\n return {\n readFile: (path) => ws.readFile(path),\n stat: (path) => ws.stat(path)\n };\n}\n\nfunction workspaceWriteOps(ws: Workspace): WriteOperations {\n return {\n writeFile: (path, content) => ws.writeFile(path, content),\n mkdir: (path, opts) => ws.mkdir(path, opts)\n };\n}\n\nfunction workspaceEditOps(ws: Workspace): EditOperations {\n return {\n readFile: (path) => ws.readFile(path),\n writeFile: (path, content) => ws.writeFile(path, content)\n };\n}\n\nfunction workspaceListOps(ws: Workspace): ListOperations {\n return {\n readDir: (dir, opts) => ws.readDir(dir, opts)\n };\n}\n\nfunction workspaceFindOps(ws: Workspace): FindOperations {\n return {\n glob: (pattern) => ws.glob(pattern)\n };\n}\n\nfunction workspaceDeleteOps(ws: Workspace): DeleteOperations {\n return {\n rm: (path, opts) => ws.rm(path, opts)\n };\n}\n\nfunction workspaceGrepOps(ws: Workspace): GrepOperations {\n return {\n glob: (pattern) => ws.glob(pattern),\n readFile: (path) => ws.readFile(path)\n };\n}\n\n/**\n * Create a complete set of AI SDK tools backed by a Workspace instance.\n *\n * ```ts\n * import { Workspace } from \"@cloudflare/shell\";\n * import { createWorkspaceTools } from \"@cloudflare/think\";\n *\n * class MyAgent extends Agent<Env> {\n * workspace = new Workspace(this);\n *\n * async onChatMessage() {\n * const tools = createWorkspaceTools(this.workspace);\n * const result = streamText({ model, tools, messages });\n * return result.toUIMessageStreamResponse();\n * }\n * }\n * ```\n */\nexport function createWorkspaceTools(workspace: Workspace) {\n return {\n read: createReadTool({ ops: workspaceReadOps(workspace) }),\n write: createWriteTool({ ops: workspaceWriteOps(workspace) }),\n edit: createEditTool({ ops: workspaceEditOps(workspace) }),\n list: createListTool({ ops: workspaceListOps(workspace) }),\n find: createFindTool({ ops: workspaceFindOps(workspace) }),\n grep: createGrepTool({ ops: workspaceGrepOps(workspace) }),\n delete: createDeleteTool({ ops: workspaceDeleteOps(workspace) })\n };\n}\n\n// ── Read ────────────────────────────────────────────────────────────\n\nconst MAX_LINES = 2000;\nconst MAX_LINE_LENGTH = 2000;\n\nexport interface ReadToolOptions {\n ops: ReadOperations;\n}\n\nexport function createReadTool(options: ReadToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"Read the contents of a file. Returns the file content with line numbers. \" +\n \"Use offset and limit for large files. Returns null if the file does not exist.\",\n inputSchema: z.object({\n path: z.string().describe(\"Absolute path to the file\"),\n offset: z\n .number()\n .int()\n .min(1)\n .optional()\n .describe(\"1-indexed line number to start reading from\"),\n limit: z\n .number()\n .int()\n .min(1)\n .optional()\n .describe(\"Number of lines to read\")\n }),\n execute: async ({ path, offset, limit }) => {\n const stat = await ops.stat(path);\n if (!stat) {\n return { error: `File not found: ${path}` };\n }\n if (stat.type === \"directory\") {\n return { error: `${path} is a directory, not a file` };\n }\n\n const content = await ops.readFile(path);\n if (content === null) {\n return { error: `Could not read file: ${path}` };\n }\n\n const allLines = content.split(\"\\n\");\n const totalLines = allLines.length;\n\n // Apply offset/limit\n const startLine = offset ? offset - 1 : 0;\n const endLine = limit ? startLine + limit : allLines.length;\n const lines = allLines.slice(startLine, endLine);\n\n // Format with line numbers, truncate long lines\n const numbered = lines.map((line, i) => {\n const lineNum = startLine + i + 1;\n const truncated =\n line.length > MAX_LINE_LENGTH\n ? line.slice(0, MAX_LINE_LENGTH) + \"... (truncated)\"\n : line;\n return `${lineNum}\\t${truncated}`;\n });\n\n // Truncate if too many lines\n let output: string;\n if (numbered.length > MAX_LINES) {\n output =\n numbered.slice(0, MAX_LINES).join(\"\\n\") +\n `\\n... (${numbered.length - MAX_LINES} more lines truncated)`;\n } else {\n output = numbered.join(\"\\n\");\n }\n\n const result: Record<string, unknown> = {\n path,\n content: output,\n totalLines\n };\n\n if (offset || limit) {\n result.fromLine = startLine + 1;\n result.toLine = Math.min(endLine, totalLines);\n }\n\n return result;\n }\n });\n}\n\n// ── Write ───────────────────────────────────────────────────────────\n\nexport interface WriteToolOptions {\n ops: WriteOperations;\n}\n\nexport function createWriteTool(options: WriteToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"Write content to a file. Creates the file if it does not exist, \" +\n \"overwrites if it does. Parent directories are created automatically.\",\n inputSchema: z.object({\n path: z.string().describe(\"Absolute path to the file\"),\n content: z.string().describe(\"Content to write to the file\")\n }),\n execute: async ({ path, content }) => {\n // Ensure parent directory exists\n const parent = path.replace(/\\/[^/]+$/, \"\");\n if (parent && parent !== \"/\") {\n await ops.mkdir(parent, { recursive: true });\n }\n\n await ops.writeFile(path, content);\n\n const lines = content.split(\"\\n\").length;\n return {\n path,\n bytesWritten: new TextEncoder().encode(content).byteLength,\n lines\n };\n }\n });\n}\n\n// ── Edit ────────────────────────────────────────────────────────────\n\nexport interface EditToolOptions {\n ops: EditOperations;\n}\n\nexport function createEditTool(options: EditToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"Make a targeted edit to a file by replacing an exact string match. \" +\n \"Provide the old_string to find and new_string to replace it with. \" +\n \"The old_string must match exactly (including whitespace and indentation). \" +\n \"Use an empty old_string with new_string to create a new file.\",\n inputSchema: z.object({\n path: z.string().describe(\"Absolute path to the file\"),\n old_string: z\n .string()\n .describe(\n \"Exact text to find and replace. Empty string to create a new file.\"\n ),\n new_string: z.string().describe(\"Replacement text\")\n }),\n execute: async ({ path, old_string, new_string }) => {\n // Create new file\n if (old_string === \"\") {\n const existing = await ops.readFile(path);\n if (existing !== null) {\n return {\n error:\n \"File already exists. Provide old_string to edit, or use the write tool to overwrite.\"\n };\n }\n await ops.writeFile(path, new_string);\n return {\n path,\n created: true,\n lines: new_string.split(\"\\n\").length\n };\n }\n\n // Edit existing file\n const content = await ops.readFile(path);\n if (content === null) {\n return { error: `File not found: ${path}` };\n }\n\n // Count occurrences\n const occurrences = countOccurrences(content, old_string);\n if (occurrences === 0) {\n // Try fuzzy match — normalize whitespace and look again\n const fuzzyResult = fuzzyReplace(content, old_string, new_string);\n if (fuzzyResult === \"ambiguous\") {\n return {\n error:\n \"old_string matches multiple locations after whitespace normalization. \" +\n \"Include more surrounding context to make the match unique.\"\n };\n }\n if (fuzzyResult !== null) {\n await ops.writeFile(path, fuzzyResult);\n return {\n path,\n replaced: true,\n fuzzyMatch: true,\n lines: fuzzyResult.split(\"\\n\").length\n };\n }\n\n return {\n error:\n \"old_string not found in file. Make sure it matches exactly, \" +\n \"including whitespace and indentation. Read the file first to verify.\"\n };\n }\n\n if (occurrences > 1) {\n return {\n error:\n `old_string appears ${occurrences} times in the file. ` +\n \"Include more surrounding context to make the match unique.\"\n };\n }\n\n const newContent = content.replace(old_string, new_string);\n await ops.writeFile(path, newContent);\n\n return {\n path,\n replaced: true,\n lines: newContent.split(\"\\n\").length\n };\n }\n });\n}\n\nfunction countOccurrences(text: string, search: string): number {\n let count = 0;\n let pos = 0;\n while (true) {\n const idx = text.indexOf(search, pos);\n if (idx === -1) break;\n count++;\n pos = idx + 1;\n }\n return count;\n}\n\n/**\n * Fuzzy replacement: normalize whitespace in both the file content\n * and the search string, find the match, then replace the corresponding\n * region in the original content.\n */\nfunction fuzzyReplace(\n content: string,\n oldStr: string,\n newStr: string\n): string | \"ambiguous\" | null {\n const normalizedContent = normalizeWhitespace(content);\n const normalizedSearch = normalizeWhitespace(oldStr);\n\n if (!normalizedSearch) return null;\n\n const idx = normalizedContent.indexOf(normalizedSearch);\n if (idx === -1) return null;\n\n // Check for multiple fuzzy matches\n const secondIdx = normalizedContent.indexOf(\n normalizedSearch,\n idx + normalizedSearch.length\n );\n if (secondIdx !== -1) return \"ambiguous\";\n\n // Map the normalized index back to the original content.\n // Walk both strings in parallel to find the original start/end.\n const originalStart = mapToOriginal(content, idx);\n const originalEnd = mapToOriginal(content, idx + normalizedSearch.length);\n\n return content.slice(0, originalStart) + newStr + content.slice(originalEnd);\n}\n\nfunction normalizeWhitespace(s: string): string {\n return s.replace(/[ \\t]+/g, \" \").replace(/\\r\\n/g, \"\\n\");\n}\n\n/**\n * Map a position in the normalized string back to the original string.\n * Walks both strings char-by-char, skipping extra whitespace in the original.\n */\nfunction mapToOriginal(original: string, normalizedPos: number): number {\n let ni = 0;\n let oi = 0;\n\n while (ni < normalizedPos && oi < original.length) {\n const oc = original[oi];\n if (oc === \"\\r\" && original[oi + 1] === \"\\n\") {\n // \\r\\n in original maps to \\n in normalized\n oi += 2;\n ni += 1;\n } else if (oc === \" \" || oc === \"\\t\") {\n // Consume a run of spaces/tabs in original → single space in normalized\n oi++;\n while (\n oi < original.length &&\n (original[oi] === \" \" || original[oi] === \"\\t\")\n ) {\n oi++;\n }\n ni++;\n } else {\n oi++;\n ni++;\n }\n }\n\n return oi;\n}\n\n// ── List ────────────────────────────────────────────────────────────\n\nexport interface ListToolOptions {\n ops: ListOperations;\n}\n\nexport function createListTool(options: ListToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"List files and directories in a given path. \" +\n \"Returns names, types, and sizes for each entry.\",\n inputSchema: z.object({\n path: z\n .string()\n .default(\"/\")\n .describe(\"Absolute path to the directory to list\"),\n limit: z\n .number()\n .int()\n .min(1)\n .max(1000)\n .optional()\n .describe(\"Maximum number of entries to return (default: 200)\"),\n offset: z\n .number()\n .int()\n .min(0)\n .optional()\n .describe(\"Number of entries to skip (for pagination)\")\n }),\n execute: async ({ path, limit, offset }) => {\n const maxEntries = limit ?? 200;\n const entries = await ops.readDir(path, {\n limit: maxEntries,\n offset: offset ?? 0\n });\n\n const formatted = entries.map((entry) => {\n const suffix = entry.type === \"directory\" ? \"/\" : \"\";\n const sizeStr =\n entry.type === \"file\" ? ` (${formatSize(entry.size)})` : \"\";\n return `${entry.name}${suffix}${sizeStr}`;\n });\n\n return {\n path,\n count: entries.length,\n entries: formatted\n };\n }\n });\n}\n\nfunction formatSize(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\n// ── Find ────────────────────────────────────────────────────────────\n\nexport interface FindToolOptions {\n ops: FindOperations;\n}\n\nexport function createFindTool(options: FindToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"Find files matching a glob pattern. \" +\n \"Supports standard glob syntax: * matches any file, ** matches directories recursively, \" +\n \"? matches a single character. Returns matching file paths with types and sizes.\",\n inputSchema: z.object({\n pattern: z\n .string()\n .describe(\n 'Glob pattern to match (e.g. \"**/*.ts\", \"src/**/*.test.ts\", \"*.md\")'\n )\n }),\n execute: async ({ pattern }) => {\n const matches = await ops.glob(pattern);\n\n const MAX_RESULTS = 200;\n const truncated = matches.length > MAX_RESULTS;\n const results = matches.slice(0, MAX_RESULTS);\n\n const formatted = results.map((entry) => {\n const suffix = entry.type === \"directory\" ? \"/\" : \"\";\n return `${entry.path}${suffix}`;\n });\n\n const result: Record<string, unknown> = {\n pattern,\n count: matches.length,\n files: formatted\n };\n\n if (truncated) {\n result.truncated = true;\n result.showing = MAX_RESULTS;\n }\n\n return result;\n }\n });\n}\n\n// ── Grep ────────────────────────────────────────────────────────────\n\nconst MAX_MATCHES = 200;\nconst MAX_FILE_SIZE = 1_048_576; // 1 MB — skip files larger than this in grep\n\nexport interface GrepToolOptions {\n ops: GrepOperations;\n}\n\nexport function createGrepTool(options: GrepToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"Search file contents using a regular expression or fixed string. \" +\n \"Returns matching lines with file paths and line numbers. \" +\n \"Searches all files matching the include glob, or all files if not specified.\",\n inputSchema: z.object({\n query: z.string().describe(\"Search pattern (regex or fixed string)\"),\n include: z\n .string()\n .optional()\n .describe(\n 'Glob pattern to filter files (e.g. \"**/*.ts\"). Defaults to \"**/*\"'\n ),\n fixedString: z\n .boolean()\n .optional()\n .describe(\"If true, treat query as a literal string instead of regex\"),\n caseSensitive: z\n .boolean()\n .optional()\n .describe(\"If true, search is case-sensitive (default: false)\"),\n contextLines: z\n .number()\n .int()\n .min(0)\n .max(10)\n .optional()\n .describe(\"Number of context lines around each match (default: 0)\")\n }),\n execute: async ({\n query,\n include,\n fixedString,\n caseSensitive,\n contextLines\n }) => {\n const pattern = include ?? \"**/*\";\n const allFiles = await ops.glob(pattern);\n const files = allFiles.filter((f: { type: string }) => f.type === \"file\");\n\n let regex: RegExp;\n try {\n const escaped = fixedString ? escapeRegex(query) : query;\n regex = new RegExp(escaped, caseSensitive ? \"g\" : \"gi\");\n } catch {\n return { error: `Invalid regex: ${query}` };\n }\n\n const ctx = contextLines ?? 0;\n const matches: Array<{\n file: string;\n line: number;\n text: string;\n context?: string[];\n }> = [];\n let totalMatches = 0;\n let filesSearched = 0;\n let filesWithMatches = 0;\n\n let filesSkipped = 0;\n\n for (const file of files) {\n if (totalMatches >= MAX_MATCHES) break;\n\n // Skip files larger than 1 MB to avoid memory blowup\n if (file.size > MAX_FILE_SIZE) {\n filesSkipped++;\n continue;\n }\n\n const content = await ops.readFile(file.path);\n if (content === null) continue;\n filesSearched++;\n\n const lines = content.split(\"\\n\");\n let fileHasMatch = false;\n\n for (let i = 0; i < lines.length; i++) {\n if (totalMatches >= MAX_MATCHES) break;\n\n regex.lastIndex = 0;\n if (regex.test(lines[i])) {\n if (!fileHasMatch) {\n fileHasMatch = true;\n filesWithMatches++;\n }\n totalMatches++;\n\n const match: {\n file: string;\n line: number;\n text: string;\n context?: string[];\n } = {\n file: file.path,\n line: i + 1,\n text: lines[i]\n };\n\n if (ctx > 0) {\n const start = Math.max(0, i - ctx);\n const end = Math.min(lines.length, i + ctx + 1);\n match.context = lines.slice(start, end).map((l, j) => {\n const lineNum = start + j + 1;\n const marker = lineNum === i + 1 ? \">\" : \" \";\n return `${marker} ${lineNum}\\t${l}`;\n });\n }\n\n matches.push(match);\n }\n }\n }\n\n const result: Record<string, unknown> = {\n query,\n filesSearched,\n filesWithMatches,\n totalMatches,\n matches: matches.map((m) => {\n if (m.context) {\n return {\n file: m.file,\n line: m.line,\n context: m.context.join(\"\\n\")\n };\n }\n return `${m.file}:${m.line}: ${m.text}`;\n })\n };\n\n if (totalMatches >= MAX_MATCHES) {\n result.truncated = true;\n }\n if (filesSkipped > 0) {\n result.filesSkipped = filesSkipped;\n result.note = `${filesSkipped} file(s) skipped (larger than 1 MB)`;\n }\n\n return result;\n }\n });\n}\n\nfunction escapeRegex(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n// ── Delete ──────────────────────────────────────────────────────────\n\nexport interface DeleteToolOptions {\n ops: DeleteOperations;\n}\n\nexport function createDeleteTool(options: DeleteToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"Delete a file or directory. \" +\n \"Set recursive to true to remove non-empty directories.\",\n inputSchema: z.object({\n path: z.string().describe(\"Absolute path to the file or directory\"),\n recursive: z\n .boolean()\n .optional()\n .describe(\"If true, remove directories and their contents recursively\")\n }),\n execute: async ({ path, recursive }) => {\n await ops.rm(path, { recursive, force: true });\n return { deleted: path };\n }\n });\n}\n"],"mappings":";;;AAgDA,SAAS,iBAAiB,IAA+B;AACvD,QAAO;EACL,WAAW,SAAS,GAAG,SAAS,KAAK;EACrC,OAAO,SAAS,GAAG,KAAK,KAAK;EAC9B;;AAGH,SAAS,kBAAkB,IAAgC;AACzD,QAAO;EACL,YA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E;MACR,MAAM,EAAE;MACR,SAAS,EAAE,QAAQ,KAAK,KAAK;MAC9B;AAEH,YAAO,GAAG,EAAE,KAAK,GAAG,EAAE,KAAK,IAAI,EAAE;MACjC;IACH;AAED,OAAI,gBAAgB,YAClB,QAAO,YAAY;AAErB,OAAI,eAAe,GAAG;AACpB,WAAO,eAAe;AACtB,WAAO,OAAO,GAAG,aAAa;;AAGhC,UAAO;;EAEV,CAAC;;AAGJ,SAAS,YAAY,GAAmB;AACtC,QAAO,EAAE,QAAQ,uBAAuB,OAAO;;AASjD,SAAgB,iBAAiB,SAA4B;CAC3D,MAAM,EAAE,QAAQ;AAEhB,QAAO,KAAK;EACV,aACE;EAEF,aAAa,EAAE,OAAO;GACpB,MAAM,EAAE,QAAQ,CAAC,SAAS,yCAAyC;GACnE,WAAW,EACR,SAAS,CACT,UAAU,CACV,SAAS,6DAA6D;GAC1E,CAAC;EACF,SAAS,OAAO,EAAE,MAAM,gBAAgB;AACtC,SAAM,IAAI,GAAG,MAAM;IAAE;IAAW,OAAO;IAAM,CAAC;AAC9C,UAAO,EAAE,SAAS,MAAM;;EAE3B,CAAC"}
1
+ {"version":3,"file":"workspace.js","names":[],"sources":["../../src/tools/workspace.ts"],"sourcesContent":["import type { Workspace, FileInfo } from \"@cloudflare/shell\";\nimport { tool } from \"ai\";\nimport { z } from \"zod\";\n\n// ── Operations interfaces ─────────────────────────────────────────\n// Abstractions over file I/O so the same tools can work against\n// Workspace, a local filesystem, or anything else.\n\nexport interface ReadOperations {\n readFile(path: string): Promise<string | null>;\n stat(path: string): Promise<FileInfo | null> | FileInfo | null;\n}\n\nexport interface WriteOperations {\n writeFile(path: string, content: string): Promise<void>;\n mkdir(path: string, opts?: { recursive?: boolean }): Promise<void> | void;\n}\n\nexport interface EditOperations {\n readFile(path: string): Promise<string | null>;\n writeFile(path: string, content: string): Promise<void>;\n}\n\nexport interface ListOperations {\n readDir(\n dir: string,\n opts?: { limit?: number; offset?: number }\n ): Promise<FileInfo[]> | FileInfo[];\n}\n\nexport interface FindOperations {\n glob(pattern: string): Promise<FileInfo[]> | FileInfo[];\n}\n\nexport interface DeleteOperations {\n rm(\n path: string,\n opts?: { recursive?: boolean; force?: boolean }\n ): Promise<void>;\n}\n\nexport interface GrepOperations {\n glob(pattern: string): Promise<FileInfo[]> | FileInfo[];\n readFile(path: string): Promise<string | null>;\n}\n\n// ── Workspace-backed operation factories ──────────────────────────\n\nfunction workspaceReadOps(ws: Workspace): ReadOperations {\n return {\n readFile: (path) => ws.readFile(path),\n stat: (path) => ws.stat(path)\n };\n}\n\nfunction workspaceWriteOps(ws: Workspace): WriteOperations {\n return {\n writeFile: (path, content) => ws.writeFile(path, content),\n mkdir: (path, opts) => ws.mkdir(path, opts)\n };\n}\n\nfunction workspaceEditOps(ws: Workspace): EditOperations {\n return {\n readFile: (path) => ws.readFile(path),\n writeFile: (path, content) => ws.writeFile(path, content)\n };\n}\n\nfunction workspaceListOps(ws: Workspace): ListOperations {\n return {\n readDir: (dir, opts) => ws.readDir(dir, opts)\n };\n}\n\nfunction workspaceFindOps(ws: Workspace): FindOperations {\n return {\n glob: (pattern) => ws.glob(pattern)\n };\n}\n\nfunction workspaceDeleteOps(ws: Workspace): DeleteOperations {\n return {\n rm: (path, opts) => ws.rm(path, opts)\n };\n}\n\nfunction workspaceGrepOps(ws: Workspace): GrepOperations {\n return {\n glob: (pattern) => ws.glob(pattern),\n readFile: (path) => ws.readFile(path)\n };\n}\n\n/**\n * Create a complete set of AI SDK tools backed by a Workspace instance.\n *\n * ```ts\n * import { Workspace } from \"@cloudflare/shell\";\n * import { createWorkspaceTools } from \"@cloudflare/think\";\n *\n * class MyAgent extends Agent<Env> {\n * workspace = new Workspace({ sql: this.ctx.storage.sql, name: () => this.name });\n *\n * async onChatMessage() {\n * const tools = createWorkspaceTools(this.workspace);\n * const result = streamText({ model, tools, messages });\n * return result.toUIMessageStreamResponse();\n * }\n * }\n * ```\n */\nexport function createWorkspaceTools(workspace: Workspace) {\n return {\n read: createReadTool({ ops: workspaceReadOps(workspace) }),\n write: createWriteTool({ ops: workspaceWriteOps(workspace) }),\n edit: createEditTool({ ops: workspaceEditOps(workspace) }),\n list: createListTool({ ops: workspaceListOps(workspace) }),\n find: createFindTool({ ops: workspaceFindOps(workspace) }),\n grep: createGrepTool({ ops: workspaceGrepOps(workspace) }),\n delete: createDeleteTool({ ops: workspaceDeleteOps(workspace) })\n };\n}\n\n// ── Read ────────────────────────────────────────────────────────────\n\nconst MAX_LINES = 2000;\nconst MAX_LINE_LENGTH = 2000;\n\nexport interface ReadToolOptions {\n ops: ReadOperations;\n}\n\nexport function createReadTool(options: ReadToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"Read the contents of a file. Returns the file content with line numbers. \" +\n \"Use offset and limit for large files. Returns null if the file does not exist.\",\n inputSchema: z.object({\n path: z.string().describe(\"Absolute path to the file\"),\n offset: z\n .number()\n .int()\n .min(1)\n .optional()\n .describe(\"1-indexed line number to start reading from\"),\n limit: z\n .number()\n .int()\n .min(1)\n .optional()\n .describe(\"Number of lines to read\")\n }),\n execute: async ({ path, offset, limit }) => {\n const stat = await ops.stat(path);\n if (!stat) {\n return { error: `File not found: ${path}` };\n }\n if (stat.type === \"directory\") {\n return { error: `${path} is a directory, not a file` };\n }\n\n const content = await ops.readFile(path);\n if (content === null) {\n return { error: `Could not read file: ${path}` };\n }\n\n const allLines = content.split(\"\\n\");\n const totalLines = allLines.length;\n\n // Apply offset/limit\n const startLine = offset ? offset - 1 : 0;\n const endLine = limit ? startLine + limit : allLines.length;\n const lines = allLines.slice(startLine, endLine);\n\n // Format with line numbers, truncate long lines\n const numbered = lines.map((line, i) => {\n const lineNum = startLine + i + 1;\n const truncated =\n line.length > MAX_LINE_LENGTH\n ? line.slice(0, MAX_LINE_LENGTH) + \"... (truncated)\"\n : line;\n return `${lineNum}\\t${truncated}`;\n });\n\n // Truncate if too many lines\n let output: string;\n if (numbered.length > MAX_LINES) {\n output =\n numbered.slice(0, MAX_LINES).join(\"\\n\") +\n `\\n... (${numbered.length - MAX_LINES} more lines truncated)`;\n } else {\n output = numbered.join(\"\\n\");\n }\n\n const result: Record<string, unknown> = {\n path,\n content: output,\n totalLines\n };\n\n if (offset || limit) {\n result.fromLine = startLine + 1;\n result.toLine = Math.min(endLine, totalLines);\n }\n\n return result;\n }\n });\n}\n\n// ── Write ───────────────────────────────────────────────────────────\n\nexport interface WriteToolOptions {\n ops: WriteOperations;\n}\n\nexport function createWriteTool(options: WriteToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"Write content to a file. Creates the file if it does not exist, \" +\n \"overwrites if it does. Parent directories are created automatically.\",\n inputSchema: z.object({\n path: z.string().describe(\"Absolute path to the file\"),\n content: z.string().describe(\"Content to write to the file\")\n }),\n execute: async ({ path, content }) => {\n // Ensure parent directory exists\n const parent = path.replace(/\\/[^/]+$/, \"\");\n if (parent && parent !== \"/\") {\n await ops.mkdir(parent, { recursive: true });\n }\n\n await ops.writeFile(path, content);\n\n const lines = content.split(\"\\n\").length;\n return {\n path,\n bytesWritten: new TextEncoder().encode(content).byteLength,\n lines\n };\n }\n });\n}\n\n// ── Edit ────────────────────────────────────────────────────────────\n\nexport interface EditToolOptions {\n ops: EditOperations;\n}\n\nexport function createEditTool(options: EditToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"Make a targeted edit to a file by replacing an exact string match. \" +\n \"Provide the old_string to find and new_string to replace it with. \" +\n \"The old_string must match exactly (including whitespace and indentation). \" +\n \"Use an empty old_string with new_string to create a new file.\",\n inputSchema: z.object({\n path: z.string().describe(\"Absolute path to the file\"),\n old_string: z\n .string()\n .describe(\n \"Exact text to find and replace. Empty string to create a new file.\"\n ),\n new_string: z.string().describe(\"Replacement text\")\n }),\n execute: async ({ path, old_string, new_string }) => {\n // Create new file\n if (old_string === \"\") {\n const existing = await ops.readFile(path);\n if (existing !== null) {\n return {\n error:\n \"File already exists. Provide old_string to edit, or use the write tool to overwrite.\"\n };\n }\n await ops.writeFile(path, new_string);\n return {\n path,\n created: true,\n lines: new_string.split(\"\\n\").length\n };\n }\n\n // Edit existing file\n const content = await ops.readFile(path);\n if (content === null) {\n return { error: `File not found: ${path}` };\n }\n\n // Count occurrences\n const occurrences = countOccurrences(content, old_string);\n if (occurrences === 0) {\n // Try fuzzy match — normalize whitespace and look again\n const fuzzyResult = fuzzyReplace(content, old_string, new_string);\n if (fuzzyResult === \"ambiguous\") {\n return {\n error:\n \"old_string matches multiple locations after whitespace normalization. \" +\n \"Include more surrounding context to make the match unique.\"\n };\n }\n if (fuzzyResult !== null) {\n await ops.writeFile(path, fuzzyResult);\n return {\n path,\n replaced: true,\n fuzzyMatch: true,\n lines: fuzzyResult.split(\"\\n\").length\n };\n }\n\n return {\n error:\n \"old_string not found in file. Make sure it matches exactly, \" +\n \"including whitespace and indentation. Read the file first to verify.\"\n };\n }\n\n if (occurrences > 1) {\n return {\n error:\n `old_string appears ${occurrences} times in the file. ` +\n \"Include more surrounding context to make the match unique.\"\n };\n }\n\n const newContent = content.replace(old_string, new_string);\n await ops.writeFile(path, newContent);\n\n return {\n path,\n replaced: true,\n lines: newContent.split(\"\\n\").length\n };\n }\n });\n}\n\nfunction countOccurrences(text: string, search: string): number {\n let count = 0;\n let pos = 0;\n while (true) {\n const idx = text.indexOf(search, pos);\n if (idx === -1) break;\n count++;\n pos = idx + 1;\n }\n return count;\n}\n\n/**\n * Fuzzy replacement: normalize whitespace in both the file content\n * and the search string, find the match, then replace the corresponding\n * region in the original content.\n */\nfunction fuzzyReplace(\n content: string,\n oldStr: string,\n newStr: string\n): string | \"ambiguous\" | null {\n const normalizedContent = normalizeWhitespace(content);\n const normalizedSearch = normalizeWhitespace(oldStr);\n\n if (!normalizedSearch) return null;\n\n const idx = normalizedContent.indexOf(normalizedSearch);\n if (idx === -1) return null;\n\n // Check for multiple fuzzy matches\n const secondIdx = normalizedContent.indexOf(\n normalizedSearch,\n idx + normalizedSearch.length\n );\n if (secondIdx !== -1) return \"ambiguous\";\n\n // Map the normalized index back to the original content.\n // Walk both strings in parallel to find the original start/end.\n const originalStart = mapToOriginal(content, idx);\n const originalEnd = mapToOriginal(content, idx + normalizedSearch.length);\n\n return content.slice(0, originalStart) + newStr + content.slice(originalEnd);\n}\n\nfunction normalizeWhitespace(s: string): string {\n return s.replace(/[ \\t]+/g, \" \").replace(/\\r\\n/g, \"\\n\");\n}\n\n/**\n * Map a position in the normalized string back to the original string.\n * Walks both strings char-by-char, skipping extra whitespace in the original.\n */\nfunction mapToOriginal(original: string, normalizedPos: number): number {\n let ni = 0;\n let oi = 0;\n\n while (ni < normalizedPos && oi < original.length) {\n const oc = original[oi];\n if (oc === \"\\r\" && original[oi + 1] === \"\\n\") {\n // \\r\\n in original maps to \\n in normalized\n oi += 2;\n ni += 1;\n } else if (oc === \" \" || oc === \"\\t\") {\n // Consume a run of spaces/tabs in original → single space in normalized\n oi++;\n while (\n oi < original.length &&\n (original[oi] === \" \" || original[oi] === \"\\t\")\n ) {\n oi++;\n }\n ni++;\n } else {\n oi++;\n ni++;\n }\n }\n\n return oi;\n}\n\n// ── List ────────────────────────────────────────────────────────────\n\nexport interface ListToolOptions {\n ops: ListOperations;\n}\n\nexport function createListTool(options: ListToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"List files and directories in a given path. \" +\n \"Returns names, types, and sizes for each entry.\",\n inputSchema: z.object({\n path: z\n .string()\n .default(\"/\")\n .describe(\"Absolute path to the directory to list\"),\n limit: z\n .number()\n .int()\n .min(1)\n .max(1000)\n .optional()\n .describe(\"Maximum number of entries to return (default: 200)\"),\n offset: z\n .number()\n .int()\n .min(0)\n .optional()\n .describe(\"Number of entries to skip (for pagination)\")\n }),\n execute: async ({ path, limit, offset }) => {\n const maxEntries = limit ?? 200;\n const entries = await ops.readDir(path, {\n limit: maxEntries,\n offset: offset ?? 0\n });\n\n const formatted = entries.map((entry) => {\n const suffix = entry.type === \"directory\" ? \"/\" : \"\";\n const sizeStr =\n entry.type === \"file\" ? ` (${formatSize(entry.size)})` : \"\";\n return `${entry.name}${suffix}${sizeStr}`;\n });\n\n return {\n path,\n count: entries.length,\n entries: formatted\n };\n }\n });\n}\n\nfunction formatSize(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\n// ── Find ────────────────────────────────────────────────────────────\n\nexport interface FindToolOptions {\n ops: FindOperations;\n}\n\nexport function createFindTool(options: FindToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"Find files matching a glob pattern. \" +\n \"Supports standard glob syntax: * matches any file, ** matches directories recursively, \" +\n \"? matches a single character. Returns matching file paths with types and sizes.\",\n inputSchema: z.object({\n pattern: z\n .string()\n .describe(\n 'Glob pattern to match (e.g. \"**/*.ts\", \"src/**/*.test.ts\", \"*.md\")'\n )\n }),\n execute: async ({ pattern }) => {\n const matches = await ops.glob(pattern);\n\n const MAX_RESULTS = 200;\n const truncated = matches.length > MAX_RESULTS;\n const results = matches.slice(0, MAX_RESULTS);\n\n const formatted = results.map((entry) => {\n const suffix = entry.type === \"directory\" ? \"/\" : \"\";\n return `${entry.path}${suffix}`;\n });\n\n const result: Record<string, unknown> = {\n pattern,\n count: matches.length,\n files: formatted\n };\n\n if (truncated) {\n result.truncated = true;\n result.showing = MAX_RESULTS;\n }\n\n return result;\n }\n });\n}\n\n// ── Grep ────────────────────────────────────────────────────────────\n\nconst MAX_MATCHES = 200;\nconst MAX_FILE_SIZE = 1_048_576; // 1 MB — skip files larger than this in grep\n\nexport interface GrepToolOptions {\n ops: GrepOperations;\n}\n\nexport function createGrepTool(options: GrepToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"Search file contents using a regular expression or fixed string. \" +\n \"Returns matching lines with file paths and line numbers. \" +\n \"Searches all files matching the include glob, or all files if not specified.\",\n inputSchema: z.object({\n query: z.string().describe(\"Search pattern (regex or fixed string)\"),\n include: z\n .string()\n .optional()\n .describe(\n 'Glob pattern to filter files (e.g. \"**/*.ts\"). Defaults to \"**/*\"'\n ),\n fixedString: z\n .boolean()\n .optional()\n .describe(\"If true, treat query as a literal string instead of regex\"),\n caseSensitive: z\n .boolean()\n .optional()\n .describe(\"If true, search is case-sensitive (default: false)\"),\n contextLines: z\n .number()\n .int()\n .min(0)\n .max(10)\n .optional()\n .describe(\"Number of context lines around each match (default: 0)\")\n }),\n execute: async ({\n query,\n include,\n fixedString,\n caseSensitive,\n contextLines\n }) => {\n const pattern = include ?? \"**/*\";\n const allFiles = await ops.glob(pattern);\n const files = allFiles.filter((f: { type: string }) => f.type === \"file\");\n\n let regex: RegExp;\n try {\n const escaped = fixedString ? escapeRegex(query) : query;\n regex = new RegExp(escaped, caseSensitive ? \"g\" : \"gi\");\n } catch {\n return { error: `Invalid regex: ${query}` };\n }\n\n const ctx = contextLines ?? 0;\n const matches: Array<{\n file: string;\n line: number;\n text: string;\n context?: string[];\n }> = [];\n let totalMatches = 0;\n let filesSearched = 0;\n let filesWithMatches = 0;\n\n let filesSkipped = 0;\n\n for (const file of files) {\n if (totalMatches >= MAX_MATCHES) break;\n\n // Skip files larger than 1 MB to avoid memory blowup\n if (file.size > MAX_FILE_SIZE) {\n filesSkipped++;\n continue;\n }\n\n const content = await ops.readFile(file.path);\n if (content === null) continue;\n filesSearched++;\n\n const lines = content.split(\"\\n\");\n let fileHasMatch = false;\n\n for (let i = 0; i < lines.length; i++) {\n if (totalMatches >= MAX_MATCHES) break;\n\n regex.lastIndex = 0;\n if (regex.test(lines[i])) {\n if (!fileHasMatch) {\n fileHasMatch = true;\n filesWithMatches++;\n }\n totalMatches++;\n\n const match: {\n file: string;\n line: number;\n text: string;\n context?: string[];\n } = {\n file: file.path,\n line: i + 1,\n text: lines[i]\n };\n\n if (ctx > 0) {\n const start = Math.max(0, i - ctx);\n const end = Math.min(lines.length, i + ctx + 1);\n match.context = lines.slice(start, end).map((l, j) => {\n const lineNum = start + j + 1;\n const marker = lineNum === i + 1 ? \">\" : \" \";\n return `${marker} ${lineNum}\\t${l}`;\n });\n }\n\n matches.push(match);\n }\n }\n }\n\n const result: Record<string, unknown> = {\n query,\n filesSearched,\n filesWithMatches,\n totalMatches,\n matches: matches.map((m) => {\n if (m.context) {\n return {\n file: m.file,\n line: m.line,\n context: m.context.join(\"\\n\")\n };\n }\n return `${m.file}:${m.line}: ${m.text}`;\n })\n };\n\n if (totalMatches >= MAX_MATCHES) {\n result.truncated = true;\n }\n if (filesSkipped > 0) {\n result.filesSkipped = filesSkipped;\n result.note = `${filesSkipped} file(s) skipped (larger than 1 MB)`;\n }\n\n return result;\n }\n });\n}\n\nfunction escapeRegex(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n// ── Delete ──────────────────────────────────────────────────────────\n\nexport interface DeleteToolOptions {\n ops: DeleteOperations;\n}\n\nexport function createDeleteTool(options: DeleteToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"Delete a file or directory. \" +\n \"Set recursive to true to remove non-empty directories.\",\n inputSchema: z.object({\n path: z.string().describe(\"Absolute path to the file or directory\"),\n recursive: z\n .boolean()\n .optional()\n .describe(\"If true, remove directories and their contents recursively\")\n }),\n execute: async ({ path, recursive }) => {\n await ops.rm(path, { recursive, force: true });\n return { deleted: path };\n }\n });\n}\n"],"mappings":";;;AAgDA,SAAS,iBAAiB,IAA+B;AACvD,QAAO;EACL,WAAW,SAAS,GAAG,SAAS,KAAK;EACrC,OAAO,SAAS,GAAG,KAAK,KAAK;EAC9B;;AAGH,SAAS,kBAAkB,IAAgC;AACzD,QAAO;EACL,YAAY,MAAM,YAAY,GAAG,UAAU,MAAM,QAAQ;EACzD,QAAQ,MAAM,SAAS,GAAG,MAAM,MAAM,KAAK;EAC5C;;AAGH,SAAS,iBAAiB,IAA+B;AACvD,QAAO;EACL,WAAW,SAAS,GAAG,SAAS,KAAK;EACrC,YAAY,MAAM,YAAY,GAAG,UAAU,MAAM,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