@cloudflare/think 0.11.0 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetch.js","names":[],"sources":["../../src/tools/fetch.ts"],"sourcesContent":["import type { JSONValue, ToolSet } from \"ai\";\nimport { tool } from \"ai\";\nimport { z } from \"zod\";\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\n/**\n * Minimal workspace surface the fetch tool needs to spill large/binary\n * responses to a file. A concrete `Workspace` from `@cloudflare/shell`\n * satisfies this.\n */\nexport interface FetchWorkspace {\n writeFile(path: string, content: string): Promise<void> | void;\n writeFileBytes?(path: string, content: Uint8Array): Promise<void> | void;\n mkdir(path: string, opts?: { recursive?: boolean }): Promise<void> | void;\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?: FetchWorkspace;\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?: FetchWorkspace;\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\" && isBlockedHost(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\" && isBlockedHost(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 isTextual = isTextualContentType(contentType);\n const path = `/fetched/${Date.now()}-${randomToken()}.${extensionFor(contentType)}`;\n try {\n await ws.mkdir(\"/fetched\", { recursive: true });\n if (isTextual) {\n await ws.writeFile(path, new TextDecoder().decode(bytes));\n } else if (ws.writeFileBytes) {\n await ws.writeFileBytes(path, bytes);\n } else {\n return {\n ok: false,\n code: \"unsupported_content_type\",\n finalUrl,\n message:\n \"Binary response cannot be stored: workspace does not support writeFileBytes.\"\n };\n }\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\nfunction isBlockedHost(hostname: string): boolean {\n const h = hostname.toLowerCase().replace(/\\.$/, \"\");\n if (h.length === 0) return true;\n if (h === \"localhost\" || h.endsWith(\".localhost\")) return true;\n if (h.endsWith(\".internal\")) return true;\n\n if (h.startsWith(\"[\") && h.endsWith(\"]\")) {\n return isBlockedIpv6(h.slice(1, -1));\n }\n if (/^\\d{1,3}(\\.\\d{1,3}){3}$/.test(h)) {\n return isBlockedIpv4(h);\n }\n // Defensive: pure-integer / hex hosts (WHATWG normally normalizes these to\n // dotted IPv4, but reject them outright in case a runtime does not).\n if (/^\\d+$/.test(h) || /^0x[0-9a-f]+$/.test(h)) return true;\n return false;\n}\n\nfunction isBlockedIpv4(ip: string): boolean {\n const parts = ip.split(\".\").map((p) => Number.parseInt(p, 10));\n if (\n parts.length !== 4 ||\n parts.some((n) => Number.isNaN(n) || n < 0 || n > 255)\n ) {\n return true;\n }\n const [a, b] = parts;\n if (a === 0) return true; // 0.0.0.0/8\n if (a === 10) return true; // 10.0.0.0/8\n if (a === 127) return true; // loopback\n if (a === 169 && b === 254) return true; // link-local\n if (a === 172 && b >= 16 && b <= 31) return true; // 172.16.0.0/12\n if (a === 192 && b === 168) return true; // 192.168.0.0/16\n if (a === 100 && b >= 64 && b <= 127) return true; // CGNAT 100.64.0.0/10\n return false;\n}\n\nfunction isBlockedIpv6(ip: string): boolean {\n const lower = ip.toLowerCase();\n if (lower === \"::1\" || lower === \"::\") return true;\n if (lower.startsWith(\"fc\") || lower.startsWith(\"fd\")) return true; // fc00::/7\n if (/^fe[89ab]/.test(lower)) return true; // fe80::/10 link-local\n // IPv4-mapped, dotted form (::ffff:127.0.0.1).\n const dotted = lower.match(/^::ffff:(\\d{1,3}(?:\\.\\d{1,3}){3})$/);\n if (dotted) return isBlockedIpv4(dotted[1]);\n // IPv4-mapped, hex form. The WHATWG URL parser serializes\n // `::ffff:127.0.0.1` as `::ffff:7f00:1`, so decode the trailing two hextets\n // back into dotted IPv4 and reuse the v4 rules.\n const hex = lower.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);\n if (hex) {\n const high = Number.parseInt(hex[1], 16);\n const low = Number.parseInt(hex[2], 16);\n const v4 = `${(high >> 8) & 0xff}.${high & 0xff}.${(low >> 8) & 0xff}.${low & 0xff}`;\n return isBlockedIpv4(v4);\n }\n return false;\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 || \"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ACrG,OAAO,QAAQ;CAAI;AAC7D"}
@@ -1,4 +1,4 @@
1
- import { on as Think, pn as ThinkSubmissionStatus } from "./index-D_S5mETO.js";
1
+ import { on as Think, pn as ThinkSubmissionStatus } from "./index-CR4-ffm_.js";
2
2
  import { ZodObject, z } from "zod";
3
3
  import { WorkflowEvent, WorkflowSleepDuration } from "cloudflare:workers";
4
4
  import {
package/docs/index.md CHANGED
@@ -852,6 +852,7 @@ path.
852
852
  | `getSkills()` | `[]` | Return Agent Skills sources for on-demand skill activation |
853
853
  | `getSkillScriptRunner()` | `null` | Enable the optional `run_skill_script` tool |
854
854
  | `workspaceBash` | `true` | Include or configure the default workspace `bash` tool |
855
+ | `fetchTools` | `false` | Opt-in allowlisted, read-only HTTP fetch tools (`fetch_url` + per-binding `fetch_<name>`). Set to a config object; see [Fetch tool](#fetch-tool) |
855
856
  | `messageConcurrency` | `"queue"` | How overlapping submits behave — see [Client Tools](./client-tools.md) |
856
857
  | `waitForMcpConnections` | `false` | Wait for MCP servers before inference |
857
858
  | `chatRecovery` | `true` | Wrap turns in `runFiber` for durable execution, including sub-agent turns. Set to `{ maxAttempts, stableTimeoutMs, terminalMessage, onExhausted }` to tune bounded recovery. |
@@ -1189,6 +1190,56 @@ handler action before the failure is logged. The next occurrence is still
1189
1190
  scheduled after the action succeeds or exhausts its retries, so failed
1190
1191
  occurrences do not block future runs.
1191
1192
 
1193
+ ## Fetch tool
1194
+
1195
+ Think can give the model a conservative, **read-only** way to read HTTP resources. It is **off by default**. Set the `fetchTools` property for static config, or call `createFetchTools()` inside `getTools()` for per-tenant/dynamic allowlists (it runs every turn). When configured, Think registers a generic `fetch_url` tool (when a public `allowlist` is provided) plus one `fetch_<name>` tool per binding target, and advertises the capability in the system prompt.
1196
+
1197
+ ```typescript
1198
+ export class DocsAgent extends Think<Env> {
1199
+ getModel() {
1200
+ /* ... */
1201
+ }
1202
+
1203
+ fetchTools = {
1204
+ allowlist: ["https://developers.cloudflare.com/**"],
1205
+ bindings: {
1206
+ docsApi: {
1207
+ binding: this.env.DOCS_API, // a service binding / Fetcher
1208
+ description: "Internal docs search API.",
1209
+ allowlist: ["/v1/docs/**"],
1210
+ headers: { "x-agent": "think" } // fixed, server-side, never model-set
1211
+ }
1212
+ }
1213
+ };
1214
+ }
1215
+ ```
1216
+
1217
+ The model sees named tools — `fetch_url({ url, response?, headers? })` and `fetch_docsApi({ path, response?, headers? })` — rather than one polymorphic tool, so per-target policy is baked into each tool.
1218
+
1219
+ **Safety model.** The threat surface is the Workers runtime: reaching loopback/`.internal`/internally bound targets, allowlist-bypass tricks, prompt-injected URLs, credential leakage, and context/storage bloat.
1220
+
1221
+ - **Read-only** — `GET` only. Mutations belong in explicit, approval-gated [Actions](#actions), not here.
1222
+ - **Allowlisted** — every request must match the configured allowlist. URLs are normalized (host lowercased, credentials rejected, paths resolved) before matching, and private/loopback/link-local/`*.internal` targets are blocked for `fetch_url` even if the allowlist is misconfigured.
1223
+ - **Bounded** — `maxBytes` caps the download, `maxModelChars` truncates the model-facing text (`truncated: true`), and `response: "workspace"` (or `spillToWorkspace: true` in auto mode) writes large or binary bodies to a workspace file so the transcript stays small.
1224
+ - **Header-safe** — only headers in `modelHeaderAllowlist` (default `accept`, `accept-language`, `range`) may be set by the model; fixed binding headers are server-side only and are stripped on cross-origin redirects.
1225
+ - **Markdown-first** — a weighted default `Accept` header (`text/markdown` → `text/plain` → `application/json` → `text/html` → `*/*;q=0.1`) nudges content-negotiating endpoints (docs platforms, `llms.txt`-style endpoints) to return clean markdown instead of HTML, while still accepting anything so a strict server never returns `406`. Override per call (the model can set `accept`) or globally via `defaultAccept` (`""` disables it).
1226
+ - **Redirects** — `followRedirects` (`allowlisted` by default) follows a redirect only when the final URL is still allowlisted; binding targets never follow cross-origin redirects.
1227
+
1228
+ Results are structured values (never thrown). Success carries `{ ok: true, status, finalUrl, contentType, bytes, truncated, response, body?/json?/path? }`; failure carries `{ ok: false, code, message, status?, finalUrl? }` where `code` is one of `disallowed_url`, `disallowed_redirect`, `timeout`, `aborted`, `non_2xx`, `unsupported_content_type`, `invalid_json`, `too_large`, `request_failed`. A `tool:fetch` observability event fires on every call, including blocked attempts, for audit.
1229
+
1230
+ **Allowlist semantics.** A bare origin (`https://example.com`) matches that origin and every subpath. Patterns are globs — `**` matches any characters (including `/`) and `*` matches any character except `/`; a pattern with an explicit path and no glob matches that path literally (`https://x.com/v1` matches only `/v1`). Matching ignores the query string and fragment (only scheme + host + port + path are compared), though the original query/fragment are still sent. Binding allowlists should be path-based (`/v1/docs/**`). Note that `json` responses are bounded by `maxBytes` (only `text` is truncated by `maxModelChars`), so for large JSON APIs lower `maxBytes` or use `response: "workspace"`.
1231
+
1232
+ You do not need new machinery to gate egress per call: `beforeToolCall` can `block` or `substitute` a fetch, and channel `tools(...)` policy can narrow which fetch tools are available.
1233
+
1234
+ **When to use what:**
1235
+
1236
+ | Capability | Use it for |
1237
+ | -------------------------------- | ---------------------------------------------------------------------------------------- |
1238
+ | Fetch tool | Reading a known, allowlisted URL or service binding; no code generation |
1239
+ | `createExecuteTool()` (codemode) | Composing/transforming several calls in sandboxed code (`globalOutbound`) |
1240
+ | Browser Run (`tools/browser`) | Rendered pages, auth flows, screenshots, CDP automation |
1241
+ | Typed tools / `agentTool()` | Calling a `WorkerEntrypoint`/DO method with a typed schema, or delegating to a sub-agent |
1242
+
1192
1243
  ## Session Integration
1193
1244
 
1194
1245
  Think uses [Session](https://github.com/cloudflare/agents/blob/main/docs/agents/sessions.md) for conversation storage. Override `configureSession` to add persistent memory, compaction, search, and skills:
@@ -1228,6 +1279,7 @@ Think's `this.messages` getter reads directly from Session's tree-structured sto
1228
1279
  | `@cloudflare/think/messengers/telegram` | Telegram messenger provider and delivery helpers |
1229
1280
  | `@cloudflare/think/workflows` | `ThinkWorkflow`, `step.prompt()` — Workflow prompts |
1230
1281
  | `@cloudflare/think/tools/workspace` | `createWorkspaceTools()` — for custom storage backends |
1282
+ | `@cloudflare/think/tools/fetch` | `createFetchTools()` — opt-in allowlisted HTTP reads |
1231
1283
  | `@cloudflare/think/tools/execute` | `createExecuteTool()` — sandboxed code execution via codemode |
1232
1284
  | `@cloudflare/think/tools/extensions` | `createExtensionTools()` — LLM-driven extension loading |
1233
1285
  | `@cloudflare/think/extensions` | `ExtensionManager`, `HostBridgeLoopback` — extension runtime |
@@ -477,7 +477,8 @@ beforeToolCall(ctx: ToolCallContext): ToolCallDecision | void {
477
477
  - **Substituted input is not re-validated.** The AI SDK validates the model's emitted input against the tool's `inputSchema` _before_ `execute` runs. When `beforeToolCall` returns `{ action: "allow", input: ... }`, that substituted input is passed straight through to `execute` without going through the schema again. If you substitute, ensure the shape stays valid for the tool you're calling.
478
478
  - **`stepNumber` is `undefined` in `ToolCallContext`.** The AI SDK's `ToolExecutionOptions` doesn't expose the current step index. The same field _is_ populated on `ToolCallResultContext` (sourced from `experimental_onToolCallFinish`).
479
479
  - **Throwing from `beforeToolCall`** propagates as a tool error — the AI SDK records it in the same way it would record an `execute` failure, and `afterToolCall` fires with `success: false, error: ...`.
480
- - **Streaming tools (AsyncIterable returns).** The AI SDK supports tools whose `execute` returns `AsyncIterable<output>` to emit preliminary results before a final value. This works regardless of whether the iterator is returned directly (`function execute(...) { return makeIter(); }`, `async function* execute(...) { … }`) or wrapped in a Promise (`async function execute(...) { return makeIter(); }`). Because Think's wrapper must `await beforeToolCall` first, preliminary chunks are collapsed — only the final yielded value reaches the model. If you need true preliminary streaming, override `getTools()` to provide such tools and avoid using `beforeToolCall` for them.
480
+ - **Streaming tools (AsyncIterable returns).** The AI SDK supports tools whose `execute` returns `AsyncIterable<output>` to emit preliminary results before a final value. The canonical form is an async generator (`async function* execute(...) { … }`). Think preserves preliminary streaming for that form even through `beforeToolCall`: each yielded value reaches the model as a `preliminary` tool-result, and the last as the final value. The non-canonical `async function execute(...) { return makeIter(); }` form returns a `Promise<AsyncIterable>`, which does not stream even in the raw AI SDK — Think collapses it to the last yielded value. Use an `async function*` `execute` if you need preliminary streaming.
481
+ - **Blocking/substituting an `async function*` tool emits one `preliminary` chunk.** To keep an `async function*` tool streaming through `beforeToolCall`, its wrapper must commit to an `AsyncIterable` shape synchronously — before the (async) decision is known. The AI SDK turns every value sent through that iterable into a `preliminary` tool-result plus a `final`, so a `block`/`substitute` outcome surfaces one extra `preliminary: true` chunk to observers like `onChunk` (a scalar-`execute` tool never does). The model-visible final output is identical and correct; this only affects observation hooks for the narrow case of blocking/substituting a streaming tool, and it matches how any streaming tool that emits a single value already behaves.
481
482
  - **Hook order:** `beforeToolCall` (subclass) → extension `beforeToolCall` dispatch → original `execute` (or `block`/`substitute` short-circuit) → AI SDK records the outcome → `afterToolCall` (subclass) → extension `afterToolCall` dispatch.
482
483
 
483
484
  ---
@@ -494,19 +495,29 @@ afterToolCall(ctx: ToolCallResultContext): void | Promise<void>
494
495
 
495
496
  `ToolCallResultContext<TOOLS>` is backed by the AI SDK's `OnToolCallFinishEvent<TOOLS>` (the parameter of `experimental_onToolCallFinish`). It spreads the originating `TypedToolCall<TOOLS>` at the top level, plus the per-call event extras and a discriminated outcome:
496
497
 
497
- | Field | Type | Description |
498
- | ------------ | ------------------------------------- | ---------------------------------------------------- |
499
- | `type` | `"tool-call"` | Discriminator (carried over from the call) |
500
- | `toolCallId` | `string` | Unique id matching the originating `ToolCallContext` |
501
- | `toolName` | `string` | Name of the tool that was called |
502
- | `input` | typed when `TOOLS` is passed | Arguments the tool was called with |
503
- | `dynamic?` | `boolean` | `true` for runtime-registered tools |
504
- | `stepNumber` | `number \| undefined` | Index of the current step |
505
- | `messages` | `ReadonlyArray<ModelMessage>` | Conversation messages visible at tool execution time |
506
- | `durationMs` | `number` | Wall-clock execution time of `execute` |
507
- | `success` | `boolean` | Discriminator: `true` on success, `false` on failure |
508
- | `output` | `unknown` (when `success` is `true`) | Whatever the tool's `execute` returned |
509
- | `error` | `unknown` (when `success` is `false`) | Whatever was thrown from `execute` |
498
+ | Field | Type | Description |
499
+ | ------------ | ----------------------------------------- | ---------------------------------------------------- |
500
+ | `type` | `"tool-call"` | Discriminator (carried over from the call) |
501
+ | `toolCallId` | `string` | Unique id matching the originating `ToolCallContext` |
502
+ | `toolName` | `string` | Name of the tool that was called |
503
+ | `input` | typed when `TOOLS` is passed | Arguments the tool was called with |
504
+ | `dynamic?` | `boolean` | `true` for runtime-registered tools |
505
+ | `stepNumber` | `number \| undefined` | Index of the current step |
506
+ | `messages` | `ReadonlyArray<ModelMessage>` | Conversation messages visible at tool execution time |
507
+ | `durationMs` | `number` | Wall-clock execution time of `execute` |
508
+ | `success` | `boolean` | Discriminator: `true` on success, `false` on failure |
509
+ | `output` | typed per tool (when `success` is `true`) | Whatever the tool's `execute` returned |
510
+ | `error` | `unknown` (when `success` is `false`) | Whatever was thrown from `execute` |
511
+
512
+ When you pass an explicit `TOOLS` generic, narrowing on `ctx.toolName` (together with `ctx.success`) narrows `ctx.output` to that tool's inferred output type. Dynamic tools (runtime-registered, MCP) stay `unknown`:
513
+
514
+ ```typescript
515
+ afterToolCall(ctx: ToolCallResultContext<typeof tools>) {
516
+ if (ctx.toolName === "search" && ctx.success) {
517
+ ctx.output.results; // typed as the `search` tool's output
518
+ }
519
+ }
520
+ ```
510
521
 
511
522
  ### Example
512
523
 
@@ -449,14 +449,15 @@ onChatRecovery(ctx: ChatRecoveryContext): ChatRecoveryOptions {
449
449
 
450
450
  ### Recovery budgets and limits
451
451
 
452
- Instead of `chatRecovery = true`, assign an object to tune how long recovery is allowed to run and when it is given up on. A turn that keeps making forward progress is never terminated by the framework on its own — duration is not a bound. Recovery is only sealed by one of the limits below.
452
+ Instead of `chatRecovery = true`, assign an object to tune how long recovery is allowed to run and when it is given up on. A turn that keeps making forward progress survives unbounded interruption — duration is not a bound — as long as it stays under the `maxRecoveryWork` backstop. Recovery is only sealed by one of the limits below.
453
453
 
454
454
  ```typescript
455
455
  export class MyAgent extends Think<Env> {
456
456
  chatRecovery = {
457
457
  maxAttempts: 10,
458
458
  noProgressTimeoutMs: 5 * 60 * 1000,
459
- maxRecoveryWork: Infinity,
459
+ maxRecoveryWork: 1000,
460
+ maxOomRetries: 3,
460
461
  terminalMessage: "The assistant was interrupted and could not recover.",
461
462
  // Consulted from the second recovery attempt onward. Return false to stop.
462
463
  // Called as `config.shouldKeepRecovering(ctx)`, so it is NOT bound to the
@@ -472,17 +473,20 @@ export class MyAgent extends Think<Env> {
472
473
  }
473
474
  ```
474
475
 
475
- | Field | Default | Description |
476
- | ---------------------- | ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
477
- | `maxAttempts` | `10` | Attempt cap. Resets on forward progress, so it catches a tight no-progress alarm loop, not a healthy long turn. |
478
- | `stableTimeoutMs` | `10_000` | How long an attempt waits for the isolate to reach stable state before rescheduling. |
479
- | `noProgressTimeoutMs` | `300_000` (5 min) | Primary stuck-turn bound: max time without forward progress before sealing. **Resets on every progress-bearing attempt.** |
480
- | `maxRecoveryWork` | `Infinity` | Runaway-loop guard: max produced content/tool units since the incident opened before a still-progressing turn is sealed. No cap by default. |
481
- | `shouldKeepRecovering` | — | Caller policy consulted from the second attempt onward. Return `false` to stop recovery. The hook point for a token/cost budget (`ctx.work` is a coarse segment count, not tokens). |
482
- | `terminalMessage` | generic message | Message shown to the user when recovery is given up on. |
483
- | `onExhausted` | — | Called once when recovery is given up on. Inspect `ctx.reason`. |
484
-
485
- `ctx.reason` on the exhausted hook is one of: `no_progress_timeout` (stuck), `max_attempts_exceeded` (no-progress alarm loop), `work_budget_exceeded` (runaway), `recovery_aborted` (your `shouldKeepRecovering` returned `false`), or `stable_timeout` (extreme churn). See [`chat-agents.md`](https://github.com/cloudflare/agents/blob/main/docs/agents/chat-agents.md#stream-recovery) for the full shared reference — Think and `@cloudflare/ai-chat` use the same recovery configuration.
476
+ | Field | Default | Description |
477
+ | ---------------------- | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
478
+ | `maxAttempts` | `10` | Attempt cap. Resets on forward progress, so it catches a tight no-progress alarm loop, not a healthy long turn. |
479
+ | `stableTimeoutMs` | `10_000` | How long an attempt waits for the isolate to reach stable state before rescheduling. |
480
+ | `noProgressTimeoutMs` | `300_000` (5 min) | Primary stuck-turn bound: max time without forward progress before sealing. **Resets on every progress-bearing attempt.** |
481
+ | `maxRecoveryWork` | `1000` | Runaway-loop guard: max produced content/tool units since the incident opened before a still-progressing turn is sealed (`work_budget_exceeded`). A generous finite backstop so a turn that keeps emitting content but never converges (for example an isolate that runs out of memory mid-stream on every recovery) cannot loop forever. Raise it, or set `Infinity`, for a very long agentic turn. |
482
+ | `maxOomRetries` | `3` | Tight retry budget for a Durable Object memory-limit reset (the isolate exceeded its 128 MB limit). An OOM usually re-OOMs on re-run, but can be a transient spike, so recovery retries a few times then seals with `out_of_memory`. Counts only attempts that ended in an OOM. Set `0` to seal on the first OOM. |
483
+ | `shouldKeepRecovering` | — | Caller policy consulted from the second attempt onward. Return `false` to stop recovery. The hook point for a token/cost budget (`ctx.work` is a coarse segment count, not tokens). |
484
+ | `terminalMessage` | generic message | Message shown to the user when recovery is given up on. |
485
+ | `onExhausted` | — | Called once when recovery is given up on. Inspect `ctx.reason`. |
486
+
487
+ `ctx.reason` on the exhausted hook is one of: `no_progress_timeout` (stuck), `max_attempts_exceeded` (no-progress alarm loop), `work_budget_exceeded` (runaway), `out_of_memory` (repeated memory-limit resets), `recovery_aborted` (your `shouldKeepRecovering` returned `false`), or `stable_timeout` (extreme churn). See [`chat-agents.md`](https://github.com/cloudflare/agents/blob/main/docs/agents/chat-agents.md#stream-recovery) for the full shared reference — Think and `@cloudflare/ai-chat` use the same recovery configuration.
488
+
489
+ > **Last-resort OOM backstop.** A memory-limit reset severe enough to bypass the budgets above (for example the Durable Object out-of-memories while loading state on wake, before recovery runs) is caught at the alarm boundary: after `maxAlarmMemoryLimitStrikes` (a base `Agent` static option, default `3`) consecutive alarms end in a memory-limit reset, the interrupted turn is sealed with `out_of_memory` and the platform's alarm-retry loop is stopped (emitting an `alarm:memory_limit_reset` event). This bounds the loop and the bill but does not shrink the working set — a turn that genuinely no longer fits in 128 MB needs a smaller context.
486
490
 
487
491
  ---
488
492
 
package/package.json CHANGED
@@ -9,7 +9,7 @@
9
9
  "tools"
10
10
  ],
11
11
  "type": "module",
12
- "version": "0.11.0",
12
+ "version": "0.11.1",
13
13
  "license": "MIT",
14
14
  "repository": {
15
15
  "directory": "packages/think",
@@ -38,7 +38,7 @@
38
38
  "@ai-sdk/openai": "^3.0.70",
39
39
  "@ai-sdk/react": "^3.0.204",
40
40
  "@chat-adapter/telegram": "^4.31.0",
41
- "@cloudflare/ai-chat": "^0.9.0",
41
+ "@cloudflare/ai-chat": "^0.9.1",
42
42
  "@cloudflare/kumo": "^2.6.0",
43
43
  "@phosphor-icons/react": "^2.1.10",
44
44
  "@streamdown/code": "^1.1.1",
@@ -48,7 +48,7 @@
48
48
  "@types/react-dom": "^19.2.3",
49
49
  "@types/yargs": "^17.0.35",
50
50
  "@vitejs/plugin-react": "^6.0.3",
51
- "agents": "^0.17.0",
51
+ "agents": "^0.17.1",
52
52
  "ai": "^6.0.202",
53
53
  "jsdom": "^29.1.1",
54
54
  "react": "^19.2.7",
@@ -61,7 +61,7 @@
61
61
  "peerDependencies": {
62
62
  "@ai-sdk/react": "^3.0.204",
63
63
  "@chat-adapter/telegram": "^4.29.0",
64
- "agents": ">=0.17.0 <1.0.0",
64
+ "agents": ">=0.17.1 <1.0.0",
65
65
  "ai": "^6.0.182",
66
66
  "react": "^19.0.0",
67
67
  "vite": ">=6 <9",
@@ -118,6 +118,10 @@
118
118
  "types": "./dist/tools/workspace.d.ts",
119
119
  "import": "./dist/tools/workspace.js"
120
120
  },
121
+ "./tools/fetch": {
122
+ "types": "./dist/tools/fetch.d.ts",
123
+ "import": "./dist/tools/fetch.js"
124
+ },
121
125
  "./tools/execute": {
122
126
  "types": "./dist/tools/execute.d.ts",
123
127
  "import": "./dist/tools/execute.js"