cdp-toolkit 3.0.2 → 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;
@@ -4869,6 +5180,41 @@ function noSuchTarget(e) {
4869
5180
  throw e;
4870
5181
  throw driverError("no-such-target", e instanceof CdpError ? e.message : String(e));
4871
5182
  }
5183
+ var NEW_TARGET_SETTLE_MS = 2000;
5184
+ async function createSettledTarget(conn, url, settleMs = NEW_TARGET_SETTLE_MS) {
5185
+ const changed = new Set;
5186
+ let id = "";
5187
+ let wake;
5188
+ const off = conn.on("Target.targetInfoChanged", (params) => {
5189
+ const t = params.targetInfo?.targetId;
5190
+ if (!t)
5191
+ return;
5192
+ changed.add(t);
5193
+ if (t === id)
5194
+ wake?.();
5195
+ });
5196
+ try {
5197
+ await conn.send("Target.setDiscoverTargets", { discover: true }).catch(() => {
5198
+ return;
5199
+ });
5200
+ const { targetId } = await conn.send("Target.createTarget", { url });
5201
+ if (!targetId)
5202
+ throw driverError("page-error", "Target.createTarget returned no targetId");
5203
+ id = targetId;
5204
+ if (!changed.has(targetId)) {
5205
+ await new Promise((resolve) => {
5206
+ const timer = setTimeout(resolve, settleMs);
5207
+ wake = () => {
5208
+ clearTimeout(timer);
5209
+ resolve();
5210
+ };
5211
+ });
5212
+ }
5213
+ return targetId;
5214
+ } finally {
5215
+ off();
5216
+ }
5217
+ }
4872
5218
 
4873
5219
  class CdpBrowserDriver {
4874
5220
  scheme = "cdp";
@@ -4883,9 +5229,7 @@ class CdpBrowserDriver {
4883
5229
  }
4884
5230
  async newPage(url) {
4885
5231
  return withBrowserConn(async (conn) => {
4886
- const { targetId } = await conn.send("Target.createTarget", { url: url ?? "about:blank" });
4887
- if (!targetId)
4888
- throw driverError("page-error", "Target.createTarget returned no targetId");
5232
+ const targetId = await createSettledTarget(conn, url ?? "about:blank");
4889
5233
  return { id: targetId, url: url ?? "about:blank", title: "" };
4890
5234
  });
4891
5235
  }
@@ -4893,7 +5237,7 @@ class CdpBrowserDriver {
4893
5237
  return withBrowserConn(async (conn) => {
4894
5238
  const res = await conn.send("Target.closeTarget", { targetId: id });
4895
5239
  if (res.success !== false)
4896
- beaconSessions.drop(id);
5240
+ beaconSessions.drop(beaconKey(id));
4897
5241
  return { success: res.success ?? true };
4898
5242
  });
4899
5243
  }
@@ -4911,12 +5255,13 @@ class CdpBrowserDriver {
4911
5255
  return new CdpPageDriver(conn, target, this);
4912
5256
  }
4913
5257
  async installActivityBeacon(targetId) {
4914
- const held = beaconSessions.get(targetId);
5258
+ const key = beaconKey(targetId);
5259
+ const held = beaconSessions.get(key);
4915
5260
  if (held) {
4916
5261
  const rearmed = await held.send("Runtime.evaluate", { expression: BEACON_SOURCE, returnByValue: true }).then(() => true).catch(() => false);
4917
5262
  if (rearmed)
4918
5263
  return true;
4919
- beaconSessions.drop(targetId);
5264
+ beaconSessions.drop(key);
4920
5265
  }
4921
5266
  const wsUrl = await targetWsUrl(targetId).catch(() => {
4922
5267
  return;
@@ -4936,16 +5281,17 @@ class CdpBrowserDriver {
4936
5281
  conn.close();
4937
5282
  return false;
4938
5283
  }
4939
- beaconSessions.set(targetId, conn);
5284
+ beaconSessions.set(key, conn);
4940
5285
  return true;
4941
5286
  }
4942
5287
  async readActivityBeacon(targetId) {
4943
- const held = beaconSessions.get(targetId);
5288
+ const key = beaconKey(targetId);
5289
+ const held = beaconSessions.get(key);
4944
5290
  if (held) {
4945
5291
  const value = await readBeaconOver(held);
4946
5292
  if (value !== undefined)
4947
5293
  return value;
4948
- beaconSessions.drop(targetId);
5294
+ beaconSessions.drop(key);
4949
5295
  }
4950
5296
  const wsUrl = await targetWsUrl(targetId).catch(() => {
4951
5297
  return;
@@ -4964,7 +5310,7 @@ class CdpBrowserDriver {
4964
5310
  }
4965
5311
  }
4966
5312
  async probeRenderer(targetId, timeoutMs = RENDERER_PROBE_TIMEOUT_MS) {
4967
- const held = beaconSessions.get(targetId);
5313
+ const held = beaconSessions.get(beaconKey(targetId));
4968
5314
  if (held)
4969
5315
  return probeOver(held, timeoutMs);
4970
5316
  const wsUrl = await targetWsUrl(targetId).catch(() => {
@@ -4997,6 +5343,7 @@ init_activity();
4997
5343
  init_origins();
4998
5344
 
4999
5345
  // src/reap.ts
5346
+ init_endpoints();
5000
5347
  init_leases();
5001
5348
  init_origins();
5002
5349
  function staleAgentTabs(input) {
@@ -5025,6 +5372,11 @@ function reapGraceMs() {
5025
5372
  const raw = Number(process.env.CDP_REAP_GRACE_MS);
5026
5373
  return Number.isFinite(raw) && raw >= 0 ? raw : DEFAULT_REAP_GRACE_MS;
5027
5374
  }
5375
+ function reapAllowed(driver) {
5376
+ if (driver.scheme === "bidi")
5377
+ return true;
5378
+ return !currentEndpoint().readOnly;
5379
+ }
5028
5380
  async function reapStaleAgentTabs(driver, backend) {
5029
5381
  const now = Date.now();
5030
5382
  const livePageIds = (await driver.listPages()).map((p) => p.id);
@@ -5567,6 +5919,7 @@ init_activity();
5567
5919
  init_origins();
5568
5920
  init_workers();
5569
5921
  init_frames();
5922
+ init_endpoints();
5570
5923
  var ARTIFACT_DIR = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
5571
5924
  var STATE_DIR = process.env.CDP_STATE_DIR ?? "/tmp/cdp-toolkit";
5572
5925
 
@@ -5576,7 +5929,7 @@ function target3(p) {
5576
5929
  return { id: p.id, url: p.url, title: p.title };
5577
5930
  }
5578
5931
  function backendOf(driver) {
5579
- return driver.scheme === "bidi" ? "firefox" : "chrome";
5932
+ return driver.scheme === "bidi" ? "firefox" : chromeLeaseBackend();
5580
5933
  }
5581
5934
  async function withPage2(driver, target, fn) {
5582
5935
  const page = await driver.page(target);
@@ -5664,8 +6017,44 @@ async function reapSet(driver, pages, all) {
5664
6017
  }
5665
6018
  }
5666
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 = {}) {
5667
6056
  const backend = backendOf(driver);
5668
- const reaped = requireLease() ? await reapStaleAgentTabs(driver, backend) : [];
6057
+ const reaped = requireLease() && reapAllowed(driver) ? await reapStaleAgentTabs(driver, backend) : [];
5669
6058
  const reapedIds = new Set(reaped.map((r) => r.targetId));
5670
6059
  const pages = (await driver.listPages({ all: args.all })).filter((p) => !reapedIds.has(p.id));
5671
6060
  const ledger = await originIndex(backend, await reapSet(driver, pages, args.all));
@@ -6306,7 +6695,7 @@ init_leases();
6306
6695
  class LeaseToolError extends Error {
6307
6696
  }
6308
6697
  function backendOf2(driver) {
6309
- return driver.scheme === "bidi" ? "firefox" : "chrome";
6698
+ return driver.scheme === "bidi" ? "firefox" : chromeLeaseBackend();
6310
6699
  }
6311
6700
  async function claimPage(driver, args = {}) {
6312
6701
  const hasTarget = typeof args.target === "string" && args.target.length > 0;
@@ -6391,7 +6780,7 @@ async function releasePage(driver, args = {}) {
6391
6780
  }
6392
6781
  async function listLeasesTool(driver, _args = {}) {
6393
6782
  const backend = backendOf2(driver);
6394
- const reaped = requireLease() ? await reapStaleAgentTabs(driver, backend) : [];
6783
+ const reaped = requireLease() && reapAllowed(driver) ? await reapStaleAgentTabs(driver, backend) : [];
6395
6784
  const reapedIds = new Set(reaped.map((r) => r.targetId));
6396
6785
  const livePages = await driver.listPages();
6397
6786
  const liveIds = livePages.map((p) => p.id);
@@ -7471,11 +7860,12 @@ async function takeHeapsnapshot(args = {}) {
7471
7860
 
7472
7861
  // src/tools/lighthouse.ts
7473
7862
  init_client();
7863
+ init_endpoints();
7474
7864
  import { spawn as spawn2 } from "node:child_process";
7475
7865
  import { mkdir as mkdir10, readFile as readFile7, stat as stat3 } from "node:fs/promises";
7476
7866
  var ARTIFACT_DIR5 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
7477
7867
  function cdpPort() {
7478
- const base = process.env.CDP_BASE ?? "http://127.0.0.1:9222";
7868
+ const base = currentEndpoint().base;
7479
7869
  const m = base.match(/:(\d+)/);
7480
7870
  return m?.[1] ? Number(m[1]) : 9222;
7481
7871
  }
@@ -7612,6 +8002,7 @@ init_network_mock();
7612
8002
  // src/tools/dispatch-mouse.ts
7613
8003
  init_activity();
7614
8004
  init_client();
8005
+ init_leases();
7615
8006
  var CLICK_MODIFIER_BITS2 = { Alt: 1, Control: 2, Meta: 4, Shift: 8 };
7616
8007
  var BUTTONS = new Set(["left", "right", "middle"]);
7617
8008
  var CDP_EVENT_TYPE = {
@@ -7648,7 +8039,7 @@ async function dispatchMouse(args) {
7648
8039
  const params = { type: CDP_EVENT_TYPE[args.action], x: args.x, y: args.y, button, modifiers };
7649
8040
  if (args.action !== "move")
7650
8041
  params.clickCount = args.clickCount ?? 1;
7651
- await sendInput(conn, "chrome", target.id, "Input.dispatchMouseEvent", params);
8042
+ await sendInput(conn, chromeLeaseBackend(), target.id, "Input.dispatchMouseEvent", params);
7652
8043
  return { dispatched: args.action, x: args.x, y: args.y };
7653
8044
  });
7654
8045
  }
@@ -7656,6 +8047,7 @@ async function dispatchMouse(args) {
7656
8047
  // src/tools/focus-emulation.ts
7657
8048
  init_activity();
7658
8049
  init_client();
8050
+ init_leases();
7659
8051
  function validateFocusEmulationArgs(args) {
7660
8052
  if (typeof args.enabled !== "boolean") {
7661
8053
  throw new Error("focus_emulation requires { enabled } of true or false");
@@ -7722,9 +8114,10 @@ async function clickFocusGated(args) {
7722
8114
  const btn = result?.value;
7723
8115
  if (btn && !btn.disabled) {
7724
8116
  const base = { x: btn.x, y: btn.y, button: "left", buttons: 1, clickCount: 1 };
7725
- await sendInput(conn, "chrome", target.id, "Input.dispatchMouseEvent", { type: "mouseMoved", x: btn.x, y: btn.y });
7726
- await sendInput(conn, "chrome", target.id, "Input.dispatchMouseEvent", { ...base, type: "mousePressed" });
7727
- 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" });
7728
8121
  return {
7729
8122
  clicked: true,
7730
8123
  x: btn.x,
@@ -7753,12 +8146,16 @@ import { basename, extname, join as join9 } from "node:path";
7753
8146
 
7754
8147
  // src/tools/browser-session.ts
7755
8148
  init_client();
8149
+ init_endpoints();
7756
8150
  import { mkdir as mkdir11 } from "node:fs/promises";
7757
8151
  import { join as join8 } from "node:path";
7758
8152
  var ARTIFACT_DIR6 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
7759
8153
  var DOWNLOADS_DIR = join8(ARTIFACT_DIR6, "downloads");
7760
8154
  var DOWNLOAD_BUFFER_LIMIT = 50;
7761
- var session;
8155
+ var sessions2 = new Map;
8156
+ function sessionKey() {
8157
+ return currentEndpoint().name;
8158
+ }
7762
8159
  function isDisconnect(e) {
7763
8160
  const m = e instanceof Error ? e.message : String(e);
7764
8161
  return /connection (not open|closed)|closed by caller|websocket|ECONNREFUSED|socket/i.test(m);
@@ -7803,13 +8200,15 @@ function subscribe(s) {
7803
8200
  });
7804
8201
  }
7805
8202
  async function getBrowserSession() {
8203
+ const key = sessionKey();
8204
+ const session = sessions2.get(key);
7806
8205
  if (session && !session.dead)
7807
8206
  return session;
7808
8207
  const previousPath = session?.armedPath;
7809
8208
  const conn = await openBrowser();
7810
8209
  const s = { conn, downloads: [], waiters: [], dead: false };
7811
8210
  subscribe(s);
7812
- session = s;
8211
+ sessions2.set(key, s);
7813
8212
  if (previousPath)
7814
8213
  await armDownloadsAt(previousPath);
7815
8214
  return s;
@@ -7840,7 +8239,7 @@ async function armDownloads() {
7840
8239
  return { downloadPath: DOWNLOADS_DIR };
7841
8240
  }
7842
8241
  function pendingDownloads() {
7843
- return (session?.downloads ?? []).filter((d) => d.state === "completed" && !d.consumed);
8242
+ return (sessions2.get(sessionKey())?.downloads ?? []).filter((d) => d.state === "completed" && !d.consumed);
7844
8243
  }
7845
8244
  async function nextCompletedDownload(timeoutMs) {
7846
8245
  const s = await getBrowserSession();
@@ -7864,14 +8263,14 @@ async function nextCompletedDownload(timeoutMs) {
7864
8263
  });
7865
8264
  }
7866
8265
  async function disposeBrowserSession() {
7867
- const s = session;
7868
- session = undefined;
7869
- if (!s)
7870
- return;
7871
- s.dead = true;
7872
- try {
7873
- s.conn.close();
7874
- } 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
+ }
7875
8274
  }
7876
8275
 
7877
8276
  // src/tools/downloads.ts
@@ -8456,7 +8855,7 @@ init_driver2();
8456
8855
 
8457
8856
  // src/bidi/launch.ts
8458
8857
  import { spawn as spawn4 } from "node:child_process";
8459
- 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";
8460
8859
  import { createConnection, createServer as createServer2 } from "node:net";
8461
8860
  import { tmpdir } from "node:os";
8462
8861
  import { join as join12 } from "node:path";
@@ -8540,7 +8939,7 @@ var LAUNCH_USER_JS_PREFS = {
8540
8939
  };
8541
8940
  function writeLaunchUserJs(profilePath) {
8542
8941
  const target = join12(profilePath, "user.js");
8543
- const existing = existsSync2(target) ? readFileSync(target, "utf8") : "";
8942
+ const existing = existsSync2(target) ? readFileSync2(target, "utf8") : "";
8544
8943
  const present = new Set;
8545
8944
  for (const line of existing.split(`
8546
8945
  `)) {
@@ -8921,6 +9320,7 @@ var FIREFOX_TOOLS = {
8921
9320
 
8922
9321
  // src/cli.ts
8923
9322
  init_leases();
9323
+ init_endpoints();
8924
9324
 
8925
9325
  // src/manifest.ts
8926
9326
  var MANIFEST = [
@@ -8941,6 +9341,14 @@ var MANIFEST = [
8941
9341
  probe: {
8942
9342
  type: "boolean",
8943
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."
8944
9352
  }
8945
9353
  },
8946
9354
  required: [],
@@ -8965,6 +9373,10 @@ var MANIFEST = [
8965
9373
  type: "boolean",
8966
9374
  description: "Claim the new tab."
8967
9375
  },
9376
+ endpoint: {
9377
+ type: "string",
9378
+ description: "Named CDP endpoint to open the tab on (CDP_ENDPOINTS); default endpoint when omitted."
9379
+ },
8968
9380
  label: {
8969
9381
  type: "string",
8970
9382
  description: "Agent lease label."
@@ -8990,7 +9402,7 @@ var MANIFEST = [
8990
9402
  },
8991
9403
  target: {
8992
9404
  type: "string",
8993
- 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."
8994
9406
  }
8995
9407
  },
8996
9408
  required: [
@@ -9011,7 +9423,7 @@ var MANIFEST = [
9011
9423
  },
9012
9424
  target: {
9013
9425
  type: "string",
9014
- 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."
9015
9427
  }
9016
9428
  },
9017
9429
  required: [
@@ -9032,7 +9444,7 @@ var MANIFEST = [
9032
9444
  },
9033
9445
  target: {
9034
9446
  type: "string",
9035
- 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."
9036
9448
  },
9037
9449
  url: {
9038
9450
  type: "string",
@@ -9082,7 +9494,7 @@ var MANIFEST = [
9082
9494
  },
9083
9495
  target: {
9084
9496
  type: "string",
9085
- 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."
9086
9498
  },
9087
9499
  text: {
9088
9500
  type: "string",
@@ -9115,7 +9527,7 @@ var MANIFEST = [
9115
9527
  },
9116
9528
  target: {
9117
9529
  type: "string",
9118
- 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."
9119
9531
  },
9120
9532
  wake: {
9121
9533
  type: "boolean",
@@ -9157,7 +9569,7 @@ var MANIFEST = [
9157
9569
  },
9158
9570
  target: {
9159
9571
  type: "string",
9160
- 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."
9161
9573
  },
9162
9574
  domain: {
9163
9575
  type: "string",
@@ -9188,7 +9600,7 @@ var MANIFEST = [
9188
9600
  },
9189
9601
  target: {
9190
9602
  type: "string",
9191
- 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."
9192
9604
  },
9193
9605
  name: {
9194
9606
  type: "string",
@@ -9252,7 +9664,7 @@ var MANIFEST = [
9252
9664
  },
9253
9665
  target: {
9254
9666
  type: "string",
9255
- 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."
9256
9668
  },
9257
9669
  name: {
9258
9670
  type: "string",
@@ -9289,7 +9701,7 @@ var MANIFEST = [
9289
9701
  },
9290
9702
  target: {
9291
9703
  type: "string",
9292
- 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."
9293
9705
  },
9294
9706
  interactiveOnly: {
9295
9707
  type: "boolean",
@@ -9312,7 +9724,7 @@ var MANIFEST = [
9312
9724
  },
9313
9725
  target: {
9314
9726
  type: "string",
9315
- 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."
9316
9728
  },
9317
9729
  uid: {
9318
9730
  type: "number",
@@ -9365,7 +9777,7 @@ var MANIFEST = [
9365
9777
  },
9366
9778
  target: {
9367
9779
  type: "string",
9368
- 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."
9369
9781
  },
9370
9782
  uid: {
9371
9783
  type: "number",
@@ -9392,7 +9804,7 @@ var MANIFEST = [
9392
9804
  },
9393
9805
  target: {
9394
9806
  type: "string",
9395
- 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."
9396
9808
  },
9397
9809
  from: {
9398
9810
  type: "object",
@@ -9478,7 +9890,7 @@ var MANIFEST = [
9478
9890
  },
9479
9891
  target: {
9480
9892
  type: "string",
9481
- 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."
9482
9894
  },
9483
9895
  uid: {
9484
9896
  type: "number",
@@ -9521,7 +9933,7 @@ var MANIFEST = [
9521
9933
  },
9522
9934
  target: {
9523
9935
  type: "string",
9524
- 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."
9525
9937
  },
9526
9938
  action: {
9527
9939
  type: "string",
@@ -9587,7 +9999,7 @@ var MANIFEST = [
9587
9999
  },
9588
10000
  target: {
9589
10001
  type: "string",
9590
- 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."
9591
10003
  },
9592
10004
  enabled: {
9593
10005
  type: "boolean",
@@ -9612,7 +10024,7 @@ var MANIFEST = [
9612
10024
  },
9613
10025
  target: {
9614
10026
  type: "string",
9615
- 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."
9616
10028
  },
9617
10029
  selector: {
9618
10030
  type: "string",
@@ -9651,7 +10063,7 @@ var MANIFEST = [
9651
10063
  },
9652
10064
  target: {
9653
10065
  type: "string",
9654
- 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."
9655
10067
  },
9656
10068
  arm: {
9657
10069
  type: "boolean",
@@ -9678,7 +10090,7 @@ var MANIFEST = [
9678
10090
  },
9679
10091
  target: {
9680
10092
  type: "string",
9681
- 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."
9682
10094
  },
9683
10095
  permissions: {
9684
10096
  type: "array",
@@ -9712,7 +10124,7 @@ var MANIFEST = [
9712
10124
  },
9713
10125
  target: {
9714
10126
  type: "string",
9715
- 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."
9716
10128
  },
9717
10129
  uid: {
9718
10130
  type: "number",
@@ -9745,7 +10157,7 @@ var MANIFEST = [
9745
10157
  },
9746
10158
  target: {
9747
10159
  type: "string",
9748
- 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."
9749
10161
  },
9750
10162
  fields: {
9751
10163
  type: "array",
@@ -9791,7 +10203,7 @@ var MANIFEST = [
9791
10203
  },
9792
10204
  target: {
9793
10205
  type: "string",
9794
- 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."
9795
10207
  },
9796
10208
  uid: {
9797
10209
  type: "number",
@@ -9824,7 +10236,7 @@ var MANIFEST = [
9824
10236
  },
9825
10237
  target: {
9826
10238
  type: "string",
9827
- 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."
9828
10240
  },
9829
10241
  key: {
9830
10242
  type: "string",
@@ -9856,7 +10268,7 @@ var MANIFEST = [
9856
10268
  },
9857
10269
  target: {
9858
10270
  type: "string",
9859
- 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."
9860
10272
  },
9861
10273
  uid: {
9862
10274
  type: "number",
@@ -9892,7 +10304,7 @@ var MANIFEST = [
9892
10304
  },
9893
10305
  target: {
9894
10306
  type: "string",
9895
- 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."
9896
10308
  },
9897
10309
  format: {
9898
10310
  type: "string",
@@ -9959,7 +10371,7 @@ var MANIFEST = [
9959
10371
  },
9960
10372
  target: {
9961
10373
  type: "string",
9962
- 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."
9963
10375
  },
9964
10376
  width: {
9965
10377
  type: "number",
@@ -10059,7 +10471,7 @@ var MANIFEST = [
10059
10471
  },
10060
10472
  target: {
10061
10473
  type: "string",
10062
- 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."
10063
10475
  },
10064
10476
  width: {
10065
10477
  type: "number",
@@ -10097,7 +10509,7 @@ var MANIFEST = [
10097
10509
  },
10098
10510
  target: {
10099
10511
  type: "string",
10100
- 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."
10101
10513
  },
10102
10514
  accept: {
10103
10515
  type: "boolean",
@@ -10134,7 +10546,7 @@ var MANIFEST = [
10134
10546
  },
10135
10547
  target: {
10136
10548
  type: "string",
10137
- 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."
10138
10550
  },
10139
10551
  reload: {
10140
10552
  type: "boolean",
@@ -10165,7 +10577,7 @@ var MANIFEST = [
10165
10577
  },
10166
10578
  target: {
10167
10579
  type: "string",
10168
- 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."
10169
10581
  },
10170
10582
  index: {
10171
10583
  type: "number",
@@ -10188,7 +10600,7 @@ var MANIFEST = [
10188
10600
  },
10189
10601
  target: {
10190
10602
  type: "string",
10191
- 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."
10192
10604
  },
10193
10605
  reload: {
10194
10606
  type: "boolean",
@@ -10223,7 +10635,7 @@ var MANIFEST = [
10223
10635
  },
10224
10636
  target: {
10225
10637
  type: "string",
10226
- 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."
10227
10639
  },
10228
10640
  requestId: {
10229
10641
  type: "string",
@@ -10262,7 +10674,7 @@ var MANIFEST = [
10262
10674
  },
10263
10675
  target: {
10264
10676
  type: "string",
10265
- 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."
10266
10678
  },
10267
10679
  categories: {
10268
10680
  type: "array",
@@ -10288,7 +10700,7 @@ var MANIFEST = [
10288
10700
  },
10289
10701
  target: {
10290
10702
  type: "string",
10291
- 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."
10292
10704
  }
10293
10705
  },
10294
10706
  required: [],
@@ -10326,7 +10738,7 @@ var MANIFEST = [
10326
10738
  },
10327
10739
  target: {
10328
10740
  type: "string",
10329
- 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."
10330
10742
  },
10331
10743
  durationMs: {
10332
10744
  type: "number",
@@ -10364,7 +10776,7 @@ var MANIFEST = [
10364
10776
  },
10365
10777
  target: {
10366
10778
  type: "string",
10367
- 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."
10368
10780
  },
10369
10781
  format: {
10370
10782
  type: "string",
@@ -10411,7 +10823,7 @@ var MANIFEST = [
10411
10823
  },
10412
10824
  target: {
10413
10825
  type: "string",
10414
- 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."
10415
10827
  },
10416
10828
  savePath: {
10417
10829
  type: "string",
@@ -10434,7 +10846,7 @@ var MANIFEST = [
10434
10846
  },
10435
10847
  target: {
10436
10848
  type: "string",
10437
- 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."
10438
10850
  },
10439
10851
  savePath: {
10440
10852
  type: "string",
@@ -10501,7 +10913,7 @@ var MANIFEST = [
10501
10913
  },
10502
10914
  target: {
10503
10915
  type: "string",
10504
- 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."
10505
10917
  },
10506
10918
  urlPattern: {
10507
10919
  type: "string",
@@ -10590,7 +11002,7 @@ var MANIFEST = [
10590
11002
  },
10591
11003
  target: {
10592
11004
  type: "string",
10593
- 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."
10594
11006
  },
10595
11007
  all: {
10596
11008
  type: "boolean",
@@ -10609,7 +11021,7 @@ var MANIFEST = [
10609
11021
  properties: {
10610
11022
  target: {
10611
11023
  type: "string",
10612
- 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."
10613
11025
  },
10614
11026
  targetId: {
10615
11027
  type: "string",
@@ -10644,7 +11056,7 @@ var MANIFEST = [
10644
11056
  },
10645
11057
  target: {
10646
11058
  type: "string",
10647
- 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."
10648
11060
  },
10649
11061
  close: {
10650
11062
  type: "boolean",
@@ -10677,7 +11089,7 @@ var MANIFEST = [
10677
11089
  },
10678
11090
  target: {
10679
11091
  type: "string",
10680
- 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."
10681
11093
  },
10682
11094
  schema: {
10683
11095
  type: "object",
@@ -10741,6 +11153,102 @@ var MANIFEST = [
10741
11153
  }
10742
11154
  ];
10743
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
+
10744
11252
  // src/install/wizard.ts
10745
11253
  import { createInterface } from "node:readline";
10746
11254
  import { homedir as homedir3 } from "node:os";
@@ -10760,6 +11268,12 @@ var CANDIDATE_BUILDERS = {
10760
11268
  "chromium"
10761
11269
  ],
10762
11270
  arc: () => [process.env.ARC_BIN, "/Applications/Arc.app/Contents/MacOS/Arc", "arc"],
11271
+ vivaldi: () => [
11272
+ process.env.VIVALDI_BIN,
11273
+ "/Applications/Vivaldi.app/Contents/MacOS/Vivaldi",
11274
+ "vivaldi",
11275
+ "/usr/bin/vivaldi"
11276
+ ],
10763
11277
  firefox: () => [
10764
11278
  process.env.FIREFOX_BIN,
10765
11279
  "/Applications/Firefox.app/Contents/MacOS/firefox",
@@ -11007,7 +11521,7 @@ function isOnPath(bin) {
11007
11521
  // src/install/wizard.ts
11008
11522
  var DEFAULT_NAME = "cdp-toolkit";
11009
11523
  var HARNESSES = ["claude", "codex", "opencode"];
11010
- var BROWSERS = ["arc", "chrome", "firefox"];
11524
+ var BROWSERS = ["arc", "chrome", "firefox", "vivaldi"];
11011
11525
  function defaultPortFor(browser) {
11012
11526
  return browser === "firefox" ? 9223 : 9222;
11013
11527
  }
@@ -11020,10 +11534,10 @@ function parseHarness(v) {
11020
11534
  }
11021
11535
  function parseBrowserChoice(v) {
11022
11536
  if (v === undefined)
11023
- throw new Error("--browser requires a value: arc, chrome, or firefox");
11537
+ throw new Error("--browser requires a value: arc, chrome, firefox, or vivaldi");
11024
11538
  if (BROWSERS.includes(v))
11025
11539
  return v;
11026
- throw new Error(`--browser must be one of arc|chrome|firefox (got '${v}')`);
11540
+ throw new Error(`--browser must be one of arc|chrome|firefox|vivaldi (got '${v}')`);
11027
11541
  }
11028
11542
  function parsePort(v) {
11029
11543
  if (v === undefined)
@@ -11104,14 +11618,14 @@ function installHelpText() {
11104
11618
  browser-launch alias (with the remote-debugging port open) to your shell rc.
11105
11619
 
11106
11620
  Usage:
11107
- cdp install [--harness <claude|codex|opencode>] [--browser <arc|chrome|firefox>]
11621
+ cdp install [--harness <claude|codex|opencode>] [--browser <arc|chrome|firefox|vivaldi>]
11108
11622
  [--port <n>] [--name <server-name>] [--alias-name <name>]
11109
11623
  [--no-alias] [--yes|-y] [--help|-h]
11110
11624
 
11111
11625
  Options:
11112
11626
  --harness <h> Coding harness to register the MCP server with: claude, codex, opencode.
11113
- --browser <b> Browser the alias launches: arc, chrome, firefox.
11114
- --port <n> Remote-debugging port (1-65535). Default: 9222 (chrome/arc), 9223 (firefox).
11627
+ --browser <b> Browser the alias launches: arc, chrome, firefox, vivaldi.
11628
+ --port <n> Remote-debugging port (1-65535). Default: 9222 (chrome/arc/vivaldi), 9223 (firefox).
11115
11629
  --name <name> MCP server name to register. Default: ${DEFAULT_NAME}.
11116
11630
  --alias-name <n> Shell alias name. Default: cdp-<browser> (e.g. cdp-firefox).
11117
11631
  --no-alias Register the MCP server only; skip writing the shell alias.
@@ -11537,11 +12051,18 @@ async function main() {
11537
12051
  return withLeaseScope(leaseFromArgs(parsed.args), async () => {
11538
12052
  if (browser === "chrome") {
11539
12053
  const fn = TOOLS[tool];
11540
- const result = await fn(parsed.args);
11541
- 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)}
11542
12058
  `);
11543
12059
  return 0;
11544
12060
  }
12061
+ if (usesEndpointArgs(parsed.args)) {
12062
+ process.stderr.write(`${JSON.stringify({ error: ENDPOINTS_FIREFOX_MESSAGE })}
12063
+ `);
12064
+ return 1;
12065
+ }
11545
12066
  const neutralFn = FIREFOX_TOOLS[tool];
11546
12067
  if (!neutralFn) {
11547
12068
  process.stderr.write(`${JSON.stringify({ error: `tool '${tool}' has no Firefox implementation wired` })}
@@ -11551,7 +12072,7 @@ async function main() {
11551
12072
  const session = await startFirefoxSession({ endpoint });
11552
12073
  try {
11553
12074
  const result = await neutralFn(session.driver, parsed.args);
11554
- process.stdout.write(`${JSON.stringify(result, null, 2)}
12075
+ process.stdout.write(`${JSON.stringify(result ?? null, null, 2)}
11555
12076
  `);
11556
12077
  return 0;
11557
12078
  } finally {