agents 0.26.0 → 0.28.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -9
- package/dist/abortable-C1SpfVoi.js +21 -0
- package/dist/abortable-C1SpfVoi.js.map +1 -0
- package/dist/{agent-routing-0DR0Tk2v.d.ts → agent-routing-QDcchcQP.d.ts} +16 -16
- package/dist/agent-routing.d.ts +1 -1
- package/dist/agent-tool-types.d.ts +1 -1
- package/dist/{agent-tools-YrATZJu2.d.ts → agent-tools-DHL2XI7u.d.ts} +2 -2
- package/dist/agent-tools.d.ts +1 -1
- package/dist/ai-ahruGw7e.d.ts +239 -0
- package/dist/ai-sdk-Bdsf6mSA.js +2444 -0
- package/dist/ai-sdk-Bdsf6mSA.js.map +1 -0
- package/dist/apply-chunks-1FheRb9W.js +99 -0
- package/dist/apply-chunks-1FheRb9W.js.map +1 -0
- package/dist/broadcast-state-CEyI4uAK.js +69 -0
- package/dist/broadcast-state-CEyI4uAK.js.map +1 -0
- package/dist/browser/ai.d.ts +8 -227
- package/dist/browser/ai.js +259 -1
- package/dist/browser/ai.js.map +1 -0
- package/dist/browser/index.d.ts +56 -46
- package/dist/browser/index.js +4 -361
- package/dist/browser/{ai-sdk.d.ts → tools/ai-sdk.d.ts} +7 -7
- package/dist/browser/{ai-sdk.js → tools/ai-sdk.js} +6 -5
- package/dist/browser/tools/ai-sdk.js.map +1 -0
- package/dist/browser/tools/pi.d.ts +111 -0
- package/dist/browser/tools/pi.js +119 -0
- package/dist/browser/tools/pi.js.map +1 -0
- package/dist/browser/{tanstack-ai.d.ts → tools/tanstack-ai.d.ts} +39 -37
- package/dist/browser/{tanstack-ai.js → tools/tanstack-ai.js} +73 -59
- package/dist/browser/tools/tanstack-ai.js.map +1 -0
- package/dist/browser-CEdNlsaD.js +481 -0
- package/dist/browser-CEdNlsaD.js.map +1 -0
- package/dist/{browser-DE3d-RLk.d.ts → browser-D30VlpcA.d.ts} +63 -37
- package/dist/{browser-tool-CQ10e6Kj.js → browser-tool-4iomavs_.js} +198 -62
- package/dist/browser-tool-4iomavs_.js.map +1 -0
- package/dist/{browser-tool-DuNdlwZ9.d.ts → browser-tool-vtrPOV8e.d.ts} +25 -6
- package/dist/{capability-B4WbF81e.js → capability-DBAKc6UZ.js} +1 -3
- package/dist/capability-DBAKc6UZ.js.map +1 -0
- package/dist/{capability-runner-DBAnGr6L.d.ts → capability-runner-BiVUtjqC.d.ts} +9 -7
- package/dist/channel-Bak_6zDP.d.ts +333 -0
- package/dist/chat/index.d.ts +11 -9
- package/dist/chat/index.js +5 -194
- package/dist/chat/index.js.map +1 -1
- package/dist/chat/react.d.ts +2 -4
- package/dist/chat/react.js +3 -1
- package/dist/chat/react.js.map +1 -1
- package/dist/chat-sdk/index.d.ts +1 -1
- package/dist/chat-sdk/index.js +1 -1
- package/dist/cli.js +144 -0
- package/dist/{client-je3koD9Z.d.ts → client-BGIQKJhX.d.ts} +2 -2
- package/dist/{client-fyQrLGkD.js → client-BnYbNT3z.js} +29 -5
- package/dist/client-BnYbNT3z.js.map +1 -0
- package/dist/client-tools-aIBO0Fk7.d.ts +53 -0
- package/dist/client.d.ts +1 -1
- package/dist/{connector-58XDGvc3.js → connector-CtZylXdk.js} +3 -603
- package/dist/connector-CtZylXdk.js.map +1 -0
- package/dist/{connector-Cl-VqPmA.d.ts → connector-DEXzVoaY.d.ts} +9 -374
- package/dist/conversations-FjHDRZyD.d.ts +192 -0
- package/dist/{current-agent-vAk_5JMt.d.ts → current-agent-CKgT5d1O.d.ts} +3 -5
- package/dist/current-agent-DhoDkSnH.js.map +1 -1
- package/dist/daemon-core-Buubj-y1.js +481 -0
- package/dist/daemon-core-Buubj-y1.js.map +1 -0
- package/dist/daemon-core-CbohVPAu.d.ts +132 -0
- package/dist/{do-oauth-client-provider-Tmf1vgKz.d.ts → do-oauth-client-provider-DfsUcpc3.d.ts} +7 -1
- package/dist/{durable-object-lifecycle-HhgOMWq9.d.ts → durable-object-lifecycle-DOI_bzCH.d.ts} +2 -2
- package/dist/{channels/email.d.ts → experimental/channels/email/index.d.ts} +25 -12
- package/dist/{channels/email.js → experimental/channels/email/index.js} +13 -35
- package/dist/experimental/channels/email/index.js.map +1 -0
- package/dist/experimental/channels/index.d.ts +270 -0
- package/dist/experimental/channels/index.js +1186 -0
- package/dist/experimental/channels/index.js.map +1 -0
- package/dist/{channels/slack.d.ts → experimental/channels/slack/index.d.ts} +19 -9
- package/dist/experimental/channels/slack/index.js +267 -0
- package/dist/experimental/channels/slack/index.js.map +1 -0
- package/dist/{channels/telegram.d.ts → experimental/channels/telegram/index.d.ts} +19 -9
- package/dist/experimental/channels/telegram/index.js +198 -0
- package/dist/experimental/channels/telegram/index.js.map +1 -0
- package/dist/experimental/channels/web/ai-sdk.d.ts +55 -0
- package/dist/experimental/channels/web/ai-sdk.js +266 -0
- package/dist/experimental/channels/web/ai-sdk.js.map +1 -0
- package/dist/experimental/channels/web/client.d.ts +97 -0
- package/dist/experimental/channels/web/client.js +349 -0
- package/dist/experimental/channels/web/client.js.map +1 -0
- package/dist/experimental/channels/web/index.d.ts +189 -0
- package/dist/experimental/channels/web/index.js +332 -0
- package/dist/experimental/channels/web/index.js.map +1 -0
- package/dist/gateway-BFO6vRDn.d.ts +100 -0
- package/dist/handle-zAzh0UW2.d.ts +460 -0
- package/dist/harness/ai-sdk/index.d.ts +175 -0
- package/dist/harness/ai-sdk/index.js +605 -0
- package/dist/harness/ai-sdk/index.js.map +1 -0
- package/dist/harness/container/daemon/index.d.ts +76 -0
- package/dist/harness/container/daemon/index.js +3 -0
- package/dist/harness/container/index.d.ts +740 -0
- package/dist/harness/container/index.js +2152 -0
- package/dist/harness/container/index.js.map +1 -0
- package/dist/harness/container/runtime/index.d.ts +144 -0
- package/dist/harness/container/runtime/index.js +1082 -0
- package/dist/harness/container/runtime/index.js.map +1 -0
- package/dist/harness/opencode/index.d.ts +369 -0
- package/dist/harness/opencode/index.js +1072 -0
- package/dist/harness/opencode/index.js.map +1 -0
- package/dist/harness/pi/index.d.ts +3 -2
- package/dist/harness/pi/index.js +3 -3
- package/dist/harness/store/index.d.ts +24 -0
- package/dist/harness/store/index.js +2 -0
- package/dist/harness/think/index.d.ts +821 -0
- package/dist/harness/think/index.js +2721 -0
- package/dist/harness/think/index.js.map +1 -0
- package/dist/harness-B6B9S3rb.d.ts +203 -0
- package/dist/{images-iiTDSyRu.js → images-Ce9SCu3X.js} +2 -248
- package/dist/images-Ce9SCu3X.js.map +1 -0
- package/dist/{index-BreL0YrQ.d.ts → index-BEL3ZV-s.d.ts} +2 -6
- package/dist/index-CBt8oRJt.d.ts +198 -0
- package/dist/index.d.ts +5 -5
- package/dist/index.js +2 -2
- package/dist/ingress-EFbrS547.js +9 -0
- package/dist/ingress-EFbrS547.js.map +1 -0
- package/dist/input-schema-BQykTEp_.js +20 -0
- package/dist/input-schema-BQykTEp_.js.map +1 -0
- package/dist/input-schema-D2QAtHZH.js +23 -0
- package/dist/input-schema-D2QAtHZH.js.map +1 -0
- package/dist/internal-kmw70xwR.js +46 -0
- package/dist/internal-kmw70xwR.js.map +1 -0
- package/dist/internal_context.d.ts +1 -1
- package/dist/lifecycle/index.d.ts +3 -3
- package/dist/lifecycle/index.js +2 -2
- package/dist/{lifecycle-CFu6OV03.js → lifecycle-DGorpAmA.js} +2 -4
- package/dist/lifecycle-DGorpAmA.js.map +1 -0
- package/dist/mcp/client/do-oauth-client-provider.d.ts +1 -1
- package/dist/mcp/client/do-oauth-client-provider.js +9 -0
- package/dist/mcp/client/do-oauth-client-provider.js.map +1 -1
- package/dist/mcp/client/index.d.ts +1 -1
- package/dist/mcp/client/index.js +1 -1
- package/dist/mcp/client/x402.d.ts +35 -4
- package/dist/mcp/client/x402.js +24 -3
- package/dist/mcp/client/x402.js.map +1 -1
- package/dist/mcp/index.d.ts +1 -1
- package/dist/mcp/index.js +2 -2
- package/dist/models/ai-sdk/index.d.ts +16 -14
- package/dist/models/ai-sdk/index.js +1 -2442
- package/dist/models/opencode/index.d.ts +65 -0
- package/dist/models/opencode/index.js +285 -0
- package/dist/models/opencode/index.js.map +1 -0
- package/dist/models/pi-ai/index.d.ts +9 -7
- package/dist/models/pi-ai/index.js +2 -1
- package/dist/models/pi-ai/index.js.map +1 -1
- package/dist/options-CiIsJHXR.d.ts +130 -0
- package/dist/protocol-BEgrJYC5.d.ts +331 -0
- package/dist/protocol-CukuI73M.d.ts +386 -0
- package/dist/protocol-cOklVBBD.js +227 -0
- package/dist/protocol-cOklVBBD.js.map +1 -0
- package/dist/{protocol-kHsr-f0X.js → protocol-eXeJxhgu.js} +2 -67
- package/dist/protocol-eXeJxhgu.js.map +1 -0
- package/dist/protocol-y2sSY584.js +148 -0
- package/dist/protocol-y2sSY584.js.map +1 -0
- package/dist/queue/index.d.ts +1 -1
- package/dist/queue/index.js +1 -1
- package/dist/{queue-BB-zfIYF.js → queue-CcIjVYTE.js} +2 -2
- package/dist/{queue-BB-zfIYF.js.map → queue-CcIjVYTE.js.map} +1 -1
- package/dist/react.d.ts +2 -2
- package/dist/routing/index.d.ts +2 -2
- package/dist/routing/index.js +1 -1
- package/dist/{scheduler-RdACNXDP.d.ts → scheduler-BCLESHSC.d.ts} +2 -12
- package/dist/{scheduler-DZ3xQfeK.js → scheduler-FIHv2-kJ.js} +2 -4
- package/dist/scheduler-FIHv2-kJ.js.map +1 -0
- package/dist/schedules/index.d.ts +1 -1
- package/dist/schedules/index.js +1 -1
- package/dist/serializable.d.ts +1 -1
- package/dist/session-store-Do4xkDcf.js +606 -0
- package/dist/session-store-Do4xkDcf.js.map +1 -0
- package/dist/session-store-DoPY12xM.d.ts +383 -0
- package/dist/sessions/index.d.ts +11 -434
- package/dist/sessions/index.js +1 -2271
- package/dist/sessions-_vN5BEZX.js +2272 -0
- package/dist/sessions-_vN5BEZX.js.map +1 -0
- package/dist/settings-C45hDliX.js +253 -0
- package/dist/settings-C45hDliX.js.map +1 -0
- package/dist/{transport-PfFnt-Ld.d.ts → settings-NgGwF7Qt.d.ts} +14 -208
- package/dist/{src-BZeu-SCD.js → src-CQxJFv4l.js} +8 -8
- package/dist/src-CQxJFv4l.js.map +1 -0
- package/dist/stall-watchdog-BpRF2uwG.js +195 -0
- package/dist/stall-watchdog-BpRF2uwG.js.map +1 -0
- package/dist/state/index.d.ts +1 -1
- package/dist/state/index.js +1 -3
- package/dist/state/index.js.map +1 -1
- package/dist/store-BKM4Xm9M.d.ts +332 -0
- package/dist/store-CslVzfN7.js +458 -0
- package/dist/store-CslVzfN7.js.map +1 -0
- package/dist/streams/index.d.ts +1 -1
- package/dist/streams/index.js +1 -1
- package/dist/{streams-DW-UCOUc.js → streams-lsHMJhRW.js} +17 -4
- package/dist/streams-lsHMJhRW.js.map +1 -0
- package/dist/{streams-Cmkj9QfW.d.ts → streams-vrCtbUIn.d.ts} +2 -2
- package/dist/sub-routing.d.ts +1 -1
- package/dist/tasks/index.d.ts +1 -1
- package/dist/tasks/index.js +1 -1
- package/dist/{tasks-68DESxf0.js → tasks-BN_5AWqI.js} +3 -2
- package/dist/tasks-BN_5AWqI.js.map +1 -0
- package/dist/{tasks-9YxYtByh.d.ts → tasks-E89KdwkS.d.ts} +2 -2
- package/dist/tool-CTp72Jb_.d.ts +278 -0
- package/dist/tool-CxKsvxjm.js +1126 -0
- package/dist/tool-CxKsvxjm.js.map +1 -0
- package/dist/tool-DoVberpN.d.ts +301 -0
- package/dist/tool-cQRkwSZZ.js +410 -0
- package/dist/tool-cQRkwSZZ.js.map +1 -0
- package/dist/tool-helpers-O5BDVEAY.js +58 -0
- package/dist/tool-helpers-O5BDVEAY.js.map +1 -0
- package/dist/transport-k2mFrtL8.d.ts +200 -0
- package/dist/turns-DCV3ycDl.js +317 -0
- package/dist/turns-DCV3ycDl.js.map +1 -0
- package/dist/voice/client.js +1 -1
- package/dist/voice/index.d.ts +2 -2
- package/dist/voice/index.js +1 -1
- package/dist/web/fetch/index.d.ts +89 -0
- package/dist/web/fetch/index.js +20 -0
- package/dist/web/fetch/index.js.map +1 -0
- package/dist/web/fetch/tools/ai-sdk.d.ts +80 -0
- package/dist/web/fetch/tools/ai-sdk.js +47 -0
- package/dist/web/fetch/tools/ai-sdk.js.map +1 -0
- package/dist/web/fetch/tools/pi.d.ts +84 -0
- package/dist/web/fetch/tools/pi.js +88 -0
- package/dist/web/fetch/tools/pi.js.map +1 -0
- package/dist/web/fetch/tools/tanstack-ai.d.ts +78 -0
- package/dist/web/fetch/tools/tanstack-ai.js +45 -0
- package/dist/web/fetch/tools/tanstack-ai.js.map +1 -0
- package/dist/web/search/index.d.ts +58 -0
- package/dist/web/search/index.js +2 -0
- package/dist/web/search/tools/ai-sdk.d.ts +77 -0
- package/dist/web/search/tools/ai-sdk.js +46 -0
- package/dist/web/search/tools/ai-sdk.js.map +1 -0
- package/dist/web/search/tools/pi.d.ts +82 -0
- package/dist/web/search/tools/pi.js +89 -0
- package/dist/web/search/tools/pi.js.map +1 -0
- package/dist/web/search/tools/tanstack-ai.d.ts +71 -0
- package/dist/web/search/tools/tanstack-ai.js +46 -0
- package/dist/web/search/tools/tanstack-ai.js.map +1 -0
- package/dist/websockets/index.d.ts +12 -296
- package/dist/websockets/index.js +1 -1
- package/dist/{websockets-Ci-LZFHH.js → websockets-C3zy8YR0.js} +20 -8
- package/dist/websockets-C3zy8YR0.js.map +1 -0
- package/dist/{wire-types-CrjKvDyi.d.ts → wire-types-Cv0iwjk5.d.ts} +3 -51
- package/dist/workflow-types.d.ts +1 -1
- package/dist/workflows.d.ts +1 -1
- package/dist/workflows.js +1 -1
- package/docs/browse-the-web.md +29 -1
- package/docs/fetch-the-web.md +276 -0
- package/docs/harnesses/pi.md +25 -0
- package/docs/harnesses/think.md +215 -0
- package/docs/index.md +99 -75
- package/docs/lifecycle.md +42 -3
- package/docs/queue.md +2 -3
- package/docs/scheduling.md +2 -6
- package/docs/search-the-web.md +135 -0
- package/package.json +148 -44
- package/dist/ai-fm7xx1BK.js +0 -312
- package/dist/ai-fm7xx1BK.js.map +0 -1
- package/dist/browser/ai-sdk.js.map +0 -1
- package/dist/browser/index.js.map +0 -1
- package/dist/browser/tanstack-ai.js.map +0 -1
- package/dist/browser-tool-CQ10e6Kj.js.map +0 -1
- package/dist/capability-B4WbF81e.js.map +0 -1
- package/dist/channel-Bnm4S7T2.d.ts +0 -491
- package/dist/channels/ai-sdk.d.ts +0 -46
- package/dist/channels/ai-sdk.js +0 -120
- package/dist/channels/ai-sdk.js.map +0 -1
- package/dist/channels/email.js.map +0 -1
- package/dist/channels/index.d.ts +0 -233
- package/dist/channels/index.js +0 -608
- package/dist/channels/index.js.map +0 -1
- package/dist/channels/slack.js +0 -614
- package/dist/channels/slack.js.map +0 -1
- package/dist/channels/tanstack-ai.d.ts +0 -39
- package/dist/channels/tanstack-ai.js +0 -17
- package/dist/channels/tanstack-ai.js.map +0 -1
- package/dist/channels/telegram.js +0 -427
- package/dist/channels/telegram.js.map +0 -1
- package/dist/channels/voice.d.ts +0 -45
- package/dist/channels/voice.js +0 -122
- package/dist/channels/voice.js.map +0 -1
- package/dist/client-fyQrLGkD.js.map +0 -1
- package/dist/connector-58XDGvc3.js.map +0 -1
- package/dist/images-iiTDSyRu.js.map +0 -1
- package/dist/index-BB0kqhIz.d.ts +0 -101
- package/dist/ingress-BfetZbMO.js +0 -83
- package/dist/ingress-BfetZbMO.js.map +0 -1
- package/dist/internal-CYlgHl1l.js +0 -59
- package/dist/internal-CYlgHl1l.js.map +0 -1
- package/dist/lifecycle-CFu6OV03.js.map +0 -1
- package/dist/models/ai-sdk/index.js.map +0 -1
- package/dist/protocol-kHsr-f0X.js.map +0 -1
- package/dist/scheduler-DZ3xQfeK.js.map +0 -1
- package/dist/sessions/index.js.map +0 -1
- package/dist/src-BZeu-SCD.js.map +0 -1
- package/dist/streams-DW-UCOUc.js.map +0 -1
- package/dist/surface-bZZJqBka.js +0 -17
- package/dist/surface-bZZJqBka.js.map +0 -1
- package/dist/tasks-68DESxf0.js.map +0 -1
- package/dist/tool-schema-CBjGPrsQ.js +0 -31
- package/dist/tool-schema-CBjGPrsQ.js.map +0 -1
- package/dist/websockets-Ci-LZFHH.js.map +0 -1
- package/docs/channels.md +0 -323
|
@@ -0,0 +1,410 @@
|
|
|
1
|
+
import "./settings-C45hDliX.js";
|
|
2
|
+
import { t as abortable } from "./abortable-C1SpfVoi.js";
|
|
3
|
+
//#region src/web/search/contract.ts
|
|
4
|
+
/**
|
|
5
|
+
* The `web_search` tool contract: its name, what it tells the model, what the
|
|
6
|
+
* model passes in, what comes back, and how results are rendered for the
|
|
7
|
+
* model. Shared by every executor of the tool — the harness-executed
|
|
8
|
+
* adapters in `agents/websearch/*` today, and a gateway-executed variant in
|
|
9
|
+
* `agents/models/*` once AI Gateway server tools ship — so a `web_search` call
|
|
10
|
+
* looks the same in a transcript whoever ran it.
|
|
11
|
+
*/
|
|
12
|
+
/**
|
|
13
|
+
* The tool's name, as the model calls it and as it appears in transcripts.
|
|
14
|
+
* `web_search` is the name models know from Anthropic's and OpenAI's built-in
|
|
15
|
+
* search tools.
|
|
16
|
+
*/
|
|
17
|
+
const WEB_SEARCH_TOOL_NAME = "web_search";
|
|
18
|
+
/** The default number of results when the model doesn't ask for a count. */
|
|
19
|
+
const DEFAULT_WEB_SEARCH_LIMIT = 5;
|
|
20
|
+
/** The most results one search can return; the API rejects more. */
|
|
21
|
+
const MAX_WEB_SEARCH_LIMIT = 10;
|
|
22
|
+
/** The longest query the API accepts, in characters. */
|
|
23
|
+
const MAX_WEB_SEARCH_QUERY_LENGTH = 1024;
|
|
24
|
+
/**
|
|
25
|
+
* Per-result description length in the model's view, in characters. Provider
|
|
26
|
+
* descriptions run to ~8,000 characters (Ceramic returns page text), which at
|
|
27
|
+
* ten results is 80 KB of context per search. The full text stays in the
|
|
28
|
+
* host-side output.
|
|
29
|
+
*/
|
|
30
|
+
const DEFAULT_WEB_SEARCH_DESCRIPTION_CHARS = 600;
|
|
31
|
+
const WEB_SEARCH_TOOL_DESCRIPTION = [
|
|
32
|
+
"Search the public web. Returns up to `limit` results, each with a URL, a title, and a short description of the page.",
|
|
33
|
+
"Use it for current events, facts you're unsure of, documentation, and anything that may have changed since your training.",
|
|
34
|
+
"There is no next page: for more or different results, search again with a rephrased query.",
|
|
35
|
+
"Results are discovery only: to read a page, fetch its URL with `web_fetch` if it is available."
|
|
36
|
+
].join(" ");
|
|
37
|
+
/**
|
|
38
|
+
* Render search results as the text the model reads: one numbered block per
|
|
39
|
+
* result, descriptions trimmed and whitespace collapsed.
|
|
40
|
+
*/
|
|
41
|
+
function renderWebSearchResults(response, options = {}) {
|
|
42
|
+
const maxChars = options.maxDescriptionChars ?? 600;
|
|
43
|
+
if (response.items.length === 0) return `No results for "${response.metadata.query}". Try a broader or rephrased query.`;
|
|
44
|
+
const blocks = response.items.map((item, index) => {
|
|
45
|
+
const lines = [`${index + 1}. ${item.title.trim() || item.url}`, item.url];
|
|
46
|
+
const description = compactDescription(item.description, maxChars);
|
|
47
|
+
if (description) lines.push(description);
|
|
48
|
+
if (item.lastModifiedDate) lines.push(`Modified: ${item.lastModifiedDate}`);
|
|
49
|
+
return lines.join("\n");
|
|
50
|
+
});
|
|
51
|
+
return [
|
|
52
|
+
`${response.items.length} result${response.items.length === 1 ? "" : "s"} for "${response.metadata.query}":`,
|
|
53
|
+
"",
|
|
54
|
+
blocks.join("\n\n")
|
|
55
|
+
].join("\n");
|
|
56
|
+
}
|
|
57
|
+
function compactDescription(description, maxChars) {
|
|
58
|
+
if (!description) return void 0;
|
|
59
|
+
const compact = description.replace(/\s+/g, " ").trim();
|
|
60
|
+
if (!compact) return void 0;
|
|
61
|
+
if (compact.length <= maxChars) return compact;
|
|
62
|
+
const cut = compact.slice(0, Math.max(0, maxChars - 1));
|
|
63
|
+
const space = cut.lastIndexOf(" ");
|
|
64
|
+
const end = space >= cut.length - WORD_BOUNDARY_BACKOFF ? space : cut.length;
|
|
65
|
+
return `${cut.slice(0, end).trimEnd()}…`;
|
|
66
|
+
}
|
|
67
|
+
/** How far truncation backs off to end on a whole word. */
|
|
68
|
+
const WORD_BOUNDARY_BACKOFF = 20;
|
|
69
|
+
//#endregion
|
|
70
|
+
//#region src/web/search/source.ts
|
|
71
|
+
/**
|
|
72
|
+
* Where searches run. A {@link WebSearchSource} turns a query into a
|
|
73
|
+
* {@link WebSearchResponse}; the tool core is written against it, so the
|
|
74
|
+
* same tool works over the Workers AI binding, the HTTP API, or a fake in
|
|
75
|
+
* tests.
|
|
76
|
+
*/
|
|
77
|
+
/**
|
|
78
|
+
* Search through the Workers AI binding. The Worker's own account and the
|
|
79
|
+
* named gateway are billed.
|
|
80
|
+
*/
|
|
81
|
+
function createAIWebSearch(options) {
|
|
82
|
+
validateGatewayOptions(options);
|
|
83
|
+
const binding = options.binding;
|
|
84
|
+
const search = async (input, call = {}) => {
|
|
85
|
+
const request = validateRequest(input);
|
|
86
|
+
if (typeof binding.websearch !== "function") throw new WebSearchError("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.", {
|
|
87
|
+
status: 501,
|
|
88
|
+
code: "web_search_unsupported_runtime",
|
|
89
|
+
retryable: false
|
|
90
|
+
});
|
|
91
|
+
call.signal?.throwIfAborted();
|
|
92
|
+
return readResponse(await abortable(binding.websearch({
|
|
93
|
+
gatewayId: options.gateway ?? "default",
|
|
94
|
+
query: request.query,
|
|
95
|
+
limit: request.limit,
|
|
96
|
+
provider: options.provider,
|
|
97
|
+
byokAlias: options.byokAlias
|
|
98
|
+
}), call.signal), request.query);
|
|
99
|
+
};
|
|
100
|
+
return {
|
|
101
|
+
search,
|
|
102
|
+
provider: options.provider
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Search through `POST /accounts/{account_id}/ai/websearch`. Use this
|
|
107
|
+
* outside Workers, or to search through a gateway in another account.
|
|
108
|
+
*/
|
|
109
|
+
function createHTTPWebSearch(options) {
|
|
110
|
+
validateGatewayOptions(options);
|
|
111
|
+
const doFetch = options.fetch ?? fetch;
|
|
112
|
+
const url = `${(options.baseUrl ?? "https://api.cloudflare.com").replace(/\/+$/, "")}/client/v4/accounts/${encodeURIComponent(options.accountId)}/ai/websearch/`;
|
|
113
|
+
const search = async (input, call = {}) => {
|
|
114
|
+
const request = validateRequest(input);
|
|
115
|
+
return readResponse(await doFetch(url, {
|
|
116
|
+
method: "POST",
|
|
117
|
+
signal: call.signal,
|
|
118
|
+
headers: {
|
|
119
|
+
Authorization: `Bearer ${options.apiToken}`,
|
|
120
|
+
"Content-Type": "application/json"
|
|
121
|
+
},
|
|
122
|
+
body: JSON.stringify({
|
|
123
|
+
query: request.query,
|
|
124
|
+
limit: request.limit,
|
|
125
|
+
provider: options.provider,
|
|
126
|
+
byokAlias: options.byokAlias,
|
|
127
|
+
options: { gateway: { id: options.gateway ?? "default" } }
|
|
128
|
+
})
|
|
129
|
+
}), request.query);
|
|
130
|
+
};
|
|
131
|
+
return {
|
|
132
|
+
search,
|
|
133
|
+
provider: options.provider
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
/** The API's pattern for `byokAlias`. */
|
|
137
|
+
const BYOK_ALIAS_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
|
|
138
|
+
/** Host configuration errors are programming errors: throw when building. */
|
|
139
|
+
function validateGatewayOptions(options) {
|
|
140
|
+
if (options.byokAlias !== void 0 && !BYOK_ALIAS_PATTERN.test(options.byokAlias)) throw new RangeError(`byokAlias must be 1–64 letters, digits, "_" or "-"; got ${JSON.stringify(options.byokAlias)}.`);
|
|
141
|
+
}
|
|
142
|
+
/** Why a search failed, with what the API said. */
|
|
143
|
+
var WebSearchError = class extends Error {
|
|
144
|
+
constructor(message, details) {
|
|
145
|
+
super(message, { cause: details.cause });
|
|
146
|
+
this.name = "WebSearchError";
|
|
147
|
+
this.status = details.status;
|
|
148
|
+
this.code = details.code;
|
|
149
|
+
this.retryable = details.retryable ?? isRetryableStatus(details.status);
|
|
150
|
+
this.requestId = details.requestId;
|
|
151
|
+
this.apiCode = details.apiCode;
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
/** Check a request against the API's limits and fill in the default limit. */
|
|
155
|
+
function validateRequest(request) {
|
|
156
|
+
const query = request.query.trim();
|
|
157
|
+
const limit = request.limit ?? 5;
|
|
158
|
+
if (query.length === 0) throw new WebSearchError("Query must not be empty.", {
|
|
159
|
+
status: 400,
|
|
160
|
+
code: "invalid_web_search_input"
|
|
161
|
+
});
|
|
162
|
+
if (query.length > 1024) throw new WebSearchError(`Query must be at most ${MAX_WEB_SEARCH_QUERY_LENGTH} characters.`, {
|
|
163
|
+
status: 400,
|
|
164
|
+
code: "invalid_web_search_input"
|
|
165
|
+
});
|
|
166
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > 10) throw new WebSearchError(`Limit must be an integer from 1 to 10.`, {
|
|
167
|
+
status: 400,
|
|
168
|
+
code: "invalid_web_search_input"
|
|
169
|
+
});
|
|
170
|
+
return {
|
|
171
|
+
query,
|
|
172
|
+
limit
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
async function readResponse(response, query) {
|
|
176
|
+
const text = await response.text();
|
|
177
|
+
let body;
|
|
178
|
+
try {
|
|
179
|
+
body = JSON.parse(text);
|
|
180
|
+
} catch {
|
|
181
|
+
body = void 0;
|
|
182
|
+
}
|
|
183
|
+
if (!response.ok) throw toWebSearchError(response.status, body, text);
|
|
184
|
+
const result = toWebSearchResponse(body, query);
|
|
185
|
+
if (!result) throw new WebSearchError(`Web search returned HTTP ${response.status} without search results${text ? `: ${text.slice(0, 200)}` : ""}.`, {
|
|
186
|
+
status: response.status,
|
|
187
|
+
code: "web_search_unavailable",
|
|
188
|
+
retryable: true
|
|
189
|
+
});
|
|
190
|
+
return result;
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Read a 200 body into a {@link WebSearchResponse}, tolerating what a beta
|
|
194
|
+
* API and three providers might send: items without a URL are dropped, a
|
|
195
|
+
* missing title falls back to the URL, unknown or mistyped fields are left
|
|
196
|
+
* out, and missing metadata gets defaults. Only a body with no `items`
|
|
197
|
+
* array is rejected.
|
|
198
|
+
*/
|
|
199
|
+
function toWebSearchResponse(body, query) {
|
|
200
|
+
if (!isRecord(body) || !Array.isArray(body.items)) return void 0;
|
|
201
|
+
const items = [];
|
|
202
|
+
for (const item of body.items) {
|
|
203
|
+
if (!isRecord(item)) continue;
|
|
204
|
+
const url = asString(item.url)?.trim();
|
|
205
|
+
if (!url) continue;
|
|
206
|
+
const result = {
|
|
207
|
+
url,
|
|
208
|
+
title: asString(item.title)?.trim() || url
|
|
209
|
+
};
|
|
210
|
+
for (const key of OPTIONAL_RESULT_FIELDS) {
|
|
211
|
+
const value = asString(item[key]);
|
|
212
|
+
if (value !== void 0) result[key] = value;
|
|
213
|
+
}
|
|
214
|
+
items.push(result);
|
|
215
|
+
}
|
|
216
|
+
const metadata = isRecord(body.metadata) ? body.metadata : {};
|
|
217
|
+
return {
|
|
218
|
+
items,
|
|
219
|
+
metadata: {
|
|
220
|
+
query: asString(metadata.query) ?? query,
|
|
221
|
+
requestId: asString(metadata.requestId) ?? "",
|
|
222
|
+
latencyMs: typeof metadata.latencyMs === "number" ? metadata.latencyMs : 0
|
|
223
|
+
}
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
const OPTIONAL_RESULT_FIELDS = [
|
|
227
|
+
"description",
|
|
228
|
+
"lastModifiedDate",
|
|
229
|
+
"imageUrl",
|
|
230
|
+
"faviconUrl"
|
|
231
|
+
];
|
|
232
|
+
/**
|
|
233
|
+
* The API fails in three shapes. Gateway-native:
|
|
234
|
+
* `{ ok: false, error: { category, code, status, retryable, gatewayRequestId } }`.
|
|
235
|
+
* Request validation, the Cloudflare envelope with issue details:
|
|
236
|
+
* `{ success: false, errors: [{ code: 7000, message }], messages: [{ message, path }] }`.
|
|
237
|
+
* Gateway configuration (`AiGatewayError`):
|
|
238
|
+
* `{ success: false, error: [{ code: 2001, message }], message, description }`.
|
|
239
|
+
*/
|
|
240
|
+
function toWebSearchError(status, body, text) {
|
|
241
|
+
if (isRecord(body)) {
|
|
242
|
+
const error = body.error;
|
|
243
|
+
if (isRecord(error) && typeof error.code === "string") {
|
|
244
|
+
const errorStatus = typeof error.status === "number" ? error.status : status;
|
|
245
|
+
return new WebSearchError(describeCode(error.code, errorStatus), {
|
|
246
|
+
status: errorStatus,
|
|
247
|
+
code: error.code,
|
|
248
|
+
retryable: typeof error.retryable === "boolean" ? error.retryable : void 0,
|
|
249
|
+
requestId: asString(error.gatewayRequestId)
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
const entries = (Array.isArray(body.errors) ? body.errors : Array.isArray(error) ? error : []).filter(isRecord);
|
|
253
|
+
const issues = Array.isArray(body.messages) ? body.messages : [];
|
|
254
|
+
const message = [...entries.map((entry) => asString(entry.message)), ...issues.map(describeIssue)].filter((m) => Boolean(m)).join("; ") || asString(body.message);
|
|
255
|
+
if (message) {
|
|
256
|
+
const apiCode = entries.map((entry) => entry.code).find((code) => typeof code === "number");
|
|
257
|
+
return new WebSearchError(message, {
|
|
258
|
+
status,
|
|
259
|
+
code: codeForApiError(apiCode, status),
|
|
260
|
+
apiCode
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
return new WebSearchError(`Web search failed with HTTP ${status}${text ? `: ${text.slice(0, 200)}` : ""}.`, {
|
|
265
|
+
status,
|
|
266
|
+
code: codeForStatus(status)
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
function codeForApiError(apiCode, status) {
|
|
270
|
+
switch (apiCode) {
|
|
271
|
+
case 7e3: return "invalid_web_search_input";
|
|
272
|
+
case 2001: return "web_search_gateway_not_configured";
|
|
273
|
+
default: return codeForStatus(status);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
function codeForStatus(status) {
|
|
277
|
+
if (status === 400) return "invalid_web_search_input";
|
|
278
|
+
if (status === 401 || status === 403) return "web_search_unauthorized";
|
|
279
|
+
if (status === 402) return "web_search_payment_required";
|
|
280
|
+
if (status === 429) return "web_search_rate_limited";
|
|
281
|
+
return "web_search_unavailable";
|
|
282
|
+
}
|
|
283
|
+
function isRetryableStatus(status) {
|
|
284
|
+
return status === 429 || status >= 500;
|
|
285
|
+
}
|
|
286
|
+
function describeCode(code, status) {
|
|
287
|
+
switch (code) {
|
|
288
|
+
case "web_search_payment_required": 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.";
|
|
289
|
+
case "web_search_byok_not_configured": return "Web search is unavailable: the requested BYOK key alias is not configured on the gateway.";
|
|
290
|
+
case "invalid_web_search_input": return "The API rejected the request: check the query (1–1024 characters), limit (1–10), and provider (ceramic, exa, or linkup).";
|
|
291
|
+
default: return `Web search failed (${code}, HTTP ${status}).`;
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
function describeIssue(issue) {
|
|
295
|
+
if (!isRecord(issue)) return void 0;
|
|
296
|
+
const message = asString(issue.message);
|
|
297
|
+
if (!message) return void 0;
|
|
298
|
+
const path = Array.isArray(issue.path) ? issue.path.join(".") : "";
|
|
299
|
+
return path ? `${path}: ${message}` : message;
|
|
300
|
+
}
|
|
301
|
+
function isRecord(value) {
|
|
302
|
+
return typeof value === "object" && value !== null;
|
|
303
|
+
}
|
|
304
|
+
function asString(value) {
|
|
305
|
+
return typeof value === "string" ? value : void 0;
|
|
306
|
+
}
|
|
307
|
+
//#endregion
|
|
308
|
+
//#region src/web/search/tool.ts
|
|
309
|
+
/**
|
|
310
|
+
* The harness-neutral core of the `web_search` tool, shared by the pi
|
|
311
|
+
* (`agents/websearch/pi`), AI SDK (`agents/websearch/ai-sdk`), and TanStack
|
|
312
|
+
* AI (`agents/websearch/tanstack-ai`) adapters. Internal — not an entry point.
|
|
313
|
+
*/
|
|
314
|
+
/** The default for {@link WebSearchToolOptions.timeoutMs}. */
|
|
315
|
+
const DEFAULT_WEB_SEARCH_TIMEOUT_MS = 3e4;
|
|
316
|
+
function createWebSearchToolCore(options) {
|
|
317
|
+
const limit = options.limit ?? 5;
|
|
318
|
+
const timeoutMs = options.timeoutMs ?? 3e4;
|
|
319
|
+
const { maxDescriptionChars } = options;
|
|
320
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > 10) throw new RangeError(`limit must be an integer from 1 to 10; got ${limit}.`);
|
|
321
|
+
if (maxDescriptionChars !== void 0 && maxDescriptionChars !== Infinity && !(Number.isInteger(maxDescriptionChars) && maxDescriptionChars > 0)) throw new RangeError(`maxDescriptionChars must be a positive integer or Infinity; got ${maxDescriptionChars}.`);
|
|
322
|
+
if (!Number.isInteger(timeoutMs) || timeoutMs <= 0) throw new RangeError(`timeoutMs must be a positive integer; got ${timeoutMs}.`);
|
|
323
|
+
const source = options.source === void 0 ? createAIWebSearch(options) : options.source;
|
|
324
|
+
const provider = source.provider;
|
|
325
|
+
const render = (output) => renderWebSearchResults(output, { maxDescriptionChars });
|
|
326
|
+
return {
|
|
327
|
+
name: WEB_SEARCH_TOOL_NAME,
|
|
328
|
+
description: options.description ?? WEB_SEARCH_TOOL_DESCRIPTION,
|
|
329
|
+
limit,
|
|
330
|
+
render,
|
|
331
|
+
async run(input, { signal } = {}) {
|
|
332
|
+
signal?.throwIfAborted();
|
|
333
|
+
const request = {
|
|
334
|
+
query: input.query,
|
|
335
|
+
limit: Math.min(clampLimit(input.limit ?? limit), limit)
|
|
336
|
+
};
|
|
337
|
+
const timeout = AbortSignal.timeout(timeoutMs);
|
|
338
|
+
const searchSignal = signal ? AbortSignal.any([signal, timeout]) : timeout;
|
|
339
|
+
try {
|
|
340
|
+
const response = await abortable(source.search(request, { signal: searchSignal }), searchSignal);
|
|
341
|
+
return {
|
|
342
|
+
ok: true,
|
|
343
|
+
output: provider ? {
|
|
344
|
+
...response,
|
|
345
|
+
provider
|
|
346
|
+
} : response,
|
|
347
|
+
text: render(response)
|
|
348
|
+
};
|
|
349
|
+
} catch (cause) {
|
|
350
|
+
if (signal?.aborted) throw signal.reason;
|
|
351
|
+
const error = toToolError(cause, timeout.aborted, timeoutMs);
|
|
352
|
+
return {
|
|
353
|
+
ok: false,
|
|
354
|
+
error,
|
|
355
|
+
text: describeFailureForModel(error)
|
|
356
|
+
};
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
/**
|
|
362
|
+
* The error a throwing adapter (AI SDK, TanStack AI) raises for a failed
|
|
363
|
+
* run. Those frameworks show the model the error's `message`, so it carries
|
|
364
|
+
* the model's text; the source's error, with the API's detail, is `cause`.
|
|
365
|
+
*/
|
|
366
|
+
function toolFailure(run) {
|
|
367
|
+
const { error } = run;
|
|
368
|
+
return new WebSearchError(run.text, {
|
|
369
|
+
status: error.status,
|
|
370
|
+
code: error.code,
|
|
371
|
+
retryable: error.retryable,
|
|
372
|
+
requestId: error.requestId,
|
|
373
|
+
apiCode: error.apiCode,
|
|
374
|
+
cause: error
|
|
375
|
+
});
|
|
376
|
+
}
|
|
377
|
+
function toToolError(cause, timedOut, timeoutMs) {
|
|
378
|
+
if (timedOut) return new WebSearchError(`Web search timed out after ${timeoutMs} ms.`, {
|
|
379
|
+
status: 504,
|
|
380
|
+
code: "web_search_timeout",
|
|
381
|
+
retryable: true,
|
|
382
|
+
cause
|
|
383
|
+
});
|
|
384
|
+
if (cause instanceof WebSearchError) return cause;
|
|
385
|
+
return new WebSearchError(cause instanceof Error ? cause.message : String(cause), {
|
|
386
|
+
status: 500,
|
|
387
|
+
code: "web_search_unavailable",
|
|
388
|
+
retryable: true,
|
|
389
|
+
cause
|
|
390
|
+
});
|
|
391
|
+
}
|
|
392
|
+
/**
|
|
393
|
+
* What the model reads when a search fails: whether to retry, change the
|
|
394
|
+
* query, or carry on without search. The operator's detail (credits, keys,
|
|
395
|
+
* gateway setup) stays on the error for the host.
|
|
396
|
+
*/
|
|
397
|
+
function describeFailureForModel(error) {
|
|
398
|
+
if (error.code === "invalid_web_search_input") return `Web search rejected the query (${error.message.replace(/\.$/, "")}). Fix the query and try again.`;
|
|
399
|
+
if (error.retryable) return `Web search failed temporarily (${error.code}). You may retry once.`;
|
|
400
|
+
return `Web search is unavailable here (${error.code}). Do not retry; answer without it and say that web search was unavailable.`;
|
|
401
|
+
}
|
|
402
|
+
/** The model's `limit`, made an integer from 1 to 10. */
|
|
403
|
+
function clampLimit(value) {
|
|
404
|
+
if (!Number.isFinite(value)) return 5;
|
|
405
|
+
return Math.min(10, Math.max(1, Math.trunc(value)));
|
|
406
|
+
}
|
|
407
|
+
//#endregion
|
|
408
|
+
export { createAIWebSearch as a, DEFAULT_WEB_SEARCH_LIMIT as c, WEB_SEARCH_TOOL_DESCRIPTION as d, WEB_SEARCH_TOOL_NAME as f, WebSearchError as i, MAX_WEB_SEARCH_LIMIT as l, createWebSearchToolCore as n, createHTTPWebSearch as o, renderWebSearchResults as p, toolFailure as r, DEFAULT_WEB_SEARCH_DESCRIPTION_CHARS as s, DEFAULT_WEB_SEARCH_TIMEOUT_MS as t, MAX_WEB_SEARCH_QUERY_LENGTH as u };
|
|
409
|
+
|
|
410
|
+
//# sourceMappingURL=tool-cQRkwSZZ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tool-cQRkwSZZ.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,KAAK,aAAa,QAAQ;EACjE,IAAI,aAAa,MAAM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|
|
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,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