cdp-toolkit 3.0.3 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -11,11 +11,308 @@ var __esm = (fn, res, err) => () => {
11
11
  return res;
12
12
  };
13
13
 
14
- // src/leases.ts
14
+ // src/endpoints.ts
15
15
  import { AsyncLocalStorage } from "node:async_hooks";
16
+ import { readFileSync } from "node:fs";
17
+ function checkName(name, where) {
18
+ if (!NAME_RE.test(name)) {
19
+ throw new EndpointConfigError(`${where}: endpoint name '${name}' is invalid; names are letters, digits and '_' only (no '-', '/', ':' or spaces)`);
20
+ }
21
+ }
22
+ function sameBase(a, b) {
23
+ return a.replace(/\/+$/, "") === b.replace(/\/+$/, "");
24
+ }
25
+ function parseBase(raw, where) {
26
+ let url;
27
+ try {
28
+ url = new URL(raw);
29
+ } catch {
30
+ throw new EndpointConfigError(`${where}: '${raw}' is not a valid URL (expected e.g. http://127.0.0.1:9222)`);
31
+ }
32
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
33
+ throw new EndpointConfigError(`${where}: '${raw}' must be an http:// or https:// DevTools origin, not ${url.protocol}`);
34
+ }
35
+ if (url.hash)
36
+ throw new EndpointConfigError(`${where}: '${raw}' must not carry a #fragment`);
37
+ let mode;
38
+ for (const [key, value] of url.searchParams) {
39
+ if (key !== "mode") {
40
+ throw new EndpointConfigError(`${where}: unknown query parameter '${key}' in '${raw}' (only ?mode=read or ?mode=write is understood)`);
41
+ }
42
+ if (value !== "read" && value !== "write") {
43
+ throw new EndpointConfigError(`${where}: unknown mode '${value}' in '${raw}' (use mode=read or mode=write)`);
44
+ }
45
+ mode = value;
46
+ }
47
+ const path = url.pathname.replace(/\/+$/, "");
48
+ return { base: `${url.protocol}//${url.host}${path}`, mode };
49
+ }
50
+ function parseEnvString(spec) {
51
+ const out = [];
52
+ const seen = new Set;
53
+ for (const part of spec.split(",")) {
54
+ const entry = part.trim();
55
+ if (!entry)
56
+ continue;
57
+ const eq = entry.indexOf("=");
58
+ if (eq <= 0) {
59
+ throw new EndpointConfigError(`CDP_ENDPOINTS: entry '${entry}' is not name=url (e.g. teams=http://127.0.0.1:9333)`);
60
+ }
61
+ const name = entry.slice(0, eq).trim();
62
+ checkName(name, "CDP_ENDPOINTS");
63
+ if (seen.has(name))
64
+ throw new EndpointConfigError(`CDP_ENDPOINTS: duplicate endpoint name '${name}'`);
65
+ seen.add(name);
66
+ const { base, mode } = parseBase(entry.slice(eq + 1).trim(), `CDP_ENDPOINTS endpoint '${name}'`);
67
+ out.push({ name, base, readOnly: mode === "read" });
68
+ }
69
+ return out;
70
+ }
71
+ function parseFile(path) {
72
+ let text;
73
+ try {
74
+ text = readFileSync(path, "utf8");
75
+ } catch (err) {
76
+ const code = err.code ?? String(err);
77
+ throw new EndpointConfigError(`CDP_ENDPOINTS_FILE: cannot read '${path}' (${code})`);
78
+ }
79
+ let json;
80
+ try {
81
+ json = JSON.parse(text);
82
+ } catch (err) {
83
+ throw new EndpointConfigError(`CDP_ENDPOINTS_FILE: '${path}' is not valid JSON (${err instanceof Error ? err.message : String(err)})`);
84
+ }
85
+ const where = `CDP_ENDPOINTS_FILE '${path}'`;
86
+ if (!json || typeof json !== "object" || Array.isArray(json)) {
87
+ throw new EndpointConfigError(`${where}: top level must be an object {"default"?, "endpoints": {...}}`);
88
+ }
89
+ const top = json;
90
+ for (const key of Object.keys(top)) {
91
+ if (key !== "default" && key !== "endpoints")
92
+ throw new EndpointConfigError(`${where}: unknown top-level key '${key}'`);
93
+ }
94
+ if (top.default !== undefined && typeof top.default !== "string") {
95
+ throw new EndpointConfigError(`${where}: "default" must be an endpoint name string`);
96
+ }
97
+ const raw = top.endpoints ?? {};
98
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
99
+ throw new EndpointConfigError(`${where}: "endpoints" must be an object keyed by endpoint name`);
100
+ }
101
+ const endpoints = [];
102
+ for (const [name, value] of Object.entries(raw)) {
103
+ checkName(name, where);
104
+ const at = `${where} endpoint '${name}'`;
105
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
106
+ throw new EndpointConfigError(`${at}: must be an object like {"base":"http://127.0.0.1:9333"}`);
107
+ }
108
+ const v = value;
109
+ for (const key of Object.keys(v)) {
110
+ if (key !== "base" && key !== "readOnly" && key !== "mode") {
111
+ throw new EndpointConfigError(`${at}: unknown key '${key}' (known: base, readOnly, mode)`);
112
+ }
113
+ }
114
+ if (typeof v.base !== "string")
115
+ throw new EndpointConfigError(`${at}: "base" is required and must be a URL string`);
116
+ if (v.readOnly !== undefined && typeof v.readOnly !== "boolean")
117
+ throw new EndpointConfigError(`${at}: "readOnly" must be a boolean`);
118
+ if (v.mode !== undefined && v.mode !== "read" && v.mode !== "write") {
119
+ throw new EndpointConfigError(`${at}: unknown mode '${String(v.mode)}' (use "read" or "write")`);
120
+ }
121
+ const parsed = parseBase(v.base, at);
122
+ const votes = [parsed.mode, v.mode, v.readOnly === undefined ? undefined : v.readOnly ? "read" : "write"].filter((x) => x !== undefined);
123
+ if (new Set(votes).size > 1)
124
+ throw new EndpointConfigError(`${at}: readOnly / mode settings contradict each other`);
125
+ endpoints.push({ name, base: parsed.base, readOnly: votes[0] === "read" });
126
+ }
127
+ return { endpoints, defaultName: top.default };
128
+ }
129
+ function loadEndpoints(env = process.env) {
130
+ const fromEnv = env.CDP_ENDPOINTS !== undefined ? parseEnvString(env.CDP_ENDPOINTS) : [];
131
+ const file = env.CDP_ENDPOINTS_FILE ? parseFile(env.CDP_ENDPOINTS_FILE) : { endpoints: [], defaultName: undefined };
132
+ const merged = new Map;
133
+ for (const ep of fromEnv)
134
+ merged.set(ep.name, ep);
135
+ for (const ep of file.endpoints) {
136
+ const prior = merged.get(ep.name);
137
+ if (prior && (prior.base !== ep.base || prior.readOnly !== ep.readOnly)) {
138
+ throw new EndpointConfigError(`endpoint '${ep.name}' is defined differently in CDP_ENDPOINTS (${prior.base}${prior.readOnly ? " read-only" : ""}) and CDP_ENDPOINTS_FILE (${ep.base}${ep.readOnly ? " read-only" : ""})`);
139
+ }
140
+ if (!prior)
141
+ merged.set(ep.name, ep);
142
+ }
143
+ const cdpBase = env.CDP_BASE;
144
+ if (cdpBase !== undefined) {
145
+ const configured = merged.get("default");
146
+ if (configured && !sameBase(configured.base, cdpBase)) {
147
+ throw new EndpointConfigError(`CDP_BASE (${cdpBase}) and the configured endpoint 'default' (${configured.base}) disagree; drop one or make them match`);
148
+ }
149
+ merged.set("default", { name: "default", base: cdpBase, readOnly: configured?.readOnly ?? false });
150
+ }
151
+ const defaultName = file.defaultName ?? "default";
152
+ if (!merged.has(defaultName)) {
153
+ if (file.defaultName !== undefined) {
154
+ throw new EndpointConfigError(`CDP_ENDPOINTS_FILE names default endpoint '${file.defaultName}', which is not defined (known: ${[...merged.keys()].join(", ") || "none"})`);
155
+ }
156
+ merged.set("default", { name: "default", base: DEFAULT_CDP_BASE, readOnly: false });
157
+ }
158
+ const def = merged.get(defaultName);
159
+ const byName = new Map([[def.name, def]]);
160
+ for (const [name, ep] of merged)
161
+ if (name !== def.name)
162
+ byName.set(name, ep);
163
+ return { default: def, byName };
164
+ }
165
+ function signature(env) {
166
+ return JSON.stringify([env.CDP_BASE ?? null, env.CDP_ENDPOINTS ?? null, env.CDP_ENDPOINTS_FILE ?? null]);
167
+ }
168
+ function endpointConfig() {
169
+ const sig = signature(process.env);
170
+ if (cache?.sig === sig)
171
+ return cache.config;
172
+ const config = loadEndpoints(process.env);
173
+ cache = { sig, config };
174
+ return config;
175
+ }
176
+ function defaultEndpoint() {
177
+ return endpointConfig().default;
178
+ }
179
+ function allEndpoints() {
180
+ return [...endpointConfig().byName.values()];
181
+ }
182
+ function getEndpoint(name) {
183
+ const { byName } = endpointConfig();
184
+ const ep = byName.get(name);
185
+ if (!ep) {
186
+ throw new EndpointConfigError(`unknown endpoint '${name}' (known: ${[...byName.keys()].join(", ")}). Configure it with CDP_ENDPOINTS or CDP_ENDPOINTS_FILE.`);
187
+ }
188
+ return ep;
189
+ }
190
+ function leaseNamespace(ep) {
191
+ const { default: def, byName } = endpointConfig();
192
+ if (sameBase(ep.base, def.base))
193
+ return;
194
+ for (const other of byName.values())
195
+ if (sameBase(other.base, ep.base))
196
+ return other.name;
197
+ return ep.name;
198
+ }
199
+ function hasEndpointPrefix(target) {
200
+ return typeof target === "string" && target.startsWith(ENDPOINT_PREFIX);
201
+ }
202
+ function splitEndpointSelector(target) {
203
+ if (!hasEndpointPrefix(target))
204
+ return { endpoint: defaultEndpoint(), rest: target };
205
+ const body = target.slice(ENDPOINT_PREFIX.length);
206
+ const slash = body.indexOf("/");
207
+ const name = slash < 0 ? body : body.slice(0, slash);
208
+ if (!name)
209
+ throw new EndpointConfigError(`selector '${target}' has an empty endpoint name; use endpoint:<name>/<selector>`);
210
+ const rest = slash < 0 ? undefined : body.slice(slash + 1);
211
+ return { endpoint: getEndpoint(name), rest: rest === "" ? undefined : rest };
212
+ }
213
+ function usesEndpointArgs(args) {
214
+ if (!args || typeof args !== "object")
215
+ return false;
216
+ const a = args;
217
+ return SELECTOR_KEYS.some((k) => hasEndpointPrefix(a[k])) || a.endpoint !== undefined || a.allEndpoints === true;
218
+ }
219
+ function stripEndpointArgs(args) {
220
+ if (!args || typeof args !== "object" || Array.isArray(args))
221
+ return { endpoint: defaultEndpoint(), args };
222
+ const a = args;
223
+ const picks = [];
224
+ let out;
225
+ for (const key of SELECTOR_KEYS) {
226
+ const v = a[key];
227
+ if (!hasEndpointPrefix(v))
228
+ continue;
229
+ const { endpoint, rest } = splitEndpointSelector(v);
230
+ picks.push({ from: `${key} '${v}'`, endpoint });
231
+ out ??= { ...a };
232
+ if (rest === undefined)
233
+ delete out[key];
234
+ else
235
+ out[key] = rest;
236
+ }
237
+ if (a.endpoint !== undefined) {
238
+ if (typeof a.endpoint !== "string" || a.endpoint === "") {
239
+ throw new EndpointConfigError("`endpoint` must be a non-empty endpoint name string");
240
+ }
241
+ picks.push({ from: `endpoint '${a.endpoint}'`, endpoint: getEndpoint(a.endpoint) });
242
+ out ??= { ...a };
243
+ delete out.endpoint;
244
+ }
245
+ const token = leaseTokenNamespace(a.lease);
246
+ if (!picks.length) {
247
+ if (token?.ns === undefined)
248
+ return { endpoint: defaultEndpoint(), args };
249
+ return { endpoint: endpointForNamespace(token.ns), args };
250
+ }
251
+ const first = picks[0];
252
+ for (const p of picks.slice(1)) {
253
+ if (p.endpoint.name !== first.endpoint.name) {
254
+ throw new EndpointConfigError(`conflicting endpoints: ${first.from} vs ${p.from}; name one endpoint per call`);
255
+ }
256
+ }
257
+ if (token && leaseNamespace(first.endpoint) !== token.ns) {
258
+ throw new EndpointConfigError(`conflicting endpoints: ${first.from} vs the lease token, which belongs to ${token.ns === undefined ? "the default endpoint" : `endpoint '${token.ns}'`}; name one endpoint per call`);
259
+ }
260
+ return { endpoint: first.endpoint, args: out ?? a };
261
+ }
262
+ function leaseTokenNamespace(lease) {
263
+ if (typeof lease !== "string")
264
+ return null;
265
+ const colon = lease.indexOf(":");
266
+ if (colon <= 0)
267
+ return null;
268
+ const head = lease.slice(0, colon);
269
+ if (head === "chrome")
270
+ return { ns: undefined };
271
+ if (!head.startsWith("chrome@"))
272
+ return null;
273
+ const ns = head.slice("chrome@".length);
274
+ return NAME_RE.test(ns) ? { ns } : null;
275
+ }
276
+ function endpointForNamespace(ns) {
277
+ for (const ep of endpointConfig().byName.values())
278
+ if (leaseNamespace(ep) === ns)
279
+ return ep;
280
+ throw new EndpointConfigError(`the lease token belongs to endpoint '${ns}', which is not configured (known: ${[...endpointConfig().byName.keys()].join(", ")})`);
281
+ }
282
+ function currentEndpoint() {
283
+ return endpointScope.getStore() ?? defaultEndpoint();
284
+ }
285
+ function isDefaultEndpoint(ep) {
286
+ return ep.name === defaultEndpoint().name;
287
+ }
288
+ function withEndpointScope(ep, fn) {
289
+ return endpointScope.run(ep, fn);
290
+ }
291
+ var EndpointConfigError, DEFAULT_CDP_BASE = "http://127.0.0.1:9222", ENDPOINT_PREFIX = "endpoint:", NAME_RE, cache, SELECTOR_KEYS, ENDPOINTS_FIREFOX_MESSAGE = "named CDP endpoints (an 'endpoint:<name>/' selector prefix, the endpoint arg, list_pages allEndpoints) need the Chrome backend; the Firefox BiDi backend has one session and no endpoints", endpointScope;
292
+ var init_endpoints = __esm(() => {
293
+ EndpointConfigError = class EndpointConfigError extends Error {
294
+ constructor(message) {
295
+ super(message);
296
+ this.name = "EndpointConfigError";
297
+ }
298
+ };
299
+ NAME_RE = /^[A-Za-z0-9_]+$/;
300
+ SELECTOR_KEYS = ["target", "targetId"];
301
+ endpointScope = new AsyncLocalStorage;
302
+ });
303
+
304
+ // src/leases.ts
305
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
16
306
  import { randomBytes } from "node:crypto";
17
307
  import { mkdir, readFile, readdir, unlink, writeFile } from "node:fs/promises";
18
308
  import { join } from "node:path";
309
+ function chromeLeaseBackend(ep = currentEndpoint()) {
310
+ const ns = leaseNamespace(ep);
311
+ return ns === undefined ? "chrome" : `chrome@${ns}`;
312
+ }
313
+ function isLeaseBackend(value) {
314
+ return BACKEND_KEY_RE.test(value);
315
+ }
19
316
  function leaseDir() {
20
317
  return process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
21
318
  }
@@ -52,7 +349,7 @@ function tokenParts(token) {
52
349
  if (first <= 0 || last <= first)
53
350
  return;
54
351
  const backend = token.slice(0, first);
55
- if (backend !== "chrome" && backend !== "firefox")
352
+ if (!isLeaseBackend(backend))
56
353
  return;
57
354
  const targetId = token.slice(first + 1, last);
58
355
  const nonce = token.slice(last + 1);
@@ -273,8 +570,10 @@ async function listLeases(opts = {}) {
273
570
  }
274
571
  return out;
275
572
  }
276
- var DEFAULT_LEASE_TTL_MS = 900000, longLived = false, LeaseConflictError, leaseScope, LEASE_FILE_RE;
573
+ var BACKEND_KEY_SOURCE = "chrome@[A-Za-z0-9_]+|chrome|firefox", BACKEND_KEY_RE, DEFAULT_LEASE_TTL_MS = 900000, longLived = false, LeaseConflictError, leaseScope, LEASE_FILE_RE;
277
574
  var init_leases = __esm(() => {
575
+ init_endpoints();
576
+ BACKEND_KEY_RE = new RegExp(`^(?:${BACKEND_KEY_SOURCE})$`);
278
577
  LeaseConflictError = class LeaseConflictError extends Error {
279
578
  targetId;
280
579
  holder;
@@ -285,8 +584,8 @@ var init_leases = __esm(() => {
285
584
  this.name = "LeaseConflictError";
286
585
  }
287
586
  };
288
- leaseScope = new AsyncLocalStorage;
289
- LEASE_FILE_RE = /^lease-(chrome|firefox)-(.+)\.json$/;
587
+ leaseScope = new AsyncLocalStorage2;
588
+ LEASE_FILE_RE = new RegExp(`^lease-(${BACKEND_KEY_SOURCE})-(.+)\\.json$`);
290
589
  });
291
590
 
292
591
  // src/origins.ts
@@ -416,7 +715,7 @@ async function resolveLiveLabel(backend, label, liveIds) {
416
715
  var ORIGIN_FILE_RE;
417
716
  var init_origins = __esm(() => {
418
717
  init_leases();
419
- ORIGIN_FILE_RE = /^origin-(chrome|firefox)-(.+)\.json$/;
718
+ ORIGIN_FILE_RE = new RegExp(`^origin-(${BACKEND_KEY_SOURCE})-(.+)\\.json$`);
420
719
  });
421
720
 
422
721
  // src/workers.ts
@@ -631,7 +930,7 @@ class CdpConnection {
631
930
  }
632
931
  }
633
932
  async function httpJson(path) {
634
- const res = await fetch(`${BASE}${path}`);
933
+ const res = await fetch(`${currentEndpoint().base}${path}`);
635
934
  if (!res.ok)
636
935
  throw new CdpError(`${path} -> HTTP ${res.status}`);
637
936
  return await res.json();
@@ -648,7 +947,7 @@ async function resolveTarget(selector, opts = {}) {
648
947
  const hit = await pickTarget(targets, selector);
649
948
  if (isWorkerTargetType(hit.type))
650
949
  return hit;
651
- await assertLeaseOk("chrome", hit.id, { lease: opts.lease, url: hit.url, title: hit.title });
950
+ await assertLeaseOk(chromeLeaseBackend(), hit.id, { lease: opts.lease, url: hit.url, title: hit.title });
652
951
  return hit;
653
952
  }
654
953
  async function pickTarget(targets, selector) {
@@ -680,7 +979,7 @@ async function pickTarget(targets, selector) {
680
979
  }
681
980
  if (selector.startsWith("label:")) {
682
981
  const label = selector.slice(6);
683
- const { matchIds, knownLabels } = await resolveLiveLabel("chrome", label, pages.map((t) => t.id));
982
+ const { matchIds, knownLabels } = await resolveLiveLabel(chromeLeaseBackend(), label, pages.map((t) => t.id));
684
983
  if (matchIds.length > 1) {
685
984
  throw new CdpError(`label 'label:${label}' matches more than one live target: ${matchIds.join(", ")}. Resolve by target id instead.`);
686
985
  }
@@ -738,9 +1037,16 @@ var BASE, DEFAULT_TIMEOUT_MS, CdpError;
738
1037
  var init_client = __esm(() => {
739
1038
  init_leases();
740
1039
  init_origins();
1040
+ init_endpoints();
741
1041
  init_workers();
742
1042
  init_frames();
743
- BASE = process.env.CDP_BASE ?? "http://127.0.0.1:9222";
1043
+ BASE = (() => {
1044
+ try {
1045
+ return defaultEndpoint().base;
1046
+ } catch {
1047
+ return process.env.CDP_BASE ?? DEFAULT_CDP_BASE;
1048
+ }
1049
+ })();
744
1050
  DEFAULT_TIMEOUT_MS = Number(process.env.CDP_TIMEOUT_MS ?? 15000);
745
1051
  CdpError = class CdpError extends Error {
746
1052
  code;
@@ -3744,6 +4050,7 @@ var init_driver2 = __esm(() => {
3744
4050
  // src/cdp/driver.ts
3745
4051
  init_client();
3746
4052
  init_leases();
4053
+ init_endpoints();
3747
4054
  init_activity();
3748
4055
 
3749
4056
  // src/tools/snapshot.ts
@@ -4231,7 +4538,7 @@ class CdpPageDriver {
4231
4538
  await this.conn.send(`${name}.enable`);
4232
4539
  }
4233
4540
  async dispatchInput(method, params = {}) {
4234
- return sendInput(this.conn, "chrome", this.info.id, method, params);
4541
+ return sendInput(this.conn, chromeLeaseBackend(), this.info.id, method, params);
4235
4542
  }
4236
4543
  async ensureDomainSoft(name) {
4237
4544
  if (this.enabledDomains.has(name))
@@ -4825,6 +5132,10 @@ class CdpPageDriver {
4825
5132
  }
4826
5133
  }
4827
5134
  var beaconSessions = new BeaconSessions((conn) => conn.close());
5135
+ function beaconKey(targetId) {
5136
+ const backend = chromeLeaseBackend(currentEndpoint());
5137
+ return backend === "chrome" ? targetId : `${backend}\x00${targetId}`;
5138
+ }
4828
5139
  async function targetWsUrl(targetId) {
4829
5140
  const hit = (await listTargets()).find((t) => t.id === targetId);
4830
5141
  return hit?.webSocketDebuggerUrl;
@@ -4926,7 +5237,7 @@ class CdpBrowserDriver {
4926
5237
  return withBrowserConn(async (conn) => {
4927
5238
  const res = await conn.send("Target.closeTarget", { targetId: id });
4928
5239
  if (res.success !== false)
4929
- beaconSessions.drop(id);
5240
+ beaconSessions.drop(beaconKey(id));
4930
5241
  return { success: res.success ?? true };
4931
5242
  });
4932
5243
  }
@@ -4944,12 +5255,13 @@ class CdpBrowserDriver {
4944
5255
  return new CdpPageDriver(conn, target, this);
4945
5256
  }
4946
5257
  async installActivityBeacon(targetId) {
4947
- const held = beaconSessions.get(targetId);
5258
+ const key = beaconKey(targetId);
5259
+ const held = beaconSessions.get(key);
4948
5260
  if (held) {
4949
5261
  const rearmed = await held.send("Runtime.evaluate", { expression: BEACON_SOURCE, returnByValue: true }).then(() => true).catch(() => false);
4950
5262
  if (rearmed)
4951
5263
  return true;
4952
- beaconSessions.drop(targetId);
5264
+ beaconSessions.drop(key);
4953
5265
  }
4954
5266
  const wsUrl = await targetWsUrl(targetId).catch(() => {
4955
5267
  return;
@@ -4969,16 +5281,17 @@ class CdpBrowserDriver {
4969
5281
  conn.close();
4970
5282
  return false;
4971
5283
  }
4972
- beaconSessions.set(targetId, conn);
5284
+ beaconSessions.set(key, conn);
4973
5285
  return true;
4974
5286
  }
4975
5287
  async readActivityBeacon(targetId) {
4976
- const held = beaconSessions.get(targetId);
5288
+ const key = beaconKey(targetId);
5289
+ const held = beaconSessions.get(key);
4977
5290
  if (held) {
4978
5291
  const value = await readBeaconOver(held);
4979
5292
  if (value !== undefined)
4980
5293
  return value;
4981
- beaconSessions.drop(targetId);
5294
+ beaconSessions.drop(key);
4982
5295
  }
4983
5296
  const wsUrl = await targetWsUrl(targetId).catch(() => {
4984
5297
  return;
@@ -4997,7 +5310,7 @@ class CdpBrowserDriver {
4997
5310
  }
4998
5311
  }
4999
5312
  async probeRenderer(targetId, timeoutMs = RENDERER_PROBE_TIMEOUT_MS) {
5000
- const held = beaconSessions.get(targetId);
5313
+ const held = beaconSessions.get(beaconKey(targetId));
5001
5314
  if (held)
5002
5315
  return probeOver(held, timeoutMs);
5003
5316
  const wsUrl = await targetWsUrl(targetId).catch(() => {
@@ -5030,6 +5343,7 @@ init_activity();
5030
5343
  init_origins();
5031
5344
 
5032
5345
  // src/reap.ts
5346
+ init_endpoints();
5033
5347
  init_leases();
5034
5348
  init_origins();
5035
5349
  function staleAgentTabs(input) {
@@ -5058,6 +5372,11 @@ function reapGraceMs() {
5058
5372
  const raw = Number(process.env.CDP_REAP_GRACE_MS);
5059
5373
  return Number.isFinite(raw) && raw >= 0 ? raw : DEFAULT_REAP_GRACE_MS;
5060
5374
  }
5375
+ function reapAllowed(driver) {
5376
+ if (driver.scheme === "bidi")
5377
+ return true;
5378
+ return !currentEndpoint().readOnly;
5379
+ }
5061
5380
  async function reapStaleAgentTabs(driver, backend) {
5062
5381
  const now = Date.now();
5063
5382
  const livePageIds = (await driver.listPages()).map((p) => p.id);
@@ -5600,6 +5919,7 @@ init_activity();
5600
5919
  init_origins();
5601
5920
  init_workers();
5602
5921
  init_frames();
5922
+ init_endpoints();
5603
5923
  var ARTIFACT_DIR = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
5604
5924
  var STATE_DIR = process.env.CDP_STATE_DIR ?? "/tmp/cdp-toolkit";
5605
5925
 
@@ -5609,7 +5929,7 @@ function target3(p) {
5609
5929
  return { id: p.id, url: p.url, title: p.title };
5610
5930
  }
5611
5931
  function backendOf(driver) {
5612
- return driver.scheme === "bidi" ? "firefox" : "chrome";
5932
+ return driver.scheme === "bidi" ? "firefox" : chromeLeaseBackend();
5613
5933
  }
5614
5934
  async function withPage2(driver, target, fn) {
5615
5935
  const page = await driver.page(target);
@@ -5697,8 +6017,44 @@ async function reapSet(driver, pages, all) {
5697
6017
  }
5698
6018
  }
5699
6019
  async function listPages(driver, args = {}) {
6020
+ const one = { all: args.all, probe: args.probe };
6021
+ if (args.allEndpoints === true) {
6022
+ if (driver.scheme === "bidi")
6023
+ throw new SharedToolError("list_pages: allEndpoints needs the Chrome backend; named endpoints are CDP-only");
6024
+ const results = await Promise.all(allEndpoints().map((ep) => withEndpointScope(ep, () => listPagesOne(driver, one)).then((r) => ({ ep, r }), (e) => ({ ep, error: e instanceof Error ? e.message : String(e) }))));
6025
+ const pages = [];
6026
+ const reaped = [];
6027
+ const endpoints = [];
6028
+ for (const res of results) {
6029
+ const { ep } = res;
6030
+ if ("error" in res) {
6031
+ endpoints.push({ endpoint: ep.name, base: ep.base, readOnly: ep.readOnly, down: true, error: res.error });
6032
+ continue;
6033
+ }
6034
+ for (const p of res.r.pages)
6035
+ pages.push({ ...p, endpoint: ep.name });
6036
+ for (const t of res.r.reaped ?? [])
6037
+ reaped.push({ ...t, endpoint: ep.name });
6038
+ endpoints.push({ endpoint: ep.name, base: ep.base, readOnly: ep.readOnly, count: res.r.count });
6039
+ }
6040
+ return { pages, count: pages.length, ...reaped.length ? { reaped } : {}, endpoints };
6041
+ }
6042
+ const res = await listPagesOne(driver, one);
6043
+ if (driver.scheme !== "bidi") {
6044
+ const ep = currentEndpoint();
6045
+ if (!isDefaultEndpoint(ep)) {
6046
+ return {
6047
+ ...res,
6048
+ pages: res.pages.map((p) => ({ ...p, endpoint: ep.name })),
6049
+ ...res.reaped ? { reaped: res.reaped.map((t) => ({ ...t, endpoint: ep.name })) } : {}
6050
+ };
6051
+ }
6052
+ }
6053
+ return res;
6054
+ }
6055
+ async function listPagesOne(driver, args = {}) {
5700
6056
  const backend = backendOf(driver);
5701
- const reaped = requireLease() ? await reapStaleAgentTabs(driver, backend) : [];
6057
+ const reaped = requireLease() && reapAllowed(driver) ? await reapStaleAgentTabs(driver, backend) : [];
5702
6058
  const reapedIds = new Set(reaped.map((r) => r.targetId));
5703
6059
  const pages = (await driver.listPages({ all: args.all })).filter((p) => !reapedIds.has(p.id));
5704
6060
  const ledger = await originIndex(backend, await reapSet(driver, pages, args.all));
@@ -6339,7 +6695,7 @@ init_leases();
6339
6695
  class LeaseToolError extends Error {
6340
6696
  }
6341
6697
  function backendOf2(driver) {
6342
- return driver.scheme === "bidi" ? "firefox" : "chrome";
6698
+ return driver.scheme === "bidi" ? "firefox" : chromeLeaseBackend();
6343
6699
  }
6344
6700
  async function claimPage(driver, args = {}) {
6345
6701
  const hasTarget = typeof args.target === "string" && args.target.length > 0;
@@ -6424,7 +6780,7 @@ async function releasePage(driver, args = {}) {
6424
6780
  }
6425
6781
  async function listLeasesTool(driver, _args = {}) {
6426
6782
  const backend = backendOf2(driver);
6427
- const reaped = requireLease() ? await reapStaleAgentTabs(driver, backend) : [];
6783
+ const reaped = requireLease() && reapAllowed(driver) ? await reapStaleAgentTabs(driver, backend) : [];
6428
6784
  const reapedIds = new Set(reaped.map((r) => r.targetId));
6429
6785
  const livePages = await driver.listPages();
6430
6786
  const liveIds = livePages.map((p) => p.id);
@@ -7504,11 +7860,12 @@ async function takeHeapsnapshot(args = {}) {
7504
7860
 
7505
7861
  // src/tools/lighthouse.ts
7506
7862
  init_client();
7863
+ init_endpoints();
7507
7864
  import { spawn as spawn2 } from "node:child_process";
7508
7865
  import { mkdir as mkdir10, readFile as readFile7, stat as stat3 } from "node:fs/promises";
7509
7866
  var ARTIFACT_DIR5 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
7510
7867
  function cdpPort() {
7511
- const base = process.env.CDP_BASE ?? "http://127.0.0.1:9222";
7868
+ const base = currentEndpoint().base;
7512
7869
  const m = base.match(/:(\d+)/);
7513
7870
  return m?.[1] ? Number(m[1]) : 9222;
7514
7871
  }
@@ -7645,6 +8002,7 @@ init_network_mock();
7645
8002
  // src/tools/dispatch-mouse.ts
7646
8003
  init_activity();
7647
8004
  init_client();
8005
+ init_leases();
7648
8006
  var CLICK_MODIFIER_BITS2 = { Alt: 1, Control: 2, Meta: 4, Shift: 8 };
7649
8007
  var BUTTONS = new Set(["left", "right", "middle"]);
7650
8008
  var CDP_EVENT_TYPE = {
@@ -7681,7 +8039,7 @@ async function dispatchMouse(args) {
7681
8039
  const params = { type: CDP_EVENT_TYPE[args.action], x: args.x, y: args.y, button, modifiers };
7682
8040
  if (args.action !== "move")
7683
8041
  params.clickCount = args.clickCount ?? 1;
7684
- await sendInput(conn, "chrome", target.id, "Input.dispatchMouseEvent", params);
8042
+ await sendInput(conn, chromeLeaseBackend(), target.id, "Input.dispatchMouseEvent", params);
7685
8043
  return { dispatched: args.action, x: args.x, y: args.y };
7686
8044
  });
7687
8045
  }
@@ -7689,6 +8047,7 @@ async function dispatchMouse(args) {
7689
8047
  // src/tools/focus-emulation.ts
7690
8048
  init_activity();
7691
8049
  init_client();
8050
+ init_leases();
7692
8051
  function validateFocusEmulationArgs(args) {
7693
8052
  if (typeof args.enabled !== "boolean") {
7694
8053
  throw new Error("focus_emulation requires { enabled } of true or false");
@@ -7755,9 +8114,10 @@ async function clickFocusGated(args) {
7755
8114
  const btn = result?.value;
7756
8115
  if (btn && !btn.disabled) {
7757
8116
  const base = { x: btn.x, y: btn.y, button: "left", buttons: 1, clickCount: 1 };
7758
- await sendInput(conn, "chrome", target.id, "Input.dispatchMouseEvent", { type: "mouseMoved", x: btn.x, y: btn.y });
7759
- await sendInput(conn, "chrome", target.id, "Input.dispatchMouseEvent", { ...base, type: "mousePressed" });
7760
- await sendInput(conn, "chrome", target.id, "Input.dispatchMouseEvent", { ...base, type: "mouseReleased" });
8117
+ const backend = chromeLeaseBackend();
8118
+ await sendInput(conn, backend, target.id, "Input.dispatchMouseEvent", { type: "mouseMoved", x: btn.x, y: btn.y });
8119
+ await sendInput(conn, backend, target.id, "Input.dispatchMouseEvent", { ...base, type: "mousePressed" });
8120
+ await sendInput(conn, backend, target.id, "Input.dispatchMouseEvent", { ...base, type: "mouseReleased" });
7761
8121
  return {
7762
8122
  clicked: true,
7763
8123
  x: btn.x,
@@ -7786,12 +8146,16 @@ import { basename, extname, join as join9 } from "node:path";
7786
8146
 
7787
8147
  // src/tools/browser-session.ts
7788
8148
  init_client();
8149
+ init_endpoints();
7789
8150
  import { mkdir as mkdir11 } from "node:fs/promises";
7790
8151
  import { join as join8 } from "node:path";
7791
8152
  var ARTIFACT_DIR6 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
7792
8153
  var DOWNLOADS_DIR = join8(ARTIFACT_DIR6, "downloads");
7793
8154
  var DOWNLOAD_BUFFER_LIMIT = 50;
7794
- var session;
8155
+ var sessions2 = new Map;
8156
+ function sessionKey() {
8157
+ return currentEndpoint().name;
8158
+ }
7795
8159
  function isDisconnect(e) {
7796
8160
  const m = e instanceof Error ? e.message : String(e);
7797
8161
  return /connection (not open|closed)|closed by caller|websocket|ECONNREFUSED|socket/i.test(m);
@@ -7836,13 +8200,15 @@ function subscribe(s) {
7836
8200
  });
7837
8201
  }
7838
8202
  async function getBrowserSession() {
8203
+ const key = sessionKey();
8204
+ const session = sessions2.get(key);
7839
8205
  if (session && !session.dead)
7840
8206
  return session;
7841
8207
  const previousPath = session?.armedPath;
7842
8208
  const conn = await openBrowser();
7843
8209
  const s = { conn, downloads: [], waiters: [], dead: false };
7844
8210
  subscribe(s);
7845
- session = s;
8211
+ sessions2.set(key, s);
7846
8212
  if (previousPath)
7847
8213
  await armDownloadsAt(previousPath);
7848
8214
  return s;
@@ -7873,7 +8239,7 @@ async function armDownloads() {
7873
8239
  return { downloadPath: DOWNLOADS_DIR };
7874
8240
  }
7875
8241
  function pendingDownloads() {
7876
- return (session?.downloads ?? []).filter((d) => d.state === "completed" && !d.consumed);
8242
+ return (sessions2.get(sessionKey())?.downloads ?? []).filter((d) => d.state === "completed" && !d.consumed);
7877
8243
  }
7878
8244
  async function nextCompletedDownload(timeoutMs) {
7879
8245
  const s = await getBrowserSession();
@@ -7897,14 +8263,14 @@ async function nextCompletedDownload(timeoutMs) {
7897
8263
  });
7898
8264
  }
7899
8265
  async function disposeBrowserSession() {
7900
- const s = session;
7901
- session = undefined;
7902
- if (!s)
7903
- return;
7904
- s.dead = true;
7905
- try {
7906
- s.conn.close();
7907
- } catch {}
8266
+ const all = [...sessions2.values()];
8267
+ sessions2.clear();
8268
+ for (const s of all) {
8269
+ s.dead = true;
8270
+ try {
8271
+ s.conn.close();
8272
+ } catch {}
8273
+ }
7908
8274
  }
7909
8275
 
7910
8276
  // src/tools/downloads.ts
@@ -8489,7 +8855,7 @@ init_driver2();
8489
8855
 
8490
8856
  // src/bidi/launch.ts
8491
8857
  import { spawn as spawn4 } from "node:child_process";
8492
- import { existsSync as existsSync2, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
8858
+ import { existsSync as existsSync2, mkdtempSync, readFileSync as readFileSync2, rmSync, writeFileSync } from "node:fs";
8493
8859
  import { createConnection, createServer as createServer2 } from "node:net";
8494
8860
  import { tmpdir } from "node:os";
8495
8861
  import { join as join12 } from "node:path";
@@ -8573,7 +8939,7 @@ var LAUNCH_USER_JS_PREFS = {
8573
8939
  };
8574
8940
  function writeLaunchUserJs(profilePath) {
8575
8941
  const target = join12(profilePath, "user.js");
8576
- const existing = existsSync2(target) ? readFileSync(target, "utf8") : "";
8942
+ const existing = existsSync2(target) ? readFileSync2(target, "utf8") : "";
8577
8943
  const present = new Set;
8578
8944
  for (const line of existing.split(`
8579
8945
  `)) {
@@ -8954,6 +9320,7 @@ var FIREFOX_TOOLS = {
8954
9320
 
8955
9321
  // src/cli.ts
8956
9322
  init_leases();
9323
+ init_endpoints();
8957
9324
 
8958
9325
  // src/manifest.ts
8959
9326
  var MANIFEST = [
@@ -8974,6 +9341,14 @@ var MANIFEST = [
8974
9341
  probe: {
8975
9342
  type: "boolean",
8976
9343
  description: "Probe renderer responsiveness."
9344
+ },
9345
+ endpoint: {
9346
+ type: "string",
9347
+ description: "Named CDP endpoint to list (CDP_ENDPOINTS); default endpoint when omitted."
9348
+ },
9349
+ allEndpoints: {
9350
+ type: "boolean",
9351
+ description: "List every configured endpoint; rows carry endpoint, a down one is reported, not thrown."
8977
9352
  }
8978
9353
  },
8979
9354
  required: [],
@@ -8998,6 +9373,10 @@ var MANIFEST = [
8998
9373
  type: "boolean",
8999
9374
  description: "Claim the new tab."
9000
9375
  },
9376
+ endpoint: {
9377
+ type: "string",
9378
+ description: "Named CDP endpoint to open the tab on (CDP_ENDPOINTS); default endpoint when omitted."
9379
+ },
9001
9380
  label: {
9002
9381
  type: "string",
9003
9382
  description: "Agent lease label."
@@ -9023,7 +9402,7 @@ var MANIFEST = [
9023
9402
  },
9024
9403
  target: {
9025
9404
  type: "string",
9026
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
9405
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9027
9406
  }
9028
9407
  },
9029
9408
  required: [
@@ -9044,7 +9423,7 @@ var MANIFEST = [
9044
9423
  },
9045
9424
  target: {
9046
9425
  type: "string",
9047
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
9426
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9048
9427
  }
9049
9428
  },
9050
9429
  required: [
@@ -9065,7 +9444,7 @@ var MANIFEST = [
9065
9444
  },
9066
9445
  target: {
9067
9446
  type: "string",
9068
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
9447
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9069
9448
  },
9070
9449
  url: {
9071
9450
  type: "string",
@@ -9115,7 +9494,7 @@ var MANIFEST = [
9115
9494
  },
9116
9495
  target: {
9117
9496
  type: "string",
9118
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
9497
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9119
9498
  },
9120
9499
  text: {
9121
9500
  type: "string",
@@ -9148,7 +9527,7 @@ var MANIFEST = [
9148
9527
  },
9149
9528
  target: {
9150
9529
  type: "string",
9151
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
9530
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9152
9531
  },
9153
9532
  wake: {
9154
9533
  type: "boolean",
@@ -9190,7 +9569,7 @@ var MANIFEST = [
9190
9569
  },
9191
9570
  target: {
9192
9571
  type: "string",
9193
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
9572
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9194
9573
  },
9195
9574
  domain: {
9196
9575
  type: "string",
@@ -9221,7 +9600,7 @@ var MANIFEST = [
9221
9600
  },
9222
9601
  target: {
9223
9602
  type: "string",
9224
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
9603
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9225
9604
  },
9226
9605
  name: {
9227
9606
  type: "string",
@@ -9285,7 +9664,7 @@ var MANIFEST = [
9285
9664
  },
9286
9665
  target: {
9287
9666
  type: "string",
9288
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
9667
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9289
9668
  },
9290
9669
  name: {
9291
9670
  type: "string",
@@ -9322,7 +9701,7 @@ var MANIFEST = [
9322
9701
  },
9323
9702
  target: {
9324
9703
  type: "string",
9325
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
9704
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9326
9705
  },
9327
9706
  interactiveOnly: {
9328
9707
  type: "boolean",
@@ -9345,7 +9724,7 @@ var MANIFEST = [
9345
9724
  },
9346
9725
  target: {
9347
9726
  type: "string",
9348
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
9727
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9349
9728
  },
9350
9729
  uid: {
9351
9730
  type: "number",
@@ -9398,7 +9777,7 @@ var MANIFEST = [
9398
9777
  },
9399
9778
  target: {
9400
9779
  type: "string",
9401
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
9780
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9402
9781
  },
9403
9782
  uid: {
9404
9783
  type: "number",
@@ -9425,7 +9804,7 @@ var MANIFEST = [
9425
9804
  },
9426
9805
  target: {
9427
9806
  type: "string",
9428
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
9807
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9429
9808
  },
9430
9809
  from: {
9431
9810
  type: "object",
@@ -9511,7 +9890,7 @@ var MANIFEST = [
9511
9890
  },
9512
9891
  target: {
9513
9892
  type: "string",
9514
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
9893
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9515
9894
  },
9516
9895
  uid: {
9517
9896
  type: "number",
@@ -9554,7 +9933,7 @@ var MANIFEST = [
9554
9933
  },
9555
9934
  target: {
9556
9935
  type: "string",
9557
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
9936
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9558
9937
  },
9559
9938
  action: {
9560
9939
  type: "string",
@@ -9620,7 +9999,7 @@ var MANIFEST = [
9620
9999
  },
9621
10000
  target: {
9622
10001
  type: "string",
9623
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
10002
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9624
10003
  },
9625
10004
  enabled: {
9626
10005
  type: "boolean",
@@ -9645,7 +10024,7 @@ var MANIFEST = [
9645
10024
  },
9646
10025
  target: {
9647
10026
  type: "string",
9648
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
10027
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9649
10028
  },
9650
10029
  selector: {
9651
10030
  type: "string",
@@ -9684,7 +10063,7 @@ var MANIFEST = [
9684
10063
  },
9685
10064
  target: {
9686
10065
  type: "string",
9687
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
10066
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9688
10067
  },
9689
10068
  arm: {
9690
10069
  type: "boolean",
@@ -9711,7 +10090,7 @@ var MANIFEST = [
9711
10090
  },
9712
10091
  target: {
9713
10092
  type: "string",
9714
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
10093
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9715
10094
  },
9716
10095
  permissions: {
9717
10096
  type: "array",
@@ -9745,7 +10124,7 @@ var MANIFEST = [
9745
10124
  },
9746
10125
  target: {
9747
10126
  type: "string",
9748
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
10127
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9749
10128
  },
9750
10129
  uid: {
9751
10130
  type: "number",
@@ -9778,7 +10157,7 @@ var MANIFEST = [
9778
10157
  },
9779
10158
  target: {
9780
10159
  type: "string",
9781
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
10160
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9782
10161
  },
9783
10162
  fields: {
9784
10163
  type: "array",
@@ -9824,7 +10203,7 @@ var MANIFEST = [
9824
10203
  },
9825
10204
  target: {
9826
10205
  type: "string",
9827
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
10206
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9828
10207
  },
9829
10208
  uid: {
9830
10209
  type: "number",
@@ -9857,7 +10236,7 @@ var MANIFEST = [
9857
10236
  },
9858
10237
  target: {
9859
10238
  type: "string",
9860
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
10239
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9861
10240
  },
9862
10241
  key: {
9863
10242
  type: "string",
@@ -9889,7 +10268,7 @@ var MANIFEST = [
9889
10268
  },
9890
10269
  target: {
9891
10270
  type: "string",
9892
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
10271
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9893
10272
  },
9894
10273
  uid: {
9895
10274
  type: "number",
@@ -9925,7 +10304,7 @@ var MANIFEST = [
9925
10304
  },
9926
10305
  target: {
9927
10306
  type: "string",
9928
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
10307
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9929
10308
  },
9930
10309
  format: {
9931
10310
  type: "string",
@@ -9992,7 +10371,7 @@ var MANIFEST = [
9992
10371
  },
9993
10372
  target: {
9994
10373
  type: "string",
9995
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
10374
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9996
10375
  },
9997
10376
  width: {
9998
10377
  type: "number",
@@ -10092,7 +10471,7 @@ var MANIFEST = [
10092
10471
  },
10093
10472
  target: {
10094
10473
  type: "string",
10095
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
10474
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
10096
10475
  },
10097
10476
  width: {
10098
10477
  type: "number",
@@ -10130,7 +10509,7 @@ var MANIFEST = [
10130
10509
  },
10131
10510
  target: {
10132
10511
  type: "string",
10133
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
10512
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
10134
10513
  },
10135
10514
  accept: {
10136
10515
  type: "boolean",
@@ -10167,7 +10546,7 @@ var MANIFEST = [
10167
10546
  },
10168
10547
  target: {
10169
10548
  type: "string",
10170
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
10549
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
10171
10550
  },
10172
10551
  reload: {
10173
10552
  type: "boolean",
@@ -10198,7 +10577,7 @@ var MANIFEST = [
10198
10577
  },
10199
10578
  target: {
10200
10579
  type: "string",
10201
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
10580
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
10202
10581
  },
10203
10582
  index: {
10204
10583
  type: "number",
@@ -10221,7 +10600,7 @@ var MANIFEST = [
10221
10600
  },
10222
10601
  target: {
10223
10602
  type: "string",
10224
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
10603
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
10225
10604
  },
10226
10605
  reload: {
10227
10606
  type: "boolean",
@@ -10256,7 +10635,7 @@ var MANIFEST = [
10256
10635
  },
10257
10636
  target: {
10258
10637
  type: "string",
10259
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
10638
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
10260
10639
  },
10261
10640
  requestId: {
10262
10641
  type: "string",
@@ -10295,7 +10674,7 @@ var MANIFEST = [
10295
10674
  },
10296
10675
  target: {
10297
10676
  type: "string",
10298
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
10677
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
10299
10678
  },
10300
10679
  categories: {
10301
10680
  type: "array",
@@ -10321,7 +10700,7 @@ var MANIFEST = [
10321
10700
  },
10322
10701
  target: {
10323
10702
  type: "string",
10324
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
10703
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
10325
10704
  }
10326
10705
  },
10327
10706
  required: [],
@@ -10359,7 +10738,7 @@ var MANIFEST = [
10359
10738
  },
10360
10739
  target: {
10361
10740
  type: "string",
10362
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
10741
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
10363
10742
  },
10364
10743
  durationMs: {
10365
10744
  type: "number",
@@ -10397,7 +10776,7 @@ var MANIFEST = [
10397
10776
  },
10398
10777
  target: {
10399
10778
  type: "string",
10400
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
10779
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
10401
10780
  },
10402
10781
  format: {
10403
10782
  type: "string",
@@ -10444,7 +10823,7 @@ var MANIFEST = [
10444
10823
  },
10445
10824
  target: {
10446
10825
  type: "string",
10447
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
10826
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
10448
10827
  },
10449
10828
  savePath: {
10450
10829
  type: "string",
@@ -10467,7 +10846,7 @@ var MANIFEST = [
10467
10846
  },
10468
10847
  target: {
10469
10848
  type: "string",
10470
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
10849
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
10471
10850
  },
10472
10851
  savePath: {
10473
10852
  type: "string",
@@ -10534,7 +10913,7 @@ var MANIFEST = [
10534
10913
  },
10535
10914
  target: {
10536
10915
  type: "string",
10537
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
10916
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
10538
10917
  },
10539
10918
  urlPattern: {
10540
10919
  type: "string",
@@ -10623,7 +11002,7 @@ var MANIFEST = [
10623
11002
  },
10624
11003
  target: {
10625
11004
  type: "string",
10626
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
11005
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
10627
11006
  },
10628
11007
  all: {
10629
11008
  type: "boolean",
@@ -10642,7 +11021,7 @@ var MANIFEST = [
10642
11021
  properties: {
10643
11022
  target: {
10644
11023
  type: "string",
10645
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
11024
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
10646
11025
  },
10647
11026
  targetId: {
10648
11027
  type: "string",
@@ -10677,7 +11056,7 @@ var MANIFEST = [
10677
11056
  },
10678
11057
  target: {
10679
11058
  type: "string",
10680
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
11059
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
10681
11060
  },
10682
11061
  close: {
10683
11062
  type: "boolean",
@@ -10710,7 +11089,7 @@ var MANIFEST = [
10710
11089
  },
10711
11090
  target: {
10712
11091
  type: "string",
10713
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
11092
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
10714
11093
  },
10715
11094
  schema: {
10716
11095
  type: "object",
@@ -10774,6 +11153,102 @@ var MANIFEST = [
10774
11153
  }
10775
11154
  ];
10776
11155
 
11156
+ // src/policy.ts
11157
+ var READ_TOOLS = new Set([
11158
+ "list_pages",
11159
+ "wait_for",
11160
+ "evaluate_script",
11161
+ "list_cookies",
11162
+ "take_snapshot",
11163
+ "take_screenshot",
11164
+ "list_console_messages",
11165
+ "get_console_message",
11166
+ "list_network_requests",
11167
+ "get_network_request",
11168
+ "performance_analyze_insight",
11169
+ "take_heapsnapshot",
11170
+ "list_mocks",
11171
+ "extract_page",
11172
+ "list_leases"
11173
+ ]);
11174
+ var MUTATING_TOOLS = new Set([
11175
+ "new_page",
11176
+ "close_page",
11177
+ "select_page",
11178
+ "navigate_page",
11179
+ "set_cookie",
11180
+ "delete_cookies",
11181
+ "click",
11182
+ "hover",
11183
+ "drag",
11184
+ "scroll",
11185
+ "fill",
11186
+ "fill_form",
11187
+ "type_text",
11188
+ "press_key",
11189
+ "upload_file",
11190
+ "emulate",
11191
+ "resize_page",
11192
+ "handle_dialog",
11193
+ "performance_start_trace",
11194
+ "performance_stop_trace",
11195
+ "performance_trace",
11196
+ "start_screen_recording",
11197
+ "stop_screen_recording",
11198
+ "lighthouse_audit",
11199
+ "mock_request",
11200
+ "clear_mocks",
11201
+ "dispatch_mouse",
11202
+ "focus_emulation",
11203
+ "click_focus_gated",
11204
+ "wait_for_download",
11205
+ "grant_permissions",
11206
+ "claim_page",
11207
+ "release_page"
11208
+ ]);
11209
+ var META_TOOLS = new Set(["search_tools", "call_tool", "describe_tool"]);
11210
+
11211
+ class PolicyError extends Error {
11212
+ code = "read_only_endpoint";
11213
+ tool;
11214
+ endpoint;
11215
+ constructor(tool, endpoint) {
11216
+ super(`'${tool}' is not allowed on endpoint '${endpoint}': the endpoint is read-only (tools that change state are refused before any CDP message is sent)`);
11217
+ this.name = "PolicyError";
11218
+ this.tool = tool;
11219
+ this.endpoint = endpoint;
11220
+ }
11221
+ }
11222
+ function escalatesToMutation(tool, args) {
11223
+ if (typeof args !== "object" || args === null)
11224
+ return false;
11225
+ const a = args;
11226
+ switch (tool) {
11227
+ case "list_console_messages":
11228
+ case "list_network_requests":
11229
+ return a.reload === true;
11230
+ case "get_network_request":
11231
+ return a.includeBody === true && typeof a.url === "string" && a.url !== "";
11232
+ case "take_screenshot":
11233
+ return a.renderWidth !== undefined || a.renderHeight !== undefined;
11234
+ default:
11235
+ return false;
11236
+ }
11237
+ }
11238
+ function assertAllowed(tool, endpoint, args) {
11239
+ if (!endpoint.readOnly)
11240
+ return;
11241
+ if (META_TOOLS.has(tool))
11242
+ return;
11243
+ if (!READ_TOOLS.has(tool))
11244
+ throw new PolicyError(tool, endpoint.name);
11245
+ if (escalatesToMutation(tool, args))
11246
+ throw new PolicyError(tool, endpoint.name);
11247
+ }
11248
+ function toolAnnotations(name) {
11249
+ return { readOnlyHint: READ_TOOLS.has(name) };
11250
+ }
11251
+
10777
11252
  // src/install/wizard.ts
10778
11253
  import { createInterface } from "node:readline";
10779
11254
  import { homedir as homedir3 } from "node:os";
@@ -11576,11 +12051,18 @@ async function main() {
11576
12051
  return withLeaseScope(leaseFromArgs(parsed.args), async () => {
11577
12052
  if (browser === "chrome") {
11578
12053
  const fn = TOOLS[tool];
11579
- const result = await fn(parsed.args);
11580
- process.stdout.write(`${JSON.stringify(result, null, 2)}
12054
+ const { endpoint, args: toolArgs } = stripEndpointArgs(parsed.args);
12055
+ assertAllowed(tool, endpoint, toolArgs);
12056
+ const result = await withEndpointScope(endpoint, () => fn(toolArgs));
12057
+ process.stdout.write(`${JSON.stringify(result ?? null, null, 2)}
11581
12058
  `);
11582
12059
  return 0;
11583
12060
  }
12061
+ if (usesEndpointArgs(parsed.args)) {
12062
+ process.stderr.write(`${JSON.stringify({ error: ENDPOINTS_FIREFOX_MESSAGE })}
12063
+ `);
12064
+ return 1;
12065
+ }
11584
12066
  const neutralFn = FIREFOX_TOOLS[tool];
11585
12067
  if (!neutralFn) {
11586
12068
  process.stderr.write(`${JSON.stringify({ error: `tool '${tool}' has no Firefox implementation wired` })}
@@ -11590,7 +12072,7 @@ async function main() {
11590
12072
  const session = await startFirefoxSession({ endpoint });
11591
12073
  try {
11592
12074
  const result = await neutralFn(session.driver, parsed.args);
11593
- process.stdout.write(`${JSON.stringify(result, null, 2)}
12075
+ process.stdout.write(`${JSON.stringify(result ?? null, null, 2)}
11594
12076
  `);
11595
12077
  return 0;
11596
12078
  } finally {