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/mcp.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;
@@ -3757,6 +4063,7 @@ import { fileURLToPath as fileURLToPath2 } from "node:url";
3757
4063
  // src/cdp/driver.ts
3758
4064
  init_client();
3759
4065
  init_leases();
4066
+ init_endpoints();
3760
4067
  init_activity();
3761
4068
 
3762
4069
  // src/tools/snapshot.ts
@@ -4244,7 +4551,7 @@ class CdpPageDriver {
4244
4551
  await this.conn.send(`${name}.enable`);
4245
4552
  }
4246
4553
  async dispatchInput(method, params = {}) {
4247
- return sendInput(this.conn, "chrome", this.info.id, method, params);
4554
+ return sendInput(this.conn, chromeLeaseBackend(), this.info.id, method, params);
4248
4555
  }
4249
4556
  async ensureDomainSoft(name) {
4250
4557
  if (this.enabledDomains.has(name))
@@ -4838,6 +5145,10 @@ class CdpPageDriver {
4838
5145
  }
4839
5146
  }
4840
5147
  var beaconSessions = new BeaconSessions((conn) => conn.close());
5148
+ function beaconKey(targetId) {
5149
+ const backend = chromeLeaseBackend(currentEndpoint());
5150
+ return backend === "chrome" ? targetId : `${backend}\x00${targetId}`;
5151
+ }
4841
5152
  async function targetWsUrl(targetId) {
4842
5153
  const hit = (await listTargets()).find((t) => t.id === targetId);
4843
5154
  return hit?.webSocketDebuggerUrl;
@@ -4939,7 +5250,7 @@ class CdpBrowserDriver {
4939
5250
  return withBrowserConn(async (conn) => {
4940
5251
  const res = await conn.send("Target.closeTarget", { targetId: id });
4941
5252
  if (res.success !== false)
4942
- beaconSessions.drop(id);
5253
+ beaconSessions.drop(beaconKey(id));
4943
5254
  return { success: res.success ?? true };
4944
5255
  });
4945
5256
  }
@@ -4957,12 +5268,13 @@ class CdpBrowserDriver {
4957
5268
  return new CdpPageDriver(conn, target, this);
4958
5269
  }
4959
5270
  async installActivityBeacon(targetId) {
4960
- const held = beaconSessions.get(targetId);
5271
+ const key = beaconKey(targetId);
5272
+ const held = beaconSessions.get(key);
4961
5273
  if (held) {
4962
5274
  const rearmed = await held.send("Runtime.evaluate", { expression: BEACON_SOURCE, returnByValue: true }).then(() => true).catch(() => false);
4963
5275
  if (rearmed)
4964
5276
  return true;
4965
- beaconSessions.drop(targetId);
5277
+ beaconSessions.drop(key);
4966
5278
  }
4967
5279
  const wsUrl = await targetWsUrl(targetId).catch(() => {
4968
5280
  return;
@@ -4982,16 +5294,17 @@ class CdpBrowserDriver {
4982
5294
  conn.close();
4983
5295
  return false;
4984
5296
  }
4985
- beaconSessions.set(targetId, conn);
5297
+ beaconSessions.set(key, conn);
4986
5298
  return true;
4987
5299
  }
4988
5300
  async readActivityBeacon(targetId) {
4989
- const held = beaconSessions.get(targetId);
5301
+ const key = beaconKey(targetId);
5302
+ const held = beaconSessions.get(key);
4990
5303
  if (held) {
4991
5304
  const value = await readBeaconOver(held);
4992
5305
  if (value !== undefined)
4993
5306
  return value;
4994
- beaconSessions.drop(targetId);
5307
+ beaconSessions.drop(key);
4995
5308
  }
4996
5309
  const wsUrl = await targetWsUrl(targetId).catch(() => {
4997
5310
  return;
@@ -5010,7 +5323,7 @@ class CdpBrowserDriver {
5010
5323
  }
5011
5324
  }
5012
5325
  async probeRenderer(targetId, timeoutMs = RENDERER_PROBE_TIMEOUT_MS) {
5013
- const held = beaconSessions.get(targetId);
5326
+ const held = beaconSessions.get(beaconKey(targetId));
5014
5327
  if (held)
5015
5328
  return probeOver(held, timeoutMs);
5016
5329
  const wsUrl = await targetWsUrl(targetId).catch(() => {
@@ -5043,6 +5356,7 @@ init_activity();
5043
5356
  init_origins();
5044
5357
 
5045
5358
  // src/reap.ts
5359
+ init_endpoints();
5046
5360
  init_leases();
5047
5361
  init_origins();
5048
5362
  function staleAgentTabs(input) {
@@ -5071,6 +5385,11 @@ function reapGraceMs() {
5071
5385
  const raw = Number(process.env.CDP_REAP_GRACE_MS);
5072
5386
  return Number.isFinite(raw) && raw >= 0 ? raw : DEFAULT_REAP_GRACE_MS;
5073
5387
  }
5388
+ function reapAllowed(driver) {
5389
+ if (driver.scheme === "bidi")
5390
+ return true;
5391
+ return !currentEndpoint().readOnly;
5392
+ }
5074
5393
  async function reapStaleAgentTabs(driver, backend) {
5075
5394
  const now = Date.now();
5076
5395
  const livePageIds = (await driver.listPages()).map((p) => p.id);
@@ -5613,6 +5932,7 @@ init_activity();
5613
5932
  init_origins();
5614
5933
  init_workers();
5615
5934
  init_frames();
5935
+ init_endpoints();
5616
5936
  var ARTIFACT_DIR = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
5617
5937
  var STATE_DIR = process.env.CDP_STATE_DIR ?? "/tmp/cdp-toolkit";
5618
5938
 
@@ -5622,7 +5942,7 @@ function target3(p) {
5622
5942
  return { id: p.id, url: p.url, title: p.title };
5623
5943
  }
5624
5944
  function backendOf(driver) {
5625
- return driver.scheme === "bidi" ? "firefox" : "chrome";
5945
+ return driver.scheme === "bidi" ? "firefox" : chromeLeaseBackend();
5626
5946
  }
5627
5947
  async function withPage2(driver, target, fn) {
5628
5948
  const page = await driver.page(target);
@@ -5710,8 +6030,44 @@ async function reapSet(driver, pages, all) {
5710
6030
  }
5711
6031
  }
5712
6032
  async function listPages(driver, args = {}) {
6033
+ const one = { all: args.all, probe: args.probe };
6034
+ if (args.allEndpoints === true) {
6035
+ if (driver.scheme === "bidi")
6036
+ throw new SharedToolError("list_pages: allEndpoints needs the Chrome backend; named endpoints are CDP-only");
6037
+ 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) }))));
6038
+ const pages = [];
6039
+ const reaped = [];
6040
+ const endpoints = [];
6041
+ for (const res of results) {
6042
+ const { ep } = res;
6043
+ if ("error" in res) {
6044
+ endpoints.push({ endpoint: ep.name, base: ep.base, readOnly: ep.readOnly, down: true, error: res.error });
6045
+ continue;
6046
+ }
6047
+ for (const p of res.r.pages)
6048
+ pages.push({ ...p, endpoint: ep.name });
6049
+ for (const t of res.r.reaped ?? [])
6050
+ reaped.push({ ...t, endpoint: ep.name });
6051
+ endpoints.push({ endpoint: ep.name, base: ep.base, readOnly: ep.readOnly, count: res.r.count });
6052
+ }
6053
+ return { pages, count: pages.length, ...reaped.length ? { reaped } : {}, endpoints };
6054
+ }
6055
+ const res = await listPagesOne(driver, one);
6056
+ if (driver.scheme !== "bidi") {
6057
+ const ep = currentEndpoint();
6058
+ if (!isDefaultEndpoint(ep)) {
6059
+ return {
6060
+ ...res,
6061
+ pages: res.pages.map((p) => ({ ...p, endpoint: ep.name })),
6062
+ ...res.reaped ? { reaped: res.reaped.map((t) => ({ ...t, endpoint: ep.name })) } : {}
6063
+ };
6064
+ }
6065
+ }
6066
+ return res;
6067
+ }
6068
+ async function listPagesOne(driver, args = {}) {
5713
6069
  const backend = backendOf(driver);
5714
- const reaped = requireLease() ? await reapStaleAgentTabs(driver, backend) : [];
6070
+ const reaped = requireLease() && reapAllowed(driver) ? await reapStaleAgentTabs(driver, backend) : [];
5715
6071
  const reapedIds = new Set(reaped.map((r) => r.targetId));
5716
6072
  const pages = (await driver.listPages({ all: args.all })).filter((p) => !reapedIds.has(p.id));
5717
6073
  const ledger = await originIndex(backend, await reapSet(driver, pages, args.all));
@@ -6352,7 +6708,7 @@ init_leases();
6352
6708
  class LeaseToolError extends Error {
6353
6709
  }
6354
6710
  function backendOf2(driver) {
6355
- return driver.scheme === "bidi" ? "firefox" : "chrome";
6711
+ return driver.scheme === "bidi" ? "firefox" : chromeLeaseBackend();
6356
6712
  }
6357
6713
  async function claimPage(driver, args = {}) {
6358
6714
  const hasTarget = typeof args.target === "string" && args.target.length > 0;
@@ -6437,7 +6793,7 @@ async function releasePage(driver, args = {}) {
6437
6793
  }
6438
6794
  async function listLeasesTool(driver, _args = {}) {
6439
6795
  const backend = backendOf2(driver);
6440
- const reaped = requireLease() ? await reapStaleAgentTabs(driver, backend) : [];
6796
+ const reaped = requireLease() && reapAllowed(driver) ? await reapStaleAgentTabs(driver, backend) : [];
6441
6797
  const reapedIds = new Set(reaped.map((r) => r.targetId));
6442
6798
  const livePages = await driver.listPages();
6443
6799
  const liveIds = livePages.map((p) => p.id);
@@ -7517,11 +7873,12 @@ async function takeHeapsnapshot(args = {}) {
7517
7873
 
7518
7874
  // src/tools/lighthouse.ts
7519
7875
  init_client();
7876
+ init_endpoints();
7520
7877
  import { spawn as spawn2 } from "node:child_process";
7521
7878
  import { mkdir as mkdir10, readFile as readFile7, stat as stat3 } from "node:fs/promises";
7522
7879
  var ARTIFACT_DIR5 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
7523
7880
  function cdpPort() {
7524
- const base = process.env.CDP_BASE ?? "http://127.0.0.1:9222";
7881
+ const base = currentEndpoint().base;
7525
7882
  const m = base.match(/:(\d+)/);
7526
7883
  return m?.[1] ? Number(m[1]) : 9222;
7527
7884
  }
@@ -7658,6 +8015,7 @@ init_network_mock();
7658
8015
  // src/tools/dispatch-mouse.ts
7659
8016
  init_activity();
7660
8017
  init_client();
8018
+ init_leases();
7661
8019
  var CLICK_MODIFIER_BITS2 = { Alt: 1, Control: 2, Meta: 4, Shift: 8 };
7662
8020
  var BUTTONS = new Set(["left", "right", "middle"]);
7663
8021
  var CDP_EVENT_TYPE = {
@@ -7694,7 +8052,7 @@ async function dispatchMouse(args) {
7694
8052
  const params = { type: CDP_EVENT_TYPE[args.action], x: args.x, y: args.y, button, modifiers };
7695
8053
  if (args.action !== "move")
7696
8054
  params.clickCount = args.clickCount ?? 1;
7697
- await sendInput(conn, "chrome", target.id, "Input.dispatchMouseEvent", params);
8055
+ await sendInput(conn, chromeLeaseBackend(), target.id, "Input.dispatchMouseEvent", params);
7698
8056
  return { dispatched: args.action, x: args.x, y: args.y };
7699
8057
  });
7700
8058
  }
@@ -7702,6 +8060,7 @@ async function dispatchMouse(args) {
7702
8060
  // src/tools/focus-emulation.ts
7703
8061
  init_activity();
7704
8062
  init_client();
8063
+ init_leases();
7705
8064
  function validateFocusEmulationArgs(args) {
7706
8065
  if (typeof args.enabled !== "boolean") {
7707
8066
  throw new Error("focus_emulation requires { enabled } of true or false");
@@ -7768,9 +8127,10 @@ async function clickFocusGated(args) {
7768
8127
  const btn = result?.value;
7769
8128
  if (btn && !btn.disabled) {
7770
8129
  const base = { x: btn.x, y: btn.y, button: "left", buttons: 1, clickCount: 1 };
7771
- await sendInput(conn, "chrome", target.id, "Input.dispatchMouseEvent", { type: "mouseMoved", x: btn.x, y: btn.y });
7772
- await sendInput(conn, "chrome", target.id, "Input.dispatchMouseEvent", { ...base, type: "mousePressed" });
7773
- await sendInput(conn, "chrome", target.id, "Input.dispatchMouseEvent", { ...base, type: "mouseReleased" });
8130
+ const backend = chromeLeaseBackend();
8131
+ await sendInput(conn, backend, target.id, "Input.dispatchMouseEvent", { type: "mouseMoved", x: btn.x, y: btn.y });
8132
+ await sendInput(conn, backend, target.id, "Input.dispatchMouseEvent", { ...base, type: "mousePressed" });
8133
+ await sendInput(conn, backend, target.id, "Input.dispatchMouseEvent", { ...base, type: "mouseReleased" });
7774
8134
  return {
7775
8135
  clicked: true,
7776
8136
  x: btn.x,
@@ -7799,12 +8159,16 @@ import { basename, extname, join as join9 } from "node:path";
7799
8159
 
7800
8160
  // src/tools/browser-session.ts
7801
8161
  init_client();
8162
+ init_endpoints();
7802
8163
  import { mkdir as mkdir11 } from "node:fs/promises";
7803
8164
  import { join as join8 } from "node:path";
7804
8165
  var ARTIFACT_DIR6 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
7805
8166
  var DOWNLOADS_DIR = join8(ARTIFACT_DIR6, "downloads");
7806
8167
  var DOWNLOAD_BUFFER_LIMIT = 50;
7807
- var session;
8168
+ var sessions2 = new Map;
8169
+ function sessionKey() {
8170
+ return currentEndpoint().name;
8171
+ }
7808
8172
  function isDisconnect(e) {
7809
8173
  const m = e instanceof Error ? e.message : String(e);
7810
8174
  return /connection (not open|closed)|closed by caller|websocket|ECONNREFUSED|socket/i.test(m);
@@ -7849,13 +8213,15 @@ function subscribe(s) {
7849
8213
  });
7850
8214
  }
7851
8215
  async function getBrowserSession() {
8216
+ const key = sessionKey();
8217
+ const session = sessions2.get(key);
7852
8218
  if (session && !session.dead)
7853
8219
  return session;
7854
8220
  const previousPath = session?.armedPath;
7855
8221
  const conn = await openBrowser();
7856
8222
  const s = { conn, downloads: [], waiters: [], dead: false };
7857
8223
  subscribe(s);
7858
- session = s;
8224
+ sessions2.set(key, s);
7859
8225
  if (previousPath)
7860
8226
  await armDownloadsAt(previousPath);
7861
8227
  return s;
@@ -7886,7 +8252,7 @@ async function armDownloads() {
7886
8252
  return { downloadPath: DOWNLOADS_DIR };
7887
8253
  }
7888
8254
  function pendingDownloads() {
7889
- return (session?.downloads ?? []).filter((d) => d.state === "completed" && !d.consumed);
8255
+ return (sessions2.get(sessionKey())?.downloads ?? []).filter((d) => d.state === "completed" && !d.consumed);
7890
8256
  }
7891
8257
  async function nextCompletedDownload(timeoutMs) {
7892
8258
  const s = await getBrowserSession();
@@ -7910,14 +8276,14 @@ async function nextCompletedDownload(timeoutMs) {
7910
8276
  });
7911
8277
  }
7912
8278
  async function disposeBrowserSession() {
7913
- const s = session;
7914
- session = undefined;
7915
- if (!s)
7916
- return;
7917
- s.dead = true;
7918
- try {
7919
- s.conn.close();
7920
- } catch {}
8279
+ const all = [...sessions2.values()];
8280
+ sessions2.clear();
8281
+ for (const s of all) {
8282
+ s.dead = true;
8283
+ try {
8284
+ s.conn.close();
8285
+ } catch {}
8286
+ }
7921
8287
  }
7922
8288
 
7923
8289
  // src/tools/downloads.ts
@@ -8516,6 +8882,14 @@ var MANIFEST = [
8516
8882
  probe: {
8517
8883
  type: "boolean",
8518
8884
  description: "Probe renderer responsiveness."
8885
+ },
8886
+ endpoint: {
8887
+ type: "string",
8888
+ description: "Named CDP endpoint to list (CDP_ENDPOINTS); default endpoint when omitted."
8889
+ },
8890
+ allEndpoints: {
8891
+ type: "boolean",
8892
+ description: "List every configured endpoint; rows carry endpoint, a down one is reported, not thrown."
8519
8893
  }
8520
8894
  },
8521
8895
  required: [],
@@ -8540,6 +8914,10 @@ var MANIFEST = [
8540
8914
  type: "boolean",
8541
8915
  description: "Claim the new tab."
8542
8916
  },
8917
+ endpoint: {
8918
+ type: "string",
8919
+ description: "Named CDP endpoint to open the tab on (CDP_ENDPOINTS); default endpoint when omitted."
8920
+ },
8543
8921
  label: {
8544
8922
  type: "string",
8545
8923
  description: "Agent lease label."
@@ -8565,7 +8943,7 @@ var MANIFEST = [
8565
8943
  },
8566
8944
  target: {
8567
8945
  type: "string",
8568
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
8946
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
8569
8947
  }
8570
8948
  },
8571
8949
  required: [
@@ -8586,7 +8964,7 @@ var MANIFEST = [
8586
8964
  },
8587
8965
  target: {
8588
8966
  type: "string",
8589
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
8967
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
8590
8968
  }
8591
8969
  },
8592
8970
  required: [
@@ -8607,7 +8985,7 @@ var MANIFEST = [
8607
8985
  },
8608
8986
  target: {
8609
8987
  type: "string",
8610
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
8988
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
8611
8989
  },
8612
8990
  url: {
8613
8991
  type: "string",
@@ -8657,7 +9035,7 @@ var MANIFEST = [
8657
9035
  },
8658
9036
  target: {
8659
9037
  type: "string",
8660
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
9038
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
8661
9039
  },
8662
9040
  text: {
8663
9041
  type: "string",
@@ -8690,7 +9068,7 @@ var MANIFEST = [
8690
9068
  },
8691
9069
  target: {
8692
9070
  type: "string",
8693
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
9071
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
8694
9072
  },
8695
9073
  wake: {
8696
9074
  type: "boolean",
@@ -8732,7 +9110,7 @@ var MANIFEST = [
8732
9110
  },
8733
9111
  target: {
8734
9112
  type: "string",
8735
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
9113
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
8736
9114
  },
8737
9115
  domain: {
8738
9116
  type: "string",
@@ -8763,7 +9141,7 @@ var MANIFEST = [
8763
9141
  },
8764
9142
  target: {
8765
9143
  type: "string",
8766
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
9144
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
8767
9145
  },
8768
9146
  name: {
8769
9147
  type: "string",
@@ -8827,7 +9205,7 @@ var MANIFEST = [
8827
9205
  },
8828
9206
  target: {
8829
9207
  type: "string",
8830
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
9208
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
8831
9209
  },
8832
9210
  name: {
8833
9211
  type: "string",
@@ -8864,7 +9242,7 @@ var MANIFEST = [
8864
9242
  },
8865
9243
  target: {
8866
9244
  type: "string",
8867
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
9245
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
8868
9246
  },
8869
9247
  interactiveOnly: {
8870
9248
  type: "boolean",
@@ -8887,7 +9265,7 @@ var MANIFEST = [
8887
9265
  },
8888
9266
  target: {
8889
9267
  type: "string",
8890
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
9268
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
8891
9269
  },
8892
9270
  uid: {
8893
9271
  type: "number",
@@ -8940,7 +9318,7 @@ var MANIFEST = [
8940
9318
  },
8941
9319
  target: {
8942
9320
  type: "string",
8943
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
9321
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
8944
9322
  },
8945
9323
  uid: {
8946
9324
  type: "number",
@@ -8967,7 +9345,7 @@ var MANIFEST = [
8967
9345
  },
8968
9346
  target: {
8969
9347
  type: "string",
8970
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
9348
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
8971
9349
  },
8972
9350
  from: {
8973
9351
  type: "object",
@@ -9053,7 +9431,7 @@ var MANIFEST = [
9053
9431
  },
9054
9432
  target: {
9055
9433
  type: "string",
9056
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
9434
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9057
9435
  },
9058
9436
  uid: {
9059
9437
  type: "number",
@@ -9096,7 +9474,7 @@ var MANIFEST = [
9096
9474
  },
9097
9475
  target: {
9098
9476
  type: "string",
9099
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
9477
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9100
9478
  },
9101
9479
  action: {
9102
9480
  type: "string",
@@ -9162,7 +9540,7 @@ var MANIFEST = [
9162
9540
  },
9163
9541
  target: {
9164
9542
  type: "string",
9165
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
9543
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9166
9544
  },
9167
9545
  enabled: {
9168
9546
  type: "boolean",
@@ -9187,7 +9565,7 @@ var MANIFEST = [
9187
9565
  },
9188
9566
  target: {
9189
9567
  type: "string",
9190
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
9568
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9191
9569
  },
9192
9570
  selector: {
9193
9571
  type: "string",
@@ -9226,7 +9604,7 @@ var MANIFEST = [
9226
9604
  },
9227
9605
  target: {
9228
9606
  type: "string",
9229
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
9607
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9230
9608
  },
9231
9609
  arm: {
9232
9610
  type: "boolean",
@@ -9253,7 +9631,7 @@ var MANIFEST = [
9253
9631
  },
9254
9632
  target: {
9255
9633
  type: "string",
9256
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
9634
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9257
9635
  },
9258
9636
  permissions: {
9259
9637
  type: "array",
@@ -9287,7 +9665,7 @@ var MANIFEST = [
9287
9665
  },
9288
9666
  target: {
9289
9667
  type: "string",
9290
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
9668
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9291
9669
  },
9292
9670
  uid: {
9293
9671
  type: "number",
@@ -9320,7 +9698,7 @@ var MANIFEST = [
9320
9698
  },
9321
9699
  target: {
9322
9700
  type: "string",
9323
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
9701
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9324
9702
  },
9325
9703
  fields: {
9326
9704
  type: "array",
@@ -9366,7 +9744,7 @@ var MANIFEST = [
9366
9744
  },
9367
9745
  target: {
9368
9746
  type: "string",
9369
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
9747
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9370
9748
  },
9371
9749
  uid: {
9372
9750
  type: "number",
@@ -9399,7 +9777,7 @@ var MANIFEST = [
9399
9777
  },
9400
9778
  target: {
9401
9779
  type: "string",
9402
- 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."
9403
9781
  },
9404
9782
  key: {
9405
9783
  type: "string",
@@ -9431,7 +9809,7 @@ var MANIFEST = [
9431
9809
  },
9432
9810
  target: {
9433
9811
  type: "string",
9434
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
9812
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9435
9813
  },
9436
9814
  uid: {
9437
9815
  type: "number",
@@ -9467,7 +9845,7 @@ var MANIFEST = [
9467
9845
  },
9468
9846
  target: {
9469
9847
  type: "string",
9470
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
9848
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9471
9849
  },
9472
9850
  format: {
9473
9851
  type: "string",
@@ -9534,7 +9912,7 @@ var MANIFEST = [
9534
9912
  },
9535
9913
  target: {
9536
9914
  type: "string",
9537
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
9915
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9538
9916
  },
9539
9917
  width: {
9540
9918
  type: "number",
@@ -9634,7 +10012,7 @@ var MANIFEST = [
9634
10012
  },
9635
10013
  target: {
9636
10014
  type: "string",
9637
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
10015
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9638
10016
  },
9639
10017
  width: {
9640
10018
  type: "number",
@@ -9672,7 +10050,7 @@ var MANIFEST = [
9672
10050
  },
9673
10051
  target: {
9674
10052
  type: "string",
9675
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
10053
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9676
10054
  },
9677
10055
  accept: {
9678
10056
  type: "boolean",
@@ -9709,7 +10087,7 @@ var MANIFEST = [
9709
10087
  },
9710
10088
  target: {
9711
10089
  type: "string",
9712
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
10090
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9713
10091
  },
9714
10092
  reload: {
9715
10093
  type: "boolean",
@@ -9740,7 +10118,7 @@ var MANIFEST = [
9740
10118
  },
9741
10119
  target: {
9742
10120
  type: "string",
9743
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
10121
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9744
10122
  },
9745
10123
  index: {
9746
10124
  type: "number",
@@ -9763,7 +10141,7 @@ var MANIFEST = [
9763
10141
  },
9764
10142
  target: {
9765
10143
  type: "string",
9766
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
10144
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9767
10145
  },
9768
10146
  reload: {
9769
10147
  type: "boolean",
@@ -9798,7 +10176,7 @@ var MANIFEST = [
9798
10176
  },
9799
10177
  target: {
9800
10178
  type: "string",
9801
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
10179
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9802
10180
  },
9803
10181
  requestId: {
9804
10182
  type: "string",
@@ -9837,7 +10215,7 @@ var MANIFEST = [
9837
10215
  },
9838
10216
  target: {
9839
10217
  type: "string",
9840
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
10218
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9841
10219
  },
9842
10220
  categories: {
9843
10221
  type: "array",
@@ -9863,7 +10241,7 @@ var MANIFEST = [
9863
10241
  },
9864
10242
  target: {
9865
10243
  type: "string",
9866
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
10244
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9867
10245
  }
9868
10246
  },
9869
10247
  required: [],
@@ -9901,7 +10279,7 @@ var MANIFEST = [
9901
10279
  },
9902
10280
  target: {
9903
10281
  type: "string",
9904
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
10282
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9905
10283
  },
9906
10284
  durationMs: {
9907
10285
  type: "number",
@@ -9939,7 +10317,7 @@ var MANIFEST = [
9939
10317
  },
9940
10318
  target: {
9941
10319
  type: "string",
9942
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
10320
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9943
10321
  },
9944
10322
  format: {
9945
10323
  type: "string",
@@ -9986,7 +10364,7 @@ var MANIFEST = [
9986
10364
  },
9987
10365
  target: {
9988
10366
  type: "string",
9989
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
10367
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
9990
10368
  },
9991
10369
  savePath: {
9992
10370
  type: "string",
@@ -10009,7 +10387,7 @@ var MANIFEST = [
10009
10387
  },
10010
10388
  target: {
10011
10389
  type: "string",
10012
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
10390
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
10013
10391
  },
10014
10392
  savePath: {
10015
10393
  type: "string",
@@ -10076,7 +10454,7 @@ var MANIFEST = [
10076
10454
  },
10077
10455
  target: {
10078
10456
  type: "string",
10079
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
10457
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
10080
10458
  },
10081
10459
  urlPattern: {
10082
10460
  type: "string",
@@ -10165,7 +10543,7 @@ var MANIFEST = [
10165
10543
  },
10166
10544
  target: {
10167
10545
  type: "string",
10168
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
10546
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
10169
10547
  },
10170
10548
  all: {
10171
10549
  type: "boolean",
@@ -10184,7 +10562,7 @@ var MANIFEST = [
10184
10562
  properties: {
10185
10563
  target: {
10186
10564
  type: "string",
10187
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
10565
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
10188
10566
  },
10189
10567
  targetId: {
10190
10568
  type: "string",
@@ -10219,7 +10597,7 @@ var MANIFEST = [
10219
10597
  },
10220
10598
  target: {
10221
10599
  type: "string",
10222
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
10600
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
10223
10601
  },
10224
10602
  close: {
10225
10603
  type: "boolean",
@@ -10252,7 +10630,7 @@ var MANIFEST = [
10252
10630
  },
10253
10631
  target: {
10254
10632
  type: "string",
10255
- description: "Page selector (index:/url:/title:/label:/targetId, default active); grammar in server instructions."
10633
+ description: "Page selector (index:/url:/title:/label:/targetId, endpoint:<name>/ prefix, default active); grammar in server instructions."
10256
10634
  },
10257
10635
  schema: {
10258
10636
  type: "object",
@@ -10321,7 +10699,7 @@ init_driver2();
10321
10699
 
10322
10700
  // src/bidi/launch.ts
10323
10701
  import { spawn as spawn4 } from "node:child_process";
10324
- import { existsSync as existsSync2, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
10702
+ import { existsSync as existsSync2, mkdtempSync, readFileSync as readFileSync2, rmSync, writeFileSync } from "node:fs";
10325
10703
  import { createConnection, createServer as createServer2 } from "node:net";
10326
10704
  import { tmpdir } from "node:os";
10327
10705
  import { join as join12 } from "node:path";
@@ -10405,7 +10783,7 @@ var LAUNCH_USER_JS_PREFS = {
10405
10783
  };
10406
10784
  function writeLaunchUserJs(profilePath) {
10407
10785
  const target = join12(profilePath, "user.js");
10408
- const existing = existsSync2(target) ? readFileSync(target, "utf8") : "";
10786
+ const existing = existsSync2(target) ? readFileSync2(target, "utf8") : "";
10409
10787
  const present = new Set;
10410
10788
  for (const line of existing.split(`
10411
10789
  `)) {
@@ -10786,6 +11164,7 @@ var FIREFOX_TOOLS = {
10786
11164
 
10787
11165
  // src/mcp.ts
10788
11166
  init_leases();
11167
+ init_endpoints();
10789
11168
 
10790
11169
  // src/toolGroups.ts
10791
11170
  var TOOL_GROUPS = [
@@ -10904,7 +11283,9 @@ var TOOL_DOCS = {
10904
11283
  params: {
10905
11284
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
10906
11285
  all: "Include non-page targets (service/shared workers, background pages, out-of-process (OOPIF) iframes); default false lists page-type tabs only. A returned non-page targetId is accepted as a bare id by any tool's `target` param.",
10907
- probe: "Ping each page-type renderer before returning, one bounded 500ms check per target and never more, so a wedged tab can't stall the listing. Adds 'responsive' (false on timeout/exception/unreachable, never an error for the whole call) and, where the same round trip finds human input, humanActiveMs. Default false. On a backend that cannot answer the ping, responsive is absent too (not false)."
11286
+ probe: "Ping each page-type renderer before returning, one bounded 500ms check per target and never more, so a wedged tab can't stall the listing. Adds 'responsive' (false on timeout/exception/unreachable, never an error for the whole call) and, where the same round trip finds human input, humanActiveMs. Default false. On a backend that cannot answer the ping, responsive is absent too (not false).",
11287
+ endpoint: "Name of a CDP endpoint configured with CDP_ENDPOINTS / CDP_ENDPOINTS_FILE (Chrome only); lists that endpoint instead of the default. Every row from a non-default endpoint carries 'endpoint', so build selectors as 'endpoint:<name>/<targetId>'. An app endpoint (e.g. the Teams desktop app, a WebView2/Electron shell) often lists an empty host page first: pick the real window with 'title:'.",
11288
+ allEndpoints: "List every configured endpoint at once (Chrome only). Each page row carries its 'endpoint'; an 'endpoints' array reports every endpoint as {endpoint, base, readOnly, count}, or {endpoint, base, readOnly, down:true, error} for one that cannot be reached, which never fails the whole call. Default false."
10908
11289
  }
10909
11290
  },
10910
11291
  new_page: {
@@ -10912,6 +11293,7 @@ var TOOL_DOCS = {
10912
11293
  params: {
10913
11294
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
10914
11295
  url: "URL to open in the new tab; defaults to about:blank.",
11296
+ endpoint: "Name of a CDP endpoint configured with CDP_ENDPOINTS / CDP_ENDPOINTS_FILE to open the tab on (Chrome only); default endpoint when omitted. Address the new tab later as 'endpoint:<name>/<targetId>'.",
10915
11297
  claim: "Claim the new tab atomically and return a lease token alongside {targetId,url}. Under CDP_REQUIRE_LEASE the tab is claimed and a lease returned even without claim:true; claim:true makes it an EXPLICIT lease that demands its token on every later call, even from this process. Default false.",
10916
11298
  label: "Agent label recorded on the lease when the tab is claimed; surfaced in conflict errors and list_leases. Defaults to pid-<pid>.",
10917
11299
  ttlMs: "How long a claimed lease survives without use before it is reclaimable. Defaults to CDP_LEASE_TTL_MS, else 900000 (15min); every checked call refreshes it. Ignored when not claiming."
@@ -10921,21 +11303,21 @@ var TOOL_DOCS = {
10921
11303
  description: "Close a page target via Target.closeTarget. Requires an explicit, resolvable target; errors rather than guessing when the selector matches nothing.",
10922
11304
  params: {
10923
11305
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
10924
- target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Grammar: see server instructions."
11306
+ target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Prefix any of these with 'endpoint:<name>/' for a named CDP endpoint (Chrome only). Grammar: see server instructions."
10925
11307
  }
10926
11308
  },
10927
11309
  select_page: {
10928
11310
  description: "Activate/focus a page target via Target.activateTarget and persist its bare targetId to the selected-state file (CDP_STATE_DIR/selected). Requires an explicit, resolvable target.",
10929
11311
  params: {
10930
11312
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
10931
- target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Grammar: see server instructions."
11313
+ target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Prefix any of these with 'endpoint:<name>/' for a named CDP endpoint (Chrome only). Grammar: see server instructions."
10932
11314
  }
10933
11315
  },
10934
11316
  navigate_page: {
10935
11317
  description: "Navigate a target page to a URL (Page.navigate), reload it (reload:true), OR go back/forward in its session history (history:'back'|'forward'), then wait for the load milestone with a bounded timeout so a wedged renderer can't hang. Exactly one of url / reload / history per call. Returns {url,frameId,waitedFor} (plus reloaded:true on a reload, traversed:'back'|'forward' on a history move); waitUntil supports 'load'|'domcontentloaded' only (no 'networkidle'), and there is no auto-snapshot of the new page. Pass reload:true with ignoreCache:true for a hard reload that refetches every subresource (e.g. to pick up a freshly-deployed, non-content-hashed bundle the HTTP cache would serve stale).",
10936
11318
  params: {
10937
11319
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
10938
- target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Grammar: see server instructions.",
11320
+ target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Prefix any of these with 'endpoint:<name>/' for a named CDP endpoint (Chrome only). Grammar: see server instructions.",
10939
11321
  url: "Destination URL to navigate to. Required unless reload:true.",
10940
11322
  reload: "Reload the current page (Page.reload) instead of navigating to url. Default false.",
10941
11323
  history: "Traverse this tab's session history instead of loading a url: 'back' and 'forward' are the browser's Back and Forward buttons. Mutually exclusive with 'url' and 'reload' — passing two of the three is refused by name, not resolved by precedence. Works on BOTH backends and waits for the same load milestone as an ordinary navigation. Going back from the first entry, or forward from the last, is an ERROR naming the direction — never a silent no-op. The result carries traversed:'back'|'forward' alongside the resulting url.",
@@ -10948,7 +11330,7 @@ var TOOL_DOCS = {
10948
11330
  description: "Poll the target until the substring appears in document.body.innerText (Runtime.evaluate on a fixed interval), or throw on timeout. Text-substring only -- no aria/role/selector or event variants; throws rather than returning {found:false}.",
10949
11331
  params: {
10950
11332
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
10951
- target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Grammar: see server instructions.",
11333
+ target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Prefix any of these with 'endpoint:<name>/' for a named CDP endpoint (Chrome only). Grammar: see server instructions.",
10952
11334
  text: "Substring to wait for in document.body.innerText. Required.",
10953
11335
  timeoutMs: "Total time budget in ms. Default 15000.",
10954
11336
  pollMs: "Poll interval in ms. Default 250."
@@ -10958,7 +11340,7 @@ var TOOL_DOCS = {
10958
11340
  description: "Run arbitrary JavaScript in the target's main-world context over raw CDP and return the evaluated value (returnByValue). With no 'args', 'expression' is a raw expression; with 'args' it must be a function literal (arrow or classic) invoked on globalThis with args passed positionally. A thrown exception surfaces as an error; non-serializable returns (DOM nodes, functions) come back as their CDP description string. savePath writes the value to a JSON file instead -- the response then carries only {path,bytes,type,target} and the value never appears in it, the way to read a credential (a JWT/session token from localStorage) without putting the secret in the transcript. This is the one tool that EVALUATES inside an MV3 extension's background SERVICE WORKER rather than OBSERVING it (Chrome, Capability 'worker.targets'): a worker: target reads chrome.storage.local, chrome.runtime and the worker's own globals directly, with an idle-evicted worker started first (see 'wake').",
10959
11341
  params: {
10960
11342
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
10961
- target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', '<targetId>'; plus 'worker:<substring>' to reach a service/shared worker (e.g. an MV3 extension background worker). The worker: arm is CHROME-ONLY (Capability 'worker.targets'). Grammar: see server instructions.",
11343
+ target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', '<targetId>'; plus 'worker:<substring>' to reach a service/shared worker (e.g. an MV3 extension background worker). The worker: arm is CHROME-ONLY (Capability 'worker.targets'). Prefix any of these with 'endpoint:<name>/' for a named CDP endpoint (Chrome only). Grammar: see server instructions.",
10962
11344
  wake: "Worker targets only, when starting a capture. Default true: an idle-evicted MV3 service worker exists in no target listing, so it is started first (ServiceWorker.startWorker) and re-confirmed; false fails fast. Rejected on a page target, a bare target id, or a read-only call. See server instructions.",
10963
11345
  expression: "JavaScript to run. Evaluated as an expression when 'args' is omitted; must be a function literal (arrow or classic) whose parameters receive 'args' when provided. REQUIRED -- the code always goes in this key, never in 'function', 'code', 'js', 'script', 'fn' or 'body'; a call using one of those is rejected with an error naming the wrong key.",
10964
11346
  awaitPromise: "Await the result if it is a Promise. Default true.",
@@ -10970,7 +11352,7 @@ var TOOL_DOCS = {
10970
11352
  description: "Read the target page's cookie store INCLUDING httpOnly cookies, which document.cookie (and therefore evaluate_script) cannot see. Page-scoped, not browser-wide: returns cookies of the resolved tab, so point at a page on the site you want. Each cookie carries name, value, domain, path, expires (Unix seconds, -1 for a session cookie), size, httpOnly, secure, sameSite ('strict'|'lax'|'none'|'default'), session. Filter with 'domain' and/or 'name'. Pass 'savePath' to write the array to a JSON file instead: the response is then {path,bytes,count,target} with no cookie value in any form, the way to capture a session cookie without putting the credential in the transcript.",
10971
11353
  params: {
10972
11354
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
10973
- target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Grammar: see server instructions.",
11355
+ target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Prefix any of these with 'endpoint:<name>/' for a named CDP endpoint (Chrome only). Grammar: see server instructions.",
10974
11356
  domain: "Keep only cookies for this domain. A leading dot is ignored on both sides and subdomains match too, so 'example.test' matches '.example.test' and 'app.example.test'. No wildcards.",
10975
11357
  name: "Keep only the cookie with exactly this name. Exact match, not a substring.",
10976
11358
  savePath: "Write the cookie array here as JSON and KEEP THE VALUES OUT OF THE RESPONSE: the result is {path,bytes,count,target} only, with no preview or truncation of any value. An absolute path (starting with /) is used as-is; a relative path resolves under the artifact dir (/tmp/cdp-toolkit); missing parents are created. Omit to get the cookies back inline."
@@ -10980,7 +11362,7 @@ var TOOL_DOCS = {
10980
11362
  description: "Write one cookie into the target page's cookie store, INCLUDING httpOnly or secure cookies that document.cookie (and therefore evaluate_script) cannot create. Either 'url' or 'domain' is REQUIRED: the call is refused when neither is given, rather than guessing the page origin. The response is {set:true,target} and never echoes the value back. A 'set:true' is earned, not assumed: Chrome raises an error when it declines the cookie (a domain the url does not belong to, a secure cookie on an insecure origin, an oversized value). On Firefox 'domain' is derived from 'url' when only the url was given (BiDi has no url parameter), and a url with no host such as about:blank or a data URL is an error, not a silent no-op. Read the result back with list_cookies when you need proof.",
10981
11363
  params: {
10982
11364
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
10983
- target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Grammar: see server instructions.",
11365
+ target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Prefix any of these with 'endpoint:<name>/' for a named CDP endpoint (Chrome only). Grammar: see server instructions.",
10984
11366
  name: "Cookie name. Required and non-empty.",
10985
11367
  value: "Cookie value. Required. It is not echoed back in the response.",
10986
11368
  url: "URL the cookie is set for, e.g. 'https://example.com/'. Chrome derives domain, path and secure from it; Firefox derives only the domain from its host. Give this or 'domain'.",
@@ -10996,7 +11378,7 @@ var TOOL_DOCS = {
10996
11378
  description: "Delete the named cookie from the target page's cookie store, httpOnly cookies included. Both 'name' and one of 'url' or 'domain' are REQUIRED: without a site constraint it would delete by name across the whole partition, so it is refused with an error instead. Narrow further with 'path'. The response is {deleted:true,target} and carries NO count, because neither protocol reports how many cookies it removed and a number here would be invented; call list_cookies before and after for a real count. 'deleted:true' means the backend accepted and performed the deletion, not that a matching cookie existed, since deleting an absent cookie succeeds on both backends.",
10997
11379
  params: {
10998
11380
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
10999
- target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Grammar: see server instructions.",
11381
+ target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Prefix any of these with 'endpoint:<name>/' for a named CDP endpoint (Chrome only). Grammar: see server instructions.",
11000
11382
  name: "Exact cookie name to delete. Required and non-empty. No wildcards: this removes a named cookie, not a swathe of them.",
11001
11383
  url: "Delete cookies matching this URL, e.g. 'https://example.com/'. Give this or 'domain'. On Firefox only the host is used, because BiDi's filter has no url field.",
11002
11384
  domain: "Delete cookies with this exact domain. Give this or 'url'.",
@@ -11007,7 +11389,7 @@ var TOOL_DOCS = {
11007
11389
  description: `Captures the page's accessibility tree as an indented text tree, each line prefixed [uid] (a CDP backendDOMNodeId). Every interaction tool (click/hover/fill/etc.) resolves that uid via DOM.resolveNode — run this first to discover uids to act on. Cross-origin iframe subtrees are not walked (they live in a separate renderer process); the iframe node itself is emitted with a frame="<targetId>" marker (also in interactiveOnly mode), so the frame is discoverable and driveable via that id or frame:<url-substring>.`,
11008
11390
  params: {
11009
11391
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
11010
- target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Grammar: see server instructions.",
11392
+ target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Prefix any of these with 'endpoint:<name>/' for a named CDP endpoint (Chrome only). Grammar: see server instructions.",
11011
11393
  interactiveOnly: "When true, emit only interactive/meaningful nodes as a flat list; default false returns the full hierarchical tree."
11012
11394
  }
11013
11395
  },
@@ -11015,7 +11397,7 @@ var TOOL_DOCS = {
11015
11397
  description: "Click an element via a synthetic mouse press/release at its scrolled-into-view center. Give exactly one of uid or selector. modifiers (Alt/Control/Meta/Shift) throws on the Firefox backend — use --browser chrome for a modifier-click. clickCount:3 triple-clicks (selects a line/paragraph in most editors).",
11016
11398
  params: {
11017
11399
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
11018
- target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Grammar: see server instructions.",
11400
+ target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Prefix any of these with 'endpoint:<name>/' for a named CDP endpoint (Chrome only). Grammar: see server instructions.",
11019
11401
  uid: "CDP backendDOMNodeId of the element to click, from take_snapshot. Exactly one of uid or selector.",
11020
11402
  selector: "CSS selector for the element to click (document.querySelector). Exactly one of uid or selector.",
11021
11403
  button: "Mouse button: 'left' (default), 'right', or 'middle'.",
@@ -11027,7 +11409,7 @@ var TOOL_DOCS = {
11027
11409
  description: "Hovers the mouse over an element by dispatching a mouseMoved event at its scrolled-into-view center, firing framework hover handlers. Give exactly one of uid or selector.",
11028
11410
  params: {
11029
11411
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
11030
- target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Grammar: see server instructions.",
11412
+ target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Prefix any of these with 'endpoint:<name>/' for a named CDP endpoint (Chrome only). Grammar: see server instructions.",
11031
11413
  uid: "CDP backendDOMNodeId of the element to hover, from take_snapshot. Exactly one of uid or selector.",
11032
11414
  selector: "CSS selector for the element to hover (document.querySelector). Exactly one of uid or selector."
11033
11415
  }
@@ -11036,7 +11418,7 @@ var TOOL_DOCS = {
11036
11418
  description: "Drags from a source element to a destination or by an offset. mode:'mouse' (default) dispatches synthetic mouse press/move/release; at the default steps:2 an HTML5 drop zone (dragover preventDefault) gets ZERO dragover events and refuses the drop. mode:'html5' replays real dragstart/dragEnter/dragOver/drop with the page's own dataTransfer instead — deterministic regardless of pointer path, but CHROME-ONLY (rejected with a clear error on the Firefox backend). 'from' takes uid or selector; destination is exactly one of 'to' (uid/selector/x+y) or 'by' ({dx,dy} offset — sliders, map panning, resize handles).",
11037
11419
  params: {
11038
11420
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
11039
- target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Grammar: see server instructions.",
11421
+ target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Prefix any of these with 'endpoint:<name>/' for a named CDP endpoint (Chrome only). Grammar: see server instructions.",
11040
11422
  from: "Source element to drag from. Exactly one of uid or selector.",
11041
11423
  to: "Where the drag ends: exactly one of uid, selector, or x+y. Mutually exclusive with 'by'; exactly one of to/by required.",
11042
11424
  by: "Offset from the source element's center: at least one of dx/dy (other defaults to 0). Mutually exclusive with 'to'; exactly one of to/by required. For sliders (by:{dx:40}), map panning, resize handles.",
@@ -11048,7 +11430,7 @@ var TOOL_DOCS = {
11048
11430
  description: "Dispatches a wheel/scroll event at an anchor point — element (uid/selector) or x+y, scrolled into view first if an element; omit all three for viewport center. At least one of deltaX/deltaY required: positive deltaY scrolls DOWN, positive deltaX scrolls RIGHT (wheel-event convention — easy to invert). Returns the resolved anchor {x,y} plus the delta actually dispatched.",
11049
11431
  params: {
11050
11432
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
11051
- target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Grammar: see server instructions.",
11433
+ target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Prefix any of these with 'endpoint:<name>/' for a named CDP endpoint (Chrome only). Grammar: see server instructions.",
11052
11434
  uid: "CDP backendDOMNodeId of the element to scroll into view and anchor at, from take_snapshot. At most one of uid, selector, or x+y.",
11053
11435
  selector: "CSS selector for the element to anchor at (document.querySelector). At most one of uid, selector, or x+y.",
11054
11436
  x: "Absolute viewport x-coordinate to anchor at; must be given with y. At most one of uid, selector, or x+y.",
@@ -11061,7 +11443,7 @@ var TOOL_DOCS = {
11061
11443
  description: "Dispatches one raw mouse event (move/down/up) at absolute viewport coordinates — the toolkit's lowest-level input primitive. Compose move/down/move/up calls yourself for anything click/drag's fixed sequences can't reach: canvas drag-painting, marquee/rubber-band selection, custom hit-testing widgets. Chrome-only: absent from tools/list under the Firefox backend, never present-and-throwing.",
11062
11444
  params: {
11063
11445
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
11064
- target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Grammar: see server instructions.",
11446
+ target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Prefix any of these with 'endpoint:<name>/' for a named CDP endpoint (Chrome only). Grammar: see server instructions.",
11065
11447
  action: "Which raw event to dispatch: 'move' (mouseMoved), 'down' (mousePressed), or 'up' (mouseReleased).",
11066
11448
  x: "Viewport x-coordinate. Required every call — CDP has no 'current pointer position' to default from.",
11067
11449
  y: "Viewport y-coordinate. Required every call.",
@@ -11074,7 +11456,7 @@ var TOOL_DOCS = {
11074
11456
  description: "Toggles CDP Emulation.setFocusEmulationEnabled on a tab: the page then BELIEVES it is focused (document.hasFocus()→true, visibilitychange stays 'visible', focus events fire) while the real OS window and active tab stay put — no focus theft. This is the primitive that unlocks focus-GATED UI (a button the site disables unless its tab is focused, e.g. Anthropic's Claude Code OAuth Authorize button on claude.ai/oauth/*) on a background tab. Chrome-only: WebDriver BiDi's emulation module has no focus primitive, so this tool is absent from tools/list under --browser firefox. Ports the core mechanism of the danbuhler/claude-code-auto-authorize extension. Remember to call with enabled:false to restore, or use click_focus_gated which restores automatically.",
11075
11457
  params: {
11076
11458
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
11077
- target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'.",
11459
+ target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Prefix any of these with 'endpoint:<name>/' for a named CDP endpoint (Chrome only).",
11078
11460
  enabled: "true = page reports focused/visible; false = restore the real focus state."
11079
11461
  }
11080
11462
  },
@@ -11082,7 +11464,7 @@ var TOOL_DOCS = {
11082
11464
  description: "One-call compose of focus emulation + trusted click for a focus-gated button: enables Emulation.setFocusEmulationEnabled, polls until the button (located by CSS selector OR exact visible-text match, e.g. 'Authorize') exists AND is enabled, dispatches a trusted move/press/release click via Input.dispatchMouseEvent (isTrusted:true — a content script's synthesized events can never satisfy a focus gate), then restores focus emulation off unless keepFocus. Built for the Claude Code OAuth Authorize button but works on any focus-gated control on a background tab. Throws with a diagnostic ('never located' vs 'found but stayed disabled') on timeout. Chrome-only; absent under --browser firefox.",
11083
11465
  params: {
11084
11466
  lease: "Lease token from claim_page. Omit for a tab this process holds. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease).",
11085
- target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'.",
11467
+ target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Prefix any of these with 'endpoint:<name>/' for a named CDP endpoint (Chrome only).",
11086
11468
  selector: "CSS selector of the button. Give exactly one of selector or text.",
11087
11469
  text: "Exact visible-text match of the button (trims whitespace, matches button/[role=button]/submit inputs), e.g. 'Authorize'. Give exactly one of selector or text.",
11088
11470
  timeoutMs: "Max ms to poll for the button to appear and become enabled. Default 30000.",
@@ -11113,7 +11495,7 @@ var TOOL_DOCS = {
11113
11495
  description: "Fills an element by focusing it, clearing existing content, then inserting value via Input.insertText (atomic paste-like commit, not per-character keystrokes — won't fire per-keypress handlers). Give exactly one of uid or selector.",
11114
11496
  params: {
11115
11497
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
11116
- target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Grammar: see server instructions.",
11498
+ target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Prefix any of these with 'endpoint:<name>/' for a named CDP endpoint (Chrome only). Grammar: see server instructions.",
11117
11499
  uid: "CDP backendDOMNodeId of the field to fill, from take_snapshot. Exactly one of uid or selector.",
11118
11500
  selector: "CSS selector for the field to fill (document.querySelector). Exactly one of uid or selector.",
11119
11501
  value: "Text value to set; the field is cleared first, overwriting existing content."
@@ -11123,7 +11505,7 @@ var TOOL_DOCS = {
11123
11505
  description: "Fills multiple form fields in one call; each is focused, cleared, then set via Input.insertText (overwrites existing content, same as fill). Each entry in the non-empty 'fields' array takes exactly one of uid or selector plus a string value.",
11124
11506
  params: {
11125
11507
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
11126
- target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Grammar: see server instructions.",
11508
+ target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Prefix any of these with 'endpoint:<name>/' for a named CDP endpoint (Chrome only). Grammar: see server instructions.",
11127
11509
  fields: "Non-empty array of fields to fill, each with exactly one of uid or selector plus a string value."
11128
11510
  }
11129
11511
  },
@@ -11131,7 +11513,7 @@ var TOOL_DOCS = {
11131
11513
  description: "Focuses an element and appends text via Input.insertText without clearing first — closest primitive to typing, but still atomic (not per-character keystrokes). Give exactly one of uid or selector.",
11132
11514
  params: {
11133
11515
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
11134
- target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Grammar: see server instructions.",
11516
+ target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Prefix any of these with 'endpoint:<name>/' for a named CDP endpoint (Chrome only). Grammar: see server instructions.",
11135
11517
  uid: "CDP backendDOMNodeId of the element to type into, from take_snapshot. Exactly one of uid or selector.",
11136
11518
  selector: "CSS selector for the element to type into (document.querySelector). Exactly one of uid or selector.",
11137
11519
  text: "Text to insert; appended to existing content rather than overwriting it."
@@ -11141,7 +11523,7 @@ var TOOL_DOCS = {
11141
11523
  description: "Dispatches a keyDown/keyUp pair for one key with optional modifiers. 'key' is a named key (Enter, Tab, Escape, ArrowDown, Backspace, etc.) or a single printable character — the named-key table is curated, with no F-keys, numpad, or IME support.",
11142
11524
  params: {
11143
11525
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
11144
- target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Grammar: see server instructions.",
11526
+ target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Prefix any of these with 'endpoint:<name>/' for a named CDP endpoint (Chrome only). Grammar: see server instructions.",
11145
11527
  key: "Key to press: a named key (Enter, Tab, Escape, ArrowDown, Backspace, ...) or a single printable character.",
11146
11528
  modifiers: "Modifier names held during the press: 'Control'/'Ctrl', 'Shift', 'Alt', 'Meta'/'Cmd'."
11147
11529
  }
@@ -11150,7 +11532,7 @@ var TOOL_DOCS = {
11150
11532
  description: "Attaches one or more files to an <input type=file> element via DOM.setFileInputFiles. Give exactly one of uid or selector for the input; 'files' is an array of absolute path(s) — wrap a single path in an array too.",
11151
11533
  params: {
11152
11534
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
11153
- target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Grammar: see server instructions.",
11535
+ target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Prefix any of these with 'endpoint:<name>/' for a named CDP endpoint (Chrome only). Grammar: see server instructions.",
11154
11536
  uid: "CDP backendDOMNodeId of the file input element, from take_snapshot. Exactly one of uid or selector.",
11155
11537
  selector: "CSS selector for the file input element (document.querySelector). Exactly one of uid or selector.",
11156
11538
  files: 'Absolute path(s) to attach to the <input type=file>, as an array — wrap a single path too, e.g. ["/tmp/a.pdf"]. Array-only because some model APIs (Google Gemini function calling) reject union-typed parameters.'
@@ -11160,7 +11542,7 @@ var TOOL_DOCS = {
11160
11542
  description: "Captures the viewport (default), the full scrollable page (fullPage), or one element (uid or selector, mutually exclusive) via CDP Page.captureScreenshot. Past 16384 device px per side Chrome can hang rather than refuse, so size is checked first via Page.getLayoutMetrics; an oversized capture is auto-tiled into vertical bands stitched losslessly into one PNG (see tile) instead of wedging the tab. Writes PNG/JPEG to /tmp/cdp-toolkit (override savePath, dir auto-created); returns {path,bytes,format,target,scale} plus width/height measured from the encoded bytes (omitted if undecodable). renderSize/renderRestored(+renderRestoreError) accompany a renderWidth/renderHeight capture, tiled/bands a banded one. returnBase64 adds raw bytes to the result but is refused on a banded capture. quality applies to jpeg only.",
11161
11543
  params: {
11162
11544
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
11163
- target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Grammar: see server instructions.",
11545
+ target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Prefix any of these with 'endpoint:<name>/' for a named CDP endpoint (Chrome only). Grammar: see server instructions.",
11164
11546
  format: "Image format, default png. quality applies only to jpeg.",
11165
11547
  quality: "JPEG quality 0-100, default 80; ignored for png.",
11166
11548
  fullPage: "Capture the full scrollable height (via Page.getLayoutMetrics), not just the viewport.",
@@ -11178,7 +11560,7 @@ var TOOL_DOCS = {
11178
11560
  description: "Applies any subset of Chrome emulation overrides in one call: device metrics (width+height together, +deviceScaleFactor/mobile), userAgent, cpuThrottlingRate(>=1), media type+features, networkConditions. Device-metrics overrides PERSIST on the target until cleared or the renderer navigates/reloads; every other override is session-scoped and resets when this call's connection closes. clearOverrides:true resets everything (ignoring other fields) and, as of 1.9.2, genuinely clears a device-metrics override set by a DIFFERENT process — Chrome's clearDeviceMetricsOverride is normally a no-op unless the clearing connection also set the override, so the driver re-asserts the tab's current size first, then clears, throwing rather than reporting cleared:true if it can't verify.",
11179
11561
  params: {
11180
11562
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
11181
- target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Grammar: see server instructions.",
11563
+ target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Prefix any of these with 'endpoint:<name>/' for a named CDP endpoint (Chrome only). Grammar: see server instructions.",
11182
11564
  width: "Device-metrics viewport width in CSS px. Must be paired with height.",
11183
11565
  height: "Device-metrics viewport height in CSS px. Must be paired with width.",
11184
11566
  deviceScaleFactor: "Device pixel ratio for the device-metrics override; 0 = platform default.",
@@ -11195,7 +11577,7 @@ var TOOL_DOCS = {
11195
11577
  description: "Sets the page's device-metrics width/height (the narrow case of emulate), optionally deviceScaleFactor/mobile, then verifies by reading back window.innerWidth/innerHeight after applying. Requires positive width and height. The override PERSISTS on the target until cleared (emulate{clearOverrides:true}) or the renderer navigates/reloads.",
11196
11578
  params: {
11197
11579
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
11198
- target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Grammar: see server instructions.",
11580
+ target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Prefix any of these with 'endpoint:<name>/' for a named CDP endpoint (Chrome only). Grammar: see server instructions.",
11199
11581
  width: "Viewport width in CSS px (required, must be positive).",
11200
11582
  height: "Viewport height in CSS px (required, must be positive).",
11201
11583
  deviceScaleFactor: "Device pixel ratio; 0 = platform default.",
@@ -11206,7 +11588,7 @@ var TOOL_DOCS = {
11206
11588
  description: "Wait for the next JavaScript dialog (alert/confirm/prompt/beforeunload) on a page and respond via Page.handleJavaScriptDialog, accepting or dismissing it. Default mode resolves with the first handled dialog or throws on timeout; set autoMs to handle every dialog opening during a fixed window and resolve with the list. Trigger the dialog out-of-band (e.g. click a button) — a blocking dialog freezes the renderer, so it cannot be triggered inline.",
11207
11589
  params: {
11208
11590
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
11209
- target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Grammar: see server instructions.",
11591
+ target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Prefix any of these with 'endpoint:<name>/' for a named CDP endpoint (Chrome only). Grammar: see server instructions.",
11210
11592
  accept: "Whether to accept (OK) or dismiss (Cancel) the dialog.",
11211
11593
  promptText: "Text to enter for a prompt() dialog when accepting.",
11212
11594
  timeoutMs: "How long to wait for the next dialog, in milliseconds (default 15000).",
@@ -11217,7 +11599,7 @@ var TOOL_DOCS = {
11217
11599
  description: "Read console output (logs, warnings, exceptions) captured for the target. Reads the existing shared buffer by default (empty if no capture ran); reload:true reloads and records a fresh capture (console+network together, so a network reload never wipes console history). WORKER capture (Chrome, Capability 'worker.targets'): a worker: target records an MV3 background service worker -- its console.log arrives as Runtime.consoleAPICalled, its outbound requests from CDP's Network domain on the worker's own session -- so the two tricks callers try first fail for plain JS reasons, not worker ones: a value bound at module top level is not visible from evaluate_script's global scope, and assigning self.fetch cannot rebind a fetch the module already captured. A worker has no reload: reload:true means 'listen for durationMs while it runs', so trigger its work (tool call, message, alarm) during the window; a worker woken by the call already ran its top-level code, so a startup message can be missed. SIDE EFFECT: the CDP session KEEPS THE WORKER ALIVE for the capture (an idle MV3 worker is evicted in seconds); Chrome resumes evicting after.",
11218
11600
  params: {
11219
11601
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
11220
- target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', '<targetId>'; plus 'worker:<substring>' to reach a service/shared worker (e.g. an MV3 extension background worker). The worker: arm is CHROME-ONLY (Capability 'worker.targets'). Grammar: see server instructions.",
11602
+ target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', '<targetId>'; plus 'worker:<substring>' to reach a service/shared worker (e.g. an MV3 extension background worker). The worker: arm is CHROME-ONLY (Capability 'worker.targets'). Prefix any of these with 'endpoint:<name>/' for a named CDP endpoint (Chrome only). Grammar: see server instructions.",
11221
11603
  reload: "Record fresh by reloading the page and capturing a window. Default false (read existing buffer). With a worker: target nothing reloads -- records for durationMs while the worker runs and keeps it alive until the capture stops.",
11222
11604
  durationMs: "Capture window for reload mode, in ms. Default 2500.",
11223
11605
  wake: "Worker targets only, when starting a capture. Default true: an idle-evicted MV3 service worker exists in no target listing, so it is started first (ServiceWorker.startWorker) and re-confirmed; false fails fast. Rejected on a page target, a bare target id, or a read-only call. See server instructions."
@@ -11227,7 +11609,7 @@ var TOOL_DOCS = {
11227
11609
  description: "Return one console entry by zero-based index from the target's existing console buffer. Throws if the index is out of range; run list_console_messages (optionally reload:true) first to populate the buffer.",
11228
11610
  params: {
11229
11611
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
11230
- target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Grammar: see server instructions.",
11612
+ target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Prefix any of these with 'endpoint:<name>/' for a named CDP endpoint (Chrome only). Grammar: see server instructions.",
11231
11613
  index: "Zero-based index into the parsed console entries. Default 0."
11232
11614
  }
11233
11615
  },
@@ -11235,7 +11617,7 @@ var TOOL_DOCS = {
11235
11617
  description: "Return correlated network rows (one per requestId; status/headers/state) for the target. Reads the existing buffer by default; reload:true records a fresh both-domains capture window. filterUrl keeps only URLs containing a substring. WORKER capture (Chrome, Capability 'worker.targets'): a worker: target records an MV3 background service worker's outbound requests from CDP's Network domain on the worker's own session -- what the code ACTUALLY SENT -- so the two tricks callers try first fail for plain JS reasons, not worker ones: a value bound at module top level is not visible from evaluate_script's global scope, and assigning self.fetch cannot rebind a fetch the module already captured. A worker has no reload: reload:true means 'listen for durationMs while it runs', so trigger its work (tool call, message, alarm) during the window; a worker woken by the call already ran its top-level code, so a startup request can be missed. SIDE EFFECT: the CDP session KEEPS THE WORKER ALIVE for the capture (an idle MV3 worker is evicted in seconds); Chrome resumes evicting after.",
11236
11618
  params: {
11237
11619
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
11238
- target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', '<targetId>'; plus 'worker:<substring>' to reach a service/shared worker (e.g. an MV3 extension background worker). The worker: arm is CHROME-ONLY (Capability 'worker.targets'). Grammar: see server instructions.",
11620
+ target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', '<targetId>'; plus 'worker:<substring>' to reach a service/shared worker (e.g. an MV3 extension background worker). The worker: arm is CHROME-ONLY (Capability 'worker.targets'). Prefix any of these with 'endpoint:<name>/' for a named CDP endpoint (Chrome only). Grammar: see server instructions.",
11239
11621
  reload: "Record fresh by reloading the page and capturing a window. Default false (read existing buffer). With a worker: target nothing reloads -- records for durationMs while the worker runs and keeps it alive until the capture stops.",
11240
11622
  durationMs: "Capture window for reload mode, in ms. Default 2500.",
11241
11623
  filterUrl: "Return only requests whose URL contains this substring.",
@@ -11246,7 +11628,7 @@ var TOOL_DOCS = {
11246
11628
  description: "Return one network request (matched by exact requestId, else url substring) with status/headers. Requires requestId or url (throws otherwise). includeBody:true drives a fresh capture (page reload, or worker listen window) matched by url ONLY -- a fresh capture re-mints requestIds, so a carried-over requestId returns metadata plus bodyUnavailableReason. WORKER capture (Chrome, Capability 'worker.targets'): a worker: target records an MV3 background service worker's outbound requests from CDP's Network domain on the worker's own session -- what the code ACTUALLY SENT -- so the two tricks callers try first fail for plain JS reasons, not worker ones: a value bound at module top level is not visible from evaluate_script's global scope, and assigning self.fetch cannot rebind a fetch the module already captured. A worker has no reload: reload means 'listen for durationMs while it runs', so trigger its work (tool call, message, alarm) during the window; a worker woken by the call already ran its top-level code, so a startup request can be missed. SIDE EFFECT: the CDP session KEEPS THE WORKER ALIVE for the capture (an idle MV3 worker is evicted in seconds); Chrome resumes evicting after.",
11247
11629
  params: {
11248
11630
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
11249
- target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', '<targetId>'; plus 'worker:<substring>' to reach a service/shared worker (e.g. an MV3 extension background worker). The worker: arm is CHROME-ONLY (Capability 'worker.targets'). Grammar: see server instructions.",
11631
+ target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', '<targetId>'; plus 'worker:<substring>' to reach a service/shared worker (e.g. an MV3 extension background worker). The worker: arm is CHROME-ONLY (Capability 'worker.targets'). Prefix any of these with 'endpoint:<name>/' for a named CDP endpoint (Chrome only). Grammar: see server instructions.",
11250
11632
  requestId: "Match by exact requestId (metadata only; cannot fetch a body, since a reload re-mints requestIds).",
11251
11633
  url: "Match by URL substring (first match). Required for body fetch (includeBody), since url is stable across reload.",
11252
11634
  includeBody: "Also fetch the response body; drives a fresh capture and requires the url selector.",
@@ -11258,7 +11640,7 @@ var TOOL_DOCS = {
11258
11640
  description: "Starts a CDP trace recording on the target and holds the recording connection in-process; you MUST call performance_stop_trace from the SAME PROCESS to end it, or use performance_trace instead for a robust cross-call trace. Throws if a trace is already in progress for this target.",
11259
11641
  params: {
11260
11642
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
11261
- target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Grammar: see server instructions.",
11643
+ target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Prefix any of these with 'endpoint:<name>/' for a named CDP endpoint (Chrome only). Grammar: see server instructions.",
11262
11644
  categories: "Trace categories to record. Defaults to timeline + user-timing + loading + disabled-by-default timeline tracks carrying LCP/LayoutShift/RunTask."
11263
11645
  }
11264
11646
  },
@@ -11266,7 +11648,7 @@ var TOOL_DOCS = {
11266
11648
  description: "Stops the in-process trace started by performance_start_trace and writes it as JSON under /tmp/cdp-toolkit, returning {path,bytes,events,metrics}. Throws if no live trace exists in THIS process (e.g. start ran in a different process) — use performance_trace instead. The target arg is accepted only for API symmetry; at most one trace is ever live per process.",
11267
11649
  params: {
11268
11650
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
11269
- target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Grammar: see server instructions."
11651
+ target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Prefix any of these with 'endpoint:<name>/' for a named CDP endpoint (Chrome only). Grammar: see server instructions."
11270
11652
  }
11271
11653
  },
11272
11654
  performance_analyze_insight: {
@@ -11280,7 +11662,7 @@ var TOOL_DOCS = {
11280
11662
  description: "RECOMMENDED entry point: one-shot trace that starts tracing, optionally reloads or navigates the page, waits durationMs (default 3000ms), stops, and writes JSON under /tmp/cdp-toolkit — returns {path,bytes,events,metrics,target}. Holds one connection open for the whole window, so unlike start/stop it is NOT limited to a single process.",
11281
11663
  params: {
11282
11664
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
11283
- target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Grammar: see server instructions.",
11665
+ target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Prefix any of these with 'endpoint:<name>/' for a named CDP endpoint (Chrome only). Grammar: see server instructions.",
11284
11666
  durationMs: "How long to record after the optional reload/navigate, in ms. Default 3000.",
11285
11667
  reload: "Reload the page after starting the trace, to capture full navigation timing.",
11286
11668
  navigateTo: "Navigate to this URL after starting the trace (alternative to reload).",
@@ -11291,7 +11673,7 @@ var TOOL_DOCS = {
11291
11673
  description: "Starts recording the target tab to video via CDP Page.startScreencast, holding one persistent connection and spooling every frame to disk — MUST be paired with stop_screen_recording WITHIN THE SAME PROCESS (frames are connection-scoped and cannot be reattached from another process, so this only works under the MCP server, not the one-process-per-call CLI). Chrome only: WebDriver BiDi has no screencast primitive, so both tools are absent under --browser firefox. Frames arrive ON REPAINT not on a clock (variable rate); each is timestamped into a ledger that stop_screen_recording turns into per-frame display durations, so a still page holds one long frame instead of racing. ffmpeg is probed here (not at stop) so a missing encoder fails before frames are captured and thrown away. Throws if the target already has a recording in progress; different targets record concurrently.",
11292
11674
  params: {
11293
11675
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
11294
- target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Grammar: see server instructions.",
11676
+ target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Prefix any of these with 'endpoint:<name>/' for a named CDP endpoint (Chrome only). Grammar: see server instructions.",
11295
11677
  format: "Frame format, default jpeg (much smaller per repaint); png is lossless. quality applies to jpeg only.",
11296
11678
  quality: "JPEG frame quality 0-100. Ignored for png; omitted leaves Chrome's own default.",
11297
11679
  maxWidth: "Caps the streamed frame width in px; also pins frame size if the viewport may change mid-recording.",
@@ -11312,7 +11694,7 @@ var TOOL_DOCS = {
11312
11694
  description: "Captures a V8 heap snapshot of the target page over CDP and writes it as a .heapsnapshot JSON file (loadable in the DevTools Memory panel) under /tmp/cdp-toolkit unless savePath is given. Returns {path,bytes,chunks,target} only — does NOT parse or summarize the snapshot.",
11313
11695
  params: {
11314
11696
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
11315
- target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Grammar: see server instructions.",
11697
+ target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Prefix any of these with 'endpoint:<name>/' for a named CDP endpoint (Chrome only). Grammar: see server instructions.",
11316
11698
  savePath: "Override the output path. Absolute paths (starting with /) are used as-is; relative paths resolve under the artifact dir (/tmp/cdp-toolkit). Defaults to an auto-named take_heapsnapshot-<targetId>-<timestamp>.heapsnapshot file."
11317
11699
  }
11318
11700
  },
@@ -11386,7 +11768,7 @@ var TOOL_DOCS = {
11386
11768
  description: "Structured extraction: take the target page's HTML, clean it, and send it to an OpenAI-compatible /chat/completions endpoint along with your JSON Schema, getting back schema-conformant JSON instead of prose. THE DEFAULT ENDPOINT IS LOOPBACK - llm-ferry at http://127.0.0.1:8090/v1 with model 'schematron' - so page content stays ON THIS MACHINE unless the operator overrides baseUrl (or sets CDP_EXTRACT_BASE_URL). Configuration: CDP_EXTRACT_BASE_URL (endpoint override), CDP_EXTRACT_MODEL (model override), CDP_EXTRACT_API_KEY (bearer token; never logged and REDACTED from every error), CDP_EXTRACT_TIMEOUT_MS, CDP_EXTRACT_MAX_CHARS, CDP_EXTRACT_PROMPT. PROMPT SHAPE: by default only the cleaned HTML is sent and the schema rides in response_format, which is what the HOSTED Schematron API expects (it injects the schema server-side); set prompt:'schematron' when baseUrl points at a LOCALLY SERVED open-weight Schematron (e.g. an MLX schematron8B), because that model was fine-tuned on a prompt with the schema INSIDE the user message and an HTML-only prompt returns garbage from it even under constrained decoding. In 'schematron' mode NO response_format is sent at all - the schema already lives in the prompt, and the client validates only that the response parses as JSON. THE SCHEMA-DESCRIPTION RULE: this is prompt-driven extraction, and the extraction INSTRUCTIONS live in the schema's property descriptions - write them like prompts ('the job title, exactly as printed', 'ISO date, not 'yesterday'). A schema whose properties carry no descriptions is REJECTED up front with an error saying so, because it would produce garbage extraction with no hint why. Source: 'dom' (live DOM, the rendered, JS-executed page) is the default; 'served' (the raw server response before rendering) currently returns a not-implemented error rather than guessing. Size guard: cleaned HTML over maxChars (default 300000) fails with html_too_large naming the actual size - shrink the payload with 'selector' to scope to a subtree, clean:'aggressive' to strip harder (standard already drops scripts/styles/hidden), or a larger maxChars if you truly need it all. Endpoint failures surface as upstream_error (with status and body, API key redacted) or timeout; the response never contains the key. A completion the endpoint cut off at its 8192-token output cap fails naming finish_reason=length and the fix (narrow with 'selector', or ask the schema for less) - it is NOT reported as invalid JSON, because a truncated tail is a size problem, not a model one. COST IS ALWAYS VISIBLE: every successful call reports the endpoint's usage token counts inline, so a slow/bloated extraction is visible in the answer itself, not discovered on a bill later.",
11387
11769
  params: {
11388
11770
  lease: "Lease token from claim_page. Omit for a tab this process holds; required for a tab held by another process or one claimed explicitly. Auto-acquired under CDP_REQUIRE_LEASE (then pass target, not lease). See server instructions.",
11389
- target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Grammar: see server instructions.",
11771
+ target: "Page selector: 'active' (default), 'index:N', 'url:<substr>', 'title:<substr>', 'label:<name>', or a 32-hex '<targetId>'. Prefix any of these with 'endpoint:<name>/' for a named CDP endpoint (Chrome only). Grammar: see server instructions.",
11390
11772
  schema: "REQUIRED JSON Schema object (type object) describing the JSON you want back. This is both the contract AND the prompt: each property's 'description' tells the extractor what to put there, so make them specific instructions. A schema with no property descriptions at all is rejected before any page work happens - empty descriptions extract garbage and the error says exactly what to fix. Nested objects and arrays of objects work; their inner descriptions count too.",
11391
11773
  selector: "CSS selector scoping extraction to that subtree's HTML only (pierces open shadow roots). The cheapest fix for html_too_large: extract the article or table, not the whole page. Omit to send the full cleaned document.",
11392
11774
  source: "'dom' (default) reads the live, rendered DOM - what the page shows after JS ran. 'served' would read the raw HTTP response before rendering; it currently returns a not-implemented error naming the arm, so callers can detect and fall back rather than guessing.",
@@ -11401,8 +11783,104 @@ var TOOL_DOCS = {
11401
11783
  }
11402
11784
  };
11403
11785
 
11786
+ // src/policy.ts
11787
+ var READ_TOOLS = new Set([
11788
+ "list_pages",
11789
+ "wait_for",
11790
+ "evaluate_script",
11791
+ "list_cookies",
11792
+ "take_snapshot",
11793
+ "take_screenshot",
11794
+ "list_console_messages",
11795
+ "get_console_message",
11796
+ "list_network_requests",
11797
+ "get_network_request",
11798
+ "performance_analyze_insight",
11799
+ "take_heapsnapshot",
11800
+ "list_mocks",
11801
+ "extract_page",
11802
+ "list_leases"
11803
+ ]);
11804
+ var MUTATING_TOOLS = new Set([
11805
+ "new_page",
11806
+ "close_page",
11807
+ "select_page",
11808
+ "navigate_page",
11809
+ "set_cookie",
11810
+ "delete_cookies",
11811
+ "click",
11812
+ "hover",
11813
+ "drag",
11814
+ "scroll",
11815
+ "fill",
11816
+ "fill_form",
11817
+ "type_text",
11818
+ "press_key",
11819
+ "upload_file",
11820
+ "emulate",
11821
+ "resize_page",
11822
+ "handle_dialog",
11823
+ "performance_start_trace",
11824
+ "performance_stop_trace",
11825
+ "performance_trace",
11826
+ "start_screen_recording",
11827
+ "stop_screen_recording",
11828
+ "lighthouse_audit",
11829
+ "mock_request",
11830
+ "clear_mocks",
11831
+ "dispatch_mouse",
11832
+ "focus_emulation",
11833
+ "click_focus_gated",
11834
+ "wait_for_download",
11835
+ "grant_permissions",
11836
+ "claim_page",
11837
+ "release_page"
11838
+ ]);
11839
+ var META_TOOLS = new Set(["search_tools", "call_tool", "describe_tool"]);
11840
+
11841
+ class PolicyError extends Error {
11842
+ code = "read_only_endpoint";
11843
+ tool;
11844
+ endpoint;
11845
+ constructor(tool, endpoint) {
11846
+ 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)`);
11847
+ this.name = "PolicyError";
11848
+ this.tool = tool;
11849
+ this.endpoint = endpoint;
11850
+ }
11851
+ }
11852
+ function escalatesToMutation(tool, args) {
11853
+ if (typeof args !== "object" || args === null)
11854
+ return false;
11855
+ const a = args;
11856
+ switch (tool) {
11857
+ case "list_console_messages":
11858
+ case "list_network_requests":
11859
+ return a.reload === true;
11860
+ case "get_network_request":
11861
+ return a.includeBody === true && typeof a.url === "string" && a.url !== "";
11862
+ case "take_screenshot":
11863
+ return a.renderWidth !== undefined || a.renderHeight !== undefined;
11864
+ default:
11865
+ return false;
11866
+ }
11867
+ }
11868
+ function assertAllowed(tool, endpoint, args) {
11869
+ if (!endpoint.readOnly)
11870
+ return;
11871
+ if (META_TOOLS.has(tool))
11872
+ return;
11873
+ if (!READ_TOOLS.has(tool))
11874
+ throw new PolicyError(tool, endpoint.name);
11875
+ if (escalatesToMutation(tool, args))
11876
+ throw new PolicyError(tool, endpoint.name);
11877
+ }
11878
+ function toolAnnotations(name) {
11879
+ return { readOnlyHint: READ_TOOLS.has(name) };
11880
+ }
11881
+
11404
11882
  // src/version.ts
11405
- var VERSION = "3.0.3";
11883
+ var VERSION = "3.1.0";
11406
11884
 
11407
11885
  // src/mcp.ts
11408
11886
  function isDirectRun() {
@@ -11462,14 +11940,14 @@ function auditCoverage() {
11462
11940
  var INSTRUCTIONS = [
11463
11941
  "cdp-toolkit drives a real browser over CDP (or Firefox WebDriver-BiDi): pages, input, screenshots, snapshots, console, network, cookies, emulation, Lighthouse, traces, screencasts.",
11464
11942
  "TOOLS: by default only 5 are listed (navigate_page, take_snapshot, click, fill, evaluate_script). ~45 more exist: find one with search_tools {query} (returns its schema; no query = catalog), run it with call_tool {name, arguments}. No tab yet? call_tool {name:'new_page'}. The listing is fixed for the process's life; CDP_TOOL_PROFILE=full lists everything.",
11465
- "TARGET SELECTOR (the `target` param, unless a tool says otherwise): 'active' (default = first page) | 'index:N' (0-based) | 'url:<substr>' | 'title:<substr>' | 'label:<name>' (exact, ledger or live lease) | a 32-hex '<targetId>' of any target type — an iframe id from list_pages{all:true} drives like a tab. Chrome tools also accept 'frame:<substr>' for OOPIF iframe targets. Four Chrome-only tools (evaluate_script, list_network_requests, get_network_request, list_console_messages) also accept 'worker:<substr>' to reach a service/shared worker (e.g. an MV3 background worker); an idle-evicted worker is started first (see `wake`).",
11943
+ "TARGET SELECTOR (the `target` param, unless a tool says otherwise): 'active' (default = first page) | 'index:N' (0-based) | 'url:<substr>' | 'title:<substr>' | 'label:<name>' (exact, ledger or live lease) | a 32-hex '<targetId>' of any target type — an iframe id from list_pages{all:true} drives like a tab. Chrome tools also accept 'frame:<substr>' for OOPIF iframe targets. Four Chrome-only tools (evaluate_script, list_network_requests, get_network_request, list_console_messages) also accept 'worker:<substr>' to reach a service/shared worker (e.g. MV3 background); an idle-evicted worker is started first (see `wake`). Prefix 'endpoint:<name>/' for a named CDP endpoint; an app endpoint (Teams) lists an empty host page first: use title:.",
11466
11944
  "LEASES (the `lease` param): claim_page, and new_page{claim:true}, mint an opaque token. Omit it for a tab THIS process already holds. It is required for a tab held by ANOTHER process, or one claimed explicitly. Under CDP_REQUIRE_LEASE the gate auto-acquires a lease for any tab this process drives — no token is surfaced, so pass `target`, not `lease` — while an explicit claim:true still demands its token on every later call.",
11467
11945
  "ORIGIN: list_pages and list_leases tag each tab's `origin` as 'agent' (this toolkit created it) or 'unknown' — never 'human', because the toolkit cannot prove a person opened a tab. An 'agent' tab stays findable after its creator releases the lease or dies."
11468
11946
  ].join(`
11469
11947
 
11470
11948
  `);
11471
11949
  var PROFILE = startupProfile();
11472
- var META_TOOLS = new Set(["search_tools", "call_tool", "describe_tool"]);
11950
+ var META_TOOLS2 = new Set(["search_tools", "call_tool", "describe_tool"]);
11473
11951
  var SEARCH_DEFAULT_LIMIT = 8;
11474
11952
  var SEARCH_MAX_LIMIT = 20;
11475
11953
  function startupProfile() {
@@ -11497,7 +11975,8 @@ var LISTING = Object.freeze([
11497
11975
  }
11498
11976
  },
11499
11977
  additionalProperties: false
11500
- }
11978
+ },
11979
+ annotations: { readOnlyHint: true }
11501
11980
  },
11502
11981
  {
11503
11982
  name: "call_tool",
@@ -11510,9 +11989,10 @@ var LISTING = Object.freeze([
11510
11989
  },
11511
11990
  required: ["name"],
11512
11991
  additionalProperties: false
11513
- }
11992
+ },
11993
+ annotations: { readOnlyHint: false }
11514
11994
  },
11515
- ...MANIFEST.filter((s) => AVAILABLE_NAMES.has(s.name) && isListed(PROFILE, s.name)).map((s) => ({ name: s.name, description: s.description, inputSchema: s.inputSchema }))
11995
+ ...MANIFEST.filter((s) => AVAILABLE_NAMES.has(s.name) && isListed(PROFILE, s.name)).map((s) => ({ name: s.name, description: s.description, inputSchema: s.inputSchema, annotations: toolAnnotations(s.name) }))
11516
11996
  ]);
11517
11997
  function renderCatalog() {
11518
11998
  const lines = [
@@ -11627,7 +12107,7 @@ function buildServer() {
11627
12107
  if (typeof inner.name !== "string" || inner.name === "") {
11628
12108
  return { content: [{ type: "text", text: "call_tool: `name` is required (find one with search_tools)" }], isError: true };
11629
12109
  }
11630
- if (META_TOOLS.has(inner.name)) {
12110
+ if (META_TOOLS2.has(inner.name)) {
11631
12111
  return { content: [{ type: "text", text: `call_tool: '${inner.name}' is a meta-tool; call it directly` }], isError: true };
11632
12112
  }
11633
12113
  const innerArgs = inner.arguments ?? {};
@@ -11640,6 +12120,14 @@ function buildServer() {
11640
12120
  });
11641
12121
  return server;
11642
12122
  }
12123
+ function endpointsLogSuffix() {
12124
+ if (BROWSER !== "chrome")
12125
+ return "";
12126
+ const eps = allEndpoints();
12127
+ if (eps.length < 2)
12128
+ return "";
12129
+ return `, endpoints=${eps.map((e) => `${e.name}=${e.base}${e.readOnly ? "(read)" : ""}`).join(",")}`;
12130
+ }
11643
12131
  async function runTool(name, args) {
11644
12132
  if (!AVAILABLE_NAMES.has(name)) {
11645
12133
  const gap = AVAILABILITY.unavailable.find((u) => u.name === name);
@@ -11654,20 +12142,25 @@ async function runTool(name, args) {
11654
12142
  if (!fn)
11655
12143
  return { content: [{ type: "text", text: `unknown tool: ${name}` }], isError: true };
11656
12144
  try {
11657
- const result = await fn(args);
11658
- return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
12145
+ const { endpoint, args: toolArgs } = stripEndpointArgs(args);
12146
+ assertAllowed(name, endpoint, toolArgs);
12147
+ const result = await withEndpointScope(endpoint, () => fn(toolArgs));
12148
+ return { content: [{ type: "text", text: JSON.stringify(result ?? null, null, 2) }] };
11659
12149
  } catch (err) {
11660
12150
  const message = err instanceof Error ? err.message : String(err);
11661
12151
  return { content: [{ type: "text", text: `Error: ${message}` }], isError: true };
11662
12152
  }
11663
12153
  }
12154
+ if (usesEndpointArgs(args)) {
12155
+ return { content: [{ type: "text", text: `Error: ${ENDPOINTS_FIREFOX_MESSAGE}` }], isError: true };
12156
+ }
11664
12157
  const neutralFn = neutralDispatch[name];
11665
12158
  if (!neutralFn)
11666
12159
  return { content: [{ type: "text", text: `unknown tool: ${name}` }], isError: true };
11667
12160
  try {
11668
12161
  const session = await getOrCreateFirefoxSession({ endpoint: FIREFOX_ENDPOINT });
11669
12162
  const result = await neutralFn(session.driver, args);
11670
- return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }] };
12163
+ return { content: [{ type: "text", text: JSON.stringify(result ?? null, null, 2) }] };
11671
12164
  } catch (err) {
11672
12165
  const message = err instanceof Error ? err.message : String(err);
11673
12166
  return { content: [{ type: "text", text: `Error: ${message}` }], isError: true };
@@ -11678,6 +12171,14 @@ async function run2(argv) {
11678
12171
  const serve = parseServeOptions(argv);
11679
12172
  auditCoverage();
11680
12173
  markLongLivedProcess();
12174
+ if (BROWSER === "chrome") {
12175
+ try {
12176
+ endpointConfig();
12177
+ } catch (err) {
12178
+ console.error(`[cdp-toolkit] ${err instanceof Error ? err.message : String(err)}`);
12179
+ process.exit(1);
12180
+ }
12181
+ }
11681
12182
  let stdioHandle;
11682
12183
  let httpHandler;
11683
12184
  let listener;
@@ -11708,7 +12209,7 @@ async function run2(argv) {
11708
12209
  return buildServer();
11709
12210
  }, { onerror: (err) => console.error(`[cdp-toolkit] stdio: ${err.message}`) });
11710
12211
  process.stdin.on("close", () => void shutdown());
11711
- console.error(`[cdp-toolkit] MCP server v${VERSION} ready, browser=${BROWSER}${FIREFOX_ENDPOINT ? ` (attach ${FIREFOX_ENDPOINT})` : ""}, ${AVAILABILITY.available.length} tools available, ${LISTING.length} listed (CDP_TOOL_PROFILE=${PROFILE.label}), CDP_BASE=${BASE}`);
12212
+ console.error(`[cdp-toolkit] MCP server v${VERSION} ready, browser=${BROWSER}${FIREFOX_ENDPOINT ? ` (attach ${FIREFOX_ENDPOINT})` : ""}, ${AVAILABILITY.available.length} tools available, ${LISTING.length} listed (CDP_TOOL_PROFILE=${PROFILE.label}), CDP_BASE=${BASE}${endpointsLogSuffix()}`);
11712
12213
  return;
11713
12214
  }
11714
12215
  if (typeof Bun === "undefined") {
@@ -11724,7 +12225,7 @@ async function run2(argv) {
11724
12225
  hostname: serve.host,
11725
12226
  fetch: (req) => hostHeaderValidationResponse(req, localhostAllowedHostnames()) ?? originValidationResponse(req, localhostAllowedOrigins()) ?? httpHandler.fetch(req)
11726
12227
  });
11727
- console.error(`[cdp-toolkit] MCP server v${VERSION} listening on streamable-http port ${listener.port} (http://${serve.host}:${listener.port}/), browser=${BROWSER}${FIREFOX_ENDPOINT ? ` (attach ${FIREFOX_ENDPOINT})` : ""}, ${AVAILABILITY.available.length} tools available, ${LISTING.length} listed (CDP_TOOL_PROFILE=${PROFILE.label}), CDP_BASE=${BASE}`);
12228
+ console.error(`[cdp-toolkit] MCP server v${VERSION} listening on streamable-http port ${listener.port} (http://${serve.host}:${listener.port}/), browser=${BROWSER}${FIREFOX_ENDPOINT ? ` (attach ${FIREFOX_ENDPOINT})` : ""}, ${AVAILABILITY.available.length} tools available, ${LISTING.length} listed (CDP_TOOL_PROFILE=${PROFILE.label}), CDP_BASE=${BASE}${endpointsLogSuffix()}`);
11728
12229
  }
11729
12230
  if (isDirectRun()) {
11730
12231
  run2(process.argv.slice(2)).catch((err) => {