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
@@ -1,931 +0,0 @@
1
- import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldSet2, r as _assertClassBrand, t as _classPrivateFieldGet2 } from "./classPrivateFieldGet2-DZBYAB34.js";
2
- import { t as _classPrivateMethodInitSpec } from "./classPrivateMethodInitSpec-qMjJ6sHQ.js";
3
- import { t as LifecycleCapability } from "./capability-DBAKc6UZ.js";
4
- import { t as browserCapabilityId } from "./capability-id-B3J8Nok_.js";
5
- import { b as listBrowserTargets, f as acquireBrowserSession, h as connectBrowserSession, n as BrowserSession, o as DurableBrowserSessionStore, p as closeBrowserSession, s as loadCdpSpec, u as createLiveView, y as isMissingBrowserSession } from "./session-7CDgVE0z.js";
6
- import { WorkerEntrypoint } from "cloudflare:workers";
7
- import { Validator } from "@cfworker/json-schema";
8
- //#region src/browser/internal-hosts.ts
9
- /**
10
- * Internal hostnames: sites only this agent's browser can open.
11
- *
12
- * A host maps a hostname such as `preview.internal` to code in your agent
13
- * (`fetch`) or to a deployed Worker (`worker`). Browser Run sends the
14
- * browser's requests for that hostname to it instead of the internet, so a
15
- * page can be served from a sandbox port or a workspace folder, without exposing anything publicly.
16
- *
17
- * How a request travels: Browser Run accepts only entrypoints of your own
18
- * Worker as routes, and keeps them for the whole browser session (observed
19
- * across redeploys and Durable Object eviction; Browser Run doesn't document
20
- * this yet). So every `fetch` host routes to {@link InternalHostRouter}, which
21
- * you export from your main module. Its props say which agent and browser
22
- * own the host, and nothing else. It calls the agent's `fetchInternalHost()`
23
- * over RPC, and the agent's `Browser` runs the host's `fetch`. `Agent` has
24
- * that method built in; a plain Durable Object adds it (see
25
- * {@link InternalHostMessage}). A `worker` host goes straight to the Worker
26
- * you gave it.
27
- */
28
- /** The most hostnames one browser can have. A Browser Run limit. */
29
- const MAX_INTERNAL_HOSTS = 8;
30
- const HOSTNAME = /^(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/;
31
- /**
32
- * Suffixes reserved so they never resolve on the internet. A real domain
33
- * would be served by the host over http but reach the real site over https
34
- * (and Chrome tries https first), so internal hostnames must use one.
35
- * Single labels like `preview` would work, but Browser Run doesn't route
36
- * labels that are real TLDs (`docs`, `app`) and gives no error for them, so
37
- * they're rejected rather than checked against a TLD list.
38
- */
39
- const RESERVED_SUFFIXES = [
40
- ".internal",
41
- ".test",
42
- ".example",
43
- ".invalid"
44
- ];
45
- /** Why `host` can't be an internal hostname, or undefined when it can. */
46
- function hostnameProblem(host) {
47
- if (host.includes("://")) return "drop the scheme";
48
- if (host.includes("/")) return "drop the path";
49
- if (host.includes(":")) return "drop the port (only port 80 is routed)";
50
- if (host !== host.toLowerCase()) return "use lowercase";
51
- if (/^\d+(\.\d+){3}$/.test(host)) return "use a name, not an IP address";
52
- if (host === "localhost" || host.endsWith(".localhost")) return "Chrome sends localhost to the browser's own machine";
53
- if (!HOSTNAME.test(host)) return "not a valid hostname";
54
- if (!RESERVED_SUFFIXES.some((suffix) => host.endsWith(suffix))) return `use a name that can't be a real site: end it in ${RESERVED_SUFFIXES.join(", ")}`;
55
- }
56
- /**
57
- * Check `internalHosts` when the provider is created, so a mistake fails at
58
- * startup instead of at the first browser launch.
59
- */
60
- function validateInternalHosts(options) {
61
- const hosts = Object.entries(options.hosts);
62
- if (hosts.length === 0) throw new Error("internalHosts.hosts needs at least one hostname");
63
- if (hosts.length > 8) throw new Error(`internalHosts has ${hosts.length} hostnames; Browser Run allows at most 8 per browser`);
64
- for (const [host, config] of hosts) {
65
- const problem = hostnameProblem(host);
66
- if (problem) throw new Error(`Internal hostname "${host}": ${problem}`);
67
- const hasFetch = typeof config.fetch === "function";
68
- const hasWorker = config.worker !== void 0;
69
- if (hasFetch === hasWorker) throw new Error(`Internal hostname "${host}" needs exactly one of fetch or worker`);
70
- if (hasWorker && config.target !== void 0) throw new Error(`Internal hostname "${host}": target needs fetch; a worker host can't be assigned`);
71
- if (hasFetch && typeof options.router !== "function") throw new Error(`Internal hostname "${host}" uses fetch, which needs internalHosts.router: this.ctx.exports.InternalHostRouter (and \`export { InternalHostRouter } from "agents/browser"\` in your main module)`);
72
- if (config.target !== void 0) targetJsonSchema(host, config.target);
73
- }
74
- }
75
- /**
76
- * Identifies the set of hostnames and how each is routed. A browser started
77
- * with a different set is replaced: Browser Run fixes routes at launch.
78
- */
79
- function internalHostsSignature(options) {
80
- if (!options) return void 0;
81
- return Object.entries(options.hosts).map(([host, config]) => `${host}=${config.worker ? "worker" : "fetch"}`).sort().join(",");
82
- }
83
- /**
84
- * The route Browser Run gets for a `worker` host. A `ctx.exports`
85
- * entrypoint is a loopback stub that Browser Run can't take as is, so it's
86
- * called (with empty props) to get a Fetcher it can.
87
- */
88
- function workerRoute(worker) {
89
- if (typeof worker !== "function") return worker;
90
- return worker({ props: {} });
91
- }
92
- function isStandardSchema(schema) {
93
- return typeof schema === "object" && schema !== null && "~standard" in schema;
94
- }
95
- /** A host's target schema as JSON Schema, for the model and for plain validation. */
96
- function targetJsonSchema(host, schema) {
97
- if (!isStandardSchema(schema)) {
98
- if (typeof schema !== "object" || schema === null) throw new Error(`Internal hostname "${host}": target must be a schema`);
99
- return schema;
100
- }
101
- const { jsonSchema } = schema["~standard"];
102
- if (!jsonSchema?.input) throw new Error(`Internal hostname "${host}": target needs a schema that can describe itself as JSON Schema (Standard JSON Schema, such as zod 4.2+), or a plain JSON Schema object`);
103
- try {
104
- return jsonSchema.input({ target: "draft-07" });
105
- } catch {
106
- return jsonSchema.input({ target: "draft-2020-12" });
107
- }
108
- }
109
- const plainValidators = /* @__PURE__ */ new WeakMap();
110
- function formatIssues(issues) {
111
- return issues.map((issue) => issue.path ? `${issue.path}: ${issue.message}` : issue.message).join("; ");
112
- }
113
- function pathString(path) {
114
- if (!path?.length) return void 0;
115
- return path.map((part) => String(typeof part === "object" ? part.key : part)).join(".");
116
- }
117
- function plainIssues(errors) {
118
- const specific = errors.filter((error) => error.keyword !== "properties");
119
- return (specific.length > 0 ? specific : errors).map((error) => ({
120
- message: error.error,
121
- path: error.instanceLocation.replace(/^#\/?/, "").replaceAll("/", ".") || void 0
122
- }));
123
- }
124
- /**
125
- * Validate a target against a host's schema. Returns the validated value
126
- * (a Standard Schema's output, which may differ from its input), or a
127
- * message saying what's wrong.
128
- */
129
- async function validateTarget(schema, value) {
130
- if (isStandardSchema(schema)) {
131
- const result = await schema["~standard"].validate(value);
132
- if (result.issues) return {
133
- ok: false,
134
- error: formatIssues(result.issues.map((issue) => ({
135
- message: issue.message,
136
- path: pathString(issue.path)
137
- })))
138
- };
139
- return {
140
- ok: true,
141
- value: result.value
142
- };
143
- }
144
- let validator = plainValidators.get(schema);
145
- if (!validator) {
146
- validator = new Validator(schema, "7", false);
147
- plainValidators.set(schema, validator);
148
- }
149
- const result = validator.validate(value);
150
- return result.valid ? {
151
- ok: true,
152
- value
153
- } : {
154
- ok: false,
155
- error: formatIssues(plainIssues(result.errors))
156
- };
157
- }
158
- function isInternalHostMessage(value) {
159
- if (typeof value !== "object" || value === null) return false;
160
- const message = value;
161
- return typeof message.browser === "string" && typeof message.host === "string" && message.request instanceof Request;
162
- }
163
- /** A plain-text response the browser shows for a failed internal request. */
164
- function internalHostError(status, message) {
165
- return new Response(message, {
166
- status,
167
- headers: { "content-type": "text/plain; charset=utf-8" }
168
- });
169
- }
170
- /**
171
- * Whether an RPC call failed because the agent has no `fetchInternalHost()`.
172
- * workerd says: `The RPC receiver does not implement the method
173
- * "fetchInternalHost".` If that wording changes, the router falls back to its
174
- * generic 502, which names the method too.
175
- */
176
- function isMissingMethod(error) {
177
- return error instanceof Error && error.message.includes("fetchInternalHost") && /does not implement|is not a function/.test(error.message);
178
- }
179
- /**
180
- * Carries a browser's requests for an internal hostname to the agent that
181
- * owns it. Export it from your Worker's main module, so
182
- * `this.ctx.exports.InternalHostRouter` exists:
183
- *
184
- * ```ts
185
- * export { InternalHostRouter } from "agents/browser";
186
- * ```
187
- *
188
- * It trusts its props: Browser Run sets them from your routes, but another
189
- * Worker in your account with a service binding to this entrypoint could
190
- * set its own and reach any agent's hosts. That Worker could already call
191
- * your agents directly, so this grants nothing new.
192
- *
193
- * It holds no logic of its own: it calls the agent's `fetchInternalHost()`
194
- * with an {@link InternalHostMessage}, and the agent's `Browser` runs the
195
- * host's `fetch`. `Agent` has `fetchInternalHost()` built in; a plain
196
- * Durable Object adds it (see {@link InternalHostMessage}).
197
- *
198
- * @experimental The API may change before it stabilizes.
199
- */
200
- var InternalHostRouter = class extends WorkerEntrypoint {
201
- async fetch(request) {
202
- const props = this.ctx.props;
203
- if (!isRouterProps(props)) return internalHostError(502, "InternalHostRouter was called without route props. Only Browser Run calls it, with the routes browserRun({ internalHosts }) gives it.");
204
- const namespace = this.ctx.exports?.[props.className];
205
- if (!namespace?.getByName) return internalHostError(502, `${props.host}: the agent class "${props.className}" isn't exported from this Worker`);
206
- try {
207
- const response = await namespace.getByName(props.name).fetchInternalHost({
208
- browser: props.browser,
209
- host: props.host,
210
- request
211
- });
212
- if (response instanceof Response) return response;
213
- return internalHostError(502, `${props.host}: the agent didn't answer with a Response`);
214
- } catch (error) {
215
- if (isMissingMethod(error)) return internalHostError(502, `${props.host}: ${props.className} has no fetchInternalHost() method. Agent has it built in; on a plain Durable Object add: fetchInternalHost(message) { return this.browser.fetchInternalHost(message); }`);
216
- console.error(`[agents/browser] ${props.className} failed to serve ${props.host}`, error);
217
- return internalHostError(502, `${props.host}: the agent failed to serve this request`);
218
- }
219
- }
220
- };
221
- function isRouterProps(props) {
222
- return props?.v === 1 && typeof props.className === "string" && typeof props.name === "string" && typeof props.browser === "string" && typeof props.host === "string";
223
- }
224
- //#endregion
225
- //#region src/browser/providers/provider-adapter.ts
226
- /**
227
- * Thrown by {@link BrowserProviderAdapter.connect} when the session no longer
228
- * exists upstream (closed, expired, or reclaimed). `Browser` treats it as
229
- * "this browser is lost" and replaces it; any other error is passed on.
230
- */
231
- var BrowserSessionGoneError = class extends Error {
232
- constructor(sessionId, options) {
233
- super(`Browser session gone: ${sessionId}`, options);
234
- this.sessionId = sessionId;
235
- this.name = "BrowserSessionGoneError";
236
- }
237
- };
238
- /**
239
- * Run the browser on Cloudflare Browser Run.
240
- *
241
- * @example
242
- * ```ts
243
- * new Browser({ provider: browserRun(env.BROWSER, { recording: true }) });
244
- * ```
245
- */
246
- function browserRun(binding, options = {}) {
247
- const erased = options;
248
- if (erased.internalHosts) validateInternalHosts(erased.internalHosts);
249
- return {
250
- kind: "browser-run",
251
- binding,
252
- options: erased
253
- };
254
- }
255
- function isDataCloneError(error) {
256
- return error instanceof Error && error.name === "DataCloneError";
257
- }
258
- /** One `outboundByHost` route per internal hostname. */
259
- function internalHostRoutes(internalHosts, owner) {
260
- const routes = {};
261
- const hosts = Object.entries(internalHosts.hosts);
262
- for (const [host, config] of hosts) {
263
- if (config.worker) {
264
- routes[host] = workerRoute(config.worker);
265
- continue;
266
- }
267
- routes[host] = internalHosts.router({ props: {
268
- v: 1,
269
- ...owner,
270
- host
271
- } });
272
- }
273
- return routes;
274
- }
275
- /** The code behind {@link browserRun}. */
276
- function browserRunAdapter(provider) {
277
- const { binding, options } = provider;
278
- const keepAliveMs = () => options.keepAliveMs ?? 6e5;
279
- return {
280
- get keepAliveMs() {
281
- return keepAliveMs();
282
- },
283
- internalHosts: options.internalHosts,
284
- internalHostsSignature: internalHostsSignature(options.internalHosts),
285
- async create(context) {
286
- const { internalHosts } = options;
287
- if (internalHosts && !context?.owner) throw new Error("Internal hostnames need the Browser installed with Lifecycle.use() on a top-level agent");
288
- try {
289
- return await acquireBrowserSession(binding, {
290
- keepAliveMs: keepAliveMs(),
291
- recording: options.recording,
292
- guardrails: options.guardrails,
293
- ...internalHosts && context?.owner ? { outboundByHost: internalHostRoutes(internalHosts, context.owner) } : {}
294
- });
295
- } catch (error) {
296
- if (internalHosts && isDataCloneError(error)) throw new Error("Browser Run couldn't take the internal hostname routes: a worker host must be a service binding or an entrypoint of this Worker (this.ctx.exports.Name), not a Dynamic Worker or another object it can't hold", { cause: error });
297
- throw error;
298
- }
299
- },
300
- async isAlive(sessionId) {
301
- try {
302
- await listBrowserTargets(binding, sessionId);
303
- return true;
304
- } catch (error) {
305
- if (isMissingBrowserSession(error)) return false;
306
- throw error;
307
- }
308
- },
309
- async connect(sessionId, connectOptions) {
310
- try {
311
- return await connectBrowserSession(binding, sessionId, connectOptions);
312
- } catch (error) {
313
- if (isMissingBrowserSession(error)) throw new BrowserSessionGoneError(sessionId, { cause: error });
314
- throw error;
315
- }
316
- },
317
- async close(sessionId) {
318
- try {
319
- await closeBrowserSession(binding, sessionId);
320
- } catch (error) {
321
- if (!isMissingBrowserSession(error)) throw error;
322
- }
323
- },
324
- spec(sessionId) {
325
- return loadCdpSpec({
326
- browser: binding,
327
- sessionId
328
- });
329
- },
330
- async liveView(sessionId, mode) {
331
- try {
332
- return createLiveView(sessionId, await listBrowserTargets(binding, sessionId), mode);
333
- } catch (error) {
334
- if (isMissingBrowserSession(error)) return void 0;
335
- throw error;
336
- }
337
- }
338
- };
339
- }
340
- /**
341
- * The scope used when a caller doesn't pick one: every caller that leaves
342
- * `scope` out shares this one active tab. See {@link BrowserConnectOptions}.
343
- */
344
- const DEFAULT_BROWSER_SCOPE = "shared";
345
- /**
346
- * Scope records kept per browser. Writing a new one past the cap deletes the
347
- * least recently used; a scope that comes back afterwards starts fresh.
348
- */
349
- const MAX_BROWSER_SCOPES = 100;
350
- const NAMED_SESSION_KEY_PREFIX = "browser:session:";
351
- /** The store key holding the named browser's current record. */
352
- function namedBrowserSessionKey(name) {
353
- return `${NAMED_SESSION_KEY_PREFIX}${name}`;
354
- }
355
- /**
356
- * Where a closed or lost browser's record moves: permanent evidence that the
357
- * name once owned a browser, so a later resolve reports `restarted: true`.
358
- * Kept outside {@link NAMED_SESSION_KEY_PREFIX} so listing that prefix
359
- * yields only names that currently own a browser. Grows with the number of
360
- * distinct names the host has ever used.
361
- */
362
- const RETIRED_SESSION_KEY_PREFIX = "browser:retired:";
363
- function retiredBrowserSessionKey(name) {
364
- return `${RETIRED_SESSION_KEY_PREFIX}${name}`;
365
- }
366
- /**
367
- * Where a browser's scope records live. The name's length is part of the
368
- * prefix, so one browser's prefix never matches another name's (`a` with
369
- * scope `b:c` vs. `a:b` with scope `c`).
370
- */
371
- function browserScopeKeyPrefix(name) {
372
- return `browser:scope:${name.length}:${name}:`;
373
- }
374
- /**
375
- * Where a browser's internal-host targets live: one key per host, under a
376
- * prefix per browser (length-prefixed like scope records, so one browser's
377
- * prefix never matches another's). Kept apart from the session record, so
378
- * targets survive the browser being replaced.
379
- */
380
- function internalHostTargetsPrefix(name) {
381
- return `browser:hosts:${name.length}:${name}:`;
382
- }
383
- /** The adapter behind a provider: one explicit case per provider kind. */
384
- function providerAdapterFor(provider) {
385
- switch (provider.kind) {
386
- case "browser-run": return browserRunAdapter(provider);
387
- }
388
- }
389
- var _options = /* @__PURE__ */ new WeakMap();
390
- var _key = /* @__PURE__ */ new WeakMap();
391
- var _adapter = /* @__PURE__ */ new WeakMap();
392
- var _store = /* @__PURE__ */ new WeakMap();
393
- var _Browser_brand = /* @__PURE__ */ new WeakSet();
394
- /**
395
- * One named, persistent browser.
396
- *
397
- * Install it with `Lifecycle.use()` — on an Agent subclass or any Durable
398
- * Object that composes `Lifecycle` — and it stores its record in the
399
- * object's own storage. It schedules nothing: the provider reclaims idle
400
- * browsers itself (Browser Run once `keep_alive` elapses), and the next use
401
- * replaces the lost browser with `restarted: true`.
402
- *
403
- * Everything here is host-side. Models never see browser names, provider
404
- * session ids, or Live View URLs through this surface.
405
- *
406
- * Store discipline: locks wrap storage operations only — liveness probes and
407
- * provider create/close calls always happen outside any lock, with a commit
408
- * re-check to detect concurrent swaps.
409
- *
410
- * @experimental The API surface may change before stabilizing.
411
- */
412
- var Browser = class extends LifecycleCapability {
413
- constructor(options) {
414
- const name = options.name ?? "default";
415
- super(browserCapabilityId(name));
416
- _classPrivateMethodInitSpec(this, _Browser_brand);
417
- _classPrivateFieldInitSpec(this, _options, void 0);
418
- _classPrivateFieldInitSpec(this, _key, void 0);
419
- _classPrivateFieldInitSpec(this, _adapter, void 0);
420
- _classPrivateFieldInitSpec(this, _store, void 0);
421
- if (name.trim() === "") throw new Error("Browser names must be non-empty");
422
- this.name = name;
423
- _classPrivateFieldSet2(_options, this, options);
424
- _classPrivateFieldSet2(_key, this, namedBrowserSessionKey(name));
425
- _classPrivateFieldSet2(_adapter, this, providerAdapterFor(options.provider));
426
- }
427
- /**
428
- * Reattach to the browser when it is still alive, otherwise create a fresh
429
- * one. See {@link ResolvedBrowser.restarted} for the mortality signal.
430
- */
431
- async resolve() {
432
- const { name } = this;
433
- const key = _classPrivateFieldGet2(_key, this);
434
- for (let attempt = 0; attempt < 4; attempt++) {
435
- const existing = await _assertClassBrand(_Browser_brand, this, _readStored).call(this);
436
- if (existing === void 0) {
437
- const { session, restarted } = await _assertClassBrand(_Browser_brand, this, _createAndCommit).call(this);
438
- return {
439
- name,
440
- restarted,
441
- ...resolvedFields(session)
442
- };
443
- }
444
- const routesMatch = existing.internalHosts === _classPrivateFieldGet2(_adapter, this).internalHostsSignature;
445
- const alive = routesMatch && await _classPrivateFieldGet2(_adapter, this).isAlive(existing.sessionId);
446
- const lock = await _get_sessionStore.call(_assertClassBrand(_Browser_brand, this)).acquireLock(key);
447
- try {
448
- const current = await _get_sessionStore.call(_assertClassBrand(_Browser_brand, this)).get(key);
449
- if (current?.sessionId !== existing.sessionId) continue;
450
- if (alive) {
451
- const refreshed = {
452
- ...current,
453
- updatedAt: Date.now()
454
- };
455
- await _get_sessionStore.call(_assertClassBrand(_Browser_brand, this)).set(key, refreshed);
456
- return {
457
- name,
458
- restarted: false,
459
- ...resolvedFields(refreshed)
460
- };
461
- }
462
- await _assertClassBrand(_Browser_brand, this, _retire).call(this, current);
463
- } finally {
464
- await lock.release();
465
- }
466
- if (!routesMatch) await _assertClassBrand(_Browser_brand, this, _closeQuietly).call(this, existing.sessionId);
467
- }
468
- throw new Error(`Browser "${name}" kept changing concurrently — retry`);
469
- }
470
- /**
471
- * Resolve the browser and open a CDP connection to it for one scope (see
472
- * {@link BrowserConnectOptions.scope}). Commands sent over the connection
473
- * refresh the record's `updatedAt` (throttled to
474
- * {@link SESSION_TOUCH_INTERVAL_MS}), so hosts can tell an actively used
475
- * browser from one the platform has likely reclaimed.
476
- *
477
- * If the browser expires between the liveness probe and the WebSocket
478
- * upgrade, the record is retired and the browser resolved once more, so
479
- * the caller gets a fresh browser instead of an error.
480
- */
481
- async connect(options = {}) {
482
- const scope = options.scope ?? "shared";
483
- if (scope.trim() === "") throw new Error("Browser scopes must be non-empty");
484
- let resolved = await this.resolve();
485
- let cdp;
486
- try {
487
- cdp = await _assertClassBrand(_Browser_brand, this, _open).call(this, resolved);
488
- } catch (error) {
489
- if (!(error instanceof BrowserSessionGoneError)) throw error;
490
- await _assertClassBrand(_Browser_brand, this, _retireIfCurrent).call(this, resolved.sessionId);
491
- resolved = await this.resolve();
492
- cdp = await _assertClassBrand(_Browser_brand, this, _open).call(this, resolved);
493
- }
494
- try {
495
- const entered = await _assertClassBrand(_Browser_brand, this, _enterScope).call(this, scope, resolved.sessionId);
496
- return _assertClassBrand(_Browser_brand, this, _connection).call(this, resolved, scope, cdp, entered);
497
- } catch (error) {
498
- cdp.disconnect();
499
- throw error;
500
- }
501
- }
502
- /**
503
- * Start a session on this browser for one run: connects on its first
504
- * call, resolves `sessionId: "active"` to the scope's tab, and reports
505
- * what happened to the browser when you close it. `browserTool` opens
506
- * one per run.
507
- */
508
- session(options) {
509
- return new BrowserSession(this, options);
510
- }
511
- /**
512
- * Close the browser: retire the record (so the next resolve reports
513
- * `restarted: true`) and close its provider session. Returns `false` when
514
- * there was nothing to close.
515
- *
516
- * The provider close is best-effort: the retired record is the durable
517
- * outcome, and a browser whose close failed is unreachable through this
518
- * store, so the provider reclaims it once idle (Browser Run: after
519
- * `keepAliveMs`, at most 20 minutes).
520
- */
521
- async close() {
522
- let stored;
523
- const lock = await _get_sessionStore.call(_assertClassBrand(_Browser_brand, this)).acquireLock(_classPrivateFieldGet2(_key, this));
524
- try {
525
- const current = await _get_sessionStore.call(_assertClassBrand(_Browser_brand, this)).get(_classPrivateFieldGet2(_key, this));
526
- if (!current) return false;
527
- stored = current;
528
- await _assertClassBrand(_Browser_brand, this, _retire).call(this, current);
529
- } finally {
530
- await lock.release();
531
- }
532
- try {
533
- await _classPrivateFieldGet2(_adapter, this).close(stored.sessionId);
534
- } catch (error) {
535
- console.warn(`[agents/browser] Failed to close browser session ${stored.sessionId}`, error);
536
- }
537
- return true;
538
- }
539
- /**
540
- * Mint Live View URLs for the browser's open tabs, fresh from a target
541
- * listing. `undefined` when the browser was never created, is closed, or
542
- * is gone. The URLs are bearer credentials with a short connect window
543
- * (~5 min) — hand them to a trusted human, never to the model, and never
544
- * store them: re-mint instead.
545
- */
546
- async liveView(options) {
547
- const entry = await _get_sessionStore.call(_assertClassBrand(_Browser_brand, this)).get(_classPrivateFieldGet2(_key, this));
548
- if (!entry) return void 0;
549
- const view = await _classPrivateFieldGet2(_adapter, this).liveView(entry.sessionId, options?.mode);
550
- if (!view) return void 0;
551
- try {
552
- if (!await _assertClassBrand(_Browser_brand, this, _touch).call(this, entry.sessionId)) return void 0;
553
- } catch (error) {
554
- console.warn(`[agents/browser] Failed to refresh activity for browser "${this.name}"`, error);
555
- }
556
- return view;
557
- }
558
- /**
559
- * The browser's internal hostnames, or `undefined` when its provider has
560
- * none. See {@link BrowserInternalHosts}.
561
- */
562
- get internalHosts() {
563
- const config = _classPrivateFieldGet2(_adapter, this).internalHosts;
564
- if (!config) return void 0;
565
- const hosts = config.hosts;
566
- const describe = () => Object.entries(hosts).map(([host, entry]) => ({
567
- host,
568
- url: `http://${host}/`,
569
- ...entry.description ? { description: entry.description } : {},
570
- assignable: entry.target !== void 0,
571
- ...entry.target !== void 0 ? { targetSchema: targetJsonSchema(host, entry.target) } : {}
572
- }));
573
- const assignable = (host) => {
574
- const entry = hosts[host];
575
- if (!entry || !Object.hasOwn(hosts, host)) throw new Error(`"${host}" isn't an internal hostname. The hostnames are: ${Object.keys(hosts).join(", ")}`);
576
- if (entry.target === void 0) throw new Error(`"${host}" always serves the same thing; it has no target to assign`);
577
- return entry.target;
578
- };
579
- return {
580
- describe,
581
- list: async () => {
582
- const prefix = internalHostTargetsPrefix(this.name);
583
- const stored = await this.lifecycle.storage.list({ prefix });
584
- return describe().map((info) => {
585
- const key = prefix + info.host;
586
- return stored.has(key) ? {
587
- ...info,
588
- target: stored.get(key)
589
- } : info;
590
- });
591
- },
592
- assign: async (host, target) => {
593
- const schema = assignable(host);
594
- if (target === void 0) throw new Error(`browser.assignHost needs a target for ${host}; use browser.clearHost to unassign it`);
595
- const json = JSON.parse(JSON.stringify(target));
596
- const checked = await validateTarget(schema, json);
597
- if (!checked.ok) throw new Error(`Invalid target for ${host}: ${checked.error}`);
598
- await this.lifecycle.storage.put(_assertClassBrand(_Browser_brand, this, _targetKey).call(this, host), json);
599
- return { url: `http://${host}/` };
600
- },
601
- clear: async (host) => {
602
- assignable(host);
603
- return this.lifecycle.storage.delete(_assertClassBrand(_Browser_brand, this, _targetKey).call(this, host));
604
- }
605
- };
606
- }
607
- /**
608
- * Serve one browser request to an internal hostname. `InternalHostRouter`
609
- * calls the agent's `fetchInternalHost()` with the message; `Agent` passes
610
- * it here on its own. A plain Durable Object passes it on itself:
611
- *
612
- * ```ts
613
- * fetchInternalHost(message: InternalHostMessage) {
614
- * return this.browser.fetchInternalHost(message);
615
- * }
616
- * ```
617
- *
618
- * Answers 502 with the reason when this browser doesn't serve the host.
619
- */
620
- async fetchInternalHost(message) {
621
- if (message.browser !== this.name) return internalHostError(502, `${message.host} belongs to browser "${message.browser}", but was passed to browser "${this.name}"`);
622
- return _assertClassBrand(_Browser_brand, this, _serveInternalHost).call(this, message.host, message.request);
623
- }
624
- /**
625
- * `Agent.fetchInternalHost()` routes here through Lifecycle, so `Agent`
626
- * needn't import the browser.
627
- *
628
- * @internal Called by Lifecycle; not part of the host API.
629
- */
630
- async onRoute(context) {
631
- const { payload } = context;
632
- if (!isInternalHostMessage(payload)) throw new Error(`Browser "${this.name}" got an unknown routed message`);
633
- return this.fetchInternalHost(payload);
634
- }
635
- };
636
- function _connection(resolved, scope, cdp, entered) {
637
- const { sessionId } = resolved;
638
- return {
639
- name: resolved.name,
640
- sessionId,
641
- scope,
642
- restarted: entered.restarted,
643
- activeTargetId: entered.activeTargetId,
644
- cdp,
645
- setActiveTarget: (targetId) => _assertClassBrand(_Browser_brand, this, _updateScope).call(this, scope, sessionId, targetId),
646
- targetsInOtherScopes: async () => activeTargets(await _assertClassBrand(_Browser_brand, this, _listScopes).call(this), scope, sessionId),
647
- spec: () => _classPrivateFieldGet2(_adapter, this).spec(sessionId)
648
- };
649
- }
650
- async function _open(resolved) {
651
- let lastTouchAt = Date.now();
652
- let touchInFlight = false;
653
- return _classPrivateFieldGet2(_adapter, this).connect(resolved.sessionId, {
654
- timeoutMs: _classPrivateFieldGet2(_options, this).timeoutMs,
655
- onActivity: () => {
656
- const now = Date.now();
657
- if (touchInFlight || now - lastTouchAt < _get_touchIntervalMs.call(_assertClassBrand(_Browser_brand, this))) return;
658
- touchInFlight = true;
659
- lastTouchAt = now;
660
- _assertClassBrand(_Browser_brand, this, _touch).call(this, resolved.sessionId).catch((error) => {
661
- console.warn(`[agents/browser] Failed to refresh activity for browser "${this.name}"`, error);
662
- }).finally(() => {
663
- touchInFlight = false;
664
- });
665
- }
666
- });
667
- }
668
- async function _serveInternalHost(host, request) {
669
- const hosts = _classPrivateFieldGet2(_adapter, this).internalHosts?.hosts;
670
- const entry = hosts && Object.hasOwn(hosts, host) ? hosts[host] : void 0;
671
- if (!entry?.fetch) return internalHostError(502, `${host} is no longer an internal hostname of browser "${this.name}"`);
672
- let target;
673
- if (entry.target !== void 0) {
674
- const assigned = await this.lifecycle.storage.get(_assertClassBrand(_Browser_brand, this, _targetKey).call(this, host));
675
- if (assigned === void 0) return internalHostError(502, `${host} isn't pointed anywhere yet. Call browser.assignHost({ host: "${host}", target }) first.`);
676
- const checked = await validateTarget(entry.target, assigned);
677
- if (!checked.ok) return internalHostError(502, `${host}'s target no longer matches its schema (${checked.error}). Call browser.assignHost again.`);
678
- target = checked.value;
679
- }
680
- const fetch = entry.fetch;
681
- try {
682
- const response = await this.lifecycle.runInHostContext(() => fetch(request, target), { request });
683
- if (response instanceof Response) return response;
684
- return internalHostError(502, `${host}: its fetch didn't return a Response`);
685
- } catch (error) {
686
- console.error(`[agents/browser] ${host}: its fetch threw`, error);
687
- return internalHostError(502, `${host}: its fetch failed`);
688
- }
689
- }
690
- /**
691
- * Which agent and browser the session's routes lead back to. `undefined`
692
- * without internal hostnames.
693
- */
694
- function _internalHostOwner() {
695
- if (!_classPrivateFieldGet2(_adapter, this).internalHosts) return void 0;
696
- const services = this.lifecycleServices;
697
- if (!services) throw new Error(`Browser "${this.name}" has internal hostnames, which need it installed with Lifecycle.use()`);
698
- if (services.routes.source !== void 0) throw new Error(`Browser "${this.name}" has internal hostnames, which sub-agents don't support yet`);
699
- return {
700
- className: services.className,
701
- name: services.name,
702
- browser: this.name
703
- };
704
- }
705
- /** The storage key of one host's target. */
706
- function _targetKey(host) {
707
- return internalHostTargetsPrefix(this.name) + host;
708
- }
709
- async function _closeQuietly(sessionId) {
710
- try {
711
- await _classPrivateFieldGet2(_adapter, this).close(sessionId);
712
- } catch (error) {
713
- console.warn(`[agents/browser] Failed to close browser session ${sessionId}`, error);
714
- }
715
- }
716
- /**
717
- * Capped at half the provider's keep-alive window: a browser with
718
- * continuous CDP traffic must never look older than the window the
719
- * provider uses to reclaim it.
720
- */
721
- function _get_touchIntervalMs() {
722
- const interval = _classPrivateFieldGet2(_options, this).touchIntervalMs ?? 6e4;
723
- const { keepAliveMs } = _classPrivateFieldGet2(_adapter, this);
724
- return keepAliveMs === void 0 ? interval : Math.min(interval, Math.floor(keepAliveMs / 2));
725
- }
726
- /** Lazy: `lifecycle.storage` exists only once `Lifecycle.use()` ran. */
727
- function _get_sessionStore() {
728
- _classPrivateFieldGet2(_store, this) ?? _classPrivateFieldSet2(_store, this, _classPrivateFieldGet2(_options, this).store ?? new DurableBrowserSessionStore(this.lifecycle.storage));
729
- return _classPrivateFieldGet2(_store, this);
730
- }
731
- /**
732
- * Refresh `updatedAt` while the record still holds `sessionId`. Returns
733
- * false when a concurrent close or replacement already retired it.
734
- */
735
- function _touch(sessionId) {
736
- return _assertClassBrand(_Browser_brand, this, _update).call(this, sessionId, (current) => ({
737
- ...current,
738
- updatedAt: Date.now()
739
- }));
740
- }
741
- /**
742
- * Rewrite the record only while it still holds `sessionId`: a replaced or
743
- * retired record is never resurrected.
744
- */
745
- async function _update(sessionId, change) {
746
- const lock = await _get_sessionStore.call(_assertClassBrand(_Browser_brand, this)).acquireLock(_classPrivateFieldGet2(_key, this));
747
- try {
748
- const current = await _get_sessionStore.call(_assertClassBrand(_Browser_brand, this)).get(_classPrivateFieldGet2(_key, this));
749
- if (current?.sessionId !== sessionId) return false;
750
- await _get_sessionStore.call(_assertClassBrand(_Browser_brand, this)).set(_classPrivateFieldGet2(_key, this), change(current));
751
- return true;
752
- } finally {
753
- await lock.release();
754
- }
755
- }
756
- function _scopeKey(scope) {
757
- return `${browserScopeKeyPrefix(this.name)}${scope}`;
758
- }
759
- /** The lock every scope record of this browser is written under. */
760
- function _get_scopesLockKey() {
761
- return browserScopeKeyPrefix(this.name);
762
- }
763
- /** Every scope record of this browser, by scope. */
764
- async function _listScopes() {
765
- const prefix = browserScopeKeyPrefix(this.name);
766
- const entries = await _get_sessionStore.call(_assertClassBrand(_Browser_brand, this)).list(prefix);
767
- const scopes = /* @__PURE__ */ new Map();
768
- for (const [key, entry] of entries) scopes.set(key.slice(prefix.length), entry);
769
- return scopes;
770
- }
771
- /**
772
- * Start a connection's scope: a scope whose record names an earlier
773
- * browser was restarted, and its record moves to this one. A new record
774
- * past {@link MAX_BROWSER_SCOPES} evicts the least recently used.
775
- */
776
- async function _enterScope(scope, sessionId) {
777
- const key = _assertClassBrand(_Browser_brand, this, _scopeKey).call(this, scope);
778
- const lock = await _get_sessionStore.call(_assertClassBrand(_Browser_brand, this)).acquireLock(_get_scopesLockKey.call(_assertClassBrand(_Browser_brand, this)));
779
- try {
780
- const entry = await _get_sessionStore.call(_assertClassBrand(_Browser_brand, this)).get(key);
781
- const now = Date.now();
782
- if (entry?.sessionId === sessionId) {
783
- await _get_sessionStore.call(_assertClassBrand(_Browser_brand, this)).set(key, {
784
- ...entry,
785
- updatedAt: now
786
- });
787
- return {
788
- restarted: false,
789
- activeTargetId: entry.activeTargetId
790
- };
791
- }
792
- await _get_sessionStore.call(_assertClassBrand(_Browser_brand, this)).set(key, {
793
- sessionId,
794
- createdAt: now,
795
- updatedAt: now
796
- });
797
- if (!entry) await _assertClassBrand(_Browser_brand, this, _evictScopes).call(this);
798
- return { restarted: entry !== void 0 };
799
- } finally {
800
- await lock.release();
801
- }
802
- }
803
- /** Delete the least recently used scope records past the cap. */
804
- async function _evictScopes() {
805
- const scopes = await _assertClassBrand(_Browser_brand, this, _listScopes).call(this);
806
- if (scopes.size <= 100) return;
807
- const oldest = [...scopes].sort(([, a], [, b]) => a.updatedAt - b.updatedAt).slice(0, scopes.size - 100);
808
- for (const [scope] of oldest) await _get_sessionStore.call(_assertClassBrand(_Browser_brand, this)).delete(_assertClassBrand(_Browser_brand, this, _scopeKey).call(this, scope));
809
- }
810
- /**
811
- * Set a scope's tab (or clear it with `undefined`). Never resurrects:
812
- * does nothing (and returns `false`) once the browser this connection
813
- * resolved was closed or replaced.
814
- */
815
- async function _updateScope(scope, sessionId, targetId) {
816
- const key = _assertClassBrand(_Browser_brand, this, _scopeKey).call(this, scope);
817
- const lock = await _get_sessionStore.call(_assertClassBrand(_Browser_brand, this)).acquireLock(_get_scopesLockKey.call(_assertClassBrand(_Browser_brand, this)));
818
- try {
819
- const current = await _get_sessionStore.call(_assertClassBrand(_Browser_brand, this)).get(_classPrivateFieldGet2(_key, this));
820
- const entry = await _get_sessionStore.call(_assertClassBrand(_Browser_brand, this)).get(key);
821
- if (current?.sessionId !== sessionId || entry?.sessionId !== sessionId) return false;
822
- await _get_sessionStore.call(_assertClassBrand(_Browser_brand, this)).set(key, {
823
- ...entry,
824
- activeTargetId: targetId,
825
- updatedAt: Date.now()
826
- });
827
- return true;
828
- } finally {
829
- await lock.release();
830
- }
831
- }
832
- /** Retire the record if it still holds `sessionId`. */
833
- async function _retireIfCurrent(sessionId) {
834
- const lock = await _get_sessionStore.call(_assertClassBrand(_Browser_brand, this)).acquireLock(_classPrivateFieldGet2(_key, this));
835
- try {
836
- const current = await _get_sessionStore.call(_assertClassBrand(_Browser_brand, this)).get(_classPrivateFieldGet2(_key, this));
837
- if (current?.sessionId === sessionId) await _assertClassBrand(_Browser_brand, this, _retire).call(this, current);
838
- } finally {
839
- await lock.release();
840
- }
841
- }
842
- /**
843
- * Move the record to its retired marker. Callers hold the key lock, so a
844
- * resolver always sees either the record or the marker.
845
- */
846
- async function _retire(current) {
847
- await _get_sessionStore.call(_assertClassBrand(_Browser_brand, this)).set(retiredBrowserSessionKey(this.name), {
848
- ...current,
849
- closedAt: Date.now()
850
- });
851
- await _get_sessionStore.call(_assertClassBrand(_Browser_brand, this)).delete(_classPrivateFieldGet2(_key, this));
852
- }
853
- /**
854
- * Create a provider session (outside any lock) and commit it. The adapter
855
- * applies the provider's creation options. If a concurrent caller
856
- * committed an entry first, theirs wins and the redundant session is
857
- * closed best-effort.
858
- *
859
- * `restarted` is read under the commit lock: a retired marker — left by
860
- * close() or a dead-browser recovery — is evidence a prior browser
861
- * existed, and only first-ever use of the name is not a restart. Markers
862
- * are permanent, so reading at commit time also catches a browser that
863
- * was created and closed while this create was in flight.
864
- */
865
- async function _createAndCommit() {
866
- const info = await _classPrivateFieldGet2(_adapter, this).create({ owner: _assertClassBrand(_Browser_brand, this, _internalHostOwner).call(this) });
867
- const now = Date.now();
868
- const signature = _classPrivateFieldGet2(_adapter, this).internalHostsSignature;
869
- const stored = {
870
- sessionId: info.sessionId,
871
- createdAt: now,
872
- updatedAt: now,
873
- ...signature !== void 0 ? { internalHosts: signature } : {}
874
- };
875
- let winner;
876
- let restarted;
877
- const lock = await _get_sessionStore.call(_assertClassBrand(_Browser_brand, this)).acquireLock(_classPrivateFieldGet2(_key, this));
878
- try {
879
- restarted = await _get_sessionStore.call(_assertClassBrand(_Browser_brand, this)).get(retiredBrowserSessionKey(this.name)) !== void 0;
880
- const current = await _get_sessionStore.call(_assertClassBrand(_Browser_brand, this)).get(_classPrivateFieldGet2(_key, this));
881
- if (current === void 0) await _get_sessionStore.call(_assertClassBrand(_Browser_brand, this)).set(_classPrivateFieldGet2(_key, this), stored);
882
- else winner = current;
883
- } finally {
884
- await lock.release();
885
- }
886
- if (winner) {
887
- try {
888
- await _classPrivateFieldGet2(_adapter, this).close(stored.sessionId);
889
- } catch (error) {
890
- console.warn(`[agents/browser] Failed to close redundant browser session ${stored.sessionId}`, error);
891
- }
892
- return {
893
- session: winner,
894
- restarted
895
- };
896
- }
897
- return {
898
- session: stored,
899
- restarted
900
- };
901
- }
902
- async function _readStored() {
903
- const lock = await _get_sessionStore.call(_assertClassBrand(_Browser_brand, this)).acquireLock(_classPrivateFieldGet2(_key, this));
904
- try {
905
- return await _get_sessionStore.call(_assertClassBrand(_Browser_brand, this)).get(_classPrivateFieldGet2(_key, this));
906
- } finally {
907
- await lock.release();
908
- }
909
- }
910
- /** A store record without fields that belong to scope records. */
911
- function resolvedFields(session) {
912
- const { sessionId, createdAt, updatedAt } = session;
913
- return {
914
- sessionId,
915
- createdAt,
916
- updatedAt
917
- };
918
- }
919
- /** The tabs scopes other than `scope` are working in, in `sessionId`. */
920
- function activeTargets(scopes, scope, sessionId) {
921
- const targets = /* @__PURE__ */ new Set();
922
- for (const [other, entry] of scopes) {
923
- if (other === scope || entry.sessionId !== sessionId) continue;
924
- if (entry.activeTargetId) targets.add(entry.activeTargetId);
925
- }
926
- return targets;
927
- }
928
- //#endregion
929
- export { InternalHostRouter as a, browserRun as i, DEFAULT_BROWSER_SCOPE as n, MAX_INTERNAL_HOSTS as o, MAX_BROWSER_SCOPES as r, Browser as t };
930
-
931
- //# sourceMappingURL=browser-1eUbPvC2.js.map