agents 0.27.0 → 0.28.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 (216) hide show
  1. package/dist/abortable-C1SpfVoi.js +21 -0
  2. package/dist/abortable-C1SpfVoi.js.map +1 -0
  3. package/dist/{agent-routing-Bhdbvf7s.d.ts → agent-routing-BMvWTFEp.d.ts} +21 -15
  4. package/dist/agent-routing.d.ts +1 -1
  5. package/dist/agent-tool-types.d.ts +1 -1
  6. package/dist/{agent-tools-bJZwBMfq.d.ts → agent-tools-ohoewW-B.d.ts} +2 -2
  7. package/dist/agent-tools.d.ts +1 -1
  8. package/dist/ai-ahruGw7e.d.ts +239 -0
  9. package/dist/{ai-sdk-OoGkFy3s.js → ai-sdk-C2iTAwUd.js} +44 -18
  10. package/dist/ai-sdk-C2iTAwUd.js.map +1 -0
  11. package/dist/browser/ai.d.ts +8 -227
  12. package/dist/browser/ai.js +259 -1
  13. package/dist/browser/ai.js.map +1 -0
  14. package/dist/browser/index.d.ts +56 -46
  15. package/dist/browser/index.js +4 -361
  16. package/dist/browser/{ai-sdk.d.ts → tools/ai-sdk.d.ts} +7 -7
  17. package/dist/browser/{ai-sdk.js → tools/ai-sdk.js} +5 -4
  18. package/dist/browser/tools/ai-sdk.js.map +1 -0
  19. package/dist/browser/tools/pi.d.ts +111 -0
  20. package/dist/browser/tools/pi.js +119 -0
  21. package/dist/browser/tools/pi.js.map +1 -0
  22. package/dist/browser/{tanstack-ai.d.ts → tools/tanstack-ai.d.ts} +39 -37
  23. package/dist/browser/{tanstack-ai.js → tools/tanstack-ai.js} +73 -59
  24. package/dist/browser/tools/tanstack-ai.js.map +1 -0
  25. package/dist/browser-CEdNlsaD.js +481 -0
  26. package/dist/browser-CEdNlsaD.js.map +1 -0
  27. package/dist/{browser-tmkcAAI3.d.ts → browser-D30VlpcA.d.ts} +63 -37
  28. package/dist/{browser-tool-CBqs6hqa.js → browser-tool-4iomavs_.js} +145 -49
  29. package/dist/browser-tool-4iomavs_.js.map +1 -0
  30. package/dist/{browser-tool-Bn-nzJQI.d.ts → browser-tool-vtrPOV8e.d.ts} +24 -5
  31. package/dist/{capability-B4WbF81e.js → capability-DBAKc6UZ.js} +1 -3
  32. package/dist/capability-DBAKc6UZ.js.map +1 -0
  33. package/dist/{capability-runner-O5VbQzqg.d.ts → capability-runner-BiVUtjqC.d.ts} +1 -7
  34. package/dist/chat/index.d.ts +4 -4
  35. package/dist/chat/index.js +1 -1
  36. package/dist/chat-sdk/index.d.ts +1 -1
  37. package/dist/chat-sdk/index.js +1 -1
  38. package/dist/{client-1tEQ1Oqz.js → client-BnYbNT3z.js} +3 -4
  39. package/dist/client-BnYbNT3z.js.map +1 -0
  40. package/dist/{client-DS3Dz9l0.d.ts → client-Bp-JwL3p.d.ts} +2 -2
  41. package/dist/client.d.ts +1 -1
  42. package/dist/{connector-58XDGvc3.js → connector-CtZylXdk.js} +3 -603
  43. package/dist/connector-CtZylXdk.js.map +1 -0
  44. package/dist/{connector-Cl-VqPmA.d.ts → connector-DEXzVoaY.d.ts} +9 -374
  45. package/dist/{conversations-DH0ut_8n.d.ts → conversations-FjHDRZyD.d.ts} +4 -4
  46. package/dist/{current-agent-C07C5o5Y.d.ts → current-agent-CKgT5d1O.d.ts} +3 -5
  47. package/dist/current-agent-DhoDkSnH.js.map +1 -1
  48. package/dist/{durable-object-lifecycle-DRqp475_.d.ts → durable-object-lifecycle-DOI_bzCH.d.ts} +2 -2
  49. package/dist/experimental/channels/index.d.ts +2 -2
  50. package/dist/experimental/channels/index.js +2 -2
  51. package/dist/experimental/channels/web/index.d.ts +2 -2
  52. package/dist/experimental/channels/web/index.js +1 -1
  53. package/dist/{gateway-BDC07gYO.d.ts → gateway-BFO6vRDn.d.ts} +2 -2
  54. package/dist/{handler-stateless-VvrWSAVA.js → handler-stateless-Bly_nSH3.js} +12 -3
  55. package/dist/handler-stateless-Bly_nSH3.js.map +1 -0
  56. package/dist/harness/ai-sdk/index.d.ts +2 -2
  57. package/dist/harness/ai-sdk/index.js +1 -1
  58. package/dist/harness/container/index.d.ts +2 -2
  59. package/dist/harness/container/index.js +3 -3
  60. package/dist/harness/opencode/index.d.ts +183 -7
  61. package/dist/harness/opencode/index.js +355 -24
  62. package/dist/harness/opencode/index.js.map +1 -1
  63. package/dist/harness/pi/index.d.ts +2 -2
  64. package/dist/harness/pi/index.js +3 -3
  65. package/dist/harness/store/index.d.ts +1 -1
  66. package/dist/harness/store/index.js +1 -1
  67. package/dist/harness/think/index.d.ts +2 -2
  68. package/dist/harness/think/index.js +363 -171
  69. package/dist/harness/think/index.js.map +1 -1
  70. package/dist/{images-Ce9SCu3X.js → images-C4hiIexM.js} +46 -4
  71. package/dist/images-C4hiIexM.js.map +1 -0
  72. package/dist/{index-D0A5tbWu.d.ts → index-BEL3ZV-s.d.ts} +2 -6
  73. package/dist/{index-Ib_4dwOo.d.ts → index-CBt8oRJt.d.ts} +3 -5
  74. package/dist/index.d.ts +4 -4
  75. package/dist/index.js +2 -2
  76. package/dist/input-schema-BQykTEp_.js +20 -0
  77. package/dist/input-schema-BQykTEp_.js.map +1 -0
  78. package/dist/{input-schema-DNrpTu49.js → input-schema-xBofjBKC.js} +3 -3
  79. package/dist/input-schema-xBofjBKC.js.map +1 -0
  80. package/dist/internal_context.d.ts +1 -1
  81. package/dist/lifecycle/index.d.ts +3 -3
  82. package/dist/lifecycle/index.js +2 -2
  83. package/dist/{lifecycle-CFu6OV03.js → lifecycle-DGorpAmA.js} +2 -4
  84. package/dist/lifecycle-DGorpAmA.js.map +1 -0
  85. package/dist/mcp/client/index.d.ts +1 -1
  86. package/dist/mcp/client/index.js +1 -1
  87. package/dist/mcp/index.d.ts +1 -1
  88. package/dist/mcp/index.js +18 -4
  89. package/dist/mcp/index.js.map +1 -1
  90. package/dist/mcp/server/index.js +1 -1
  91. package/dist/models/ai-sdk/index.d.ts +45 -17
  92. package/dist/models/ai-sdk/index.js +1 -1
  93. package/dist/models/opencode/index.d.ts +2 -2
  94. package/dist/models/opencode/index.js +1 -1
  95. package/dist/models/pi-ai/index.d.ts +8 -3
  96. package/dist/models/pi-ai/index.js +6 -6
  97. package/dist/models/pi-ai/index.js.map +1 -1
  98. package/dist/{options-pwTNq9z6.d.ts → options-CiIsJHXR.d.ts} +2 -6
  99. package/dist/queue/index.d.ts +1 -1
  100. package/dist/queue/index.js +1 -1
  101. package/dist/{queue-BB-zfIYF.js → queue-CcIjVYTE.js} +2 -2
  102. package/dist/{queue-BB-zfIYF.js.map → queue-CcIjVYTE.js.map} +1 -1
  103. package/dist/react.d.ts +2 -2
  104. package/dist/routing/index.d.ts +2 -2
  105. package/dist/routing/index.js +1 -1
  106. package/dist/{scheduler-CrFCnv_J.d.ts → scheduler-BCLESHSC.d.ts} +2 -12
  107. package/dist/{scheduler-DZ3xQfeK.js → scheduler-FIHv2-kJ.js} +2 -4
  108. package/dist/scheduler-FIHv2-kJ.js.map +1 -0
  109. package/dist/schedules/index.d.ts +1 -1
  110. package/dist/schedules/index.js +1 -1
  111. package/dist/serializable.d.ts +1 -1
  112. package/dist/session-store-Do4xkDcf.js +606 -0
  113. package/dist/session-store-Do4xkDcf.js.map +1 -0
  114. package/dist/session-store-DoPY12xM.d.ts +383 -0
  115. package/dist/sessions/index.d.ts +1 -1
  116. package/dist/sessions/index.js +1 -1
  117. package/dist/{sessions-B9pNuxdT.js → sessions-_vN5BEZX.js} +2 -2
  118. package/dist/{sessions-B9pNuxdT.js.map → sessions-_vN5BEZX.js.map} +1 -1
  119. package/dist/{settings-C45hDliX.js → settings-BjAiPd6Z.js} +7 -4
  120. package/dist/settings-BjAiPd6Z.js.map +1 -0
  121. package/dist/{settings-NgGwF7Qt.d.ts → settings-DnD__xuE.d.ts} +22 -4
  122. package/dist/{src-DgCbZtIR.js → src-CQxJFv4l.js} +8 -8
  123. package/dist/src-CQxJFv4l.js.map +1 -0
  124. package/dist/state/index.d.ts +1 -1
  125. package/dist/state/index.js +1 -3
  126. package/dist/state/index.js.map +1 -1
  127. package/dist/{store-DLeqKuj3.d.ts → store-BKM4Xm9M.d.ts} +23 -1
  128. package/dist/{store-vgcPYo8K.js → store-CslVzfN7.js} +28 -2
  129. package/dist/store-CslVzfN7.js.map +1 -0
  130. package/dist/streams/index.d.ts +1 -1
  131. package/dist/streams/index.js +1 -1
  132. package/dist/{streams-CITClVer.js → streams-lsHMJhRW.js} +2 -2
  133. package/dist/{streams-CITClVer.js.map → streams-lsHMJhRW.js.map} +1 -1
  134. package/dist/{streams-fbG61qM8.d.ts → streams-vrCtbUIn.d.ts} +2 -2
  135. package/dist/sub-routing.d.ts +1 -1
  136. package/dist/tasks/index.d.ts +1 -1
  137. package/dist/tasks/index.js +1 -1
  138. package/dist/{tasks-CkTZNaV1.js → tasks-BN_5AWqI.js} +2 -2
  139. package/dist/{tasks-CkTZNaV1.js.map → tasks-BN_5AWqI.js.map} +1 -1
  140. package/dist/{tasks-PtlB4Uyn.d.ts → tasks-E89KdwkS.d.ts} +2 -2
  141. package/dist/{tool-BPJEbwaX.d.ts → tool-CTp72Jb_.d.ts} +4 -4
  142. package/dist/tool-CxKsvxjm.js +1126 -0
  143. package/dist/tool-CxKsvxjm.js.map +1 -0
  144. package/dist/tool-DoVberpN.d.ts +301 -0
  145. package/dist/{tool-3PA8xjB_.js → tool-VF0qiO7q.js} +7 -18
  146. package/dist/tool-VF0qiO7q.js.map +1 -0
  147. package/dist/tool-helpers-O5BDVEAY.js +58 -0
  148. package/dist/tool-helpers-O5BDVEAY.js.map +1 -0
  149. package/dist/{transport-k2mFrtL8.d.ts → transport-DCyarnwm.d.ts} +2 -2
  150. package/dist/voice/index.d.ts +2 -2
  151. package/dist/web/fetch/index.d.ts +89 -0
  152. package/dist/web/fetch/index.js +20 -0
  153. package/dist/web/fetch/index.js.map +1 -0
  154. package/dist/web/fetch/tools/ai-sdk.d.ts +80 -0
  155. package/dist/web/fetch/tools/ai-sdk.js +47 -0
  156. package/dist/web/fetch/tools/ai-sdk.js.map +1 -0
  157. package/dist/web/fetch/tools/pi.d.ts +84 -0
  158. package/dist/web/fetch/tools/pi.js +88 -0
  159. package/dist/web/fetch/tools/pi.js.map +1 -0
  160. package/dist/web/fetch/tools/tanstack-ai.d.ts +78 -0
  161. package/dist/web/fetch/tools/tanstack-ai.js +45 -0
  162. package/dist/web/fetch/tools/tanstack-ai.js.map +1 -0
  163. package/dist/{websearch → web/search}/index.d.ts +1 -1
  164. package/dist/{websearch → web/search}/index.js +1 -1
  165. package/dist/{websearch → web/search}/tools/ai-sdk.d.ts +2 -2
  166. package/dist/{websearch → web/search}/tools/ai-sdk.js +3 -3
  167. package/dist/web/search/tools/ai-sdk.js.map +1 -0
  168. package/dist/{websearch → web/search}/tools/pi.d.ts +3 -3
  169. package/dist/{websearch → web/search}/tools/pi.js +2 -2
  170. package/dist/web/search/tools/pi.js.map +1 -0
  171. package/dist/{websearch → web/search}/tools/tanstack-ai.d.ts +2 -2
  172. package/dist/{websearch → web/search}/tools/tanstack-ai.js +3 -3
  173. package/dist/web/search/tools/tanstack-ai.js.map +1 -0
  174. package/dist/websockets/index.d.ts +2 -2
  175. package/dist/websockets/index.js +1 -1
  176. package/dist/{websockets-CmENGb-Z.js → websockets-C3zy8YR0.js} +3 -5
  177. package/dist/websockets-C3zy8YR0.js.map +1 -0
  178. package/dist/workflow-types.d.ts +1 -1
  179. package/dist/workflows.d.ts +1 -1
  180. package/dist/workflows.js +1 -1
  181. package/docs/browse-the-web.md +26 -1
  182. package/docs/fetch-the-web.md +276 -0
  183. package/docs/harnesses/pi.md +25 -0
  184. package/docs/index.md +99 -76
  185. package/docs/lifecycle.md +2 -3
  186. package/docs/mcp-client.md +1 -1
  187. package/docs/mcp-servers.md +1 -1
  188. package/docs/models-pi-ai.md +11 -0
  189. package/docs/models.md +45 -3
  190. package/docs/queue.md +2 -3
  191. package/docs/scheduling.md +2 -6
  192. package/docs/search-the-web.md +2 -0
  193. package/package.json +52 -27
  194. package/dist/ai-fm7xx1BK.js +0 -312
  195. package/dist/ai-fm7xx1BK.js.map +0 -1
  196. package/dist/ai-sdk-OoGkFy3s.js.map +0 -1
  197. package/dist/browser/ai-sdk.js.map +0 -1
  198. package/dist/browser/index.js.map +0 -1
  199. package/dist/browser/tanstack-ai.js.map +0 -1
  200. package/dist/browser-tool-CBqs6hqa.js.map +0 -1
  201. package/dist/capability-B4WbF81e.js.map +0 -1
  202. package/dist/client-1tEQ1Oqz.js.map +0 -1
  203. package/dist/connector-58XDGvc3.js.map +0 -1
  204. package/dist/handler-stateless-VvrWSAVA.js.map +0 -1
  205. package/dist/images-Ce9SCu3X.js.map +0 -1
  206. package/dist/input-schema-DNrpTu49.js.map +0 -1
  207. package/dist/lifecycle-CFu6OV03.js.map +0 -1
  208. package/dist/scheduler-DZ3xQfeK.js.map +0 -1
  209. package/dist/settings-C45hDliX.js.map +0 -1
  210. package/dist/src-DgCbZtIR.js.map +0 -1
  211. package/dist/store-vgcPYo8K.js.map +0 -1
  212. package/dist/tool-3PA8xjB_.js.map +0 -1
  213. package/dist/websearch/tools/ai-sdk.js.map +0 -1
  214. package/dist/websearch/tools/pi.js.map +0 -1
  215. package/dist/websearch/tools/tanstack-ai.js.map +0 -1
  216. package/dist/websockets-CmENGb-Z.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool-VF0qiO7q.js","names":[],"sources":["../src/web/search/contract.ts","../src/web/search/source.ts","../src/web/search/tool.ts"],"sourcesContent":["/**\n * The `web_search` tool contract: its name, what it tells the model, what the\n * model passes in, what comes back, and how results are rendered for the\n * model. Shared by every executor of the tool — the harness-executed\n * adapters in `agents/websearch/*` today, and a gateway-executed variant in\n * `agents/models/*` once AI Gateway server tools ship — so a `web_search` call\n * looks the same in a transcript whoever ran it.\n */\n\n/**\n * The tool's name, as the model calls it and as it appears in transcripts.\n * `web_search` is the name models know from Anthropic's and OpenAI's built-in\n * search tools.\n */\nexport const WEB_SEARCH_TOOL_NAME = \"web_search\";\n\n/** The default number of results when the model doesn't ask for a count. */\nexport const DEFAULT_WEB_SEARCH_LIMIT = 5;\n\n/** The most results one search can return; the API rejects more. */\nexport const MAX_WEB_SEARCH_LIMIT = 10;\n\n/** The longest query the API accepts, in characters. */\nexport const MAX_WEB_SEARCH_QUERY_LENGTH = 1024;\n\n/**\n * Per-result description length in the model's view, in characters. Provider\n * descriptions run to ~8,000 characters (Ceramic returns page text), which at\n * ten results is 80 KB of context per search. The full text stays in the\n * host-side output.\n */\nexport const DEFAULT_WEB_SEARCH_DESCRIPTION_CHARS = 600;\n\n/*\n * These are type aliases, not interfaces: pi stores tool details as strict\n * JSON, and only aliases satisfy its `JsonValue` index signature.\n */\n\n/** What the model says when it wants a search. */\nexport type WebSearchToolInput = {\n /** The search query. */\n query: string;\n /** How many results to return, 1–10. Defaults to the host's `limit`. */\n limit?: number;\n};\n\n/**\n * One search result. `url` and `title` are always present; the rest only\n * when the provider returns them (Exa adds `imageUrl` and\n * `lastModifiedDate`, Linkup adds `faviconUrl`, Ceramic adds neither).\n */\nexport type WebSearchResult = {\n url: string;\n title: string;\n /** A snippet or extract of the page. Length and style vary by provider. */\n description?: string;\n /** ISO 8601 timestamp of the page's last modification. */\n lastModifiedDate?: string;\n imageUrl?: string;\n faviconUrl?: string;\n};\n\n/** The Web Search API's response: results plus request metadata. */\nexport type WebSearchResponse = {\n items: WebSearchResult[];\n metadata: {\n /** The query as the provider saw it. */\n query: string;\n /** AI Gateway request id, for the gateway log. */\n requestId: string;\n /** Provider latency in milliseconds. */\n latencyMs: number;\n };\n};\n\n/**\n * What one `web_search` run produces for the host: the full API response and\n * which provider served it. The model sees {@link renderWebSearchResults}\n * of this.\n */\nexport type WebSearchToolOutput = WebSearchResponse & {\n /** The provider that ran the search, when the source knows. */\n provider?: string;\n};\n\nexport const WEB_SEARCH_TOOL_DESCRIPTION = [\n \"Search the public web. Returns up to `limit` results, each with a URL, a title, and a short description of the page.\",\n \"Use it for current events, facts you're unsure of, documentation, and anything that may have changed since your training.\",\n \"There is no next page: for more or different results, search again with a rephrased query.\",\n \"Results are discovery only: to read a page, fetch its URL with `web_fetch` if it is available.\"\n].join(\" \");\n\nexport interface RenderWebSearchResultsOptions {\n /**\n * Trim each description to this many characters in the model's view.\n * Defaults to {@link DEFAULT_WEB_SEARCH_DESCRIPTION_CHARS}; `Infinity`\n * disables trimming.\n */\n maxDescriptionChars?: number;\n}\n\n/**\n * Render search results as the text the model reads: one numbered block per\n * result, descriptions trimmed and whitespace collapsed.\n */\nexport function renderWebSearchResults(\n response: WebSearchResponse,\n options: RenderWebSearchResultsOptions = {}\n): string {\n const maxChars =\n options.maxDescriptionChars ?? DEFAULT_WEB_SEARCH_DESCRIPTION_CHARS;\n if (response.items.length === 0) {\n return `No results for \"${response.metadata.query}\". Try a broader or rephrased query.`;\n }\n const blocks = response.items.map((item, index) => {\n const lines = [`${index + 1}. ${item.title.trim() || item.url}`, item.url];\n const description = compactDescription(item.description, maxChars);\n if (description) lines.push(description);\n if (item.lastModifiedDate) lines.push(`Modified: ${item.lastModifiedDate}`);\n return lines.join(\"\\n\");\n });\n return [\n `${response.items.length} result${response.items.length === 1 ? \"\" : \"s\"} for \"${response.metadata.query}\":`,\n \"\",\n blocks.join(\"\\n\\n\")\n ].join(\"\\n\");\n}\n\nfunction compactDescription(\n description: string | undefined,\n maxChars: number\n): string | undefined {\n if (!description) return undefined;\n const compact = description.replace(/\\s+/g, \" \").trim();\n if (!compact) return undefined;\n if (compact.length <= maxChars) return compact;\n const cut = compact.slice(0, Math.max(0, maxChars - 1));\n // Back off to the last word boundary, unless that loses too much.\n const space = cut.lastIndexOf(\" \");\n const end = space >= cut.length - WORD_BOUNDARY_BACKOFF ? space : cut.length;\n return `${cut.slice(0, end).trimEnd()}…`;\n}\n\n/** How far truncation backs off to end on a whole word. */\nconst WORD_BOUNDARY_BACKOFF = 20;\n","/**\n * Where searches run. A {@link WebSearchSource} turns a query into a\n * {@link WebSearchResponse}; the tool core is written against it, so the\n * same tool works over the Workers AI binding, the HTTP API, or a fake in\n * tests.\n */\nimport { DEFAULT_GATEWAY_ID } from \"../../models/core/settings\";\nimport { abortable } from \"../abortable\";\nimport {\n DEFAULT_WEB_SEARCH_LIMIT,\n MAX_WEB_SEARCH_LIMIT,\n MAX_WEB_SEARCH_QUERY_LENGTH,\n type WebSearchResponse,\n type WebSearchResult\n} from \"./contract\";\n\n/**\n * Search providers behind the Cloudflare Web Search API. `ceramic` is the\n * platform default and the cheapest; `exa` and `linkup` cost more and, in our\n * testing, ranked announcement-style queries noticeably better. Pricing and\n * data-retention terms are in the Web Search docs.\n */\nexport type WebSearchProvider = \"ceramic\" | \"exa\" | \"linkup\";\n\n/** One search request as a source receives it. */\nexport interface WebSearchRequest {\n /** 1–1024 characters. */\n query: string;\n /** 1–10. Defaults to 5. */\n limit?: number;\n}\n\n/** Per-call options a source receives alongside the request. */\nexport interface WebSearchCallOptions {\n /** Abort the search. A source should reject with the signal's reason. */\n signal?: AbortSignal;\n}\n\n/**\n * Runs searches. The tool core calls `search` and renders what comes back.\n * An object rather than a bare function so a wrapper (caching, logging)\n * keeps `provider` by spreading the source it wraps.\n */\nexport interface WebSearchSource {\n search(\n request: WebSearchRequest,\n options?: WebSearchCallOptions\n ): Promise<WebSearchResponse>;\n /**\n * The provider this source searches with, when known. Informational:\n * recorded on the tool's host output.\n */\n readonly provider?: WebSearchProvider;\n}\n\n/** Options shared by the AI-binding and HTTP sources. */\nexport interface WebSearchGatewayOptions {\n /** AI Gateway id. Defaults to `\"default\"`, which Cloudflare creates on first use. */\n gateway?: string;\n /**\n * Which provider runs the search. Host-chosen; the model never picks.\n * Defaults to the platform default (`ceramic`).\n */\n provider?: WebSearchProvider;\n /**\n * The BYOK key alias on the gateway to bill the provider with. When set\n * and no such key exists the request fails rather than falling back to\n * AI Gateway credits. When omitted, a key under the `default` alias is\n * used if one exists, otherwise credits.\n */\n byokAlias?: string;\n}\n\n/** A search over the Workers AI binding (`env.AI.websearch`). */\nexport interface AIWebSearchOptions extends WebSearchGatewayOptions {\n /** The Workers AI binding. Requires `\"ai\": { \"binding\": \"AI\" }` in wrangler.jsonc. */\n binding: Ai;\n}\n\n/**\n * `Ai.websearch` as `@cloudflare/workers-types` ≥ 5.20260812.1 declares it.\n * This repo can't take that version yet — it breaks `@types/node`'s\n * `Buffer` (cloudflare/workerd#7026) — so the method is spelled out here\n * and the binding is viewed through it. Drop once the repo bumps.\n */\ninterface AiWebSearchBinding {\n websearch(request: {\n gatewayId: string;\n query: string;\n limit?: number;\n provider?: string;\n byokAlias?: string;\n }): Promise<Response>;\n}\n\n/**\n * Search through the Workers AI binding. The Worker's own account and the\n * named gateway are billed.\n */\nexport function createAIWebSearch(\n options: AIWebSearchOptions\n): WebSearchSource {\n validateGatewayOptions(options);\n const binding = options.binding as unknown as AiWebSearchBinding;\n const search: WebSearchSource[\"search\"] = async (input, call = {}) => {\n const request = validateRequest(input);\n if (typeof binding.websearch !== \"function\") {\n throw new WebSearchError(\n \"This Workers runtime has no env.AI.websearch(). Web search needs workerd 1.20260924.1 or later; see https://github.com/cloudflare/agents/blob/main/docs/agents/search-the-web.md.\",\n {\n status: 501,\n code: \"web_search_unsupported_runtime\",\n retryable: false\n }\n );\n }\n // Do not start a billed search for a call that is already cancelled.\n call.signal?.throwIfAborted();\n // The binding takes no signal, so an abort stops waiting for it.\n const response = await abortable(\n binding.websearch({\n gatewayId: options.gateway ?? DEFAULT_GATEWAY_ID,\n query: request.query,\n limit: request.limit,\n provider: options.provider,\n byokAlias: options.byokAlias\n }),\n call.signal\n );\n return readResponse(response, request.query);\n };\n return { search, provider: options.provider };\n}\n\n/** A search over the HTTP API, from any runtime with `fetch`. */\nexport interface HTTPWebSearchOptions extends WebSearchGatewayOptions {\n /** The Cloudflare account the gateway belongs to. */\n accountId: string;\n /** An API token with `Workers AI: Read` and `AI Gateway: Read` on that account. */\n apiToken: string;\n /** Override for tests. Defaults to the global `fetch`. */\n fetch?: typeof fetch;\n /** API origin. Defaults to `https://api.cloudflare.com`. */\n baseUrl?: string;\n}\n\n/**\n * Search through `POST /accounts/{account_id}/ai/websearch`. Use this\n * outside Workers, or to search through a gateway in another account.\n */\nexport function createHTTPWebSearch(\n options: HTTPWebSearchOptions\n): WebSearchSource {\n validateGatewayOptions(options);\n const doFetch = options.fetch ?? fetch;\n const baseUrl = (options.baseUrl ?? \"https://api.cloudflare.com\").replace(\n /\\/+$/,\n \"\"\n );\n const url = `${baseUrl}/client/v4/accounts/${encodeURIComponent(options.accountId)}/ai/websearch/`;\n const search: WebSearchSource[\"search\"] = async (input, call = {}) => {\n const request = validateRequest(input);\n const response = await doFetch(url, {\n method: \"POST\",\n signal: call.signal,\n headers: {\n Authorization: `Bearer ${options.apiToken}`,\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({\n query: request.query,\n limit: request.limit,\n provider: options.provider,\n byokAlias: options.byokAlias,\n options: { gateway: { id: options.gateway ?? DEFAULT_GATEWAY_ID } }\n })\n });\n return readResponse(response, request.query);\n };\n return { search, provider: options.provider };\n}\n\n/** The API's pattern for `byokAlias`. */\nconst BYOK_ALIAS_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;\n\n/** Host configuration errors are programming errors: throw when building. */\nfunction validateGatewayOptions(options: WebSearchGatewayOptions): void {\n if (\n options.byokAlias !== undefined &&\n !BYOK_ALIAS_PATTERN.test(options.byokAlias)\n ) {\n throw new RangeError(\n `byokAlias must be 1–64 letters, digits, \"_\" or \"-\"; got ${JSON.stringify(options.byokAlias)}.`\n );\n }\n}\n\n/**\n * Error codes a {@link WebSearchError} carries. The `web_search_*` codes the\n * API returns pass through as-is; failures without one get a code from the\n * HTTP status, so every error has a code to branch on.\n */\nexport type WebSearchErrorCode =\n /** No AI Gateway credits and no provider key for the search. */\n | \"web_search_payment_required\"\n /** `byokAlias` names a key the gateway does not have. */\n | \"web_search_byok_not_configured\"\n /** The query, limit, or provider was rejected. */\n | \"invalid_web_search_input\"\n /** The gateway does not exist or is not set up. */\n | \"web_search_gateway_not_configured\"\n /** The API token or binding is not allowed to search. */\n | \"web_search_unauthorized\"\n /** Too many searches; retry later. */\n | \"web_search_rate_limited\"\n /** The search took longer than the tool's `timeoutMs`. */\n | \"web_search_timeout\"\n /** The API or the provider failed. */\n | \"web_search_unavailable\"\n /** The Workers runtime has no `env.AI.websearch()`. */\n | \"web_search_unsupported_runtime\"\n /** A code the API added after this release. */\n | (string & {});\n\n/** Why a search failed, with what the API said. */\nexport class WebSearchError extends Error {\n override readonly name = \"WebSearchError\";\n readonly status: number;\n readonly code: WebSearchErrorCode;\n /** Whether retrying the same search might succeed. */\n readonly retryable: boolean;\n /** AI Gateway's id for the failed request, for the gateway log. */\n readonly requestId?: string;\n /** The Cloudflare API's numeric error code, when it gave one. */\n readonly apiCode?: number;\n\n constructor(\n message: string,\n details: {\n status: number;\n code: WebSearchErrorCode;\n retryable?: boolean;\n requestId?: string;\n apiCode?: number;\n cause?: unknown;\n }\n ) {\n super(message, { cause: details.cause });\n this.status = details.status;\n this.code = details.code;\n this.retryable = details.retryable ?? isRetryableStatus(details.status);\n this.requestId = details.requestId;\n this.apiCode = details.apiCode;\n }\n}\n\n/** Check a request against the API's limits and fill in the default limit. */\nfunction validateRequest(\n request: WebSearchRequest\n): Required<WebSearchRequest> {\n const query = request.query.trim();\n const limit = request.limit ?? DEFAULT_WEB_SEARCH_LIMIT;\n if (query.length === 0) {\n throw new WebSearchError(\"Query must not be empty.\", {\n status: 400,\n code: \"invalid_web_search_input\"\n });\n }\n if (query.length > MAX_WEB_SEARCH_QUERY_LENGTH) {\n throw new WebSearchError(\n `Query must be at most ${MAX_WEB_SEARCH_QUERY_LENGTH} characters.`,\n { status: 400, code: \"invalid_web_search_input\" }\n );\n }\n if (!Number.isInteger(limit) || limit < 1 || limit > MAX_WEB_SEARCH_LIMIT) {\n throw new WebSearchError(\n `Limit must be an integer from 1 to ${MAX_WEB_SEARCH_LIMIT}.`,\n { status: 400, code: \"invalid_web_search_input\" }\n );\n }\n return { query, limit };\n}\n\nasync function readResponse(\n response: Response,\n query: string\n): Promise<WebSearchResponse> {\n const text = await response.text();\n let body: unknown;\n try {\n body = JSON.parse(text);\n } catch {\n body = undefined;\n }\n if (!response.ok) throw toWebSearchError(response.status, body, text);\n const result = toWebSearchResponse(body, query);\n if (!result) {\n // A success status with a body that is not a search response is an\n // upstream fault, likely transient, not a reason to stop searching.\n throw new WebSearchError(\n `Web search returned HTTP ${response.status} without search results${text ? `: ${text.slice(0, 200)}` : \"\"}.`,\n {\n status: response.status,\n code: \"web_search_unavailable\",\n retryable: true\n }\n );\n }\n return result;\n}\n\n/**\n * Read a 200 body into a {@link WebSearchResponse}, tolerating what a beta\n * API and three providers might send: items without a URL are dropped, a\n * missing title falls back to the URL, unknown or mistyped fields are left\n * out, and missing metadata gets defaults. Only a body with no `items`\n * array is rejected.\n */\nfunction toWebSearchResponse(\n body: unknown,\n query: string\n): WebSearchResponse | undefined {\n if (!isRecord(body) || !Array.isArray(body.items)) return undefined;\n const items: WebSearchResult[] = [];\n for (const item of body.items as unknown[]) {\n if (!isRecord(item)) continue;\n const url = asString(item.url)?.trim();\n if (!url) continue;\n const result: WebSearchResult = {\n url,\n title: asString(item.title)?.trim() || url\n };\n for (const key of OPTIONAL_RESULT_FIELDS) {\n const value = asString(item[key]);\n if (value !== undefined) result[key] = value;\n }\n items.push(result);\n }\n const metadata = isRecord(body.metadata) ? body.metadata : {};\n return {\n items,\n metadata: {\n query: asString(metadata.query) ?? query,\n requestId: asString(metadata.requestId) ?? \"\",\n latencyMs: typeof metadata.latencyMs === \"number\" ? metadata.latencyMs : 0\n }\n };\n}\n\nconst OPTIONAL_RESULT_FIELDS = [\n \"description\",\n \"lastModifiedDate\",\n \"imageUrl\",\n \"faviconUrl\"\n] as const satisfies readonly (keyof WebSearchResult)[];\n\n/**\n * The API fails in three shapes. Gateway-native:\n * `{ ok: false, error: { category, code, status, retryable, gatewayRequestId } }`.\n * Request validation, the Cloudflare envelope with issue details:\n * `{ success: false, errors: [{ code: 7000, message }], messages: [{ message, path }] }`.\n * Gateway configuration (`AiGatewayError`):\n * `{ success: false, error: [{ code: 2001, message }], message, description }`.\n */\nfunction toWebSearchError(\n status: number,\n body: unknown,\n text: string\n): WebSearchError {\n if (isRecord(body)) {\n const error = body.error;\n if (isRecord(error) && typeof error.code === \"string\") {\n const errorStatus =\n typeof error.status === \"number\" ? error.status : status;\n return new WebSearchError(describeCode(error.code, errorStatus), {\n status: errorStatus,\n code: error.code,\n retryable:\n typeof error.retryable === \"boolean\" ? error.retryable : undefined,\n requestId: asString(error.gatewayRequestId)\n });\n }\n const envelope: unknown[] = Array.isArray(body.errors)\n ? body.errors\n : Array.isArray(error)\n ? error\n : [];\n const entries = envelope.filter(isRecord);\n const issues: unknown[] = Array.isArray(body.messages) ? body.messages : [];\n const message =\n [\n ...entries.map((entry) => asString(entry.message)),\n ...issues.map(describeIssue)\n ]\n .filter((m): m is string => Boolean(m))\n .join(\"; \") || asString(body.message);\n if (message) {\n const apiCode = entries\n .map((entry) => entry.code)\n .find((code): code is number => typeof code === \"number\");\n return new WebSearchError(message, {\n status,\n code: codeForApiError(apiCode, status),\n apiCode\n });\n }\n }\n return new WebSearchError(\n `Web search failed with HTTP ${status}${text ? `: ${text.slice(0, 200)}` : \"\"}.`,\n { status, code: codeForStatus(status) }\n );\n}\n\nfunction codeForApiError(\n apiCode: number | undefined,\n status: number\n): WebSearchErrorCode {\n switch (apiCode) {\n case 7000:\n return \"invalid_web_search_input\";\n case 2001:\n return \"web_search_gateway_not_configured\";\n default:\n return codeForStatus(status);\n }\n}\n\nfunction codeForStatus(status: number): WebSearchErrorCode {\n if (status === 400) return \"invalid_web_search_input\";\n if (status === 401 || status === 403) return \"web_search_unauthorized\";\n if (status === 402) return \"web_search_payment_required\";\n if (status === 429) return \"web_search_rate_limited\";\n return \"web_search_unavailable\";\n}\n\nfunction isRetryableStatus(status: number): boolean {\n return status === 429 || status >= 500;\n}\n\nfunction describeCode(code: string, status: number): string {\n switch (code) {\n case \"web_search_payment_required\":\n return \"Web search is unavailable: the AI Gateway has no credits and no provider key for this search. Top up AI Gateway credits or store a BYOK key for the provider.\";\n case \"web_search_byok_not_configured\":\n return \"Web search is unavailable: the requested BYOK key alias is not configured on the gateway.\";\n case \"invalid_web_search_input\":\n return \"The API rejected the request: check the query (1–1024 characters), limit (1–10), and provider (ceramic, exa, or linkup).\";\n default:\n return `Web search failed (${code}, HTTP ${status}).`;\n }\n}\n\nfunction describeIssue(issue: unknown): string | undefined {\n if (!isRecord(issue)) return undefined;\n const message = asString(issue.message);\n if (!message) return undefined;\n const path = Array.isArray(issue.path) ? issue.path.join(\".\") : \"\";\n return path ? `${path}: ${message}` : message;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\nfunction asString(value: unknown): string | undefined {\n return typeof value === \"string\" ? value : undefined;\n}\n","/**\n * The harness-neutral core of the `web_search` tool, shared by the pi\n * (`agents/websearch/pi`), AI SDK (`agents/websearch/ai-sdk`), and TanStack\n * AI (`agents/websearch/tanstack-ai`) adapters. Internal — not an entry point.\n */\nimport {\n DEFAULT_WEB_SEARCH_LIMIT,\n MAX_WEB_SEARCH_LIMIT,\n WEB_SEARCH_TOOL_DESCRIPTION,\n WEB_SEARCH_TOOL_NAME,\n renderWebSearchResults,\n type WebSearchResponse,\n type WebSearchToolInput,\n type WebSearchToolOutput\n} from \"./contract\";\nimport { abortable } from \"../abortable\";\nimport {\n WebSearchError,\n createAIWebSearch,\n type AIWebSearchOptions,\n type WebSearchSource\n} from \"./source\";\n\n/** Search through the Workers AI binding; the tool builds the source. */\nexport type WebSearchToolBindingOptions = AIWebSearchOptions & {\n source?: never;\n};\n\n/**\n * Search through a source you built. Gateway, provider, and billing belong\n * to the source, so the binding options are not accepted here.\n */\nexport type WebSearchToolSourceOptions = {\n /** Where searches run, instead of the Workers AI binding. */\n source: WebSearchSource;\n binding?: never;\n gateway?: never;\n provider?: never;\n byokAlias?: never;\n};\n\n/**\n * Options every `web_search` tool adapter accepts. Invalid values throw a\n * `RangeError` when the tool is created.\n */\nexport type WebSearchToolOptions = (\n | WebSearchToolBindingOptions\n | WebSearchToolSourceOptions\n) & {\n /**\n * Results per search when the model doesn't ask for a count, and the most\n * it gets when it asks for more. An integer from 1 to 10; defaults to 5.\n */\n limit?: number;\n /** Replaces the default tool description. */\n description?: string;\n /**\n * Per-result description length in the model's view. A positive integer;\n * defaults to 600 characters. `Infinity` passes descriptions through whole.\n */\n maxDescriptionChars?: number;\n /**\n * Give up on a search after this many milliseconds, as a retryable\n * `web_search_timeout` failure. A positive integer; defaults to 30 seconds.\n */\n timeoutMs?: number;\n};\n\n/** The default for {@link WebSearchToolOptions.timeoutMs}. */\nexport const DEFAULT_WEB_SEARCH_TIMEOUT_MS = 30_000;\n\n/**\n * What one run returns to the adapter: the host output, and the model's\n * text. On failure, `error` is the source's error, with the API's detail for\n * the host, and `text` is what the model should read instead.\n */\nexport type WebSearchToolRun =\n | { ok: true; output: WebSearchToolOutput; text: string }\n | { ok: false; error: WebSearchError; text: string };\n\nexport interface WebSearchToolCore {\n name: typeof WEB_SEARCH_TOOL_NAME;\n description: string;\n /** The host's `limit`: the default and the cap for the model's `limit`. */\n limit: number;\n /** Render a search's output as the text the model reads. */\n render(output: WebSearchResponse): string;\n /**\n * Run one search. Aborting `signal` rejects with its reason rather than\n * producing a failed run, so the harness sees a cancelled call.\n */\n run(\n input: WebSearchToolInput,\n options?: { signal?: AbortSignal }\n ): Promise<WebSearchToolRun>;\n}\n\nexport function createWebSearchToolCore(\n options: WebSearchToolOptions\n): WebSearchToolCore {\n const limit = options.limit ?? DEFAULT_WEB_SEARCH_LIMIT;\n const timeoutMs = options.timeoutMs ?? DEFAULT_WEB_SEARCH_TIMEOUT_MS;\n const { maxDescriptionChars } = options;\n if (!Number.isInteger(limit) || limit < 1 || limit > MAX_WEB_SEARCH_LIMIT) {\n throw new RangeError(\n `limit must be an integer from 1 to ${MAX_WEB_SEARCH_LIMIT}; got ${limit}.`\n );\n }\n if (\n maxDescriptionChars !== undefined &&\n maxDescriptionChars !== Infinity &&\n !(Number.isInteger(maxDescriptionChars) && maxDescriptionChars > 0)\n ) {\n throw new RangeError(\n `maxDescriptionChars must be a positive integer or Infinity; got ${maxDescriptionChars}.`\n );\n }\n if (!Number.isInteger(timeoutMs) || timeoutMs <= 0) {\n throw new RangeError(\n `timeoutMs must be a positive integer; got ${timeoutMs}.`\n );\n }\n const source =\n options.source === undefined ? createAIWebSearch(options) : options.source;\n const provider = source.provider;\n const render = (output: WebSearchResponse) =>\n renderWebSearchResults(output, { maxDescriptionChars });\n\n return {\n name: WEB_SEARCH_TOOL_NAME,\n description: options.description ?? WEB_SEARCH_TOOL_DESCRIPTION,\n limit,\n render,\n async run(input, { signal } = {}) {\n signal?.throwIfAborted();\n const request = {\n query: input.query,\n limit: Math.min(clampLimit(input.limit ?? limit), limit)\n };\n const timeout = AbortSignal.timeout(timeoutMs);\n const searchSignal = signal\n ? AbortSignal.any([signal, timeout])\n : timeout;\n try {\n // Race the source too: a custom source may ignore the signal, and\n // the deadline must still end the call.\n const response = await abortable(\n source.search(request, { signal: searchSignal }),\n searchSignal\n );\n const output: WebSearchToolOutput = provider\n ? { ...response, provider }\n : response;\n return {\n ok: true,\n output,\n text: render(response)\n };\n } catch (cause) {\n if (signal?.aborted) throw signal.reason;\n const error = toToolError(cause, timeout.aborted, timeoutMs);\n return { ok: false, error, text: describeFailureForModel(error) };\n }\n }\n };\n}\n\n/**\n * The error a throwing adapter (AI SDK, TanStack AI) raises for a failed\n * run. Those frameworks show the model the error's `message`, so it carries\n * the model's text; the source's error, with the API's detail, is `cause`.\n */\nexport function toolFailure(\n run: Extract<WebSearchToolRun, { ok: false }>\n): WebSearchError {\n const { error } = run;\n return new WebSearchError(run.text, {\n status: error.status,\n code: error.code,\n retryable: error.retryable,\n requestId: error.requestId,\n apiCode: error.apiCode,\n cause: error\n });\n}\n\nfunction toToolError(\n cause: unknown,\n timedOut: boolean,\n timeoutMs: number\n): WebSearchError {\n if (timedOut) {\n return new WebSearchError(`Web search timed out after ${timeoutMs} ms.`, {\n status: 504,\n code: \"web_search_timeout\",\n retryable: true,\n cause\n });\n }\n if (cause instanceof WebSearchError) return cause;\n return new WebSearchError(\n cause instanceof Error ? cause.message : String(cause),\n { status: 500, code: \"web_search_unavailable\", retryable: true, cause }\n );\n}\n\n/**\n * What the model reads when a search fails: whether to retry, change the\n * query, or carry on without search. The operator's detail (credits, keys,\n * gateway setup) stays on the error for the host.\n */\nfunction describeFailureForModel(error: WebSearchError): string {\n if (error.code === \"invalid_web_search_input\") {\n return `Web search rejected the query (${error.message.replace(/\\.$/, \"\")}). Fix the query and try again.`;\n }\n if (error.retryable) {\n return `Web search failed temporarily (${error.code}). You may retry once.`;\n }\n return `Web search is unavailable here (${error.code}). Do not retry; answer without it and say that web search was unavailable.`;\n}\n\n/** The model's `limit`, made an integer from 1 to 10. */\nfunction clampLimit(value: number): number {\n if (!Number.isFinite(value)) return DEFAULT_WEB_SEARCH_LIMIT;\n return Math.min(MAX_WEB_SEARCH_LIMIT, Math.max(1, Math.trunc(value)));\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAcA,MAAa,uBAAuB;;AAGpC,MAAa,2BAA2B;;AAGxC,MAAa,uBAAuB;;AAGpC,MAAa,8BAA8B;;;;;;;AAQ3C,MAAa,uCAAuC;AAsDpD,MAAa,8BAA8B;CACzC;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,GAAG;;;;;AAeV,SAAgB,uBACd,UACA,UAAyC,CAAC,GAClC;CACR,MAAM,WACJ,QAAQ,uBAAA;CACV,IAAI,SAAS,MAAM,WAAW,GAC5B,OAAO,mBAAmB,SAAS,SAAS,MAAM;CAEpD,MAAM,SAAS,SAAS,MAAM,KAAK,MAAM,UAAU;EACjD,MAAM,QAAQ,CAAC,GAAG,QAAQ,EAAE,IAAI,KAAK,MAAM,KAAK,KAAK,KAAK,OAAO,KAAK,GAAG;EACzE,MAAM,cAAc,mBAAmB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entContext } from "./current-agent-DhoDkSnH.js";
2
+ import "./internal_context.js";
3
+ import { t as redactBase64Payloads } from "./base64-redaction-C1Uu29t5.js";
4
+ import { truncateResult } from "@cloudflare/codemode";
5
+ //#region src/browser/tool-helpers.ts
6
+ function browserScreenshotOutput(value) {
7
+ const outer = typeof value === "object" && value !== null ? value : null;
8
+ const result = outer && typeof outer.result === "object" && outer.result !== null ? outer.result : outer;
9
+ if (result?.type !== "browser_screenshot" || typeof result.mediaType !== "string" || typeof result.data !== "string") return null;
10
+ return result;
11
+ }
12
+ function transformBrowserResult(value) {
13
+ return browserScreenshotOutput(value) ? value : truncateResult(redactBase64Payloads(value));
14
+ }
15
+ /**
16
+ * @param notes Sentences appended when a screenshot collapses the output to
17
+ * text, so notices on the output aren't lost with it.
18
+ */
19
+ function browserExecuteModelOutput(output, notes = []) {
20
+ const screenshot = browserScreenshotOutput(output);
21
+ if (screenshot) {
22
+ const approximateBytes = Math.floor(screenshot.data.length * 3 / 4);
23
+ return {
24
+ type: "text",
25
+ value: [`Screenshot captured successfully (${screenshot.mediaType}, approximately ${approximateBytes.toLocaleString()} bytes); the image is kept for the UI and omitted here.`, ...notes].join(" ")
26
+ };
27
+ }
28
+ const redacted = redactBase64Payloads(typeof output === "object" && output !== null && !Array.isArray(output) ? (({ calls: _calls, ...rest }) => ({
29
+ ...rest,
30
+ ...Array.isArray(rest.logs) ? { logs: truncateResult(rest.logs) } : {}
31
+ }))(output) : output);
32
+ try {
33
+ const serialized = JSON.stringify(redacted);
34
+ return {
35
+ type: "json",
36
+ value: serialized === void 0 ? null : JSON.parse(serialized)
37
+ };
38
+ } catch {
39
+ return {
40
+ type: "text",
41
+ value: "Browser execution completed, but its result could not be serialized for model context."
42
+ };
43
+ }
44
+ }
45
+ /**
46
+ * The Durable Object state to build the runtime in: the explicit `ctx` if
47
+ * given, otherwise the current Agent's `ctx` (via `getCurrentAgent()`), so
48
+ * `createBrowserRuntime` can be called from an Agent method without threading
49
+ * `this.ctx` through.
50
+ */
51
+ function resolveCtx(options) {
52
+ if (options.ctx) return options.ctx;
53
+ return (__DO_NOT_USE_WILL_BREAK__agentContext.getStore()?.agent)?.ctx;
54
+ }
55
+ //#endregion
56
+ export { transformBrowserResult as i, browserScreenshotOutput as n, resolveCtx as r, browserExecuteModelOutput as t };
57
+
58
+ //# sourceMappingURL=tool-helpers-O5BDVEAY.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool-helpers-O5BDVEAY.js","names":["agentContext"],"sources":["../src/browser/tool-helpers.ts"],"sourcesContent":["/**\n * Helpers shared by the browser tools: `createBrowserTools` in `ai.ts`, and\n * the `browserTool` adapters in `tools/`. Internal — not an entry point.\n */\nimport type { JSONValue } from \"ai\";\nimport { truncateResult } from \"@cloudflare/codemode\";\nimport { redactBase64Payloads } from \"../core/base64-redaction\";\nimport { __DO_NOT_USE_WILL_BREAK__agentContext as agentContext } from \"../internal_context\";\n\ninterface BrowserScreenshotOutput {\n type: \"browser_screenshot\";\n mediaType: string;\n data: string;\n}\n\nexport function browserScreenshotOutput(\n value: unknown\n): BrowserScreenshotOutput | null {\n const outer =\n typeof value === \"object\" && value !== null\n ? (value as Record<string, unknown>)\n : null;\n const result =\n outer && typeof outer.result === \"object\" && outer.result !== null\n ? (outer.result as Record<string, unknown>)\n : outer;\n if (\n result?.type !== \"browser_screenshot\" ||\n typeof result.mediaType !== \"string\" ||\n typeof result.data !== \"string\"\n ) {\n return null;\n }\n return result as unknown as BrowserScreenshotOutput;\n}\n\nexport function transformBrowserResult(value: unknown): unknown {\n // Keep canonical screenshot output intact for UIMessage persistence and the\n // chat renderer. Other results are redacted before truncation so a nested\n // binary payload cannot become a large serialized preview.\n return browserScreenshotOutput(value)\n ? value\n : truncateResult(redactBase64Payloads(value));\n}\n\n/** What the model sees in place of a browser tool's output. */\nexport type BrowserModelOutput =\n | { type: \"text\"; value: string }\n | { type: \"json\"; value: JSONValue };\n\n/**\n * @param notes Sentences appended when a screenshot collapses the output to\n * text, so notices on the output aren't lost with it.\n */\nexport function browserExecuteModelOutput(\n output: unknown,\n notes: string[] = []\n): BrowserModelOutput {\n const screenshot = browserScreenshotOutput(output);\n if (screenshot) {\n const approximateBytes = Math.floor((screenshot.data.length * 3) / 4);\n return {\n type: \"text\",\n value: [\n `Screenshot captured successfully (${screenshot.mediaType}, approximately ${approximateBytes.toLocaleString()} bytes); the image is kept for the UI and omitted here.`,\n ...notes\n ].join(\" \")\n };\n }\n\n // `calls` is the durable audit log; like the codemode tool's own projection,\n // it stays on the persisted part and never enters the model's context, and\n // the sandbox `logs` are bounded like a result.\n const modelFacing =\n typeof output === \"object\" && output !== null && !Array.isArray(output)\n ? (({ calls: _calls, ...rest }: { calls?: unknown; logs?: unknown }) => ({\n ...rest,\n ...(Array.isArray(rest.logs)\n ? { logs: truncateResult(rest.logs) }\n : {})\n }))(output)\n : output;\n const redacted = redactBase64Payloads(modelFacing);\n try {\n const serialized = JSON.stringify(redacted);\n return {\n type: \"json\",\n value:\n serialized === undefined ? null : (JSON.parse(serialized) as JSONValue)\n };\n } catch {\n return {\n type: \"text\",\n value:\n \"Browser execution completed, but its result could not be serialized for model context.\"\n };\n }\n}\n\n/**\n * The Durable Object state to build the runtime in: the explicit `ctx` if\n * given, otherwise the current Agent's `ctx` (via `getCurrentAgent()`), so\n * `createBrowserRuntime` can be called from an Agent method without threading\n * `this.ctx` through.\n */\nexport function resolveCtx(options: {\n ctx?: DurableObjectState;\n}): DurableObjectState | undefined {\n if (options.ctx) return options.ctx;\n const agent = agentContext.getStore()?.agent as\n | { ctx?: DurableObjectState }\n | undefined;\n return agent?.ctx;\n}\n"],"mappings":";;;;;AAeA,SAAgB,wBACd,OACgC;CAChC,MAAM,QACJ,OAAO,UAAU,YAAY,UAAU,OAClC,QACD;CACN,MAAM,SACJ,SAAS,OAAO,MAAM,WAAW,YAAY,MAAM,WAAW,OACzD,MAAM,SACP;CACN,IACE,QAAQ,SAAS,wBACjB,OAAO,OAAO,cAAc,YAC5B,OAAO,OAAO,SAAS,UAEvB,OAAO;CAET,OAAO;AACT;AAEA,SAAgB,uBAAuB,OAAyB;CAI9D,OAAO,wBAAwB,KAAK,IAChC,QACA,eAAe,qBAAqB,KAAK,CAAC;AAChD;;;;;AAWA,SAAgB,0BACd,QACA,QAAkB,CAAC,GACC;CACpB,MAAM,aAAa,wBAAwB,MAAM;CACjD,IAAI,YAAY;EACd,MAAM,mBAAmB,KAAK,MAAO,WAAW,KAAK,SAAS,IAAK,CAAC;EACpE,OAAO;GACL,MAAM;GACN,OAAO,CACL,qCAAqC,WAAW,UAAU,kBAAkB,iBAAiB,eAAe,EAAE,0DAC9G,GAAG,KACL,CAAC,CAAC,KAAK,GAAG;EACZ;CACF;CAcA,MAAM,WAAW,qBARf,OAAO,WAAW,YAAY,WAAW,QAAQ,CAAC,MAAM,QAAQ,MAAM,MAChE,EAAE,OAAO,QAAQ,GAAG,YAAiD;EACrE,GAAG;EACH,GAAI,MAAM,QAAQ,KAAK,IAAI,IACvB,EAAE,MAAM,eAAe,KAAK,IAAI,EAAE,IAClC,CAAC;CACP,GAAA,CAAI,MAAM,IACV,MAC2C;CACjD,IAAI;EACF,MAAM,aAAa,KAAK,UAAU,QAAQ;EAC1C,OAAO;GACL,MAAM;GACN,OACE,eAAe,KAAA,IAAY,OAAQ,KAAK,MAAM,UAAU;EAC5D;CACF,QAAQ;EACN,OAAO;GACL,MAAM;GACN,OACE;EACJ;CACF;AACF;;;;;;;AAQA,SAAgB,WAAW,SAEQ;CACjC,IAAI,QAAQ,KAAK,OAAO,QAAQ;CAIhC,QAHcA,sCAAa,SAAS,CAAC,EAAE,MAAA,EAGzB;AAChB"}
@@ -1,4 +1,4 @@
1
- import { a as ResolvedGateway } from "./settings-NgGwF7Qt.js";
1
+ import { a as ResolvedGateway } from "./settings-DnD__xuE.js";
2
2
 
3
3
  //#region src/models/core/errors.d.ts
4
4
  /**
@@ -197,4 +197,4 @@ export {
197
197
  GatewayProviderName as r,
198
198
  Transport as t
199
199
  };
200
- //# sourceMappingURL=transport-k2mFrtL8.d.ts.map
200
+ //# sourceMappingURL=transport-DCyarnwm.d.ts.map
@@ -1,5 +1,5 @@
1
- import { x as Connection } from "../capability-runner-O5VbQzqg.js";
2
- import { c as Agent } from "../agent-routing-Bhdbvf7s.js";
1
+ import { x as Connection } from "../capability-runner-BiVUtjqC.js";
2
+ import { c as Agent } from "../agent-routing-BMvWTFEp.js";
3
3
  import {
4
4
  C as VoiceTransport,
5
5
  D as VoiceTurnSource,
@@ -0,0 +1,89 @@
1
+ import {
2
+ C as WindowWebFetchPageOptions,
3
+ S as WebFetchVia,
4
+ T as windowWebFetchPage,
5
+ _ as WEB_FETCH_TOOL_NAME,
6
+ a as WebFetchCallOptions,
7
+ b as WebFetchToolInput,
8
+ c as WebFetchRequest,
9
+ d as DEFAULT_WEB_FETCH_MAX_BYTES,
10
+ f as DEFAULT_WEB_FETCH_MAX_REDIRECTS,
11
+ g as WEB_FETCH_TOOL_DESCRIPTION,
12
+ h as MAX_WEB_FETCH_URL_LENGTH,
13
+ i as DirectWebFetchOptions,
14
+ l as WebFetchSource,
15
+ m as DEFAULT_WEB_FETCH_TIMEOUT_MS,
16
+ n as WebFetchToolOptions,
17
+ o as WebFetchError,
18
+ p as DEFAULT_WEB_FETCH_PAGE_CHARS,
19
+ r as WebFetchToolSourceOptions,
20
+ s as WebFetchErrorCode,
21
+ t as WebFetchToolDirectOptions,
22
+ u as createDirectWebFetch,
23
+ v as WebFetchFormat,
24
+ w as renderWebFetchPage,
25
+ x as WebFetchToolOutput,
26
+ y as WebFetchPage
27
+ } from "../../tool-DoVberpN.js";
28
+
29
+ //#region src/web/url-policy.d.ts
30
+ /**
31
+ * Whether a host, as `URL.hostname` gives it, is in one of the ranges below
32
+ * (IPv4, or IPv6 including IPv4-mapped, NAT64 and 6to4 forms), or is
33
+ * `localhost` or ends in `.localhost` or `.internal`.
34
+ */
35
+ declare function isPrivateOrLocalHost(hostname: string): boolean;
36
+ //#endregion
37
+ //#region src/web/fetch/index.d.ts
38
+ /** Options for {@link fetchWeb}: the direct source's, plus a deadline. */
39
+ interface FetchWebOptions extends DirectWebFetchOptions {
40
+ /**
41
+ * Give up after this many milliseconds with a `web_fetch_timeout` error.
42
+ * A positive integer; defaults to 30 seconds.
43
+ */
44
+ timeoutMs?: number;
45
+ /** Abort the fetch; rejects with the signal's reason. */
46
+ signal?: AbortSignal;
47
+ }
48
+ /**
49
+ * Fetch one URL directly, without a tool: {@link createDirectWebFetch} plus
50
+ * a deadline. Returns the whole page; to show it to a model a window at a
51
+ * time, as the tool does, pass it to {@link windowWebFetchPage} and
52
+ * {@link renderWebFetchPage}.
53
+ */
54
+ declare function fetchWeb(
55
+ request: WebFetchRequest,
56
+ options: FetchWebOptions
57
+ ): Promise<WebFetchPage>;
58
+ //#endregion
59
+ export {
60
+ DEFAULT_WEB_FETCH_MAX_BYTES,
61
+ DEFAULT_WEB_FETCH_MAX_REDIRECTS,
62
+ DEFAULT_WEB_FETCH_PAGE_CHARS,
63
+ DEFAULT_WEB_FETCH_TIMEOUT_MS,
64
+ type DirectWebFetchOptions,
65
+ FetchWebOptions,
66
+ MAX_WEB_FETCH_URL_LENGTH,
67
+ WEB_FETCH_TOOL_DESCRIPTION,
68
+ WEB_FETCH_TOOL_NAME,
69
+ type WebFetchCallOptions,
70
+ WebFetchError,
71
+ type WebFetchErrorCode,
72
+ type WebFetchFormat,
73
+ type WebFetchPage,
74
+ type WebFetchRequest,
75
+ type WebFetchSource,
76
+ type WebFetchToolDirectOptions,
77
+ type WebFetchToolInput,
78
+ type WebFetchToolOptions,
79
+ type WebFetchToolOutput,
80
+ type WebFetchToolSourceOptions,
81
+ type WebFetchVia,
82
+ type WindowWebFetchPageOptions,
83
+ createDirectWebFetch,
84
+ fetchWeb,
85
+ isPrivateOrLocalHost,
86
+ renderWebFetchPage,
87
+ windowWebFetchPage
88
+ };
89
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,20 @@
1
+ import { a as WebFetchError, c as DEFAULT_WEB_FETCH_MAX_REDIRECTS, d as MAX_WEB_FETCH_URL_LENGTH, f as WEB_FETCH_TOOL_DESCRIPTION, g as isPrivateOrLocalHost, h as windowWebFetchPage, i as validateTimeout, l as DEFAULT_WEB_FETCH_PAGE_CHARS, m as renderWebFetchPage, n as fetchWithDeadline, o as createDirectWebFetch, p as WEB_FETCH_TOOL_NAME, s as DEFAULT_WEB_FETCH_MAX_BYTES, u as DEFAULT_WEB_FETCH_TIMEOUT_MS } from "../../tool-CxKsvxjm.js";
2
+ //#region src/web/fetch/index.ts
3
+ /**
4
+ * Fetch one URL directly, without a tool: {@link createDirectWebFetch} plus
5
+ * a deadline. Returns the whole page; to show it to a model a window at a
6
+ * time, as the tool does, pass it to {@link windowWebFetchPage} and
7
+ * {@link renderWebFetchPage}.
8
+ */
9
+ async function fetchWeb(request, options) {
10
+ const { timeoutMs, signal, ...sourceOptions } = options;
11
+ const deadline = validateTimeout(timeoutMs);
12
+ return fetchWithDeadline(createDirectWebFetch(sourceOptions), request, {
13
+ timeoutMs: deadline,
14
+ signal
15
+ });
16
+ }
17
+ //#endregion
18
+ export { DEFAULT_WEB_FETCH_MAX_BYTES, DEFAULT_WEB_FETCH_MAX_REDIRECTS, DEFAULT_WEB_FETCH_PAGE_CHARS, DEFAULT_WEB_FETCH_TIMEOUT_MS, MAX_WEB_FETCH_URL_LENGTH, WEB_FETCH_TOOL_DESCRIPTION, WEB_FETCH_TOOL_NAME, WebFetchError, createDirectWebFetch, fetchWeb, isPrivateOrLocalHost, renderWebFetchPage, windowWebFetchPage };
19
+
20
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../src/web/fetch/index.ts"],"sourcesContent":["/**\n * `agents/webfetch` — read a URL as Markdown, JSON, or text, with\n * host-controlled URL policy and size limits, from a Worker.\n *\n * The tool adapters live beside this entry: `agents/webfetch/pi`,\n * `agents/webfetch/ai-sdk`, and `agents/webfetch/tanstack-ai`. Import from\n * here to fetch without a model in the loop, or to build a source for the\n * tools.\n *\n * @beta\n */\nimport type { WebFetchPage } from \"./contract\";\nimport {\n createDirectWebFetch,\n type DirectWebFetchOptions,\n type WebFetchRequest\n} from \"./source\";\nimport { fetchWithDeadline, validateTimeout } from \"./tool\";\n\nexport {\n DEFAULT_WEB_FETCH_MAX_BYTES,\n DEFAULT_WEB_FETCH_MAX_REDIRECTS,\n DEFAULT_WEB_FETCH_PAGE_CHARS,\n DEFAULT_WEB_FETCH_TIMEOUT_MS,\n MAX_WEB_FETCH_URL_LENGTH,\n WEB_FETCH_TOOL_DESCRIPTION,\n WEB_FETCH_TOOL_NAME,\n renderWebFetchPage,\n windowWebFetchPage,\n type WebFetchFormat,\n type WebFetchPage,\n type WebFetchToolInput,\n type WebFetchToolOutput,\n type WebFetchVia,\n type WindowWebFetchPageOptions\n} from \"./contract\";\nexport {\n WebFetchError,\n createDirectWebFetch,\n type DirectWebFetchOptions,\n type WebFetchCallOptions,\n type WebFetchErrorCode,\n type WebFetchRequest,\n type WebFetchSource\n} from \"./source\";\nexport { isPrivateOrLocalHost } from \"../url-policy\";\nexport {\n type WebFetchToolDirectOptions,\n type WebFetchToolOptions,\n type WebFetchToolSourceOptions\n} from \"./tool\";\n\n/** Options for {@link fetchWeb}: the direct source's, plus a deadline. */\nexport interface FetchWebOptions extends DirectWebFetchOptions {\n /**\n * Give up after this many milliseconds with a `web_fetch_timeout` error.\n * A positive integer; defaults to 30 seconds.\n */\n timeoutMs?: number;\n /** Abort the fetch; rejects with the signal's reason. */\n signal?: AbortSignal;\n}\n\n/**\n * Fetch one URL directly, without a tool: {@link createDirectWebFetch} plus\n * a deadline. Returns the whole page; to show it to a model a window at a\n * time, as the tool does, pass it to {@link windowWebFetchPage} and\n * {@link renderWebFetchPage}.\n */\nexport async function fetchWeb(\n request: WebFetchRequest,\n options: FetchWebOptions\n): Promise<WebFetchPage> {\n const { timeoutMs, signal, ...sourceOptions } = options;\n const deadline = validateTimeout(timeoutMs);\n const source = createDirectWebFetch(sourceOptions);\n return fetchWithDeadline(source, request, { timeoutMs: deadline, signal });\n}\n"],"mappings":";;;;;;;;AAqEA,eAAsB,SACpB,SACA,SACuB;CACvB,MAAM,EAAE,WAAW,QAAQ,GAAG,kBAAkB;CAChD,MAAM,WAAW,gBAAgB,SAAS;CAE1C,OAAO,kBADQ,qBAAqB,aACN,GAAG,SAAS;EAAE,WAAW;EAAU;CAAO,CAAC;AAC3E"}
@@ -0,0 +1,80 @@
1
+ import {
2
+ S as WebFetchVia,
3
+ b as WebFetchToolInput,
4
+ c as WebFetchRequest,
5
+ l as WebFetchSource,
6
+ n as WebFetchToolOptions,
7
+ o as WebFetchError,
8
+ s as WebFetchErrorCode,
9
+ v as WebFetchFormat,
10
+ x as WebFetchToolOutput,
11
+ y as WebFetchPage
12
+ } from "../../../tool-DoVberpN.js";
13
+ import { FlexibleSchema } from "ai";
14
+
15
+ //#region src/web/fetch/tools/ai-sdk.d.ts
16
+ /**
17
+ * The part of the AI SDK's tool execution options the tool reads. Spelled
18
+ * out rather than imported so it fits every supported `ai` major.
19
+ */
20
+ interface WebFetchToolExecuteOptions {
21
+ abortSignal?: AbortSignal;
22
+ }
23
+ /**
24
+ * The AI SDK tool {@link webFetchTool} returns. Assignable to the AI SDK's
25
+ * `Tool`; `execute` and `toModelOutput` are always present.
26
+ */
27
+ interface WebFetchTool {
28
+ description: string;
29
+ inputSchema: FlexibleSchema<WebFetchToolInput>;
30
+ execute(
31
+ input: WebFetchToolInput,
32
+ options: WebFetchToolExecuteOptions
33
+ ): Promise<WebFetchToolOutput>;
34
+ toModelOutput(options: { output: WebFetchToolOutput }): {
35
+ type: "text";
36
+ value: string;
37
+ };
38
+ }
39
+ /**
40
+ * Create an AI SDK tool that reads a URL as Markdown, JSON, or text. The
41
+ * tool's output is the window the model read plus the page's metadata
42
+ * (status, headers, redirects, total length), so it stays small in stored
43
+ * messages; `toModelOutput` renders it for the model. A failed fetch throws a `WebFetchError`, which
44
+ * the AI SDK reports to the model as a tool error: its `message` is written
45
+ * for the model, and its `cause` is the source's error with the detail.
46
+ *
47
+ * `toModelOutput` only applies to earlier turns when the tools are passed to
48
+ * `convertToModelMessages(messages, { tools })`; otherwise the AI SDK sends
49
+ * the output back to the model as JSON, without the header or the
50
+ * untrusted-content wrapper. `AiSdkHarness` passes them.
51
+ *
52
+ * @example
53
+ * ```ts
54
+ * import { webFetchTool } from "agents/webfetch/ai-sdk";
55
+ *
56
+ * const result = streamText({
57
+ * model,
58
+ * tools: { web_fetch: webFetchTool({ binding: env.AI }) },
59
+ * messages
60
+ * });
61
+ * ```
62
+ */
63
+ declare function webFetchTool(options: WebFetchToolOptions): WebFetchTool;
64
+ //#endregion
65
+ export {
66
+ WebFetchError,
67
+ type WebFetchErrorCode,
68
+ type WebFetchFormat,
69
+ type WebFetchPage,
70
+ type WebFetchRequest,
71
+ type WebFetchSource,
72
+ WebFetchTool,
73
+ WebFetchToolExecuteOptions,
74
+ type WebFetchToolInput,
75
+ type WebFetchToolOptions,
76
+ type WebFetchToolOutput,
77
+ type WebFetchVia,
78
+ webFetchTool
79
+ };
80
+ //# sourceMappingURL=ai-sdk.d.ts.map
@@ -0,0 +1,47 @@
1
+ import { a as WebFetchError, r as toolFailure, t as createWebFetchToolCore } from "../../../tool-CxKsvxjm.js";
2
+ import { t as webFetchInputSchema } from "../../../input-schema-BQykTEp_.js";
3
+ //#region src/web/fetch/tools/ai-sdk.ts
4
+ /**
5
+ * Create an AI SDK tool that reads a URL as Markdown, JSON, or text. The
6
+ * tool's output is the window the model read plus the page's metadata
7
+ * (status, headers, redirects, total length), so it stays small in stored
8
+ * messages; `toModelOutput` renders it for the model. A failed fetch throws a `WebFetchError`, which
9
+ * the AI SDK reports to the model as a tool error: its `message` is written
10
+ * for the model, and its `cause` is the source's error with the detail.
11
+ *
12
+ * `toModelOutput` only applies to earlier turns when the tools are passed to
13
+ * `convertToModelMessages(messages, { tools })`; otherwise the AI SDK sends
14
+ * the output back to the model as JSON, without the header or the
15
+ * untrusted-content wrapper. `AiSdkHarness` passes them.
16
+ *
17
+ * @example
18
+ * ```ts
19
+ * import { webFetchTool } from "agents/webfetch/ai-sdk";
20
+ *
21
+ * const result = streamText({
22
+ * model,
23
+ * tools: { web_fetch: webFetchTool({ binding: env.AI }) },
24
+ * messages
25
+ * });
26
+ * ```
27
+ */
28
+ function webFetchTool(options) {
29
+ const core = createWebFetchToolCore(options);
30
+ return {
31
+ description: core.description,
32
+ inputSchema: webFetchInputSchema(),
33
+ async execute(input, { abortSignal }) {
34
+ const run = await core.run(input, { signal: abortSignal });
35
+ if (!run.ok) throw toolFailure(run);
36
+ return run.output;
37
+ },
38
+ toModelOutput: ({ output }) => ({
39
+ type: "text",
40
+ value: core.render(output)
41
+ })
42
+ };
43
+ }
44
+ //#endregion
45
+ export { WebFetchError, webFetchTool };
46
+
47
+ //# sourceMappingURL=ai-sdk.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ai-sdk.js","names":[],"sources":["../../../../src/web/fetch/tools/ai-sdk.ts"],"sourcesContent":["/**\n * `agents/webfetch/ai-sdk` — the `web_fetch` tool for the AI SDK.\n *\n * @beta\n */\nimport type { FlexibleSchema } from \"ai\";\nimport type { WebFetchToolInput, WebFetchToolOutput } from \"../contract\";\nimport {\n createWebFetchToolCore,\n toolFailure,\n type WebFetchToolOptions\n} from \"../tool\";\nimport { webFetchInputSchema } from \"./input-schema\";\n\nexport type {\n WebFetchFormat,\n WebFetchPage,\n WebFetchToolInput,\n WebFetchToolOutput,\n WebFetchVia\n} from \"../contract\";\nexport {\n WebFetchError,\n type WebFetchErrorCode,\n type WebFetchRequest,\n type WebFetchSource\n} from \"../source\";\nexport type { WebFetchToolOptions } from \"../tool\";\n\n/**\n * The part of the AI SDK's tool execution options the tool reads. Spelled\n * out rather than imported so it fits every supported `ai` major.\n */\nexport interface WebFetchToolExecuteOptions {\n abortSignal?: AbortSignal;\n}\n\n/**\n * The AI SDK tool {@link webFetchTool} returns. Assignable to the AI SDK's\n * `Tool`; `execute` and `toModelOutput` are always present.\n */\nexport interface WebFetchTool {\n description: string;\n inputSchema: FlexibleSchema<WebFetchToolInput>;\n execute(\n input: WebFetchToolInput,\n options: WebFetchToolExecuteOptions\n ): Promise<WebFetchToolOutput>;\n toModelOutput(options: { output: WebFetchToolOutput }): {\n type: \"text\";\n value: string;\n };\n}\n\n/**\n * Create an AI SDK tool that reads a URL as Markdown, JSON, or text. The\n * tool's output is the window the model read plus the page's metadata\n * (status, headers, redirects, total length), so it stays small in stored\n * messages; `toModelOutput` renders it for the model. A failed fetch throws a `WebFetchError`, which\n * the AI SDK reports to the model as a tool error: its `message` is written\n * for the model, and its `cause` is the source's error with the detail.\n *\n * `toModelOutput` only applies to earlier turns when the tools are passed to\n * `convertToModelMessages(messages, { tools })`; otherwise the AI SDK sends\n * the output back to the model as JSON, without the header or the\n * untrusted-content wrapper. `AiSdkHarness` passes them.\n *\n * @example\n * ```ts\n * import { webFetchTool } from \"agents/webfetch/ai-sdk\";\n *\n * const result = streamText({\n * model,\n * tools: { web_fetch: webFetchTool({ binding: env.AI }) },\n * messages\n * });\n * ```\n */\nexport function webFetchTool(options: WebFetchToolOptions): WebFetchTool {\n const core = createWebFetchToolCore(options);\n return {\n description: core.description,\n inputSchema: webFetchInputSchema(),\n async execute(input, { abortSignal }) {\n const run = await core.run(input, { signal: abortSignal });\n if (!run.ok) throw toolFailure(run);\n return run.output;\n },\n toModelOutput: ({ output }) => ({\n type: \"text\",\n value: core.render(output)\n })\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA8EA,SAAgB,aAAa,SAA4C;CACvE,MAAM,OAAO,uBAAuB,OAAO;CAC3C,OAAO;EACL,aAAa,KAAK;EAClB,aAAa,oBAAoB;EACjC,MAAM,QAAQ,OAAO,EAAE,eAAe;GACpC,MAAM,MAAM,MAAM,KAAK,IAAI,OAAO,EAAE,QAAQ,YAAY,CAAC;GACzD,IAAI,CAAC,IAAI,IAAI,MAAM,YAAY,GAAG;GAClC,OAAO,IAAI;EACb;EACA,gBAAgB,EAAE,cAAc;GAC9B,MAAM;GACN,OAAO,KAAK,OAAO,MAAM;EAC3B;CACF;AACF"}
@@ -0,0 +1,84 @@
1
+ import {
2
+ S as WebFetchVia,
3
+ b as WebFetchToolInput,
4
+ c as WebFetchRequest,
5
+ l as WebFetchSource,
6
+ n as WebFetchToolOptions,
7
+ o as WebFetchError,
8
+ s as WebFetchErrorCode,
9
+ v as WebFetchFormat,
10
+ x as WebFetchToolOutput,
11
+ y as WebFetchPage
12
+ } from "../../../tool-DoVberpN.js";
13
+ import { Type } from "@earendil-works/pi-ai";
14
+ import { ToolRegistration } from "@earendil-works/pi-durable";
15
+
16
+ //#region src/web/fetch/tools/pi.d.ts
17
+ /** The model's input schema. pi already coerces `"20000"` to `20000`. */
18
+ declare function webFetchParameters(): Type.TObject<{
19
+ url: Type.TString;
20
+ offset: Type.TOptional<Type.TInteger>;
21
+ format: Type.TOptional<
22
+ Type.TUnion<[Type.TLiteral<"auto">, Type.TLiteral<"raw">]>
23
+ >;
24
+ }>;
25
+ type WebFetchParameters = ReturnType<typeof webFetchParameters>;
26
+ /**
27
+ * Host-side details pi stores with each `web_fetch` result: the output (the
28
+ * window the model read, with the page's metadata) or the failure.
29
+ */
30
+ type WebFetchToolDetails =
31
+ | {
32
+ ok: true;
33
+ output: WebFetchToolOutput;
34
+ }
35
+ | {
36
+ ok: false /** The source's error message, with the detail for the host. */;
37
+ message: string;
38
+ status: number;
39
+ code: WebFetchErrorCode;
40
+ retryable: boolean;
41
+ url?: string /** The response's media type, when a response was read. */;
42
+ contentType?: string;
43
+ };
44
+ /**
45
+ * Create a pi tool that reads a URL as Markdown, JSON, or text. Install it
46
+ * on a registry like any other pi tool.
47
+ *
48
+ * The model chooses the URL, the window (`offset`), and the format; the
49
+ * host chooses the URL policy, size limits, and window size. The tool is
50
+ * `replay: "safe"`: a fetch interrupted mid-call (say, by an eviction) runs
51
+ * again when the session recovers. Completed results are stored and not
52
+ * fetched again.
53
+ *
54
+ * @example
55
+ * ```ts
56
+ * import { createRegistry } from "@earendil-works/pi-durable";
57
+ * import { webFetchTool } from "agents/webfetch/pi";
58
+ *
59
+ * const registry = createRegistry();
60
+ * registry.install({
61
+ * name: "tools",
62
+ * tools: [webFetchTool({ binding: env.AI })]
63
+ * });
64
+ * ```
65
+ */
66
+ declare function webFetchTool(
67
+ options: WebFetchToolOptions
68
+ ): ToolRegistration<WebFetchParameters, WebFetchToolDetails>;
69
+ //#endregion
70
+ export {
71
+ WebFetchError,
72
+ type WebFetchErrorCode,
73
+ type WebFetchFormat,
74
+ type WebFetchPage,
75
+ type WebFetchRequest,
76
+ type WebFetchSource,
77
+ WebFetchToolDetails,
78
+ type WebFetchToolInput,
79
+ type WebFetchToolOptions,
80
+ type WebFetchToolOutput,
81
+ type WebFetchVia,
82
+ webFetchTool
83
+ };
84
+ //# sourceMappingURL=pi.d.ts.map
@@ -0,0 +1,88 @@
1
+ import { a as WebFetchError, d as MAX_WEB_FETCH_URL_LENGTH, t as createWebFetchToolCore } from "../../../tool-CxKsvxjm.js";
2
+ import { Type } from "@earendil-works/pi-ai";
3
+ //#region src/web/fetch/tools/pi.ts
4
+ /**
5
+ * `agents/webfetch/pi` — the `web_fetch` tool for the pi harness.
6
+ *
7
+ * @beta
8
+ */
9
+ /** The model's input schema. pi already coerces `"20000"` to `20000`. */
10
+ function webFetchParameters() {
11
+ return Type.Object({
12
+ url: Type.String({
13
+ minLength: 1,
14
+ maxLength: MAX_WEB_FETCH_URL_LENGTH,
15
+ description: "The http(s) URL to read."
16
+ }),
17
+ offset: Type.Optional(Type.Integer({
18
+ minimum: 0,
19
+ description: "Character offset into the content, to continue a long page from the previous result's offset. Default 0."
20
+ })),
21
+ format: Type.Optional(Type.Union([Type.Literal("auto"), Type.Literal("raw")], { description: "\"auto\" (default) converts to the most readable form; \"raw\" returns the body as served." }))
22
+ });
23
+ }
24
+ /**
25
+ * Create a pi tool that reads a URL as Markdown, JSON, or text. Install it
26
+ * on a registry like any other pi tool.
27
+ *
28
+ * The model chooses the URL, the window (`offset`), and the format; the
29
+ * host chooses the URL policy, size limits, and window size. The tool is
30
+ * `replay: "safe"`: a fetch interrupted mid-call (say, by an eviction) runs
31
+ * again when the session recovers. Completed results are stored and not
32
+ * fetched again.
33
+ *
34
+ * @example
35
+ * ```ts
36
+ * import { createRegistry } from "@earendil-works/pi-durable";
37
+ * import { webFetchTool } from "agents/webfetch/pi";
38
+ *
39
+ * const registry = createRegistry();
40
+ * registry.install({
41
+ * name: "tools",
42
+ * tools: [webFetchTool({ binding: env.AI })]
43
+ * });
44
+ * ```
45
+ */
46
+ function webFetchTool(options) {
47
+ const core = createWebFetchToolCore(options);
48
+ return {
49
+ name: core.name,
50
+ description: core.description,
51
+ parameters: webFetchParameters(),
52
+ replay: "safe",
53
+ async execute(input, _api, context) {
54
+ const run = await core.run(input, { signal: context.abortSignal });
55
+ if (run.ok) return {
56
+ content: [{
57
+ type: "text",
58
+ text: run.text
59
+ }],
60
+ details: {
61
+ ok: true,
62
+ output: run.output
63
+ }
64
+ };
65
+ const details = {
66
+ ok: false,
67
+ message: run.error.message,
68
+ status: run.error.status,
69
+ code: run.error.code,
70
+ retryable: run.error.retryable
71
+ };
72
+ if (run.error.url !== void 0) details.url = run.error.url;
73
+ if (run.error.contentType !== void 0) details.contentType = run.error.contentType;
74
+ return {
75
+ content: [{
76
+ type: "text",
77
+ text: run.text
78
+ }],
79
+ isError: true,
80
+ details
81
+ };
82
+ }
83
+ };
84
+ }
85
+ //#endregion
86
+ export { WebFetchError, webFetchTool };
87
+
88
+ //# sourceMappingURL=pi.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pi.js","names":[],"sources":["../../../../src/web/fetch/tools/pi.ts"],"sourcesContent":["/**\n * `agents/webfetch/pi` — the `web_fetch` tool for the pi harness.\n *\n * @beta\n */\nimport { Type } from \"@earendil-works/pi-ai\";\nimport type { ToolRegistration } from \"@earendil-works/pi-durable\";\nimport { MAX_WEB_FETCH_URL_LENGTH, type WebFetchToolOutput } from \"../contract\";\nimport type { WebFetchErrorCode } from \"../source\";\nimport { createWebFetchToolCore, type WebFetchToolOptions } from \"../tool\";\n\nexport type {\n WebFetchFormat,\n WebFetchPage,\n WebFetchToolInput,\n WebFetchToolOutput,\n WebFetchVia\n} from \"../contract\";\nexport {\n WebFetchError,\n type WebFetchErrorCode,\n type WebFetchRequest,\n type WebFetchSource\n} from \"../source\";\nexport type { WebFetchToolOptions } from \"../tool\";\n\n/** The model's input schema. pi already coerces `\"20000\"` to `20000`. */\nfunction webFetchParameters() {\n return Type.Object({\n url: Type.String({\n minLength: 1,\n maxLength: MAX_WEB_FETCH_URL_LENGTH,\n description: \"The http(s) URL to read.\"\n }),\n offset: Type.Optional(\n Type.Integer({\n minimum: 0,\n description:\n \"Character offset into the content, to continue a long page from the previous result's offset. Default 0.\"\n })\n ),\n format: Type.Optional(\n Type.Union([Type.Literal(\"auto\"), Type.Literal(\"raw\")], {\n description:\n '\"auto\" (default) converts to the most readable form; \"raw\" returns the body as served.'\n })\n )\n });\n}\n\ntype WebFetchParameters = ReturnType<typeof webFetchParameters>;\n\n/**\n * Host-side details pi stores with each `web_fetch` result: the output (the\n * window the model read, with the page's metadata) or the failure.\n */\nexport type WebFetchToolDetails =\n | { ok: true; output: WebFetchToolOutput }\n | {\n ok: false;\n /** The source's error message, with the detail for the host. */\n message: string;\n status: number;\n code: WebFetchErrorCode;\n retryable: boolean;\n url?: string;\n /** The response's media type, when a response was read. */\n contentType?: string;\n };\n\n/**\n * Create a pi tool that reads a URL as Markdown, JSON, or text. Install it\n * on a registry like any other pi tool.\n *\n * The model chooses the URL, the window (`offset`), and the format; the\n * host chooses the URL policy, size limits, and window size. The tool is\n * `replay: \"safe\"`: a fetch interrupted mid-call (say, by an eviction) runs\n * again when the session recovers. Completed results are stored and not\n * fetched again.\n *\n * @example\n * ```ts\n * import { createRegistry } from \"@earendil-works/pi-durable\";\n * import { webFetchTool } from \"agents/webfetch/pi\";\n *\n * const registry = createRegistry();\n * registry.install({\n * name: \"tools\",\n * tools: [webFetchTool({ binding: env.AI })]\n * });\n * ```\n */\nexport function webFetchTool(\n options: WebFetchToolOptions\n): ToolRegistration<WebFetchParameters, WebFetchToolDetails> {\n const core = createWebFetchToolCore(options);\n return {\n name: core.name,\n description: core.description,\n parameters: webFetchParameters(),\n replay: \"safe\",\n async execute(input, _api, context) {\n const run = await core.run(input, { signal: context.abortSignal });\n if (run.ok) {\n return {\n content: [{ type: \"text\", text: run.text }],\n details: { ok: true, output: run.output }\n };\n }\n const details: WebFetchToolDetails = {\n ok: false,\n message: run.error.message,\n status: run.error.status,\n code: run.error.code,\n retryable: run.error.retryable\n };\n if (run.error.url !== undefined) details.url = run.error.url;\n if (run.error.contentType !== undefined) {\n details.contentType = run.error.contentType;\n }\n return {\n content: [{ type: \"text\", text: run.text }],\n isError: true,\n details\n };\n }\n };\n}\n"],"mappings":";;;;;;;;;AA2BA,SAAS,qBAAqB;CAC5B,OAAO,KAAK,OAAO;EACjB,KAAK,KAAK,OAAO;GACf,WAAW;GACX,WAAW;GACX,aAAa;EACf,CAAC;EACD,QAAQ,KAAK,SACX,KAAK,QAAQ;GACX,SAAS;GACT,aACE;EACJ,CAAC,CACH;EACA,QAAQ,KAAK,SACX,KAAK,MAAM,CAAC,KAAK,QAAQ,MAAM,GAAG,KAAK,QAAQ,KAAK,CAAC,GAAG,EACtD,aACE,6FACJ,CAAC,CACH;CACF,CAAC;AACH;;;;;;;;;;;;;;;;;;;;;;;AA4CA,SAAgB,aACd,SAC2D;CAC3D,MAAM,OAAO,uBAAuB,OAAO;CAC3C,OAAO;EACL,MAAM,KAAK;EACX,aAAa,KAAK;EAClB,YAAY,mBAAmB;EAC/B,QAAQ;EACR,MAAM,QAAQ,OAAO,MAAM,SAAS;GAClC,MAAM,MAAM,MAAM,KAAK,IAAI,OAAO,EAAE,QAAQ,QAAQ,YAAY,CAAC;GACjE,IAAI,IAAI,IACN,OAAO;IACL,SAAS,CAAC;KAAE,MAAM;KAAQ,MAAM,IAAI;IAAK,CAAC;IAC1C,SAAS;KAAE,IAAI;KAAM,QAAQ,IAAI;IAAO;GAC1C;GAEF,MAAM,UAA+B;IACnC,IAAI;IACJ,SAAS,IAAI,MAAM;IACnB,QAAQ,IAAI,MAAM;IAClB,MAAM,IAAI,MAAM;IAChB,WAAW,IAAI,MAAM;GACvB;GACA,IAAI,IAAI,MAAM,QAAQ,KAAA,GAAW,QAAQ,MAAM,IAAI,MAAM;GACzD,IAAI,IAAI,MAAM,gBAAgB,KAAA,GAC5B,QAAQ,cAAc,IAAI,MAAM;GAElC,OAAO;IACL,SAAS,CAAC;KAAE,MAAM;KAAQ,MAAM,IAAI;IAAK,CAAC;IAC1C,SAAS;IACT;GACF;EACF;CACF;AACF"}