@cloudflare/think 0.10.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.
Files changed (138) hide show
  1. package/README.md +73 -17
  2. package/dist/{chat-sdk-Bb93yaZh.js → chat-sdk-D6cUghsQ.js} +33 -8
  3. package/dist/chat-sdk-D6cUghsQ.js.map +1 -0
  4. package/dist/cli/index.js +224 -55
  5. package/dist/cli/index.js.map +1 -1
  6. package/dist/{codegen-CuPdJRpV.js → codegen-DlA2QQuU.js} +6 -38
  7. package/dist/codegen-DlA2QQuU.js.map +1 -0
  8. package/dist/{config-D512sQYg.d.ts → config-CD7hqncK.d.ts} +5 -5
  9. package/dist/extensions/index.js +1 -1
  10. package/dist/fetch-By3eIQ-a.d.ts +147 -0
  11. package/dist/framework/index.d.ts +17 -62
  12. package/dist/framework/index.js +3 -57
  13. package/dist/{think-i1Pkgb1R.d.ts → index-CR4-ffm_.d.ts} +1734 -736
  14. package/dist/{manager-BPndMP_6.js → manager-CSk5htym.js} +7 -7
  15. package/dist/{manager-BPndMP_6.js.map → manager-CSk5htym.js.map} +1 -1
  16. package/dist/{manifest-CpB-xngB.d.ts → manifest-DK5HuGga.d.ts} +16 -18
  17. package/dist/messengers/index.d.ts +59 -55
  18. package/dist/messengers/index.js +2 -2
  19. package/dist/messengers/telegram.d.ts +4 -4
  20. package/dist/messengers/telegram.js +1 -1
  21. package/dist/react.d.ts +79 -0
  22. package/dist/react.js +28 -0
  23. package/dist/react.js.map +1 -0
  24. package/dist/server-entry.d.ts +1 -1
  25. package/dist/server-entry.js +1 -1
  26. package/dist/server-entry.js.map +1 -1
  27. package/dist/studio/assets/{angular-html-z-TUogET.js → angular-html-D27LthTc.js} +1 -1
  28. package/dist/studio/assets/{angular-ts-DMGuEVeg.js → angular-ts-DtNL2gQ7.js} +1 -1
  29. package/dist/studio/assets/{apl-KvrEROqd.js → apl-BgEcDqM0.js} +1 -1
  30. package/dist/studio/assets/{astro-Bm_woEti.js → astro-CstbRF9e.js} +1 -1
  31. package/dist/studio/assets/{blade-BdCF3r89.js → blade-CLG-7epG.js} +1 -1
  32. package/dist/studio/assets/{c-CDqDtkvZ.js → c-CssQqwxO.js} +1 -1
  33. package/dist/studio/assets/{cobol-CeFM1vZz.js → cobol-CjmzHCjg.js} +1 -1
  34. package/dist/studio/assets/{coffee-2ed6LBym.js → coffee-B_rqYPkp.js} +1 -1
  35. package/dist/studio/assets/{cpp-Dj3nX0J4.js → cpp-5YyZJlb7.js} +1 -1
  36. package/dist/studio/assets/{crystal-BsIYZMQ3.js → crystal-D7uKze0i.js} +1 -1
  37. package/dist/studio/assets/{css-B48fnuoH.js → css-k9oPgg7G.js} +1 -1
  38. package/dist/studio/assets/{edge-C7qt1aza.js → edge-CGgsSt0x.js} +1 -1
  39. package/dist/studio/assets/{elixir-CiTmwoQ3.js → elixir-BX_d5Evo.js} +1 -1
  40. package/dist/studio/assets/{elm-exDZ-PRY.js → elm-DENxDm5e.js} +1 -1
  41. package/dist/studio/assets/{erb-3fmfgt-Q.js → erb-DvYOup03.js} +1 -1
  42. package/dist/studio/assets/{git-rebase-75I-C7zW.js → git-rebase-BsAdTS5A.js} +1 -1
  43. package/dist/studio/assets/{glimmer-js-JjRzYRv8.js → glimmer-js-e0h98Z67.js} +1 -1
  44. package/dist/studio/assets/{glimmer-ts-DcC_g6bi.js → glimmer-ts-C9s5Kv8m.js} +1 -1
  45. package/dist/studio/assets/{glsl-CHo__hpu.js → glsl-CCiyeTRs.js} +1 -1
  46. package/dist/studio/assets/{graphql-J3cHpSdo.js → graphql-BRtHwsqk.js} +1 -1
  47. package/dist/studio/assets/{hack-or1FCnPg.js → hack-Dnt0QXHh.js} +1 -1
  48. package/dist/studio/assets/{haml-uv3vtlo6.js → haml-EXGmzuB1.js} +1 -1
  49. package/dist/studio/assets/{handlebars--xrOP0sp.js → handlebars-CzyBIDJE.js} +1 -1
  50. package/dist/studio/assets/{highlighted-body-OFNGDK62-D5UBAw6b.js → highlighted-body-OFNGDK62-CQUFKLNu.js} +1 -1
  51. package/dist/studio/assets/{html-CWnTqWKh.js → html-BAT8b_VM.js} +1 -1
  52. package/dist/studio/assets/{html-derivative-DWyLco-z.js → html-derivative-7tkS-r6F.js} +1 -1
  53. package/dist/studio/assets/{http-BGB8mLqf.js → http-Cgka02Qq.js} +1 -1
  54. package/dist/studio/assets/{hurl-BWdvIVUG.js → hurl-Cbkh8WEw.js} +1 -1
  55. package/dist/studio/assets/index-D6n8vpkp.js +390 -0
  56. package/dist/studio/assets/index-DkGWw6ES.css +2 -0
  57. package/dist/studio/assets/{java-BqyrPpKF.js → java-DrRKiUno.js} +1 -1
  58. package/dist/studio/assets/{javascript-D8Aej0xg.js → javascript-9LAnHOxD.js} +1 -1
  59. package/dist/studio/assets/{jinja-SIORrXov.js → jinja-CqRt4prs.js} +1 -1
  60. package/dist/studio/assets/{jison-B2T4v51n.js → jison-BX-IOQpJ.js} +1 -1
  61. package/dist/studio/assets/{json-BFdVRj9r.js → json-dOrE-En8.js} +1 -1
  62. package/dist/studio/assets/{jsx-w4r1xieS.js → jsx-BSTPfqWX.js} +1 -1
  63. package/dist/studio/assets/{julia-BFBtDmmM.js → julia-Dvz-BPmf.js} +1 -1
  64. package/dist/studio/assets/{just-CjAPsU_y.js → just-BHQm0Atq.js} +1 -1
  65. package/dist/studio/assets/{latex-CghDKqKz.js → latex-CxdhxuXv.js} +1 -1
  66. package/dist/studio/assets/{liquid-Cp9loVkE.js → liquid-D-hM-Q_F.js} +1 -1
  67. package/dist/studio/assets/{lua-HNnIDxnY.js → lua-5qtqjLHq.js} +1 -1
  68. package/dist/studio/assets/{marko-BXT10Apm.js → marko-5FJaM2co.js} +1 -1
  69. package/dist/studio/assets/{mdc-CaiOz4_A.js → mdc-BhYW7lCG.js} +1 -1
  70. package/dist/studio/assets/mermaid-GHXKKRXX-CWM2EB-u.js +1 -0
  71. package/dist/studio/assets/{nginx-DgYZ5SY9.js → nginx-rtAXrRye.js} +1 -1
  72. package/dist/studio/assets/{nim-CAMVX-MV.js → nim-DQSmaN9U.js} +1 -1
  73. package/dist/studio/assets/{perl-Dc6Wp7SD.js → perl-B54AdcaE.js} +1 -1
  74. package/dist/studio/assets/{php-DgLi8LNU.js → php-DpvTxCny.js} +1 -1
  75. package/dist/studio/assets/{pug-ZHFv4Vgd.js → pug-Cyffw0Ho.js} +1 -1
  76. package/dist/studio/assets/{qml-DU62cSZp.js → qml-CxRetSkO.js} +1 -1
  77. package/dist/studio/assets/{r-BwU69RSh.js → r-CXWRxrXc.js} +1 -1
  78. package/dist/studio/assets/{razor-BUgi_XZM.js → razor-BJzI-zc9.js} +1 -1
  79. package/dist/studio/assets/{regexp-DuNhqfkW.js → regexp-dqxdfrnE.js} +1 -1
  80. package/dist/studio/assets/{rst-BB3BeaSy.js → rst-BW7eKYj4.js} +1 -1
  81. package/dist/studio/assets/{ruby-T0tkEfUZ.js → ruby-D5Npyj8-.js} +1 -1
  82. package/dist/studio/assets/{sas-CMhZa3S0.js → sas-DZLppjul.js} +1 -1
  83. package/dist/studio/assets/{scss-DtXjZ3vZ.js → scss-CbqoxyAe.js} +1 -1
  84. package/dist/studio/assets/{shellscript-BESt-FLs.js → shellscript-CFHqBeXu.js} +1 -1
  85. package/dist/studio/assets/{shellsession-8irtvYxL.js → shellsession-CbZDA4Bf.js} +1 -1
  86. package/dist/studio/assets/{soy-CIvhOgLR.js → soy-PImjtV58.js} +1 -1
  87. package/dist/studio/assets/{sql-obAOXh1G.js → sql-DhGo8urW.js} +1 -1
  88. package/dist/studio/assets/{stata-D3OCK8xW.js → stata-CjHWbU2v.js} +1 -1
  89. package/dist/studio/assets/{surrealql-Dk_bguB0.js → surrealql-o8Qr4t56.js} +1 -1
  90. package/dist/studio/assets/{svelte-C0-KQt-t.js → svelte-DlSIyEV1.js} +1 -1
  91. package/dist/studio/assets/{templ-lg4nvF9H.js → templ-qizfwU1w.js} +1 -1
  92. package/dist/studio/assets/{tex-BNcQSX7R.js → tex-Ca7T661H.js} +1 -1
  93. package/dist/studio/assets/{ts-tags-AgW9jVv0.js → ts-tags-DUmjLkgl.js} +1 -1
  94. package/dist/studio/assets/{tsx-CL8XyR3d.js → tsx-CfwgIqHW.js} +1 -1
  95. package/dist/studio/assets/{twig-VkSbsH0Y.js → twig-D7NAYUBY.js} +1 -1
  96. package/dist/studio/assets/{typescript-BfD1znAG.js → typescript-Bbz9oX-P.js} +1 -1
  97. package/dist/studio/assets/{vue-html-w3sbjuft.js → vue-html-CcxTb_Jn.js} +1 -1
  98. package/dist/studio/assets/{vue-gv_2i8Vk.js → vue-vYpz06zQ.js} +1 -1
  99. package/dist/studio/assets/{vue-vine-C9sgcRlL.js → vue-vine-DW4RqCKF.js} +1 -1
  100. package/dist/studio/assets/{xml-nNPxMKnG.js → xml-R4LZ_u4f.js} +1 -1
  101. package/dist/studio/assets/{xsl-C7iHP36x.js → xsl-CS-xzp3L.js} +1 -1
  102. package/dist/studio/assets/{yaml-Cq3YaG6o.js → yaml-CqDWbYXd.js} +1 -1
  103. package/dist/studio/index.html +2 -2
  104. package/dist/think.d.ts +3 -2
  105. package/dist/think.js +8406 -2
  106. package/dist/think.js.map +1 -0
  107. package/dist/tools/extensions.js +1 -1
  108. package/dist/tools/fetch.d.ts +22 -0
  109. package/dist/tools/fetch.js +646 -0
  110. package/dist/tools/fetch.js.map +1 -0
  111. package/dist/tools/workspace.js +2 -2
  112. package/dist/tools/workspace.js.map +1 -1
  113. package/dist/{types-codegen-B6c5KpYH.js → types-codegen-C-9yeFao.js} +9 -33
  114. package/dist/types-codegen-C-9yeFao.js.map +1 -0
  115. package/dist/vite.d.ts +5 -5
  116. package/dist/vite.js +1 -1
  117. package/dist/workflows.d.ts +1 -1
  118. package/docs/actions.md +297 -0
  119. package/docs/channels.md +185 -0
  120. package/docs/client-tools.md +233 -0
  121. package/docs/getting-started.md +314 -0
  122. package/docs/index.md +1324 -0
  123. package/docs/lifecycle-hooks.md +850 -0
  124. package/docs/messengers.md +197 -0
  125. package/docs/programmatic-submissions.md +206 -0
  126. package/docs/sub-agents.md +524 -0
  127. package/docs/tools.md +582 -0
  128. package/docs/workflows.md +217 -0
  129. package/package.json +50 -17
  130. package/dist/chat-sdk-Bb93yaZh.js.map +0 -1
  131. package/dist/codegen-CuPdJRpV.js.map +0 -1
  132. package/dist/framework/index.js.map +0 -1
  133. package/dist/studio/assets/index-Cbb3GlZY.js +0 -496
  134. package/dist/studio/assets/index-DN9_cL01.css +0 -2
  135. package/dist/studio/assets/mermaid-GHXKKRXX-I2ZcYo7k.js +0 -1
  136. package/dist/think-BYZXQ-vm.js +0 -6513
  137. package/dist/think-BYZXQ-vm.js.map +0 -1
  138. package/dist/types-codegen-B6c5KpYH.js.map +0 -1
@@ -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 || \"unknown\"}${output.truncated ? \", truncated\" : \"\"}):\\n\\n`;\n return { type: \"text\", value: prefix + (output.body ?? \"\") };\n}\n"],"mappings":";;;AA+HA,MAAM,oBAAoB;AAC1B,MAAM,0BAA0B;AAChC,MAAM,qBAAqB;AAC3B,MAAM,iCAAiC;CAAC;CAAU;CAAmB;AAAO;AAG5E,MAAM,iBACJ;AACF,MAAM,gBAAgB;;;;;;;;;;;;;;;;;;;AA8CtB,SAAgB,iBAAiB,SAA2C;CAC1E,MAAM,mBAAmB,QAAQ,aAAa,CAAC,EAAA,CAAG,QAC/C,UAAU,MAAM,SAAS,CAC5B;CACA,MAAM,WAAW,QAAQ,YAAY,CAAC;CACtC,MAAM,eAAe,OAAO,KAAK,QAAQ;CAEzC,IAAI,gBAAgB,WAAW,KAAK,aAAa,WAAW,GAC1D,MAAM,IAAI,MACR,sFACF;CAGF,MAAM,SAAyB;EAC7B,UAAU,QAAQ,YAAY;EAC9B,eAAe,QAAQ,iBAAiB;EACxC,kBAAkB,QAAQ,oBAAoB;EAC9C,WAAW,QAAQ;EACnB,WAAW,QAAQ,aAAa;EAChC,UAAU,QAAQ,YAAY;EAC9B,iBAAiB,QAAQ,mBAAmB;EAC5C,sBAAsB,IAAI,KACvB,QAAQ,wBAAwB,+BAAA,CAAgC,KAC9D,SAAS,KAAK,YAAY,CAC7B,CACF;EACA,eAAe,QAAQ,iBAAiB;EACxC,SAAS,Q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ACjB,aAAa,OAAO;GACpB,MAAM,OAAO,QAAQ;EACvB;CACF;CAEF,IAAI,OAAO,aAAa,aACtB,OAAO;EACL,MAAM;EACN,OACE,WAAW,OAAO,SAAS,IAAI,OAAO,eAAe,UAAU,IAC5D,OAAO,MAAM,QAAQ,OAAO,YAAY,gBAAgB,GAAG,iBAC9C,OAAO,KAAK;CAChC;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"}
@@ -654,7 +654,7 @@ async function snapshotWorkspaceForBash(options) {
654
654
  const maxFileBytes = options.maxWorkspaceFileBytes ?? DEFAULT_BASH_MAX_WORKSPACE_FILE_BYTES;
655
655
  const files = {};
656
656
  const initialFiles = /* @__PURE__ */ new Map();
657
- const initialDirectories = new Set(["/"]);
657
+ const initialDirectories = /* @__PURE__ */ new Set(["/"]);
658
658
  const protectedPaths = /* @__PURE__ */ new Set();
659
659
  const skippedFiles = [];
660
660
  const pending = ["/"];
@@ -717,7 +717,7 @@ async function syncBashFilesToWorkspace({ ops, bash, initialFiles, initialDirect
717
717
  };
718
718
  const errors = [];
719
719
  const finalFiles = /* @__PURE__ */ new Map();
720
- const finalDirectories = new Set(["/"]);
720
+ const finalDirectories = /* @__PURE__ */ new Set(["/"]);
721
721
  for (const rawPath of bash.fs.getAllPaths()) {
722
722
  const path = normalizeWorkspacePath(rawPath);
723
723
  if (!shouldSyncBashPath(path, initialFiles, protectedPaths)) continue;
@@ -1 +1 @@
1
- {"version":3,"file":"workspace.js","names":[],"sources":["../../src/tools/workspace.ts"],"sourcesContent":["import type { Workspace, FileInfo } from \"@cloudflare/shell\";\nimport type { JSONValue } from \"ai\";\nimport type { InitialFiles } from \"just-bash\";\nimport { Bash } from \"just-bash\";\nimport { tool } from \"ai\";\nimport { z } from \"zod\";\n\n// ── WorkspaceLike ─────────────────────────────────────────────────\n//\n// Minimum workspace surface that Think's internals rely on. Covers the\n// methods called by `createWorkspaceTools()` below plus the handful\n// Think itself uses (`readFile`/`writeFile`/`readDir`/`rm` in\n// `think.ts`). The read tool also needs `readFileBytes` so image/PDF\n// reads can be rehydrated as AI SDK multimodal content. A concrete\n// `Workspace` from `@cloudflare/shell` satisfies this; so do custom\n// implementations like the `SharedWorkspace` proxy in `examples/assistant`\n// that forwards to a parent DO.\n//\n// Consumers who reach for the fuller filesystem API (e.g.\n// `createWorkspaceStateBackend` for codemode's `state.*` in a sandbox)\n// still need a concrete `Workspace`.\n//\n// @experimental The API surface may change before stabilizing.\n\nexport type WorkspaceLike = Pick<\n Workspace,\n | \"readFile\"\n | \"readFileBytes\"\n | \"writeFile\"\n | \"readDir\"\n | \"rm\"\n | \"glob\"\n | \"mkdir\"\n | \"stat\"\n>;\n\n// ── Operations interfaces ─────────────────────────────────────────\n// Abstractions over file I/O so the same tools can work against\n// Workspace, a local filesystem, or anything else.\n\nexport interface ReadOperations {\n readFile(path: string): Promise<string | null>;\n readFileBytes(path: string): Promise<Uint8Array | null>;\n stat(path: string): Promise<FileInfo | null> | FileInfo | null;\n}\n\nexport interface WriteOperations {\n writeFile(path: string, content: string): Promise<void>;\n mkdir(path: string, opts?: { recursive?: boolean }): Promise<void> | void;\n}\n\nexport interface EditOperations {\n readFile(path: string): Promise<string | null>;\n writeFile(path: string, content: string): Promise<void>;\n}\n\nexport interface ListOperations {\n readDir(\n dir: string,\n opts?: { limit?: number; offset?: number }\n ): Promise<FileInfo[]> | FileInfo[];\n}\n\nexport interface FindOperations {\n glob(pattern: string): Promise<FileInfo[]> | FileInfo[];\n}\n\nexport interface DeleteOperations {\n rm(\n path: string,\n opts?: { recursive?: boolean; force?: boolean }\n ): Promise<void>;\n}\n\nexport interface GrepOperations {\n glob(pattern: string): Promise<FileInfo[]> | FileInfo[];\n readFile(path: string): Promise<string | null>;\n}\n\nexport interface BashOperations {\n readDir(\n dir: string,\n opts?: { limit?: number; offset?: number }\n ): Promise<FileInfo[]> | FileInfo[];\n readFileBytes(path: string): Promise<Uint8Array | null>;\n writeFile(path: string, content: string): Promise<void>;\n writeFileBytes?: (path: string, content: Uint8Array) => Promise<void>;\n mkdir(path: string, opts?: { recursive?: boolean }): Promise<void> | void;\n rm(\n path: string,\n opts?: { recursive?: boolean; force?: boolean }\n ): Promise<void>;\n}\n\n// ── Workspace-backed operation factories ──────────────────────────\n\nfunction workspaceReadOps(ws: WorkspaceLike): ReadOperations {\n return {\n readFile: (path) => ws.readFile(path),\n readFileBytes: (path) => ws.readFileBytes(path),\n stat: (path) => ws.stat(path)\n };\n}\n\nfunction workspaceWriteOps(ws: WorkspaceLike): WriteOperations {\n return {\n writeFile: (path, content) => ws.writeFile(path, content),\n mkdir: (path, opts) => ws.mkdir(path, opts)\n };\n}\n\nfunction workspaceEditOps(ws: WorkspaceLike): EditOperations {\n return {\n readFile: (path) => ws.readFile(path),\n writeFile: (path, content) => ws.writeFile(path, content)\n };\n}\n\nfunction workspaceListOps(ws: WorkspaceLike): ListOperations {\n return {\n readDir: (dir, opts) => ws.readDir(dir, opts)\n };\n}\n\nfunction workspaceFindOps(ws: WorkspaceLike): FindOperations {\n return {\n glob: (pattern) => ws.glob(pattern)\n };\n}\n\nfunction workspaceDeleteOps(ws: WorkspaceLike): DeleteOperations {\n return {\n rm: (path, opts) => ws.rm(path, opts)\n };\n}\n\nfunction workspaceGrepOps(ws: WorkspaceLike): GrepOperations {\n return {\n glob: (pattern) => ws.glob(pattern),\n readFile: (path) => ws.readFile(path)\n };\n}\n\nfunction workspaceBashOps(ws: WorkspaceLike): BashOperations {\n const maybeBytesWriter = ws as WorkspaceLike & {\n writeFileBytes?: (path: string, content: Uint8Array) => Promise<void>;\n };\n return {\n readDir: (dir, opts) => ws.readDir(dir, opts),\n readFileBytes: (path) => ws.readFileBytes(path),\n writeFile: (path, content) => ws.writeFile(path, content),\n writeFileBytes: maybeBytesWriter.writeFileBytes\n ? (path, content) => maybeBytesWriter.writeFileBytes!(path, content)\n : undefined,\n mkdir: (path, opts) => ws.mkdir(path, opts),\n rm: (path, opts) => ws.rm(path, opts)\n };\n}\n\nexport interface WorkspaceToolsOptions {\n /**\n * Include the default workspace Bash tool. Enabled by default; pass `false`\n * to omit it, or an options object to tune execution limits.\n */\n bash?: boolean | Omit<BashToolOptions, \"ops\">;\n}\n\nexport type WorkspaceTools = {\n read: ReturnType<typeof createReadTool>;\n write: ReturnType<typeof createWriteTool>;\n edit: ReturnType<typeof createEditTool>;\n list: ReturnType<typeof createListTool>;\n find: ReturnType<typeof createFindTool>;\n grep: ReturnType<typeof createGrepTool>;\n delete: ReturnType<typeof createDeleteTool>;\n bash?: ReturnType<typeof createBashTool>;\n};\n\n/**\n * Create a complete set of AI SDK tools backed by a workspace.\n *\n * Accepts either a concrete `Workspace` from `@cloudflare/shell` or any\n * `WorkspaceLike` implementation — e.g. a proxy that forwards calls to a\n * shared workspace owned by a parent DO.\n *\n * ```ts\n * import { Workspace } from \"@cloudflare/shell\";\n * import { createWorkspaceTools } from \"@cloudflare/think\";\n *\n * class MyAgent extends Agent<Env> {\n * workspace = new Workspace({ sql: this.ctx.storage.sql, name: () => this.name });\n *\n * async onChatMessage() {\n * const tools = createWorkspaceTools(this.workspace);\n * const result = streamText({ model, tools, messages });\n * return result.toUIMessageStreamResponse();\n * }\n * }\n * ```\n */\nexport function createWorkspaceTools(\n workspace: WorkspaceLike,\n options: WorkspaceToolsOptions = {}\n): WorkspaceTools {\n const tools: WorkspaceTools = {\n read: createReadTool({ ops: workspaceReadOps(workspace) }),\n write: createWriteTool({ ops: workspaceWriteOps(workspace) }),\n edit: createEditTool({ ops: workspaceEditOps(workspace) }),\n list: createListTool({ ops: workspaceListOps(workspace) }),\n find: createFindTool({ ops: workspaceFindOps(workspace) }),\n grep: createGrepTool({ ops: workspaceGrepOps(workspace) }),\n delete: createDeleteTool({ ops: workspaceDeleteOps(workspace) })\n };\n\n if (options.bash !== false) {\n tools.bash = createBashTool({\n ...(typeof options.bash === \"object\" ? options.bash : {}),\n ops: workspaceBashOps(workspace)\n });\n }\n\n return tools;\n}\n\n// ── Read ────────────────────────────────────────────────────────────\n\nconst MAX_LINES = 2000;\nconst MAX_LINE_LENGTH = 2000;\nconst MAX_MODEL_FILE_BYTES = 3.5 * 1024 * 1024;\n\ntype TextReadToolOutput = {\n path: string;\n content: string;\n totalLines: number;\n fromLine?: number;\n toLine?: number;\n};\n\ntype ImageReadToolOutput = {\n kind: \"image\";\n path: string;\n name: string;\n mediaType: string;\n sizeBytes: number;\n};\n\ntype FileReadToolOutput = {\n kind: \"file\";\n path: string;\n name: string;\n mediaType: string;\n sizeBytes: number;\n};\n\ntype BinaryReadToolOutput = {\n kind: \"binary\";\n path: string;\n name: string;\n mediaType: string;\n sizeBytes: number;\n unsupported: true;\n};\n\ntype ReadToolError = { error: string };\n\ntype ReadToolOutput =\n | TextReadToolOutput\n | ImageReadToolOutput\n | FileReadToolOutput\n | BinaryReadToolOutput\n | ReadToolError;\n\ntype ReadToolInput = {\n path: string;\n offset?: number;\n limit?: number;\n};\n\nexport interface ReadToolOptions {\n ops: ReadOperations;\n}\n\nexport function createReadTool(options: ReadToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"Read a workspace file. Text files return line-numbered content. \" +\n \"Images and PDFs are passed to capable models as file content. \" +\n \"Use offset and limit for large text files. Returns null if the file does not exist.\",\n inputSchema: z.object({\n path: z.string().describe(\"Absolute path to the file\"),\n offset: z\n .number()\n .int()\n .min(1)\n .optional()\n .describe(\"1-indexed line number to start reading from\"),\n limit: z\n .number()\n .int()\n .min(1)\n .optional()\n .describe(\"Number of lines to read\")\n }),\n execute: async ({\n path,\n offset,\n limit\n }: ReadToolInput): Promise<ReadToolOutput> => {\n const stat = await ops.stat(path);\n if (!stat) {\n return { error: `File not found: ${path}` };\n }\n if (stat.type === \"directory\") {\n return { error: `${path} is a directory, not a file` };\n }\n\n const mediaType = await detectWorkspaceMediaType({ ops, path, stat });\n\n if (mediaType.startsWith(\"image/\")) {\n return {\n kind: \"image\",\n path,\n name: stat.name,\n mediaType,\n sizeBytes: stat.size\n };\n }\n\n if (mediaType === \"application/pdf\") {\n return {\n kind: \"file\",\n path,\n name: stat.name,\n mediaType,\n sizeBytes: stat.size\n };\n }\n\n if (!isTextMediaType(mediaType)) {\n return {\n kind: \"binary\",\n path,\n name: stat.name,\n mediaType,\n sizeBytes: stat.size,\n unsupported: true\n };\n }\n\n return readTextWithLineNumbers({ ops, path, offset, limit });\n },\n toModelOutput: async ({\n input,\n output\n }: {\n input: unknown;\n output: unknown;\n }) => {\n const replayOutput: unknown = output;\n\n if (!isRecord(replayOutput)) {\n return { type: \"text\", value: String(replayOutput) };\n }\n\n if (typeof replayOutput.error === \"string\") {\n return { type: \"error-text\", value: replayOutput.error };\n }\n\n if (typeof replayOutput.content === \"string\") {\n return { type: \"text\", value: replayOutput.content };\n }\n\n if (replayOutput.kind === \"binary\") {\n return {\n type: \"json\",\n value: toJSONValue(replayOutput)\n };\n }\n\n if (!isModelFileReadOutput(replayOutput)) {\n return {\n type: \"json\",\n value: toJSONValue(replayOutput)\n };\n }\n\n if (!isReadToolInput(input)) {\n return {\n type: \"json\",\n value: toJSONValue(replayOutput)\n };\n }\n\n const bytes = await ops.readFileBytes(input.path);\n if (bytes === null) {\n return {\n type: \"error-text\",\n value: `Could not read file bytes: ${input.path}`\n };\n }\n if (bytes.byteLength > MAX_MODEL_FILE_BYTES) {\n return {\n type: \"error-text\",\n value:\n `Read ${replayOutput.path} (${replayOutput.mediaType}, ${formatSize(bytes.byteLength)}), ` +\n `but it exceeds the ${formatSize(MAX_MODEL_FILE_BYTES)} inline model output limit.`\n };\n }\n\n const data = uint8ArrayToBase64(bytes);\n const note = `Read ${replayOutput.path} (${replayOutput.mediaType}, ${formatSize(bytes.byteLength)}).`;\n\n if (replayOutput.kind === \"image\") {\n return {\n type: \"content\",\n value: [\n { type: \"text\", text: note },\n { type: \"image-data\", data, mediaType: replayOutput.mediaType }\n ]\n };\n }\n\n return {\n type: \"content\",\n value: [\n { type: \"text\", text: note },\n {\n type: \"file-data\",\n data,\n mediaType: replayOutput.mediaType,\n filename: replayOutput.name\n }\n ]\n };\n }\n });\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction isModelFileReadOutput(\n value: Record<string, unknown>\n): value is ImageReadToolOutput | FileReadToolOutput {\n return (\n (value.kind === \"image\" || value.kind === \"file\") &&\n typeof value.path === \"string\" &&\n typeof value.name === \"string\" &&\n typeof value.mediaType === \"string\"\n );\n}\n\nfunction isReadToolInput(value: unknown): value is ReadToolInput {\n return isRecord(value) && typeof value.path === \"string\";\n}\n\nfunction toJSONValue(value: unknown): JSONValue {\n try {\n const json = JSON.stringify(value);\n return json === undefined ? null : (JSON.parse(json) as JSONValue);\n } catch {\n return String(value);\n }\n}\n\nfunction readTextWithLineNumbers({\n ops,\n path,\n offset,\n limit\n}: {\n ops: ReadOperations;\n path: string;\n offset?: number;\n limit?: number;\n}): Promise<TextReadToolOutput | ReadToolError> {\n return Promise.resolve(ops.readFile(path)).then((content) => {\n if (content === null) {\n return { error: `Could not read file: ${path}` };\n }\n\n const allLines = content.split(\"\\n\");\n const totalLines = allLines.length;\n\n // Apply offset/limit\n const startLine = offset ? offset - 1 : 0;\n const endLine = limit ? startLine + limit : allLines.length;\n const lines = allLines.slice(startLine, endLine);\n\n // Format with line numbers, truncate long lines\n const numbered = lines.map((line, i) => {\n const lineNum = startLine + i + 1;\n const truncated =\n line.length > MAX_LINE_LENGTH\n ? line.slice(0, MAX_LINE_LENGTH) + \"... (truncated)\"\n : line;\n return `${lineNum}\\t${truncated}`;\n });\n\n // Truncate if too many lines\n let output: string;\n if (numbered.length > MAX_LINES) {\n output =\n numbered.slice(0, MAX_LINES).join(\"\\n\") +\n `\\n... (${numbered.length - MAX_LINES} more lines truncated)`;\n } else {\n output = numbered.join(\"\\n\");\n }\n\n const result: TextReadToolOutput = {\n path,\n content: output,\n totalLines\n };\n\n if (offset || limit) {\n result.fromLine = startLine + 1;\n result.toLine = Math.min(endLine, totalLines);\n }\n\n return result;\n });\n}\n\nasync function detectWorkspaceMediaType({\n ops,\n path,\n stat\n}: {\n ops: ReadOperations;\n path: string;\n stat: FileInfo;\n}): Promise<string> {\n const statMime = normalizeMediaType(stat.mimeType);\n if (statMime && !isGenericMediaType(statMime)) {\n return statMime;\n }\n\n const bytes = await ops.readFileBytes(path);\n if (bytes === null) {\n return statMime || \"application/octet-stream\";\n }\n\n const sniffed = sniffMediaType(bytes);\n if (sniffed) {\n return sniffed;\n }\n\n return looksLikeText(bytes) ? \"text/plain\" : \"application/octet-stream\";\n}\n\nfunction normalizeMediaType(mediaType: string | undefined): string | null {\n const normalized = mediaType?.split(\";\")[0]?.trim().toLowerCase();\n return normalized || null;\n}\n\nfunction isGenericMediaType(mediaType: string): boolean {\n return (\n mediaType === \"application/octet-stream\" ||\n mediaType === \"binary/octet-stream\"\n );\n}\n\nfunction isTextMediaType(mediaType: string): boolean {\n return (\n mediaType.startsWith(\"text/\") ||\n mediaType === \"application/json\" ||\n mediaType === \"application/javascript\" ||\n mediaType === \"application/typescript\" ||\n mediaType === \"application/xml\" ||\n mediaType === \"application/x-javascript\" ||\n mediaType.endsWith(\"+json\") ||\n mediaType.endsWith(\"+xml\")\n );\n}\n\nfunction sniffMediaType(bytes: Uint8Array): string | null {\n if (startsWith(bytes, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) {\n return \"image/png\";\n }\n if (startsWith(bytes, [0xff, 0xd8, 0xff])) {\n return \"image/jpeg\";\n }\n if (startsWithAscii(bytes, \"GIF87a\") || startsWithAscii(bytes, \"GIF89a\")) {\n return \"image/gif\";\n }\n if (startsWithAscii(bytes, \"RIFF\") && asciiAt(bytes, 8, 12) === \"WEBP\") {\n return \"image/webp\";\n }\n if (startsWithAscii(bytes, \"%PDF-\")) {\n return \"application/pdf\";\n }\n if (looksLikeSvg(bytes)) {\n return \"image/svg+xml\";\n }\n return null;\n}\n\nfunction startsWith(bytes: Uint8Array, prefix: number[]): boolean {\n if (bytes.length < prefix.length) return false;\n return prefix.every((byte, index) => bytes[index] === byte);\n}\n\nfunction startsWithAscii(bytes: Uint8Array, prefix: string): boolean {\n return asciiAt(bytes, 0, prefix.length) === prefix;\n}\n\nfunction asciiAt(bytes: Uint8Array, start: number, end: number): string {\n return String.fromCharCode(...bytes.subarray(start, end));\n}\n\nfunction looksLikeSvg(bytes: Uint8Array): boolean {\n const prefix = new TextDecoder()\n .decode(bytes.subarray(0, Math.min(bytes.length, 512)))\n .trimStart()\n .toLowerCase();\n return prefix.startsWith(\"<svg\") || prefix.includes(\"<svg\");\n}\n\nfunction looksLikeText(bytes: Uint8Array): boolean {\n if (bytes.length === 0) return true;\n if (bytes.includes(0)) return false;\n\n const text = new TextDecoder().decode(bytes.subarray(0, 4096));\n if (text.length === 0) return true;\n\n let replacementChars = 0;\n for (const char of text) {\n if (char === \"\\uFFFD\") {\n replacementChars++;\n }\n }\n return replacementChars / text.length < 0.01;\n}\n\nfunction uint8ArrayToBase64(bytes: Uint8Array): string {\n let binary = \"\";\n const chunkSize = 0x8000;\n for (let i = 0; i < bytes.length; i += chunkSize) {\n binary += String.fromCharCode(...bytes.subarray(i, i + chunkSize));\n }\n return btoa(binary);\n}\n\n// ── Write ───────────────────────────────────────────────────────────\n\nexport interface WriteToolOptions {\n ops: WriteOperations;\n}\n\nexport function createWriteTool(options: WriteToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"Write content to a file. Creates the file if it does not exist, \" +\n \"overwrites if it does. Parent directories are created automatically.\",\n inputSchema: z.object({\n path: z.string().describe(\"Absolute path to the file\"),\n content: z.string().describe(\"Content to write to the file\")\n }),\n execute: async ({ path, content }) => {\n // Ensure parent directory exists\n const parent = path.replace(/\\/[^/]+$/, \"\");\n if (parent && parent !== \"/\") {\n await ops.mkdir(parent, { recursive: true });\n }\n\n await ops.writeFile(path, content);\n\n const lines = content.split(\"\\n\").length;\n return {\n path,\n bytesWritten: new TextEncoder().encode(content).byteLength,\n lines\n };\n }\n });\n}\n\n// ── Edit ────────────────────────────────────────────────────────────\n\nexport interface EditToolOptions {\n ops: EditOperations;\n}\n\nexport function createEditTool(options: EditToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"Make a targeted edit to a file by replacing an exact string match. \" +\n \"Provide the old_string to find and new_string to replace it with. \" +\n \"The old_string must match exactly (including whitespace and indentation). \" +\n \"Use an empty old_string with new_string to create a new file.\",\n inputSchema: z.object({\n path: z.string().describe(\"Absolute path to the file\"),\n old_string: z\n .string()\n .describe(\n \"Exact text to find and replace. Empty string to create a new file.\"\n ),\n new_string: z.string().describe(\"Replacement text\")\n }),\n execute: async ({ path, old_string, new_string }) => {\n // Create new file\n if (old_string === \"\") {\n const existing = await ops.readFile(path);\n if (existing !== null) {\n return {\n error:\n \"File already exists. Provide old_string to edit, or use the write tool to overwrite.\"\n };\n }\n await ops.writeFile(path, new_string);\n return {\n path,\n created: true,\n lines: new_string.split(\"\\n\").length\n };\n }\n\n // Edit existing file\n const content = await ops.readFile(path);\n if (content === null) {\n return { error: `File not found: ${path}` };\n }\n\n // Count occurrences\n const occurrences = countOccurrences(content, old_string);\n if (occurrences === 0) {\n // Try fuzzy match — normalize whitespace and look again\n const fuzzyResult = fuzzyReplace(content, old_string, new_string);\n if (fuzzyResult === \"ambiguous\") {\n return {\n error:\n \"old_string matches multiple locations after whitespace normalization. \" +\n \"Include more surrounding context to make the match unique.\"\n };\n }\n if (fuzzyResult !== null) {\n await ops.writeFile(path, fuzzyResult);\n return {\n path,\n replaced: true,\n fuzzyMatch: true,\n lines: fuzzyResult.split(\"\\n\").length\n };\n }\n\n return {\n error:\n \"old_string not found in file. Make sure it matches exactly, \" +\n \"including whitespace and indentation. Read the file first to verify.\"\n };\n }\n\n if (occurrences > 1) {\n return {\n error:\n `old_string appears ${occurrences} times in the file. ` +\n \"Include more surrounding context to make the match unique.\"\n };\n }\n\n const newContent = content.replace(old_string, new_string);\n await ops.writeFile(path, newContent);\n\n return {\n path,\n replaced: true,\n lines: newContent.split(\"\\n\").length\n };\n }\n });\n}\n\nfunction countOccurrences(text: string, search: string): number {\n let count = 0;\n let pos = 0;\n while (true) {\n const idx = text.indexOf(search, pos);\n if (idx === -1) break;\n count++;\n pos = idx + 1;\n }\n return count;\n}\n\n/**\n * Fuzzy replacement: normalize whitespace in both the file content\n * and the search string, find the match, then replace the corresponding\n * region in the original content.\n */\nfunction fuzzyReplace(\n content: string,\n oldStr: string,\n newStr: string\n): string | \"ambiguous\" | null {\n const normalizedContent = normalizeWhitespace(content);\n const normalizedSearch = normalizeWhitespace(oldStr);\n\n if (!normalizedSearch) return null;\n\n const idx = normalizedContent.indexOf(normalizedSearch);\n if (idx === -1) return null;\n\n // Check for multiple fuzzy matches\n const secondIdx = normalizedContent.indexOf(\n normalizedSearch,\n idx + normalizedSearch.length\n );\n if (secondIdx !== -1) return \"ambiguous\";\n\n // Map the normalized index back to the original content.\n // Walk both strings in parallel to find the original start/end.\n const originalStart = mapToOriginal(content, idx);\n const originalEnd = mapToOriginal(content, idx + normalizedSearch.length);\n\n return content.slice(0, originalStart) + newStr + content.slice(originalEnd);\n}\n\nfunction normalizeWhitespace(s: string): string {\n return s.replace(/[ \\t]+/g, \" \").replace(/\\r\\n/g, \"\\n\");\n}\n\n/**\n * Map a position in the normalized string back to the original string.\n * Walks both strings char-by-char, skipping extra whitespace in the original.\n */\nfunction mapToOriginal(original: string, normalizedPos: number): number {\n let ni = 0;\n let oi = 0;\n\n while (ni < normalizedPos && oi < original.length) {\n const oc = original[oi];\n if (oc === \"\\r\" && original[oi + 1] === \"\\n\") {\n // \\r\\n in original maps to \\n in normalized\n oi += 2;\n ni += 1;\n } else if (oc === \" \" || oc === \"\\t\") {\n // Consume a run of spaces/tabs in original → single space in normalized\n oi++;\n while (\n oi < original.length &&\n (original[oi] === \" \" || original[oi] === \"\\t\")\n ) {\n oi++;\n }\n ni++;\n } else {\n oi++;\n ni++;\n }\n }\n\n return oi;\n}\n\n// ── List ────────────────────────────────────────────────────────────\n\nexport interface ListToolOptions {\n ops: ListOperations;\n}\n\nexport function createListTool(options: ListToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"List files and directories in a given path. \" +\n \"Returns names, types, and sizes for each entry.\",\n inputSchema: z.object({\n path: z\n .string()\n .default(\"/\")\n .describe(\"Absolute path to the directory to list\"),\n limit: z\n .number()\n .int()\n .min(1)\n .max(1000)\n .optional()\n .describe(\"Maximum number of entries to return (default: 200)\"),\n offset: z\n .number()\n .int()\n .min(0)\n .optional()\n .describe(\"Number of entries to skip (for pagination)\")\n }),\n execute: async ({ path, limit, offset }) => {\n const maxEntries = limit ?? 200;\n const entries = await ops.readDir(path, {\n limit: maxEntries,\n offset: offset ?? 0\n });\n\n const formatted = entries.map((entry) => {\n const suffix = entry.type === \"directory\" ? \"/\" : \"\";\n const sizeStr =\n entry.type === \"file\" ? ` (${formatSize(entry.size)})` : \"\";\n return `${entry.name}${suffix}${sizeStr}`;\n });\n\n return {\n path,\n count: entries.length,\n entries: formatted\n };\n }\n });\n}\n\nfunction formatSize(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\n// ── Find ────────────────────────────────────────────────────────────\n\nexport interface FindToolOptions {\n ops: FindOperations;\n}\n\nexport function createFindTool(options: FindToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"Find files matching a glob pattern. \" +\n \"Supports standard glob syntax: * matches any file, ** matches directories recursively, \" +\n \"? matches a single character. Returns matching file paths with types and sizes.\",\n inputSchema: z.object({\n pattern: z\n .string()\n .describe(\n 'Glob pattern to match (e.g. \"**/*.ts\", \"src/**/*.test.ts\", \"*.md\")'\n )\n }),\n execute: async ({ pattern }) => {\n const matches = await ops.glob(pattern);\n\n const MAX_RESULTS = 200;\n const truncated = matches.length > MAX_RESULTS;\n const results = matches.slice(0, MAX_RESULTS);\n\n const formatted = results.map((entry) => {\n const suffix = entry.type === \"directory\" ? \"/\" : \"\";\n return `${entry.path}${suffix}`;\n });\n\n const result: Record<string, unknown> = {\n pattern,\n count: matches.length,\n files: formatted\n };\n\n if (truncated) {\n result.truncated = true;\n result.showing = MAX_RESULTS;\n }\n\n return result;\n }\n });\n}\n\n// ── Grep ────────────────────────────────────────────────────────────\n\nconst MAX_MATCHES = 200;\nconst MAX_FILE_SIZE = 1_048_576; // 1 MB — skip files larger than this in grep\n\nexport interface GrepToolOptions {\n ops: GrepOperations;\n}\n\nexport function createGrepTool(options: GrepToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"Search file contents using a regular expression or fixed string. \" +\n \"Returns matching lines with file paths and line numbers. \" +\n \"Searches all files matching the include glob, or all files if not specified.\",\n inputSchema: z.object({\n query: z.string().describe(\"Search pattern (regex or fixed string)\"),\n include: z\n .string()\n .optional()\n .describe(\n 'Glob pattern to filter files (e.g. \"**/*.ts\"). Defaults to \"**/*\"'\n ),\n fixedString: z\n .boolean()\n .optional()\n .describe(\"If true, treat query as a literal string instead of regex\"),\n caseSensitive: z\n .boolean()\n .optional()\n .describe(\"If true, search is case-sensitive (default: false)\"),\n contextLines: z\n .number()\n .int()\n .min(0)\n .max(10)\n .optional()\n .describe(\"Number of context lines around each match (default: 0)\")\n }),\n execute: async ({\n query,\n include,\n fixedString,\n caseSensitive,\n contextLines\n }) => {\n const pattern = include ?? \"**/*\";\n const allFiles = await ops.glob(pattern);\n const files = allFiles.filter((f: { type: string }) => f.type === \"file\");\n\n let regex: RegExp;\n try {\n const escaped = fixedString ? escapeRegex(query) : query;\n regex = new RegExp(escaped, caseSensitive ? \"g\" : \"gi\");\n } catch {\n return { error: `Invalid regex: ${query}` };\n }\n\n const ctx = contextLines ?? 0;\n const matches: Array<{\n file: string;\n line: number;\n text: string;\n context?: string[];\n }> = [];\n let totalMatches = 0;\n let filesSearched = 0;\n let filesWithMatches = 0;\n\n let filesSkipped = 0;\n\n for (const file of files) {\n if (totalMatches >= MAX_MATCHES) break;\n\n // Skip files larger than 1 MB to avoid memory blowup\n if (file.size > MAX_FILE_SIZE) {\n filesSkipped++;\n continue;\n }\n\n const content = await ops.readFile(file.path);\n if (content === null) continue;\n filesSearched++;\n\n const lines = content.split(\"\\n\");\n let fileHasMatch = false;\n\n for (let i = 0; i < lines.length; i++) {\n if (totalMatches >= MAX_MATCHES) break;\n\n regex.lastIndex = 0;\n if (regex.test(lines[i])) {\n if (!fileHasMatch) {\n fileHasMatch = true;\n filesWithMatches++;\n }\n totalMatches++;\n\n const match: {\n file: string;\n line: number;\n text: string;\n context?: string[];\n } = {\n file: file.path,\n line: i + 1,\n text: lines[i]\n };\n\n if (ctx > 0) {\n const start = Math.max(0, i - ctx);\n const end = Math.min(lines.length, i + ctx + 1);\n match.context = lines.slice(start, end).map((l, j) => {\n const lineNum = start + j + 1;\n const marker = lineNum === i + 1 ? \">\" : \" \";\n return `${marker} ${lineNum}\\t${l}`;\n });\n }\n\n matches.push(match);\n }\n }\n }\n\n const result: Record<string, unknown> = {\n query,\n filesSearched,\n filesWithMatches,\n totalMatches,\n matches: matches.map((m) => {\n if (m.context) {\n return {\n file: m.file,\n line: m.line,\n context: m.context.join(\"\\n\")\n };\n }\n return `${m.file}:${m.line}: ${m.text}`;\n })\n };\n\n if (totalMatches >= MAX_MATCHES) {\n result.truncated = true;\n }\n if (filesSkipped > 0) {\n result.filesSkipped = filesSkipped;\n result.note = `${filesSkipped} file(s) skipped (larger than 1 MB)`;\n }\n\n return result;\n }\n });\n}\n\nfunction escapeRegex(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n// ── Bash ─────────────────────────────────────────────────────────────\n\nconst DEFAULT_BASH_TIMEOUT_MS = 30_000;\nconst DEFAULT_BASH_MAX_WORKSPACE_FILES = 1_000;\nconst DEFAULT_BASH_MAX_WORKSPACE_FILE_BYTES = 1_000_000;\nconst DEFAULT_BASH_MAX_OUTPUT_BYTES = 64_000;\nconst BASH_READDIR_PAGE_SIZE = 1_000;\n// Synthetic paths the bash sandbox creates for itself (shell builtins under\n// /bin and /usr/bin, pseudo-filesystems, scratch space). New files here must\n// never be persisted to the workspace — only pre-existing workspace files\n// under these roots keep syncing.\nconst BASH_EXCLUDED_SYNC_ROOTS = [\"/bin\", \"/usr\", \"/dev\", \"/proc\", \"/sys\"];\n\ntype BashToolInput = {\n script: string;\n cwd?: string;\n};\n\ntype BashChangedFiles = {\n created: string[];\n updated: string[];\n deleted: string[];\n directoriesCreated: string[];\n directoriesDeleted: string[];\n};\n\nexport interface BashToolOptions {\n ops: BashOperations;\n timeout?: number;\n network?: boolean;\n maxWorkspaceFiles?: number;\n maxWorkspaceFileBytes?: number;\n maxOutputBytes?: number;\n}\n\nexport function createBashTool(options: BashToolOptions) {\n return tool({\n description:\n \"Run a Bash script against the workspace. Use for shell-style workflows \" +\n \"that combine multiple file operations. The script runs in a sandboxed \" +\n \"virtual filesystem with the workspace mounted at `/` (also the default \" +\n \"working directory) — there is no `/workspace` or `/home`; use absolute \" +\n \"paths like `/notes.txt`. Changed files are written back to the workspace.\",\n inputSchema: z.object({\n script: z.string().describe(\"Bash script to run\"),\n cwd: z\n .string()\n .optional()\n .describe(\n \"Working directory for the script. Defaults to / (the workspace root)\"\n )\n }),\n execute: async ({ script, cwd }: BashToolInput) => {\n const timeout = options.timeout ?? DEFAULT_BASH_TIMEOUT_MS;\n const maxOutputBytes =\n options.maxOutputBytes ?? DEFAULT_BASH_MAX_OUTPUT_BYTES;\n const snapshot = await snapshotWorkspaceForBash(options);\n const bash = new Bash({\n files: snapshot.files,\n cwd: normalizeWorkspacePath(cwd ?? \"/\"),\n defenseInDepth: true,\n network: options.network ? {} : undefined\n });\n\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeout);\n let result:\n | {\n stdout: string;\n stderr: string;\n exitCode: number;\n }\n | undefined;\n try {\n for (const directory of snapshot.directories) {\n await bash.fs.mkdir(directory, { recursive: true }).catch(() => {});\n }\n\n try {\n result = await bash.exec(script, {\n cwd: normalizeWorkspacePath(cwd ?? \"/\"),\n signal: controller.signal,\n rawScript: true\n });\n } catch (error) {\n result = {\n stdout: \"\",\n stderr: errorMessage(error),\n exitCode: controller.signal.aborted ? 124 : 1\n };\n }\n\n const sync = await syncBashFilesToWorkspace({\n ops: options.ops,\n bash,\n initialFiles: snapshot.initialFiles,\n initialDirectories: snapshot.initialDirectories,\n protectedPaths: snapshot.protectedPaths\n });\n\n return {\n stdout: truncateToolOutput(result.stdout, maxOutputBytes),\n stderr: truncateToolOutput(result.stderr, maxOutputBytes),\n exitCode: result.exitCode,\n changedFiles: sync.changedFiles,\n ...(snapshot.skippedFiles.length > 0\n ? { skippedFiles: snapshot.skippedFiles }\n : {}),\n ...(sync.errors.length > 0 ? { errors: sync.errors } : {})\n };\n } finally {\n clearTimeout(timer);\n }\n }\n });\n}\n\nasync function snapshotWorkspaceForBash(options: BashToolOptions): Promise<{\n files: InitialFiles;\n initialFiles: Map<string, Uint8Array>;\n initialDirectories: Set<string>;\n protectedPaths: Set<string>;\n directories: string[];\n skippedFiles: string[];\n}> {\n const maxFiles =\n options.maxWorkspaceFiles ?? DEFAULT_BASH_MAX_WORKSPACE_FILES;\n const maxFileBytes =\n options.maxWorkspaceFileBytes ?? DEFAULT_BASH_MAX_WORKSPACE_FILE_BYTES;\n const files: InitialFiles = {};\n const initialFiles = new Map<string, Uint8Array>();\n const initialDirectories = new Set<string>([\"/\"]);\n const protectedPaths = new Set<string>();\n const skippedFiles: string[] = [];\n const pending = [\"/\"];\n\n while (pending.length > 0) {\n const dir = pending.shift()!;\n const entries = await readAllBashDirEntries(options.ops, dir);\n for (const entry of entries) {\n const path = normalizeWorkspacePath(entry.path);\n if (entry.type === \"directory\") {\n initialDirectories.add(path);\n pending.push(path);\n continue;\n }\n if (entry.type !== \"file\") continue;\n if (initialFiles.size >= maxFiles || entry.size > maxFileBytes) {\n protectedPaths.add(path);\n skippedFiles.push(path);\n continue;\n }\n const bytes = await options.ops.readFileBytes(path);\n if (bytes === null) {\n protectedPaths.add(path);\n skippedFiles.push(path);\n continue;\n }\n files[path] = bytes;\n initialFiles.set(path, bytes);\n }\n }\n\n return {\n files,\n initialFiles,\n initialDirectories,\n protectedPaths,\n directories: [...initialDirectories].sort((a, b) => a.localeCompare(b)),\n skippedFiles\n };\n}\n\nasync function readAllBashDirEntries(\n ops: BashOperations,\n dir: string\n): Promise<FileInfo[]> {\n const entries: FileInfo[] = [];\n let offset = 0;\n\n while (true) {\n const page = await ops.readDir(dir, {\n limit: BASH_READDIR_PAGE_SIZE,\n offset\n });\n entries.push(...page);\n if (page.length !== BASH_READDIR_PAGE_SIZE) break;\n offset += page.length;\n }\n\n return entries;\n}\n\nasync function syncBashFilesToWorkspace({\n ops,\n bash,\n initialFiles,\n initialDirectories,\n protectedPaths\n}: {\n ops: BashOperations;\n bash: {\n fs: {\n getAllPaths(): string[];\n stat(path: string): Promise<{ isFile: boolean; isDirectory: boolean }>;\n readFileBuffer(path: string): Promise<Uint8Array>;\n };\n };\n initialFiles: Map<string, Uint8Array>;\n initialDirectories: Set<string>;\n protectedPaths: Set<string>;\n}): Promise<{ changedFiles: BashChangedFiles; errors: string[] }> {\n const changedFiles: BashChangedFiles = {\n created: [],\n updated: [],\n deleted: [],\n directoriesCreated: [],\n directoriesDeleted: []\n };\n const errors: string[] = [];\n const finalFiles = new Map<string, Uint8Array>();\n const finalDirectories = new Set<string>([\"/\"]);\n\n for (const rawPath of bash.fs.getAllPaths()) {\n const path = normalizeWorkspacePath(rawPath);\n if (!shouldSyncBashPath(path, initialFiles, protectedPaths)) continue;\n const stat = await bash.fs.stat(path).catch(() => null);\n if (stat?.isDirectory) {\n finalDirectories.add(path);\n continue;\n }\n if (stat?.isFile) {\n finalFiles.set(path, await bash.fs.readFileBuffer(path));\n }\n }\n\n for (const path of [...finalDirectories].sort((a, b) => a.localeCompare(b))) {\n if (path === \"/\" || initialDirectories.has(path)) continue;\n if (hasProtectedDescendant(path, protectedPaths)) {\n errors.push(\n `Skipped creating directory ${path}: contains protected paths.`\n );\n continue;\n }\n const created = await Promise.resolve(ops.mkdir(path, { recursive: true }))\n .then(() => true)\n .catch((error: unknown) => {\n errors.push(\n `Failed to create directory ${path}: ${errorMessage(error)}`\n );\n return false;\n });\n if (!created) continue;\n changedFiles.directoriesCreated.push(path);\n }\n\n for (const [path, bytes] of finalFiles) {\n if (protectedPaths.has(path)) {\n errors.push(`Skipped writing protected workspace file: ${path}`);\n continue;\n }\n const existing = initialFiles.get(path);\n if (existing && bytesEqual(existing, bytes)) continue;\n const written = await writeWorkspaceBytes(ops, path, bytes, errors);\n if (!written) continue;\n if (existing) changedFiles.updated.push(path);\n else changedFiles.created.push(path);\n }\n\n for (const path of [...initialFiles.keys()].sort((a, b) =>\n b.localeCompare(a)\n )) {\n if (finalFiles.has(path) || protectedPaths.has(path)) continue;\n const deleted = await ops\n .rm(path, { force: true })\n .then(() => true)\n .catch((error: unknown) => {\n errors.push(`Failed to delete ${path}: ${errorMessage(error)}`);\n return false;\n });\n if (!deleted) continue;\n changedFiles.deleted.push(path);\n }\n\n for (const path of [...initialDirectories].sort((a, b) =>\n b.localeCompare(a)\n )) {\n if (path === \"/\" || finalDirectories.has(path)) continue;\n if (hasProtectedDescendant(path, protectedPaths)) {\n errors.push(`Skipped deleting protected workspace directory: ${path}`);\n continue;\n }\n const deleted = await ops\n .rm(path, { recursive: true, force: true })\n .then(() => true)\n .catch((error: unknown) => {\n errors.push(\n `Failed to delete directory ${path}: ${errorMessage(error)}`\n );\n return false;\n });\n if (!deleted) continue;\n changedFiles.directoriesDeleted.push(path);\n }\n\n changedFiles.created.sort();\n changedFiles.updated.sort();\n changedFiles.deleted.sort();\n changedFiles.directoriesCreated.sort();\n changedFiles.directoriesDeleted.sort();\n\n return { changedFiles, errors };\n}\n\nasync function writeWorkspaceBytes(\n ops: BashOperations,\n path: string,\n bytes: Uint8Array,\n errors: string[]\n): Promise<boolean> {\n const parent = parentDir(path);\n if (parent !== \"/\") {\n const parentCreated = await Promise.resolve(\n ops.mkdir(parent, { recursive: true })\n )\n .then(() => true)\n .catch((error: unknown) => {\n errors.push(\n `Failed to create parent directory ${parent}: ${errorMessage(error)}`\n );\n return false;\n });\n if (!parentCreated) return false;\n }\n\n if (ops.writeFileBytes) {\n return ops\n .writeFileBytes(path, bytes)\n .then(() => true)\n .catch((error: unknown) => {\n errors.push(`Failed to write ${path}: ${errorMessage(error)}`);\n return false;\n });\n }\n\n if (!looksLikeText(bytes)) {\n errors.push(\n `Could not persist binary file ${path}: workspace does not support writeFileBytes.`\n );\n return false;\n }\n\n const content = new TextDecoder().decode(bytes);\n return ops\n .writeFile(path, content)\n .then(() => true)\n .catch((error: unknown) => {\n errors.push(`Failed to write ${path}: ${errorMessage(error)}`);\n return false;\n });\n}\n\nfunction shouldSyncBashPath(\n path: string,\n initialFiles: Map<string, Uint8Array>,\n protectedPaths: Set<string>\n): boolean {\n if (path === \"/\") return false;\n if (initialFiles.has(path)) return true;\n if (protectedPaths.has(path)) return true;\n if (path === \"/tmp\" || path.startsWith(\"/tmp/\")) return false;\n return !BASH_EXCLUDED_SYNC_ROOTS.some(\n (root) => path === root || path.startsWith(`${root}/`)\n );\n}\n\nfunction hasProtectedDescendant(\n path: string,\n protectedPaths: Set<string>\n): boolean {\n const prefix = path.endsWith(\"/\") ? path : `${path}/`;\n for (const protectedPath of protectedPaths) {\n if (protectedPath.startsWith(prefix)) return true;\n }\n return false;\n}\n\nfunction normalizeWorkspacePath(path: string): string {\n const parts: string[] = [];\n const raw = path.startsWith(\"/\") ? path : `/${path}`;\n for (const part of raw.split(\"/\")) {\n if (!part || part === \".\") continue;\n if (part === \"..\") parts.pop();\n else parts.push(part);\n }\n return `/${parts.join(\"/\")}`;\n}\n\nfunction parentDir(path: string): string {\n const normalized = normalizeWorkspacePath(path);\n const index = normalized.lastIndexOf(\"/\");\n return index <= 0 ? \"/\" : normalized.slice(0, index);\n}\n\nfunction bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n if (a.byteLength !== b.byteLength) return false;\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) return false;\n }\n return true;\n}\n\nfunction truncateToolOutput(value: string, maxBytes: number): string {\n const bytes = new TextEncoder().encode(value);\n if (bytes.byteLength <= maxBytes) return value;\n const truncated = new TextDecoder().decode(bytes.slice(0, maxBytes));\n return `${truncated}\\n... (${formatSize(bytes.byteLength - maxBytes)} truncated)`;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n// ── Delete ──────────────────────────────────────────────────────────\n\nexport interface DeleteToolOptions {\n ops: DeleteOperations;\n}\n\nexport function createDeleteTool(options: DeleteToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"Delete a file or directory. \" +\n \"Set recursive to true to remove non-empty directories.\",\n inputSchema: z.object({\n path: z.string().describe(\"Absolute path to the file or directory\"),\n recursive: z\n .boolean()\n .optional()\n .describe(\"If true, remove directories and their contents recursively\")\n }),\n execute: async ({ path, recursive }) => {\n await ops.rm(path, { recursive, force: true });\n return { deleted: path };\n }\n });\n}\n"],"mappings":";;;;AAgGA,SAAS,iBAAiB,IAAmC;CAC3D,OAAO;EACL,WAAW,SAAS,GAAG,SAAS,IAAI;EACpC,gBAAgB,SAAS,GAAG,cAAc,IAAI;EAC9C,OAAO,SAAS,GAAG,KAAK,IAAI;CAC9B;AACF;AAEA,SAAS,kBAAkB,IAAoC;CAC7D,OAAO;EACL,YAAY,MAAM,YAAY,GAAG,UAAU,MAAM,OAAO;EACxD,QAAQ,MAAM,SAAS,GAAG,MAAM,MAAM,IAAI;CAC5C;AACF;AAEA,SAAS,iBAAiB,IAAmC;CAC3D,OAAO;EACL,WAAW,SAAS,GAAG,SAAS,IAAI;EACpC,YAAY,MAA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AE,OAAO;GACpB,MAAM,EAAE,OAAO,CAAC,CAAC,SAAS,wCAAwC;GAClE,WAAW,EACR,QAAQ,CAAC,CACT,SAAS,CAAC,CACV,SAAS,4DAA4D;EAC1E,CAAC;EACD,SAAS,OAAO,EAAE,MAAM,gBAAgB;GACtC,MAAM,IAAI,GAAG,MAAM;IAAE;IAAW,OAAO;GAAK,CAAC;GAC7C,OAAO,EAAE,SAAS,KAAK;EACzB;CACF,CAAC;AACH"}
1
+ {"version":3,"file":"workspace.js","names":[],"sources":["../../src/tools/workspace.ts"],"sourcesContent":["import type { Workspace, FileInfo } from \"@cloudflare/shell\";\nimport type { JSONValue } from \"ai\";\nimport type { InitialFiles } from \"just-bash\";\nimport { Bash } from \"just-bash\";\nimport { tool } from \"ai\";\nimport { z } from \"zod\";\n\n// ── WorkspaceLike ─────────────────────────────────────────────────\n//\n// Minimum workspace surface that Think's internals rely on. Covers the\n// methods called by `createWorkspaceTools()` below plus the handful\n// Think itself uses (`readFile`/`writeFile`/`readDir`/`rm` in\n// `think.ts`). The read tool also needs `readFileBytes` so image/PDF\n// reads can be rehydrated as AI SDK multimodal content. A concrete\n// `Workspace` from `@cloudflare/shell` satisfies this; so do custom\n// implementations like the `SharedWorkspace` proxy in `examples/assistant`\n// that forwards to a parent DO.\n//\n// Consumers who reach for the fuller filesystem API (e.g.\n// `createWorkspaceStateBackend` for codemode's `state.*` in a sandbox)\n// still need a concrete `Workspace`.\n//\n// @experimental The API surface may change before stabilizing.\n\nexport type WorkspaceLike = Pick<\n Workspace,\n | \"readFile\"\n | \"readFileBytes\"\n | \"writeFile\"\n | \"readDir\"\n | \"rm\"\n | \"glob\"\n | \"mkdir\"\n | \"stat\"\n>;\n\n// ── Operations interfaces ─────────────────────────────────────────\n// Abstractions over file I/O so the same tools can work against\n// Workspace, a local filesystem, or anything else.\n\nexport interface ReadOperations {\n readFile(path: string): Promise<string | null>;\n readFileBytes(path: string): Promise<Uint8Array | null>;\n stat(path: string): Promise<FileInfo | null> | FileInfo | null;\n}\n\nexport interface WriteOperations {\n writeFile(path: string, content: string): Promise<void>;\n mkdir(path: string, opts?: { recursive?: boolean }): Promise<void> | void;\n}\n\nexport interface EditOperations {\n readFile(path: string): Promise<string | null>;\n writeFile(path: string, content: string): Promise<void>;\n}\n\nexport interface ListOperations {\n readDir(\n dir: string,\n opts?: { limit?: number; offset?: number }\n ): Promise<FileInfo[]> | FileInfo[];\n}\n\nexport interface FindOperations {\n glob(pattern: string): Promise<FileInfo[]> | FileInfo[];\n}\n\nexport interface DeleteOperations {\n rm(\n path: string,\n opts?: { recursive?: boolean; force?: boolean }\n ): Promise<void>;\n}\n\nexport interface GrepOperations {\n glob(pattern: string): Promise<FileInfo[]> | FileInfo[];\n readFile(path: string): Promise<string | null>;\n}\n\nexport interface BashOperations {\n readDir(\n dir: string,\n opts?: { limit?: number; offset?: number }\n ): Promise<FileInfo[]> | FileInfo[];\n readFileBytes(path: string): Promise<Uint8Array | null>;\n writeFile(path: string, content: string): Promise<void>;\n writeFileBytes?: (path: string, content: Uint8Array) => Promise<void>;\n mkdir(path: string, opts?: { recursive?: boolean }): Promise<void> | void;\n rm(\n path: string,\n opts?: { recursive?: boolean; force?: boolean }\n ): Promise<void>;\n}\n\n// ── Workspace-backed operation factories ──────────────────────────\n\nfunction workspaceReadOps(ws: WorkspaceLike): ReadOperations {\n return {\n readFile: (path) => ws.readFile(path),\n readFileBytes: (path) => ws.readFileBytes(path),\n stat: (path) => ws.stat(path)\n };\n}\n\nfunction workspaceWriteOps(ws: WorkspaceLike): WriteOperations {\n return {\n writeFile: (path, content) => ws.writeFile(path, content),\n mkdir: (path, opts) => ws.mkdir(path, opts)\n };\n}\n\nfunction workspaceEditOps(ws: WorkspaceLike): EditOperations {\n return {\n readFile: (path) => ws.readFile(path),\n writeFile: (path, content) => ws.writeFile(path, content)\n };\n}\n\nfunction workspaceListOps(ws: WorkspaceLike): ListOperations {\n return {\n readDir: (dir, opts) => ws.readDir(dir, opts)\n };\n}\n\nfunction workspaceFindOps(ws: WorkspaceLike): FindOperations {\n return {\n glob: (pattern) => ws.glob(pattern)\n };\n}\n\nfunction workspaceDeleteOps(ws: WorkspaceLike): DeleteOperations {\n return {\n rm: (path, opts) => ws.rm(path, opts)\n };\n}\n\nfunction workspaceGrepOps(ws: WorkspaceLike): GrepOperations {\n return {\n glob: (pattern) => ws.glob(pattern),\n readFile: (path) => ws.readFile(path)\n };\n}\n\nfunction workspaceBashOps(ws: WorkspaceLike): BashOperations {\n const maybeBytesWriter = ws as WorkspaceLike & {\n writeFileBytes?: (path: string, content: Uint8Array) => Promise<void>;\n };\n return {\n readDir: (dir, opts) => ws.readDir(dir, opts),\n readFileBytes: (path) => ws.readFileBytes(path),\n writeFile: (path, content) => ws.writeFile(path, content),\n writeFileBytes: maybeBytesWriter.writeFileBytes\n ? (path, content) => maybeBytesWriter.writeFileBytes!(path, content)\n : undefined,\n mkdir: (path, opts) => ws.mkdir(path, opts),\n rm: (path, opts) => ws.rm(path, opts)\n };\n}\n\nexport interface WorkspaceToolsOptions {\n /**\n * Include the default workspace Bash tool. Enabled by default; pass `false`\n * to omit it, or an options object to tune execution limits.\n */\n bash?: boolean | Omit<BashToolOptions, \"ops\">;\n}\n\nexport type WorkspaceTools = {\n read: ReturnType<typeof createReadTool>;\n write: ReturnType<typeof createWriteTool>;\n edit: ReturnType<typeof createEditTool>;\n list: ReturnType<typeof createListTool>;\n find: ReturnType<typeof createFindTool>;\n grep: ReturnType<typeof createGrepTool>;\n delete: ReturnType<typeof createDeleteTool>;\n bash?: ReturnType<typeof createBashTool>;\n};\n\n/**\n * Create a complete set of AI SDK tools backed by a workspace.\n *\n * Accepts either a concrete `Workspace` from `@cloudflare/shell` or any\n * `WorkspaceLike` implementation — e.g. a proxy that forwards calls to a\n * shared workspace owned by a parent DO.\n *\n * ```ts\n * import { Workspace } from \"@cloudflare/shell\";\n * import { createWorkspaceTools } from \"@cloudflare/think\";\n *\n * class MyAgent extends Agent<Env> {\n * workspace = new Workspace({ sql: this.ctx.storage.sql, name: () => this.name });\n *\n * async onChatMessage() {\n * const tools = createWorkspaceTools(this.workspace);\n * const result = streamText({ model, tools, messages });\n * return result.toUIMessageStreamResponse();\n * }\n * }\n * ```\n */\nexport function createWorkspaceTools(\n workspace: WorkspaceLike,\n options: WorkspaceToolsOptions = {}\n): WorkspaceTools {\n const tools: WorkspaceTools = {\n read: createReadTool({ ops: workspaceReadOps(workspace) }),\n write: createWriteTool({ ops: workspaceWriteOps(workspace) }),\n edit: createEditTool({ ops: workspaceEditOps(workspace) }),\n list: createListTool({ ops: workspaceListOps(workspace) }),\n find: createFindTool({ ops: workspaceFindOps(workspace) }),\n grep: createGrepTool({ ops: workspaceGrepOps(workspace) }),\n delete: createDeleteTool({ ops: workspaceDeleteOps(workspace) })\n };\n\n if (options.bash !== false) {\n tools.bash = createBashTool({\n ...(typeof options.bash === \"object\" ? options.bash : {}),\n ops: workspaceBashOps(workspace)\n });\n }\n\n return tools;\n}\n\n// ── Read ────────────────────────────────────────────────────────────\n\nconst MAX_LINES = 2000;\nconst MAX_LINE_LENGTH = 2000;\nconst MAX_MODEL_FILE_BYTES = 3.5 * 1024 * 1024;\n\ntype TextReadToolOutput = {\n path: string;\n content: string;\n totalLines: number;\n fromLine?: number;\n toLine?: number;\n};\n\ntype ImageReadToolOutput = {\n kind: \"image\";\n path: string;\n name: string;\n mediaType: string;\n sizeBytes: number;\n};\n\ntype FileReadToolOutput = {\n kind: \"file\";\n path: string;\n name: string;\n mediaType: string;\n sizeBytes: number;\n};\n\ntype BinaryReadToolOutput = {\n kind: \"binary\";\n path: string;\n name: string;\n mediaType: string;\n sizeBytes: number;\n unsupported: true;\n};\n\ntype ReadToolError = { error: string };\n\ntype ReadToolOutput =\n | TextReadToolOutput\n | ImageReadToolOutput\n | FileReadToolOutput\n | BinaryReadToolOutput\n | ReadToolError;\n\ntype ReadToolInput = {\n path: string;\n offset?: number;\n limit?: number;\n};\n\nexport interface ReadToolOptions {\n ops: ReadOperations;\n}\n\nexport function createReadTool(options: ReadToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"Read a workspace file. Text files return line-numbered content. \" +\n \"Images and PDFs are passed to capable models as file content. \" +\n \"Use offset and limit for large text files. Returns null if the file does not exist.\",\n inputSchema: z.object({\n path: z.string().describe(\"Absolute path to the file\"),\n offset: z\n .number()\n .int()\n .min(1)\n .optional()\n .describe(\"1-indexed line number to start reading from\"),\n limit: z\n .number()\n .int()\n .min(1)\n .optional()\n .describe(\"Number of lines to read\")\n }),\n execute: async ({\n path,\n offset,\n limit\n }: ReadToolInput): Promise<ReadToolOutput> => {\n const stat = await ops.stat(path);\n if (!stat) {\n return { error: `File not found: ${path}` };\n }\n if (stat.type === \"directory\") {\n return { error: `${path} is a directory, not a file` };\n }\n\n const mediaType = await detectWorkspaceMediaType({ ops, path, stat });\n\n if (mediaType.startsWith(\"image/\")) {\n return {\n kind: \"image\",\n path,\n name: stat.name,\n mediaType,\n sizeBytes: stat.size\n };\n }\n\n if (mediaType === \"application/pdf\") {\n return {\n kind: \"file\",\n path,\n name: stat.name,\n mediaType,\n sizeBytes: stat.size\n };\n }\n\n if (!isTextMediaType(mediaType)) {\n return {\n kind: \"binary\",\n path,\n name: stat.name,\n mediaType,\n sizeBytes: stat.size,\n unsupported: true\n };\n }\n\n return readTextWithLineNumbers({ ops, path, offset, limit });\n },\n toModelOutput: async ({\n input,\n output\n }: {\n input: unknown;\n output: unknown;\n }) => {\n const replayOutput: unknown = output;\n\n if (!isRecord(replayOutput)) {\n return { type: \"text\", value: String(replayOutput) };\n }\n\n if (typeof replayOutput.error === \"string\") {\n return { type: \"error-text\", value: replayOutput.error };\n }\n\n if (typeof replayOutput.content === \"string\") {\n return { type: \"text\", value: replayOutput.content };\n }\n\n if (replayOutput.kind === \"binary\") {\n return {\n type: \"json\",\n value: toJSONValue(replayOutput)\n };\n }\n\n if (!isModelFileReadOutput(replayOutput)) {\n return {\n type: \"json\",\n value: toJSONValue(replayOutput)\n };\n }\n\n if (!isReadToolInput(input)) {\n return {\n type: \"json\",\n value: toJSONValue(replayOutput)\n };\n }\n\n const bytes = await ops.readFileBytes(input.path);\n if (bytes === null) {\n return {\n type: \"error-text\",\n value: `Could not read file bytes: ${input.path}`\n };\n }\n if (bytes.byteLength > MAX_MODEL_FILE_BYTES) {\n return {\n type: \"error-text\",\n value:\n `Read ${replayOutput.path} (${replayOutput.mediaType}, ${formatSize(bytes.byteLength)}), ` +\n `but it exceeds the ${formatSize(MAX_MODEL_FILE_BYTES)} inline model output limit.`\n };\n }\n\n const data = uint8ArrayToBase64(bytes);\n const note = `Read ${replayOutput.path} (${replayOutput.mediaType}, ${formatSize(bytes.byteLength)}).`;\n\n if (replayOutput.kind === \"image\") {\n return {\n type: \"content\",\n value: [\n { type: \"text\", text: note },\n { type: \"image-data\", data, mediaType: replayOutput.mediaType }\n ]\n };\n }\n\n return {\n type: \"content\",\n value: [\n { type: \"text\", text: note },\n {\n type: \"file-data\",\n data,\n mediaType: replayOutput.mediaType,\n filename: replayOutput.name\n }\n ]\n };\n }\n });\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction isModelFileReadOutput(\n value: Record<string, unknown>\n): value is ImageReadToolOutput | FileReadToolOutput {\n return (\n (value.kind === \"image\" || value.kind === \"file\") &&\n typeof value.path === \"string\" &&\n typeof value.name === \"string\" &&\n typeof value.mediaType === \"string\"\n );\n}\n\nfunction isReadToolInput(value: unknown): value is ReadToolInput {\n return isRecord(value) && typeof value.path === \"string\";\n}\n\nfunction toJSONValue(value: unknown): JSONValue {\n try {\n const json = JSON.stringify(value);\n return json === undefined ? null : (JSON.parse(json) as JSONValue);\n } catch {\n return String(value);\n }\n}\n\nfunction readTextWithLineNumbers({\n ops,\n path,\n offset,\n limit\n}: {\n ops: ReadOperations;\n path: string;\n offset?: number;\n limit?: number;\n}): Promise<TextReadToolOutput | ReadToolError> {\n return Promise.resolve(ops.readFile(path)).then((content) => {\n if (content === null) {\n return { error: `Could not read file: ${path}` };\n }\n\n const allLines = content.split(\"\\n\");\n const totalLines = allLines.length;\n\n // Apply offset/limit\n const startLine = offset ? offset - 1 : 0;\n const endLine = limit ? startLine + limit : allLines.length;\n const lines = allLines.slice(startLine, endLine);\n\n // Format with line numbers, truncate long lines\n const numbered = lines.map((line, i) => {\n const lineNum = startLine + i + 1;\n const truncated =\n line.length > MAX_LINE_LENGTH\n ? line.slice(0, MAX_LINE_LENGTH) + \"... (truncated)\"\n : line;\n return `${lineNum}\\t${truncated}`;\n });\n\n // Truncate if too many lines\n let output: string;\n if (numbered.length > MAX_LINES) {\n output =\n numbered.slice(0, MAX_LINES).join(\"\\n\") +\n `\\n... (${numbered.length - MAX_LINES} more lines truncated)`;\n } else {\n output = numbered.join(\"\\n\");\n }\n\n const result: TextReadToolOutput = {\n path,\n content: output,\n totalLines\n };\n\n if (offset || limit) {\n result.fromLine = startLine + 1;\n result.toLine = Math.min(endLine, totalLines);\n }\n\n return result;\n });\n}\n\nasync function detectWorkspaceMediaType({\n ops,\n path,\n stat\n}: {\n ops: ReadOperations;\n path: string;\n stat: FileInfo;\n}): Promise<string> {\n const statMime = normalizeMediaType(stat.mimeType);\n if (statMime && !isGenericMediaType(statMime)) {\n return statMime;\n }\n\n const bytes = await ops.readFileBytes(path);\n if (bytes === null) {\n return statMime || \"application/octet-stream\";\n }\n\n const sniffed = sniffMediaType(bytes);\n if (sniffed) {\n return sniffed;\n }\n\n return looksLikeText(bytes) ? \"text/plain\" : \"application/octet-stream\";\n}\n\nfunction normalizeMediaType(mediaType: string | undefined): string | null {\n const normalized = mediaType?.split(\";\")[0]?.trim().toLowerCase();\n return normalized || null;\n}\n\nfunction isGenericMediaType(mediaType: string): boolean {\n return (\n mediaType === \"application/octet-stream\" ||\n mediaType === \"binary/octet-stream\"\n );\n}\n\nfunction isTextMediaType(mediaType: string): boolean {\n return (\n mediaType.startsWith(\"text/\") ||\n mediaType === \"application/json\" ||\n mediaType === \"application/javascript\" ||\n mediaType === \"application/typescript\" ||\n mediaType === \"application/xml\" ||\n mediaType === \"application/x-javascript\" ||\n mediaType.endsWith(\"+json\") ||\n mediaType.endsWith(\"+xml\")\n );\n}\n\nfunction sniffMediaType(bytes: Uint8Array): string | null {\n if (startsWith(bytes, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) {\n return \"image/png\";\n }\n if (startsWith(bytes, [0xff, 0xd8, 0xff])) {\n return \"image/jpeg\";\n }\n if (startsWithAscii(bytes, \"GIF87a\") || startsWithAscii(bytes, \"GIF89a\")) {\n return \"image/gif\";\n }\n if (startsWithAscii(bytes, \"RIFF\") && asciiAt(bytes, 8, 12) === \"WEBP\") {\n return \"image/webp\";\n }\n if (startsWithAscii(bytes, \"%PDF-\")) {\n return \"application/pdf\";\n }\n if (looksLikeSvg(bytes)) {\n return \"image/svg+xml\";\n }\n return null;\n}\n\nfunction startsWith(bytes: Uint8Array, prefix: number[]): boolean {\n if (bytes.length < prefix.length) return false;\n return prefix.every((byte, index) => bytes[index] === byte);\n}\n\nfunction startsWithAscii(bytes: Uint8Array, prefix: string): boolean {\n return asciiAt(bytes, 0, prefix.length) === prefix;\n}\n\nfunction asciiAt(bytes: Uint8Array, start: number, end: number): string {\n return String.fromCharCode(...bytes.subarray(start, end));\n}\n\nfunction looksLikeSvg(bytes: Uint8Array): boolean {\n const prefix = new TextDecoder()\n .decode(bytes.subarray(0, Math.min(bytes.length, 512)))\n .trimStart()\n .toLowerCase();\n return prefix.startsWith(\"<svg\") || prefix.includes(\"<svg\");\n}\n\nfunction looksLikeText(bytes: Uint8Array): boolean {\n if (bytes.length === 0) return true;\n if (bytes.includes(0)) return false;\n\n const text = new TextDecoder().decode(bytes.subarray(0, 4096));\n if (text.length === 0) return true;\n\n let replacementChars = 0;\n for (const char of text) {\n if (char === \"\\uFFFD\") {\n replacementChars++;\n }\n }\n return replacementChars / text.length < 0.01;\n}\n\nfunction uint8ArrayToBase64(bytes: Uint8Array): string {\n let binary = \"\";\n const chunkSize = 0x8000;\n for (let i = 0; i < bytes.length; i += chunkSize) {\n binary += String.fromCharCode(...bytes.subarray(i, i + chunkSize));\n }\n return btoa(binary);\n}\n\n// ── Write ───────────────────────────────────────────────────────────\n\nexport interface WriteToolOptions {\n ops: WriteOperations;\n}\n\nexport function createWriteTool(options: WriteToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"Write content to a file. Creates the file if it does not exist, \" +\n \"overwrites if it does. Parent directories are created automatically.\",\n inputSchema: z.object({\n path: z.string().describe(\"Absolute path to the file\"),\n content: z.string().describe(\"Content to write to the file\")\n }),\n execute: async ({ path, content }) => {\n // Ensure parent directory exists\n const parent = path.replace(/\\/[^/]+$/, \"\");\n if (parent && parent !== \"/\") {\n await ops.mkdir(parent, { recursive: true });\n }\n\n await ops.writeFile(path, content);\n\n const lines = content.split(\"\\n\").length;\n return {\n path,\n bytesWritten: new TextEncoder().encode(content).byteLength,\n lines\n };\n }\n });\n}\n\n// ── Edit ────────────────────────────────────────────────────────────\n\nexport interface EditToolOptions {\n ops: EditOperations;\n}\n\nexport function createEditTool(options: EditToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"Make a targeted edit to a file by replacing an exact string match. \" +\n \"Provide the old_string to find and new_string to replace it with. \" +\n \"The old_string must match exactly (including whitespace and indentation). \" +\n \"Use an empty old_string with new_string to create a new file.\",\n inputSchema: z.object({\n path: z.string().describe(\"Absolute path to the file\"),\n old_string: z\n .string()\n .describe(\n \"Exact text to find and replace. Empty string to create a new file.\"\n ),\n new_string: z.string().describe(\"Replacement text\")\n }),\n execute: async ({ path, old_string, new_string }) => {\n // Create new file\n if (old_string === \"\") {\n const existing = await ops.readFile(path);\n if (existing !== null) {\n return {\n error:\n \"File already exists. Provide old_string to edit, or use the write tool to overwrite.\"\n };\n }\n await ops.writeFile(path, new_string);\n return {\n path,\n created: true,\n lines: new_string.split(\"\\n\").length\n };\n }\n\n // Edit existing file\n const content = await ops.readFile(path);\n if (content === null) {\n return { error: `File not found: ${path}` };\n }\n\n // Count occurrences\n const occurrences = countOccurrences(content, old_string);\n if (occurrences === 0) {\n // Try fuzzy match — normalize whitespace and look again\n const fuzzyResult = fuzzyReplace(content, old_string, new_string);\n if (fuzzyResult === \"ambiguous\") {\n return {\n error:\n \"old_string matches multiple locations after whitespace normalization. \" +\n \"Include more surrounding context to make the match unique.\"\n };\n }\n if (fuzzyResult !== null) {\n await ops.writeFile(path, fuzzyResult);\n return {\n path,\n replaced: true,\n fuzzyMatch: true,\n lines: fuzzyResult.split(\"\\n\").length\n };\n }\n\n return {\n error:\n \"old_string not found in file. Make sure it matches exactly, \" +\n \"including whitespace and indentation. Read the file first to verify.\"\n };\n }\n\n if (occurrences > 1) {\n return {\n error:\n `old_string appears ${occurrences} times in the file. ` +\n \"Include more surrounding context to make the match unique.\"\n };\n }\n\n const newContent = content.replace(old_string, new_string);\n await ops.writeFile(path, newContent);\n\n return {\n path,\n replaced: true,\n lines: newContent.split(\"\\n\").length\n };\n }\n });\n}\n\nfunction countOccurrences(text: string, search: string): number {\n let count = 0;\n let pos = 0;\n while (true) {\n const idx = text.indexOf(search, pos);\n if (idx === -1) break;\n count++;\n pos = idx + 1;\n }\n return count;\n}\n\n/**\n * Fuzzy replacement: normalize whitespace in both the file content\n * and the search string, find the match, then replace the corresponding\n * region in the original content.\n */\nfunction fuzzyReplace(\n content: string,\n oldStr: string,\n newStr: string\n): string | \"ambiguous\" | null {\n const normalizedContent = normalizeWhitespace(content);\n const normalizedSearch = normalizeWhitespace(oldStr);\n\n if (!normalizedSearch) return null;\n\n const idx = normalizedContent.indexOf(normalizedSearch);\n if (idx === -1) return null;\n\n // Check for multiple fuzzy matches\n const secondIdx = normalizedContent.indexOf(\n normalizedSearch,\n idx + normalizedSearch.length\n );\n if (secondIdx !== -1) return \"ambiguous\";\n\n // Map the normalized index back to the original content.\n // Walk both strings in parallel to find the original start/end.\n const originalStart = mapToOriginal(content, idx);\n const originalEnd = mapToOriginal(content, idx + normalizedSearch.length);\n\n return content.slice(0, originalStart) + newStr + content.slice(originalEnd);\n}\n\nfunction normalizeWhitespace(s: string): string {\n return s.replace(/[ \\t]+/g, \" \").replace(/\\r\\n/g, \"\\n\");\n}\n\n/**\n * Map a position in the normalized string back to the original string.\n * Walks both strings char-by-char, skipping extra whitespace in the original.\n */\nfunction mapToOriginal(original: string, normalizedPos: number): number {\n let ni = 0;\n let oi = 0;\n\n while (ni < normalizedPos && oi < original.length) {\n const oc = original[oi];\n if (oc === \"\\r\" && original[oi + 1] === \"\\n\") {\n // \\r\\n in original maps to \\n in normalized\n oi += 2;\n ni += 1;\n } else if (oc === \" \" || oc === \"\\t\") {\n // Consume a run of spaces/tabs in original → single space in normalized\n oi++;\n while (\n oi < original.length &&\n (original[oi] === \" \" || original[oi] === \"\\t\")\n ) {\n oi++;\n }\n ni++;\n } else {\n oi++;\n ni++;\n }\n }\n\n return oi;\n}\n\n// ── List ────────────────────────────────────────────────────────────\n\nexport interface ListToolOptions {\n ops: ListOperations;\n}\n\nexport function createListTool(options: ListToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"List files and directories in a given path. \" +\n \"Returns names, types, and sizes for each entry.\",\n inputSchema: z.object({\n path: z\n .string()\n .default(\"/\")\n .describe(\"Absolute path to the directory to list\"),\n limit: z\n .number()\n .int()\n .min(1)\n .max(1000)\n .optional()\n .describe(\"Maximum number of entries to return (default: 200)\"),\n offset: z\n .number()\n .int()\n .min(0)\n .optional()\n .describe(\"Number of entries to skip (for pagination)\")\n }),\n execute: async ({ path, limit, offset }) => {\n const maxEntries = limit ?? 200;\n const entries = await ops.readDir(path, {\n limit: maxEntries,\n offset: offset ?? 0\n });\n\n const formatted = entries.map((entry) => {\n const suffix = entry.type === \"directory\" ? \"/\" : \"\";\n const sizeStr =\n entry.type === \"file\" ? ` (${formatSize(entry.size)})` : \"\";\n return `${entry.name}${suffix}${sizeStr}`;\n });\n\n return {\n path,\n count: entries.length,\n entries: formatted\n };\n }\n });\n}\n\nfunction formatSize(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\n// ── Find ────────────────────────────────────────────────────────────\n\nexport interface FindToolOptions {\n ops: FindOperations;\n}\n\nexport function createFindTool(options: FindToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"Find files matching a glob pattern. \" +\n \"Supports standard glob syntax: * matches any file, ** matches directories recursively, \" +\n \"? matches a single character. Returns matching file paths with types and sizes.\",\n inputSchema: z.object({\n pattern: z\n .string()\n .describe(\n 'Glob pattern to match (e.g. \"**/*.ts\", \"src/**/*.test.ts\", \"*.md\")'\n )\n }),\n execute: async ({ pattern }) => {\n const matches = await ops.glob(pattern);\n\n const MAX_RESULTS = 200;\n const truncated = matches.length > MAX_RESULTS;\n const results = matches.slice(0, MAX_RESULTS);\n\n const formatted = results.map((entry) => {\n const suffix = entry.type === \"directory\" ? \"/\" : \"\";\n return `${entry.path}${suffix}`;\n });\n\n const result: Record<string, unknown> = {\n pattern,\n count: matches.length,\n files: formatted\n };\n\n if (truncated) {\n result.truncated = true;\n result.showing = MAX_RESULTS;\n }\n\n return result;\n }\n });\n}\n\n// ── Grep ────────────────────────────────────────────────────────────\n\nconst MAX_MATCHES = 200;\nconst MAX_FILE_SIZE = 1_048_576; // 1 MB — skip files larger than this in grep\n\nexport interface GrepToolOptions {\n ops: GrepOperations;\n}\n\nexport function createGrepTool(options: GrepToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"Search file contents using a regular expression or fixed string. \" +\n \"Returns matching lines with file paths and line numbers. \" +\n \"Searches all files matching the include glob, or all files if not specified.\",\n inputSchema: z.object({\n query: z.string().describe(\"Search pattern (regex or fixed string)\"),\n include: z\n .string()\n .optional()\n .describe(\n 'Glob pattern to filter files (e.g. \"**/*.ts\"). Defaults to \"**/*\"'\n ),\n fixedString: z\n .boolean()\n .optional()\n .describe(\"If true, treat query as a literal string instead of regex\"),\n caseSensitive: z\n .boolean()\n .optional()\n .describe(\"If true, search is case-sensitive (default: false)\"),\n contextLines: z\n .number()\n .int()\n .min(0)\n .max(10)\n .optional()\n .describe(\"Number of context lines around each match (default: 0)\")\n }),\n execute: async ({\n query,\n include,\n fixedString,\n caseSensitive,\n contextLines\n }) => {\n const pattern = include ?? \"**/*\";\n const allFiles = await ops.glob(pattern);\n const files = allFiles.filter((f: { type: string }) => f.type === \"file\");\n\n let regex: RegExp;\n try {\n const escaped = fixedString ? escapeRegex(query) : query;\n regex = new RegExp(escaped, caseSensitive ? \"g\" : \"gi\");\n } catch {\n return { error: `Invalid regex: ${query}` };\n }\n\n const ctx = contextLines ?? 0;\n const matches: Array<{\n file: string;\n line: number;\n text: string;\n context?: string[];\n }> = [];\n let totalMatches = 0;\n let filesSearched = 0;\n let filesWithMatches = 0;\n\n let filesSkipped = 0;\n\n for (const file of files) {\n if (totalMatches >= MAX_MATCHES) break;\n\n // Skip files larger than 1 MB to avoid memory blowup\n if (file.size > MAX_FILE_SIZE) {\n filesSkipped++;\n continue;\n }\n\n const content = await ops.readFile(file.path);\n if (content === null) continue;\n filesSearched++;\n\n const lines = content.split(\"\\n\");\n let fileHasMatch = false;\n\n for (let i = 0; i < lines.length; i++) {\n if (totalMatches >= MAX_MATCHES) break;\n\n regex.lastIndex = 0;\n if (regex.test(lines[i])) {\n if (!fileHasMatch) {\n fileHasMatch = true;\n filesWithMatches++;\n }\n totalMatches++;\n\n const match: {\n file: string;\n line: number;\n text: string;\n context?: string[];\n } = {\n file: file.path,\n line: i + 1,\n text: lines[i]\n };\n\n if (ctx > 0) {\n const start = Math.max(0, i - ctx);\n const end = Math.min(lines.length, i + ctx + 1);\n match.context = lines.slice(start, end).map((l, j) => {\n const lineNum = start + j + 1;\n const marker = lineNum === i + 1 ? \">\" : \" \";\n return `${marker} ${lineNum}\\t${l}`;\n });\n }\n\n matches.push(match);\n }\n }\n }\n\n const result: Record<string, unknown> = {\n query,\n filesSearched,\n filesWithMatches,\n totalMatches,\n matches: matches.map((m) => {\n if (m.context) {\n return {\n file: m.file,\n line: m.line,\n context: m.context.join(\"\\n\")\n };\n }\n return `${m.file}:${m.line}: ${m.text}`;\n })\n };\n\n if (totalMatches >= MAX_MATCHES) {\n result.truncated = true;\n }\n if (filesSkipped > 0) {\n result.filesSkipped = filesSkipped;\n result.note = `${filesSkipped} file(s) skipped (larger than 1 MB)`;\n }\n\n return result;\n }\n });\n}\n\nfunction escapeRegex(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n// ── Bash ─────────────────────────────────────────────────────────────\n\nconst DEFAULT_BASH_TIMEOUT_MS = 30_000;\nconst DEFAULT_BASH_MAX_WORKSPACE_FILES = 1_000;\nconst DEFAULT_BASH_MAX_WORKSPACE_FILE_BYTES = 1_000_000;\nconst DEFAULT_BASH_MAX_OUTPUT_BYTES = 64_000;\nconst BASH_READDIR_PAGE_SIZE = 1_000;\n// Synthetic paths the bash sandbox creates for itself (shell builtins under\n// /bin and /usr/bin, pseudo-filesystems, scratch space). New files here must\n// never be persisted to the workspace — only pre-existing workspace files\n// under these roots keep syncing.\nconst BASH_EXCLUDED_SYNC_ROOTS = [\"/bin\", \"/usr\", \"/dev\", \"/proc\", \"/sys\"];\n\ntype BashToolInput = {\n script: string;\n cwd?: string;\n};\n\ntype BashChangedFiles = {\n created: string[];\n updated: string[];\n deleted: string[];\n directoriesCreated: string[];\n directoriesDeleted: string[];\n};\n\nexport interface BashToolOptions {\n ops: BashOperations;\n timeout?: number;\n network?: boolean;\n maxWorkspaceFiles?: number;\n maxWorkspaceFileBytes?: number;\n maxOutputBytes?: number;\n}\n\nexport function createBashTool(options: BashToolOptions) {\n return tool({\n description:\n \"Run a Bash script against the workspace. Use for shell-style workflows \" +\n \"that combine multiple file operations. The script runs in a sandboxed \" +\n \"virtual filesystem with the workspace mounted at `/` (also the default \" +\n \"working directory) — there is no `/workspace` or `/home`; use absolute \" +\n \"paths like `/notes.txt`. Changed files are written back to the workspace.\",\n inputSchema: z.object({\n script: z.string().describe(\"Bash script to run\"),\n cwd: z\n .string()\n .optional()\n .describe(\n \"Working directory for the script. Defaults to / (the workspace root)\"\n )\n }),\n execute: async ({ script, cwd }: BashToolInput) => {\n const timeout = options.timeout ?? DEFAULT_BASH_TIMEOUT_MS;\n const maxOutputBytes =\n options.maxOutputBytes ?? DEFAULT_BASH_MAX_OUTPUT_BYTES;\n const snapshot = await snapshotWorkspaceForBash(options);\n const bash = new Bash({\n files: snapshot.files,\n cwd: normalizeWorkspacePath(cwd ?? \"/\"),\n defenseInDepth: true,\n network: options.network ? {} : undefined\n });\n\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeout);\n let result:\n | {\n stdout: string;\n stderr: string;\n exitCode: number;\n }\n | undefined;\n try {\n for (const directory of snapshot.directories) {\n await bash.fs.mkdir(directory, { recursive: true }).catch(() => {});\n }\n\n try {\n result = await bash.exec(script, {\n cwd: normalizeWorkspacePath(cwd ?? \"/\"),\n signal: controller.signal,\n rawScript: true\n });\n } catch (error) {\n result = {\n stdout: \"\",\n stderr: errorMessage(error),\n exitCode: controller.signal.aborted ? 124 : 1\n };\n }\n\n const sync = await syncBashFilesToWorkspace({\n ops: options.ops,\n bash,\n initialFiles: snapshot.initialFiles,\n initialDirectories: snapshot.initialDirectories,\n protectedPaths: snapshot.protectedPaths\n });\n\n return {\n stdout: truncateToolOutput(result.stdout, maxOutputBytes),\n stderr: truncateToolOutput(result.stderr, maxOutputBytes),\n exitCode: result.exitCode,\n changedFiles: sync.changedFiles,\n ...(snapshot.skippedFiles.length > 0\n ? { skippedFiles: snapshot.skippedFiles }\n : {}),\n ...(sync.errors.length > 0 ? { errors: sync.errors } : {})\n };\n } finally {\n clearTimeout(timer);\n }\n }\n });\n}\n\nasync function snapshotWorkspaceForBash(options: BashToolOptions): Promise<{\n files: InitialFiles;\n initialFiles: Map<string, Uint8Array>;\n initialDirectories: Set<string>;\n protectedPaths: Set<string>;\n directories: string[];\n skippedFiles: string[];\n}> {\n const maxFiles =\n options.maxWorkspaceFiles ?? DEFAULT_BASH_MAX_WORKSPACE_FILES;\n const maxFileBytes =\n options.maxWorkspaceFileBytes ?? DEFAULT_BASH_MAX_WORKSPACE_FILE_BYTES;\n const files: InitialFiles = {};\n const initialFiles = new Map<string, Uint8Array>();\n const initialDirectories = new Set<string>([\"/\"]);\n const protectedPaths = new Set<string>();\n const skippedFiles: string[] = [];\n const pending = [\"/\"];\n\n while (pending.length > 0) {\n const dir = pending.shift()!;\n const entries = await readAllBashDirEntries(options.ops, dir);\n for (const entry of entries) {\n const path = normalizeWorkspacePath(entry.path);\n if (entry.type === \"directory\") {\n initialDirectories.add(path);\n pending.push(path);\n continue;\n }\n if (entry.type !== \"file\") continue;\n if (initialFiles.size >= maxFiles || entry.size > maxFileBytes) {\n protectedPaths.add(path);\n skippedFiles.push(path);\n continue;\n }\n const bytes = await options.ops.readFileBytes(path);\n if (bytes === null) {\n protectedPaths.add(path);\n skippedFiles.push(path);\n continue;\n }\n files[path] = bytes;\n initialFiles.set(path, bytes);\n }\n }\n\n return {\n files,\n initialFiles,\n initialDirectories,\n protectedPaths,\n directories: [...initialDirectories].sort((a, b) => a.localeCompare(b)),\n skippedFiles\n };\n}\n\nasync function readAllBashDirEntries(\n ops: BashOperations,\n dir: string\n): Promise<FileInfo[]> {\n const entries: FileInfo[] = [];\n let offset = 0;\n\n while (true) {\n const page = await ops.readDir(dir, {\n limit: BASH_READDIR_PAGE_SIZE,\n offset\n });\n entries.push(...page);\n if (page.length !== BASH_READDIR_PAGE_SIZE) break;\n offset += page.length;\n }\n\n return entries;\n}\n\nasync function syncBashFilesToWorkspace({\n ops,\n bash,\n initialFiles,\n initialDirectories,\n protectedPaths\n}: {\n ops: BashOperations;\n bash: {\n fs: {\n getAllPaths(): string[];\n stat(path: string): Promise<{ isFile: boolean; isDirectory: boolean }>;\n readFileBuffer(path: string): Promise<Uint8Array>;\n };\n };\n initialFiles: Map<string, Uint8Array>;\n initialDirectories: Set<string>;\n protectedPaths: Set<string>;\n}): Promise<{ changedFiles: BashChangedFiles; errors: string[] }> {\n const changedFiles: BashChangedFiles = {\n created: [],\n updated: [],\n deleted: [],\n directoriesCreated: [],\n directoriesDeleted: []\n };\n const errors: string[] = [];\n const finalFiles = new Map<string, Uint8Array>();\n const finalDirectories = new Set<string>([\"/\"]);\n\n for (const rawPath of bash.fs.getAllPaths()) {\n const path = normalizeWorkspacePath(rawPath);\n if (!shouldSyncBashPath(path, initialFiles, protectedPaths)) continue;\n const stat = await bash.fs.stat(path).catch(() => null);\n if (stat?.isDirectory) {\n finalDirectories.add(path);\n continue;\n }\n if (stat?.isFile) {\n finalFiles.set(path, await bash.fs.readFileBuffer(path));\n }\n }\n\n for (const path of [...finalDirectories].sort((a, b) => a.localeCompare(b))) {\n if (path === \"/\" || initialDirectories.has(path)) continue;\n if (hasProtectedDescendant(path, protectedPaths)) {\n errors.push(\n `Skipped creating directory ${path}: contains protected paths.`\n );\n continue;\n }\n const created = await Promise.resolve(ops.mkdir(path, { recursive: true }))\n .then(() => true)\n .catch((error: unknown) => {\n errors.push(\n `Failed to create directory ${path}: ${errorMessage(error)}`\n );\n return false;\n });\n if (!created) continue;\n changedFiles.directoriesCreated.push(path);\n }\n\n for (const [path, bytes] of finalFiles) {\n if (protectedPaths.has(path)) {\n errors.push(`Skipped writing protected workspace file: ${path}`);\n continue;\n }\n const existing = initialFiles.get(path);\n if (existing && bytesEqual(existing, bytes)) continue;\n const written = await writeWorkspaceBytes(ops, path, bytes, errors);\n if (!written) continue;\n if (existing) changedFiles.updated.push(path);\n else changedFiles.created.push(path);\n }\n\n for (const path of [...initialFiles.keys()].sort((a, b) =>\n b.localeCompare(a)\n )) {\n if (finalFiles.has(path) || protectedPaths.has(path)) continue;\n const deleted = await ops\n .rm(path, { force: true })\n .then(() => true)\n .catch((error: unknown) => {\n errors.push(`Failed to delete ${path}: ${errorMessage(error)}`);\n return false;\n });\n if (!deleted) continue;\n changedFiles.deleted.push(path);\n }\n\n for (const path of [...initialDirectories].sort((a, b) =>\n b.localeCompare(a)\n )) {\n if (path === \"/\" || finalDirectories.has(path)) continue;\n if (hasProtectedDescendant(path, protectedPaths)) {\n errors.push(`Skipped deleting protected workspace directory: ${path}`);\n continue;\n }\n const deleted = await ops\n .rm(path, { recursive: true, force: true })\n .then(() => true)\n .catch((error: unknown) => {\n errors.push(\n `Failed to delete directory ${path}: ${errorMessage(error)}`\n );\n return false;\n });\n if (!deleted) continue;\n changedFiles.directoriesDeleted.push(path);\n }\n\n changedFiles.created.sort();\n changedFiles.updated.sort();\n changedFiles.deleted.sort();\n changedFiles.directoriesCreated.sort();\n changedFiles.directoriesDeleted.sort();\n\n return { changedFiles, errors };\n}\n\nasync function writeWorkspaceBytes(\n ops: BashOperations,\n path: string,\n bytes: Uint8Array,\n errors: string[]\n): Promise<boolean> {\n const parent = parentDir(path);\n if (parent !== \"/\") {\n const parentCreated = await Promise.resolve(\n ops.mkdir(parent, { recursive: true })\n )\n .then(() => true)\n .catch((error: unknown) => {\n errors.push(\n `Failed to create parent directory ${parent}: ${errorMessage(error)}`\n );\n return false;\n });\n if (!parentCreated) return false;\n }\n\n if (ops.writeFileBytes) {\n return ops\n .writeFileBytes(path, bytes)\n .then(() => true)\n .catch((error: unknown) => {\n errors.push(`Failed to write ${path}: ${errorMessage(error)}`);\n return false;\n });\n }\n\n if (!looksLikeText(bytes)) {\n errors.push(\n `Could not persist binary file ${path}: workspace does not support writeFileBytes.`\n );\n return false;\n }\n\n const content = new TextDecoder().decode(bytes);\n return ops\n .writeFile(path, content)\n .then(() => true)\n .catch((error: unknown) => {\n errors.push(`Failed to write ${path}: ${errorMessage(error)}`);\n return false;\n });\n}\n\nfunction shouldSyncBashPath(\n path: string,\n initialFiles: Map<string, Uint8Array>,\n protectedPaths: Set<string>\n): boolean {\n if (path === \"/\") return false;\n if (initialFiles.has(path)) return true;\n if (protectedPaths.has(path)) return true;\n if (path === \"/tmp\" || path.startsWith(\"/tmp/\")) return false;\n return !BASH_EXCLUDED_SYNC_ROOTS.some(\n (root) => path === root || path.startsWith(`${root}/`)\n );\n}\n\nfunction hasProtectedDescendant(\n path: string,\n protectedPaths: Set<string>\n): boolean {\n const prefix = path.endsWith(\"/\") ? path : `${path}/`;\n for (const protectedPath of protectedPaths) {\n if (protectedPath.startsWith(prefix)) return true;\n }\n return false;\n}\n\nfunction normalizeWorkspacePath(path: string): string {\n const parts: string[] = [];\n const raw = path.startsWith(\"/\") ? path : `/${path}`;\n for (const part of raw.split(\"/\")) {\n if (!part || part === \".\") continue;\n if (part === \"..\") parts.pop();\n else parts.push(part);\n }\n return `/${parts.join(\"/\")}`;\n}\n\nfunction parentDir(path: string): string {\n const normalized = normalizeWorkspacePath(path);\n const index = normalized.lastIndexOf(\"/\");\n return index <= 0 ? \"/\" : normalized.slice(0, index);\n}\n\nfunction bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n if (a.byteLength !== b.byteLength) return false;\n for (let i = 0; i < a.byteLength; i++) {\n if (a[i] !== b[i]) return false;\n }\n return true;\n}\n\nfunction truncateToolOutput(value: string, maxBytes: number): string {\n const bytes = new TextEncoder().encode(value);\n if (bytes.byteLength <= maxBytes) return value;\n const truncated = new TextDecoder().decode(bytes.slice(0, maxBytes));\n return `${truncated}\\n... (${formatSize(bytes.byteLength - maxBytes)} truncated)`;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n// ── Delete ──────────────────────────────────────────────────────────\n\nexport interface DeleteToolOptions {\n ops: DeleteOperations;\n}\n\nexport function createDeleteTool(options: DeleteToolOptions) {\n const { ops } = options;\n\n return tool({\n description:\n \"Delete a file or directory. \" +\n \"Set recursive to true to remove non-empty directories.\",\n inputSchema: z.object({\n path: z.string().describe(\"Absolute path to the file or directory\"),\n recursive: z\n .boolean()\n .optional()\n .describe(\"If true, remove directories and their contents recursively\")\n }),\n execute: async ({ path, recursive }) => {\n await ops.rm(path, { recursive, force: true });\n return { deleted: path };\n }\n });\n}\n"],"mappings":";;;;AAgGA,SAAS,iBAAiB,IAAmC;CAC3D,OAAO;EACL,WAAW,SAAS,GAAG,SAAS,IAAI;EACpC,gBAAgB,SAAS,GAAG,cAAc,IAAI;EAC9C,OAAO,SAAS,GAAG,KAAK,IAAI;CAC9B;AACF;AAEA,SAAS,kBAAkB,IAAoC;CAC7D,OAAO;EACL,YAAY,MAAM,YAAY,GAAG,UAAU,MAAM,OAAO;EACxD,QAAQ,MAAM,SAAS,GAAG,MAAM,MAAM,IAAI;CAC5C;AACF;AAEA,SAAS,iBAAiB,IAAmC;CAC3D,OAAO;EACL,WAAW,SAAS,GAAG,SAAS,IAAI;EACpC,YAAY,MAAM,YAAY,GAAG,UAAU,MAAM,OAAO;CAC1D;AACF;AAEA,SAAS,iBAAiB,IAAmC;CAC3D,OAAO,EACL,UAAU,KAAK,SAAS,GAAG,QAAQ,KAAK,IAAI,EAC9C;AACF;AAEA,SAAS,iBAAiB,IAAmC;CAC3D,OAAO,EACL,OAAO,YAAY,GAAG,KAAK,OAAO,EACpC;AACF;AAEA,SAAS,mBAAmB,IAAqC;CAC/D,OAAO,EACL,KAAK,MAAM,SAAS,GAAG,GAAG,MAAM,IAAI,EACtC;AACF;AAEA,SAAS,iBAAiB,IAAmC;CAC3D,OAAO;EACL,OAAO,YAAY,GAAG,KAAK,OAAO;EAClC,WAAW,SAAS,GAAG,SAAS,IAAI;CACtC;AACF;AAEA,SAAS,iBAAiB,IAAmC;CAC3D,MAAM,mBAAmB;CAGzB,OAAO;EACL,UAAU,KAAK,SAAS,GAAG,QAAQ,KAAK,IAAI;EAC5C,gBAAgB,SAAS,GAAG,cAAc,IAAI;EAC9C,YAAY,MAAM,YAAY,GAAG,UAAU,MAAM,OAAO;EACxD,gBAAgB,iBAAiB,kBAC5B,MAAM,YAAY,iBAAiB,eAAgB,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G,IAAI,EAAE,YAAY,KAChC,IAAI,EAAE,OAAO,EAAE,IAAI,OAAO;CAE5B,OAAO;AACT;AAEA,SAAS,mBAAmB,OAAe,UAA0B;CACnE,MAAM,QAAQ,IAAI,YAAY,CAAC,CAAC,OAAO,KAAK;CAC5C,IAAI,MAAM,cAAc,UAAU,OAAO;CAEzC,OAAO,GADW,IAAI,YAAY,CAAC,CAAC,OAAO,MAAM,MAAM,GAAG,QAAQ,CAChD,EAAE,SAAS,WAAW,MAAM,aAAa,QAAQ,EAAE;AACvE;AAEA,SAAS,aAAa,OAAwB;CAC5C,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D;AAQA,SAAgB,iBAAiB,SAA4B;CAC3D,MAAM,EAAE,QAAQ;CAEhB,OAAO,KAAK;EACV,aACE;EAEF,aAAa,EAAE,OAAO;GACpB,MAAM,EAAE,OAAO,CAAC,CAAC,SAAS,wCAAwC;GAClE,WAAW,EACR,QAAQ,CAAC,CACT,SAAS,CAAC,CACV,SAAS,4DAA4D;EAC1E,CAAC;EACD,SAAS,OAAO,EAAE,MAAM,gBAAgB;GACtC,MAAM,IAAI,GAAG,MAAM;IAAE;IAAW,OAAO;GAAK,CAAC;GAC7C,OAAO,EAAE,SAAS,KAAK;EACzB;CACF,CAAC;AACH"}
@@ -55,45 +55,21 @@ function generateThinkEnvBlock(manifest, options) {
55
55
  }
56
56
  function agentConstructorType(agent, fromFile, files) {
57
57
  const exportInfo = inferAgentExport(agent, files);
58
- if (exportInfo.kind === "class") {
59
- const specifier = relativeModuleSpecifier(fromFile, agent.sourcePath);
60
- return `(typeof import(${JSON.stringify(specifier)}))${exportAccessor(exportInfo.exportName)}`;
61
- }
62
- return `typeof import("@cloudflare/think").Think<Cloudflare.Env>`;
58
+ const specifier = relativeModuleSpecifier(fromFile, agent.sourcePath);
59
+ return `(typeof import(${JSON.stringify(specifier)}))${exportAccessor(exportInfo.exportName)}`;
63
60
  }
64
61
  function agentInstanceType(agent, fromFile, files) {
65
62
  const exportInfo = inferAgentExport(agent, files);
66
- if (exportInfo.kind === "class") {
67
- const specifier = relativeModuleSpecifier(fromFile, agent.sourcePath);
68
- return `InstanceType<(typeof import(${JSON.stringify(specifier)}))${exportAccessor(exportInfo.exportName)}>`;
69
- }
70
- return `import("@cloudflare/think").Think<Cloudflare.Env>`;
63
+ const specifier = relativeModuleSpecifier(fromFile, agent.sourcePath);
64
+ return `InstanceType<(typeof import(${JSON.stringify(specifier)}))${exportAccessor(exportInfo.exportName)}>`;
71
65
  }
72
66
  function inferAgentExport(agent, files) {
73
67
  const source = files?.[agent.sourcePath];
74
- if (!source) return agent.exportName ? {
75
- kind: "class",
76
- exportName: agent.exportName
77
- } : { kind: "declarative" };
78
- if (/export\s+default\s+agent\s*\(/.test(source)) return { kind: "declarative" };
79
- if (/export\s+default\s+class\b/.test(source)) return {
80
- kind: "class",
81
- exportName: "default"
82
- };
68
+ if (!source) return { exportName: agent.exportName ?? "default" };
69
+ if (/export\s+default\s+class\b/.test(source)) return { exportName: "default" };
83
70
  const namedClass = source.match(/export\s+(?:abstract\s+)?class\s+([A-Za-z_$][\w$]*)/);
84
- if (namedClass?.[1]) return {
85
- kind: "class",
86
- exportName: namedClass[1]
87
- };
88
- if (source.match(/export\s+const\s+([A-Za-z_$][\w$]*)\s*=\s*agent\s*\(/)) return { kind: "declarative" };
89
- if (source.match(/export\s*\{\s*([A-Za-z_$][\w$]*)\s+as\s+default\s*\}/)?.[1]) return {
90
- kind: "class",
91
- exportName: "default"
92
- };
93
- return agent.exportName ? {
94
- kind: "class",
95
- exportName: agent.exportName
96
- } : { kind: "declarative" };
71
+ if (namedClass?.[1]) return { exportName: namedClass[1] };
72
+ return { exportName: agent.exportName ?? "default" };
97
73
  }
98
74
  function exportAccessor(exportName) {
99
75
  return exportName === "default" ? ".default" : `[${JSON.stringify(exportName)}]`;
@@ -122,4 +98,4 @@ function normalizePath(file) {
122
98
  //#endregion
123
99
  export { isThinkGeneratedFile as n, generateThinkTypes as t };
124
100
 
125
- //# sourceMappingURL=types-codegen-B6c5KpYH.js.map
101
+ //# sourceMappingURL=types-codegen-C-9yeFao.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types-codegen-C-9yeFao.js","names":[],"sources":["../src/framework/types-codegen.ts"],"sourcesContent":["import path from \"node:path\";\nimport type { ThinkFrameworkAgent, ThinkFrameworkManifest } from \"./manifest\";\n\nexport const THINK_TYPES_BEGIN = \"// <think-generated>\";\nexport const THINK_TYPES_END = \"// </think-generated>\";\n\nconst GENERATED_FILE_HEADER = [\n \"// Generated by `think types`. Do not edit this file directly.\",\n \"// Re-run `think types` after changing Think agents or Wrangler bindings.\"\n].join(\"\\n\");\n\nexport interface ThinkTypesCodegenOptions {\n files?: Record<string, string>;\n typesFile?: string;\n}\n\nexport interface ThinkGeneratedFile {\n path: string;\n content: string;\n}\n\nexport function generateThinkTypes(\n manifest: ThinkFrameworkManifest,\n options: ThinkTypesCodegenOptions = {}\n): ThinkGeneratedFile[] {\n const typesFile = normalizePath(options.typesFile ?? \"think.d.ts\");\n return [\n {\n path: typesFile,\n content: generateThinkEnvBlock(manifest, {\n ...options,\n typesFile\n })\n }\n ];\n}\n\nexport function isThinkGeneratedFile(source: string): boolean {\n return source.startsWith(GENERATED_FILE_HEADER);\n}\n\nfunction generateThinkEnvBlock(\n manifest: ThinkFrameworkManifest,\n options: Required<Pick<ThinkTypesCodegenOptions, \"typesFile\">> &\n ThinkTypesCodegenOptions\n): string {\n const sourceFile = options.typesFile;\n const entryExports = manifest.agents.map((agent) => {\n return ` export const ${agent.className}: ${agentConstructorType(agent, sourceFile, options.files)};`;\n });\n const bindingExports = topLevelAgents(manifest).map((agent) => {\n const binding = agent.bindingName ?? agent.className;\n return [\n ` ${binding}: DurableObjectNamespace<`,\n ` ${agentInstanceType(agent, sourceFile, options.files)}`,\n ` >;`\n ].join(\"\\n\");\n });\n\n return (\n [\n GENERATED_FILE_HEADER,\n \"\",\n THINK_TYPES_BEGIN,\n `declare module \"virtual:think/entry\" {`,\n ` const entry: ExportedHandler<Cloudflare.Env>;`,\n ` export default entry;`,\n ...entryExports,\n `}`,\n ``,\n `declare module \"virtual:think/router\" {`,\n ` export const thinkRouter: import(\"@cloudflare/think/server-entry\").ThinkRouter;`,\n `}`,\n bindingExports.length\n ? [\n ``,\n `declare namespace Cloudflare {`,\n ` interface Env {`,\n ...bindingExports,\n ` }`,\n `}`\n ].join(\"\\n\")\n : \"\",\n THINK_TYPES_END,\n \"\"\n ]\n .filter((line) => line.length > 0)\n .join(\"\\n\") + \"\\n\"\n );\n}\n\nfunction agentConstructorType(\n agent: ThinkFrameworkAgent,\n fromFile: string,\n files: Record<string, string> | undefined\n): string {\n const exportInfo = inferAgentExport(agent, files);\n const specifier = relativeModuleSpecifier(fromFile, agent.sourcePath);\n return `(typeof import(${JSON.stringify(specifier)}))${exportAccessor(exportInfo.exportName)}`;\n}\n\nfunction agentInstanceType(\n agent: ThinkFrameworkAgent,\n fromFile: string,\n files: Record<string, string> | undefined\n): string {\n const exportInfo = inferAgentExport(agent, files);\n const specifier = relativeModuleSpecifier(fromFile, agent.sourcePath);\n return `InstanceType<(typeof import(${JSON.stringify(specifier)}))${exportAccessor(exportInfo.exportName)}>`;\n}\n\nfunction inferAgentExport(\n agent: ThinkFrameworkAgent,\n files: Record<string, string> | undefined\n): { exportName: string } {\n const source = files?.[agent.sourcePath];\n if (!source) {\n return { exportName: agent.exportName ?? \"default\" };\n }\n if (/export\\s+default\\s+class\\b/.test(source)) {\n return { exportName: \"default\" };\n }\n const namedClass = source.match(\n /export\\s+(?:abstract\\s+)?class\\s+([A-Za-z_$][\\w$]*)/\n );\n if (namedClass?.[1]) {\n return { exportName: namedClass[1] };\n }\n\n return { exportName: agent.exportName ?? \"default\" };\n}\n\nfunction exportAccessor(exportName: string): string {\n return exportName === \"default\"\n ? \".default\"\n : `[${JSON.stringify(exportName)}]`;\n}\n\nfunction topLevelAgents(\n manifest: ThinkFrameworkManifest\n): ThinkFrameworkAgent[] {\n return manifest.agents.filter((agent) => agent.kind === \"top-level\");\n}\n\nfunction relativeModuleSpecifier(fromFile: string, targetFile: string): string {\n const fromDirectory = dirname(fromFile);\n const withoutExtension = stripExtension(targetFile);\n let relative = path.posix.relative(fromDirectory, withoutExtension);\n if (!relative.startsWith(\".\")) relative = `./${relative}`;\n return relative;\n}\n\nfunction stripExtension(file: string): string {\n return file.replace(/\\.(?:d\\.)?(?:ts|tsx|js|mjs)$/, \"\");\n}\n\nfunction dirname(file: string): string {\n const normalized = normalizePath(file);\n const directory = path.posix.dirname(normalized);\n return directory === \".\" ? \".\" : directory;\n}\n\nfunction normalizePath(file: string): string {\n return file.replace(/\\\\/g, \"/\").replace(/^\\.?\\//, \"\");\n}\n"],"mappings":";;AAGA,MAAa,oBAAoB;AACjC,MAAa,kBAAkB;AAE/B,MAAM,wBAAwB,CAC5B,kEACA,2EACF,CAAC,CAAC,KAAK,IAAI;AAYX,SAAgB,mBACd,UACA,UAAoC,CAAC,GACf;CACtB,MAAM,YAAY,cAAc,QAAQ,aAAa,YAAY;CACjE,OAAO,CACL;EACE,MAAM;EACN,SAAS,sBAAsB,UAAU;GACvC,GAAG;GACH;EACF,CAAC;CACH,CACF;AACF;AAEA,SAAgB,qBAAqB,QAAyB;CAC5D,OAAO,OAAO,WAAW,qBAAqB;AAChD;AAEA,SAAS,sBACP,UACA,SAEQ;CACR,MAAM,aAAa,QAAQ;CAC3B,MAAM,eAAe,SAAS,OAAO,KAAK,UAAU;EAClD,OAAO,kBAAkB,MAAM,UAAU,IAAI,qBAAqB,OAAO,YAAY,QAAQ,KAAK,EAAE;CACtG,CAAC;CACD,MAAM,iBAAiB,eAAe,QAAQ,CAAC,CAAC,KAAK,UAAU;EAE7D,OAAO;GACL,OAFc,MAAM,eAAe,MAAM,UAE1B;GACf,SAAS,kBAAkB,OAAO,YAAY,QAAQ,KAAK;GAC3D;EACF,CAAC,CAAC,KAAK,IAAI;CACb,CAAC;CAED,OACE;EACE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D,IAAI,WAAW,KAAK,MAAM,SAAS,eAAe,gBAAgB;CAClE,IAAI,CAAC,SAAS,WAAW,GAAG,GAAG,WAAW,KAAK;CAC/C,OAAO;AACT;AAEA,SAAS,eAAe,MAAsB;CAC5C,OAAO,KAAK,QAAQ,gCAAgC,EAAE;AACxD;AAEA,SAAS,QAAQ,MAAsB;CACrC,MAAM,aAAa,cAAc,IAAI;CACrC,MAAM,YAAY,KAAK,MAAM,QAAQ,UAAU;CAC/C,OAAO,cAAc,MAAM,MAAM;AACnC;AAEA,SAAS,cAAc,MAAsB;CAC3C,OAAO,KAAK,QAAQ,OAAO,GAAG,CAAC,CAAC,QAAQ,UAAU,EAAE;AACtD"}
package/dist/vite.d.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  import {
2
- g as ThinkWorkerConfigOptions,
3
- h as ThinkWorkerConfig,
4
- o as ThinkFrameworkManifest
5
- } from "./manifest-CpB-xngB.js";
6
- import { n as ThinkConfigMergeResult } from "./config-D512sQYg.js";
2
+ a as ThinkFrameworkManifest,
3
+ h as ThinkWorkerConfigOptions,
4
+ m as ThinkWorkerConfig
5
+ } from "./manifest-DK5HuGga.js";
6
+ import { n as ThinkConfigMergeResult } from "./config-CD7hqncK.js";
7
7
  import { PluginOption } from "vite";
8
8
 
9
9
  //#region src/vite.d.ts
package/dist/vite.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { a as readWranglerConfig, c as createThinkWorkerConfig, d as diagnoseThinkWorkerConfig, l as createThinkWorkerDefaults, m as summarizeThinkManifest, o as resolveThinkManifest, p as mergeThinkWorkerConfig, s as watchWranglerConfigFiles, t as applyUserBindingNames } from "./project-BHurFdu4.js";
2
- import { a as generateThinkRouterModule, i as generateThinkManifestModule, n as generateThinkConfigModule, o as generateThinkServerEntryModule, r as generateThinkEntry, t as generateThinkAgentsModule } from "./codegen-CuPdJRpV.js";
2
+ import { a as generateThinkRouterModule, i as generateThinkManifestModule, n as generateThinkConfigModule, o as generateThinkServerEntryModule, r as generateThinkEntry, t as generateThinkAgentsModule } from "./codegen-DlA2QQuU.js";
3
3
  import path from "node:path";
4
4
  import { spawn } from "node:child_process";
5
5
  import { existsSync } from "node:fs";
@@ -1,4 +1,4 @@
1
- import { B as Think, q as ThinkSubmissionStatus } from "./think-i1Pkgb1R.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 {