agents 0.32.0 → 0.33.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.
Files changed (64) hide show
  1. package/dist/ai-sdk-CpuRsjP5.d.ts +72 -0
  2. package/dist/browser/ai.js +2 -3
  3. package/dist/browser/ai.js.map +1 -1
  4. package/dist/browser/index.d.ts +29 -21
  5. package/dist/browser/index.js +937 -4
  6. package/dist/browser/index.js.map +1 -0
  7. package/dist/browser/tools/ai-sdk.d.ts +5 -70
  8. package/dist/browser/tools/ai-sdk.js +9 -3
  9. package/dist/browser/tools/ai-sdk.js.map +1 -1
  10. package/dist/browser/tools/pi.d.ts +11 -8
  11. package/dist/browser/tools/pi.js +58 -11
  12. package/dist/browser/tools/pi.js.map +1 -1
  13. package/dist/browser/tools/tanstack-ai.d.ts +4 -4
  14. package/dist/browser/tools/tanstack-ai.js +3 -3
  15. package/dist/browser/tools/tanstack-ai.js.map +1 -1
  16. package/dist/{browser-D9RNpJuT.d.ts → browser-CI97khiJ.d.ts} +222 -94
  17. package/dist/{browser-tool-BhjCcNVE.d.ts → browser-tool-Cxtiwfua.d.ts} +2 -2
  18. package/dist/browser-tool-DOqT1oSD.js +360 -0
  19. package/dist/browser-tool-DOqT1oSD.js.map +1 -0
  20. package/dist/chat/react.js +1 -0
  21. package/dist/chat/react.js.map +1 -1
  22. package/dist/cli.js +63 -62
  23. package/dist/{connector-CM-uuxKM.js → connector-Dl098To-.js} +402 -3
  24. package/dist/connector-Dl098To-.js.map +1 -0
  25. package/dist/experimental/webmcp.js +1 -1
  26. package/dist/harness/pi/index.d.ts +73 -26
  27. package/dist/harness/pi/index.js +77 -83
  28. package/dist/harness/pi/index.js.map +1 -1
  29. package/dist/{input-schema-BQykTEp_.js → input-schema-0uUu392-.js} +2 -2
  30. package/dist/input-schema-0uUu392-.js.map +1 -0
  31. package/dist/{input-schema-B0Etuo-o.js → input-schema-waggtYrH.js} +2 -2
  32. package/dist/input-schema-waggtYrH.js.map +1 -0
  33. package/dist/mcp/client/x402.d.ts +8 -8
  34. package/dist/mcp/index.d.ts +1 -1
  35. package/dist/mcp/index.js +3 -3
  36. package/dist/mcp/index.js.map +1 -1
  37. package/dist/models/pi-ai/index.js +11 -141
  38. package/dist/models/pi-ai/index.js.map +1 -1
  39. package/dist/{session-7CDgVE0z.js → session-CRY0bGiI.js} +423 -411
  40. package/dist/session-CRY0bGiI.js.map +1 -0
  41. package/dist/{tool-helpers-BI7ifO2S.js → tool-helpers-F3_Wy2YX.js} +2 -2
  42. package/dist/{tool-helpers-BI7ifO2S.js.map → tool-helpers-F3_Wy2YX.js.map} +1 -1
  43. package/dist/web/fetch/tools/ai-sdk.js +1 -1
  44. package/dist/web/fetch/tools/pi.d.ts +4 -7
  45. package/dist/web/fetch/tools/pi.js +7 -6
  46. package/dist/web/fetch/tools/pi.js.map +1 -1
  47. package/dist/web/fetch/tools/tanstack-ai.js +1 -1
  48. package/dist/web/search/tools/ai-sdk.js +1 -1
  49. package/dist/web/search/tools/pi.d.ts +5 -4
  50. package/dist/web/search/tools/pi.js +5 -10
  51. package/dist/web/search/tools/pi.js.map +1 -1
  52. package/dist/web/search/tools/tanstack-ai.js +1 -1
  53. package/docs/browse-the-web.md +36 -3
  54. package/docs/harnesses/pi.md +50 -30
  55. package/docs/models-pi-ai.md +1 -1
  56. package/package.json +14 -8
  57. package/dist/browser-1eUbPvC2.js +0 -931
  58. package/dist/browser-1eUbPvC2.js.map +0 -1
  59. package/dist/browser-tool-DRan7Lk6.js +0 -497
  60. package/dist/browser-tool-DRan7Lk6.js.map +0 -1
  61. package/dist/connector-CM-uuxKM.js.map +0 -1
  62. package/dist/input-schema-B0Etuo-o.js.map +0 -1
  63. package/dist/input-schema-BQykTEp_.js.map +0 -1
  64. package/dist/session-7CDgVE0z.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-CRY0bGiI.js","names":[],"sources":["../src/browser/cdp-connection.ts","../src/browser/validate.ts","../src/browser/browser-functions.ts","../src/browser/scope.ts","../src/browser/session.ts"],"sourcesContent":["interface PendingCommand {\n resolve: (result: unknown) => void;\n reject: (error: Error) => void;\n timeoutId: ReturnType<typeof setTimeout>;\n method: string;\n sessionId?: string;\n startedAt: number;\n}\n\ninterface DebugEntry {\n at: string;\n type: string;\n [key: string]: unknown;\n}\n\nexport interface CdpSendOptions {\n timeoutMs?: number;\n sessionId?: string;\n}\n\nexport interface CdpAttachOptions {\n timeoutMs?: number;\n}\n\n/** Construction options for {@link CdpConnection}. */\nexport interface CdpConnectionOptions {\n /** Default per-command timeout. Defaults to 10 seconds. */\n timeoutMs?: number;\n /**\n * Invoked exactly once when the session reaches a terminal state — an\n * explicit `close()`, peer closure, or a socket error.\n */\n onClose?: () => void;\n /** Browser Run session id, when connected to a session-scoped browser. */\n sessionId?: string;\n /** Invoked on every CDP command sent — an activity signal for idle tracking. */\n onActivity?: () => void;\n}\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\n\n/** JSON-RPC's \"method not found\" code, which Chrome also uses for CDP. */\nexport const CDP_METHOD_NOT_FOUND = -32601;\n\n/** The browser answered a command with a JSON-RPC error. */\nexport class CdpProtocolError extends Error {\n override readonly name = \"CdpProtocolError\";\n /** JSON-RPC error code, e.g. {@link CDP_METHOD_NOT_FOUND}. */\n readonly code: number | undefined;\n /** The CDP method that failed. */\n readonly method: string;\n\n constructor(method: string, code: number | undefined, message: string) {\n super(`CDP error ${code ?? \"unknown\"}: ${message} for ${method}`);\n this.code = code;\n this.method = method;\n }\n}\nconst MAX_DEBUG_ENTRIES = 400;\n\n/**\n * One Chrome DevTools Protocol connection over an open WebSocket. Manages\n * command correlation, timeouts, per-tab CDP sessions, and a debug event\n * ring buffer.\n *\n * Used host-side (not in the sandbox) — the sandbox calls into this\n * via DynamicWorkerExecutor's ToolDispatcher RPC.\n */\nexport class CdpConnection {\n #socket: WebSocket;\n #nextId = 1;\n #pending = new Map<number, PendingCommand>();\n #debugLog: DebugEntry[] = [];\n #defaultTimeoutMs: number;\n #dispose?: () => void;\n #disposed = false;\n #onActivity?: () => void;\n readonly sessionId?: string;\n\n constructor(socket: WebSocket, options?: CdpConnectionOptions);\n /**\n * @deprecated Pass a {@link CdpConnectionOptions} object instead —\n * `new CdpConnection(socket, { timeoutMs, onClose, sessionId })`. The\n * positional form will be removed.\n */\n constructor(\n socket: WebSocket,\n timeoutMs?: number,\n onClose?: () => void,\n sessionId?: string\n );\n constructor(\n socket: WebSocket,\n optionsOrTimeoutMs?: CdpConnectionOptions | number,\n onClose?: () => void,\n sessionId?: string\n ) {\n const options: CdpConnectionOptions =\n typeof optionsOrTimeoutMs === \"object\"\n ? optionsOrTimeoutMs\n : { timeoutMs: optionsOrTimeoutMs, onClose, sessionId };\n this.#socket = socket;\n this.#defaultTimeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n this.#dispose = options.onClose;\n this.sessionId = options.sessionId;\n this.#onActivity = options.onActivity;\n\n socket.addEventListener(\"message\", (event) => this.#handleMessage(event));\n socket.addEventListener(\"error\", () => {\n this.#rejectAll(new Error(\"CDP socket error\"));\n this.#runDispose();\n });\n socket.addEventListener(\"close\", () => {\n this.#rejectAll(new Error(\"CDP connection closed\"));\n this.#runDispose();\n });\n }\n\n send(\n method: string,\n params?: unknown,\n options: CdpSendOptions = {}\n ): Promise<unknown> {\n this.#onActivity?.();\n const id = this.#nextId++;\n const timeoutMs = options.timeoutMs ?? this.#defaultTimeoutMs;\n const sessionId =\n typeof options.sessionId === \"string\" && options.sessionId.length > 0\n ? options.sessionId\n : undefined;\n\n const domain = typeof method === \"string\" ? method.split(\".\")[0] : \"\";\n if (!sessionId && domain && ![\"Browser\", \"Target\"].includes(domain)) {\n this.#recordDebug(\"warning\", {\n id,\n method,\n reason: \"target-scoped method sent without sessionId\"\n });\n }\n\n const result = new Promise<unknown>((resolve, reject) => {\n const startedAt = performance.now();\n const timeoutId = setTimeout(() => {\n this.#pending.delete(id);\n reject(\n new Error(`CDP command timed out after ${timeoutMs}ms: ${method}`)\n );\n }, timeoutMs);\n this.#pending.set(id, {\n resolve,\n reject,\n timeoutId,\n method,\n sessionId,\n startedAt\n });\n });\n\n this.#recordDebug(\"send\", { id, method, sessionId, timeoutMs });\n try {\n this.#socket.send(JSON.stringify({ id, method, params, sessionId }));\n } catch (error) {\n // A closed socket throws on send: fail this command now rather than\n // leave it pending until it times out.\n const pending = this.#pending.get(id);\n if (pending) {\n clearTimeout(pending.timeoutId);\n this.#pending.delete(id);\n pending.reject(\n error instanceof Error ? error : new Error(String(error))\n );\n }\n }\n return result;\n }\n\n async attachToTarget(\n targetId: string,\n options: CdpAttachOptions = {}\n ): Promise<string> {\n if (typeof targetId !== \"string\" || !targetId) {\n throw new Error(\n \"attachToTarget requires a targetId — list open tabs with \" +\n \"send('Target.getTargets') or create one with \" +\n \"send('Target.createTarget', { url })\"\n );\n }\n\n const result = (await this.send(\n \"Target.attachToTarget\",\n {\n targetId,\n flatten: true\n },\n { timeoutMs: options.timeoutMs }\n )) as { sessionId?: string };\n\n const sessionId = result?.sessionId ?? \"\";\n if (!sessionId) {\n throw new Error(\n `Target.attachToTarget did not return a sessionId for target ${targetId}`\n );\n }\n\n this.#recordDebug(\"attach\", { targetId, sessionId });\n return sessionId;\n }\n\n getDebugLog(limit = 50): DebugEntry[] {\n const normalized = Number.isFinite(limit)\n ? Math.max(1, Math.floor(limit))\n : 50;\n return this.#debugLog.slice(-normalized);\n }\n\n clearDebugLog(): void {\n this.#debugLog = [];\n }\n\n disconnect(): void {\n this.#rejectAll(new Error(\"CDP session disconnected\"));\n try {\n this.#socket.close(1000, \"Done\");\n } catch {\n // socket may already be closed\n }\n }\n\n close(): void {\n this.disconnect();\n this.#runDispose();\n }\n\n /**\n * Run the dispose callback exactly once, on the first terminal event —\n * an explicit {@link close}, peer closure, or a socket error.\n */\n #runDispose(): void {\n if (this.#disposed) return;\n this.#disposed = true;\n this.#dispose?.();\n }\n\n #rejectAll(error: Error): void {\n for (const [id, pending] of this.#pending.entries()) {\n clearTimeout(pending.timeoutId);\n this.#pending.delete(id);\n pending.reject(error);\n }\n }\n\n #handleMessage(event: MessageEvent): void {\n if (typeof event.data !== \"string\") {\n return;\n }\n\n let payload: Record<string, unknown>;\n try {\n payload = JSON.parse(event.data) as Record<string, unknown>;\n } catch {\n return;\n }\n\n this.#recordDebug(\"receive\", {\n id: payload.id,\n method: payload.method,\n sessionId: payload.sessionId,\n hasError: !!payload.error\n });\n\n if (typeof payload.id !== \"number\") {\n return;\n }\n\n const pending = this.#pending.get(payload.id);\n if (!pending) {\n return;\n }\n\n clearTimeout(pending.timeoutId);\n this.#pending.delete(payload.id);\n\n if (payload.error) {\n const err = payload.error as { code?: unknown; message?: string };\n pending.reject(\n new CdpProtocolError(\n pending.method,\n typeof err.code === \"number\" ? err.code : undefined,\n err.message ?? \"CDP error\"\n )\n );\n return;\n }\n\n pending.resolve(payload.result);\n }\n\n #recordDebug(type: string, data: Record<string, unknown>): void {\n this.#debugLog.push({\n at: new Date().toISOString(),\n type,\n ...data\n });\n if (this.#debugLog.length > MAX_DEBUG_ENTRIES) {\n this.#debugLog.splice(0, this.#debugLog.length - MAX_DEBUG_ENTRIES);\n }\n }\n}\n\nconst LOCALHOST_HOSTS = new Set([\n \"localhost\",\n \"127.0.0.1\",\n \"0.0.0.0\",\n \"::1\",\n \"[::1]\"\n]);\n\n/**\n * Connect to a browser via a CDP base URL (e.g. http://localhost:9222).\n * Discovers the WebSocket debugger URL via /json/version,\n * rewrites localhost URLs to the base URL host, and opens the WebSocket.\n *\n * Useful for local development with `chrome --remote-debugging-port=9222`\n * or when connecting through a tunnel.\n */\nexport async function connectUrl(\n baseUrl: string,\n options?: { timeoutMs?: number; headers?: Record<string, string> }\n): Promise<CdpConnection> {\n const endpoint = new URL(\"/json/version\", baseUrl).toString();\n const response = await fetch(endpoint, {\n headers: options?.headers\n });\n if (!response.ok) {\n throw new Error(\n `Failed to discover CDP endpoint at ${endpoint}: ${response.status}`\n );\n }\n\n const payload = (await response.json()) as {\n webSocketDebuggerUrl?: string;\n };\n if (!payload.webSocketDebuggerUrl) {\n throw new Error(\"CDP /json/version did not include webSocketDebuggerUrl\");\n }\n\n let wsUrl = payload.webSocketDebuggerUrl;\n const parsed = new URL(wsUrl);\n if (LOCALHOST_HOSTS.has(parsed.hostname)) {\n const base = new URL(baseUrl);\n parsed.hostname = base.hostname;\n parsed.port = base.port;\n parsed.protocol = base.protocol;\n } else {\n // Workers runtime requires fetch + Upgrade header for outbound WebSockets\n parsed.protocol = parsed.protocol === \"wss:\" ? \"https:\" : \"http:\";\n }\n const fetchUrl = parsed.toString();\n\n const wsResponse = await fetch(fetchUrl, {\n headers: { ...options?.headers, Upgrade: \"websocket\" }\n });\n const ws = wsResponse.webSocket;\n if (!ws) {\n throw new Error(\n `Failed to establish CDP WebSocket at ${fetchUrl} (status ${wsResponse.status})`\n );\n }\n ws.accept();\n\n return new CdpConnection(ws, { timeoutMs: options?.timeoutMs });\n}\n\n/** @deprecated Renamed to {@link CdpConnection}. */\nexport const CdpSession = CdpConnection;\n/** @deprecated Renamed to {@link CdpConnection}. */\nexport type CdpSession = CdpConnection;\n","/**\n * Input validation for the `browser.*` functions. Internal — not an entry\n * point. Used by `session.ts` and `browser-functions.ts`.\n */\nimport { Validator, type OutputUnit, type Schema } from \"@cfworker/json-schema\";\n\nconst validators = new WeakMap<object, Validator>();\n\n/**\n * Check a method's input against its schema before it touches the browser,\n * so the model gets a precise error. An omitted input counts as `{}`.\n */\nexport function validate(\n name: string,\n schema: object,\n input: unknown\n): unknown {\n let validator = validators.get(schema);\n if (!validator) {\n // SAFETY: The callers' schemas are draft-7 objects; @cfworker's `Schema`\n // type is only narrower around boolean subschemas, which they don't use.\n validator = new Validator(schema as Schema, \"7\", false);\n validators.set(schema, validator);\n }\n const value = input ?? {};\n const result = validator.validate(value);\n if (!result.valid) {\n throw new Error(formatValidationError(name, result.errors));\n }\n return value;\n}\n\nfunction formatValidationError(name: string, errors: OutputUnit[]): string {\n // A failing property emits both a generic parent `properties` error and a\n // specific child error. Prefer the latter so the model sees what to fix.\n const specific = errors.filter((error) => error.keyword !== \"properties\");\n const relevant = specific.length > 0 ? specific : errors;\n const details = relevant.map((error) => {\n const location = error.instanceLocation\n .replace(/^#\\/?/, \"\")\n .replaceAll(\"~1\", \"/\")\n .replaceAll(\"~0\", \"~\")\n .replaceAll(\"/\", \".\");\n return `${location ? ` at ${location}` : \"\"}: ${error.error}`;\n });\n return `Invalid arguments for ${name}${details.join(\";\")}`;\n}\n","/**\n * The `browser` object model-written code drives a browser with, defined\n * once. `browserTool`'s sandbox exposes it as the `browser` global, and a\n * Workspace module exposes the same functions, docs and rules through\n * `BrowserSession.functions` and `Browser.functionDocs()`. Internal — not an\n * entry point.\n *\n * Every function takes one options object. The CDP functions are backed by\n * a `BrowserSession`, which validates the input; `spec` shapes the session's\n * full protocol into pieces small enough for a result. The hosts functions,\n * there only when the browser has internal hostnames, are backed by its\n * `internalHosts`.\n */\nimport type { BrowserInternalHosts } from \"./browser\";\nimport type { InternalHostInfo } from \"./internal-hosts\";\nimport type {\n BrowserAttachInput,\n BrowserDebugLogInput,\n BrowserSendInput,\n BrowserSession\n} from \"./session\";\nimport type { SearchableCdpSpec } from \"./spec\";\nimport { validate } from \"./validate\";\n\n/**\n * One function on the `browser` object, as the host runs it: it takes one\n * input object (usually from model-written code, so it's validated) and\n * resolves with a JSON-safe result.\n *\n * @experimental The API surface may change before stabilizing.\n */\nexport type BrowserFunction = (input: unknown) => Promise<unknown>;\n\n/**\n * What the model needs to know to use the `browser` object, for a tool or\n * module description. `Browser.functionDocs()` returns it.\n *\n * @experimental The API surface may change before stabilizing.\n */\nexport interface BrowserFunctionDocs {\n /**\n * The `browser.*` functions in Markdown, one bullet per function, then the\n * browser's internal sites when it has any.\n */\n functions: string;\n /**\n * How to use the browser, one rule per entry, without bullets. Rules about\n * how the code runs (timeouts, how screenshots reach the model) belong to\n * whatever runs it, so add those yourself.\n */\n rules: string[];\n}\n\ninterface BrowserFunctionDefinition {\n /** One line for the model: how to call it and what it returns. */\n doc: string;\n call(session: BrowserSession, input: unknown): Promise<unknown>;\n}\n\n/** `browser.spec`'s input. */\ninterface BrowserSpecInput {\n /** A CDP domain, e.g. `\"Page\"`. Omit for the list of domains. */\n domain?: string;\n}\n\nconst SPEC_SCHEMA = {\n type: \"object\",\n properties: { domain: { type: \"string\", minLength: 1 } }\n} as const;\n\n// SAFETY: Each session method validates its input before using it, so the\n// casts below only tell TypeScript what the session checks at runtime.\nconst BROWSER_FUNCTIONS = {\n cdp: {\n doc: '`browser.cdp({ method, params?, sessionId?, timeoutMs? })` sends a CDP command and returns its result without the JSON-RPC envelope. Page-scoped commands take `sessionId: \"active\"`: `await browser.cdp({ method: \"Page.navigate\", params: { url }, sessionId: \"active\" })` returns `{ frameId, errorText? }`. `timeoutMs` limits this one command. A failed command throws, and the error often says how to fix the call.',\n call: (session, input) => session.send(input as BrowserSendInput)\n },\n attachToTarget: {\n doc: '`browser.attachToTarget({ targetId })` switches to an open tab, with `targetId` from `Target.getTargets`, and makes it active: `sessionId: \"active\"` points at it from then on. Returns `{ sessionId }` for that tab.',\n call: (session, input) =>\n session.attachToTarget(input as BrowserAttachInput)\n },\n spec: {\n doc: '`browser.spec()` lists the protocol\\'s domains as `{ domains: [{ name, description }] }`; `browser.spec({ domain: \"Page\" })` returns one domain\\'s `{ commands, events, types }`, each command a `{ name, method, description, parameters, returns }` (`name` is `\"navigate\"`, `method` is `\"Page.navigate\"`). Big domains get cut short in your result, so filter in code: `(await browser.spec({ domain: \"Network\" })).commands.find((c) => c.name === \"enable\")`.',\n call: async (session, input) => {\n // Check the input before connecting, like the session's own methods.\n const { domain } = validate(\n \"browser.spec\",\n SPEC_SCHEMA,\n input\n ) as BrowserSpecInput;\n return specResult(await session.spec(), domain);\n }\n },\n getDebugLog: {\n doc: \"`browser.getDebugLog({ limit? })` returns recent protocol traffic, newest last (50 entries unless `limit` says otherwise), each `{ at, type, ... }`. Use it when a command fails or times out.\",\n call: (session, input) => session.getDebugLog(input as BrowserDebugLogInput)\n },\n clearDebugLog: {\n doc: \"`browser.clearDebugLog()` forgets the traffic recorded so far, so the next `getDebugLog` shows only what follows.\",\n call: (session) => session.clearDebugLog()\n }\n} satisfies Record<string, BrowserFunctionDefinition>;\n\n/**\n * Without a domain, every domain's name and first sentence, which is small;\n * with one, that domain's commands, events and types. The whole protocol is\n * about 650 KB, too much for one result.\n */\nfunction specResult(spec: SearchableCdpSpec, domain: string | undefined) {\n const { domains } = spec;\n if (domain === undefined) {\n return {\n domains: domains.map(({ name, description }) => ({\n name,\n ...(description ? { description: firstSentence(description) } : {})\n })),\n hint: 'browser.spec({ domain: \"Page\" }) returns one domain\\'s commands, events and types.'\n };\n }\n const found = domains.find((d) => d.name === domain);\n if (found) return found;\n const near = domains.find(\n (d) => d.name.toLowerCase() === domain.toLowerCase()\n );\n throw new Error(\n `No CDP domain named '${domain}'.` +\n (near\n ? ` Did you mean '${near.name}'?`\n : \" browser.spec() lists the domains.\")\n );\n}\n\n/** A CDP description's first sentence, for the list of domains. */\nfunction firstSentence(text: string): string {\n return text.match(/^[\\s\\S]*?\\.(?=\\s|$)/)?.[0] ?? text;\n}\n\ninterface HostsFunctionDefinition {\n doc: string;\n /** Only offered when at least one host is assignable. */\n assignable?: true;\n /** Throw a fix-it error for bad input, before the session admits the call. */\n check?(input: unknown): void;\n call(hosts: BrowserInternalHosts, input: unknown): Promise<unknown>;\n}\n\n/**\n * The internal hosts a session's functions use, and the session's check\n * that runs before each hosts call: it rejects once the session is closed,\n * and waits for the scope's lock when the session locks, as the CDP\n * functions do.\n */\nexport interface SessionHosts {\n hosts: BrowserInternalHosts;\n admit(): Promise<void>;\n}\n\n/** The `host` field of a hosts function's input, or a fix-it error. */\nfunction hostOf(name: string, input: unknown): string {\n const host =\n typeof input === \"object\" && input !== null\n ? (input as { host?: unknown }).host\n : undefined;\n if (typeof host !== \"string\") {\n throw new Error(\n `browser.${name} needs { host }: the bare hostname, like \"preview.internal\".`\n );\n }\n return host;\n}\n\nconst HOSTS_FUNCTIONS = {\n listHosts: {\n doc: \"`browser.listHosts()` returns each internal site and the target it points at.\",\n call: (hosts) => hosts.list()\n },\n assignHost: {\n doc: '`browser.assignHost({ host, target })` points an assignable site at a target matching its schema and returns `{ url }`; `host` is the bare hostname, like \"preview.internal\". Navigate to the url next. It stays assigned across runs.',\n assignable: true,\n check: (input) => {\n const host = hostOf(\"assignHost\", input);\n if ((input as { target?: unknown }).target === undefined) {\n throw new Error(\n `browser.assignHost needs a target for ${host}; use browser.clearHost to unassign it`\n );\n }\n },\n call: (hosts, input) =>\n hosts.assign(\n hostOf(\"assignHost\", input),\n (input as { target?: unknown }).target\n )\n },\n clearHost: {\n doc: \"`browser.clearHost({ host })` unassigns a site and returns `{ cleared }`. An unassigned site answers 502.\",\n assignable: true,\n check: (input) => hostOf(\"clearHost\", input),\n call: async (hosts, input) => ({\n cleared: await hosts.clear(hostOf(\"clearHost\", input))\n })\n }\n} satisfies Record<string, HostsFunctionDefinition>;\n\n/** The hosts functions to offer: assign and clear only if any host can be. */\nfunction hostsFunctions(\n infos: InternalHostInfo[]\n): [string, HostsFunctionDefinition][] {\n const assignable = infos.some((info) => info.assignable);\n return Object.entries(HOSTS_FUNCTIONS).filter(\n ([, definition]: [string, HostsFunctionDefinition]) =>\n assignable || !definition.assignable\n );\n}\n\n/**\n * The `browser` object's functions, bound to one run's session, plus the\n * hosts functions when the browser has internal hostnames. Each hosts\n * function checks its input, then waits for `admit`, then calls the hosts.\n */\nexport function browserFunctions(\n session: BrowserSession,\n sessionHosts?: SessionHosts\n): Record<string, BrowserFunction> {\n const functions: Record<string, BrowserFunction> = Object.fromEntries(\n Object.entries(BROWSER_FUNCTIONS).map(([name, definition]) => [\n name,\n (input: unknown) => definition.call(session, input)\n ])\n );\n if (sessionHosts) {\n const { hosts, admit } = sessionHosts;\n for (const [name, definition] of hostsFunctions(hosts.describe())) {\n functions[name] = async (input: unknown) => {\n definition.check?.(input);\n await admit();\n return definition.call(hosts, input);\n };\n }\n }\n return functions;\n}\n\n/** How one internal site reads in the docs. */\nfunction describeHost(info: InternalHostInfo): string {\n const description = info.description ? ` — ${info.description}` : \"\";\n const target = info.assignable\n ? `. Assignable; target schema: ${JSON.stringify(info.targetSchema ?? {})}`\n : \"\";\n return `- ${info.url}${description}${target}`;\n}\n\n/**\n * The `browser` object's docs for the model: the functions offered for\n * `hosts`, and the rules.\n */\nexport function browserFunctionDocs(\n hosts?: BrowserInternalHosts\n): BrowserFunctionDocs {\n return { functions: functionsMarkdown(hosts), rules: [...BROWSER_RULES] };\n}\n\n/**\n * The functions in Markdown: one line per function, then the internal sites\n * when the browser has any.\n */\nfunction functionsMarkdown(hosts?: BrowserInternalHosts): string {\n const infos = hosts?.describe() ?? [];\n const functions = [\n ...Object.values(BROWSER_FUNCTIONS),\n ...(hosts ? hostsFunctions(infos).map(([, definition]) => definition) : [])\n ];\n const lines = functions.map((definition) => `- ${definition.doc}`);\n if (!hosts) return lines.join(\"\\n\");\n return [\n ...lines,\n \"\",\n \"## Internal sites\",\n \"\",\n \"The browser can open these sites, which aren't on the public internet. Plain http only: no https:// and no WebSockets, so a dev server's hot reload won't connect; reload the page instead.\",\n \"\",\n ...infos.map(describeHost)\n ].join(\"\\n\");\n}\n\n/**\n * How to use the browser, one rule per line. Each rule fixes a mistake\n * models make with CDP, or states something about this browser they can't\n * know; leave out what a model knows already. Rules about how the code runs\n * (timeouts, screenshots) belong to whatever runs it.\n */\nconst BROWSER_RULES: readonly string[] = [\n \"The browser persists between runs: tabs, cookies, and logins are still there next time. You never start or close it.\",\n \"If the browser was replaced (idle timeout, crash), a notice says so and earlier tabs and logins are gone. Before an action that matters (submitting a form, a purchase), check you're on the page you expect.\",\n 'Page-scoped commands (Page.*, Runtime.*, DOM.*, Input.*, Network.*, Emulation.*) need sessionId: \"active\", your tab, which is remembered between runs. Browser.* and Target.* commands take no sessionId.',\n \"Other open tabs (Target.getTargets) may belong to other conversations using this browser: don't close, navigate, or attach to a tab you didn't open unless the user asks.\",\n \"Target.createTarget opens a tab and makes it active. To switch to another open tab, call browser.attachToTarget({ targetId }); the sessionId it returns keeps working in later runs, while one from a raw Target.attachToTarget only works in the current run.\",\n \"Tabs a page opens itself (popups, target=_blank links) don't become active; a notice lists them.\",\n \"Runtime.evaluate: pass returnByValue: true, or objects come back as a remote reference with no value, and awaitPromise: true for async expressions. The value is at result.value. A thrown error doesn't reject: check exceptionDetails.\",\n \"Page.navigate returns before the page loads and doesn't throw when it fails: check errorText, then poll document.readyState with Runtime.evaluate until it is 'complete'.\",\n \"Pick out what you need inside Runtime.evaluate and return only that. Page.captureScreenshot throws when its result is over 1 MB.\"\n];\n","/**\n * Browser scopes: who is driving a shared `Browser`. Sessions with the same\n * scope share an active tab (and, when they lock, a lock); each scope\n * keeps its own. Cookies and logins are shared by every scope.\n */\n\n/**\n * The scope used when a caller doesn't pick one: every caller that leaves\n * `scope` out shares this one active tab. See `BrowserConnectOptions`.\n */\nexport const DEFAULT_BROWSER_SCOPE = \"shared\";\n\n/**\n * The scope for one conversation: `conversation:<id>`. pi's `browserTool`\n * gives each conversation this scope by default, so app code that opens\n * sessions with the same scope (a Workspace's `codemode:browser`, say) lands\n * in the same tab as the tool. pi's conversation ids are numbers: pass\n * `String(conversationId)`.\n *\n * Throws on a missing or empty id rather than returning\n * `\"conversation:undefined\"`, which would quietly put every conversation\n * without an id in one tab.\n *\n * @experimental The API surface may change before stabilizing.\n */\nexport function conversationScope(id: string): string {\n if (typeof id !== \"string\" || id === \"\") {\n throw new Error(\n `conversationScope needs a conversation id, got ${String(id)}.`\n );\n }\n return `conversation:${id}`;\n}\n","/**\n * `BrowserSession`: one run's connection to a persistent `Browser`, with the\n * rules that make CDP usable from model-written code.\n *\n * The model never manages CDP sessions. `sessionId: \"active\"` addresses the\n * tab the scope last worked in, `attachToTarget` returns a handle that keeps\n * working in later runs, and common protocol mistakes come back as\n * instructions. When the session closes it saves the scope's active tab and\n * reports what happened to the browser: a restart, a tab closed by someone\n * else, a tab shared with another scope, tabs the page opened.\n *\n * A session opened with `lock: true` holds its scope's lock from its first\n * call (or `lock()`) until it closes; other locking sessions in the scope\n * wait for it, in order.\n *\n * `browserTool` opens one per run.\n */\n\nimport {\n CDP_METHOD_NOT_FOUND,\n CdpProtocolError,\n type CdpConnection\n} from \"./cdp-connection\";\nimport type {\n BrowserConnection,\n BrowserConnectOptions,\n BrowserInternalHosts\n} from \"./browser\";\nimport {\n browserFunctions,\n type BrowserFunction,\n type SessionHosts\n} from \"./browser-functions\";\nimport { DEFAULT_BROWSER_SCOPE } from \"./scope\";\nimport type { SearchableCdpSpec } from \"./spec\";\nimport { validate } from \"./validate\";\n\n/**\n * What a {@link BrowserSession} connects to. Usually a `Browser` installed on\n * the host's Lifecycle.\n */\nexport interface BrowserSource {\n /** The browser's name, for log messages. */\n readonly name: string;\n /**\n * Reattach to the browser (or replace it) and open a CDP connection for\n * a scope. A source that ignores `scope` shares one active tab between\n * every caller.\n */\n connect(options?: BrowserConnectOptions): Promise<BrowserConnection>;\n /**\n * The browser's internal hostnames, when it has any. The docs list them,\n * and {@link BrowserSession.functions} adds the hosts functions.\n */\n readonly internalHosts?: BrowserInternalHosts;\n}\n\nexport interface BrowserSessionOptions {\n /**\n * Who is driving: sessions with the same scope share an active tab, and\n * each scope keeps its own. Cookies and logins are shared by every scope.\n * Defaults to the browser's default scope.\n */\n scope?: string;\n /**\n * The largest `Page.captureScreenshot` result `send` returns, measured as\n * JSON. Defaults to 1,000,000 bytes.\n */\n maxResultBytes?: number;\n /**\n * Lock the scope on this browser: the session takes the scope's lock at\n * its first call (or at {@link BrowserSession.lock}) and holds it until it\n * closes. Other locking sessions in the scope wait for the lock, in order,\n * rather than fail, so their calls never interleave. Sessions without it\n * don't wait and aren't waited for. Locks are per isolate, which is per\n * Durable Object.\n *\n * Use it when several runs in one scope can start together (parallel\n * tool calls, say) and must not see each other's navigation.\n *\n * Only `close()` releases the lock: not aborting a signal, losing the\n * browser, or dropping the session. Close a locking session in `finally`,\n * even when connecting failed, or its scope stays locked until the\n * isolate restarts.\n */\n lock?: boolean;\n}\n\n/** {@link BrowserSession.lock}'s options. */\nexport interface BrowserLockOptions {\n /**\n * Bounds this call's wait: when it aborts, this call rejects with its\n * reason. The session keeps waiting while other calls still are; once\n * none is, it leaves the queue at once, so it doesn't hold up the\n * sessions behind it. A call without a signal, including the wait a\n * session's first function call makes, never gives up. The signal does\n * nothing once the lock is held: only `close()` releases it.\n */\n signal?: AbortSignal;\n}\n\n/** `send`'s input. */\nexport interface BrowserSendInput {\n /** CDP method, e.g. `\"Page.navigate\"`. */\n method: string;\n /** CDP command parameters. */\n params?: Record<string, unknown>;\n /**\n * `\"active\"` for the current tab, or a handle from `attachToTarget`. Omit\n * for `Browser.*` and `Target.*` commands.\n */\n sessionId?: string;\n /** Per-command timeout in milliseconds. */\n timeoutMs?: number;\n}\n\n/** `attachToTarget`'s input. */\nexport interface BrowserAttachInput {\n /** Target id from `Target.getTargets` or `Target.createTarget`. */\n targetId: string;\n timeoutMs?: number;\n}\n\n/** `getDebugLog`'s input. */\nexport interface BrowserDebugLogInput {\n /** Most entries to return, newest last. Defaults to 50; 400 are kept. */\n limit?: number;\n}\n\n/** A tab a page opened on its own during a session. */\nexport interface BrowserNewTab {\n targetId: string;\n url?: string;\n title?: string;\n}\n\n/**\n * What happened to the browser during one session, beyond the results of its\n * calls. {@link BrowserSession.close} returns it.\n */\nexport interface BrowserSessionReport {\n /** The browser was replaced before this session; earlier page state is gone. */\n restarted: boolean;\n /** Tabs the page opened itself (popups, `target=_blank`). */\n newTabs: BrowserNewTab[];\n /**\n * The tab this scope was working in was closed by someone else (another\n * scope, or a person in Live View), so `\"active\"` will be a new blank tab.\n */\n tabClosed: boolean;\n /** Another scope is working in this scope's active tab too. */\n tabShared: boolean;\n /**\n * The report as sentences for the model, one per thing that happened,\n * empty when nothing did. Show them after the run's result.\n */\n notices: string[];\n}\n\nconst RESTARTED_NOTICE =\n \"The browser was restarted before this run (it expired or was closed): earlier tabs, logins, and page state are gone. Your code ran in a fresh browser — navigate again before relying on page state.\";\n\nconst TAB_CLOSED_NOTICE =\n 'The tab you were working in was closed (by another conversation using this browser, or a person). `sessionId: \"active\"` now opens a blank tab — navigate again before relying on page state.';\n\nconst TAB_SHARED_NOTICE =\n \"Another conversation using this browser is also working in your tab, so its page may change between your runs. Open a tab of your own with Target.createTarget if you need one.\";\n\n/** What the report says, in sentences the model reads. */\nfunction reportNotices(report: Omit<BrowserSessionReport, \"notices\">) {\n return [\n report.restarted && RESTARTED_NOTICE,\n report.tabClosed && !report.restarted && TAB_CLOSED_NOTICE,\n report.tabShared && TAB_SHARED_NOTICE,\n report.newTabs.length > 0 &&\n `New tabs opened by the page: ${JSON.stringify(report.newTabs)}`\n ].filter((notice) => typeof notice === \"string\");\n}\n\n/** One waiter in a {@link LockQueue}. */\ninterface LockWaiter {\n grant(): void;\n}\n\n/**\n * Who holds a scope's lock, and who waits for it, in order. A waiter that\n * gives up is removed at once, so nobody behind it waits on it.\n */\nclass LockQueue {\n #held = false;\n readonly #waiting: LockWaiter[] = [];\n\n readonly #onIdle: () => void;\n\n /** `onIdle` runs when the lock is freed with nobody waiting. */\n constructor(onIdle: () => void) {\n this.#onIdle = onIdle;\n }\n\n /** Resolve once this caller holds the lock. */\n take(signal: AbortSignal): Promise<void> {\n if (signal.aborted) {\n if (!this.#held && this.#waiting.length === 0) this.#onIdle();\n return Promise.reject(signal.reason);\n }\n if (!this.#held) {\n this.#held = true;\n return Promise.resolve();\n }\n return new Promise<void>((resolve, reject) => {\n const onAbort = () => {\n const index = this.#waiting.indexOf(waiter);\n if (index !== -1) this.#waiting.splice(index, 1);\n reject(signal.reason);\n };\n const waiter: LockWaiter = {\n grant: () => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve();\n }\n };\n this.#waiting.push(waiter);\n signal.addEventListener(\"abort\", onAbort, { once: true });\n });\n }\n\n /** Hand the lock to the next waiter, or free the scope. */\n release(): void {\n const next = this.#waiting.shift();\n if (next) {\n next.grant();\n return;\n }\n this.#held = false;\n this.#onIdle();\n }\n}\n\n/**\n * The lock queues per browser and scope. Keyed by the source, so custom\n * sources lock too, and dropped with it.\n */\nconst lockQueues = new WeakMap<BrowserSource, Map<string, LockQueue>>();\n\n/**\n * The scopes with a lock queue on `browser`: held, or waited for.\n *\n * @internal For tests that check queues are cleaned up.\n */\nexport function lockedScopes(browser: BrowserSource): string[] {\n return [...(lockQueues.get(browser)?.keys() ?? [])];\n}\n\n/**\n * One session's wait for its lock, shared by its concurrent `lock()` calls.\n * It gives up only when every call waiting on it has: none waits without a\n * signal, and every signal has aborted.\n */\ninterface LockAcquisition {\n promise: Promise<void>;\n /** Calls with a signal that are still waiting. */\n bounded: number;\n /** A call without a signal is waiting, so the wait never gives up. */\n unbounded: boolean;\n giveUp: AbortController;\n}\n\nfunction lockQueue(browser: BrowserSource, scope: string): LockQueue {\n let queues = lockQueues.get(browser);\n if (!queues) lockQueues.set(browser, (queues = new Map()));\n let queue = queues.get(scope);\n if (!queue) {\n const scopes = queues;\n queue = new LockQueue(() => scopes.delete(scope));\n queues.set(scope, queue);\n }\n return queue;\n}\n\n/** `sessionId` value that addresses the tab the agent is working in. */\nexport const ACTIVE_PAGE_SESSION = \"active\";\n\n/**\n * `attachToTarget` returns `{ sessionId: \"target:<targetId>\" }`, a stable\n * handle rather than a connection-scoped CDP session id, so it keeps working\n * in later runs. `send` resolves it on the live socket.\n */\nconst ATTACH_HANDLE_PREFIX = \"target:\";\n\n/** Chrome's JSON-RPC code for a CDP session id it doesn't know. */\nconst CDP_SESSION_NOT_FOUND = -32001;\n\n/**\n * Screenshots are kept whole in the chat message for the UI, and a stored\n * message must fit SQLite's 2 MB row (see `ROW_MAX_BYTES` in chat/sanitize.ts),\n * or the image is compacted away. Failing early lets the model retake it\n * smaller. Other results are cut to a preview before they're stored.\n *\n * @internal The tools also refuse to keep a returned screenshot over it.\n */\nexport const DEFAULT_MAX_RESULT_BYTES = 1_000_000;\n\n/** `#liveParams`: nothing to detach. */\nconst DETACHED = Symbol(\"detached\");\n\nconst MANAGED_BROWSER =\n \"this browser is managed for you and persists between runs. To close a \" +\n \"tab, send Target.closeTarget with its targetId.\";\nconst HOST_ONLY = \"it is for the host, not your code.\";\nconst NO_TUNNELING =\n \"send each command with browser.cdp instead, passing sessionId to reach a tab.\";\n\n/**\n * Commands model code can't send, and why.\n *\n * - Ending the browser: the host owns its lifetime, so the model can't close\n * it out from under the agent (and lose its logins).\n * - Live View and handoff: a Live View link controls the whole browser, so it\n * goes to a trusted person through `Browser.liveView()`, never to the model.\n * - Tunnels: these carry raw protocol messages past this check.\n */\nconst REFUSED_COMMANDS = new Map([\n [\"Browser.close\", MANAGED_BROWSER],\n [\"Browser.crash\", MANAGED_BROWSER],\n [\"Browser.crashGpuProcess\", MANAGED_BROWSER],\n [\"Cloudflare.getLiveView\", HOST_ONLY],\n [\"Cloudflare.handoff\", HOST_ONLY],\n [\"Target.sendMessageToTarget\", NO_TUNNELING],\n [\"Target.exposeDevToolsProtocol\", NO_TUNNELING]\n]);\n\n/** A CDP target id: for this session, a tab. */\ntype TargetId = string & { readonly __brand: \"TargetId\" };\n\n/** A CDP session id from `Target.attachToTarget`, valid on one socket only. */\ntype LiveSessionId = string & { readonly __brand: \"LiveSessionId\" };\n\n/** The stable `sessionId` handle `attachToTarget` gives the model. */\ntype AttachHandle = `${typeof ATTACH_HANDLE_PREFIX}${string}`;\n\ninterface TargetInfo {\n targetId: TargetId;\n type: string;\n url?: string;\n title?: string;\n /** The tab that opened this one (popups, `target=_blank` links). */\n openerId?: TargetId;\n}\n\n/** The session's connection and what it learned. Dropped when it closes. */\ninterface ConnectedState {\n connected: BrowserConnection;\n /** Live CDP session per target, valid on this socket only. */\n attached: Map<TargetId, LiveSessionId>;\n /**\n * Tabs this session attached to, through `attachToTarget` or a raw\n * `Target.attachToTarget`. Their popups are this session's new tabs.\n */\n workedIn: Set<TargetId>;\n /** Page targets open when the session connected. */\n initialPages: Set<TargetId>;\n /** The tab `\"active\"` resolves to, decided on first use. */\n activeTargetId?: TargetId;\n /** Whether {@link activeTargetId} was decided (vs. never needed). */\n activeResolved: boolean;\n /** Tabs this session closed with `Target.closeTarget`. */\n closed: Set<TargetId>;\n report: Omit<BrowserSessionReport, \"notices\">;\n}\n\nconst SEND_SCHEMA = {\n type: \"object\",\n properties: {\n method: { type: \"string\", minLength: 1 },\n params: { type: \"object\" },\n sessionId: { type: \"string\" },\n timeoutMs: { type: \"number\", exclusiveMinimum: 0 }\n },\n required: [\"method\"]\n} as const;\n\nconst ATTACH_SCHEMA = {\n type: \"object\",\n properties: {\n targetId: { type: \"string\", minLength: 1 },\n timeoutMs: { type: \"number\", exclusiveMinimum: 0 }\n },\n required: [\"targetId\"]\n} as const;\n\nconst DEBUG_LOG_SCHEMA = {\n type: \"object\",\n properties: { limit: { type: \"number\", minimum: 1 } }\n} as const;\n\n/**\n * One run's connection to a persistent browser, for one scope.\n *\n * It connects on its first call and stays connected until {@link close}.\n * Concurrent first calls share one connect. Every method takes one options\n * object, validated before anything touches the browser, because the input\n * usually comes from model-written code.\n *\n * Create one per run with `browser.session({ scope })`, and close it when\n * the run ends. The browser itself stays open. Pass `lock: true` when\n * runs in one scope may overlap; see {@link BrowserSessionOptions.lock}.\n *\n * @experimental The API surface may change before stabilizing.\n */\nexport class BrowserSession {\n readonly #browser: BrowserSource;\n readonly #scope: string | undefined;\n readonly #maxResultBytes: number;\n readonly #locksScope: boolean;\n #state?: ConnectedState;\n #connecting?: Promise<ConnectedState>;\n #closed = false;\n #functions?: Readonly<Record<string, BrowserFunction>>;\n /** The wait for the lock, until it settles. */\n #acquiring?: LockAcquisition;\n /** The queue this session holds the lock in, until it closes. */\n #heldLock?: LockQueue;\n /** Aborts this session's wait for the lock when it closes. */\n readonly #closing = new AbortController();\n #waitedForLockMs = 0;\n\n constructor(browser: BrowserSource, options: BrowserSessionOptions = {}) {\n this.#browser = browser;\n this.#scope = options.scope;\n this.#maxResultBytes = options.maxResultBytes ?? DEFAULT_MAX_RESULT_BYTES;\n this.#locksScope = options.lock ?? false;\n }\n\n /**\n * The `browser.*` functions bound to this session, by name: the ones\n * `Browser.functionDocs()` describes. Each takes one input object and\n * validates it, so model-written code can call them directly. Like the\n * session's methods, every one rejects once the session is closed, and\n * waits for the scope's lock when the session locks.\n */\n get functions(): Readonly<Record<string, BrowserFunction>> {\n this.#functions ??= Object.freeze(\n browserFunctions(this, this.#sessionHosts())\n );\n return this.#functions;\n }\n\n /**\n * Take this scope's lock now rather than at the first call, and hold it\n * until {@link close}. For sessions opened with `lock: true`; a\n * caller with its own time limit calls it first, so the wait doesn't count\n * against the limit, or passes `signal` to bound the wait.\n *\n * Resolves once the session holds the lock, after the locking sessions\n * ahead of it close; later and concurrent calls resolve with the same\n * lock. Rejects when the session closes while waiting. Each call's\n * `signal` bounds only that call's wait: it rejects with the signal's\n * reason, and the session leaves the queue once no call is still\n * waiting (see {@link BrowserLockOptions.signal}); a later call or first\n * call waits again.\n */\n lock(options: BrowserLockOptions = {}): Promise<void> {\n if (!this.#locksScope) {\n return Promise.reject(\n new Error(\n \"This browser session doesn't lock its scope. Open it with { lock: true }.\"\n )\n );\n }\n if (this.#closed) {\n return Promise.reject(new Error(\"This browser session is closed.\"));\n }\n if (this.#heldLock) return Promise.resolve();\n const { signal } = options;\n if (signal?.aborted) return Promise.reject(signal.reason);\n const acquisition = (this.#acquiring ??= this.#acquire());\n if (acquisition.giveUp.signal.aborted) {\n // Every earlier call gave up and the wait is ending: wait again once\n // it has, unless it got the lock first.\n return acquisition.promise.then(\n () => undefined,\n () => this.lock(options)\n );\n }\n if (!signal) {\n acquisition.unbounded = true;\n return acquisition.promise;\n }\n acquisition.bounded++;\n return new Promise<void>((resolve, reject) => {\n const onAbort = () => {\n acquisition.bounded--;\n if (acquisition.bounded === 0 && !acquisition.unbounded) {\n acquisition.giveUp.abort(signal.reason);\n }\n reject(signal.reason);\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n acquisition.promise.then(\n () => {\n signal.removeEventListener(\"abort\", onAbort);\n resolve();\n },\n (error: unknown) => {\n signal.removeEventListener(\"abort\", onAbort);\n reject(error);\n }\n );\n });\n }\n\n /**\n * How long this session waited for its lock, in milliseconds: `0` until\n * it has waited, and for sessions that don't lock.\n */\n get waitedForLockMs(): number {\n return this.#waitedForLockMs;\n }\n\n /**\n * Send a CDP command and resolve with its result, without the JSON-RPC\n * envelope. `sessionId: \"active\"` runs it in the scope's tab.\n */\n async send(input: BrowserSendInput): Promise<unknown> {\n const { method, params, sessionId, timeoutMs } = validate(\n \"browser.cdp\",\n SEND_SCHEMA,\n input\n ) as BrowserSendInput;\n const refused = REFUSED_COMMANDS.get(method);\n if (refused) throw new Error(`${method} is not available: ${refused}`);\n const state = await this.#connect();\n const live = await this.#resolveSessionId(state, sessionId);\n const liveParams = this.#liveParams(state, method, params);\n if (liveParams === DETACHED) return {};\n let result: unknown;\n try {\n result = await state.connected.cdp.send(method, liveParams, {\n sessionId: live,\n timeoutMs\n });\n } catch (error) {\n throw await this.#teach(state, error, method, sessionId);\n }\n this.#observe(state, method, liveParams, result);\n if (method === \"Page.captureScreenshot\") this.#assertFits(result);\n return result;\n }\n\n /**\n * Make an open tab the scope's active tab, and resolve with a `sessionId`\n * handle for it that keeps working in later runs.\n */\n async attachToTarget(\n input: BrowserAttachInput\n ): Promise<{ sessionId: string }> {\n const { targetId, timeoutMs } = validate(\n \"browser.attachToTarget\",\n ATTACH_SCHEMA,\n input\n ) as BrowserAttachInput;\n const state = await this.#connect();\n // SAFETY: Chrome rejects a target id it doesn't know.\n const target = targetId as TargetId;\n await this.#attach(state, target, timeoutMs);\n this.#setActive(state, target);\n return { sessionId: attachHandle(target) };\n }\n\n /** The Chrome DevTools Protocol description the browser serves. */\n async spec(): Promise<SearchableCdpSpec> {\n return (await this.#connect()).connected.spec();\n }\n\n /** Recent CDP traffic on this session's connection, newest last. */\n async getDebugLog(input?: BrowserDebugLogInput): Promise<unknown[]> {\n const { limit } = validate(\n \"browser.getDebugLog\",\n DEBUG_LOG_SCHEMA,\n input\n ) as BrowserDebugLogInput;\n return (await this.#connect()).connected.cdp.getDebugLog(limit);\n }\n\n /** Forget the CDP traffic recorded so far. */\n async clearDebugLog(): Promise<null> {\n (await this.#connect()).connected.cdp.clearDebugLog();\n return null;\n }\n\n /**\n * End the session: save the scope's active tab, work out what happened to\n * the browser, and close the connection. The browser stays open.\n *\n * Resolves with the report, or `undefined` when the session never\n * connected. Never rejects: failures to read the browser's state are\n * logged and leave the report incomplete. Later calls resolve with\n * `undefined`, and other methods reject.\n *\n * A locking session releases the lock once the active tab is saved, or\n * stops waiting for it if it was still waiting.\n */\n async close(): Promise<BrowserSessionReport | undefined> {\n if (this.#closed) return undefined;\n this.#closed = true;\n // Stop waiting for the lock, if this session is.\n this.#closing.abort(new Error(\"This browser session is closed.\"));\n try {\n let state: ConnectedState | undefined;\n try {\n state = this.#state ?? (await this.#connecting);\n } catch {\n return undefined; // the connect failed; its caller got the error\n }\n if (!state) return undefined;\n this.#state = undefined;\n try {\n const open = await this.#recordNewTabs(state);\n const active = await this.#saveActiveTarget(state, open);\n if (active && state.activeResolved) {\n await this.#recordSharedTab(state, active);\n }\n } finally {\n state.connected.cdp.disconnect();\n }\n return { ...state.report, notices: reportNotices(state.report) };\n } finally {\n // Release the lock only after the active tab is saved, so the next\n // session in the scope finds where this one left off.\n await this.#acquiring?.promise.catch(() => undefined);\n this.#heldLock?.release();\n this.#heldLock = undefined;\n }\n }\n\n // ── Internals ────────────────────────────────────────────────────────────\n\n /**\n * Connect once, after taking the lock if this session locks its scope.\n * Concurrent first calls share one connect.\n */\n #connect(): Promise<ConnectedState> {\n if (this.#closed) {\n return Promise.reject(new Error(\"This browser session is closed.\"));\n }\n if (this.#state) return Promise.resolve(this.#state);\n this.#connecting ??= this.#admitThenOpen().finally(() => {\n this.#connecting = undefined;\n });\n return this.#connecting;\n }\n\n /** The browser's internal hosts, behind this session's admission check. */\n #sessionHosts(): SessionHosts | undefined {\n const hosts = this.#browser.internalHosts;\n return hosts && { hosts, admit: () => this.#admit() };\n }\n\n async #admitThenOpen(): Promise<ConnectedState> {\n await this.#admit();\n return this.#open();\n }\n\n /**\n * The check every function makes before it touches the browser: reject\n * once the session is closed, and wait for the lock when the session\n * locks. It doesn't connect.\n */\n async #admit(): Promise<void> {\n if (this.#closed) throw new Error(\"This browser session is closed.\");\n if (!this.#locksScope) return;\n await this.lock();\n if (this.#closed) throw new Error(\"This browser session is closed.\");\n }\n\n /** Start waiting for the lock, given up when its calls do or on close. */\n #acquire(): LockAcquisition {\n const giveUp = new AbortController();\n const promise: Promise<void> = this.#waitForLock(\n AbortSignal.any([giveUp.signal, this.#closing.signal])\n ).finally(() => {\n if (this.#acquiring?.promise === promise) this.#acquiring = undefined;\n });\n // Callers get the error; this keeps a wait nobody awaits from going\n // unhandled.\n promise.catch(() => undefined);\n return { promise, bounded: 0, unbounded: false, giveUp };\n }\n\n async #waitForLock(signal: AbortSignal): Promise<void> {\n // Before the queue exists, so a wait given up at once leaves none.\n signal.throwIfAborted();\n const queue = lockQueue(\n this.#browser,\n this.#scope ?? DEFAULT_BROWSER_SCOPE\n );\n const started = Date.now();\n try {\n await queue.take(signal);\n this.#heldLock = queue;\n } finally {\n this.#waitedForLockMs += Date.now() - started;\n }\n }\n\n async #open(): Promise<ConnectedState> {\n const connected = await this.#browser.connect(\n this.#scope === undefined ? undefined : { scope: this.#scope }\n );\n let initialPages: TargetInfo[];\n try {\n initialPages = await this.#pages(connected.cdp);\n } catch (error) {\n connected.cdp.disconnect();\n throw error;\n }\n const state: ConnectedState = {\n connected,\n attached: new Map(),\n workedIn: new Set(),\n initialPages: new Set(initialPages.map((page) => page.targetId)),\n activeResolved: false,\n closed: new Set(),\n report: {\n restarted: connected.restarted,\n newTabs: [],\n tabClosed: false,\n tabShared: false\n }\n };\n if (this.#closed) {\n // Closed while connecting: close() is waiting on this state.\n return state;\n }\n this.#state = state;\n return state;\n }\n\n /**\n * A screenshot over the limit is too big to keep in the chat message\n * (see `DEFAULT_MAX_RESULT_BYTES`), so fail with how to take a smaller one.\n */\n #assertFits(result: unknown): void {\n // Measure the result as JSON, not just the data, so a screenshot just\n // under the limit can't slip past with its JSON framing.\n const size = JSON.stringify(result ?? null).length;\n if (size <= this.#maxResultBytes) return;\n const megabytes = (size / 1_000_000).toFixed(1);\n const limit = (this.#maxResultBytes / 1_000_000).toFixed(0);\n throw new Error(\n `The screenshot result is ${megabytes} MB, over the ${limit} MB limit on a ` +\n `send result. Capture just the viewport (no captureBeyondViewport ` +\n `or clip larger than the window), or pass format: \"jpeg\" with ` +\n `quality: 60.`\n );\n }\n\n /**\n * Add tabs the page opened during this session to the report. Returns the\n * open tabs, or `undefined` when the browser couldn't be asked.\n */\n async #recordNewTabs(\n state: ConnectedState\n ): Promise<Set<TargetId> | undefined> {\n let pages: TargetInfo[];\n try {\n pages = await this.#pages(state.connected.cdp);\n } catch (error) {\n this.#warn(\"list the open tabs\", error);\n return undefined;\n }\n const opened = new Set<string>();\n // A new tab is this session's when its opener is a tab this session\n // worked in, or another of its new tabs (a popup's popup). Chrome sets\n // openerId only on tabs a page opened, never on Target.createTarget\n // tabs, and a popup another scope's page opened meanwhile has that\n // scope's tab as its opener.\n let grew = true;\n while (grew) {\n grew = false;\n for (const page of pages) {\n const opener = page.openerId;\n if (\n !opener ||\n opened.has(page.targetId) ||\n state.initialPages.has(page.targetId)\n ) {\n continue;\n }\n if (state.workedIn.has(opener) || opened.has(opener)) {\n opened.add(page.targetId);\n grew = true;\n }\n }\n }\n state.report.newTabs = pages\n .filter((page) => opened.has(page.targetId))\n .map(({ targetId, url, title }) => ({ targetId, url, title }));\n return new Set(pages.map((page) => page.targetId));\n }\n\n /**\n * Save the tab this session settled on, forgetting one that has since\n * closed, and return it. Without the list of open tabs, save the choice\n * unchecked: the next session checks the stored tab is still open before\n * using it.\n */\n async #saveActiveTarget(\n state: ConnectedState,\n open: Set<TargetId> | undefined\n ): Promise<TargetId | undefined> {\n const stored = state.connected.activeTargetId as TargetId | undefined;\n // A session that never used \"active\" still sees the stored tab is gone;\n // say so now, since the next session won't know there was one.\n if (\n !state.activeResolved &&\n stored &&\n open &&\n !open.has(stored) &&\n !state.closed.has(stored)\n ) {\n state.report.tabClosed = true;\n }\n const candidate = state.activeResolved ? state.activeTargetId : stored;\n const active =\n candidate && (!open || open.has(candidate)) ? candidate : undefined;\n if (active === stored) return active;\n try {\n await state.connected.setActiveTarget(active);\n } catch (error) {\n this.#warn(\"save the active tab\", error);\n }\n return active;\n }\n\n /** Report when another scope is working in this session's tab too. */\n async #recordSharedTab(\n state: ConnectedState,\n active: TargetId\n ): Promise<void> {\n try {\n const others = await state.connected.targetsInOtherScopes();\n if (others.has(active)) state.report.tabShared = true;\n } catch (error) {\n this.#warn(\"check whether the active tab is shared\", error);\n }\n }\n\n #warn(action: string, error: unknown): void {\n console.warn(\n `[agents/browser] Failed to ${action} for browser \"${this.#browser.name}\"`,\n error\n );\n }\n\n async #pages(cdp: CdpConnection): Promise<TargetInfo[]> {\n const result = (await cdp.send(\"Target.getTargets\")) as {\n targetInfos?: TargetInfo[];\n };\n return (result?.targetInfos ?? []).filter((info) => info.type === \"page\");\n }\n\n async #resolveSessionId(\n state: ConnectedState,\n sessionId: string | undefined\n ): Promise<LiveSessionId | undefined> {\n if (sessionId === ACTIVE_PAGE_SESSION) {\n return this.#attach(state, await this.#activeTarget(state));\n }\n if (isAttachHandle(sessionId)) {\n return this.#attach(state, targetOfHandle(sessionId));\n }\n // Omitted, or a raw CDP session id the model got from send().\n return sessionId as LiveSessionId | undefined;\n }\n\n /**\n * Decide which tab `\"active\"` means, once per session: the scope's stored\n * tab if it is still open, else a new blank tab. Never a tab the scope\n * didn't open, even a blank one: it may be another scope's, or a popup.\n */\n async #activeTarget(state: ConnectedState): Promise<TargetId> {\n if (state.activeTargetId) return state.activeTargetId;\n const { connected } = state;\n const pages = await this.#pages(connected.cdp);\n const stored = connected.activeTargetId as TargetId | undefined;\n let targetId = pages.find((page) => page.targetId === stored)?.targetId;\n if (!targetId && stored && !state.closed.has(stored)) {\n state.report.tabClosed = true;\n }\n if (!targetId) {\n const created = (await connected.cdp.send(\"Target.createTarget\", {\n url: \"about:blank\"\n })) as { targetId: TargetId };\n targetId = created.targetId;\n }\n this.#setActive(state, targetId);\n return targetId;\n }\n\n #setActive(state: ConnectedState, targetId: TargetId | undefined): void {\n state.activeTargetId = targetId;\n state.activeResolved = true;\n }\n\n async #attach(\n state: ConnectedState,\n targetId: TargetId,\n timeoutMs?: number\n ): Promise<LiveSessionId> {\n const existing = state.attached.get(targetId);\n if (existing) return existing;\n const live = (await state.connected.cdp.attachToTarget(targetId, {\n timeoutMs\n })) as LiveSessionId;\n state.attached.set(targetId, live);\n state.workedIn.add(targetId);\n return live;\n }\n\n /** Track tab changes the model makes through raw Target commands. */\n #observe(\n state: ConnectedState,\n method: string,\n params: Record<string, unknown> | undefined,\n result: unknown\n ): void {\n const targetId =\n typeof params?.targetId === \"string\"\n ? (params.targetId as TargetId)\n : undefined;\n if (method === \"Target.createTarget\") {\n const created = (result as { targetId?: unknown } | undefined)?.targetId;\n if (typeof created === \"string\") {\n this.#setActive(state, created as TargetId);\n }\n } else if (method === \"Target.attachToTarget\" && targetId) {\n this.#setActive(state, targetId);\n state.workedIn.add(targetId);\n } else if (method === \"Target.closeTarget\" && targetId) {\n state.attached.delete(targetId);\n state.closed.add(targetId);\n // The next \"active\" use picks a tab afresh.\n if (state.activeTargetId === targetId) state.activeTargetId = undefined;\n } else if (method === \"Target.detachFromTarget\") {\n // Forget a session the model detached, so the next use reattaches.\n for (const [target, live] of state.attached) {\n if (target === targetId || live === params?.sessionId) {\n state.attached.delete(target);\n }\n }\n }\n }\n\n /**\n * Swap a handle in `Target.detachFromTarget`'s `sessionId` param for the\n * live CDP session id. Returns {@link DETACHED} when the handle's tab isn't\n * attached on this socket, so there is nothing to detach.\n */\n #liveParams(\n state: ConnectedState,\n method: string,\n params: Record<string, unknown> | undefined\n ): Record<string, unknown> | undefined | typeof DETACHED {\n const handle = params?.sessionId;\n if (method !== \"Target.detachFromTarget\" || typeof handle !== \"string\") {\n return params;\n }\n if (!isAttachHandle(handle)) return params;\n const live = state.attached.get(targetOfHandle(handle));\n return live ? { ...params, sessionId: live } : DETACHED;\n }\n\n /**\n * Turn the common protocol mistakes into instructions: an expired CDP\n * session id, an event sent as a command, and a page-scoped command\n * without a session.\n */\n async #teach(\n state: ConnectedState,\n error: unknown,\n method: string,\n sessionId: string | undefined\n ): Promise<unknown> {\n if (!(error instanceof CdpProtocolError)) return error;\n if (\n error.code === CDP_SESSION_NOT_FOUND &&\n sessionId &&\n sessionId !== ACTIVE_PAGE_SESSION &&\n !isAttachHandle(sessionId)\n ) {\n return new Error(\n `${error.message}. CDP session ids don't carry over between runs. ` +\n `Use sessionId: \"active\" for the current tab, or the handle from ` +\n `browser.attachToTarget({ targetId }) for another tab.`\n );\n }\n if (error.code !== CDP_METHOD_NOT_FOUND) return error;\n if (await this.#isEvent(state, method)) {\n return new Error(\n `${error.message}. '${method}' is a CDP *event*, not a command, so it ` +\n `cannot be sent. To wait for page state, poll instead (e.g. ` +\n `Runtime.evaluate of document.readyState until \"complete\").`\n );\n }\n if (!sessionId) {\n return new Error(\n `${error.message}. '${method}' is page-scoped: pass sessionId: ` +\n `\"active\" to run it in the current tab: ` +\n `browser.cdp({ method: \"${method}\", params, sessionId: \"active\" }).`\n );\n }\n return error;\n }\n\n async #isEvent(state: ConnectedState, method: string): Promise<boolean> {\n try {\n const spec = await state.connected.spec();\n const domain = method.split(\".\")[0];\n return spec.domains.some(\n (d) => d.name === domain && d.events.some((e) => e.event === method)\n );\n } catch {\n return false;\n }\n }\n}\n\nfunction attachHandle(targetId: TargetId): AttachHandle {\n return `${ATTACH_HANDLE_PREFIX}${targetId}`;\n}\n\nfunction isAttachHandle(\n sessionId: string | undefined\n): sessionId is AttachHandle {\n return sessionId?.startsWith(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AAQ;EACN,OAAO;CACT;AACF;AAGF,SAAS,aAAa,UAAkC;CACtD,OAAO,GAAG,uBAAuB;AACnC;AAEA,SAAS,eACP,WAC2B;CAC3B,OAAO,WAAW,WAAW,oBAAoB,KAAK;AACxD;AAEA,SAAS,eAAe,QAAgC;CACtD,OAAO,OAAO,MAAM,CAA2B;AACjD"}
@@ -1,5 +1,5 @@
1
1
  import { t as __DO_NOT_USE_WILL_BREAK__agentContext } from "./current-agent-DhoDkSnH.js";
2
- import "./session-7CDgVE0z.js";
2
+ import "./session-CRY0bGiI.js";
3
3
  import { t as redactBase64Payloads } from "./base64-redaction-C1Uu29t5.js";
4
4
  //#region src/browser/truncate.ts
5
5
  /**
@@ -252,4 +252,4 @@ function resolveCtx(options) {
252
252
  //#endregion
253
253
  export { truncateResult as a, transformBrowserResult as i, browserScreenshotOutput as n, resolveCtx as r, browserExecuteModelOutput as t };
254
254
 
255
- //# sourceMappingURL=tool-helpers-BI7ifO2S.js.map
255
+ //# sourceMappingURL=tool-helpers-F3_Wy2YX.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"tool-helpers-BI7ifO2S.js","names":["agentContext"],"sources":["../src/browser/truncate.ts","../src/browser/tool-helpers.ts"],"sourcesContent":["/**\n * Result truncation for the browser tools, copied from\n * `@cloudflare/codemode`'s `truncateResult` so `agents/browser` doesn't need\n * codemode. Internal — not an entry point.\n *\n * Structured values are truncated structurally: the output is always valid\n * JSON of the same shape, with the largest values cut first. A truncated\n * string ends with a marker, a truncated array ends with a marker element\n * counting the dropped items, and an object that had to lose entries carries a\n * marker entry naming the omitted keys. Every marker contains\n * `--- TRUNCATED ---` so callers and models can find them.\n */\n\n/** ~4 characters per token is a reasonable cross-model estimate. */\nconst CHARS_PER_TOKEN = 4;\nconst DEFAULT_MAX_TOKENS = 6000;\nconst TRUNCATION_MARKER = \"--- TRUNCATED ---\";\n/**\n * The least a string or container is worth keeping at (see `floorSize`). A\n * value that would get fewer serialized characters than this is dropped in\n * favour of its siblings rather than reduced to a bare marker.\n */\nconst MIN_SLOT = 128;\n\ntype TruncateOptions = {\n /**\n * Maximum characters in the (serialized) output before truncation kicks in.\n * Defaults to `maxTokens * 4`.\n */\n maxChars?: number;\n /** Token budget used to derive the default `maxChars`. Defaults to 6000. */\n maxTokens?: number;\n};\n\nfunction budget(options?: TruncateOptions): {\n maxChars: number;\n maxTokens: number;\n} {\n const maxTokens = options?.maxTokens ?? DEFAULT_MAX_TOKENS;\n const maxChars = options?.maxChars ?? maxTokens * CHARS_PER_TOKEN;\n return { maxChars, maxTokens };\n}\n\n/**\n * Truncate a text response to a character budget, appending a marker that notes\n * the original size so the model knows the output was clipped. Returns the\n * input unchanged when it is within budget.\n */\nfunction truncateResponse(text: string, options?: TruncateOptions): string {\n const { maxChars, maxTokens } = budget(options);\n if (text.length <= maxChars) return text;\n\n const estimatedTokens = Math.ceil(text.length / CHARS_PER_TOKEN);\n return (\n text.slice(0, maxChars) +\n `\\n\\n${TRUNCATION_MARKER}\\nResponse was ~${estimatedTokens.toLocaleString()} tokens ` +\n `(limit: ${maxTokens.toLocaleString()}). Narrow the request to reduce response size.`\n );\n}\n\n/**\n * Truncate a structured result. Strings are truncated directly. Other values\n * pass through unchanged (same reference) when their JSON serialization is\n * within budget. When oversized, the value is shrunk structurally — largest\n * values first, deepest last — so the model gets a bounded value that is still\n * valid JSON of the original shape, with markers where content was cut.\n *\n * Values that can't be serialized (cycles, bigint, `undefined`) are returned\n * unchanged.\n */\nexport function truncateResult(\n value: unknown,\n options?: TruncateOptions\n): unknown {\n if (typeof value === \"string\") return truncateResponse(value, options);\n\n let serialized: string | undefined;\n try {\n serialized = JSON.stringify(value);\n } catch {\n return value;\n }\n if (serialized === undefined) return value;\n\n const { maxChars } = budget(options);\n if (serialized.length <= maxChars) return value;\n\n // Re-parse so `toJSON`, class instances and `undefined` members are seen in\n // their serialized form — the shape the model would receive anyway.\n const shrunk = shrink(JSON.parse(serialized) as Json, maxChars);\n // `shrink` honours its budget for anything a container can hold; only a\n // scalar (a number too long for the budget) can still miss it.\n return size(shrunk) <= maxChars\n ? shrunk\n : truncateResponse(serialized, options);\n}\n\n// ---------------------------------------------------------------------------\n// Structural shrinking\n// ---------------------------------------------------------------------------\n//\n// Every `shrink*` below returns a value whose compact serialization fits the\n// budget it was given, provided the budget can hold an empty container (2\n// chars). Containers share their budget by water-filling: each child is owed\n// at least its floor (`floorSize`), small children keep their full size, and\n// the largest children absorb the cut. A container only drops children when\n// even their floors cannot fit — arrays drop from the tail (order carries\n// meaning), objects drop their largest values first (keys are all meaningful).\n\ntype Json = string | number | boolean | null | Json[] | { [key: string]: Json };\n\n/** Serialized size in characters (compact JSON). */\nfunction size(value: Json): number {\n return JSON.stringify(value).length;\n}\n\n/** Only strings and containers can give up characters; scalars are atomic. */\nfunction shrinkable(value: Json): boolean {\n return typeof value === \"string\" || (typeof value === \"object\" && !!value);\n}\n\n/**\n * The least budget a value is kept at; a scalar must fit whole. The floor\n * never exceeds half the container's own budget, so tiny budgets still keep\n * something rather than nothing.\n */\nfunction floorSize(value: Json, maxChars: number): number {\n const full = size(value);\n return shrinkable(value)\n ? Math.min(full, MIN_SLOT, Math.max(2, Math.floor(maxChars / 2)))\n : full;\n}\n\nfunction shrink(value: Json, maxChars: number): Json {\n if (size(value) <= maxChars) return value;\n if (typeof value === \"string\") return shrinkString(value, maxChars);\n if (Array.isArray(value)) return shrinkArray(value, maxChars);\n if (typeof value === \"object\" && value !== null) {\n return shrinkObject(value, maxChars);\n }\n return value;\n}\n\nfunction shrinkString(value: string, maxChars: number): string {\n const suffix = ` ${TRUNCATION_MARKER} ${value.length.toLocaleString()} chars`;\n let keep = Math.max(0, maxChars - suffix.length - 2);\n let out = value.slice(0, keep) + suffix;\n // Escapes inflate the serialized form; back off until it fits.\n while (keep > 0 && size(out) > maxChars) {\n keep = Math.max(0, keep - (size(out) - maxChars));\n out = value.slice(0, keep) + suffix;\n }\n // No room for a prefix and the size note: keep as much of the marker as fits.\n return size(out) <= maxChars\n ? out\n : TRUNCATION_MARKER.slice(0, Math.max(0, maxChars - 2));\n}\n\n/**\n * Share `available` characters across values by water-filling: values are\n * admitted smallest first, each taking the lesser of its full size and an\n * equal share of what is left. Requires `available >= Σ floorSize(values)`;\n * then every value receives at least its floor.\n */\nfunction allocate(values: Json[], available: number): number[] {\n const sizes = values.map(size);\n const order = sizes.map((_, i) => i).sort((a, b) => sizes[a] - sizes[b]);\n const allocation = new Array<number>(values.length);\n let remaining = available;\n let count = values.length;\n for (const i of order) {\n const alloc = Math.min(sizes[i], Math.floor(remaining / count));\n allocation[i] = alloc;\n remaining -= alloc;\n count--;\n }\n return allocation;\n}\n\nfunction shrinkArray(items: Json[], maxChars: number): Json[] {\n const marker = (dropped: number) =>\n `${TRUNCATION_MARKER} ${dropped.toLocaleString()} more items`;\n const floors = items.map((item) => floorSize(item, maxChars));\n const skeleton = (count: number) => 2 + Math.max(0, count - 1);\n\n // Keep everything when every floor fits.\n let keep = items.length;\n if (floors.reduce((n, f) => n + f, 0) + skeleton(keep) > maxChars) {\n // Otherwise keep the longest prefix whose floors fit beside a tail marker\n // (sized for the largest possible count, so the real one always fits).\n const tail = size(marker(items.length)) + 1;\n let used = skeleton(0) + tail;\n keep = 0;\n while (keep < items.length && used + floors[keep] + 1 <= maxChars) {\n used += floors[keep] + 1;\n keep++;\n }\n }\n\n const kept = items.slice(0, keep);\n const dropped = items.length - keep;\n const tail = dropped > 0 ? size(marker(dropped)) + (keep > 0 ? 1 : 0) : 0;\n const allocation = allocate(kept, maxChars - skeleton(keep) - tail);\n const out = kept.map((item, i) => shrink(item, allocation[i]));\n if (dropped > 0 && size([...out, marker(dropped)]) <= maxChars) {\n out.push(marker(dropped));\n }\n return out;\n}\n\nfunction shrinkObject(\n value: { [key: string]: Json },\n maxChars: number\n): { [key: string]: Json } {\n const entries = Object.entries(value);\n // The marker entry must not shadow a real key.\n let markerKey = TRUNCATION_MARKER;\n while (markerKey in value) markerKey += \" \";\n const keyCost = (key: string) => size(key) + 1;\n const floors = entries.map(([k, v]) => keyCost(k) + floorSize(v, maxChars));\n const floorOf = (chars: number) =>\n Math.min(chars, MIN_SLOT, Math.max(2, Math.floor(maxChars / 2)));\n\n // Drop the largest values first, only until the remaining floors fit. Costs\n // are tracked incrementally so a wide object stays linear in its key count;\n // the marker note's cost is derived arithmetically from the omitted names.\n const byValueSize = entries\n .map((_, i) => i)\n .sort((a, b) => size(entries[b][1]) - size(entries[a][1]));\n const dropped = new Set<number>();\n let present = entries.length;\n let floorsSum = floors.reduce((n, f) => n + f, 0);\n let namesLength = 0;\n const noteLength = () =>\n `${dropped.size.toLocaleString()} keys omitted: `.length +\n namesLength +\n 2 * (dropped.size - 1);\n const cost = () => {\n const marker =\n dropped.size > 0 ? keyCost(markerKey) + floorOf(noteLength() + 2) : 0;\n const count = present + (dropped.size > 0 ? 1 : 0);\n return 2 + Math.max(0, count - 1) + floorsSum + marker;\n };\n for (const i of byValueSize) {\n if (cost() <= maxChars) break;\n dropped.add(i);\n present--;\n floorsSum -= floors[i];\n namesLength += size(entries[i][0]) - 2;\n }\n\n const kept = entries.filter((_, i) => !dropped.has(i));\n const omitted = [...dropped].sort((a, b) => a - b).map((i) => entries[i][0]);\n const note = `${omitted.length.toLocaleString()} keys omitted: ${omitted.join(\", \")}`;\n if (cost() > maxChars) {\n // Not even the marker fits at its floor: keep as much of it as there is\n // room for, or nothing.\n const room = maxChars - 2 - keyCost(markerKey);\n return room >= 2 ? { [markerKey]: shrink(note, room) } : {};\n }\n const all: [string, Json][] = [...kept];\n if (omitted.length > 0) all.push([markerKey, note]);\n const fixed =\n 2 + Math.max(0, all.length - 1) + all.reduce((n, [k]) => n + keyCost(k), 0);\n // The note is shrunk like any other value, so it can never overshoot.\n const allocation = allocate(\n all.map(([, v]) => v),\n maxChars - fixed\n );\n const out: { [key: string]: Json } = {};\n all.forEach(([k, v], i) => {\n out[k] = shrink(v, allocation[i]);\n });\n return out;\n}\n","/**\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 { DEFAULT_MAX_RESULT_BYTES } from \"./session\";\nimport { truncateResult } from \"./truncate\";\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\n/** What `Page.captureScreenshot` can produce. */\nconst SCREENSHOT_MEDIA_TYPES = new Set([\n \"image/png\",\n \"image/jpeg\",\n \"image/webp\"\n]);\nconst BASE64 = /^[A-Za-z0-9+/]*={0,2}$/;\n\n/**\n * The screenshot the model's code returned, or `null` if it didn't return\n * one. The model writes this shape itself, so only an image type, base64\n * data, and the session's size limit count: anything else is treated as a\n * plain result and cut down like one, rather than kept whole or sent to the\n * model as an image.\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 !SCREENSHOT_MEDIA_TYPES.has(result.mediaType) ||\n result.data.length > DEFAULT_MAX_RESULT_BYTES ||\n !BASE64.test(result.data)\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`, the durable audit log `createBrowserTools` adds, stays on the\n // persisted part and never enters the model's context, and the sandbox\n // `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":";;;;;;;;;;;;;;;;;AAcA,MAAM,kBAAkB;AACxB,MAAM,qBAAqB;AAC3B,MAAM,oBAAoB;;;;;;AAM1B,MAAM,WAAW;AAYjB,SAAS,OAAO,SAGd;CACA,MAAM,YAAY,SAAS,aAAa;CAExC,OAAO;EAAE,UADQ,S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AAE,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
+ {"version":3,"file":"tool-helpers-F3_Wy2YX.js","names":["agentContext"],"sources":["../src/browser/truncate.ts","../src/browser/tool-helpers.ts"],"sourcesContent":["/**\n * Result truncation for the browser tools, copied from\n * `@cloudflare/codemode`'s `truncateResult` so `agents/browser` doesn't need\n * codemode. Internal — not an entry point.\n *\n * Structured values are truncated structurally: the output is always valid\n * JSON of the same shape, with the largest values cut first. A truncated\n * string ends with a marker, a truncated array ends with a marker element\n * counting the dropped items, and an object that had to lose entries carries a\n * marker entry naming the omitted keys. Every marker contains\n * `--- TRUNCATED ---` so callers and models can find them.\n */\n\n/** ~4 characters per token is a reasonable cross-model estimate. */\nconst CHARS_PER_TOKEN = 4;\nconst DEFAULT_MAX_TOKENS = 6000;\nconst TRUNCATION_MARKER = \"--- TRUNCATED ---\";\n/**\n * The least a string or container is worth keeping at (see `floorSize`). A\n * value that would get fewer serialized characters than this is dropped in\n * favour of its siblings rather than reduced to a bare marker.\n */\nconst MIN_SLOT = 128;\n\ntype TruncateOptions = {\n /**\n * Maximum characters in the (serialized) output before truncation kicks in.\n * Defaults to `maxTokens * 4`.\n */\n maxChars?: number;\n /** Token budget used to derive the default `maxChars`. Defaults to 6000. */\n maxTokens?: number;\n};\n\nfunction budget(options?: TruncateOptions): {\n maxChars: number;\n maxTokens: number;\n} {\n const maxTokens = options?.maxTokens ?? DEFAULT_MAX_TOKENS;\n const maxChars = options?.maxChars ?? maxTokens * CHARS_PER_TOKEN;\n return { maxChars, maxTokens };\n}\n\n/**\n * Truncate a text response to a character budget, appending a marker that notes\n * the original size so the model knows the output was clipped. Returns the\n * input unchanged when it is within budget.\n */\nfunction truncateResponse(text: string, options?: TruncateOptions): string {\n const { maxChars, maxTokens } = budget(options);\n if (text.length <= maxChars) return text;\n\n const estimatedTokens = Math.ceil(text.length / CHARS_PER_TOKEN);\n return (\n text.slice(0, maxChars) +\n `\\n\\n${TRUNCATION_MARKER}\\nResponse was ~${estimatedTokens.toLocaleString()} tokens ` +\n `(limit: ${maxTokens.toLocaleString()}). Narrow the request to reduce response size.`\n );\n}\n\n/**\n * Truncate a structured result. Strings are truncated directly. Other values\n * pass through unchanged (same reference) when their JSON serialization is\n * within budget. When oversized, the value is shrunk structurally — largest\n * values first, deepest last — so the model gets a bounded value that is still\n * valid JSON of the original shape, with markers where content was cut.\n *\n * Values that can't be serialized (cycles, bigint, `undefined`) are returned\n * unchanged.\n */\nexport function truncateResult(\n value: unknown,\n options?: TruncateOptions\n): unknown {\n if (typeof value === \"string\") return truncateResponse(value, options);\n\n let serialized: string | undefined;\n try {\n serialized = JSON.stringify(value);\n } catch {\n return value;\n }\n if (serialized === undefined) return value;\n\n const { maxChars } = budget(options);\n if (serialized.length <= maxChars) return value;\n\n // Re-parse so `toJSON`, class instances and `undefined` members are seen in\n // their serialized form — the shape the model would receive anyway.\n const shrunk = shrink(JSON.parse(serialized) as Json, maxChars);\n // `shrink` honours its budget for anything a container can hold; only a\n // scalar (a number too long for the budget) can still miss it.\n return size(shrunk) <= maxChars\n ? shrunk\n : truncateResponse(serialized, options);\n}\n\n// ---------------------------------------------------------------------------\n// Structural shrinking\n// ---------------------------------------------------------------------------\n//\n// Every `shrink*` below returns a value whose compact serialization fits the\n// budget it was given, provided the budget can hold an empty container (2\n// chars). Containers share their budget by water-filling: each child is owed\n// at least its floor (`floorSize`), small children keep their full size, and\n// the largest children absorb the cut. A container only drops children when\n// even their floors cannot fit — arrays drop from the tail (order carries\n// meaning), objects drop their largest values first (keys are all meaningful).\n\ntype Json = string | number | boolean | null | Json[] | { [key: string]: Json };\n\n/** Serialized size in characters (compact JSON). */\nfunction size(value: Json): number {\n return JSON.stringify(value).length;\n}\n\n/** Only strings and containers can give up characters; scalars are atomic. */\nfunction shrinkable(value: Json): boolean {\n return typeof value === \"string\" || (typeof value === \"object\" && !!value);\n}\n\n/**\n * The least budget a value is kept at; a scalar must fit whole. The floor\n * never exceeds half the container's own budget, so tiny budgets still keep\n * something rather than nothing.\n */\nfunction floorSize(value: Json, maxChars: number): number {\n const full = size(value);\n return shrinkable(value)\n ? Math.min(full, MIN_SLOT, Math.max(2, Math.floor(maxChars / 2)))\n : full;\n}\n\nfunction shrink(value: Json, maxChars: number): Json {\n if (size(value) <= maxChars) return value;\n if (typeof value === \"string\") return shrinkString(value, maxChars);\n if (Array.isArray(value)) return shrinkArray(value, maxChars);\n if (typeof value === \"object\" && value !== null) {\n return shrinkObject(value, maxChars);\n }\n return value;\n}\n\nfunction shrinkString(value: string, maxChars: number): string {\n const suffix = ` ${TRUNCATION_MARKER} ${value.length.toLocaleString()} chars`;\n let keep = Math.max(0, maxChars - suffix.length - 2);\n let out = value.slice(0, keep) + suffix;\n // Escapes inflate the serialized form; back off until it fits.\n while (keep > 0 && size(out) > maxChars) {\n keep = Math.max(0, keep - (size(out) - maxChars));\n out = value.slice(0, keep) + suffix;\n }\n // No room for a prefix and the size note: keep as much of the marker as fits.\n return size(out) <= maxChars\n ? out\n : TRUNCATION_MARKER.slice(0, Math.max(0, maxChars - 2));\n}\n\n/**\n * Share `available` characters across values by water-filling: values are\n * admitted smallest first, each taking the lesser of its full size and an\n * equal share of what is left. Requires `available >= Σ floorSize(values)`;\n * then every value receives at least its floor.\n */\nfunction allocate(values: Json[], available: number): number[] {\n const sizes = values.map(size);\n const order = sizes.map((_, i) => i).sort((a, b) => sizes[a] - sizes[b]);\n const allocation = new Array<number>(values.length);\n let remaining = available;\n let count = values.length;\n for (const i of order) {\n const alloc = Math.min(sizes[i], Math.floor(remaining / count));\n allocation[i] = alloc;\n remaining -= alloc;\n count--;\n }\n return allocation;\n}\n\nfunction shrinkArray(items: Json[], maxChars: number): Json[] {\n const marker = (dropped: number) =>\n `${TRUNCATION_MARKER} ${dropped.toLocaleString()} more items`;\n const floors = items.map((item) => floorSize(item, maxChars));\n const skeleton = (count: number) => 2 + Math.max(0, count - 1);\n\n // Keep everything when every floor fits.\n let keep = items.length;\n if (floors.reduce((n, f) => n + f, 0) + skeleton(keep) > maxChars) {\n // Otherwise keep the longest prefix whose floors fit beside a tail marker\n // (sized for the largest possible count, so the real one always fits).\n const tail = size(marker(items.length)) + 1;\n let used = skeleton(0) + tail;\n keep = 0;\n while (keep < items.length && used + floors[keep] + 1 <= maxChars) {\n used += floors[keep] + 1;\n keep++;\n }\n }\n\n const kept = items.slice(0, keep);\n const dropped = items.length - keep;\n const tail = dropped > 0 ? size(marker(dropped)) + (keep > 0 ? 1 : 0) : 0;\n const allocation = allocate(kept, maxChars - skeleton(keep) - tail);\n const out = kept.map((item, i) => shrink(item, allocation[i]));\n if (dropped > 0 && size([...out, marker(dropped)]) <= maxChars) {\n out.push(marker(dropped));\n }\n return out;\n}\n\nfunction shrinkObject(\n value: { [key: string]: Json },\n maxChars: number\n): { [key: string]: Json } {\n const entries = Object.entries(value);\n // The marker entry must not shadow a real key.\n let markerKey = TRUNCATION_MARKER;\n while (markerKey in value) markerKey += \" \";\n const keyCost = (key: string) => size(key) + 1;\n const floors = entries.map(([k, v]) => keyCost(k) + floorSize(v, maxChars));\n const floorOf = (chars: number) =>\n Math.min(chars, MIN_SLOT, Math.max(2, Math.floor(maxChars / 2)));\n\n // Drop the largest values first, only until the remaining floors fit. Costs\n // are tracked incrementally so a wide object stays linear in its key count;\n // the marker note's cost is derived arithmetically from the omitted names.\n const byValueSize = entries\n .map((_, i) => i)\n .sort((a, b) => size(entries[b][1]) - size(entries[a][1]));\n const dropped = new Set<number>();\n let present = entries.length;\n let floorsSum = floors.reduce((n, f) => n + f, 0);\n let namesLength = 0;\n const noteLength = () =>\n `${dropped.size.toLocaleString()} keys omitted: `.length +\n namesLength +\n 2 * (dropped.size - 1);\n const cost = () => {\n const marker =\n dropped.size > 0 ? keyCost(markerKey) + floorOf(noteLength() + 2) : 0;\n const count = present + (dropped.size > 0 ? 1 : 0);\n return 2 + Math.max(0, count - 1) + floorsSum + marker;\n };\n for (const i of byValueSize) {\n if (cost() <= maxChars) break;\n dropped.add(i);\n present--;\n floorsSum -= floors[i];\n namesLength += size(entries[i][0]) - 2;\n }\n\n const kept = entries.filter((_, i) => !dropped.has(i));\n const omitted = [...dropped].sort((a, b) => a - b).map((i) => entries[i][0]);\n const note = `${omitted.length.toLocaleString()} keys omitted: ${omitted.join(\", \")}`;\n if (cost() > maxChars) {\n // Not even the marker fits at its floor: keep as much of it as there is\n // room for, or nothing.\n const room = maxChars - 2 - keyCost(markerKey);\n return room >= 2 ? { [markerKey]: shrink(note, room) } : {};\n }\n const all: [string, Json][] = [...kept];\n if (omitted.length > 0) all.push([markerKey, note]);\n const fixed =\n 2 + Math.max(0, all.length - 1) + all.reduce((n, [k]) => n + keyCost(k), 0);\n // The note is shrunk like any other value, so it can never overshoot.\n const allocation = allocate(\n all.map(([, v]) => v),\n maxChars - fixed\n );\n const out: { [key: string]: Json } = {};\n all.forEach(([k, v], i) => {\n out[k] = shrink(v, allocation[i]);\n });\n return out;\n}\n","/**\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 { DEFAULT_MAX_RESULT_BYTES } from \"./session\";\nimport { truncateResult } from \"./truncate\";\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\n/** What `Page.captureScreenshot` can produce. */\nconst SCREENSHOT_MEDIA_TYPES = new Set([\n \"image/png\",\n \"image/jpeg\",\n \"image/webp\"\n]);\nconst BASE64 = /^[A-Za-z0-9+/]*={0,2}$/;\n\n/**\n * The screenshot the model's code returned, or `null` if it didn't return\n * one. The model writes this shape itself, so only an image type, base64\n * data, and the session's size limit count: anything else is treated as a\n * plain result and cut down like one, rather than kept whole or sent to the\n * model as an image.\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 !SCREENSHOT_MEDIA_TYPES.has(result.mediaType) ||\n result.data.length > DEFAULT_MAX_RESULT_BYTES ||\n !BASE64.test(result.data)\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`, the durable audit log `createBrowserTools` adds, stays on the\n // persisted part and never enters the model's context, and the sandbox\n // `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":";;;;;;;;;;;;;;;;;AAcA,MAAM,kBAAkB;AACxB,MAAM,qBAAqB;AAC3B,MAAM,oBAAoB;;;;;;AAM1B,MAAM,WAAW;AAYjB,SAAS,OAAO,SAGd;CACA,MAAM,YAAY,SAAS,aAAa;CAExC,OAAO;EAAE,UADQ,SAAS,YAAY,YAAY;EAC/B;CAAU;AAC/B;;;;;;AAOA,SAAS,iBAAiB,MAAc,SAAmC;CACzE,MAAM,EAAE,UAAU,cAAc,OAAO,OAAO;CAC9C,IAAI,KAAK,UAAU,UAAU,OAAO;CAEpC,MAAM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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,5 +1,5 @@
1
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";
2
+ import { t as webFetchInputSchema } from "../../../input-schema-0uUu392-.js";
3
3
  //#region src/web/fetch/tools/ai-sdk.ts
4
4
  /**
5
5
  * Create an AI SDK tool that reads a URL as Markdown, JSON, or text. The
@@ -10,17 +10,14 @@ import {
10
10
  x as WebFetchToolOutput,
11
11
  y as WebFetchPage
12
12
  } from "../../../tool-DoVberpN.js";
13
- import { Type } from "@earendil-works/pi-ai";
14
13
  import { ToolRegistration } from "@earendil-works/pi-durable";
15
14
 
16
15
  //#region src/web/fetch/tools/pi.d.ts
17
16
  /** 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
- >;
17
+ declare function webFetchParameters(): import("@earendil-works/pi-schema").Schema<{
18
+ url: string;
19
+ offset?: number | undefined;
20
+ format?: "auto" | "raw" | undefined;
24
21
  }>;
25
22
  type WebFetchParameters = ReturnType<typeof webFetchParameters>;
26
23
  /**
@@ -1,5 +1,6 @@
1
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";
2
+ import { int, obj, opt, str } from "@earendil-works/pi-schema";
3
+ import { StringEnum } from "@earendil-works/pi-ai";
3
4
  //#region src/web/fetch/tools/pi.ts
4
5
  /**
5
6
  * `agents/webfetch/pi` — the `web_fetch` tool for the pi harness.
@@ -8,18 +9,18 @@ import { Type } from "@earendil-works/pi-ai";
8
9
  */
9
10
  /** The model's input schema. pi already coerces `"20000"` to `20000`. */
10
11
  function webFetchParameters() {
11
- return Type.Object({
12
- url: Type.String({
12
+ return obj({
13
+ url: str({
13
14
  minLength: 1,
14
15
  maxLength: MAX_WEB_FETCH_URL_LENGTH,
15
16
  description: "The http(s) URL to read."
16
17
  }),
17
- offset: Type.Optional(Type.Integer({
18
+ offset: opt(int({
18
19
  minimum: 0,
19
20
  description: "Character offset into the content, to continue a long page from the previous result's offset. Default 0."
20
21
  })),
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
- });
22
+ format: opt(StringEnum(["auto", "raw"], { description: "\"auto\" (default) converts to the most readable form; \"raw\" returns the body as served." }))
23
+ }, { open: true });
23
24
  }
24
25
  /**
25
26
  * Create a pi tool that reads a URL as Markdown, JSON, or text. Install it
@@ -1 +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, Harness } from \"@earendil-works/pi-durable\";\n * import { webFetchTool } from \"agents/webfetch/pi\";\n *\n * // In PiHarness's factory, so each object gets its own registry.\n * harness: ({ storage, context, onWake }) => {\n * const registry = createRegistry();\n * registry.install({\n * name: \"tools\",\n * tools: [webFetchTool({ binding: this.env.AI })]\n * });\n * return Harness.open(storage, { models, registry, onWake }, context);\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 output: [{ 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 output: [{ 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;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,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,QAAQ,CAAC;KAAE,MAAM;KAAQ,MAAM,IAAI;IAAK,CAAC;IACzC,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,QAAQ,CAAC;KAAE,MAAM;KAAQ,MAAM,IAAI;IAAK,CAAC;IACzC,SAAS;IACT;GACF;EACF;CACF;AACF"}
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 { StringEnum } from \"@earendil-works/pi-ai\";\nimport type { ToolRegistration } from \"@earendil-works/pi-durable\";\nimport { int, obj, opt, str } from \"@earendil-works/pi-schema\";\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 obj(\n {\n url: str({\n minLength: 1,\n maxLength: MAX_WEB_FETCH_URL_LENGTH,\n description: \"The http(s) URL to read.\"\n }),\n offset: opt(\n int({\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: opt(\n StringEnum([\"auto\", \"raw\"] as const, {\n description:\n '\"auto\" (default) converts to the most readable form; \"raw\" returns the body as served.'\n })\n )\n },\n { open: true }\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, Harness } from \"@earendil-works/pi-durable\";\n * import { webFetchTool } from \"agents/webfetch/pi\";\n *\n * // In PiHarness's factory, so each object gets its own registry.\n * harness: ({ storage, context, onWake }) => {\n * const registry = createRegistry();\n * registry.install({\n * name: \"tools\",\n * tools: [webFetchTool({ binding: this.env.AI })]\n * });\n * return Harness.open(storage, { models, registry, onWake }, context);\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 output: [{ 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 output: [{ type: \"text\", text: run.text }],\n isError: true,\n details\n };\n }\n };\n}\n"],"mappings":";;;;;;;;;;AA4BA,SAAS,qBAAqB;CAC5B,OAAO,IACL;EACE,KAAK,IAAI;GACP,WAAW;GACX,WAAW;GACX,aAAa;EACf,CAAC;EACD,QAAQ,IACN,IAAI;GACF,SAAS;GACT,aACE;EACJ,CAAC,CACH;EACA,QAAQ,IACN,WAAW,CAAC,QAAQ,KAAK,GAAY,EACnC,aACE,6FACJ,CAAC,CACH;CACF,GACA,EAAE,MAAM,KAAK,CACf;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,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,QAAQ,CAAC;KAAE,MAAM;KAAQ,MAAM,IAAI;IAAK,CAAC;IACzC,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,QAAQ,CAAC;KAAE,MAAM;KAAQ,MAAM,IAAI;IAAK,CAAC;IACzC,SAAS;IACT;GACF;EACF;CACF;AACF"}
@@ -1,5 +1,5 @@
1
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";
2
+ import { t as webFetchInputSchema } from "../../../input-schema-0uUu392-.js";
3
3
  import { toolDefinition } from "@tanstack/ai";
4
4
  //#region src/web/fetch/tools/tanstack-ai.ts
5
5
  /**
@@ -1,5 +1,5 @@
1
1
  import { i as WebSearchError, n as createWebSearchToolCore, r as toolFailure } from "../../../tool-DkT_DJBm.js";
2
- import { t as webSearchInputSchema } from "../../../input-schema-B0Etuo-o.js";
2
+ import { t as webSearchInputSchema } from "../../../input-schema-waggtYrH.js";
3
3
  //#region src/web/search/tools/ai-sdk.ts
4
4
  /**
5
5
  * Create an AI SDK tool that searches the web through Cloudflare's Web
@@ -9,7 +9,6 @@ import {
9
9
  r as WebSearchToolOptions,
10
10
  w as WebSearchResult
11
11
  } from "../../../tool-CTp72Jb_.js";
12
- import { Type } from "@earendil-works/pi-ai";
13
12
  import { ToolRegistration } from "@earendil-works/pi-durable";
14
13
 
15
14
  //#region src/web/search/tools/pi.d.ts
@@ -18,9 +17,11 @@ import { ToolRegistration } from "@earendil-works/pi-durable";
18
17
  * `limit`; a larger value is not rejected (which would cost a validation
19
18
  * round trip) but capped by the core. pi already coerces `"5"` to `5`.
20
19
  */
21
- declare function webSearchParameters(maxLimit: number): Type.TObject<{
22
- query: Type.TString;
23
- limit: Type.TOptional<Type.TInteger>;
20
+ declare function webSearchParameters(
21
+ maxLimit: number
22
+ ): import("@earendil-works/pi-schema").Schema<{
23
+ query: string;
24
+ limit?: number | undefined;
24
25
  }>;
25
26
  type WebSearchParameters = ReturnType<typeof webSearchParameters>;
26
27
  /**
@@ -1,28 +1,23 @@
1
1
  import { i as WebSearchError, n as createWebSearchToolCore, u as MAX_WEB_SEARCH_QUERY_LENGTH } from "../../../tool-DkT_DJBm.js";
2
- import { Type } from "@earendil-works/pi-ai";
2
+ import { int, obj, opt, str } from "@earendil-works/pi-schema";
3
3
  //#region src/web/search/tools/pi.ts
4
4
  /**
5
- * `agents/websearch/pi` — the `web_search` tool for the pi harness.
6
- *
7
- * @beta
8
- */
9
- /**
10
5
  * The model's input schema. The description tells the model the host's
11
6
  * `limit`; a larger value is not rejected (which would cost a validation
12
7
  * round trip) but capped by the core. pi already coerces `"5"` to `5`.
13
8
  */
14
9
  function webSearchParameters(maxLimit) {
15
- return Type.Object({
16
- query: Type.String({
10
+ return obj({
11
+ query: str({
17
12
  minLength: 1,
18
13
  maxLength: MAX_WEB_SEARCH_QUERY_LENGTH,
19
14
  description: "What to search for."
20
15
  }),
21
- limit: Type.Optional(Type.Integer({
16
+ limit: opt(int({
22
17
  minimum: 1,
23
18
  description: `How many results to return (at most ${maxLimit}).`
24
19
  }))
25
- });
20
+ }, { open: true });
26
21
  }
27
22
  /**
28
23
  * Create a pi tool that searches the web through Cloudflare's Web Search
@@ -1 +1 @@
1
- {"version":3,"file":"pi.js","names":[],"sources":["../../../../src/web/search/tools/pi.ts"],"sourcesContent":["/**\n * `agents/websearch/pi` — the `web_search` 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 {\n MAX_WEB_SEARCH_QUERY_LENGTH,\n type WebSearchToolOutput\n} from \"../contract\";\nimport type { WebSearchErrorCode } from \"../source\";\nimport { createWebSearchToolCore, type WebSearchToolOptions } from \"../tool\";\n\nexport type {\n WebSearchResponse,\n WebSearchResult,\n WebSearchToolInput,\n WebSearchToolOutput\n} from \"../contract\";\nexport {\n WebSearchError,\n type WebSearchErrorCode,\n type WebSearchProvider,\n type WebSearchSource\n} from \"../source\";\nexport type { WebSearchToolOptions } from \"../tool\";\n\n/**\n * The model's input schema. The description tells the model the host's\n * `limit`; a larger value is not rejected (which would cost a validation\n * round trip) but capped by the core. pi already coerces `\"5\"` to `5`.\n */\nfunction webSearchParameters(maxLimit: number) {\n return Type.Object({\n query: Type.String({\n minLength: 1,\n maxLength: MAX_WEB_SEARCH_QUERY_LENGTH,\n description: \"What to search for.\"\n }),\n limit: Type.Optional(\n Type.Integer({\n minimum: 1,\n description: `How many results to return (at most ${maxLimit}).`\n })\n )\n });\n}\n\ntype WebSearchParameters = ReturnType<typeof webSearchParameters>;\n\n/**\n * Host-side details pi stores with each `web_search` result: the full API\n * response (untrimmed descriptions, provider metadata) or the failure.\n */\nexport type WebSearchToolDetails =\n | { ok: true; output: WebSearchToolOutput }\n | {\n ok: false;\n /** The source's error message, with the API's detail. */\n message: string;\n status: number;\n code: WebSearchErrorCode;\n retryable: boolean;\n requestId?: string;\n };\n\n/**\n * Create a pi tool that searches the web through Cloudflare's Web Search\n * API. Install it on a registry like any other pi tool.\n *\n * The model chooses the query and (within the host's `limit`) how many\n * results; the host chooses the gateway, provider, and billing. The tool is\n * `replay: \"safe\"`: a search interrupted mid-call (say, by an eviction) runs\n * again when the session recovers, which is a second billed search.\n * Completed results are stored and not searched again.\n *\n * @example\n * ```ts\n * import { createRegistry, Harness } from \"@earendil-works/pi-durable\";\n * import { webSearchTool } from \"agents/websearch/pi\";\n *\n * // In PiHarness's factory, so each object gets its own registry.\n * harness: ({ storage, context, onWake }) => {\n * const registry = createRegistry();\n * registry.install({\n * name: \"tools\",\n * tools: [webSearchTool({ binding: this.env.AI, provider: \"exa\" })]\n * });\n * return Harness.open(storage, { models, registry, onWake }, context);\n * }\n * ```\n */\nexport function webSearchTool(\n options: WebSearchToolOptions\n): ToolRegistration<WebSearchParameters, WebSearchToolDetails> {\n const core = createWebSearchToolCore(options);\n return {\n name: core.name,\n description: core.description,\n parameters: webSearchParameters(core.limit),\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 output: [{ type: \"text\", text: run.text }],\n details: { ok: true, output: run.output }\n };\n }\n return {\n output: [{ type: \"text\", text: run.text }],\n isError: true,\n details: {\n ok: false,\n message: run.error.message,\n status: run.error.status,\n code: run.error.code,\n retryable: run.error.retryable,\n requestId: run.error.requestId\n }\n };\n }\n };\n}\n"],"mappings":";;;;;;;;;;;;;AAiCA,SAAS,oBAAoB,UAAkB;CAC7C,OAAO,KAAK,OAAO;EACjB,OAAO,KAAK,OAAO;GACjB,WAAW;GACX,WAAW;GACX,aAAa;EACf,CAAC;EACD,OAAO,KAAK,SACV,KAAK,QAAQ;GACX,SAAS;GACT,aAAa,uCAAuC,SAAS;EAC/D,CAAC,CACH;CACF,CAAC;AACH;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,SAAgB,cACd,SAC6D;CAC7D,MAAM,OAAO,wBAAwB,OAAO;CAC5C,OAAO;EACL,MAAM,KAAK;EACX,aAAa,KAAK;EAClB,YAAY,oBAAoB,KAAK,KAAK;EAC1C,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,QAAQ,CAAC;KAAE,MAAM;KAAQ,MAAM,IAAI;IAAK,CAAC;IACzC,SAAS;KAAE,IAAI;KAAM,QAAQ,IAAI;IAAO;GAC1C;GAEF,OAAO;IACL,QAAQ,CAAC;KAAE,MAAM;KAAQ,MAAM,IAAI;IAAK,CAAC;IACzC,SAAS;IACT,SAAS;KACP,IAAI;KACJ,SAAS,IAAI,MAAM;KACnB,QAAQ,IAAI,MAAM;KAClB,MAAM,IAAI,MAAM;KAChB,WAAW,IAAI,MAAM;KACrB,WAAW,IAAI,MAAM;IACvB;GACF;EACF;CACF;AACF"}
1
+ {"version":3,"file":"pi.js","names":[],"sources":["../../../../src/web/search/tools/pi.ts"],"sourcesContent":["/**\n * `agents/websearch/pi` — the `web_search` tool for the pi harness.\n *\n * @beta\n */\nimport type { ToolRegistration } from \"@earendil-works/pi-durable\";\nimport { int, obj, opt, str } from \"@earendil-works/pi-schema\";\nimport {\n MAX_WEB_SEARCH_QUERY_LENGTH,\n type WebSearchToolOutput\n} from \"../contract\";\nimport type { WebSearchErrorCode } from \"../source\";\nimport { createWebSearchToolCore, type WebSearchToolOptions } from \"../tool\";\n\nexport type {\n WebSearchResponse,\n WebSearchResult,\n WebSearchToolInput,\n WebSearchToolOutput\n} from \"../contract\";\nexport {\n WebSearchError,\n type WebSearchErrorCode,\n type WebSearchProvider,\n type WebSearchSource\n} from \"../source\";\nexport type { WebSearchToolOptions } from \"../tool\";\n\n/**\n * The model's input schema. The description tells the model the host's\n * `limit`; a larger value is not rejected (which would cost a validation\n * round trip) but capped by the core. pi already coerces `\"5\"` to `5`.\n */\nfunction webSearchParameters(maxLimit: number) {\n return obj(\n {\n query: str({\n minLength: 1,\n maxLength: MAX_WEB_SEARCH_QUERY_LENGTH,\n description: \"What to search for.\"\n }),\n limit: opt(\n int({\n minimum: 1,\n description: `How many results to return (at most ${maxLimit}).`\n })\n )\n },\n { open: true }\n );\n}\n\ntype WebSearchParameters = ReturnType<typeof webSearchParameters>;\n\n/**\n * Host-side details pi stores with each `web_search` result: the full API\n * response (untrimmed descriptions, provider metadata) or the failure.\n */\nexport type WebSearchToolDetails =\n | { ok: true; output: WebSearchToolOutput }\n | {\n ok: false;\n /** The source's error message, with the API's detail. */\n message: string;\n status: number;\n code: WebSearchErrorCode;\n retryable: boolean;\n requestId?: string;\n };\n\n/**\n * Create a pi tool that searches the web through Cloudflare's Web Search\n * API. Install it on a registry like any other pi tool.\n *\n * The model chooses the query and (within the host's `limit`) how many\n * results; the host chooses the gateway, provider, and billing. The tool is\n * `replay: \"safe\"`: a search interrupted mid-call (say, by an eviction) runs\n * again when the session recovers, which is a second billed search.\n * Completed results are stored and not searched again.\n *\n * @example\n * ```ts\n * import { createRegistry, Harness } from \"@earendil-works/pi-durable\";\n * import { webSearchTool } from \"agents/websearch/pi\";\n *\n * // In PiHarness's factory, so each object gets its own registry.\n * harness: ({ storage, context, onWake }) => {\n * const registry = createRegistry();\n * registry.install({\n * name: \"tools\",\n * tools: [webSearchTool({ binding: this.env.AI, provider: \"exa\" })]\n * });\n * return Harness.open(storage, { models, registry, onWake }, context);\n * }\n * ```\n */\nexport function webSearchTool(\n options: WebSearchToolOptions\n): ToolRegistration<WebSearchParameters, WebSearchToolDetails> {\n const core = createWebSearchToolCore(options);\n return {\n name: core.name,\n description: core.description,\n parameters: webSearchParameters(core.limit),\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 output: [{ type: \"text\", text: run.text }],\n details: { ok: true, output: run.output }\n };\n }\n return {\n output: [{ type: \"text\", text: run.text }],\n isError: true,\n details: {\n ok: false,\n message: run.error.message,\n status: run.error.status,\n code: run.error.code,\n retryable: run.error.retryable,\n requestId: run.error.requestId\n }\n };\n }\n };\n}\n"],"mappings":";;;;;;;;AAiCA,SAAS,oBAAoB,UAAkB;CAC7C,OAAO,IACL;EACE,OAAO,IAAI;GACT,WAAW;GACX,WAAW;GACX,aAAa;EACf,CAAC;EACD,OAAO,IACL,IAAI;GACF,SAAS;GACT,aAAa,uCAAuC,SAAS;EAC/D,CAAC,CACH;CACF,GACA,EAAE,MAAM,KAAK,CACf;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,SAAgB,cACd,SAC6D;CAC7D,MAAM,OAAO,wBAAwB,OAAO;CAC5C,OAAO;EACL,MAAM,KAAK;EACX,aAAa,KAAK;EAClB,YAAY,oBAAoB,KAAK,KAAK;EAC1C,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,QAAQ,CAAC;KAAE,MAAM;KAAQ,MAAM,IAAI;IAAK,CAAC;IACzC,SAAS;KAAE,IAAI;KAAM,QAAQ,IAAI;IAAO;GAC1C;GAEF,OAAO;IACL,QAAQ,CAAC;KAAE,MAAM;KAAQ,MAAM,IAAI;IAAK,CAAC;IACzC,SAAS;IACT,SAAS;KACP,IAAI;KACJ,SAAS,IAAI,MAAM;KACnB,QAAQ,IAAI,MAAM;KAClB,MAAM,IAAI,MAAM;KAChB,WAAW,IAAI,MAAM;KACrB,WAAW,IAAI,MAAM;IACvB;GACF;EACF;CACF;AACF"}
@@ -1,5 +1,5 @@
1
1
  import { i as WebSearchError, n as createWebSearchToolCore, r as toolFailure } from "../../../tool-DkT_DJBm.js";
2
- import { t as webSearchInputSchema } from "../../../input-schema-B0Etuo-o.js";
2
+ import { t as webSearchInputSchema } from "../../../input-schema-waggtYrH.js";
3
3
  import { toolDefinition } from "@tanstack/ai";
4
4
  //#region src/web/search/tools/tanstack-ai.ts
5
5
  /**