agents 0.32.0 → 0.34.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 (187) hide show
  1. package/README.md +1 -1
  2. package/dist/{agent-routing-vVMA7m8Y.d.ts → agent-routing-BSoZzNiP.d.ts} +537 -373
  3. package/dist/agent-routing.d.ts +1 -1
  4. package/dist/agent-tool-types.d.ts +1 -1
  5. package/dist/{agent-tools-gGXXkf1z.d.ts → agent-tools-Be-hpRpH.d.ts} +2 -2
  6. package/dist/agent-tools.d.ts +1 -1
  7. package/dist/{ai-sdk-Kon40i0q.js → ai-sdk-CRMlEBX7.js} +75 -44
  8. package/dist/ai-sdk-CRMlEBX7.js.map +1 -0
  9. package/dist/browser/ai.js +2 -3
  10. package/dist/browser/ai.js.map +1 -1
  11. package/dist/browser/index.d.ts +33 -21
  12. package/dist/browser/index.js +937 -4
  13. package/dist/browser/index.js.map +1 -0
  14. package/dist/browser/tools/ai-sdk.d.ts +4 -4
  15. package/dist/browser/tools/ai-sdk.js +9 -3
  16. package/dist/browser/tools/ai-sdk.js.map +1 -1
  17. package/dist/browser/tools/pi.d.ts +11 -8
  18. package/dist/browser/tools/pi.js +58 -11
  19. package/dist/browser/tools/pi.js.map +1 -1
  20. package/dist/browser/tools/tanstack-ai.d.ts +4 -4
  21. package/dist/browser/tools/tanstack-ai.js +3 -3
  22. package/dist/browser/tools/tanstack-ai.js.map +1 -1
  23. package/dist/{browser-D9RNpJuT.d.ts → browser-C9T74n4c.d.ts} +302 -95
  24. package/dist/browser-tool-DOqT1oSD.js +360 -0
  25. package/dist/browser-tool-DOqT1oSD.js.map +1 -0
  26. package/dist/{browser-tool-BhjCcNVE.d.ts → browser-tool-DxAYQY9T.d.ts} +2 -2
  27. package/dist/capability-DBAKc6UZ.js.map +1 -1
  28. package/dist/{capability-runner-BiVUtjqC.d.ts → capability-runner-uFOdSANC.d.ts} +3 -2
  29. package/dist/chat/index.d.ts +37 -6
  30. package/dist/chat/index.js +39 -3
  31. package/dist/chat/index.js.map +1 -1
  32. package/dist/chat/react.js +1 -0
  33. package/dist/chat/react.js.map +1 -1
  34. package/dist/chat-sdk/index.d.ts +3 -3
  35. package/dist/chat-sdk/index.js +1 -1
  36. package/dist/cli.js +62 -60
  37. package/dist/client-CkT8voRY.js +3740 -0
  38. package/dist/client-CkT8voRY.js.map +1 -0
  39. package/dist/{client-eSfgYvd3.d.ts → client-DqS6oequ.d.ts} +2 -2
  40. package/dist/client.d.ts +1 -1
  41. package/dist/{connector-CM-uuxKM.js → connector-Bphz6wIw.js} +414 -3
  42. package/dist/connector-Bphz6wIw.js.map +1 -0
  43. package/dist/{conversations-FjHDRZyD.d.ts → conversations-CoAYNW_q.d.ts} +4 -4
  44. package/dist/{current-agent-CKgT5d1O.d.ts → current-agent-DShbQHDO.d.ts} +24 -3
  45. package/dist/current-agent-DhoDkSnH.js.map +1 -1
  46. package/dist/{do-oauth-client-provider-DtNqv7oj.d.ts → do-oauth-client-provider-BsT8-vtd.d.ts} +22 -2
  47. package/dist/{durable-object-lifecycle-DOI_bzCH.d.ts → durable-object-lifecycle-CRCA6O0W.d.ts} +2 -2
  48. package/dist/experimental/channels/index.d.ts +2 -2
  49. package/dist/experimental/channels/web/index.d.ts +2 -2
  50. package/dist/experimental/channels/web/index.js +1 -1
  51. package/dist/{gateway-BFO6vRDn.d.ts → gateway-Dz8zyZBJ.d.ts} +2 -2
  52. package/dist/harness/ai-sdk/index.d.ts +2 -2
  53. package/dist/harness/container/index.d.ts +2 -2
  54. package/dist/harness/container/index.js +1 -1
  55. package/dist/harness/container/index.js.map +1 -1
  56. package/dist/harness/opencode/index.d.ts +1 -1
  57. package/dist/harness/pi/index.d.ts +200 -37
  58. package/dist/harness/pi/index.js +202 -100
  59. package/dist/harness/pi/index.js.map +1 -1
  60. package/dist/harness/think/index.d.ts +2 -2
  61. package/dist/{images-CfuRCjwq.js → images-D4gtE06D.js} +119 -27
  62. package/dist/images-D4gtE06D.js.map +1 -0
  63. package/dist/{index-8k4qsX1T.d.ts → index-BXVgv6tp.d.ts} +4 -4
  64. package/dist/{index-BEL3ZV-s.d.ts → index-Cs7Ed9la.d.ts} +2 -2
  65. package/dist/{index-CBt8oRJt.d.ts → index-XiZxauMU.d.ts} +3 -3
  66. package/dist/index.d.ts +21 -21
  67. package/dist/index.js +2 -2
  68. package/dist/{input-schema-BQykTEp_.js → input-schema-D6GilRXI.js} +3 -3
  69. package/dist/input-schema-D6GilRXI.js.map +1 -0
  70. package/dist/{input-schema-B0Etuo-o.js → input-schema-y8W5bOdM.js} +3 -3
  71. package/dist/input-schema-y8W5bOdM.js.map +1 -0
  72. package/dist/internal_context.d.ts +1 -1
  73. package/dist/lifecycle/index.d.ts +3 -3
  74. package/dist/lifecycle/index.js +1 -1
  75. package/dist/{lifecycle-v1rKHV2C.js → lifecycle-CB5Dmtrt.js} +126 -38
  76. package/dist/lifecycle-CB5Dmtrt.js.map +1 -0
  77. package/dist/mcp/client/do-oauth-client-provider.d.ts +1 -1
  78. package/dist/mcp/client/do-oauth-client-provider.js +45 -2
  79. package/dist/mcp/client/do-oauth-client-provider.js.map +1 -1
  80. package/dist/mcp/client/index.d.ts +42 -36
  81. package/dist/mcp/client/index.js +2 -2
  82. package/dist/mcp/index.d.ts +16 -16
  83. package/dist/mcp/index.js +2 -2
  84. package/dist/models/ai-sdk/index.d.ts +9 -5
  85. package/dist/models/ai-sdk/index.js +1 -1
  86. package/dist/models/opencode/index.d.ts +3 -3
  87. package/dist/models/opencode/index.js +2 -2
  88. package/dist/models/opencode/index.js.map +1 -1
  89. package/dist/models/pi-ai/index.d.ts +4 -4
  90. package/dist/models/pi-ai/index.js +64 -170
  91. package/dist/models/pi-ai/index.js.map +1 -1
  92. package/dist/{options-CiIsJHXR.d.ts → options-CiXaymmZ.d.ts} +2 -2
  93. package/dist/queue/index.d.ts +1 -1
  94. package/dist/queue/index.js +1 -1
  95. package/dist/{queue-CcIjVYTE.js → queue-B_wl6K0Z.js} +24 -5
  96. package/dist/queue-B_wl6K0Z.js.map +1 -0
  97. package/dist/react.d.ts +2 -2
  98. package/dist/routing/index.d.ts +2 -2
  99. package/dist/{scheduler-BCLESHSC.d.ts → scheduler-CTpR0Ct0.d.ts} +2 -2
  100. package/dist/{scheduler-FIHv2-kJ.js → scheduler-DGNEmxQR.js} +2 -1
  101. package/dist/scheduler-DGNEmxQR.js.map +1 -0
  102. package/dist/schedules/index.d.ts +1 -1
  103. package/dist/schedules/index.js +1 -1
  104. package/dist/serializable.d.ts +1 -1
  105. package/dist/{session-7CDgVE0z.js → session-CRY0bGiI.js} +423 -411
  106. package/dist/session-CRY0bGiI.js.map +1 -0
  107. package/dist/sessions/index.d.ts +1 -1
  108. package/dist/{settings-Dk2il2Hf.js → settings-D2F_qONv.js} +11 -2
  109. package/dist/settings-D2F_qONv.js.map +1 -0
  110. package/dist/{src-DoGNJ4Ud.js → src-BO1FdLK1.js} +145 -86
  111. package/dist/src-BO1FdLK1.js.map +1 -0
  112. package/dist/state/index.d.ts +1 -1
  113. package/dist/streams/index.d.ts +1 -1
  114. package/dist/{streams-vrCtbUIn.d.ts → streams-CAZxZBDg.d.ts} +2 -2
  115. package/dist/sub-routing.d.ts +12 -12
  116. package/dist/tasks/index.d.ts +1 -1
  117. package/dist/tasks/index.js +1 -1
  118. package/dist/{tasks-BN_5AWqI.js → tasks-Cf_UfEO4.js} +2 -1
  119. package/dist/{tasks-BN_5AWqI.js.map → tasks-Cf_UfEO4.js.map} +1 -1
  120. package/dist/{tasks-E89KdwkS.d.ts → tasks-Cs8ilctE.d.ts} +2 -2
  121. package/dist/{tool-DkT_DJBm.js → tool-CmAGY6Fo.js} +24 -3
  122. package/dist/tool-CmAGY6Fo.js.map +1 -0
  123. package/dist/{tool-CxKsvxjm.js → tool-Kxcj8_22.js} +24 -4
  124. package/dist/tool-Kxcj8_22.js.map +1 -0
  125. package/dist/{tool-helpers-BI7ifO2S.js → tool-helpers-F3_Wy2YX.js} +2 -2
  126. package/dist/{tool-helpers-BI7ifO2S.js.map → tool-helpers-F3_Wy2YX.js.map} +1 -1
  127. package/dist/{transport-5moD2pW5.d.ts → transport-hV8AW4Bv.d.ts} +45 -12
  128. package/dist/voice/index.d.ts +2 -2
  129. package/dist/web/fetch/index.js +1 -1
  130. package/dist/web/fetch/tools/ai-sdk.js +2 -2
  131. package/dist/web/fetch/tools/pi.d.ts +9 -7
  132. package/dist/web/fetch/tools/pi.js +31 -7
  133. package/dist/web/fetch/tools/pi.js.map +1 -1
  134. package/dist/web/fetch/tools/tanstack-ai.js +2 -2
  135. package/dist/web/search/index.js +1 -1
  136. package/dist/web/search/tools/ai-sdk.js +2 -2
  137. package/dist/web/search/tools/pi.d.ts +9 -4
  138. package/dist/web/search/tools/pi.js +27 -11
  139. package/dist/web/search/tools/pi.js.map +1 -1
  140. package/dist/web/search/tools/tanstack-ai.js +2 -2
  141. package/dist/websockets/index.d.ts +2 -2
  142. package/dist/websockets/index.js +1 -1
  143. package/dist/{websockets-C6SJtWCJ.js → websockets-W4uhRg4-.js} +68 -5
  144. package/dist/websockets-W4uhRg4-.js.map +1 -0
  145. package/dist/workflow-types.d.ts +1 -1
  146. package/dist/workflows.d.ts +1 -1
  147. package/docs/agent-class.md +30 -4
  148. package/docs/browse-the-web.md +50 -3
  149. package/docs/chat-agents.md +13 -10
  150. package/docs/client-tools-continuation.md +1 -1
  151. package/docs/codemode.md +1 -1
  152. package/docs/configuration.md +6 -3
  153. package/docs/cross-domain-authentication.md +1 -1
  154. package/docs/fetch-the-web.md +20 -0
  155. package/docs/harnesses/pi.md +242 -33
  156. package/docs/harnesses/think.md +1 -1
  157. package/docs/http-websockets.md +40 -32
  158. package/docs/human-in-the-loop.md +2 -2
  159. package/docs/lifecycle.md +56 -0
  160. package/docs/mcp-client.md +104 -7
  161. package/docs/models-pi-ai.md +24 -10
  162. package/docs/models.md +42 -17
  163. package/docs/resumable-streaming.md +1 -1
  164. package/docs/retries.md +3 -6
  165. package/docs/search-the-web.md +10 -0
  166. package/docs/voice.md +1 -1
  167. package/package.json +16 -9
  168. package/dist/ai-sdk-Kon40i0q.js.map +0 -1
  169. package/dist/browser-1eUbPvC2.js +0 -931
  170. package/dist/browser-1eUbPvC2.js.map +0 -1
  171. package/dist/browser-tool-DRan7Lk6.js +0 -497
  172. package/dist/browser-tool-DRan7Lk6.js.map +0 -1
  173. package/dist/client-DMWujQJ1.js +0 -2325
  174. package/dist/client-DMWujQJ1.js.map +0 -1
  175. package/dist/connector-CM-uuxKM.js.map +0 -1
  176. package/dist/images-CfuRCjwq.js.map +0 -1
  177. package/dist/input-schema-B0Etuo-o.js.map +0 -1
  178. package/dist/input-schema-BQykTEp_.js.map +0 -1
  179. package/dist/lifecycle-v1rKHV2C.js.map +0 -1
  180. package/dist/queue-CcIjVYTE.js.map +0 -1
  181. package/dist/scheduler-FIHv2-kJ.js.map +0 -1
  182. package/dist/session-7CDgVE0z.js.map +0 -1
  183. package/dist/settings-Dk2il2Hf.js.map +0 -1
  184. package/dist/src-DoGNJ4Ud.js.map +0 -1
  185. package/dist/tool-CxKsvxjm.js.map +0 -1
  186. package/dist/tool-DkT_DJBm.js.map +0 -1
  187. package/dist/websockets-C6SJtWCJ.js.map +0 -1
@@ -236,405 +236,221 @@ async function connectUrl(baseUrl, options) {
236
236
  /** @deprecated Renamed to {@link CdpConnection}. */
237
237
  const CdpSession = CdpConnection;
238
238
  //#endregion
239
- //#region src/browser/browser-run.ts
240
- var BrowserRenderingError = class extends Error {
241
- constructor(message, status) {
242
- super(message);
243
- this.status = status;
244
- this.name = "BrowserRenderingError";
245
- }
246
- };
239
+ //#region src/browser/validate.ts
247
240
  /**
248
- * Whether an error means the platform session is gone: Browser Run uses 404
249
- * for unknown ids and 410 after `keep_alive` expiry.
241
+ * Input validation for the `browser.*` functions. Internal — not an entry
242
+ * point. Used by `session.ts` and `browser-functions.ts`.
243
+ */
244
+ const validators = /* @__PURE__ */ new WeakMap();
245
+ /**
246
+ * Check a method's input against its schema before it touches the browser,
247
+ * so the model gets a precise error. An omitted input counts as `{}`.
250
248
  */
251
- function isMissingBrowserSession(error) {
252
- return error instanceof BrowserRenderingError && (error.status === 404 || error.status === 410);
249
+ function validate(name, schema, input) {
250
+ let validator = validators.get(schema);
251
+ if (!validator) {
252
+ validator = new Validator(schema, "7", false);
253
+ validators.set(schema, validator);
254
+ }
255
+ const value = input ?? {};
256
+ const result = validator.validate(value);
257
+ if (!result.valid) throw new Error(formatValidationError(name, result.errors));
258
+ return value;
253
259
  }
254
- function browserSessionEndpoint(sessionId, options) {
255
- const path = sessionId ? `/v1/devtools/browser/${sessionId}` : "/v1/devtools/browser";
256
- const url = new URL(`https://localhost${path}`);
257
- if (options?.keepAliveMs !== void 0) url.searchParams.set("keep_alive", String(options.keepAliveMs));
258
- if (options?.includeTargets) url.searchParams.set("targets", "true");
259
- if (options?.recording) url.searchParams.set("recording", "true");
260
- if (options?.browser) url.searchParams.set("browser", options.browser);
261
- return url.toString();
260
+ function formatValidationError(name, errors) {
261
+ const specific = errors.filter((error) => error.keyword !== "properties");
262
+ return `Invalid arguments for ${name}${(specific.length > 0 ? specific : errors).map((error) => {
263
+ const location = error.instanceLocation.replace(/^#\/?/, "").replaceAll("~1", "/").replaceAll("~0", "~").replaceAll("/", ".");
264
+ return `${location ? ` at ${location}` : ""}: ${error.error}`;
265
+ }).join(";")}`;
262
266
  }
263
- async function parseBrowserSessionInfo(response) {
264
- const payload = await response.json();
265
- const sessionId = typeof payload.sessionId === "string" ? payload.sessionId : "";
266
- if (!sessionId) throw new Error("Browser Rendering response did not include a sessionId");
267
- return {
268
- sessionId,
269
- targets: Array.isArray(payload.targets) ? payload.targets : void 0,
270
- webSocketDebuggerUrl: typeof payload.webSocketDebuggerUrl === "string" ? payload.webSocketDebuggerUrl : void 0
267
+ //#endregion
268
+ //#region src/browser/browser-functions.ts
269
+ const SPEC_SCHEMA = {
270
+ type: "object",
271
+ properties: { domain: {
272
+ type: "string",
273
+ minLength: 1
274
+ } }
275
+ };
276
+ const BROWSER_FUNCTIONS = {
277
+ cdp: {
278
+ 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.",
279
+ call: (session, input) => session.send(input)
280
+ },
281
+ attachToTarget: {
282
+ 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.",
283
+ call: (session, input) => session.attachToTarget(input)
284
+ },
285
+ spec: {
286
+ 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\")`.",
287
+ call: async (session, input) => {
288
+ const { domain } = validate("browser.spec", SPEC_SCHEMA, input);
289
+ return specResult(await session.spec(), domain);
290
+ }
291
+ },
292
+ getDebugLog: {
293
+ 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.",
294
+ call: (session, input) => session.getDebugLog(input)
295
+ },
296
+ clearDebugLog: {
297
+ doc: "`browser.clearDebugLog()` forgets the traffic recorded so far, so the next `getDebugLog` shows only what follows.",
298
+ call: (session) => session.clearDebugLog()
299
+ }
300
+ };
301
+ /**
302
+ * Without a domain, every domain's name and first sentence, which is small;
303
+ * with one, that domain's commands, events and types. The whole protocol is
304
+ * about 650 KB, too much for one result.
305
+ */
306
+ function specResult(spec, domain) {
307
+ const { domains } = spec;
308
+ if (domain === void 0) return {
309
+ domains: domains.map(({ name, description }) => ({
310
+ name,
311
+ ...description ? { description: firstSentence(description) } : {}
312
+ })),
313
+ hint: "browser.spec({ domain: \"Page\" }) returns one domain's commands, events and types."
271
314
  };
315
+ const found = domains.find((d) => d.name === domain);
316
+ if (found) return found;
317
+ const near = domains.find((d) => d.name.toLowerCase() === domain.toLowerCase());
318
+ throw new Error(`No CDP domain named '${domain}'.` + (near ? ` Did you mean '${near.name}'?` : " browser.spec() lists the domains."));
272
319
  }
273
- async function createBrowserSession(browser, options) {
274
- const response = await browser.fetch(browserSessionEndpoint(void 0, options), {
275
- method: "POST",
276
- headers: { "Content-Type": "application/json" },
277
- body: JSON.stringify(options?.guardrails ? { guardrails: options.guardrails } : {})
278
- });
279
- if (!response.ok) throw new BrowserRenderingError(`Failed to create Browser Rendering session: ${response.status}`, response.status);
280
- return parseBrowserSessionInfo(response);
281
- }
282
- async function listBrowserTargets(browser, sessionId) {
283
- const response = await browser.fetch(`https://localhost/v1/devtools/browser/${sessionId}/json/list`);
284
- if (!response.ok) throw new BrowserRenderingError(`Failed to list Browser Rendering targets for ${sessionId}: ${response.status}`, response.status);
285
- const payload = await response.json();
286
- return Array.isArray(payload) ? payload : [];
320
+ /** A CDP description's first sentence, for the list of domains. */
321
+ function firstSentence(text) {
322
+ return text.match(/^[\s\S]*?\.(?=\s|$)/)?.[0] ?? text;
287
323
  }
288
- async function deleteBrowserSession(browser, sessionId) {
289
- const response = await browser.fetch(`https://localhost/v1/devtools/browser/${sessionId}`, { method: "DELETE" });
290
- if (!response.ok && response.status !== 404) throw new BrowserRenderingError(`Failed to delete Browser Rendering session ${sessionId}: ${response.status}`, response.status);
324
+ /** The `host` field of a hosts function's input, or a fix-it error. */
325
+ function hostOf(name, input) {
326
+ const host = typeof input === "object" && input !== null ? input.host : void 0;
327
+ if (typeof host !== "string") throw new Error(`browser.${name} needs { host }: the bare hostname, like "preview.internal".`);
328
+ return host;
291
329
  }
292
- /**
293
- * Whether a typed binding call failed because the binding doesn't have that
294
- * method. Fully local dev (Miniflare) has only `fetch`: every other method
295
- * still looks like a function, then throws this when called.
296
- */
297
- function isUnimplementedBindingMethod(error, method) {
298
- return error instanceof TypeError && error.message === `The RPC receiver does not implement the method "${method}".`;
330
+ const HOSTS_FUNCTIONS = {
331
+ listHosts: {
332
+ doc: "`browser.listHosts()` returns each internal site and the target it points at.",
333
+ call: (hosts) => hosts.list()
334
+ },
335
+ assignHost: {
336
+ 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.",
337
+ assignable: true,
338
+ check: (input) => {
339
+ const host = hostOf("assignHost", input);
340
+ if (input.target === void 0) throw new Error(`browser.assignHost needs a target for ${host}; use browser.clearHost to unassign it`);
341
+ },
342
+ call: (hosts, input) => hosts.assign(hostOf("assignHost", input), input.target)
343
+ },
344
+ clearHost: {
345
+ doc: "`browser.clearHost({ host })` unassigns a site and returns `{ cleared }`. An unassigned site answers 502.",
346
+ assignable: true,
347
+ check: (input) => hostOf("clearHost", input),
348
+ call: async (hosts, input) => ({ cleared: await hosts.clear(hostOf("clearHost", input)) })
349
+ }
350
+ };
351
+ /** The hosts functions to offer: assign and clear only if any host can be. */
352
+ function hostsFunctions(infos) {
353
+ const assignable = infos.some((info) => info.assignable);
354
+ return Object.entries(HOSTS_FUNCTIONS).filter(([, definition]) => assignable || !definition.assignable);
299
355
  }
300
356
  /**
301
- * Create a session with the binding's typed `acquire()`. Falls back to the
302
- * HTTP API ({@link createBrowserSession}) when the binding doesn't have
303
- * `acquire()`, as in fully local dev.
357
+ * The `browser` object's functions, bound to one run's session, plus the
358
+ * hosts functions when the browser has internal hostnames. Each hosts
359
+ * function checks its input, then waits for `admit`, then calls the hosts.
304
360
  */
305
- async function acquireBrowserSession(browser, options = {}) {
306
- const { outboundByHost, ...httpOptions } = options;
307
- if (browser.acquire) try {
308
- const { sessionId } = await browser.acquire({
309
- keepAlive: options.keepAliveMs,
310
- recording: options.recording,
311
- guardrails: options.guardrails,
312
- ...outboundByHost ? { outboundByHost } : {}
313
- });
314
- return { sessionId };
315
- } catch (error) {
316
- if (!isUnimplementedBindingMethod(error, "acquire")) throw error;
361
+ function browserFunctions(session, sessionHosts) {
362
+ const functions = Object.fromEntries(Object.entries(BROWSER_FUNCTIONS).map(([name, definition]) => [name, (input) => definition.call(session, input)]));
363
+ if (sessionHosts) {
364
+ const { hosts, admit } = sessionHosts;
365
+ for (const [name, definition] of hostsFunctions(hosts.describe())) functions[name] = async (input) => {
366
+ definition.check?.(input);
367
+ await admit();
368
+ return definition.call(hosts, input);
369
+ };
317
370
  }
318
- if (outboundByHost) warnInternalHostsUnavailable(Object.keys(outboundByHost));
319
- const { sessionId } = await createBrowserSession(browser, httpOptions);
320
- return { sessionId };
371
+ return functions;
321
372
  }
322
- let warnedInternalHostsUnavailable = false;
323
- /** Say once per isolate that internal hostnames need a deployed Worker. */
324
- function warnInternalHostsUnavailable(hosts) {
325
- if (warnedInternalHostsUnavailable) return;
326
- warnedInternalHostsUnavailable = true;
327
- console.warn(`[agents/browser] Internal hostnames (${hosts.join(", ")}) only work once deployed: this Browser Run binding has no acquire(), as in local dev, so the browser starts without them.`);
373
+ /** How one internal site reads in the docs. */
374
+ function describeHost(info) {
375
+ const description = info.description ? ` — ${info.description}` : "";
376
+ const target = info.assignable ? `. Assignable; target schema: ${JSON.stringify(info.targetSchema ?? {})}` : "";
377
+ return `- ${info.url}${description}${target}`;
328
378
  }
329
379
  /**
330
- * The HTTP status in a typed binding method's error. Browser Run's binding
331
- * errors carry it only in the message, e.g. `Not Found (status=404)`.
380
+ * The `browser` object's docs for the model: the functions offered for
381
+ * `hosts`, and the rules.
332
382
  */
333
- function bindingErrorStatus(error) {
334
- if (!(error instanceof Error)) return void 0;
335
- const match = /\(status=(\d{3})[,)]/.exec(error.message);
336
- return match ? Number(match[1]) : void 0;
383
+ function browserFunctionDocs(hosts) {
384
+ return {
385
+ functions: functionsMarkdown(hosts),
386
+ rules: [...BROWSER_RULES]
387
+ };
337
388
  }
338
389
  /**
339
- * Close a session with the binding's typed `closeSession()`. A session
340
- * Browser Run no longer knows (404 or 410) counts as closed. Falls back to
341
- * the HTTP API ({@link deleteBrowserSession}) when the binding doesn't have
342
- * `closeSession()`, as in fully local dev.
390
+ * The functions in Markdown: one line per function, then the internal sites
391
+ * when the browser has any.
343
392
  */
344
- async function closeBrowserSession(browser, sessionId) {
345
- if (browser.closeSession) try {
346
- await browser.closeSession(sessionId);
347
- return;
348
- } catch (error) {
349
- const status = bindingErrorStatus(error);
350
- if (status === 404 || status === 410) return;
351
- if (!isUnimplementedBindingMethod(error, "closeSession")) throw error;
352
- }
353
- await deleteBrowserSession(browser, sessionId);
393
+ function functionsMarkdown(hosts) {
394
+ const infos = hosts?.describe() ?? [];
395
+ const lines = [...Object.values(BROWSER_FUNCTIONS), ...hosts ? hostsFunctions(infos).map(([, definition]) => definition) : []].map((definition) => `- ${definition.doc}`);
396
+ if (!hosts) return lines.join("\n");
397
+ return [
398
+ ...lines,
399
+ "",
400
+ "## Internal sites",
401
+ "",
402
+ "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.",
403
+ "",
404
+ ...infos.map(describeHost)
405
+ ].join("\n");
354
406
  }
355
407
  /**
356
- * Connect to a Browser Rendering session and delete it when closed.
408
+ * How to use the browser, one rule per line. Each rule fixes a mistake
409
+ * models make with CDP, or states something about this browser they can't
410
+ * know; leave out what a model knows already. Rules about how the code runs
411
+ * (timeouts, screenshots) belong to whatever runs it.
357
412
  */
358
- async function connectBrowser(browser, options) {
359
- const normalizedOptions = typeof options === "number" ? { timeoutMs: options } : options ?? {};
360
- if (normalizedOptions.browser === "kitesurf") {
361
- const smuggled = normalizedOptions;
362
- if (smuggled.keepAliveMs || smuggled.includeTargets || smuggled.recording) throw new Error("Kitesurf does not support keepAliveMs, includeTargets, or recording");
363
- }
364
- const response = await browser.fetch(browserSessionEndpoint(void 0, normalizedOptions.browser === "kitesurf" ? { browser: "kitesurf" } : {
365
- keepAliveMs: normalizedOptions.keepAliveMs,
366
- includeTargets: normalizedOptions.includeTargets,
367
- recording: normalizedOptions.recording
368
- }), { headers: { Upgrade: "websocket" } });
369
- const ws = response.webSocket;
370
- if (!ws) throw new Error("Browser Rendering binding did not return a WebSocket. Ensure the 'browser' binding is configured in wrangler.jsonc.");
371
- if (normalizedOptions.browser === "kitesurf") {
372
- ws.accept();
373
- return new CdpConnection(ws, { timeoutMs: normalizedOptions.timeoutMs });
374
- }
375
- const sessionId = response.headers.get("cf-browser-session-id");
376
- if (!sessionId) throw new Error("Browser Rendering binding did not include a session ID when opening the CDP WebSocket");
377
- ws.accept();
378
- return new CdpConnection(ws, {
379
- timeoutMs: normalizedOptions.timeoutMs,
380
- onClose: () => {
381
- deleteBrowserSession(browser, sessionId).catch((error) => {
382
- console.warn(`[agents/browser] Failed to delete one-shot Browser Run session ${sessionId}`, error);
383
- });
384
- },
385
- sessionId
386
- });
387
- }
388
- /**
389
- * Fetch a Browser Run [session recording](https://developers.cloudflare.com/browser-run/features/session-recording/)
390
- * by session id, via the Browser Rendering REST API.
391
- *
392
- * A recording is only available **after** the session closes (explicit
393
- * `closeSession()`, idle `keep_alive` expiry, or sweep) and is retained for 30
394
- * days. Capture the session id while the session is alive — e.g. from
395
- * `connector.liveView()`/`sessionInfo()` — then call this once it has ended.
396
- *
397
- * Unlike the binding-based helpers, this hits `api.cloudflare.com` directly, so
398
- * it needs an account id and an API token with `Browser Rendering` read access
399
- * (the Workers Browser Run binding cannot read recordings).
400
- */
401
- async function getBrowserRecording(options) {
402
- const { accountId, apiToken, sessionId } = options;
403
- const response = await (options.fetchImpl ?? fetch)(`https://api.cloudflare.com/client/v4/accounts/${accountId}/browser-rendering/recording/${sessionId}`, { headers: { Authorization: `Bearer ${apiToken}` } });
404
- if (!response.ok) throw new BrowserRenderingError(`Failed to fetch Browser Run recording for ${sessionId}: ${response.status}`, response.status);
405
- const payload = await response.json();
406
- return "result" in payload && payload.result ? payload.result : payload;
407
- }
408
- async function connectBrowserSession(browser, sessionId, options) {
409
- const normalized = typeof options === "number" ? { timeoutMs: options } : options ?? {};
410
- const response = await browser.fetch(browserSessionEndpoint(sessionId), { headers: { Upgrade: "websocket" } });
411
- const ws = response.webSocket;
412
- if (!ws) throw new BrowserRenderingError(`Browser Rendering binding did not return a WebSocket for session ${sessionId} (${response.status})`, response.status);
413
- ws.accept();
414
- return new CdpConnection(ws, {
415
- timeoutMs: normalized.timeoutMs,
416
- onClose: normalized.onClose,
417
- sessionId,
418
- onActivity: normalized.onActivity
419
- });
420
- }
413
+ const BROWSER_RULES = [
414
+ "The browser persists between runs: tabs, cookies, and logins are still there next time. You never start or close it.",
415
+ "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.",
416
+ "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.",
417
+ "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.",
418
+ "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.",
419
+ "Tabs a page opens itself (popups, target=_blank links) don't become active; a notice lists them.",
420
+ "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.",
421
+ "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'.",
422
+ "Pick out what you need inside Runtime.evaluate and return only that. Page.captureScreenshot throws when its result is over 1 MB."
423
+ ];
421
424
  //#endregion
422
- //#region src/browser/live-view.ts
425
+ //#region src/browser/scope.ts
423
426
  /**
424
- * Browser Run mints `devtoolsFrontendUrl`s (the Live View links) that are
425
- * valid for ~5 minutes. We surface the window so callers can decide how long
426
- * a shared link is good for before re-listing targets.
427
+ * Browser scopes: who is driving a shared `Browser`. Sessions with the same
428
+ * scope share an active tab (and, when they lock, a lock); each scope
429
+ * keeps its own. Cookies and logins are shared by every scope.
427
430
  */
428
- const LIVE_VIEW_URL_TTL_MS = 300 * 1e3;
429
431
  /**
430
- * Rewrite the hosted Live View UI's `mode` query param (`tab` | `devtools`).
431
- * The raw `devtoolsFrontendUrl` is returned unchanged when no mode is asked
432
- * for or the URL can't be parsed.
432
+ * The scope used when a caller doesn't pick one: every caller that leaves
433
+ * `scope` out shares this one active tab. See `BrowserConnectOptions`.
433
434
  */
434
- function applyLiveViewMode(rawUrl, mode) {
435
- if (!mode) return rawUrl;
436
- try {
437
- const url = new URL(rawUrl);
438
- url.searchParams.set("mode", mode === "devtools" ? "devtools" : "tab");
439
- return url.toString();
440
- } catch {
441
- return rawUrl;
442
- }
443
- }
435
+ const DEFAULT_BROWSER_SCOPE = "shared";
444
436
  /**
445
- * Project a fresh target listing into Live View links — one per tab that has
446
- * a `devtoolsFrontendUrl`. Pure; the caller supplies just-listed targets.
437
+ * The scope for one conversation: `conversation:<id>`. pi's `browserTool`
438
+ * gives each conversation this scope by default, so app code that opens
439
+ * sessions with the same scope (a Workspace's `codemode:browser`, say) lands
440
+ * in the same tab as the tool. pi's conversation ids are numbers: pass
441
+ * `String(conversationId)`.
442
+ *
443
+ * Throws on a missing or empty id rather than returning
444
+ * `"conversation:undefined"`, which would quietly put every conversation
445
+ * without an id in one tab.
446
+ *
447
+ * @experimental The API surface may change before stabilizing.
447
448
  */
448
- function createLiveView(sessionId, targets, mode) {
449
- return {
450
- sessionId,
451
- targets: targets.filter((target) => target.devtoolsFrontendUrl).map((target) => ({
452
- targetId: target.id,
453
- url: applyLiveViewMode(target.devtoolsFrontendUrl, mode),
454
- pageUrl: target.url,
455
- title: target.title,
456
- type: target.type
457
- })),
458
- expiresInMs: LIVE_VIEW_URL_TTL_MS
459
- };
449
+ function conversationScope(id) {
450
+ if (typeof id !== "string" || id === "") throw new Error(`conversationScope needs a conversation id, got ${String(id)}.`);
451
+ return `conversation:${id}`;
460
452
  }
461
453
  //#endregion
462
- //#region src/browser/spec.ts
463
- const MISSING_BROWSER_CONFIG = "Either 'browser' (Fetcher binding) or 'cdpUrl' must be provided";
464
- const urlSpecCache = /* @__PURE__ */ new Map();
465
- const bindingSpecCache = /* @__PURE__ */ new WeakMap();
466
- const CACHE_TTL_MS = 300 * 1e3;
467
- /** Qualify a same-domain `$ref` (`"FrameId"` → `"Page.FrameId"`). */
468
- function qualifyRef(domain, ref) {
469
- if (ref === void 0) return void 0;
470
- return ref.includes(".") ? ref : `${domain}.${ref}`;
471
- }
472
- function normalizeItems(domain, items) {
473
- if (!items) return void 0;
474
- return {
475
- type: items.type,
476
- $ref: qualifyRef(domain, items.$ref),
477
- enum: items.enum
478
- };
479
- }
480
- function normalizeFields(domain, fields) {
481
- return (fields ?? []).map((field) => ({
482
- name: field.name,
483
- description: field.description,
484
- optional: field.optional,
485
- experimental: field.experimental,
486
- deprecated: field.deprecated,
487
- type: field.type,
488
- $ref: qualifyRef(domain, field.$ref),
489
- enum: field.enum,
490
- items: normalizeItems(domain, field.items)
491
- }));
492
- }
493
- function normalizeCdpSpec(spec) {
494
- return { domains: (spec.domains ?? []).map(({ domain, ...raw }) => ({
495
- name: domain,
496
- description: raw.description,
497
- experimental: raw.experimental,
498
- deprecated: raw.deprecated,
499
- commands: (raw.commands ?? []).map((command) => ({
500
- name: command.name,
501
- method: `${domain}.${command.name}`,
502
- description: command.description,
503
- experimental: command.experimental,
504
- deprecated: command.deprecated,
505
- parameters: normalizeFields(domain, command.parameters),
506
- returns: normalizeFields(domain, command.returns)
507
- })),
508
- events: (raw.events ?? []).map((event) => ({
509
- name: event.name,
510
- event: `${domain}.${event.name}`,
511
- description: event.description,
512
- experimental: event.experimental,
513
- deprecated: event.deprecated,
514
- parameters: normalizeFields(domain, event.parameters)
515
- })),
516
- types: (raw.types ?? []).map((type) => ({
517
- id: type.id,
518
- name: `${domain}.${type.id}`,
519
- description: type.description,
520
- experimental: type.experimental,
521
- deprecated: type.deprecated,
522
- type: type.type,
523
- enum: type.enum,
524
- properties: normalizeFields(domain, type.properties),
525
- items: normalizeItems(domain, type.items)
526
- }))
527
- })) };
528
- }
529
- function getSpecCacheKey(source, headers) {
530
- const headerEntries = Object.entries(headers ?? {}).sort(([a], [b]) => a.localeCompare(b));
531
- return `${source}:${JSON.stringify(headerEntries)}`;
532
- }
533
- async function getCachedSpec(cache, key, load) {
534
- const cached = cache.get(key);
535
- if (cached && Date.now() - cached.cachedAt < CACHE_TTL_MS) return cached.spec;
536
- const spec = normalizeCdpSpec(await load());
537
- cache.set(key, {
538
- spec,
539
- cachedAt: Date.now()
540
- });
541
- return spec;
542
- }
543
- async function fetchCdpSpecFromUrl(cdpBaseUrl, headers) {
544
- const endpoint = new URL("/json/protocol", cdpBaseUrl).toString();
545
- return getCachedSpec(urlSpecCache, getSpecCacheKey(endpoint, headers), async () => {
546
- const response = await fetch(endpoint, { headers });
547
- if (!response.ok) throw new Error(`Failed to fetch CDP spec from ${endpoint}: ${response.status}`);
548
- return await response.json();
549
- });
550
- }
551
- async function fetchCdpSpecFromSession(browser, sessionId) {
552
- return getCachedSpec(bindingSpecCache, browser, async () => {
553
- const response = await browser.fetch(`https://localhost/v1/devtools/browser/${sessionId}/json/protocol`);
554
- if (!response.ok) throw new Error(`Failed to fetch CDP spec from Browser Rendering: ${response.status}`);
555
- return await response.json();
556
- });
557
- }
558
- async function fetchCdpSpecFromBrowser(browser) {
559
- return getCachedSpec(bindingSpecCache, browser, async () => {
560
- const createResponse = await browser.fetch("https://localhost/v1/devtools/browser", { method: "POST" });
561
- if (!createResponse.ok) throw new Error(`Failed to create Browser Rendering session for protocol fetch: ${createResponse.status}`);
562
- const sessionId = (await createResponse.json()).sessionId;
563
- if (!sessionId) throw new Error("Browser Rendering session response did not include a sessionId");
564
- try {
565
- const response = await browser.fetch(`https://localhost/v1/devtools/browser/${sessionId}/json/protocol`);
566
- if (!response.ok) throw new Error(`Failed to fetch CDP spec from Browser Rendering: ${response.status}`);
567
- return await response.json();
568
- } finally {
569
- try {
570
- await browser.fetch(`https://localhost/v1/devtools/browser/${sessionId}`, { method: "DELETE" });
571
- } catch {}
572
- }
573
- });
574
- }
575
- /** Load the (cached) searchable CDP spec for a browser source. */
576
- async function loadCdpSpec(source) {
577
- if (source.cdpUrl) return fetchCdpSpecFromUrl(source.cdpUrl, source.cdpHeaders);
578
- if (source.browser && source.sessionId) return fetchCdpSpecFromSession(source.browser, source.sessionId);
579
- if (source.browser) return fetchCdpSpecFromBrowser(source.browser);
580
- throw new Error(MISSING_BROWSER_CONFIG);
581
- }
582
- //#endregion
583
- //#region src/browser/session-store.ts
584
- var _DurableBrowserSessionStore_brand = /* @__PURE__ */ new WeakSet();
585
- var DurableBrowserSessionStore = class {
586
- constructor(storage) {
587
- this.storage = storage;
588
- _classPrivateMethodInitSpec(this, _DurableBrowserSessionStore_brand);
589
- }
590
- async acquireLock(key) {
591
- let queues = _queues._.get(this.storage);
592
- if (!queues) {
593
- queues = /* @__PURE__ */ new Map();
594
- _queues._.set(this.storage, queues);
595
- }
596
- const previous = queues.get(key) ?? Promise.resolve();
597
- let releaseQueue = () => void 0;
598
- const current = previous.then(() => new Promise((resolve) => {
599
- releaseQueue = resolve;
600
- }));
601
- queues.set(key, current);
602
- await previous;
603
- let released = false;
604
- return { release: () => {
605
- if (released) return;
606
- released = true;
607
- if (queues.get(key) === current) queues.delete(key);
608
- releaseQueue();
609
- } };
610
- }
611
- async get(key) {
612
- return this.storage.get(_assertClassBrand(_DurableBrowserSessionStore_brand, this, _storageKey).call(this, key));
613
- }
614
- async set(key, session) {
615
- await this.storage.put(_assertClassBrand(_DurableBrowserSessionStore_brand, this, _storageKey).call(this, key), session);
616
- }
617
- async delete(key) {
618
- await this.storage.delete(_assertClassBrand(_DurableBrowserSessionStore_brand, this, _storageKey).call(this, key));
619
- }
620
- async list(prefix) {
621
- const storagePrefix = _assertClassBrand(_DurableBrowserSessionStore_brand, this, _storageKey).call(this, prefix);
622
- const entries = await this.storage.list({ prefix: storagePrefix });
623
- const result = /* @__PURE__ */ new Map();
624
- for (const [storageKey, value] of entries) result.set(storageKey.slice(16), value);
625
- return result;
626
- }
627
- };
628
- function _storageKey(key) {
629
- return `browser-session:${key}`;
630
- }
631
- var _queues = { _: /* @__PURE__ */ new WeakMap() };
632
- /**
633
- * Default idle window used by {@link BrowserConnector.sweep} for the shared
634
- * (reuse/promoted) session entry.
635
- */
636
- const DEFAULT_SWEEP_IDLE_MS = 600 * 1e3;
637
- //#endregion
638
454
  //#region src/browser/session.ts
639
455
  /**
640
456
  * `BrowserSession`: one run's connection to a persistent `Browser`, with the
@@ -647,8 +463,90 @@ const DEFAULT_SWEEP_IDLE_MS = 600 * 1e3;
647
463
  * reports what happened to the browser: a restart, a tab closed by someone
648
464
  * else, a tab shared with another scope, tabs the page opened.
649
465
  *
466
+ * A session opened with `lock: true` holds its scope's lock from its first
467
+ * call (or `lock()`) until it closes; other locking sessions in the scope
468
+ * wait for it, in order.
469
+ *
650
470
  * `browserTool` opens one per run.
651
471
  */
472
+ const RESTARTED_NOTICE = "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.";
473
+ const TAB_CLOSED_NOTICE = "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.";
474
+ const TAB_SHARED_NOTICE = "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.";
475
+ /** What the report says, in sentences the model reads. */
476
+ function reportNotices(report) {
477
+ return [
478
+ report.restarted && RESTARTED_NOTICE,
479
+ report.tabClosed && !report.restarted && TAB_CLOSED_NOTICE,
480
+ report.tabShared && TAB_SHARED_NOTICE,
481
+ report.newTabs.length > 0 && `New tabs opened by the page: ${JSON.stringify(report.newTabs)}`
482
+ ].filter((notice) => typeof notice === "string");
483
+ }
484
+ var _held = /* @__PURE__ */ new WeakMap();
485
+ var _waiting = /* @__PURE__ */ new WeakMap();
486
+ var _onIdle = /* @__PURE__ */ new WeakMap();
487
+ /**
488
+ * Who holds a scope's lock, and who waits for it, in order. A waiter that
489
+ * gives up is removed at once, so nobody behind it waits on it.
490
+ */
491
+ var LockQueue = class {
492
+ /** `onIdle` runs when the lock is freed with nobody waiting. */
493
+ constructor(onIdle) {
494
+ _classPrivateFieldInitSpec(this, _held, false);
495
+ _classPrivateFieldInitSpec(this, _waiting, []);
496
+ _classPrivateFieldInitSpec(this, _onIdle, void 0);
497
+ _classPrivateFieldSet2(_onIdle, this, onIdle);
498
+ }
499
+ /** Resolve once this caller holds the lock. */
500
+ take(signal) {
501
+ if (signal.aborted) {
502
+ if (!_classPrivateFieldGet2(_held, this) && _classPrivateFieldGet2(_waiting, this).length === 0) _classPrivateFieldGet2(_onIdle, this).call(this);
503
+ return Promise.reject(signal.reason);
504
+ }
505
+ if (!_classPrivateFieldGet2(_held, this)) {
506
+ _classPrivateFieldSet2(_held, this, true);
507
+ return Promise.resolve();
508
+ }
509
+ return new Promise((resolve, reject) => {
510
+ const onAbort = () => {
511
+ const index = _classPrivateFieldGet2(_waiting, this).indexOf(waiter);
512
+ if (index !== -1) _classPrivateFieldGet2(_waiting, this).splice(index, 1);
513
+ reject(signal.reason);
514
+ };
515
+ const waiter = { grant: () => {
516
+ signal.removeEventListener("abort", onAbort);
517
+ resolve();
518
+ } };
519
+ _classPrivateFieldGet2(_waiting, this).push(waiter);
520
+ signal.addEventListener("abort", onAbort, { once: true });
521
+ });
522
+ }
523
+ /** Hand the lock to the next waiter, or free the scope. */
524
+ release() {
525
+ const next = _classPrivateFieldGet2(_waiting, this).shift();
526
+ if (next) {
527
+ next.grant();
528
+ return;
529
+ }
530
+ _classPrivateFieldSet2(_held, this, false);
531
+ _classPrivateFieldGet2(_onIdle, this).call(this);
532
+ }
533
+ };
534
+ /**
535
+ * The lock queues per browser and scope. Keyed by the source, so custom
536
+ * sources lock too, and dropped with it.
537
+ */
538
+ const lockQueues = /* @__PURE__ */ new WeakMap();
539
+ function lockQueue(browser, scope) {
540
+ let queues = lockQueues.get(browser);
541
+ if (!queues) lockQueues.set(browser, queues = /* @__PURE__ */ new Map());
542
+ let queue = queues.get(scope);
543
+ if (!queue) {
544
+ const scopes = queues;
545
+ queue = new LockQueue(() => scopes.delete(scope));
546
+ queues.set(scope, queue);
547
+ }
548
+ return queue;
549
+ }
652
550
  /** `sessionId` value that addresses the tab the agent is working in. */
653
551
  const ACTIVE_PAGE_SESSION = "active";
654
552
  /**
@@ -731,9 +629,15 @@ const DEBUG_LOG_SCHEMA = {
731
629
  var _browser = /* @__PURE__ */ new WeakMap();
732
630
  var _scope = /* @__PURE__ */ new WeakMap();
733
631
  var _maxResultBytes = /* @__PURE__ */ new WeakMap();
632
+ var _locksScope = /* @__PURE__ */ new WeakMap();
734
633
  var _state = /* @__PURE__ */ new WeakMap();
735
634
  var _connecting = /* @__PURE__ */ new WeakMap();
736
635
  var _closed = /* @__PURE__ */ new WeakMap();
636
+ var _functions = /* @__PURE__ */ new WeakMap();
637
+ var _acquiring = /* @__PURE__ */ new WeakMap();
638
+ var _heldLock = /* @__PURE__ */ new WeakMap();
639
+ var _closing = /* @__PURE__ */ new WeakMap();
640
+ var _waitedForLockMs = /* @__PURE__ */ new WeakMap();
737
641
  var _BrowserSession_brand = /* @__PURE__ */ new WeakSet();
738
642
  /**
739
643
  * One run's connection to a persistent browser, for one scope.
@@ -744,7 +648,8 @@ var _BrowserSession_brand = /* @__PURE__ */ new WeakSet();
744
648
  * usually comes from model-written code.
745
649
  *
746
650
  * Create one per run with `browser.session({ scope })`, and close it when
747
- * the run ends. The browser itself stays open.
651
+ * the run ends. The browser itself stays open. Pass `lock: true` when
652
+ * runs in one scope may overlap; see {@link BrowserSessionOptions.lock}.
748
653
  *
749
654
  * @experimental The API surface may change before stabilizing.
750
655
  */
@@ -754,12 +659,80 @@ var BrowserSession = class {
754
659
  _classPrivateFieldInitSpec(this, _browser, void 0);
755
660
  _classPrivateFieldInitSpec(this, _scope, void 0);
756
661
  _classPrivateFieldInitSpec(this, _maxResultBytes, void 0);
662
+ _classPrivateFieldInitSpec(this, _locksScope, void 0);
757
663
  _classPrivateFieldInitSpec(this, _state, void 0);
758
664
  _classPrivateFieldInitSpec(this, _connecting, void 0);
759
665
  _classPrivateFieldInitSpec(this, _closed, false);
666
+ _classPrivateFieldInitSpec(this, _functions, void 0);
667
+ _classPrivateFieldInitSpec(this, _acquiring, void 0);
668
+ _classPrivateFieldInitSpec(this, _heldLock, void 0);
669
+ _classPrivateFieldInitSpec(this, _closing, new AbortController());
670
+ _classPrivateFieldInitSpec(this, _waitedForLockMs, 0);
760
671
  _classPrivateFieldSet2(_browser, this, browser);
761
672
  _classPrivateFieldSet2(_scope, this, options.scope);
762
673
  _classPrivateFieldSet2(_maxResultBytes, this, options.maxResultBytes ?? 1e6);
674
+ _classPrivateFieldSet2(_locksScope, this, options.lock ?? false);
675
+ }
676
+ /**
677
+ * The `browser.*` functions bound to this session, by name: the ones
678
+ * `Browser.functionDocs()` describes. Each takes one input object and
679
+ * validates it, so model-written code can call them directly. Like the
680
+ * session's methods, every one rejects once the session is closed, and
681
+ * waits for the scope's lock when the session locks.
682
+ */
683
+ get functions() {
684
+ _classPrivateFieldGet2(_functions, this) ?? _classPrivateFieldSet2(_functions, this, Object.freeze(browserFunctions(this, _assertClassBrand(_BrowserSession_brand, this, _sessionHosts).call(this))));
685
+ return _classPrivateFieldGet2(_functions, this);
686
+ }
687
+ /**
688
+ * Take this scope's lock now rather than at the first call, and hold it
689
+ * until {@link close}. For sessions opened with `lock: true`; a
690
+ * caller with its own time limit calls it first, so the wait doesn't count
691
+ * against the limit, or passes `signal` to bound the wait.
692
+ *
693
+ * Resolves once the session holds the lock, after the locking sessions
694
+ * ahead of it close; later and concurrent calls resolve with the same
695
+ * lock. Rejects when the session closes while waiting. Each call's
696
+ * `signal` bounds only that call's wait: it rejects with the signal's
697
+ * reason, and the session leaves the queue once no call is still
698
+ * waiting (see {@link BrowserLockOptions.signal}); a later call or first
699
+ * call waits again.
700
+ */
701
+ lock(options = {}) {
702
+ if (!_classPrivateFieldGet2(_locksScope, this)) return Promise.reject(/* @__PURE__ */ new Error("This browser session doesn't lock its scope. Open it with { lock: true }."));
703
+ if (_classPrivateFieldGet2(_closed, this)) return Promise.reject(/* @__PURE__ */ new Error("This browser session is closed."));
704
+ if (_classPrivateFieldGet2(_heldLock, this)) return Promise.resolve();
705
+ const { signal } = options;
706
+ if (signal?.aborted) return Promise.reject(signal.reason);
707
+ const acquisition = _classPrivateFieldGet2(_acquiring, this) ?? _classPrivateFieldSet2(_acquiring, this, _assertClassBrand(_BrowserSession_brand, this, _acquire).call(this));
708
+ if (acquisition.giveUp.signal.aborted) return acquisition.promise.then(() => void 0, () => this.lock(options));
709
+ if (!signal) {
710
+ acquisition.unbounded = true;
711
+ return acquisition.promise;
712
+ }
713
+ acquisition.bounded++;
714
+ return new Promise((resolve, reject) => {
715
+ const onAbort = () => {
716
+ acquisition.bounded--;
717
+ if (acquisition.bounded === 0 && !acquisition.unbounded) acquisition.giveUp.abort(signal.reason);
718
+ reject(signal.reason);
719
+ };
720
+ signal.addEventListener("abort", onAbort, { once: true });
721
+ acquisition.promise.then(() => {
722
+ signal.removeEventListener("abort", onAbort);
723
+ resolve();
724
+ }, (error) => {
725
+ signal.removeEventListener("abort", onAbort);
726
+ reject(error);
727
+ });
728
+ });
729
+ }
730
+ /**
731
+ * How long this session waited for its lock, in milliseconds: `0` until
732
+ * it has waited, and for sessions that don't lock.
733
+ */
734
+ get waitedForLockMs() {
735
+ return _classPrivateFieldGet2(_waitedForLockMs, this);
763
736
  }
764
737
  /**
765
738
  * Send a CDP command and resolve with its result, without the JSON-RPC
@@ -820,37 +793,101 @@ var BrowserSession = class {
820
793
  * connected. Never rejects: failures to read the browser's state are
821
794
  * logged and leave the report incomplete. Later calls resolve with
822
795
  * `undefined`, and other methods reject.
796
+ *
797
+ * A locking session releases the lock once the active tab is saved, or
798
+ * stops waiting for it if it was still waiting.
823
799
  */
824
800
  async close() {
825
801
  if (_classPrivateFieldGet2(_closed, this)) return void 0;
826
802
  _classPrivateFieldSet2(_closed, this, true);
827
- let state;
803
+ _classPrivateFieldGet2(_closing, this).abort(/* @__PURE__ */ new Error("This browser session is closed."));
828
804
  try {
829
- state = _classPrivateFieldGet2(_state, this) ?? await _classPrivateFieldGet2(_connecting, this);
830
- } catch {
831
- return;
832
- }
833
- if (!state) return void 0;
834
- _classPrivateFieldSet2(_state, this, void 0);
835
- try {
836
- const open = await _assertClassBrand(_BrowserSession_brand, this, _recordNewTabs).call(this, state);
837
- const active = await _assertClassBrand(_BrowserSession_brand, this, _saveActiveTarget).call(this, state, open);
838
- if (active && state.activeResolved) await _assertClassBrand(_BrowserSession_brand, this, _recordSharedTab).call(this, state, active);
805
+ let state;
806
+ try {
807
+ state = _classPrivateFieldGet2(_state, this) ?? await _classPrivateFieldGet2(_connecting, this);
808
+ } catch {
809
+ return;
810
+ }
811
+ if (!state) return void 0;
812
+ _classPrivateFieldSet2(_state, this, void 0);
813
+ try {
814
+ const open = await _assertClassBrand(_BrowserSession_brand, this, _recordNewTabs).call(this, state);
815
+ const active = await _assertClassBrand(_BrowserSession_brand, this, _saveActiveTarget).call(this, state, open);
816
+ if (active && state.activeResolved) await _assertClassBrand(_BrowserSession_brand, this, _recordSharedTab).call(this, state, active);
817
+ } finally {
818
+ state.connected.cdp.disconnect();
819
+ }
820
+ return {
821
+ ...state.report,
822
+ notices: reportNotices(state.report)
823
+ };
839
824
  } finally {
840
- state.connected.cdp.disconnect();
825
+ await _classPrivateFieldGet2(_acquiring, this)?.promise.catch(() => void 0);
826
+ _classPrivateFieldGet2(_heldLock, this)?.release();
827
+ _classPrivateFieldSet2(_heldLock, this, void 0);
841
828
  }
842
- return state.report;
843
829
  }
844
830
  };
845
- /** Connect once. Concurrent first calls share one connect. */
831
+ /**
832
+ * Connect once, after taking the lock if this session locks its scope.
833
+ * Concurrent first calls share one connect.
834
+ */
846
835
  function _connect() {
847
836
  if (_classPrivateFieldGet2(_closed, this)) return Promise.reject(/* @__PURE__ */ new Error("This browser session is closed."));
848
837
  if (_classPrivateFieldGet2(_state, this)) return Promise.resolve(_classPrivateFieldGet2(_state, this));
849
- _classPrivateFieldGet2(_connecting, this) ?? _classPrivateFieldSet2(_connecting, this, _assertClassBrand(_BrowserSession_brand, this, _open).call(this).finally(() => {
838
+ _classPrivateFieldGet2(_connecting, this) ?? _classPrivateFieldSet2(_connecting, this, _assertClassBrand(_BrowserSession_brand, this, _admitThenOpen).call(this).finally(() => {
850
839
  _classPrivateFieldSet2(_connecting, this, void 0);
851
840
  }));
852
841
  return _classPrivateFieldGet2(_connecting, this);
853
842
  }
843
+ /** The browser's internal hosts, behind this session's admission check. */
844
+ function _sessionHosts() {
845
+ const hosts = _classPrivateFieldGet2(_browser, this).internalHosts;
846
+ return hosts && {
847
+ hosts,
848
+ admit: () => _assertClassBrand(_BrowserSession_brand, this, _admit).call(this)
849
+ };
850
+ }
851
+ async function _admitThenOpen() {
852
+ await _assertClassBrand(_BrowserSession_brand, this, _admit).call(this);
853
+ return _assertClassBrand(_BrowserSession_brand, this, _open).call(this);
854
+ }
855
+ /**
856
+ * The check every function makes before it touches the browser: reject
857
+ * once the session is closed, and wait for the lock when the session
858
+ * locks. It doesn't connect.
859
+ */
860
+ async function _admit() {
861
+ if (_classPrivateFieldGet2(_closed, this)) throw new Error("This browser session is closed.");
862
+ if (!_classPrivateFieldGet2(_locksScope, this)) return;
863
+ await this.lock();
864
+ if (_classPrivateFieldGet2(_closed, this)) throw new Error("This browser session is closed.");
865
+ }
866
+ /** Start waiting for the lock, given up when its calls do or on close. */
867
+ function _acquire() {
868
+ const giveUp = new AbortController();
869
+ const promise = _assertClassBrand(_BrowserSession_brand, this, _waitForLock).call(this, AbortSignal.any([giveUp.signal, _classPrivateFieldGet2(_closing, this).signal])).finally(() => {
870
+ if (_classPrivateFieldGet2(_acquiring, this)?.promise === promise) _classPrivateFieldSet2(_acquiring, this, void 0);
871
+ });
872
+ promise.catch(() => void 0);
873
+ return {
874
+ promise,
875
+ bounded: 0,
876
+ unbounded: false,
877
+ giveUp
878
+ };
879
+ }
880
+ async function _waitForLock(signal) {
881
+ signal.throwIfAborted();
882
+ const queue = lockQueue(_classPrivateFieldGet2(_browser, this), _classPrivateFieldGet2(_scope, this) ?? "shared");
883
+ const started = Date.now();
884
+ try {
885
+ await queue.take(signal);
886
+ _classPrivateFieldSet2(_heldLock, this, queue);
887
+ } finally {
888
+ _classPrivateFieldSet2(_waitedForLockMs, this, _classPrivateFieldGet2(_waitedForLockMs, this) + (Date.now() - started));
889
+ }
890
+ }
854
891
  async function _open() {
855
892
  const connected = await _classPrivateFieldGet2(_browser, this).connect(_classPrivateFieldGet2(_scope, this) === void 0 ? void 0 : { scope: _classPrivateFieldGet2(_scope, this) });
856
893
  let initialPages;
@@ -1050,32 +1087,7 @@ function isAttachHandle(sessionId) {
1050
1087
  function targetOfHandle(handle) {
1051
1088
  return handle.slice(7);
1052
1089
  }
1053
- const validators = /* @__PURE__ */ new WeakMap();
1054
- /**
1055
- * Check a method's input against its schema before it touches the browser,
1056
- * so the model gets a precise error. An omitted input counts as `{}`.
1057
- *
1058
- * @internal Also used by `browser-functions.ts`.
1059
- */
1060
- function validate(name, schema, input) {
1061
- let validator = validators.get(schema);
1062
- if (!validator) {
1063
- validator = new Validator(schema, "7", false);
1064
- validators.set(schema, validator);
1065
- }
1066
- const value = input ?? {};
1067
- const result = validator.validate(value);
1068
- if (!result.valid) throw new Error(formatValidationError(name, result.errors));
1069
- return value;
1070
- }
1071
- function formatValidationError(name, errors) {
1072
- const specific = errors.filter((error) => error.keyword !== "properties");
1073
- return `Invalid arguments for ${name}${(specific.length > 0 ? specific : errors).map((error) => {
1074
- const location = error.instanceLocation.replace(/^#\/?/, "").replaceAll("~1", "/").replaceAll("~0", "~").replaceAll("/", ".");
1075
- return `${location ? ` at ${location}` : ""}: ${error.error}`;
1076
- }).join(";")}`;
1077
- }
1078
1090
  //#endregion
1079
- export { CdpProtocolError as C, CdpConnection as S, connectUrl as T, deleteBrowserSession as _, DEFAULT_SWEEP_IDLE_MS as a, listBrowserTargets as b, LIVE_VIEW_URL_TTL_MS as c, BrowserRenderingError as d, acquireBrowserSession as f, createBrowserSession as g, connectBrowserSession as h, validate as i, applyLiveViewMode as l, connectBrowser as m, BrowserSession as n, DurableBrowserSessionStore as o, closeBrowserSession as p, DEFAULT_MAX_RESULT_BYTES as r, loadCdpSpec as s, ACTIVE_PAGE_SESSION as t, createLiveView as u, getBrowserRecording as v, CdpSession as w, CDP_METHOD_NOT_FOUND as x, isMissingBrowserSession as y };
1091
+ export { conversationScope as a, CdpConnection as c, connectUrl as d, DEFAULT_BROWSER_SCOPE as i, CdpProtocolError as l, BrowserSession as n, browserFunctionDocs as o, DEFAULT_MAX_RESULT_BYTES as r, CDP_METHOD_NOT_FOUND as s, ACTIVE_PAGE_SESSION as t, CdpSession as u };
1080
1092
 
1081
- //# sourceMappingURL=session-7CDgVE0z.js.map
1093
+ //# sourceMappingURL=session-CRY0bGiI.js.map