cdp-toolkit 3.0.2 → 3.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +25 -0
- package/CONTRACT.md +2 -2
- package/README.md +85 -2
- package/dist/bidi/mux-daemon.js +316 -10
- package/dist/cli.js +615 -94
- package/dist/index.js +440 -41
- package/dist/mcp.js +667 -133
- package/package.json +1 -1
- package/src/cdp/driver.ts +71 -11
- package/src/cli.ts +17 -4
- package/src/client.ts +22 -6
- package/src/endpoints.ts +428 -0
- package/src/install/browser.ts +9 -3
- package/src/install/wizard.ts +8 -8
- package/src/leases-tools.ts +6 -3
- package/src/leases.ts +28 -4
- package/src/manifest.ts +54 -42
- package/src/mcp.ts +52 -8
- package/src/origins.ts +5 -2
- package/src/policy.ts +163 -0
- package/src/reap.ts +14 -0
- package/src/shared-tools.ts +72 -4
- package/src/toolDocs.ts +39 -36
- package/src/tools/browser-session.ts +26 -12
- package/src/tools/dispatch-mouse.ts +2 -1
- package/src/tools/focus-emulation.ts +5 -3
- package/src/tools/lighthouse.ts +4 -2
- package/src/version.ts +1 -1
package/src/endpoints.ts
ADDED
|
@@ -0,0 +1,428 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Named CDP endpoints (issue #15): one process, several DevTools ports.
|
|
3
|
+
*
|
|
4
|
+
* A LEAF MODULE ON PURPOSE. client.ts, leases.ts and origins.ts all import it,
|
|
5
|
+
* so it imports nothing from this package, only node builtins.
|
|
6
|
+
*
|
|
7
|
+
* CONFIG SOURCES, all optional:
|
|
8
|
+
* CDP_BASE the single-endpoint shorthand. It is the endpoint named
|
|
9
|
+
* `default`, stored VERBATIM (no normalization, no
|
|
10
|
+
* validation), so `${base}${path}` is byte-for-byte what
|
|
11
|
+
* it was before this module existed.
|
|
12
|
+
* CDP_ENDPOINTS "browser=http://127.0.0.1:9222,teams=http://127.0.0.1:9333?mode=read"
|
|
13
|
+
* CDP_ENDPOINTS_FILE path to JSON:
|
|
14
|
+
* {"default":"browser","endpoints":{"browser":{"base":"http://127.0.0.1:9222"},
|
|
15
|
+
* "teams":{"base":"http://127.0.0.1:9333","readOnly":true}}}
|
|
16
|
+
* `"mode":"read"` is accepted as an alias of `"readOnly":true`.
|
|
17
|
+
*
|
|
18
|
+
* PRECEDENCE AND MERGING. The env string and the file are merged, never
|
|
19
|
+
* shadowed: a name both define must define it identically (same base, same
|
|
20
|
+
* mode), otherwise it is a config error, so precedence can never silently pick
|
|
21
|
+
* the wrong port. Order (which matters only for listing) is env string, then
|
|
22
|
+
* file. The DEFAULT endpoint is the file's `"default"` key if present, else the
|
|
23
|
+
* endpoint named `default`. When no source defines `default`, it is synthesized
|
|
24
|
+
* from CDP_BASE, else http://127.0.0.1:9222, exactly as before; it is NOT
|
|
25
|
+
* synthesized when the file names a different default and CDP_BASE is unset.
|
|
26
|
+
* When CDP_BASE is set and the config also defines `default`, both must agree on
|
|
27
|
+
* the base.
|
|
28
|
+
*
|
|
29
|
+
* NAMES are [A-Za-z0-9_]+ (no '-'): the name lands in lease and origin
|
|
30
|
+
* filenames as `lease-chrome@<name>-<targetId>.json`, and a '-' in it would make
|
|
31
|
+
* the name/id boundary unparseable.
|
|
32
|
+
*
|
|
33
|
+
* Malformed config throws EndpointConfigError naming the problem. Nothing here
|
|
34
|
+
* caches a failure: a bad file that gets fixed is picked up on the next call,
|
|
35
|
+
* and endpoint reachability is never consulted at all (connect-per-call already
|
|
36
|
+
* retries a port that was down at startup).
|
|
37
|
+
*/
|
|
38
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
39
|
+
import { readFileSync } from "node:fs";
|
|
40
|
+
|
|
41
|
+
export interface Endpoint {
|
|
42
|
+
name: string;
|
|
43
|
+
base: string;
|
|
44
|
+
readOnly: boolean;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export class EndpointConfigError extends Error {
|
|
48
|
+
constructor(message: string) {
|
|
49
|
+
super(message);
|
|
50
|
+
this.name = "EndpointConfigError";
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** The implicit base when nothing is configured; unchanged from client.ts's old const. */
|
|
55
|
+
export const DEFAULT_CDP_BASE = "http://127.0.0.1:9222";
|
|
56
|
+
|
|
57
|
+
/** The selector prefix, e.g. `endpoint:teams/title:Chat`. */
|
|
58
|
+
export const ENDPOINT_PREFIX = "endpoint:";
|
|
59
|
+
|
|
60
|
+
const NAME_RE = /^[A-Za-z0-9_]+$/;
|
|
61
|
+
|
|
62
|
+
export interface EndpointConfig {
|
|
63
|
+
default: Endpoint;
|
|
64
|
+
byName: Map<string, Endpoint>;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function checkName(name: string, where: string): void {
|
|
68
|
+
if (!NAME_RE.test(name)) {
|
|
69
|
+
throw new EndpointConfigError(
|
|
70
|
+
`${where}: endpoint name '${name}' is invalid; names are letters, digits and '_' only (no '-', '/', ':' or spaces)`,
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Compare bases on a trailing-slash-insensitive form. Never used to BUILD a URL. */
|
|
76
|
+
function sameBase(a: string, b: string): boolean {
|
|
77
|
+
return a.replace(/\/+$/, "") === b.replace(/\/+$/, "");
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Parse one configured base URL (from CDP_ENDPOINTS or the file), pulling out `?mode=`. */
|
|
81
|
+
function parseBase(raw: string, where: string): { base: string; mode?: "read" | "write" } {
|
|
82
|
+
let url: URL;
|
|
83
|
+
try {
|
|
84
|
+
url = new URL(raw);
|
|
85
|
+
} catch {
|
|
86
|
+
throw new EndpointConfigError(`${where}: '${raw}' is not a valid URL (expected e.g. http://127.0.0.1:9222)`);
|
|
87
|
+
}
|
|
88
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
|
89
|
+
throw new EndpointConfigError(`${where}: '${raw}' must be an http:// or https:// DevTools origin, not ${url.protocol}`);
|
|
90
|
+
}
|
|
91
|
+
if (url.hash) throw new EndpointConfigError(`${where}: '${raw}' must not carry a #fragment`);
|
|
92
|
+
let mode: "read" | "write" | undefined;
|
|
93
|
+
for (const [key, value] of url.searchParams) {
|
|
94
|
+
if (key !== "mode") {
|
|
95
|
+
throw new EndpointConfigError(`${where}: unknown query parameter '${key}' in '${raw}' (only ?mode=read or ?mode=write is understood)`);
|
|
96
|
+
}
|
|
97
|
+
if (value !== "read" && value !== "write") {
|
|
98
|
+
throw new EndpointConfigError(`${where}: unknown mode '${value}' in '${raw}' (use mode=read or mode=write)`);
|
|
99
|
+
}
|
|
100
|
+
mode = value;
|
|
101
|
+
}
|
|
102
|
+
const path = url.pathname.replace(/\/+$/, "");
|
|
103
|
+
return { base: `${url.protocol}//${url.host}${path}`, mode };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function parseEnvString(spec: string): Endpoint[] {
|
|
107
|
+
const out: Endpoint[] = [];
|
|
108
|
+
const seen = new Set<string>();
|
|
109
|
+
for (const part of spec.split(",")) {
|
|
110
|
+
const entry = part.trim();
|
|
111
|
+
if (!entry) continue;
|
|
112
|
+
const eq = entry.indexOf("=");
|
|
113
|
+
if (eq <= 0) {
|
|
114
|
+
throw new EndpointConfigError(`CDP_ENDPOINTS: entry '${entry}' is not name=url (e.g. teams=http://127.0.0.1:9333)`);
|
|
115
|
+
}
|
|
116
|
+
const name = entry.slice(0, eq).trim();
|
|
117
|
+
checkName(name, "CDP_ENDPOINTS");
|
|
118
|
+
if (seen.has(name)) throw new EndpointConfigError(`CDP_ENDPOINTS: duplicate endpoint name '${name}'`);
|
|
119
|
+
seen.add(name);
|
|
120
|
+
const { base, mode } = parseBase(entry.slice(eq + 1).trim(), `CDP_ENDPOINTS endpoint '${name}'`);
|
|
121
|
+
out.push({ name, base, readOnly: mode === "read" });
|
|
122
|
+
}
|
|
123
|
+
return out;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function parseFile(path: string): { endpoints: Endpoint[]; defaultName?: string } {
|
|
127
|
+
let text: string;
|
|
128
|
+
try {
|
|
129
|
+
text = readFileSync(path, "utf8");
|
|
130
|
+
} catch (err) {
|
|
131
|
+
const code = (err as NodeJS.ErrnoException).code ?? String(err);
|
|
132
|
+
throw new EndpointConfigError(`CDP_ENDPOINTS_FILE: cannot read '${path}' (${code})`);
|
|
133
|
+
}
|
|
134
|
+
let json: unknown;
|
|
135
|
+
try {
|
|
136
|
+
json = JSON.parse(text);
|
|
137
|
+
} catch (err) {
|
|
138
|
+
throw new EndpointConfigError(`CDP_ENDPOINTS_FILE: '${path}' is not valid JSON (${err instanceof Error ? err.message : String(err)})`);
|
|
139
|
+
}
|
|
140
|
+
const where = `CDP_ENDPOINTS_FILE '${path}'`;
|
|
141
|
+
if (!json || typeof json !== "object" || Array.isArray(json)) {
|
|
142
|
+
throw new EndpointConfigError(`${where}: top level must be an object {"default"?, "endpoints": {...}}`);
|
|
143
|
+
}
|
|
144
|
+
const top = json as Record<string, unknown>;
|
|
145
|
+
for (const key of Object.keys(top)) {
|
|
146
|
+
if (key !== "default" && key !== "endpoints") throw new EndpointConfigError(`${where}: unknown top-level key '${key}'`);
|
|
147
|
+
}
|
|
148
|
+
if (top.default !== undefined && typeof top.default !== "string") {
|
|
149
|
+
throw new EndpointConfigError(`${where}: "default" must be an endpoint name string`);
|
|
150
|
+
}
|
|
151
|
+
const raw = top.endpoints ?? {};
|
|
152
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
|
|
153
|
+
throw new EndpointConfigError(`${where}: "endpoints" must be an object keyed by endpoint name`);
|
|
154
|
+
}
|
|
155
|
+
const endpoints: Endpoint[] = [];
|
|
156
|
+
for (const [name, value] of Object.entries(raw as Record<string, unknown>)) {
|
|
157
|
+
checkName(name, where);
|
|
158
|
+
const at = `${where} endpoint '${name}'`;
|
|
159
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
160
|
+
throw new EndpointConfigError(`${at}: must be an object like {"base":"http://127.0.0.1:9333"}`);
|
|
161
|
+
}
|
|
162
|
+
const v = value as Record<string, unknown>;
|
|
163
|
+
for (const key of Object.keys(v)) {
|
|
164
|
+
if (key !== "base" && key !== "readOnly" && key !== "mode") {
|
|
165
|
+
throw new EndpointConfigError(`${at}: unknown key '${key}' (known: base, readOnly, mode)`);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
if (typeof v.base !== "string") throw new EndpointConfigError(`${at}: "base" is required and must be a URL string`);
|
|
169
|
+
if (v.readOnly !== undefined && typeof v.readOnly !== "boolean") throw new EndpointConfigError(`${at}: "readOnly" must be a boolean`);
|
|
170
|
+
if (v.mode !== undefined && v.mode !== "read" && v.mode !== "write") {
|
|
171
|
+
throw new EndpointConfigError(`${at}: unknown mode '${String(v.mode)}' (use "read" or "write")`);
|
|
172
|
+
}
|
|
173
|
+
const parsed = parseBase(v.base, at);
|
|
174
|
+
const votes = [parsed.mode, v.mode as string | undefined, v.readOnly === undefined ? undefined : v.readOnly ? "read" : "write"].filter(
|
|
175
|
+
(x): x is string => x !== undefined,
|
|
176
|
+
);
|
|
177
|
+
if (new Set(votes).size > 1) throw new EndpointConfigError(`${at}: readOnly / mode settings contradict each other`);
|
|
178
|
+
endpoints.push({ name, base: parsed.base, readOnly: votes[0] === "read" });
|
|
179
|
+
}
|
|
180
|
+
return { endpoints, defaultName: top.default as string | undefined };
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Parse the endpoint config out of `env`. Pure apart from reading
|
|
185
|
+
* CDP_ENDPOINTS_FILE; no caching (see the memoized accessors below).
|
|
186
|
+
*/
|
|
187
|
+
export function loadEndpoints(env: NodeJS.ProcessEnv = process.env): EndpointConfig {
|
|
188
|
+
const fromEnv = env.CDP_ENDPOINTS !== undefined ? parseEnvString(env.CDP_ENDPOINTS) : [];
|
|
189
|
+
const file = env.CDP_ENDPOINTS_FILE ? parseFile(env.CDP_ENDPOINTS_FILE) : { endpoints: [] as Endpoint[], defaultName: undefined };
|
|
190
|
+
|
|
191
|
+
const merged = new Map<string, Endpoint>();
|
|
192
|
+
for (const ep of fromEnv) merged.set(ep.name, ep);
|
|
193
|
+
for (const ep of file.endpoints) {
|
|
194
|
+
const prior = merged.get(ep.name);
|
|
195
|
+
if (prior && (prior.base !== ep.base || prior.readOnly !== ep.readOnly)) {
|
|
196
|
+
throw new EndpointConfigError(
|
|
197
|
+
`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" : ""})`,
|
|
198
|
+
);
|
|
199
|
+
}
|
|
200
|
+
if (!prior) merged.set(ep.name, ep);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// CDP_BASE is the endpoint named `default`. Read with `!== undefined`, not
|
|
204
|
+
// truthiness, matching the old `process.env.CDP_BASE ?? ...` exactly.
|
|
205
|
+
const cdpBase = env.CDP_BASE;
|
|
206
|
+
if (cdpBase !== undefined) {
|
|
207
|
+
const configured = merged.get("default");
|
|
208
|
+
if (configured && !sameBase(configured.base, cdpBase)) {
|
|
209
|
+
throw new EndpointConfigError(
|
|
210
|
+
`CDP_BASE (${cdpBase}) and the configured endpoint 'default' (${configured.base}) disagree; drop one or make them match`,
|
|
211
|
+
);
|
|
212
|
+
}
|
|
213
|
+
// Verbatim string, never the normalized one, so a CDP_BASE-only setup builds byte-identical URLs.
|
|
214
|
+
merged.set("default", { name: "default", base: cdpBase, readOnly: configured?.readOnly ?? false });
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
const defaultName = file.defaultName ?? "default";
|
|
218
|
+
if (!merged.has(defaultName)) {
|
|
219
|
+
if (file.defaultName !== undefined) {
|
|
220
|
+
throw new EndpointConfigError(
|
|
221
|
+
`CDP_ENDPOINTS_FILE names default endpoint '${file.defaultName}', which is not defined (known: ${[...merged.keys()].join(", ") || "none"})`,
|
|
222
|
+
);
|
|
223
|
+
}
|
|
224
|
+
merged.set("default", { name: "default", base: DEFAULT_CDP_BASE, readOnly: false });
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// The default endpoint first, then config order: listing order and the lease
|
|
228
|
+
// namespace tie-break (see leaseNamespace) both read this order.
|
|
229
|
+
const def = merged.get(defaultName)!;
|
|
230
|
+
const byName = new Map<string, Endpoint>([[def.name, def]]);
|
|
231
|
+
for (const [name, ep] of merged) if (name !== def.name) byName.set(name, ep);
|
|
232
|
+
return { default: def, byName };
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/* ------------------------------ memoized accessors ------------------------------ */
|
|
236
|
+
|
|
237
|
+
let cache: { sig: string; config: EndpointConfig } | undefined;
|
|
238
|
+
|
|
239
|
+
function signature(env: NodeJS.ProcessEnv): string {
|
|
240
|
+
return JSON.stringify([env.CDP_BASE ?? null, env.CDP_ENDPOINTS ?? null, env.CDP_ENDPOINTS_FILE ?? null]);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** The process config, re-parsed whenever the three env vars change. Errors are never cached. */
|
|
244
|
+
export function endpointConfig(): EndpointConfig {
|
|
245
|
+
const sig = signature(process.env);
|
|
246
|
+
if (cache?.sig === sig) return cache.config;
|
|
247
|
+
const config = loadEndpoints(process.env);
|
|
248
|
+
cache = { sig, config };
|
|
249
|
+
return config;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** Test hook: forget the memoized config (e.g. after rewriting the file in place). */
|
|
253
|
+
export function resetEndpointCache(): void {
|
|
254
|
+
cache = undefined;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
export function defaultEndpoint(): Endpoint {
|
|
258
|
+
return endpointConfig().default;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/** Every configured endpoint, default first. */
|
|
262
|
+
export function allEndpoints(): Endpoint[] {
|
|
263
|
+
return [...endpointConfig().byName.values()];
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
export function getEndpoint(name: string): Endpoint {
|
|
267
|
+
const { byName } = endpointConfig();
|
|
268
|
+
const ep = byName.get(name);
|
|
269
|
+
if (!ep) {
|
|
270
|
+
throw new EndpointConfigError(
|
|
271
|
+
`unknown endpoint '${name}' (known: ${[...byName.keys()].join(", ")}). Configure it with CDP_ENDPOINTS or CDP_ENDPOINTS_FILE.`,
|
|
272
|
+
);
|
|
273
|
+
}
|
|
274
|
+
return ep;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* The lease/origin namespace of an endpoint: undefined means the legacy
|
|
279
|
+
* un-suffixed filenames (`lease-chrome-<id>.json`), shared with older
|
|
280
|
+
* processes. That is the default endpoint, and ANY endpoint whose base equals
|
|
281
|
+
* the default's: two names for one browser must share one lease space, or
|
|
282
|
+
* `endpoint:browser/` would walk straight past a lease held through the
|
|
283
|
+
* default. Two non-default names for one base share the namespace of the first
|
|
284
|
+
* declared.
|
|
285
|
+
*/
|
|
286
|
+
export function leaseNamespace(ep: Endpoint): string | undefined {
|
|
287
|
+
const { default: def, byName } = endpointConfig();
|
|
288
|
+
if (sameBase(ep.base, def.base)) return undefined;
|
|
289
|
+
for (const other of byName.values()) if (sameBase(other.base, ep.base)) return other.name;
|
|
290
|
+
return ep.name;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/* ---------------------------------- selectors ---------------------------------- */
|
|
294
|
+
|
|
295
|
+
/** True when `target` starts with the `endpoint:` prefix. `url:endpoint:x` is NOT a prefix. */
|
|
296
|
+
export function hasEndpointPrefix(target: unknown): target is string {
|
|
297
|
+
return typeof target === "string" && target.startsWith(ENDPOINT_PREFIX);
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/**
|
|
301
|
+
* Split `endpoint:<name>/<rest>` into the endpoint and the remaining selector.
|
|
302
|
+
* No prefix: the default endpoint and the selector unchanged. `endpoint:teams`
|
|
303
|
+
* or `endpoint:teams/` alone: rest undefined (the endpoint's active page).
|
|
304
|
+
*/
|
|
305
|
+
export function splitEndpointSelector(target: string | undefined): { endpoint: Endpoint; rest: string | undefined } {
|
|
306
|
+
if (!hasEndpointPrefix(target)) return { endpoint: defaultEndpoint(), rest: target };
|
|
307
|
+
const body = target.slice(ENDPOINT_PREFIX.length);
|
|
308
|
+
const slash = body.indexOf("/");
|
|
309
|
+
const name = slash < 0 ? body : body.slice(0, slash);
|
|
310
|
+
if (!name) throw new EndpointConfigError(`selector '${target}' has an empty endpoint name; use endpoint:<name>/<selector>`);
|
|
311
|
+
const rest = slash < 0 ? undefined : body.slice(slash + 1);
|
|
312
|
+
return { endpoint: getEndpoint(name), rest: rest === "" ? undefined : rest };
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/** Args keys that carry a target selector: `target` everywhere, `targetId` on claim_page. */
|
|
316
|
+
export const SELECTOR_KEYS = ["target", "targetId"] as const;
|
|
317
|
+
|
|
318
|
+
/** The refusal for any endpoint feature under the Firefox backend (mcp.ts and cli.ts). */
|
|
319
|
+
export const ENDPOINTS_FIREFOX_MESSAGE =
|
|
320
|
+
"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";
|
|
321
|
+
|
|
322
|
+
/** True when args ask for any endpoint feature at all (used to refuse them on Firefox, without loading config). */
|
|
323
|
+
export function usesEndpointArgs(args: unknown): boolean {
|
|
324
|
+
if (!args || typeof args !== "object") return false;
|
|
325
|
+
const a = args as Record<string, unknown>;
|
|
326
|
+
return SELECTOR_KEYS.some((k) => hasEndpointPrefix(a[k])) || a.endpoint !== undefined || a.allEndpoints === true;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/**
|
|
330
|
+
* Resolve the endpoint and strip the prefix: the one place dispatch rewrites
|
|
331
|
+
* args. With no prefix and no `endpoint` key the ORIGINAL object comes back
|
|
332
|
+
* untouched. A prefix that names nothing after the slash deletes the key (so
|
|
333
|
+
* the tool sees its own default, 'active'), and the `endpoint` key itself is
|
|
334
|
+
* removed so no tool's own arg checks ever see it.
|
|
335
|
+
*/
|
|
336
|
+
export function stripEndpointArgs(args: unknown): { endpoint: Endpoint; args: unknown } {
|
|
337
|
+
if (!args || typeof args !== "object" || Array.isArray(args)) return { endpoint: defaultEndpoint(), args };
|
|
338
|
+
const a = args as Record<string, unknown>;
|
|
339
|
+
const picks: Array<{ from: string; endpoint: Endpoint }> = [];
|
|
340
|
+
let out: Record<string, unknown> | undefined;
|
|
341
|
+
for (const key of SELECTOR_KEYS) {
|
|
342
|
+
const v = a[key];
|
|
343
|
+
if (!hasEndpointPrefix(v)) continue;
|
|
344
|
+
const { endpoint, rest } = splitEndpointSelector(v);
|
|
345
|
+
picks.push({ from: `${key} '${v}'`, endpoint });
|
|
346
|
+
out ??= { ...a };
|
|
347
|
+
if (rest === undefined) delete out[key];
|
|
348
|
+
else out[key] = rest;
|
|
349
|
+
}
|
|
350
|
+
if (a.endpoint !== undefined) {
|
|
351
|
+
if (typeof a.endpoint !== "string" || a.endpoint === "") {
|
|
352
|
+
throw new EndpointConfigError("`endpoint` must be a non-empty endpoint name string");
|
|
353
|
+
}
|
|
354
|
+
picks.push({ from: `endpoint '${a.endpoint}'`, endpoint: getEndpoint(a.endpoint) });
|
|
355
|
+
out ??= { ...a };
|
|
356
|
+
delete out.endpoint;
|
|
357
|
+
}
|
|
358
|
+
// A Chrome lease token names its endpoint too (`chrome@<ns>:<targetId>:<nonce>`), so
|
|
359
|
+
// `release_page {lease}` with no prefix acts on the endpoint the lease was taken on,
|
|
360
|
+
// not the default. The token stays in args: the lease scope still reads it.
|
|
361
|
+
const token = leaseTokenNamespace(a.lease);
|
|
362
|
+
if (!picks.length) {
|
|
363
|
+
if (token?.ns === undefined) return { endpoint: defaultEndpoint(), args };
|
|
364
|
+
return { endpoint: endpointForNamespace(token.ns), args };
|
|
365
|
+
}
|
|
366
|
+
const first = picks[0]!;
|
|
367
|
+
for (const p of picks.slice(1)) {
|
|
368
|
+
if (p.endpoint.name !== first.endpoint.name) {
|
|
369
|
+
throw new EndpointConfigError(`conflicting endpoints: ${first.from} vs ${p.from}; name one endpoint per call`);
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
// Compared by lease namespace, not name: two names for one base share one lease space.
|
|
373
|
+
if (token && leaseNamespace(first.endpoint) !== token.ns) {
|
|
374
|
+
throw new EndpointConfigError(
|
|
375
|
+
`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`,
|
|
376
|
+
);
|
|
377
|
+
}
|
|
378
|
+
return { endpoint: first.endpoint, args: out ?? a };
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/**
|
|
382
|
+
* The lease namespace a Chrome lease token was minted under (leases.ts mintToken:
|
|
383
|
+
* `<backend>:<targetId>:<nonce>`, backend `chrome` or `chrome@<ns>`). `{ns: undefined}`
|
|
384
|
+
* is the default namespace (plain `chrome`). null for anything else: no token, a
|
|
385
|
+
* Firefox token, or a malformed one, which the lease layer rejects on its own terms.
|
|
386
|
+
* Parsed here rather than via leases.ts's tokenParts because this module is a leaf.
|
|
387
|
+
*/
|
|
388
|
+
function leaseTokenNamespace(lease: unknown): { ns: string | undefined } | null {
|
|
389
|
+
if (typeof lease !== "string") return null;
|
|
390
|
+
const colon = lease.indexOf(":");
|
|
391
|
+
if (colon <= 0) return null;
|
|
392
|
+
const head = lease.slice(0, colon);
|
|
393
|
+
if (head === "chrome") return { ns: undefined };
|
|
394
|
+
if (!head.startsWith("chrome@")) return null;
|
|
395
|
+
const ns = head.slice("chrome@".length);
|
|
396
|
+
return NAME_RE.test(ns) ? { ns } : null;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/** The first configured endpoint whose lease namespace is `ns` (see leaseNamespace). */
|
|
400
|
+
function endpointForNamespace(ns: string): Endpoint {
|
|
401
|
+
for (const ep of endpointConfig().byName.values()) if (leaseNamespace(ep) === ns) return ep;
|
|
402
|
+
throw new EndpointConfigError(
|
|
403
|
+
`the lease token belongs to endpoint '${ns}', which is not configured (known: ${[...endpointConfig().byName.keys()].join(", ")})`,
|
|
404
|
+
);
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/** The endpoint a call's args select (selector prefix, `endpoint` key, or a `chrome@<ns>` lease token), else the default. */
|
|
408
|
+
export function endpointForArgs(args: unknown): Endpoint {
|
|
409
|
+
return stripEndpointArgs(args).endpoint;
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/* ------------------------------------ scope ------------------------------------ */
|
|
413
|
+
|
|
414
|
+
const endpointScope = new AsyncLocalStorage<Endpoint>();
|
|
415
|
+
|
|
416
|
+
/** The endpoint of the enclosing withEndpointScope, else the default endpoint. */
|
|
417
|
+
export function currentEndpoint(): Endpoint {
|
|
418
|
+
return endpointScope.getStore() ?? defaultEndpoint();
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/** True when the current scope is a non-default endpoint (used to tag output rows). */
|
|
422
|
+
export function isDefaultEndpoint(ep: Endpoint): boolean {
|
|
423
|
+
return ep.name === defaultEndpoint().name;
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
export function withEndpointScope<T>(ep: Endpoint, fn: () => Promise<T>): Promise<T> {
|
|
427
|
+
return endpointScope.run(ep, fn);
|
|
428
|
+
}
|
package/src/install/browser.ts
CHANGED
|
@@ -10,7 +10,7 @@ import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
|
10
10
|
import { homedir } from "node:os";
|
|
11
11
|
import { delimiter, dirname, join } from "node:path";
|
|
12
12
|
|
|
13
|
-
export type BrowserChoice = "arc" | "chrome" | "firefox";
|
|
13
|
+
export type BrowserChoice = "arc" | "chrome" | "firefox" | "vivaldi";
|
|
14
14
|
|
|
15
15
|
export interface BrowserInfo {
|
|
16
16
|
choice: BrowserChoice;
|
|
@@ -40,7 +40,7 @@ export interface RcAppendResult {
|
|
|
40
40
|
|
|
41
41
|
/**
|
|
42
42
|
* Per-choice candidate lists, built fresh on every call so env var overrides (CHROME_BIN /
|
|
43
|
-
* ARC_BIN / FIREFOX_BIN) are read live rather than captured once at module load — important for
|
|
43
|
+
* ARC_BIN / VIVALDI_BIN / FIREFOX_BIN) are read live rather than captured once at module load — important for
|
|
44
44
|
* tests that set/restore these env vars around a single call.
|
|
45
45
|
*
|
|
46
46
|
* macOS-first, Linux fallback. Order mirrors the spec: env override, then the macOS .app bundle
|
|
@@ -56,6 +56,12 @@ const CANDIDATE_BUILDERS: Record<BrowserChoice, () => Array<string | undefined>>
|
|
|
56
56
|
"chromium",
|
|
57
57
|
],
|
|
58
58
|
arc: () => [process.env.ARC_BIN, "/Applications/Arc.app/Contents/MacOS/Arc", "arc"],
|
|
59
|
+
vivaldi: () => [
|
|
60
|
+
process.env.VIVALDI_BIN,
|
|
61
|
+
"/Applications/Vivaldi.app/Contents/MacOS/Vivaldi",
|
|
62
|
+
"vivaldi",
|
|
63
|
+
"/usr/bin/vivaldi",
|
|
64
|
+
],
|
|
59
65
|
firefox: () => [
|
|
60
66
|
process.env.FIREFOX_BIN,
|
|
61
67
|
"/Applications/Firefox.app/Contents/MacOS/firefox",
|
|
@@ -113,7 +119,7 @@ export function defaultAliasName(choice: BrowserChoice): string {
|
|
|
113
119
|
}
|
|
114
120
|
|
|
115
121
|
/**
|
|
116
|
-
* The launch flags only (no binary). Chrome and
|
|
122
|
+
* The launch flags only (no binary). Chrome, Arc and Vivaldi are all Chromium-based and accept
|
|
117
123
|
* Chrome's flags, so they share a shape: --remote-debugging-port plus a DEDICATED
|
|
118
124
|
* --user-data-dir. The dedicated profile is required, not cosmetic — Chrome silently ignores
|
|
119
125
|
* --remote-debugging-port when it hands off to an already-running instance on the default
|
package/src/install/wizard.ts
CHANGED
|
@@ -63,7 +63,7 @@ export interface InstallerIO {
|
|
|
63
63
|
|
|
64
64
|
const DEFAULT_NAME = "cdp-toolkit";
|
|
65
65
|
const HARNESSES: readonly HarnessChoice[] = ["claude", "codex", "opencode"];
|
|
66
|
-
const BROWSERS: readonly BrowserChoice[] = ["arc", "chrome", "firefox"];
|
|
66
|
+
const BROWSERS: readonly BrowserChoice[] = ["arc", "chrome", "firefox", "vivaldi"];
|
|
67
67
|
|
|
68
68
|
/* --------------------------------- pure: arg parsing --------------------------------- */
|
|
69
69
|
|
|
@@ -79,9 +79,9 @@ function parseHarness(v: string | undefined): HarnessChoice {
|
|
|
79
79
|
}
|
|
80
80
|
|
|
81
81
|
function parseBrowserChoice(v: string | undefined): BrowserChoice {
|
|
82
|
-
if (v === undefined) throw new Error("--browser requires a value: arc, chrome, or
|
|
82
|
+
if (v === undefined) throw new Error("--browser requires a value: arc, chrome, firefox, or vivaldi");
|
|
83
83
|
if ((BROWSERS as readonly string[]).includes(v)) return v as BrowserChoice;
|
|
84
|
-
throw new Error(`--browser must be one of arc|chrome|firefox (got '${v}')`);
|
|
84
|
+
throw new Error(`--browser must be one of arc|chrome|firefox|vivaldi (got '${v}')`);
|
|
85
85
|
}
|
|
86
86
|
|
|
87
87
|
function parsePort(v: string | undefined): number {
|
|
@@ -165,8 +165,8 @@ export function parseInstallArgs(argv: string[]): InstallArgs {
|
|
|
165
165
|
* PURE. Build the MCP stdio server config for a given browser + debug port.
|
|
166
166
|
*
|
|
167
167
|
* The server always runs `npx -y cdp-toolkit`. Only the env differs by browser, and even then
|
|
168
|
-
* chrome and
|
|
169
|
-
* whatever is listening on CDP_BASE — the arc-vs-chrome distinction lives entirely in the shell
|
|
168
|
+
* chrome, arc and vivaldi are IDENTICAL: both are driven over CDP, and the driver just talks CDP to
|
|
169
|
+
* whatever is listening on CDP_BASE — the arc-vs-chrome-vs-vivaldi distinction lives entirely in the shell
|
|
170
170
|
* ALIAS (which .app it launches), not in the server env. Firefox is the odd one out: it is driven
|
|
171
171
|
* over WebDriver BiDi, selected by CDP_BROWSER=firefox with the port in CDP_FIREFOX_ENDPOINT.
|
|
172
172
|
*/
|
|
@@ -185,14 +185,14 @@ export function installHelpText(): string {
|
|
|
185
185
|
browser-launch alias (with the remote-debugging port open) to your shell rc.
|
|
186
186
|
|
|
187
187
|
Usage:
|
|
188
|
-
cdp install [--harness <claude|codex|opencode>] [--browser <arc|chrome|firefox>]
|
|
188
|
+
cdp install [--harness <claude|codex|opencode>] [--browser <arc|chrome|firefox|vivaldi>]
|
|
189
189
|
[--port <n>] [--name <server-name>] [--alias-name <name>]
|
|
190
190
|
[--no-alias] [--yes|-y] [--help|-h]
|
|
191
191
|
|
|
192
192
|
Options:
|
|
193
193
|
--harness <h> Coding harness to register the MCP server with: claude, codex, opencode.
|
|
194
|
-
--browser <b> Browser the alias launches: arc, chrome, firefox.
|
|
195
|
-
--port <n> Remote-debugging port (1-65535). Default: 9222 (chrome/arc), 9223 (firefox).
|
|
194
|
+
--browser <b> Browser the alias launches: arc, chrome, firefox, vivaldi.
|
|
195
|
+
--port <n> Remote-debugging port (1-65535). Default: 9222 (chrome/arc/vivaldi), 9223 (firefox).
|
|
196
196
|
--name <name> MCP server name to register. Default: ${DEFAULT_NAME}.
|
|
197
197
|
--alias-name <n> Shell alias name. Default: cdp-<browser> (e.g. cdp-firefox).
|
|
198
198
|
--no-alias Register the MCP server only; skip writing the shell alias.
|
package/src/leases-tools.ts
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
import { beaconSupported, contentionWarning, installBeacon, readHumanActiveMs } from "./activity.ts";
|
|
7
7
|
import type { BrowserDriver } from "./driver.ts";
|
|
8
8
|
import { newTrackedPage, readOrigin } from "./origins.ts";
|
|
9
|
-
import { reapStaleAgentTabs, type ReapedTab } from "./reap.ts";
|
|
9
|
+
import { reapAllowed, reapStaleAgentTabs, type ReapedTab } from "./reap.ts";
|
|
10
10
|
import { pickPage, resolvePage } from "./shared-tools.ts";
|
|
11
11
|
import type { TargetSelector } from "./types.ts";
|
|
12
12
|
import {
|
|
@@ -18,6 +18,7 @@ import {
|
|
|
18
18
|
releaseLeaseFor,
|
|
19
19
|
requireLease,
|
|
20
20
|
tokenParts,
|
|
21
|
+
chromeLeaseBackend,
|
|
21
22
|
type LeaseBackend,
|
|
22
23
|
type LeaseSummary,
|
|
23
24
|
type LeaseToken,
|
|
@@ -28,7 +29,8 @@ class LeaseToolError extends Error {}
|
|
|
28
29
|
/** The driver's uid scheme is the one stable per-backend discriminator on the
|
|
29
30
|
* BrowserDriver surface ("cdp" for Chrome, "bidi" for Firefox). */
|
|
30
31
|
function backendOf(driver: BrowserDriver): LeaseBackend {
|
|
31
|
-
|
|
32
|
+
// Chrome's key carries the dispatch scope's named endpoint (chrome@<name>); see LeaseBackend.
|
|
33
|
+
return driver.scheme === "bidi" ? "firefox" : chromeLeaseBackend();
|
|
32
34
|
}
|
|
33
35
|
|
|
34
36
|
export interface ClaimPageResult {
|
|
@@ -310,7 +312,8 @@ export async function listLeasesTool(
|
|
|
310
312
|
// Same reap as list_pages, and for the same reason: this is the other tool an
|
|
311
313
|
// operator runs when tabs look wrong, so it must not report a lease it is
|
|
312
314
|
// about to delete. Strict mode only.
|
|
313
|
-
|
|
315
|
+
// Never on a read-only endpoint (#15): reapAllowed.
|
|
316
|
+
const reaped = requireLease() && reapAllowed(driver) ? await reapStaleAgentTabs(driver, backend) : [];
|
|
314
317
|
const reapedIds = new Set(reaped.map((r) => r.targetId));
|
|
315
318
|
const livePages = await driver.listPages();
|
|
316
319
|
const liveIds = livePages.map((p) => p.id);
|
package/src/leases.ts
CHANGED
|
@@ -29,13 +29,37 @@ import { AsyncLocalStorage } from "node:async_hooks";
|
|
|
29
29
|
import { randomBytes } from "node:crypto";
|
|
30
30
|
import { mkdir, readFile, readdir, unlink, writeFile } from "node:fs/promises";
|
|
31
31
|
import { join } from "node:path";
|
|
32
|
+
import { currentEndpoint, leaseNamespace, type Endpoint } from "./endpoints.ts";
|
|
32
33
|
|
|
33
34
|
/** Opaque ownership token. Hold it, pass it back, never parse or build one. */
|
|
34
35
|
export type LeaseToken = string;
|
|
35
36
|
|
|
36
37
|
/** Ownership is keyed by backend plus id: a CDP targetId and a BiDi context id
|
|
37
|
-
* are not guaranteed disjoint, so a bare id could collide across browsers.
|
|
38
|
-
|
|
38
|
+
* are not guaranteed disjoint, so a bare id could collide across browsers.
|
|
39
|
+
*
|
|
40
|
+
* A NAMED CDP ENDPOINT (src/endpoints.ts) is its own browser, so it is its own
|
|
41
|
+
* backend key: `chrome@<name>`. The default endpoint stays plain "chrome", so
|
|
42
|
+
* lease and origin filenames, and tokens, are byte-identical to every older
|
|
43
|
+
* process sharing the directory. Because the endpoint rides IN the key, every
|
|
44
|
+
* existing "same backend" comparison (liveBackend scoping, reap, list_pages
|
|
45
|
+
* annotation, token checks) scopes by endpoint with no extra code: a target
|
|
46
|
+
* list read from one port can never mark another port's lease stale. */
|
|
47
|
+
export type LeaseBackend = "chrome" | "firefox" | `chrome@${string}`;
|
|
48
|
+
|
|
49
|
+
/** The Chrome lease key for an endpoint (by default the current dispatch scope's). */
|
|
50
|
+
export function chromeLeaseBackend(ep: Endpoint = currentEndpoint()): LeaseBackend {
|
|
51
|
+
const ns = leaseNamespace(ep);
|
|
52
|
+
return ns === undefined ? "chrome" : `chrome@${ns}`;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Regex source for a backend key as it appears in filenames and tokens. Endpoint
|
|
56
|
+
* names are [A-Za-z0-9_]+, so a key never contains '-' or ':'. Shared with origins.ts. */
|
|
57
|
+
export const BACKEND_KEY_SOURCE = "chrome@[A-Za-z0-9_]+|chrome|firefox";
|
|
58
|
+
const BACKEND_KEY_RE = new RegExp(`^(?:${BACKEND_KEY_SOURCE})$`);
|
|
59
|
+
|
|
60
|
+
export function isLeaseBackend(value: string): value is LeaseBackend {
|
|
61
|
+
return BACKEND_KEY_RE.test(value);
|
|
62
|
+
}
|
|
39
63
|
|
|
40
64
|
export interface LeaseRecord {
|
|
41
65
|
backend: LeaseBackend;
|
|
@@ -139,7 +163,7 @@ export function tokenParts(token: LeaseToken): { backend: LeaseBackend; targetId
|
|
|
139
163
|
const last = token.lastIndexOf(":");
|
|
140
164
|
if (first <= 0 || last <= first) return undefined;
|
|
141
165
|
const backend = token.slice(0, first);
|
|
142
|
-
if (backend
|
|
166
|
+
if (!isLeaseBackend(backend)) return undefined;
|
|
143
167
|
const targetId = token.slice(first + 1, last);
|
|
144
168
|
const nonce = token.slice(last + 1);
|
|
145
169
|
if (!targetId.length || !/^[0-9a-f]{24}$/.test(nonce)) return undefined;
|
|
@@ -532,7 +556,7 @@ export interface LeaseSummary {
|
|
|
532
556
|
unreadable?: string;
|
|
533
557
|
}
|
|
534
558
|
|
|
535
|
-
const LEASE_FILE_RE =
|
|
559
|
+
const LEASE_FILE_RE = new RegExp(`^lease-(${BACKEND_KEY_SOURCE})-(.+)\\.json$`);
|
|
536
560
|
|
|
537
561
|
/**
|
|
538
562
|
* Enumerate every lease on disk. Diagnosis only, so it needs no token.
|