@cloudflare/think 0.20.1 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetch-9f1p8UrI.js","names":[],"sources":["../src/workspace-files.ts","../src/tools/fetch.ts"],"sourcesContent":["import type { Workspace } from \"@cloudflare/computer\";\nimport type { CreateAIToolsOptions } from \"@cloudflare/computer/tools/ai-sdk\";\n\n/**\n * The filesystem methods Think uses, from `@cloudflare/computer`'s\n * `workspace.fs`.\n */\nexport type ThinkWorkspaceFilesystem = Pick<\n Workspace[\"fs\"],\n | \"readFile\"\n | \"writeFile\"\n | \"mkdir\"\n | \"rm\"\n | \"stat\"\n | \"readdir\"\n | \"find\"\n | \"grep\"\n>;\n\n/** The parts of a Workspace the `@cloudflare/computer` tools use besides `fs`. */\ntype ToolsWorkspace = CreateAIToolsOptions[\"workspace\"];\n\n/**\n * The Workspace a Think agent works in.\n *\n * A `Workspace` from `@cloudflare/computer` satisfies this, and so does the\n * client `getWorkspace(stub)` returns for a Workspace owned by another\n * Durable Object. Think reads and writes through `workspace.fs`. The\n * `@cloudflare/computer` tools also use `runtime` for `exec` and `assets`\n * for `publish` when the Workspace has them.\n *\n * @experimental The API surface may change before stabilizing.\n */\nexport type ThinkWorkspace = {\n /** The Workspace filesystem. */\n readonly fs: ThinkWorkspaceFilesystem;\n} & Partial<Pick<ToolsWorkspace, \"runtime\" | \"sessionId\" | \"assets\">>;\n\n/** One file, directory, or symlink in a Workspace. */\nexport type WorkspaceEntry = {\n /** Absolute path. */\n readonly path: string;\n /** Last path segment. */\n readonly name: string;\n /** Entry kind. */\n readonly type: \"file\" | \"directory\" | \"symlink\";\n /** Size in bytes. `0` for directories. */\n readonly size: number;\n /** Last modification time in milliseconds since the epoch. */\n readonly updatedAt: number;\n};\n\n/** Directory Computer's backends and tools treat as the working root. */\nexport const WORKSPACE_ROOT = \"/workspace\";\n\n/**\n * Resolve a path against {@link WORKSPACE_ROOT}. Absolute paths pass\n * through; relative ones, such as an extension's `notes/today.md`, land\n * under `/workspace`.\n *\n * @param path - Absolute or root-relative path.\n * @returns An absolute path.\n */\nexport function resolveWorkspacePath(path: string): string {\n if (path.startsWith(\"/\")) return path;\n const relative = path.replace(/^\\.\\//, \"\");\n return relative === \"\" || relative === \".\"\n ? WORKSPACE_ROOT\n : `${WORKSPACE_ROOT}/${relative}`;\n}\n\nconst TEXT_ENCODER = new TextEncoder();\nconst TEXT_DECODER = new TextDecoder();\n\n/**\n * Think's file operations over a {@link ThinkWorkspace}.\n *\n * Translates the Workspace's node-style filesystem into the shape Think's\n * internals use: missing files read as `null` instead of rejecting with\n * `ENOENT`, writes create their parent directories, and listings return\n * {@link WorkspaceEntry} values.\n *\n * @internal\n */\nexport class WorkspaceFiles {\n readonly #fs: ThinkWorkspaceFilesystem;\n\n /**\n * @param workspace - The Workspace to operate on.\n */\n constructor(workspace: ThinkWorkspace) {\n this.#fs = workspace.fs;\n }\n\n /**\n * Read a file as UTF-8 text.\n *\n * @param path - Absolute file path.\n * @returns The text, or `null` when the file does not exist.\n */\n async readText(path: string): Promise<string | null> {\n const bytes = await this.readBytes(path);\n return bytes === null ? null : TEXT_DECODER.decode(bytes);\n }\n\n /**\n * Read a file's bytes.\n *\n * @param path - Absolute file path.\n * @returns The bytes, or `null` when the file does not exist.\n */\n async readBytes(path: string): Promise<Uint8Array | null> {\n try {\n return await drain(await this.#fs.readFile(path));\n } catch (error) {\n if (isNotFound(error)) return null;\n throw error;\n }\n }\n\n /**\n * Write a file, creating missing parent directories.\n *\n * @param path - Absolute file path.\n * @param content - Text, written as UTF-8, or bytes.\n */\n async write(path: string, content: string | Uint8Array): Promise<void> {\n const parent = parentDirectory(path);\n if (parent !== \"/\") await this.#fs.mkdir(parent, { recursive: true });\n await this.#fs.writeFile(\n path,\n typeof content === \"string\" ? TEXT_ENCODER.encode(content) : content\n );\n }\n\n /**\n * Remove a file or directory.\n *\n * @param path - Absolute path.\n * @param options - `recursive` removes a non-empty directory; `force`\n * accepts a missing path.\n */\n async remove(\n path: string,\n options?: { recursive?: boolean; force?: boolean }\n ): Promise<void> {\n await this.#fs.rm(path, options);\n }\n\n /**\n * List a directory's entries in name order.\n *\n * @param path - Absolute directory path.\n * @param options - Page size and start.\n * @returns The entries on the requested page.\n */\n async list(\n path: string,\n options?: { limit?: number; offset?: number }\n ): Promise<WorkspaceEntry[]> {\n const entries = await this.#fs.readdir(path, options);\n return entries.map((entry) => ({\n path: joinPath(path, entry.name),\n name: entry.name,\n type: entry.isDirectory\n ? \"directory\"\n : entry.isSymbolicLink\n ? \"symlink\"\n : \"file\",\n size: entry.size,\n updatedAt: entry.mtime\n }));\n }\n}\n\nasync function drain(stream: ReadableStream<Uint8Array>): Promise<Uint8Array> {\n const parts: Uint8Array[] = [];\n let total = 0;\n for await (const part of stream) {\n parts.push(part);\n total += part.byteLength;\n }\n if (parts.length === 1 && parts[0]) return parts[0];\n const bytes = new Uint8Array(total);\n let offset = 0;\n for (const part of parts) {\n bytes.set(part, offset);\n offset += part.byteLength;\n }\n return bytes;\n}\n\nfunction isNotFound(error: unknown): boolean {\n return (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n error.code === \"ENOENT\"\n );\n}\n\nfunction parentDirectory(path: string): string {\n const index = path.lastIndexOf(\"/\");\n return index <= 0 ? \"/\" : path.slice(0, index);\n}\n\nfunction joinPath(directory: string, name: string): string {\n return directory.endsWith(\"/\")\n ? `${directory}${name}`\n : `${directory}/${name}`;\n}\n\n/**\n * A {@link ThinkWorkspace} that resolves the real Workspace on first use.\n *\n * Use it for a Workspace another Durable Object owns, so the agent does not\n * reach the owner until a turn actually touches a file:\n *\n * ```ts\n * import { getWorkspace } from \"@cloudflare/computer\";\n *\n * override workspace = lazyWorkspace(async () =>\n * getWorkspace(await this.parentAgent(Directory))\n * );\n * ```\n *\n * The resolved Workspace is kept and reused. A failed resolution is not\n * kept, so the next operation tries again. To start over with a new client,\n * for example after disposing the old one, assign a new `lazyWorkspace`.\n *\n * Only `fs` is forwarded, so the agent gets the file tools but no `exec`:\n * the exec tool lists the Workspace's backends synchronously, before\n * anything has been resolved.\n *\n * @param resolve - Produces the Workspace.\n * @returns A Workspace whose `fs` forwards to the resolved one.\n */\nexport function lazyWorkspace(\n resolve: () => Promise<ThinkWorkspace>\n): ThinkWorkspace {\n let resolved: Promise<ThinkWorkspace> | undefined;\n const fs = async (): Promise<ThinkWorkspaceFilesystem> => {\n resolved ??= resolve().catch((error: unknown) => {\n resolved = undefined;\n throw error;\n });\n return (await resolved).fs;\n };\n type Fs = ThinkWorkspaceFilesystem;\n const forwarding = {\n readFile: async (...args: Parameters<Fs[\"readFile\"]>) =>\n (await fs()).readFile(...args),\n writeFile: async (...args: Parameters<Fs[\"writeFile\"]>) =>\n (await fs()).writeFile(...args),\n mkdir: async (...args: Parameters<Fs[\"mkdir\"]>) =>\n (await fs()).mkdir(...args),\n rm: async (...args: Parameters<Fs[\"rm\"]>) => (await fs()).rm(...args),\n stat: async (...args: Parameters<Fs[\"stat\"]>) => (await fs()).stat(...args),\n readdir: async (...args: Parameters<Fs[\"readdir\"]>) =>\n (await fs()).readdir(...args),\n find: async (...args: Parameters<Fs[\"find\"]>) => (await fs()).find(...args),\n grep: async (...args: Parameters<Fs[\"grep\"]>) => (await fs()).grep(...args)\n };\n // SAFETY: Every method forwards its arguments unchanged to the same method\n // on the resolved filesystem, so each `readFile` overload returns what the\n // resolved overload returns. TypeScript cannot carry overloads through a\n // forwarding wrapper.\n return { fs: forwarding as unknown as Fs };\n}\n","import type { JSONValue, ToolSet } from \"ai\";\nimport { tool } from \"ai\";\nimport { isPrivateOrLocalHost } from \"agents/webfetch\";\nimport { z } from \"zod\";\nimport { WorkspaceFiles, type ThinkWorkspace } from \"../workspace-files\";\n\n// ── Public types ──────────────────────────────────────────────────\n//\n// A conservative, opt-in HTTP read capability for Think agents. It is\n// deliberately read-only (GET), allowlisted, and bounded. It is NOT a\n// general-purpose HTTP client and NOT an SSRF primitive — mutations and\n// rendered-page automation live elsewhere (explicit actions, Browser Run).\n//\n// @experimental The API surface may change before stabilizing.\n\nexport type FetchResponseMode = \"text\" | \"json\" | \"auto\" | \"workspace\";\nexport type FetchRedirectPolicy = \"allowlisted\" | \"same-origin\" | \"none\";\n\nexport type FetchErrorCode =\n | \"disallowed_url\"\n | \"disallowed_redirect\"\n | \"timeout\"\n | \"aborted\"\n | \"non_2xx\"\n | \"unsupported_content_type\"\n | \"invalid_json\"\n | \"too_large\"\n | \"request_failed\";\n\nexport type FetchResult =\n | {\n ok: true;\n status: number;\n finalUrl: string;\n contentType: string;\n bytes: number;\n truncated: boolean;\n response: \"text\" | \"json\" | \"workspace\";\n body?: string;\n json?: JSONValue;\n path?: string;\n }\n | {\n ok: false;\n code: FetchErrorCode;\n status?: number;\n finalUrl?: string;\n message: string;\n };\n\nexport interface FetchToolEvent {\n tool: string;\n ok: boolean;\n requestedUrl: string;\n finalUrl?: string;\n status?: number;\n bytes?: number;\n truncated?: boolean;\n response?: FetchResponseMode;\n code?: FetchErrorCode;\n}\n\nexport interface FetchBindingTarget {\n /** The service binding / Fetcher requests are routed through. */\n binding: Fetcher;\n /** Documented purpose — surfaced in the generated tool description. */\n description?: string;\n /**\n * Allowlist for this target. Entries starting with `/` match the request\n * pathname (e.g. `/v1/docs/**`); entries starting with `http(s)://` match\n * the full canonical URL.\n */\n allowlist: string[];\n /** Fixed, server-side headers. Never settable by the model, never echoed. */\n headers?: Record<string, string>;\n /** Base URL used to resolve relative paths. Defaults to `https://binding.local`. */\n baseUrl?: string;\n}\n\nexport interface CreateFetchToolsOptions {\n /**\n * Allowlist for the generic public `fetch_url` tool. Entries are absolute\n * URL/origin/path globs (e.g. `https://developers.cloudflare.com/**`). When\n * omitted/empty, `fetch_url` is not registered.\n */\n allowlist?: string[];\n /**\n * Named binding targets. Each entry generates a `fetch_<name>` tool with the\n * binding, allowlist, and fixed headers baked in.\n */\n bindings?: Record<string, FetchBindingTarget>;\n /** Hard download cap in bytes. Default 1_000_000. */\n maxBytes?: number;\n /** Model-facing text truncation in characters. Default 24_000. */\n maxModelChars?: number;\n /** Allow large/binary bodies to spill to a workspace file. Default false. */\n spillToWorkspace?: boolean;\n /** Workspace used for `response: \"workspace\"` / spill. */\n workspace?: ThinkWorkspace;\n /** Per-request timeout in ms. Default 10_000. */\n timeoutMs?: number;\n /** Default response handling. Default `\"auto\"`. */\n response?: FetchResponseMode;\n /** Redirect policy. Default `\"allowlisted\"`. */\n followRedirects?: FetchRedirectPolicy;\n /** Header names the model may set. Default `[\"accept\", \"accept-language\", \"range\"]`. */\n modelHeaderAllowlist?: string[];\n /**\n * Default `Accept` header sent when neither the binding's fixed headers nor\n * the model already set one. Defaults to a markdown-first, weighted value so\n * content-negotiating endpoints return clean markdown/plain text/JSON instead\n * of HTML. Set to `\"\"` to send no default `Accept` header.\n */\n defaultAccept?: string;\n /** Observability hook. Fires once per fetch (success or failure/block). */\n onEvent?: (event: FetchToolEvent) => void;\n}\n\nconst DEFAULT_MAX_BYTES = 1_000_000;\nconst DEFAULT_MAX_MODEL_CHARS = 24_000;\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst DEFAULT_MODEL_HEADER_ALLOWLIST = [\"accept\", \"accept-language\", \"range\"];\n// Markdown-first, but still accepts everything (`*/*;q=0.1`) so a strict\n// content-negotiating server never answers 406.\nconst DEFAULT_ACCEPT =\n \"text/markdown, text/plain;q=0.9, application/json;q=0.8, text/html;q=0.5, */*;q=0.1\";\nconst MAX_REDIRECTS = 5;\n\ninterface ResolvedConfig {\n maxBytes: number;\n maxModelChars: number;\n spillToWorkspace: boolean;\n workspace?: ThinkWorkspace;\n timeoutMs: number;\n response: FetchResponseMode;\n followRedirects: FetchRedirectPolicy;\n modelHeaderAllowlist: Set<string>;\n defaultAccept: string;\n onEvent?: (event: FetchToolEvent) => void;\n}\n\ninterface CompiledPattern {\n scope: \"path\" | \"url\";\n re: RegExp;\n}\n\ninterface ResolvedTarget {\n kind: \"public\" | \"binding\";\n binding?: Fetcher;\n allowlist: CompiledPattern[];\n fixedHeaders: Record<string, string>;\n baseUrl: string;\n}\n\n/**\n * Create the Think fetch tools.\n *\n * Returns a generic `fetch_url` tool (when a public `allowlist` is configured)\n * plus one `fetch_<name>` tool per configured binding target. Throws when no\n * allowlist and no bindings are configured, so a misconfiguration fails loudly\n * instead of silently registering nothing.\n *\n * @example\n * ```ts\n * createFetchTools({\n * allowlist: [\"https://developers.cloudflare.com/**\"],\n * bindings: {\n * docsApi: { binding: env.DOCS_API, allowlist: [\"/v1/docs/**\"] }\n * }\n * });\n * ```\n */\nexport function createFetchTools(options: CreateFetchToolsOptions): ToolSet {\n const publicAllowlist = (options.allowlist ?? []).filter(\n (entry) => entry.length > 0\n );\n const bindings = options.bindings ?? {};\n const bindingNames = Object.keys(bindings);\n\n if (publicAllowlist.length === 0 && bindingNames.length === 0) {\n throw new Error(\n \"createFetchTools requires a non-empty `allowlist` or at least one `bindings` target.\"\n );\n }\n\n const config: ResolvedConfig = {\n maxBytes: options.maxBytes ?? DEFAULT_MAX_BYTES,\n maxModelChars: options.maxModelChars ?? DEFAULT_MAX_MODEL_CHARS,\n spillToWorkspace: options.spillToWorkspace ?? false,\n workspace: options.workspace,\n timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n response: options.response ?? \"auto\",\n followRedirects: options.followRedirects ?? \"allowlisted\",\n modelHeaderAllowlist: new Set(\n (options.modelHeaderAllowlist ?? DEFAULT_MODEL_HEADER_ALLOWLIST).map(\n (name) => name.toLowerCase()\n )\n ),\n defaultAccept: options.defaultAccept ?? DEFAULT_ACCEPT,\n onEvent: options.onEvent\n };\n\n const tools: ToolSet = {};\n\n if (publicAllowlist.length > 0) {\n const target: ResolvedTarget = {\n kind: \"public\",\n allowlist: publicAllowlist.map(compilePattern),\n fixedHeaders: {},\n baseUrl: \"\"\n };\n tools.fetch_url = tool({\n description:\n \"Fetch an allowlisted public URL over HTTP(S) (read-only GET). \" +\n \"Returns the response body as text or JSON, or spills large/binary \" +\n \"bodies to a workspace file. The URL must be on the configured \" +\n \"allowlist; disallowed or private-network URLs are rejected.\",\n inputSchema: z.object({\n url: z\n .string()\n .describe(\"Absolute http(s) URL to fetch. Must be allowlisted.\"),\n response: responseModeSchema,\n headers: headersSchema\n }),\n execute: (input: FetchUrlInput, opts) =>\n runFetch({\n toolName: \"fetch_url\",\n target,\n config,\n requested: input.url,\n responseOverride: input.response,\n modelHeaders: input.headers,\n abortSignal: opts?.abortSignal\n }),\n toModelOutput: ({ output }) => toModelOutput(output as FetchResult)\n });\n }\n\n for (const name of bindingNames) {\n const def = bindings[name];\n const toolName = `fetch_${sanitizeName(name)}`;\n const target: ResolvedTarget = {\n kind: \"binding\",\n binding: def.binding,\n allowlist: def.allowlist.map(compilePattern),\n fixedHeaders: def.headers ?? {},\n baseUrl: def.baseUrl ?? \"https://binding.local\"\n };\n const purpose = def.description ? ` ${def.description}` : \"\";\n tools[toolName] = tool({\n description:\n `Fetch a read-only resource from the \"${name}\" service binding.${purpose} ` +\n \"Provide a path (or an allowlisted absolute URL). Requests are routed \" +\n \"through the configured binding with fixed server-side headers.\",\n inputSchema: z.object({\n path: z\n .string()\n .describe(\n \"Path (e.g. /v1/docs/search) or an allowlisted absolute URL.\"\n ),\n response: responseModeSchema,\n headers: headersSchema\n }),\n execute: (input: FetchBindingInput, opts) =>\n runFetch({\n toolName,\n target,\n config,\n requested: input.path,\n responseOverride: input.response,\n modelHeaders: input.headers,\n abortSignal: opts?.abortSignal\n }),\n toModelOutput: ({ output }) => toModelOutput(output as FetchResult)\n });\n }\n\n return tools;\n}\n\nconst responseModeSchema = z\n .enum([\"text\", \"json\", \"auto\", \"workspace\"])\n .optional()\n .describe(\n \"How to handle the response body. Defaults to the configured mode.\"\n );\n\nconst headersSchema = z\n .record(z.string(), z.string())\n .optional()\n .describe(\"Optional request headers; only safe read headers are honored.\");\n\ninterface FetchUrlInput {\n url: string;\n response?: FetchResponseMode;\n headers?: Record<string, string>;\n}\n\ninterface FetchBindingInput {\n path: string;\n response?: FetchResponseMode;\n headers?: Record<string, string>;\n}\n\ninterface RunFetchArgs {\n toolName: string;\n target: ResolvedTarget;\n config: ResolvedConfig;\n requested: string;\n responseOverride?: FetchResponseMode;\n modelHeaders?: Record<string, string>;\n abortSignal?: AbortSignal;\n}\n\nasync function runFetch(args: RunFetchArgs): Promise<FetchResult> {\n const { toolName, config, requested } = args;\n const result = await runFetchInner(args);\n if (config.onEvent) {\n try {\n config.onEvent(\n result.ok\n ? {\n tool: toolName,\n ok: true,\n requestedUrl: requested,\n finalUrl: result.finalUrl,\n status: result.status,\n bytes: result.bytes,\n truncated: result.truncated,\n response: result.response\n }\n : {\n tool: toolName,\n ok: false,\n requestedUrl: requested,\n finalUrl: result.finalUrl,\n status: result.status,\n code: result.code\n }\n );\n } catch {\n // Observability must never break a tool call.\n }\n }\n return result;\n}\n\nasync function runFetchInner(args: RunFetchArgs): Promise<FetchResult> {\n const { target, config, requested, responseOverride, modelHeaders } = args;\n\n // Resolve the requested string into an absolute URL.\n const rawUrl =\n target.kind === \"binding\" && !/^https?:\\/\\//i.test(requested)\n ? resolveAgainstBase(requested, target.baseUrl)\n : requested;\n if (rawUrl === null) {\n return { ok: false, code: \"disallowed_url\", message: \"Invalid path.\" };\n }\n\n const normalized = normalizeRequestUrl(rawUrl);\n if (\"error\" in normalized) {\n return { ok: false, code: \"disallowed_url\", message: normalized.error };\n }\n const url = normalized.url;\n\n if (target.kind === \"public\" && isPrivateOrLocalHost(url.hostname)) {\n return {\n ok: false,\n code: \"disallowed_url\",\n message: `Refusing to fetch a private or local address: ${url.hostname}`\n };\n }\n\n if (!matchesAllowlist(url, target.allowlist)) {\n return {\n ok: false,\n code: \"disallowed_url\",\n message: `URL is not on the allowlist: ${url.toString()}`\n };\n }\n\n const responseMode = responseOverride ?? config.response;\n const safeModelHeaders = filterModelHeaders(\n modelHeaders,\n config.modelHeaderAllowlist\n );\n\n return executeRequest({\n target,\n config,\n initialUrl: url,\n responseMode,\n fixedHeaders: target.fixedHeaders,\n modelHeaders: safeModelHeaders,\n abortSignal: args.abortSignal\n });\n}\n\ninterface ExecuteRequestArgs {\n target: ResolvedTarget;\n config: ResolvedConfig;\n initialUrl: URL;\n responseMode: FetchResponseMode;\n fixedHeaders: Record<string, string>;\n modelHeaders: Record<string, string>;\n abortSignal?: AbortSignal;\n}\n\nasync function executeRequest(args: ExecuteRequestArgs): Promise<FetchResult> {\n const { target, config, initialUrl, responseMode } = args;\n const method = \"GET\";\n\n const controller = new AbortController();\n const onAbort = () => controller.abort();\n if (args.abortSignal) {\n if (args.abortSignal.aborted) controller.abort();\n else args.abortSignal.addEventListener(\"abort\", onAbort, { once: true });\n }\n const timer = setTimeout(() => controller.abort(), config.timeoutMs);\n\n const initialOrigin = initialUrl.origin;\n let currentUrl = initialUrl;\n let headers: Record<string, string> = applyDefaultAccept(\n mergeHeaders(args.fixedHeaders, args.modelHeaders),\n config.defaultAccept\n );\n\n try {\n for (let hop = 0; ; hop++) {\n if (hop > MAX_REDIRECTS) {\n return {\n ok: false,\n code: \"request_failed\",\n finalUrl: currentUrl.toString(),\n message: \"Too many redirects.\"\n };\n }\n\n const res = await doFetch(\n target,\n currentUrl,\n method,\n headers,\n controller.signal\n );\n\n if (isRedirect(res.status)) {\n const location = res.headers.get(\"location\");\n if (location) {\n const redirectOutcome = resolveRedirect({\n target,\n config,\n location,\n currentUrl,\n initialOrigin\n });\n if (\"error\" in redirectOutcome) {\n discardBody(res);\n return {\n ok: false,\n code: \"disallowed_redirect\",\n status: res.status,\n finalUrl: currentUrl.toString(),\n message: redirectOutcome.error\n };\n }\n // We're following the redirect; drop the 3xx body before the next hop.\n discardBody(res);\n // Strip credentials/headers on cross-origin hops, but keep a safe\n // default Accept so the next hop still negotiates for clean content.\n if (redirectOutcome.url.origin !== currentUrl.origin) {\n headers = applyDefaultAccept({}, config.defaultAccept);\n }\n currentUrl = redirectOutcome.url;\n continue;\n }\n }\n\n if (res.status < 200 || res.status >= 300) {\n discardBody(res);\n return {\n ok: false,\n code: \"non_2xx\",\n status: res.status,\n finalUrl: currentUrl.toString(),\n message: `HTTP ${res.status}`\n };\n }\n\n return finalizeResponse({\n res,\n config,\n responseMode,\n finalUrl: currentUrl.toString()\n });\n }\n } catch (error) {\n if (controller.signal.aborted) {\n const aborted = args.abortSignal?.aborted ?? false;\n return {\n ok: false,\n code: aborted ? \"aborted\" : \"timeout\",\n finalUrl: currentUrl.toString(),\n message: aborted ? \"Request aborted.\" : \"Request timed out.\"\n };\n }\n return {\n ok: false,\n code: \"request_failed\",\n finalUrl: currentUrl.toString(),\n message: errorMessage(error)\n };\n } finally {\n clearTimeout(timer);\n args.abortSignal?.removeEventListener(\"abort\", onAbort);\n }\n}\n\n/**\n * Cancel a response body we won't read (non-2xx, blocked/followed redirects)\n * so the underlying connection isn't left dangling.\n */\nfunction discardBody(res: Response): void {\n res.body?.cancel().catch(() => {});\n}\n\nfunction doFetch(\n target: ResolvedTarget,\n url: URL,\n method: string,\n headers: Record<string, string>,\n signal: AbortSignal\n): Promise<Response> {\n const init: RequestInit = {\n method,\n headers,\n redirect: \"manual\",\n signal\n };\n if (target.kind === \"binding\" && target.binding) {\n return target.binding.fetch(url.toString(), init);\n }\n return fetch(url.toString(), init);\n}\n\ninterface ResolveRedirectArgs {\n target: ResolvedTarget;\n config: ResolvedConfig;\n location: string;\n currentUrl: URL;\n initialOrigin: string;\n}\n\nfunction resolveRedirect(\n args: ResolveRedirectArgs\n): { url: URL } | { error: string } {\n const { target, config, location, currentUrl, initialOrigin } = args;\n if (config.followRedirects === \"none\") {\n return { error: \"Redirects are disabled.\" };\n }\n\n let next: URL;\n try {\n next = new URL(location, currentUrl);\n } catch {\n return { error: \"Invalid redirect target.\" };\n }\n if (next.protocol !== \"http:\" && next.protocol !== \"https:\") {\n return { error: \"Redirect to a non-http(s) URL is not allowed.\" };\n }\n if (next.username || next.password) {\n return { error: \"Redirect to a URL with credentials is not allowed.\" };\n }\n\n // Bindings are a transport, not a generic client: never redirect off-origin.\n if (target.kind === \"binding\" && next.origin !== currentUrl.origin) {\n return { error: \"Cross-origin redirects are not allowed for bindings.\" };\n }\n\n if (target.kind === \"public\" && isPrivateOrLocalHost(next.hostname)) {\n return {\n error: `Redirect to a private or local address: ${next.hostname}`\n };\n }\n\n if (config.followRedirects === \"same-origin\") {\n if (next.origin !== initialOrigin) {\n return { error: \"Redirect escaped the original origin.\" };\n }\n } else if (config.followRedirects === \"allowlisted\") {\n if (!matchesAllowlist(next, target.allowlist)) {\n return { error: \"Redirect target is not on the allowlist.\" };\n }\n }\n\n return { url: next };\n}\n\ninterface FinalizeArgs {\n res: Response;\n config: ResolvedConfig;\n responseMode: FetchResponseMode;\n finalUrl: string;\n}\n\nasync function finalizeResponse(args: FinalizeArgs): Promise<FetchResult> {\n const { res, config, responseMode, finalUrl } = args;\n const contentType = (res.headers.get(\"content-type\") ?? \"\")\n .split(\";\")[0]\n .trim()\n .toLowerCase();\n\n const { bytes, capped } = await readCapped(res, config.maxBytes);\n const mode = resolveResponseMode(responseMode, contentType, config);\n\n // An empty body (204, HEAD-like, or a content-less 2xx) is a successful\n // empty-text read, not an unsupported content type.\n if (bytes.byteLength === 0 && mode !== \"workspace\") {\n return {\n ok: true,\n status: res.status,\n finalUrl,\n contentType,\n bytes: 0,\n truncated: false,\n response: \"text\",\n body: \"\"\n };\n }\n\n if (mode === \"unsupported\") {\n return {\n ok: false,\n code: \"unsupported_content_type\",\n finalUrl,\n message: `Unsupported content type: ${contentType || \"unknown\"}. Use response: \"workspace\" to store it.`\n };\n }\n\n if (mode === \"workspace\") {\n return spillToWorkspace({\n bytes,\n capped,\n contentType,\n finalUrl,\n status: res.status,\n config\n });\n }\n\n const text = new TextDecoder().decode(bytes);\n\n if (mode === \"json\") {\n if (capped) {\n return {\n ok: false,\n code: \"too_large\",\n finalUrl,\n message: `Response exceeded the ${config.maxBytes} byte cap and cannot be parsed as JSON. Use response: \"workspace\".`\n };\n }\n try {\n const json = JSON.parse(text) as JSONValue;\n return {\n ok: true,\n status: res.status,\n finalUrl,\n contentType,\n bytes: bytes.byteLength,\n truncated: false,\n response: \"json\",\n json\n };\n } catch {\n return {\n ok: false,\n code: \"invalid_json\",\n finalUrl,\n message: \"Response body is not valid JSON.\"\n };\n }\n }\n\n const { value, truncated: textTruncated } = truncateText(\n text,\n config.maxModelChars\n );\n return {\n ok: true,\n status: res.status,\n finalUrl,\n contentType,\n bytes: bytes.byteLength,\n truncated: capped || textTruncated,\n response: \"text\",\n body: value\n };\n}\n\ninterface SpillArgs {\n bytes: Uint8Array;\n capped: boolean;\n contentType: string;\n finalUrl: string;\n status: number;\n config: ResolvedConfig;\n}\n\nasync function spillToWorkspace(args: SpillArgs): Promise<FetchResult> {\n const { bytes, capped, contentType, finalUrl, status, config } = args;\n const ws = config.workspace;\n if (!ws) {\n return {\n ok: false,\n code: \"unsupported_content_type\",\n finalUrl,\n message:\n 'response: \"workspace\" requires a workspace, but none is configured.'\n };\n }\n\n const path = `/workspace/fetched/${Date.now()}-${randomToken()}.${extensionFor(contentType)}`;\n try {\n await new WorkspaceFiles(ws).write(path, bytes);\n } catch (error) {\n return {\n ok: false,\n code: \"request_failed\",\n finalUrl,\n message: `Failed to write workspace file: ${errorMessage(error)}`\n };\n }\n\n return {\n ok: true,\n status,\n finalUrl,\n contentType,\n bytes: bytes.byteLength,\n truncated: capped,\n response: \"workspace\",\n path\n };\n}\n\nasync function readCapped(\n res: Response,\n maxBytes: number\n): Promise<{ bytes: Uint8Array; capped: boolean }> {\n const body = res.body;\n if (!body) return { bytes: new Uint8Array(0), capped: false };\n\n const reader = body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n let capped = false;\n\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n if (!value) continue;\n if (total + value.byteLength > maxBytes) {\n const remaining = Math.max(0, maxBytes - total);\n if (remaining > 0) chunks.push(value.slice(0, remaining));\n total += remaining;\n capped = true;\n await reader.cancel().catch(() => {});\n break;\n }\n chunks.push(value);\n total += value.byteLength;\n }\n\n const out = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n out.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return { bytes: out, capped };\n}\n\ntype ResolvedResponseMode = \"text\" | \"json\" | \"workspace\" | \"unsupported\";\n\nfunction resolveResponseMode(\n mode: FetchResponseMode,\n contentType: string,\n config: ResolvedConfig\n): ResolvedResponseMode {\n if (mode === \"text\") return \"text\";\n if (mode === \"json\") return \"json\";\n if (mode === \"workspace\") return \"workspace\";\n\n // auto\n if (isJsonContentType(contentType)) return \"json\";\n if (isTextualContentType(contentType)) return \"text\";\n if (config.spillToWorkspace && config.workspace) return \"workspace\";\n return \"unsupported\";\n}\n\n// ── Allowlist + URL helpers ───────────────────────────────────────\n\nfunction normalizeRequestUrl(raw: string): { url: URL } | { error: string } {\n let url: URL;\n try {\n url = new URL(raw);\n } catch {\n return { error: \"Invalid URL.\" };\n }\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") {\n return { error: \"Only http(s) URLs are allowed.\" };\n }\n if (url.username || url.password) {\n return { error: \"URLs with embedded credentials are not allowed.\" };\n }\n return { url };\n}\n\nfunction resolveAgainstBase(pathOrUrl: string, baseUrl: string): string | null {\n try {\n return new URL(pathOrUrl, baseUrl).toString();\n } catch {\n return null;\n }\n}\n\n/**\n * A bare origin (`https://example.com`, no path) is treated as the origin and\n * everything under it, since the canonical URL always has at least a `/` path.\n * Patterns with an explicit path are matched literally unless they include\n * globs.\n */\nfunction normalizeAllowlistPattern(pattern: string): string {\n if (/^https?:\\/\\/[^/]+$/i.test(pattern)) return `${pattern}/**`;\n return pattern;\n}\n\n/**\n * Compile an allowlist pattern once at config time so we don't rebuild a\n * `RegExp` on every request. Path-only patterns (`/v1/**`) match against the\n * URL pathname; everything else matches against the canonical origin+path.\n */\nfunction compilePattern(pattern: string): CompiledPattern {\n const normalized = normalizeAllowlistPattern(pattern);\n return {\n scope: normalized.startsWith(\"/\") ? \"path\" : \"url\",\n re: globToRegExp(normalized)\n };\n}\n\nfunction canonicalForMatch(url: URL): string {\n const host = url.hostname.replace(/\\.$/, \"\");\n const port = url.port ? `:${url.port}` : \"\";\n return `${url.protocol}//${host}${port}${url.pathname}`;\n}\n\nfunction matchesAllowlist(url: URL, patterns: CompiledPattern[]): boolean {\n const canonical = canonicalForMatch(url);\n for (const pattern of patterns) {\n const subject = pattern.scope === \"path\" ? url.pathname : canonical;\n if (pattern.re.test(subject)) return true;\n }\n return false;\n}\n\nfunction globToRegExp(glob: string): RegExp {\n let re = \"\";\n for (let i = 0; i < glob.length; i++) {\n const c = glob[i];\n if (c === \"*\") {\n if (glob[i + 1] === \"*\") {\n re += \".*\";\n i++;\n } else {\n re += \"[^/]*\";\n }\n } else if (\"\\\\^$.|?+()[]{}\".includes(c)) {\n re += `\\\\${c}`;\n } else {\n re += c;\n }\n }\n return new RegExp(`^${re}$`);\n}\n\n/**\n * Merge fixed (server-side) and model headers into a lowercased-key map. Fixed\n * headers win, so the model can never override a binding's configured header,\n * and case-only duplicates (`Accept` vs `accept`) can't both be sent.\n */\nfunction mergeHeaders(\n fixed: Record<string, string>,\n model: Record<string, string>\n): Record<string, string> {\n const out: Record<string, string> = {};\n for (const [name, value] of Object.entries(model)) {\n out[name.toLowerCase()] = value;\n }\n for (const [name, value] of Object.entries(fixed)) {\n out[name.toLowerCase()] = value;\n }\n return out;\n}\n\nfunction applyDefaultAccept(\n headers: Record<string, string>,\n defaultAccept: string\n): Record<string, string> {\n if (!defaultAccept) return headers;\n const hasAccept = Object.keys(headers).some(\n (name) => name.toLowerCase() === \"accept\"\n );\n if (hasAccept) return headers;\n return { ...headers, accept: defaultAccept };\n}\n\nfunction filterModelHeaders(\n headers: Record<string, string> | undefined,\n allowlist: Set<string>\n): Record<string, string> {\n if (!headers) return {};\n const out: Record<string, string> = {};\n for (const [name, value] of Object.entries(headers)) {\n if (allowlist.has(name.toLowerCase())) out[name] = value;\n }\n return out;\n}\n\n// ── Content-type helpers ──────────────────────────────────────────\n\nfunction isJsonContentType(contentType: string): boolean {\n return (\n contentType === \"application/json\" ||\n contentType.endsWith(\"+json\") ||\n contentType === \"text/json\"\n );\n}\n\nfunction isTextualContentType(contentType: string): boolean {\n if (contentType.length === 0) return false;\n if (contentType.startsWith(\"text/\")) return true;\n if (isJsonContentType(contentType)) return true;\n return (\n contentType === \"application/xml\" ||\n contentType === \"application/javascript\" ||\n contentType === \"application/x-www-form-urlencoded\"\n );\n}\n\nfunction extensionFor(contentType: string): string {\n if (isJsonContentType(contentType)) return \"json\";\n if (contentType === \"text/html\") return \"html\";\n if (contentType.includes(\"xml\")) return \"xml\";\n if (contentType.startsWith(\"text/\")) return \"txt\";\n if (contentType === \"application/pdf\") return \"pdf\";\n if (contentType.startsWith(\"image/\")) {\n return contentType.slice(\"image/\".length).split(\"+\")[0] || \"img\";\n }\n return \"bin\";\n}\n\nfunction truncateText(\n value: string,\n maxChars: number\n): { value: string; truncated: boolean } {\n if (value.length <= maxChars) return { value, truncated: false };\n return {\n value: `${value.slice(0, maxChars)}\\n... (truncated ${value.length - maxChars} chars)`,\n truncated: true\n };\n}\n\nfunction isRedirect(status: number): boolean {\n return (\n status === 301 ||\n status === 302 ||\n status === 303 ||\n status === 307 ||\n status === 308\n );\n}\n\nfunction sanitizeName(name: string): string {\n return name.replace(/[^a-zA-Z0-9_]/g, \"_\");\n}\n\nfunction randomToken(): string {\n return Math.random().toString(36).slice(2, 10);\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n// ── Model output mapping ──────────────────────────────────────────\n\nfunction toModelOutput(\n output: FetchResult\n):\n | { type: \"text\"; value: string }\n | { type: \"error-text\"; value: string }\n | { type: \"json\"; value: JSONValue } {\n if (!output.ok) {\n return { type: \"error-text\", value: output.message };\n }\n if (output.response === \"json\") {\n return {\n type: \"json\",\n value: {\n status: output.status,\n finalUrl: output.finalUrl,\n contentType: output.contentType,\n json: output.json ?? null\n }\n };\n }\n if (output.response === \"workspace\") {\n return {\n type: \"text\",\n value:\n `Fetched ${output.finalUrl} (${output.contentType || \"unknown\"}, ` +\n `${output.bytes} bytes${output.truncated ? \", truncated\" : \"\"}) ` +\n `and saved to ${output.path}.`\n };\n }\n const prefix = `Fetched ${output.finalUrl} (HTTP ${output.status}, ${output.contentType || \"unknown\"}${output.truncated ? \", truncated\" : \"\"}):\\n\\n`;\n return { type: \"text\", value: prefix + (output.body ?? \"\") };\n}\n"],"mappings":";;;;;;AAqDA,MAAa,iBAAiB;;;;;;;;;AAU9B,SAAgB,qBAAqB,MAAsB;CACzD,IAAI,KAAK,WAAW,GAAG,GAAG,OAAO;CACjC,MAAM,WAAW,KAAK,QAAQ,SAAS,EAAE;CACzC,OAAO,aAAa,MAAM,aAAa,MACnC,iBACA,GAAG,eAAe,GAAG;AAC3B;AAEA,MAAM,eAAe,IAAI,YAAY;AACrC,MAAM,eAAe,IAAI,YAAY;;;;;;;;;;;;AAYrC,IAAa,iBAAb,MAA4B;;;;CAM1B,YAAY,WAA2B;;EACrC,uBAAA,KAAA,MAAW,UAAU,EAAA;CACvB;;;;;;;CAQA,MAAM,SAAS,MAAsC;EACnD,MAAM,QAAQ,MAAM,KAAK,UAAU,IAAI;EACvC,OAAO,UAAU,OAAO,OAAO,aAAa,OAAO,KAAK;CAC1D;;;;;;;CAQA,MAAM,UAAU,MAA0C;EACxD,IAAI;GACF,OAAO,MAAM,MAAM,MAAA,uBAAA,KAAM,IAAA,CAAA,CAAS,SAAS,IAAI,CAAC;EAClD,SAAS,OAAO;GACd,IAAI,WAAW,KAAK,GAAG,OAAO;GAC9B,MAAM;EACR;CACF;;;;;;;CAQA,MAAM,MAAM,MAAc,SAA6C;EACrE,MAAM,SAAS,gBAAgB,IAAI;EACnC,IAAI,WAAW,KAAK,MAAA,uBAAA,KAAM,IAAA,CAAA,CAAS,MAAM,QAAQ,EAAE,WAAW,KAAK,CAAC;EACpE,MA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ChC;CAGF,OAAO;EAAE,MAAM;EAAQ,OAAO,WADJ,OAAO,SAAS,SAAS,OAAO,OAAO,IAAI,OAAO,eAAe,YAAY,OAAO,YAAY,gBAAgB,GAAG,WACrG,OAAO,QAAQ;CAAI;AAC7D"}
@@ -1,5 +1,68 @@
1
1
  import { JSONValue, ToolSet } from "ai";
2
+ import { Workspace } from "@cloudflare/computer";
3
+ import { CreateAIToolsOptions } from "@cloudflare/computer/tools/ai-sdk";
2
4
 
5
+ //#region src/workspace-files.d.ts
6
+ /**
7
+ * The filesystem methods Think uses, from `@cloudflare/computer`'s
8
+ * `workspace.fs`.
9
+ */
10
+ type ThinkWorkspaceFilesystem = Pick<
11
+ Workspace["fs"],
12
+ | "readFile"
13
+ | "writeFile"
14
+ | "mkdir"
15
+ | "rm"
16
+ | "stat"
17
+ | "readdir"
18
+ | "find"
19
+ | "grep"
20
+ >;
21
+ /** The parts of a Workspace the `@cloudflare/computer` tools use besides `fs`. */
22
+ type ToolsWorkspace = CreateAIToolsOptions["workspace"];
23
+ /**
24
+ * The Workspace a Think agent works in.
25
+ *
26
+ * A `Workspace` from `@cloudflare/computer` satisfies this, and so does the
27
+ * client `getWorkspace(stub)` returns for a Workspace owned by another
28
+ * Durable Object. Think reads and writes through `workspace.fs`. The
29
+ * `@cloudflare/computer` tools also use `runtime` for `exec` and `assets`
30
+ * for `publish` when the Workspace has them.
31
+ *
32
+ * @experimental The API surface may change before stabilizing.
33
+ */
34
+ type ThinkWorkspace = {
35
+ /** The Workspace filesystem. */ readonly fs: ThinkWorkspaceFilesystem;
36
+ } & Partial<Pick<ToolsWorkspace, "runtime" | "sessionId" | "assets">>;
37
+ /**
38
+ * A {@link ThinkWorkspace} that resolves the real Workspace on first use.
39
+ *
40
+ * Use it for a Workspace another Durable Object owns, so the agent does not
41
+ * reach the owner until a turn actually touches a file:
42
+ *
43
+ * ```ts
44
+ * import { getWorkspace } from "@cloudflare/computer";
45
+ *
46
+ * override workspace = lazyWorkspace(async () =>
47
+ * getWorkspace(await this.parentAgent(Directory))
48
+ * );
49
+ * ```
50
+ *
51
+ * The resolved Workspace is kept and reused. A failed resolution is not
52
+ * kept, so the next operation tries again. To start over with a new client,
53
+ * for example after disposing the old one, assign a new `lazyWorkspace`.
54
+ *
55
+ * Only `fs` is forwarded, so the agent gets the file tools but no `exec`:
56
+ * the exec tool lists the Workspace's backends synchronously, before
57
+ * anything has been resolved.
58
+ *
59
+ * @param resolve - Produces the Workspace.
60
+ * @returns A Workspace whose `fs` forwards to the resolved one.
61
+ */
62
+ declare function lazyWorkspace(
63
+ resolve: () => Promise<ThinkWorkspace>
64
+ ): ThinkWorkspace;
65
+ //#endregion
3
66
  //#region src/tools/fetch.d.ts
4
67
  type FetchResponseMode = "text" | "json" | "auto" | "workspace";
5
68
  type FetchRedirectPolicy = "allowlisted" | "same-origin" | "none";
@@ -44,21 +107,6 @@ interface FetchToolEvent {
44
107
  response?: FetchResponseMode;
45
108
  code?: FetchErrorCode;
46
109
  }
47
- /**
48
- * Minimal workspace surface the fetch tool needs to spill large/binary
49
- * responses to a file. A concrete `Workspace` from `@cloudflare/shell`
50
- * satisfies this.
51
- */
52
- interface FetchWorkspace {
53
- writeFile(path: string, content: string): Promise<void> | void;
54
- writeFileBytes?(path: string, content: Uint8Array): Promise<void> | void;
55
- mkdir(
56
- path: string,
57
- opts?: {
58
- recursive?: boolean;
59
- }
60
- ): Promise<void> | void;
61
- }
62
110
  interface FetchBindingTarget {
63
111
  /** The service binding / Fetcher requests are routed through. */
64
112
  binding: Fetcher;
@@ -94,7 +142,7 @@ interface CreateFetchToolsOptions {
94
142
  /** Allow large/binary bodies to spill to a workspace file. Default false. */
95
143
  spillToWorkspace?: boolean;
96
144
  /** Workspace used for `response: "workspace"` / spill. */
97
- workspace?: FetchWorkspace;
145
+ workspace?: ThinkWorkspace;
98
146
  /** Per-request timeout in ms. Default 10_000. */
99
147
  timeoutMs?: number;
100
148
  /** Default response handling. Default `"auto"`. */
@@ -135,13 +183,15 @@ declare function createFetchTools(options: CreateFetchToolsOptions): ToolSet;
135
183
  //#endregion
136
184
  export {
137
185
  FetchResponseMode as a,
138
- FetchWorkspace as c,
186
+ createFetchTools as c,
187
+ lazyWorkspace as d,
139
188
  FetchRedirectPolicy as i,
140
- createFetchTools as l,
189
+ ThinkWorkspace as l,
141
190
  FetchBindingTarget as n,
142
191
  FetchResult as o,
143
192
  FetchErrorCode as r,
144
193
  FetchToolEvent as s,
145
- CreateFetchToolsOptions as t
194
+ CreateFetchToolsOptions as t,
195
+ ThinkWorkspaceFilesystem as u
146
196
  };
147
- //# sourceMappingURL=fetch-By3eIQ-a.d.ts.map
197
+ //# sourceMappingURL=fetch-C7s1mpgg.d.ts.map
@@ -3,10 +3,9 @@ import {
3
3
  t as ExtensionManager
4
4
  } from "./manager-dOcdCX4u.js";
5
5
  import {
6
- D as createWorkspaceTools,
7
- h as WorkspaceLike
8
- } from "./workspace-CNeXc2vl.js";
9
- import { t as CreateFetchToolsOptions } from "./fetch-By3eIQ-a.js";
6
+ l as ThinkWorkspace,
7
+ t as CreateFetchToolsOptions
8
+ } from "./fetch-C7s1mpgg.js";
10
9
  import {
11
10
  FlexibleSchema,
12
11
  GenerateTextOnStepFinishCallback,
@@ -104,7 +103,7 @@ import {
104
103
  ContextConfig,
105
104
  WritableContextProvider
106
105
  } from "agents/context";
107
- import { Workspace as Workspace$1 } from "@cloudflare/shell";
106
+ import { WorkspaceStub } from "@cloudflare/computer";
108
107
  import {
109
108
  ActionEvent,
110
109
  Adapter,
@@ -281,7 +280,7 @@ interface MediaEvictionConfig {
281
280
  maxRowsPerPass?: number;
282
281
  /**
283
282
  * @deprecated Ignored. Evicted bytes are always preserved in the Workspace
284
- * under `/attachments/evicted/`; there is no drop-the-bytes mode. Accepted
283
+ * under `/workspace/attachments/evicted/`; there is no drop-the-bytes mode. Accepted
285
284
  * so existing configurations keep compiling.
286
285
  */
287
286
  externalizeToWorkspace?: boolean;
@@ -1633,8 +1632,7 @@ declare class Think<
1633
1632
  storeTools: boolean;
1634
1633
  /**
1635
1634
  * Project `getSkills()` into the active workspace so the agent can read
1636
- * and edit skills as files. Computer workspaces use
1637
- * `/workspace/.agents/skills`; legacy Shell uses `/.agents/skills`.
1635
+ * and edit skills as files under `/workspace/.agents/skills`.
1638
1636
  * Existing edits are preserved. Off by default: skills load from their
1639
1637
  * sources and nothing is written to the Workspace, as before. Set `{}` to
1640
1638
  * project with the defaults.
@@ -1806,27 +1804,27 @@ declare class Think<
1806
1804
  */
1807
1805
  extensionManager?: ExtensionManager;
1808
1806
  /**
1809
- * Workspace filesystem available in `getTools()` and lifecycle hooks.
1810
- * Defaults to a full `Workspace` backed by the DO's SQLite storage.
1807
+ * The agent's Workspace, available in `getTools()` and lifecycle hooks.
1808
+ * Defaults to a `Workspace` from `@cloudflare/computer` on this Durable
1809
+ * Object's storage, with no execution backends.
1811
1810
  *
1812
- * Typed as `WorkspaceLike` rather than `Workspace` so subclasses can
1813
- * replace it with anything that satisfies the interface — e.g. a proxy
1814
- * that forwards to a shared workspace owned by a parent DO. Override as
1815
- * a class field to skip the default init entirely:
1811
+ * Override it as a class field to add backends, mounts, or git, or to
1812
+ * work in a Workspace another Durable Object owns:
1816
1813
  *
1817
1814
  * ```typescript
1818
- * // Default init with R2 spillover for large files.
1815
+ * import { Workspace, type WorkspaceStub } from "@cloudflare/computer";
1816
+ import { createAITools } from "@cloudflare/computer/tools/ai-sdk";
1817
+ *
1819
1818
  * override workspace = new Workspace({
1820
- * sql: this.ctx.storage.sql,
1821
- * r2: this.env.R2,
1822
- * name: () => this.name
1819
+ * storage: this.ctx.storage,
1820
+ * backends: [...]
1823
1821
  * });
1824
1822
  *
1825
- * // Or a custom WorkspaceLike — e.g. a parent-owned shared workspace.
1826
- * override workspace: WorkspaceLike = new SharedWorkspace(this);
1823
+ * // A Workspace owned by a parent Durable Object.
1824
+ * override workspace = await getWorkspace(parentStub);
1827
1825
  * ```
1828
1826
  */
1829
- workspace: WorkspaceLike;
1827
+ workspace: ThinkWorkspace;
1830
1828
  /**
1831
1829
  * The codemode runtime behind the execute tool, when one has been created
1832
1830
  * via `createExecuteRuntime(this)` / `createExecuteTool(this)` (from
@@ -1835,14 +1833,6 @@ declare class Think<
1835
1833
  * (`executions`), `expirePaused`, and snippets.
1836
1834
  */
1837
1835
  codemode?: import("@cloudflare/codemode").CodemodeRuntimeHandle;
1838
- /**
1839
- * Include the default workspace Bash tool. Enabled by default so models can
1840
- * run shell-style multi-file workflows against the workspace. Set to `false`
1841
- * to omit it from the built-in workspace tools.
1842
- */
1843
- workspaceBash:
1844
- | boolean
1845
- | NonNullable<Parameters<typeof createWorkspaceTools>[1]>["bash"];
1846
1836
  /**
1847
1837
  * Opt-in HTTP fetch tools. Disabled by default — set to a config object to
1848
1838
  * register a generic `fetch_url` tool (when `allowlist` is provided) and one
@@ -1981,7 +1971,6 @@ declare class Think<
1981
1971
  * since — not zero — and the request they left pending can pass the gate.
1982
1972
  */
1983
1973
  private _mediaEvictionAppendsDuringPass;
1984
- private _warnedEvictionUnsupported;
1985
1974
  /**
1986
1975
  * The last pass that found nothing to evict while aged rows were hidden
1987
1976
  * from the cache: the stored size it saw, and how many linear appends have
@@ -3254,6 +3243,16 @@ declare class Think<
3254
3243
  private _pipelineExtensionToolCallFinish;
3255
3244
  private _pipelineExtensionStepFinish;
3256
3245
  private _pipelineExtensionChunk;
3246
+ /**
3247
+ * Hand out an RPC stub to this agent's Workspace. `getWorkspace(stub)`
3248
+ * from `@cloudflare/computer` calls it to reach the Workspace from
3249
+ * another Worker or Durable Object, and the Worker shell backend calls it
3250
+ * so its isolate can reach back into the Workspace.
3251
+ *
3252
+ * Only a Workspace this agent owns can hand out a stub; a client for
3253
+ * another object's Workspace cannot.
3254
+ */
3255
+ __getWorkspaceStub(): Promise<WorkspaceStub>;
3257
3256
  _hostReadFile(path: string): Promise<string | null>;
3258
3257
  _hostWriteFile(path: string, content: string): Promise<void>;
3259
3258
  _hostDeleteFile(path: string): Promise<boolean>;
@@ -4580,34 +4579,16 @@ declare class Think<
4580
4579
  * `stable_timeout`.
4581
4580
  */
4582
4581
  private _exhaustRecoveryAfterStableTimeout;
4583
- /**
4584
- * Apply the tight OOM-retry budget to a recovery error (#1825). Invoked from
4585
- * `_handleRecoveryCallbackError`, i.e. for an OOM that is *thrown* out of a
4586
- * recovery turn (typically from recovery bookkeeping or storage/SQL ops that
4587
- * reject with the memory-limit-reset message after an isolate reset). An OOM
4588
- * that surfaces as a returned `error` result means `continueLastTurn` already
4589
- * terminalized the turn (client error frame + `onError`), so it is NOT routed
4590
- * here — re-driving a terminalized turn would be wasteful and risk a second
4591
- * terminal signal. `error` may be an Error or a wrapper with a `cause` chain.
4592
- *
4593
- * The reliable terminator is the begin-path (`evaluateChatRecoveryIncident`),
4594
- * which seals once `oomAttempts` exceeds the budget; that runs before the
4595
- * memory-heavy turn, in the low-memory window where writes succeed. This
4596
- * method's job is to persist `oomAttempts` (small writes) so the begin path
4597
- * can act on it, and to schedule a delayed re-run while under budget.
4598
- *
4599
- * Returns `true` when the error was an OOM and this method owns the outcome:
4600
- * - under budget → a delayed re-run was scheduled (best-effort: a transient
4601
- * spike may clear);
4602
- * - over budget (or untrackable, or the bookkeeping itself OOMed) →
4603
- * terminalized via the give-up path with `reason="out_of_memory"`.
4604
- * Returns `false` for non-OOM errors so the caller proceeds normally.
4605
- */
4606
- private _handleRecoveryOom;
4607
4582
  /**
4608
4583
  * Handle an error thrown by `_chatRecoveryContinue` / `_chatRecoveryRetry`
4609
4584
  * after the incident was opened.
4610
4585
  *
4586
+ * - A Durable Object memory-limit reset is re-thrown with no bookkeeping.
4587
+ * The isolate is condemned: its storage calls reject and unconfirmed
4588
+ * writes are discarded, so nothing written here would survive (#2613).
4589
+ * The attempt's `attemptsInFlight` entry stays behind, and the next
4590
+ * attempt counts it against `maxInterruptedAttempts` before running
4591
+ * anything heavy.
4611
4592
  * - A platform transient (`isPlatformTransientError` from `agents` — a
4612
4593
  * deploy code-update reset / script supersede, a `retryable`-flagged
4613
4594
  * platform error, or "Network connection lost.", looking through wrappers
@@ -5582,13 +5563,13 @@ declare function toMessengerAttachment(
5582
5563
  //#endregion
5583
5564
  export {
5584
5565
  MessengerEventKind as $,
5585
- messengerChannel as $n,
5566
+ MediaEvictionConfig as $n,
5586
5567
  RunTurnWait as $t,
5587
5568
  ERROR_MESSENGER_RESPONSE as A,
5588
5569
  TurnConfig as An,
5589
5570
  ChunkContext as At,
5590
5571
  defaultDeliveryTag as B,
5591
- action as Bn,
5572
+ defaultContextOverflowClassifier as Bn,
5592
5573
  MessageMetadataCallback as Bt,
5593
5574
  toMessengerAuthor as C,
5594
5575
  ThinkSubmissionInspection as Cn,
@@ -5603,19 +5584,19 @@ export {
5603
5584
  TurnTrigger as Fn,
5604
5585
  ExtensionConfig as Ft,
5605
5586
  parseMessengerReplySnapshot as G,
5606
- ChannelContext as Gn,
5587
+ ChannelDefinition as Gn,
5607
5588
  PrepareStepResult$1 as Gt,
5608
5589
  messengerReplyFailureMode as H,
5609
- isAction as Hn,
5590
+ skills as Hn,
5610
5591
  PendingApproval as Ht,
5611
5592
  MessengerReplySnapshot as I,
5612
5593
  TypedToolCall$1 as In,
5613
5594
  FiberContext$1 as It,
5614
5595
  MessengerAttachment as J,
5615
- ChannelDeliverySurface as Jn,
5596
+ ChannelIngress as Jn,
5616
5597
  ResolvedChatRecoveryConfig as Jt,
5617
5598
  ChannelSpeakerLabel as K,
5618
- ChannelDefinition as Kn,
5599
+ ChannelDeliveryPolicy as Kn,
5619
5600
  RejectExecutionOptions as Kt,
5620
5601
  MessengerReplyStage as L,
5621
5602
  TypedToolResult as Ln,
@@ -5633,7 +5614,7 @@ export {
5633
5614
  TurnResult as Pn,
5634
5615
  DeliverNoticeOptions as Pt,
5635
5616
  MessengerEvent as Q,
5636
- ThinkChannels as Qn,
5617
+ messengerChannel as Qn,
5637
5618
  RunTurnSubmit as Qt,
5638
5619
  TextStreamCallback as R,
5639
5620
  WaitForSubmissionOptions as Rn,
@@ -5645,22 +5626,22 @@ export {
5645
5626
  ThinkTime as Tn,
5646
5627
  ChatRecoveryExhaustedContext as Tt,
5647
5628
  messengerReplyRecoveryMode as U,
5648
- skills as Un,
5629
+ ChannelCapabilities as Un,
5649
5630
  PrepareStepContext as Ut,
5650
5631
  deliverMessengerReply as V,
5651
- defaultContextOverflowClassifier as Vn,
5632
+ isAction as Vn,
5652
5633
  OnStartDegradation as Vt,
5653
5634
  messengerReplySnapshot as W,
5654
- ChannelCapabilities as Wn,
5635
+ ChannelContext as Wn,
5655
5636
  PrepareStepFunction$1 as Wt,
5656
5637
  MessengerCapabilities as X,
5657
- ChannelKind as Xn,
5638
+ NormalizedChannelDefinition as Xn,
5658
5639
  RunTurnOptions as Xt,
5659
5640
  MessengerAuthor as Y,
5660
- ChannelIngress as Yn,
5641
+ ChannelKind as Yn,
5661
5642
  RunTurnBase as Yt,
5662
5643
  MessengerContext as Z,
5663
- NormalizedChannelDefinition as Zn,
5644
+ ThinkChannels as Zn,
5664
5645
  RunTurnStream as Zt,
5665
5646
  defaultChatSdkEvent as _,
5666
5647
  ThinkModel as _n,
@@ -5678,7 +5659,7 @@ export {
5678
5659
  StreamableResult as dn,
5679
5660
  ActionConfig as dt,
5680
5661
  SaveMessagesOptions$1 as en,
5681
- MediaEvictionConfig as er,
5662
+ CompactAfterOptions as er,
5682
5663
  MessengerMessage as et,
5683
5664
  NormalizedMessengerDefinition as f,
5684
5665
  SubmitMessagesOptions as fn,
@@ -5691,7 +5672,6 @@ export {
5691
5672
  ActionPermissionSpec as ht,
5692
5673
  MessengerConcurrency as i,
5693
5674
  SkillSource$1 as in,
5694
- ThinkSession as ir,
5695
5675
  serializableMessengerEvent as it,
5696
5676
  INTERRUPTED_MESSENGER_RESPONSE as j,
5697
5677
  TurnContext as jn,
@@ -5707,7 +5687,7 @@ export {
5707
5687
  ActionKind as mt,
5708
5688
  ChatSdkMessengerOptions as n,
5709
5689
  SessionMessage$1 as nn,
5710
- CompactionErrorHandler as nr,
5690
+ SessionContextOptions as nr,
5711
5691
  messengerContextFromEvent as nt,
5712
5692
  MessengerConversationResolver as o,
5713
5693
  StepConfig as on,
@@ -5716,18 +5696,18 @@ export {
5716
5696
  SubmitMessagesResult as pn,
5717
5697
  ActionIdempotencyKey as pt,
5718
5698
  MessengerAction as q,
5719
- ChannelDeliveryPolicy as qn,
5699
+ ChannelDeliverySurface as qn,
5720
5700
  ReplyAttachment as qt,
5721
5701
  DEFAULT_MESSENGER_CONCURRENCY as r,
5722
5702
  SkillRunContext as rn,
5723
- SessionContextOptions as rr,
5703
+ ThinkSession as rr,
5724
5704
  resolveChannelSpeakerLabel as rt,
5725
5705
  MessengerConversationTarget as s,
5726
5706
  StepContext as sn,
5727
5707
  ActionApprovalDescriptor as st,
5728
5708
  ChatSdkMessengerEventInput as t,
5729
5709
  SaveMessagesResult$1 as tn,
5730
- CompactAfterOptions as tr,
5710
+ CompactionErrorHandler as tr,
5731
5711
  MessengerThread as tt,
5732
5712
  MessengerThinkHost as u,
5733
5713
  StreamCallback as un,
@@ -5745,7 +5725,7 @@ export {
5745
5725
  ThinkScheduledTask as yn,
5746
5726
  ChatErrorClassification as yt,
5747
5727
  TextStreamCallbackOptions as z,
5748
- Workspace$1 as zn,
5728
+ action as zn,
5749
5729
  MessageConcurrency$1 as zt
5750
5730
  };
5751
- //# sourceMappingURL=index-CmhSKa6U.d.ts.map
5731
+ //# sourceMappingURL=index-Cjq_e9F2.d.ts.map
@@ -1,35 +1,10 @@
1
+ import { a as _checkPrivateRedeclaration, i as _classPrivateFieldInitSpec, n as _classPrivateFieldGet2, r as _assertClassBrand, t as _classPrivateFieldSet2 } from "./classPrivateFieldSet2-DwGJfC3w.js";
1
2
  import { jsonSchema, tool } from "ai";
2
- //#region \0@oxc-project+runtime@0.137.0/helpers/esm/checkPrivateRedeclaration.js
3
- function _checkPrivateRedeclaration(e, t) {
4
- if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object");
5
- }
6
- //#endregion
7
3
  //#region \0@oxc-project+runtime@0.137.0/helpers/esm/classPrivateMethodInitSpec.js
8
4
  function _classPrivateMethodInitSpec(e, a) {
9
5
  _checkPrivateRedeclaration(e, a), a.add(e);
10
6
  }
11
7
  //#endregion
12
- //#region \0@oxc-project+runtime@0.137.0/helpers/esm/classPrivateFieldInitSpec.js
13
- function _classPrivateFieldInitSpec(e, t, a) {
14
- _checkPrivateRedeclaration(e, t), t.set(e, a);
15
- }
16
- //#endregion
17
- //#region \0@oxc-project+runtime@0.137.0/helpers/esm/assertClassBrand.js
18
- function _assertClassBrand(e, t, n) {
19
- if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n;
20
- throw new TypeError("Private element is not present on this object");
21
- }
22
- //#endregion
23
- //#region \0@oxc-project+runtime@0.137.0/helpers/esm/classPrivateFieldGet2.js
24
- function _classPrivateFieldGet2(s, a) {
25
- return s.get(_assertClassBrand(s, a));
26
- }
27
- //#endregion
28
- //#region \0@oxc-project+runtime@0.137.0/helpers/esm/classPrivateFieldSet2.js
29
- function _classPrivateFieldSet2(s, a, r) {
30
- return s.set(_assertClassBrand(s, a), r), r;
31
- }
32
- //#endregion
33
8
  //#region src/extensions/manager.ts
34
9
  /**
35
10
  * ExtensionManager — loads, manages, and exposes tools from extension Workers.
@@ -333,6 +308,6 @@ export default class Extension extends WorkerEntrypoint {
333
308
  `;
334
309
  }
335
310
  //#endregion
336
- export { _assertClassBrand as a, _classPrivateFieldGet2 as i, sanitizeName as n, _classPrivateFieldInitSpec as o, _classPrivateFieldSet2 as r, _classPrivateMethodInitSpec as s, ExtensionManager as t };
311
+ export { sanitizeName as n, _classPrivateMethodInitSpec as r, ExtensionManager as t };
337
312
 
338
- //# sourceMappingURL=manager-Cb3DNZgp.js.map
313
+ //# sourceMappingURL=manager-BubfmA3q.js.map