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,360 @@
1
+ import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldSet2, t as _classPrivateFieldGet2 } from "./classPrivateFieldGet2-DZBYAB34.js";
2
+ import { n as BrowserSession, o as browserFunctionDocs } from "./session-CRY0bGiI.js";
3
+ import { a as truncateResult, i as transformBrowserResult } from "./tool-helpers-F3_Wy2YX.js";
4
+ import { RpcTarget } from "cloudflare:workers";
5
+ //#region src/browser/sandbox.ts
6
+ /**
7
+ * Runs model-written JavaScript in a Dynamic Worker, with a `browser`
8
+ * object whose functions run on the host. Used by `browserTool`.
9
+ * Internal — not an entry point.
10
+ *
11
+ * The Worker has no network access (`globalOutbound: null`) and no bindings:
12
+ * the only way out is `browser`, whose calls go back to the host over RPC.
13
+ */
14
+ /**
15
+ * Code run as a function body returns nothing unless it says `return`. Tell
16
+ * the model, rather than parse the code to return its last expression. A text
17
+ * search for `return` can't tell a real one from one inside a string, so any
18
+ * body run that comes back empty gets the notice.
19
+ */
20
+ const STATEMENTS_NOTICE = "Your code ran as statements and returned nothing. If you wanted a value, `return` it, or write an async arrow function.";
21
+ var _functions = /* @__PURE__ */ new WeakMap();
22
+ /**
23
+ * The host side of `browser`. A failed call resolves with `{ error }`
24
+ * instead of rejecting across RPC; the sandbox rethrows it as a local error
25
+ * the code can catch.
26
+ */
27
+ var HostFunctions = class extends RpcTarget {
28
+ constructor(functions) {
29
+ super();
30
+ _classPrivateFieldInitSpec(this, _functions, void 0);
31
+ _classPrivateFieldSet2(_functions, this, functions);
32
+ }
33
+ async call(name, input) {
34
+ const fn = Object.hasOwn(_classPrivateFieldGet2(_functions, this), name) ? _classPrivateFieldGet2(_functions, this)[name] : void 0;
35
+ if (!fn) return { error: `browser.${name} is not a function.` };
36
+ try {
37
+ return { value: await fn(input) };
38
+ } catch (error) {
39
+ return { error: error instanceof Error ? error.message : String(error) };
40
+ }
41
+ }
42
+ };
43
+ /** Console lines a run keeps, and the characters kept of each. */
44
+ const MAX_LOG_LINES = 100;
45
+ const MAX_LOG_LINE_CHARS = 2e3;
46
+ /**
47
+ * The entry module. `code.js` holds the model's code; keeping it in its own
48
+ * module keeps the harness's names out of its scope.
49
+ */
50
+ function mainModule(timeoutMs, names) {
51
+ return `import { WorkerEntrypoint } from "cloudflare:workers";
52
+ import run from "./code.js";
53
+
54
+ export default class BrowserCode extends WorkerEntrypoint {
55
+ async evaluate(binding) {
56
+ // Logs are kept in the tool's stored output, so bound them here.
57
+ const lines = [];
58
+ let dropped = 0;
59
+ const record = (prefix) => (...args) => {
60
+ if (lines.length >= ${MAX_LOG_LINES}) {
61
+ dropped++;
62
+ return;
63
+ }
64
+ const line = prefix + args.map(String).join(" ");
65
+ lines.push(
66
+ line.length > ${MAX_LOG_LINE_CHARS}
67
+ ? line.slice(0, ${MAX_LOG_LINE_CHARS}) + "…"
68
+ : line
69
+ );
70
+ };
71
+ const logs = () =>
72
+ dropped > 0 ? [...lines, "[" + dropped + " more lines dropped]"] : lines;
73
+ console.log = record("");
74
+ console.info = record("");
75
+ console.warn = record("[warn] ");
76
+ console.error = record("[error] ");
77
+ const call = async (method, input) => {
78
+ const reply = await binding.call(method, input);
79
+ if ("error" in reply) throw new Error(reply.error);
80
+ return reply.value;
81
+ };
82
+ const browser = Object.freeze({
83
+ ${names.map((name) => ` ${JSON.stringify(name)}: (input) => call(${JSON.stringify(name)}, input),`).join("\n")}
84
+ });
85
+ let timer;
86
+ const timeout = new Promise((_, reject) => {
87
+ timer = setTimeout(
88
+ () => reject(new Error("Execution timed out after ${timeoutMs}ms")),
89
+ ${timeoutMs}
90
+ );
91
+ });
92
+ try {
93
+ return {
94
+ result: await Promise.race([run(browser), timeout]),
95
+ logs: logs()
96
+ };
97
+ } catch (error) {
98
+ return {
99
+ error: error instanceof Error ? error.message : String(error),
100
+ logs: logs()
101
+ };
102
+ } finally {
103
+ clearTimeout(timer);
104
+ }
105
+ }
106
+ }
107
+ `;
108
+ }
109
+ /** Strip the markdown fences models often wrap code in. */
110
+ function stripFences(code) {
111
+ return code.trim().match(/^```(?:js|javascript|typescript|ts|tsx|jsx)?\s*\n([\s\S]*?)```\s*$/)?.[1] ?? code.trim();
112
+ }
113
+ /**
114
+ * The model's code as an expression: an async arrow function (what the tool
115
+ * asks for) is called, and any other expression is awaited.
116
+ */
117
+ function expressionModule(code) {
118
+ return `export default async function (browser) {
119
+ const value = (
120
+ ${code.replace(/^export\s+default\s+/, "").replace(/;\s*(\/\/[^\n"'`]*)?\s*$/, "")}
121
+ );
122
+ return typeof value === "function" ? await value() : await value;
123
+ }
124
+ `;
125
+ }
126
+ /** The model's code as a function body, for statements with a `return`. */
127
+ function bodyModule(code) {
128
+ return `export default async function (browser) {
129
+ ${code}
130
+ }
131
+ `;
132
+ }
133
+ /** The Worker failed to start because a module didn't parse. */
134
+ function isSyntaxError(error) {
135
+ return error instanceof Error && /SyntaxError/.test(error.message);
136
+ }
137
+ /**
138
+ * Run the model's code in a fresh Dynamic Worker, with `browser` bound to
139
+ * `functions`.
140
+ *
141
+ * The code is first loaded as an expression (an async arrow function, as
142
+ * the tool asks for). If that doesn't parse, it's loaded once more as a
143
+ * function body, so statements ending in `return` work too; statements
144
+ * with no `return` at all get a `notice`. Errors thrown
145
+ * by the code, including timeouts, come back as `{ error }`; this only
146
+ * rejects when the Worker can't run at all.
147
+ */
148
+ async function runBrowserCode(options) {
149
+ const code = stripFences(options.code);
150
+ if (code === "") return {
151
+ result: void 0,
152
+ logs: []
153
+ };
154
+ const binding = new HostFunctions(options.functions);
155
+ try {
156
+ return await evaluate(options, expressionModule(code), binding);
157
+ } catch (error) {
158
+ if (!isSyntaxError(error)) throw error;
159
+ }
160
+ let ran;
161
+ try {
162
+ ran = await evaluate(options, bodyModule(code), binding);
163
+ } catch (error) {
164
+ if (!isSyntaxError(error)) throw error;
165
+ return {
166
+ error: `Your code didn't parse: ${error.message}. Write an async arrow function, async () => { ... }.`,
167
+ logs: []
168
+ };
169
+ }
170
+ return "result" in ran && ran.result === void 0 ? {
171
+ ...ran,
172
+ notice: STATEMENTS_NOTICE
173
+ } : ran;
174
+ }
175
+ /**
176
+ * How long past `timeoutMs` the host waits before giving up on a run whose
177
+ * sandbox didn't time itself out. Capped at `timeoutMs` for short runs.
178
+ */
179
+ const HOST_TIMEOUT_GRACE_MS = 5e3;
180
+ async function evaluate(options, codeModule, binding) {
181
+ const worker = options.loader.load({
182
+ compatibilityDate: "2025-06-01",
183
+ mainModule: "main.js",
184
+ modules: {
185
+ "main.js": mainModule(options.timeoutMs, Object.keys(options.functions)),
186
+ "code.js": codeModule
187
+ },
188
+ globalOutbound: null
189
+ });
190
+ try {
191
+ const entrypoint = worker.getEntrypoint();
192
+ const running = entrypoint.evaluate(binding);
193
+ running.catch(() => {});
194
+ let timer;
195
+ const deadline = new Promise((resolve) => {
196
+ timer = setTimeout(() => resolve({
197
+ error: `Execution timed out after ${options.timeoutMs}ms`,
198
+ logs: []
199
+ }), options.timeoutMs + Math.min(HOST_TIMEOUT_GRACE_MS, options.timeoutMs));
200
+ });
201
+ const { signal } = options;
202
+ let onAbort;
203
+ const stopped = new Promise((resolve) => {
204
+ onAbort = () => resolve({
205
+ error: "The run was stopped before it finished.",
206
+ logs: []
207
+ });
208
+ if (signal?.aborted) onAbort();
209
+ else signal?.addEventListener("abort", onAbort, { once: true });
210
+ });
211
+ try {
212
+ return await Promise.race([
213
+ running,
214
+ deadline,
215
+ stopped
216
+ ]);
217
+ } finally {
218
+ if (onAbort) signal?.removeEventListener("abort", onAbort);
219
+ clearTimeout(timer);
220
+ disposeQuietly(entrypoint);
221
+ }
222
+ } finally {
223
+ disposeQuietly(worker);
224
+ }
225
+ }
226
+ function disposeQuietly(resource) {
227
+ if (typeof resource !== "object" || resource === null || !(Symbol.dispose in resource)) return;
228
+ const dispose = resource[Symbol.dispose];
229
+ if (typeof dispose !== "function") return;
230
+ try {
231
+ dispose.call(resource);
232
+ } catch {}
233
+ }
234
+ //#endregion
235
+ //#region src/browser/browser-tool.ts
236
+ /**
237
+ * The harness-neutral core of `browserTool`, shared by the adapters
238
+ * in `tools/` (`agents/browser/ai-sdk`, `agents/browser/tanstack-ai`,
239
+ * `agents/browser/pi`). Internal — not an entry point.
240
+ */
241
+ const DEFAULT_TIMEOUT_MS = 6e4;
242
+ /**
243
+ * The model's input schema, as a Standard Schema with a JSON Schema view,
244
+ * so the AI SDK and TanStack AI both accept it without zod.
245
+ */
246
+ const inputJsonSchema = {
247
+ type: "object",
248
+ properties: { code: {
249
+ type: "string",
250
+ description: "An async arrow function that drives the browser with `browser`"
251
+ } },
252
+ required: ["code"],
253
+ additionalProperties: false
254
+ };
255
+ const browserToolInputSchema = { "~standard": {
256
+ version: 1,
257
+ vendor: "agents",
258
+ types: void 0,
259
+ validate: (value) => typeof value === "object" && value !== null && "code" in value && typeof value.code === "string" ? { value: { code: value.code } } : { issues: [{ message: "Expected an object with a string code property" }] },
260
+ jsonSchema: {
261
+ input: (_options) => inputJsonSchema,
262
+ output: (_options) => inputJsonSchema
263
+ }
264
+ } };
265
+ /**
266
+ * Build the description and `execute` for one `browserTool`.
267
+ *
268
+ * Each run opens a session on the browser in its scope, runs the model's
269
+ * code in a fresh Dynamic Worker with `browser` bound to that session, closes
270
+ * the session, and adds its report's notices to the result. Runs in one
271
+ * scope lock it, since they drive one tab, so they wait for each other and
272
+ * for other locking sessions; runs in different scopes go in parallel.
273
+ */
274
+ function createBrowserToolCore(options, adapter) {
275
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
276
+ const docs = browserFunctionDocs(options.browser.internalHosts);
277
+ const rules = [
278
+ ...docs.rules,
279
+ "Results over about 24,000 characters are cut short.",
280
+ `Each run times out after ${Math.round(timeoutMs / 1e3)}s, so split long jobs (crawling a site, say) across runs.`,
281
+ adapter.screenshotHint,
282
+ "If your code doesn't parse, the line number in the error counts from wrapper code, not yours. Check regex literals and escapes."
283
+ ].map((rule) => `- ${rule}`).join("\n");
284
+ const description = [
285
+ "Run JavaScript that drives a persistent Chrome browser over the Chrome DevTools Protocol (CDP).",
286
+ "",
287
+ "Write an async arrow function, `async () => { ... }`, and return a small JSON value. Use the `browser` global to reach the browser. `fetch` is blocked and there is no file system or Node.js API.",
288
+ "",
289
+ "## browser",
290
+ "",
291
+ docs.functions,
292
+ "",
293
+ "## Rules",
294
+ "",
295
+ rules
296
+ ].join("\n");
297
+ const defaultScope = options.scope ?? "shared";
298
+ async function run(input, scope, signal) {
299
+ const session = new BrowserSession(options.browser, {
300
+ scope,
301
+ lock: true
302
+ });
303
+ try {
304
+ await session.lock({ signal });
305
+ } catch (error) {
306
+ await session.close();
307
+ throw error;
308
+ }
309
+ const executionId = crypto.randomUUID();
310
+ let output;
311
+ try {
312
+ const ran = await runBrowserCode({
313
+ loader: options.loader,
314
+ code: input.code,
315
+ functions: session.functions,
316
+ timeoutMs,
317
+ signal
318
+ });
319
+ const logs = ran.logs.length > 0 ? { logs: ran.logs } : {};
320
+ output = "error" in ran ? {
321
+ status: "error",
322
+ executionId,
323
+ error: truncateResult(ran.error),
324
+ ...logs
325
+ } : {
326
+ status: "completed",
327
+ executionId,
328
+ result: transformBrowserResult(ran.result),
329
+ ...logs,
330
+ ...ran.notice ? { notice: ran.notice } : {}
331
+ };
332
+ } catch (error) {
333
+ output = {
334
+ status: "error",
335
+ executionId,
336
+ error: error instanceof Error ? error.message : String(error)
337
+ };
338
+ }
339
+ const report = await session.close();
340
+ const notice = [output.notice, ...report?.notices ?? []].filter(Boolean).join(" ");
341
+ return {
342
+ ...output,
343
+ ...notice ? { notice } : {}
344
+ };
345
+ }
346
+ return {
347
+ description,
348
+ inputSchema: browserToolInputSchema,
349
+ /**
350
+ * Run `input` in `scope`, which defaults to the tool's `scope`. When
351
+ * `signal` aborts, a run still waiting for the lock rejects with its
352
+ * reason, and a running one stops with an error result.
353
+ */
354
+ execute: (input, call = {}) => run(input, call.scope ?? defaultScope, call.signal)
355
+ };
356
+ }
357
+ //#endregion
358
+ export { createBrowserToolCore as t };
359
+
360
+ //# sourceMappingURL=browser-tool-DOqT1oSD.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browser-tool-DOqT1oSD.js","names":[],"sources":["../src/browser/sandbox.ts","../src/browser/browser-tool.ts"],"sourcesContent":["/**\n * Runs model-written JavaScript in a Dynamic Worker, with a `browser`\n * object whose functions run on the host. Used by `browserTool`.\n * Internal — not an entry point.\n *\n * The Worker has no network access (`globalOutbound: null`) and no bindings:\n * the only way out is `browser`, whose calls go back to the host over RPC.\n */\nimport { RpcTarget } from \"cloudflare:workers\";\nimport type { BrowserFunction } from \"./browser-functions\";\n\n/**\n * What a run returns: the code's result or error, its console output, and a\n * `notice` for the model when the code likely didn't do what it meant.\n */\nexport type BrowserCodeRun =\n | { result: unknown; logs: string[]; notice?: string }\n | { error: string; logs: string[] };\n\n/**\n * Code run as a function body returns nothing unless it says `return`. Tell\n * the model, rather than parse the code to return its last expression. A text\n * search for `return` can't tell a real one from one inside a string, so any\n * body run that comes back empty gets the notice.\n */\nconst STATEMENTS_NOTICE =\n \"Your code ran as statements and returned nothing. If you wanted a value, `return` it, or write an async arrow function.\";\n\nexport interface RunBrowserCodeOptions {\n loader: WorkerLoader;\n /** The model's code: an async arrow function, or a function body. */\n code: string;\n /** The functions on the `browser` global, run on the host. */\n functions: Record<string, BrowserFunction>;\n /** How long the code may run before it fails. */\n timeoutMs: number;\n /** Stops waiting for the code, as the timeout does. */\n signal?: AbortSignal;\n}\n\n/**\n * The host side of `browser`. A failed call resolves with `{ error }`\n * instead of rejecting across RPC; the sandbox rethrows it as a local error\n * the code can catch.\n */\nclass HostFunctions extends RpcTarget {\n readonly #functions: Record<string, BrowserFunction>;\n\n constructor(functions: Record<string, BrowserFunction>) {\n super();\n this.#functions = functions;\n }\n\n async call(\n name: string,\n input: unknown\n ): Promise<{ value: unknown } | { error: string }> {\n const fn = Object.hasOwn(this.#functions, name)\n ? this.#functions[name]\n : undefined;\n if (!fn) return { error: `browser.${name} is not a function.` };\n try {\n return { value: await fn(input) };\n } catch (error) {\n return { error: error instanceof Error ? error.message : String(error) };\n }\n }\n}\n\n/** Console lines a run keeps, and the characters kept of each. */\nconst MAX_LOG_LINES = 100;\nconst MAX_LOG_LINE_CHARS = 2_000;\n\n/**\n * The entry module. `code.js` holds the model's code; keeping it in its own\n * module keeps the harness's names out of its scope.\n */\nfunction mainModule(timeoutMs: number, names: string[]): string {\n return `import { WorkerEntrypoint } from \"cloudflare:workers\";\nimport run from \"./code.js\";\n\nexport default class BrowserCode extends WorkerEntrypoint {\n async evaluate(binding) {\n // Logs are kept in the tool's stored output, so bound them here.\n const lines = [];\n let dropped = 0;\n const record = (prefix) => (...args) => {\n if (lines.length >= ${MAX_LOG_LINES}) {\n dropped++;\n return;\n }\n const line = prefix + args.map(String).join(\" \");\n lines.push(\n line.length > ${MAX_LOG_LINE_CHARS}\n ? line.slice(0, ${MAX_LOG_LINE_CHARS}) + \"…\"\n : line\n );\n };\n const logs = () =>\n dropped > 0 ? [...lines, \"[\" + dropped + \" more lines dropped]\"] : lines;\n console.log = record(\"\");\n console.info = record(\"\");\n console.warn = record(\"[warn] \");\n console.error = record(\"[error] \");\n const call = async (method, input) => {\n const reply = await binding.call(method, input);\n if (\"error\" in reply) throw new Error(reply.error);\n return reply.value;\n };\n const browser = Object.freeze({\n${names.map((name) => ` ${JSON.stringify(name)}: (input) => call(${JSON.stringify(name)}, input),`).join(\"\\n\")}\n });\n let timer;\n const timeout = new Promise((_, reject) => {\n timer = setTimeout(\n () => reject(new Error(\"Execution timed out after ${timeoutMs}ms\")),\n ${timeoutMs}\n );\n });\n try {\n return {\n result: await Promise.race([run(browser), timeout]),\n logs: logs()\n };\n } catch (error) {\n return {\n error: error instanceof Error ? error.message : String(error),\n logs: logs()\n };\n } finally {\n clearTimeout(timer);\n }\n }\n}\n`;\n}\n\n/** Strip the markdown fences models often wrap code in. */\nfunction stripFences(code: string): string {\n const fenced =\n /^```(?:js|javascript|typescript|ts|tsx|jsx)?\\s*\\n([\\s\\S]*?)```\\s*$/;\n return code.trim().match(fenced)?.[1] ?? code.trim();\n}\n\n/**\n * The model's code as an expression: an async arrow function (what the tool\n * asks for) is called, and any other expression is awaited.\n */\nfunction expressionModule(code: string): string {\n const expression = code\n .replace(/^export\\s+default\\s+/, \"\")\n // A last `;`, even with a comment after it, would end the expression.\n .replace(/;\\s*(\\/\\/[^\\n\"'`]*)?\\s*$/, \"\");\n return `export default async function (browser) {\n const value = (\n${expression}\n );\n return typeof value === \"function\" ? await value() : await value;\n}\n`;\n}\n\n/** The model's code as a function body, for statements with a `return`. */\nfunction bodyModule(code: string): string {\n return `export default async function (browser) {\n${code}\n}\n`;\n}\n\n/** The Worker failed to start because a module didn't parse. */\nfunction isSyntaxError(error: unknown): boolean {\n return error instanceof Error && /SyntaxError/.test(error.message);\n}\n\n/**\n * Run the model's code in a fresh Dynamic Worker, with `browser` bound to\n * `functions`.\n *\n * The code is first loaded as an expression (an async arrow function, as\n * the tool asks for). If that doesn't parse, it's loaded once more as a\n * function body, so statements ending in `return` work too; statements\n * with no `return` at all get a `notice`. Errors thrown\n * by the code, including timeouts, come back as `{ error }`; this only\n * rejects when the Worker can't run at all.\n */\nexport async function runBrowserCode(\n options: RunBrowserCodeOptions\n): Promise<BrowserCodeRun> {\n const code = stripFences(options.code);\n if (code === \"\") return { result: undefined, logs: [] };\n const binding = new HostFunctions(options.functions);\n try {\n return await evaluate(options, expressionModule(code), binding);\n } catch (error) {\n if (!isSyntaxError(error)) throw error;\n }\n let ran: BrowserCodeRun;\n try {\n ran = await evaluate(options, bodyModule(code), binding);\n } catch (error) {\n if (!isSyntaxError(error)) throw error;\n return {\n error: `Your code didn't parse: ${(error as Error).message}. Write an async arrow function, async () => { ... }.`,\n logs: []\n };\n }\n return \"result\" in ran && ran.result === undefined\n ? { ...ran, notice: STATEMENTS_NOTICE }\n : ran;\n}\n\n/**\n * How long past `timeoutMs` the host waits before giving up on a run whose\n * sandbox didn't time itself out. Capped at `timeoutMs` for short runs.\n */\nconst HOST_TIMEOUT_GRACE_MS = 5_000;\n\nasync function evaluate(\n options: RunBrowserCodeOptions,\n codeModule: string,\n binding: HostFunctions\n): Promise<BrowserCodeRun> {\n // `load()`, not `get(id, ...)`: every run's code is different, so there\n // is nothing to cache by id.\n const worker = options.loader.load({\n compatibilityDate: \"2025-06-01\",\n mainModule: \"main.js\",\n modules: {\n \"main.js\": mainModule(options.timeoutMs, Object.keys(options.functions)),\n \"code.js\": codeModule\n },\n globalOutbound: null\n });\n // The loaded Worker and its entrypoint stub own native handles. Dispose\n // both once the run settles rather than leaving them to GC, which can\n // finalize them during isolate shutdown and crash workerd.\n try {\n const entrypoint = worker.getEntrypoint() as unknown as {\n evaluate(binding: HostFunctions): Promise<BrowserCodeRun>;\n };\n const running = entrypoint.evaluate(binding);\n // If the deadline wins, the run's own settling is ignored.\n running.catch(() => {});\n // The sandbox times itself out, but its code can cancel that timer, so\n // the host keeps a deadline too. Missing it frees the scope's queue;\n // the run's later browser calls fail once its session closes.\n let timer: ReturnType<typeof setTimeout> | undefined;\n const deadline = new Promise<BrowserCodeRun>((resolve) => {\n timer = setTimeout(\n () =>\n resolve({\n error: `Execution timed out after ${options.timeoutMs}ms`,\n logs: []\n }),\n options.timeoutMs + Math.min(HOST_TIMEOUT_GRACE_MS, options.timeoutMs)\n );\n });\n // Stopping works like the deadline: the run's later browser calls fail\n // once its session closes.\n const { signal } = options;\n let onAbort: (() => void) | undefined;\n const stopped = new Promise<BrowserCodeRun>((resolve) => {\n onAbort = () =>\n resolve({ error: \"The run was stopped before it finished.\", logs: [] });\n if (signal?.aborted) onAbort();\n else signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n try {\n return await Promise.race([running, deadline, stopped]);\n } finally {\n if (onAbort) signal?.removeEventListener(\"abort\", onAbort);\n clearTimeout(timer);\n disposeQuietly(entrypoint);\n }\n } finally {\n disposeQuietly(worker);\n }\n}\n\nfunction disposeQuietly(resource: unknown): void {\n if (\n typeof resource !== \"object\" ||\n resource === null ||\n !(Symbol.dispose in resource)\n ) {\n return;\n }\n const dispose = (resource as { [Symbol.dispose]?: unknown })[Symbol.dispose];\n if (typeof dispose !== \"function\") return;\n try {\n (dispose as () => void).call(resource);\n } catch {\n // Disposal must never mask the run's result.\n }\n}\n","/**\n * The harness-neutral core of `browserTool`, shared by the adapters\n * in `tools/` (`agents/browser/ai-sdk`, `agents/browser/tanstack-ai`,\n * `agents/browser/pi`). Internal — not an entry point.\n */\nimport { browserFunctionDocs } from \"./browser-functions\";\nimport { runBrowserCode } from \"./sandbox\";\nimport { DEFAULT_BROWSER_SCOPE } from \"./scope\";\nimport { BrowserSession, type BrowserSource } from \"./session\";\nimport { transformBrowserResult } from \"./tool-helpers\";\nimport { truncateResult } from \"./truncate\";\n\nexport interface BrowserToolOptions {\n /**\n * The browser the tool drives — usually a `Browser` installed on the\n * host's Lifecycle. Tools built from the same `Browser` share it.\n */\n browser: BrowserSource;\n\n /**\n * Worker Loader binding the model's code runs in. Each run gets a fresh\n * Dynamic Worker with no network access.\n *\n * Requires `\"worker_loaders\": [{ \"binding\": \"LOADER\" }]` in wrangler.jsonc.\n */\n loader: WorkerLoader;\n\n /** How long one run may take, in milliseconds. Defaults to 60000 (60s). */\n timeoutMs?: number;\n\n /**\n * Who is driving, when several chats or users share one `Browser`: runs\n * with the same scope share an active tab, and each scope keeps its own.\n * Cookies and logins are shared by every scope. Defaults to `\"shared\"`,\n * one active tab for every tool that leaves it out.\n */\n scope?: string;\n\n /**\n * @deprecated Not needed any more: the tool no longer runs on a codemode\n * facet. Ignored.\n */\n ctx?: DurableObjectState;\n}\n\n/** The model's input to `browserTool`: JavaScript to run. */\nexport interface BrowserToolInput {\n code: string;\n}\n\n/** What happened to the browser during a run, added to its result. */\ninterface BrowserReportFields {\n /**\n * Sentences telling the model what happened to its browser: it was\n * restarted, its tab was closed by someone else, another scope is working\n * in its tab too, or the page opened new tabs.\n */\n notice?: string;\n}\n\n/**\n * The result of one `browserTool` run: the code's result, or the\n * error it threw, plus what happened to the browser. Errors are returned,\n * not thrown, so the model can read them and try again.\n */\nexport type BrowserToolOutput = (\n | {\n status: \"completed\";\n /** Identifies the run, for logs and UIs. */\n executionId: string;\n result: unknown;\n /** What the code wrote to the console. */\n logs?: string[];\n }\n | {\n status: \"error\";\n executionId: string;\n error: string;\n logs?: string[];\n }\n) &\n BrowserReportFields;\n\nconst DEFAULT_TIMEOUT_MS = 60_000;\n\n/**\n * The model's input schema, as a Standard Schema with a JSON Schema view,\n * so the AI SDK and TanStack AI both accept it without zod.\n */\nconst inputJsonSchema = {\n type: \"object\",\n properties: {\n code: {\n type: \"string\",\n description:\n \"An async arrow function that drives the browser with `browser`\"\n }\n },\n required: [\"code\"],\n additionalProperties: false\n};\n\nconst browserToolInputSchema = {\n \"~standard\": {\n version: 1 as const,\n vendor: \"agents\",\n types: undefined as\n | { readonly input: BrowserToolInput; readonly output: BrowserToolInput }\n | undefined,\n validate: (\n value: unknown\n ):\n | { readonly value: BrowserToolInput }\n | { readonly issues: ReadonlyArray<{ readonly message: string }> } =>\n typeof value === \"object\" &&\n value !== null &&\n \"code\" in value &&\n typeof value.code === \"string\"\n ? { value: { code: value.code } }\n : {\n issues: [\n { message: \"Expected an object with a string code property\" }\n ]\n },\n jsonSchema: {\n input: (_options: { readonly target: string }) => inputJsonSchema,\n output: (_options: { readonly target: string }) => inputJsonSchema\n }\n }\n};\n\n/**\n * Build the description and `execute` for one `browserTool`.\n *\n * Each run opens a session on the browser in its scope, runs the model's\n * code in a fresh Dynamic Worker with `browser` bound to that session, closes\n * the session, and adds its report's notices to the result. Runs in one\n * scope lock it, since they drive one tab, so they wait for each other and\n * for other locking sessions; runs in different scopes go in parallel.\n */\nexport function createBrowserToolCore(\n options: BrowserToolOptions,\n adapter: {\n /** What the adapter does with screenshots, told to the model. */\n screenshotHint: string;\n }\n) {\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n // The source's own hosts, so custom sources need nothing beyond\n // `BrowserSource`; a `Browser`'s `functionDocs()` returns the same.\n const docs = browserFunctionDocs(options.browser.internalHosts);\n const rules = [\n ...docs.rules,\n \"Results over about 24,000 characters are cut short.\",\n `Each run times out after ${Math.round(timeoutMs / 1000)}s, so split long jobs (crawling a site, say) across runs.`,\n adapter.screenshotHint,\n \"If your code doesn't parse, the line number in the error counts from wrapper code, not yours. Check regex literals and escapes.\"\n ]\n .map((rule) => `- ${rule}`)\n .join(\"\\n\");\n const description = [\n \"Run JavaScript that drives a persistent Chrome browser over the Chrome DevTools Protocol (CDP).\",\n \"\",\n \"Write an async arrow function, `async () => { ... }`, and return a small JSON value. Use the `browser` global to reach the browser. `fetch` is blocked and there is no file system or Node.js API.\",\n \"\",\n \"## browser\",\n \"\",\n docs.functions,\n \"\",\n \"## Rules\",\n \"\",\n rules\n ].join(\"\\n\");\n\n const defaultScope = options.scope ?? DEFAULT_BROWSER_SCOPE;\n\n async function run(\n input: BrowserToolInput,\n scope: string,\n signal: AbortSignal | undefined\n ) {\n const session = new BrowserSession(options.browser, {\n scope,\n lock: true\n });\n // Take the scope's lock before the timeout starts, so the\n // wait doesn't count against the run.\n try {\n await session.lock({ signal });\n } catch (error) {\n await session.close();\n throw error;\n }\n const executionId = crypto.randomUUID();\n let output: BrowserToolOutput;\n try {\n const ran = await runBrowserCode({\n loader: options.loader,\n code: input.code,\n functions: session.functions,\n timeoutMs,\n signal\n });\n const logs = ran.logs.length > 0 ? { logs: ran.logs } : {};\n output =\n \"error\" in ran\n ? {\n status: \"error\",\n executionId,\n // The code can throw anything, so bound it like a result.\n error: truncateResult(ran.error) as string,\n ...logs\n }\n : {\n status: \"completed\",\n executionId,\n result: transformBrowserResult(ran.result),\n ...logs,\n ...(ran.notice ? { notice: ran.notice } : {})\n };\n } catch (error) {\n output = {\n status: \"error\",\n executionId,\n error: error instanceof Error ? error.message : String(error)\n };\n }\n const report = await session.close();\n const notice = [output.notice, ...(report?.notices ?? [])]\n .filter(Boolean)\n .join(\" \");\n return { ...output, ...(notice ? { notice } : {}) };\n }\n\n return {\n description,\n inputSchema: browserToolInputSchema,\n /**\n * Run `input` in `scope`, which defaults to the tool's `scope`. When\n * `signal` aborts, a run still waiting for the lock rejects with its\n * reason, and a running one stops with an error result.\n */\n execute: (\n input: BrowserToolInput,\n call: { scope?: string; signal?: AbortSignal } = {}\n ): Promise<BrowserToolOutput> =>\n run(input, call.scope ?? defaultScope, call.signal)\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAyBA,MAAM,oBACJ;;;;;;;AAmBF,IAAM,gBAAN,cAA4B,UAAU;CAGpC,YAAY,WAA4C;EACtD,MAAM;;EACN,uBAAA,YAAA,MAAkB,SAAA;CACpB;CAEA,MAAM,KACJ,MACA,OACiD;EACjD,MAAM,KAAK,OAAO,OAAA,uBAAA,YAAO,IAAA,GAAiB,IAAI,IAAA,uBAAA,YAC1C,IAAA,CAAA,CAAgB,QAChB,KAAA;EACJ,IAAI,CAAC,IAAI,OAAO,EAAE,OAAO,WAAW,KAAK,qBAAqB;EAC9D,IAAI;GACF,OAAO,EAAE,OAAO,MAAM,GAAG,KAAK,EAAE;EAClC,SAAS,OAAO;GACd,OAAO,EAAE,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAE;EACzE;CACF;AACF;;AAGA,MAAM,gBAAgB;AACtB,MAAM,qBAAqB;;;;;AAM3B,SAAS,WAAW,WAAmB,OAAyB;CAC9D,OAAO;;;;;;;;;4BASmB,cAAc;;;;;;wBAMlB,mBAAmB;4BACf,mBAAmB;;;;;;;;;;;;;;;;EAgB7C,MAAM,KAAK,SAAS,SAAS,KAAK,UAAU,IAAI,EAAE,oBAAoB,KAAK,UAAU,IAAI,EAAE,UAAU,CAAC,CAAC,KAAK,IAAI,EAAE;;;;;4DAKxD,UAAU;UAC5D,UAAU;;;;;;;;;;;;;;;;;;;AAmBpB;;AAGA,SAAS,YAAY,MAAsB;CAGzC,OAAO,KAAK,KAAK,CAAC,CAAC,MAAM,oEAAM,CAAC,GAAG,MAAM,KAAK,KAAK;AACrD;;;;;AAMA,SAAS,iBAAiB,MAAsB;CAK9C,OAAO;;EAJY,KAChB,QAAQ,wBAAwB,EAAE,CAAC,CAE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,OAAO,KAAK;GAC9D;EACF;EACA,MAAM,SAAS,MAAM,QAAQ,MAAM;EACnC,MAAM,SAAS,CAAC,OAAO,QAAQ,GAAI,QAAQ,WAAW,CAAC,CAAE,CAAC,CACvD,OAAO,OAAO,CAAC,CACf,KAAK,GAAG;EACX,OAAO;GAAE,GAAG;GAAQ,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;EAAG;CACpD;CAEA,OAAO;EACL;EACA,aAAa;;;;;;EAMb,UACE,OACA,OAAiD,CAAC,MAElD,IAAI,OAAO,KAAK,SAAS,cAAc,KAAK,MAAM;CACtD;AACF"}
@@ -1072,6 +1072,7 @@ function useAgentChat(options) {
1072
1072
  continuation: data.continuation
1073
1073
  });
1074
1074
  streamStateRef.current = result.state;
1075
+ if (result.isStreaming) customTransport.observeServerTurn(data.id);
1075
1076
  if (result.messagesUpdate) setMessages(result.messagesUpdate);
1076
1077
  setIsServerStreaming(result.isStreaming);
1077
1078
  if (completedObservedToolContinuation) resetToolContinuation();