cdp-toolkit 1.2.0 → 1.4.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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "cdp-toolkit",
3
- "version": "1.2.0",
4
- "description": "A lightweight chrome-devtools-mcp alternative: a single-target MCP server + CLI that drives one tab over a direct WebSocket with a bounded timeout on every call, so a stuck page can't wedge your agent or force a /mcp restart. Chrome over CDP and Firefox over WebDriver BiDi, with tools a backend can't run absent from tools/list rather than throwing mid-task. 36 tools including built-in network mocking. No Puppeteer, no all-target fan-out.",
3
+ "version": "1.4.0",
4
+ "description": "A lightweight chrome-devtools-mcp alternative: a single-target MCP server + CLI that drives one tab over a direct WebSocket with a bounded timeout on every call, so a stuck page can't wedge your agent or force a /mcp restart. Chrome over CDP and Firefox over WebDriver BiDi, with tools a backend can't run absent from tools/list rather than throwing mid-task. 39 tools including built-in network mocking and a cookie group. No Puppeteer, no all-target fan-out.",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "author": {
@@ -76,7 +76,8 @@
76
76
  "smoke": "bun run ./test/smoke.ts",
77
77
  "mock:smoke": "bun run ./test/mock-smoke.ts",
78
78
  "mcp:smoke": "bun run ./test/mcp-smoke.ts",
79
- "firefox:smoke": "bun run ./test/firefox-smoke.ts"
79
+ "firefox:smoke": "bun run ./test/firefox-smoke.ts",
80
+ "lease:smoke": "bun run ./test/lease-smoke.ts"
80
81
  },
81
82
  "devDependencies": {
82
83
  "@types/node": "22.10.10",
@@ -25,7 +25,8 @@
25
25
  import type { TargetSelector } from "../types.ts";
26
26
  import {
27
27
  UID_STAMP_ATTR, isDriverError,
28
- type BrowserDriver, type Capability, type HandledDialogInfo, type DriverError, type DriverErrorCode, type DriverEvent,
28
+ type BrowserCookie, type BrowserDriver, type Capability, type DeleteCookiesFilter, type HandledDialogInfo, type DriverError, type DriverErrorCode, type DriverEvent,
29
+ type SetCookieParams,
29
30
  type DriverUid, type ElementLocator, type EmulationOptions, type InterceptRule, type KeyPress, type LifetimeModel,
30
31
  type MouseButtonOptions, type NavigateOptions, type NavigateResult, type PageDriver, type PageInfo,
31
32
  type ScreenshotOptions, type SnapshotNode, type UidStability,
@@ -38,8 +39,60 @@ import type {
38
39
  BrowsingContextId, BrowsingContextInfo, BrowsingContextLocator, BrowsingContextReadinessState,
39
40
  BrowsingContextCaptureScreenshotParameters, ScriptSharedReference, ScriptRemoteValue, ScriptLocalValue,
40
41
  ScriptNodeRemoteValue, ScriptExceptionDetails, InputSourceActions, InputPointerSourceAction, InputKeySourceAction,
42
+ NetworkCookie,
41
43
  } from "./protocol.ts";
42
44
 
45
+ /* ---------------------------------- cookies ---------------------------------- */
46
+ /**
47
+ * BiDi's cookie shape to the neutral one. Three differences to absorb:
48
+ * - the value is a network.BytesValue, either a plain string or base64, so a
49
+ * base64 one is decoded rather than handed back as opaque base64;
50
+ * - `expiry` is optional and simply absent for a session cookie, which becomes
51
+ * the neutral -1 that CDP reports directly;
52
+ * - `session` has no BiDi field at all, so it is derived from that same
53
+ * absence, which is exactly what a session cookie means.
54
+ * `sameSite` already uses the lowercase vocabulary the neutral shape adopted.
55
+ */
56
+ export function normalizeBidiCookie(c: NetworkCookie): BrowserCookie {
57
+ const value = c.value.type === "base64" ? Buffer.from(c.value.value, "base64").toString("utf8") : c.value.value;
58
+ const hasExpiry = typeof c.expiry === "number";
59
+ return {
60
+ name: c.name, value, domain: c.domain, path: c.path,
61
+ expires: hasExpiry ? (c.expiry as number) : -1,
62
+ size: typeof c.size === "number" ? c.size : Buffer.byteLength(`${c.name}${value}`, "utf8"),
63
+ httpOnly: c.httpOnly === true, secure: c.secure === true,
64
+ sameSite: c.sameSite ?? "default", session: !hasExpiry,
65
+ };
66
+ }
67
+
68
+ /**
69
+ * The host of a url, for the BiDi cookie calls that require a `domain` and have
70
+ * no `url` parameter of their own.
71
+ *
72
+ * Exported so a test can pin the failure cases without a browser. Every branch
73
+ * that cannot produce a host THROWS: an absent url, an unparseable one, and a
74
+ * parseable one with an empty host (about:blank, data:, javascript:) all raise
75
+ * a message naming the tool and what it needs. The alternative, sending the
76
+ * call without a domain, is a request Firefox answers cleanly while writing or
77
+ * deleting nothing recognizable, which is the exact wrong-but-plausible ack
78
+ * this driver refuses to emit.
79
+ */
80
+ export function hostFromUrl(url: string | undefined, toolName: string): string {
81
+ if (url === undefined || url === "") {
82
+ throw driverError("unsupported", `${toolName} on Firefox needs a 'domain': BiDi's storage cookie calls have no 'url' parameter, and no url was given to derive one from.`);
83
+ }
84
+ let host = "";
85
+ try {
86
+ host = new URL(url).hostname;
87
+ } catch {
88
+ throw driverError("unsupported", `${toolName} could not parse the url '${url}' to derive the 'domain' BiDi requires. Pass 'domain' explicitly.`);
89
+ }
90
+ if (host === "") {
91
+ throw driverError("unsupported", `${toolName} cannot derive a 'domain' from '${url}': that url has no host. Pass 'domain' explicitly.`);
92
+ }
93
+ return host;
94
+ }
95
+
43
96
  /* ------------------------------ error + uid codec ------------------------------ */
44
97
  function driverError(code: DriverErrorCode, message: string, data?: unknown): DriverError {
45
98
  return Object.assign(new Error(message), { code, ...(data !== undefined ? { data } : {}) }) as DriverError;
@@ -643,6 +696,88 @@ class BidiPageDriver implements PageDriver {
643
696
  return this.handleOneDialog(accept, promptText, opts?.timeoutMs ?? 15_000);
644
697
  }
645
698
 
699
+ /**
700
+ * storage.getCookies, partitioned by THIS browsing context.
701
+ *
702
+ * The context partition is the BiDi counterpart of the CDP driver's choice of
703
+ * the page-scoped Network.getCookies over the browser-wide jar: it asks for
704
+ * the cookies of the tab that was resolved, not for every cookie the profile
705
+ * holds. httpOnly cookies are included, since this reads the cookie store
706
+ * over the protocol rather than evaluating document.cookie in the page.
707
+ */
708
+ async getCookies(): Promise<BrowserCookie[]> {
709
+ try {
710
+ const { cookies } = await this.conn.send("storage.getCookies", { partition: { type: "context", context: this.contextId } });
711
+ return (cookies ?? []).map(normalizeBidiCookie);
712
+ } catch (e) {
713
+ throw mapBidiError(e);
714
+ }
715
+ }
716
+
717
+ /**
718
+ * storage.setCookie, partitioned by THIS browsing context.
719
+ *
720
+ * One real difference from CDP to absorb, and it is absorbed EXPLICITLY
721
+ * rather than papered over: BiDi has no `url` parameter and requires
722
+ * `domain`, while CDP accepts either and derives the rest from the url. So a
723
+ * caller who supplied only a url gets its host used as the domain, and a url
724
+ * with no host (about:blank, a data: URL, a malformed string) throws instead
725
+ * of being dropped, because a set that silently did nothing is the failure
726
+ * this tool must never produce.
727
+ *
728
+ * Note the derivation is narrower than CDP's: CDP also takes `path` and
729
+ * `secure` from the url, and this does not, so those stay exactly as the
730
+ * caller gave them on both backends.
731
+ */
732
+ async setCookie(params: SetCookieParams): Promise<void> {
733
+ const domain = params.domain ?? hostFromUrl(params.url, "set_cookie");
734
+ try {
735
+ await this.conn.send("storage.setCookie", {
736
+ cookie: {
737
+ name: params.name,
738
+ value: { type: "string", value: params.value },
739
+ domain,
740
+ ...(params.path !== undefined ? { path: params.path } : {}),
741
+ ...(params.expires !== undefined ? { expiry: params.expires } : {}),
742
+ ...(params.httpOnly !== undefined ? { httpOnly: params.httpOnly } : {}),
743
+ ...(params.secure !== undefined ? { secure: params.secure } : {}),
744
+ ...(params.sameSite !== undefined ? { sameSite: params.sameSite } : {}),
745
+ },
746
+ partition: { type: "context", context: this.contextId },
747
+ });
748
+ } catch (e) {
749
+ throw mapBidiError(e);
750
+ }
751
+ }
752
+
753
+ /**
754
+ * storage.deleteCookies with a filter, partitioned by THIS browsing context.
755
+ *
756
+ * Same url-to-domain derivation as setCookie and for the same reason: the
757
+ * BiDi filter has `domain` and no `url`, and a filter that quietly dropped
758
+ * the only site constraint would delete by name across the partition, which
759
+ * is a bigger deletion than the caller asked for.
760
+ *
761
+ * BiDi reports a partitionKey and no count, exactly as CDP reports nothing,
762
+ * so this returns nothing on both backends rather than one of them inventing
763
+ * a number the other cannot produce.
764
+ */
765
+ async deleteCookies(filter: DeleteCookiesFilter): Promise<void> {
766
+ const domain = filter.domain ?? hostFromUrl(filter.url, "delete_cookies");
767
+ try {
768
+ await this.conn.send("storage.deleteCookies", {
769
+ filter: {
770
+ name: filter.name,
771
+ domain,
772
+ ...(filter.path !== undefined ? { path: filter.path } : {}),
773
+ },
774
+ partition: { type: "context", context: this.contextId },
775
+ });
776
+ } catch (e) {
777
+ throw mapBidiError(e);
778
+ }
779
+ }
780
+
646
781
  // Response bodies need network.addDataCollector armed BEFORE the request, per the established
647
782
  // fact this driver was handed: no way to read a body for a request that happened before
648
783
  // capture was armed. That is the mirror of the CDP driver's own honest omission of
package/src/cdp/driver.ts CHANGED
@@ -7,10 +7,12 @@
7
7
  */
8
8
  import { type CdpConnection, CdpError, listTargets, openBrowser, openPage, resolveTarget } from "../client.ts";
9
9
  import type { Target, TargetSelector } from "../types.ts";
10
+ import { LeaseConflictError } from "../leases.ts";
10
11
  import { resolveUid } from "../tools/snapshot.ts";
11
12
  import { buildFulfillParams, effectiveAction, selectRule } from "../tools/network_mock.ts";
12
13
  import {
13
- LEGACY_NUMERIC_UID, type BrowserDriver, type Capability, type HandledDialogInfo, type DriverError, type DriverErrorCode, type DriverEvent,
14
+ LEGACY_NUMERIC_UID, type BrowserCookie, type BrowserDriver, type Capability, type DeleteCookiesFilter, type HandledDialogInfo, type DriverError, type DriverErrorCode, type DriverEvent,
15
+ type SetCookieParams,
14
16
  type DriverUid, type ElementLocator, type EmulationOptions, type InterceptRule, type KeyPress, type LifetimeModel, type MouseButtonOptions,
15
17
  type NavigateOptions, type NavigateResult, type PageDriver, type PageInfo, type ScreenshotOptions, type SnapshotNode, type UidStability,
16
18
  } from "../driver.ts";
@@ -29,6 +31,49 @@ function decodeUid(uid: DriverUid): number {
29
31
  if (!Number.isSafeInteger(n) || n <= 0) throw driverError("foreign-uid", `malformed cdp uid payload: ${uid}`);
30
32
  return n;
31
33
  }
34
+ /* ---------------------------------- cookies ---------------------------------- */
35
+ /** The subset of CDP's `Network.Cookie` this driver reads. */
36
+ export interface CdpCookie {
37
+ name: string; value: string; domain: string; path: string; expires: number; size: number;
38
+ httpOnly: boolean; secure: boolean; session: boolean; sameSite?: string;
39
+ }
40
+
41
+ /**
42
+ * CDP's cookie shape to the neutral one. Two mappings carry the difference:
43
+ * `sameSite` is capitalized by CDP and absent when the cookie never set the
44
+ * attribute, so it lowercases and falls back to "default" (BiDi's word for the
45
+ * same state); `expires` is already CDP's Unix seconds with -1 for a session
46
+ * cookie, so it passes through, with `session` kept as the browser's own flag
47
+ * rather than re-derived from the timestamp.
48
+ */
49
+ export function normalizeCdpCookie(c: CdpCookie): BrowserCookie {
50
+ const same = (c.sameSite ?? "").toLowerCase();
51
+ const sameSite: BrowserCookie["sameSite"] =
52
+ same === "strict" || same === "lax" || same === "none" ? same : "default";
53
+ return {
54
+ name: c.name, value: c.value, domain: c.domain, path: c.path,
55
+ expires: typeof c.expires === "number" ? c.expires : -1,
56
+ size: typeof c.size === "number" ? c.size : Buffer.byteLength(`${c.name}${c.value}`, "utf8"),
57
+ httpOnly: c.httpOnly === true, secure: c.secure === true, sameSite, session: c.session === true,
58
+ };
59
+ }
60
+
61
+ /**
62
+ * The neutral lowercase `sameSite` back to CDP's own vocabulary.
63
+ *
64
+ * The inverse of normalizeCdpCookie's mapping, and it has to be the inverse:
65
+ * CDP capitalizes the three real values and has NO word for "default", which
66
+ * is BiDi's name for a cookie that never set the attribute. So "default"
67
+ * returns undefined and the caller omits the field, which is exactly the state
68
+ * it describes.
69
+ */
70
+ export function cdpSameSite(sameSite?: "strict" | "lax" | "none" | "default"): "Strict" | "Lax" | "None" | undefined {
71
+ if (sameSite === "strict") return "Strict";
72
+ if (sameSite === "lax") return "Lax";
73
+ if (sameSite === "none") return "None";
74
+ return undefined;
75
+ }
76
+
32
77
  /* ---------------------- copied helpers, see attributions below ---------------------- */
33
78
  // Copied verbatim from src/tools/input.ts `centerOf`: scroll into view, read viewport-space center.
34
79
  async function centerOf(conn: CdpConnection, objectId: string): Promise<{ x: number; y: number }> {
@@ -535,6 +580,79 @@ class CdpPageDriver implements PageDriver {
535
580
  });
536
581
  });
537
582
  }
583
+ /**
584
+ * `Network.getCookies` over `Storage.getCookies`, deliberately.
585
+ *
586
+ * The two differ in SCOPE, not in detail: `Storage.getCookies` returns the
587
+ * whole browser jar (every cookie for every site the profile has), while
588
+ * `Network.getCookies`, called with no `urls`, returns the cookies of the
589
+ * page this connection is attached to and its subframes. This driver is
590
+ * always attached to one resolved target, so the page-scoped call is the one
591
+ * that answers the question the caller asked. It also keeps unrelated sites'
592
+ * session credentials out of a result that only named one tab.
593
+ *
594
+ * The Network domain is enabled with the same lazy ensureDomain the rest of
595
+ * the class uses. httpOnly cookies come back either way: this is a protocol
596
+ * read of the cookie store, not a `document.cookie` evaluation, which is the
597
+ * entire reason a tool is better here than a script.
598
+ */
599
+ async getCookies(): Promise<BrowserCookie[]> {
600
+ await this.ensureDomain("Network");
601
+ const { cookies } = await this.conn.send<{ cookies: CdpCookie[] }>("Network.getCookies");
602
+ return (cookies ?? []).map(normalizeCdpCookie);
603
+ }
604
+ /**
605
+ * `Network.setCookie`, which answers `{success: boolean}` rather than an
606
+ * error when it declines a cookie.
607
+ *
608
+ * That return is the whole reason this method is more than one line. Chrome
609
+ * refuses a cookie for plenty of ordinary reasons (a domain the url does not
610
+ * belong to, `secure` on an insecure origin, an oversized value) and reports
611
+ * the refusal as `success:false` with a perfectly successful protocol reply.
612
+ * Resolving on that would hand the caller a "cookie set" that is not set, so
613
+ * a false is turned into a thrown error naming the cookie.
614
+ *
615
+ * `path` is passed through as given, not defaulted: with a `url` CDP derives
616
+ * the path from it, and inventing "/" here would silently widen the scope of
617
+ * a cookie the caller asked to scope narrowly.
618
+ */
619
+ async setCookie(params: SetCookieParams): Promise<void> {
620
+ await this.ensureDomain("Network");
621
+ const sameSite = cdpSameSite(params.sameSite);
622
+ const { success } = await this.conn.send<{ success: boolean }>("Network.setCookie", {
623
+ name: params.name,
624
+ value: params.value,
625
+ ...(params.url !== undefined ? { url: params.url } : {}),
626
+ ...(params.domain !== undefined ? { domain: params.domain } : {}),
627
+ ...(params.path !== undefined ? { path: params.path } : {}),
628
+ ...(params.expires !== undefined ? { expires: params.expires } : {}),
629
+ ...(params.httpOnly !== undefined ? { httpOnly: params.httpOnly } : {}),
630
+ ...(params.secure !== undefined ? { secure: params.secure } : {}),
631
+ ...(sameSite !== undefined ? { sameSite } : {}),
632
+ });
633
+ if (success !== true) {
634
+ // "page-error" is this file's code for a browser-side refusal of an
635
+ // operation that reached the browser intact, which is precisely this.
636
+ throw driverError(
637
+ "page-error",
638
+ `Network.setCookie declined the cookie '${params.name}'. Chrome rejects a cookie whose domain does not match the url, a secure cookie on an insecure origin, and an oversized name or value.`,
639
+ );
640
+ }
641
+ }
642
+ /**
643
+ * `Network.deleteCookies`. Unlike setCookie it reports nothing at all, not
644
+ * even a count, so this resolves on the protocol acknowledgement and the tool
645
+ * above it returns a boolean ack instead of a fabricated number.
646
+ */
647
+ async deleteCookies(filter: DeleteCookiesFilter): Promise<void> {
648
+ await this.ensureDomain("Network");
649
+ await this.conn.send("Network.deleteCookies", {
650
+ name: filter.name,
651
+ ...(filter.url !== undefined ? { url: filter.url } : {}),
652
+ ...(filter.domain !== undefined ? { domain: filter.domain } : {}),
653
+ ...(filter.path !== undefined ? { path: filter.path } : {}),
654
+ });
655
+ }
538
656
  async startBodyCapture(): Promise<() => Promise<void>> {
539
657
  await this.ensureDomain("Network");
540
658
  return async () => {
@@ -587,7 +705,33 @@ async function withBrowserConn<T>(fn: (conn: CdpConnection) => Promise<T>): Prom
587
705
  conn.close();
588
706
  }
589
707
  }
708
+ /**
709
+ * Relabel a target-resolution failure as `no-such-target`, but ONLY when the
710
+ * failure carries no type of its own.
711
+ *
712
+ * This used to relabel everything, and that was wrong in a way no unit test
713
+ * caught, because the message text survived and the MCP surface reads message
714
+ * text. resolveTarget is where the Chrome lease gate lives, so a
715
+ * LeaseConflictError raised by assertLeaseOk came through here and lost its
716
+ * class, its targetId and its holder, and came out coded `no-such-target`,
717
+ * which tells a caller the selector matched nothing and it should stop. A lease
718
+ * conflict is the one case where retrying, or going to fetch the token, is the
719
+ * right move. readLease's deliberate rethrow on an UNREADABLE lease file was
720
+ * mislabeled the same way, which is precisely the confusion that throw exists
721
+ * to prevent. BiDi never had a blanket catch, so the two backends disagreed.
722
+ *
723
+ * The pass-through is by TYPE, not by an enumerated list of errors, so a typed
724
+ * error added anywhere below this frame is protected without anyone having to
725
+ * remember to come back here:
726
+ * - LeaseConflictError, named because it is the one the caller acts on;
727
+ * - anything carrying a STRING `code`, which covers every DriverError and
728
+ * every fs errno (an EACCES out of readLease reaches this frame).
729
+ * CdpError's `code` is a NUMBER (a CDP protocol error code), so a genuine
730
+ * "that target does not exist" from pickTarget still relabels, as it must.
731
+ */
590
732
  function noSuchTarget(e: unknown): never {
733
+ if (e instanceof LeaseConflictError) throw e;
734
+ if (typeof (e as { code?: unknown } | null | undefined)?.code === "string") throw e;
591
735
  throw driverError("no-such-target", e instanceof CdpError ? e.message : String(e));
592
736
  }
593
737
  class CdpBrowserDriver implements BrowserDriver {
package/src/driver.ts CHANGED
@@ -281,6 +281,80 @@ export interface HandledDialogInfo extends DialogInfo {
281
281
  handled: true;
282
282
  }
283
283
 
284
+ /**
285
+ * One cookie, neutral over CDP's `Network.Cookie` and BiDi's `network.Cookie`.
286
+ *
287
+ * Every flag a caller needs to reason about a session credential is present:
288
+ * an httpOnly cookie is exactly the one `document.cookie` cannot read, so a
289
+ * shape that dropped `httpOnly` would make the reason this exists invisible.
290
+ *
291
+ * Two normalizations, applied by both drivers so the shape does not change
292
+ * with the backend:
293
+ * - `expires` is a Unix timestamp in SECONDS, or -1 for a session cookie.
294
+ * CDP reports exactly that; BiDi reports an optional `expiry` and omits it
295
+ * for a session cookie, which the BiDi driver maps to -1.
296
+ * - `sameSite` is lowercased to BiDi's vocabulary ("strict" | "lax" | "none"
297
+ * | "default"). CDP capitalizes it and omits it entirely when unset, which
298
+ * the CDP driver maps to "default".
299
+ */
300
+ export interface BrowserCookie {
301
+ name: string;
302
+ value: string;
303
+ domain: string;
304
+ path: string;
305
+ /** Unix seconds, or -1 for a session cookie. */
306
+ expires: number;
307
+ /** Byte length of name plus value, as the browser reports it. */
308
+ size: number;
309
+ httpOnly: boolean;
310
+ secure: boolean;
311
+ sameSite: "strict" | "lax" | "none" | "default";
312
+ /** True when the cookie expires with the browsing session (no expiry set). */
313
+ session: boolean;
314
+ }
315
+
316
+ /**
317
+ * One cookie to WRITE, neutral over CDP's `Network.setCookie` and BiDi's
318
+ * `storage.setCookie`.
319
+ *
320
+ * `url` and `domain` are both optional here but not both omittable: the cookie
321
+ * has to be attributed to a site somehow, and every backend refuses without
322
+ * one. The tool layer enforces that before either driver is reached, so the
323
+ * refusal is one message rather than two different protocol errors.
324
+ *
325
+ * `expires` follows the read shape: Unix seconds. Omit it for a session cookie,
326
+ * which is what both backends do when no expiry is supplied.
327
+ */
328
+ export interface SetCookieParams {
329
+ name: string;
330
+ value: string;
331
+ /** The URL the cookie is being set for. CDP derives domain, path and secure
332
+ * from it; BiDi has no url parameter, so its driver derives the domain. */
333
+ url?: string;
334
+ domain?: string;
335
+ path?: string;
336
+ /** Unix seconds. Omitted means a session cookie. */
337
+ expires?: number;
338
+ httpOnly?: boolean;
339
+ secure?: boolean;
340
+ sameSite?: "strict" | "lax" | "none" | "default";
341
+ }
342
+
343
+ /**
344
+ * Which cookies to DELETE, neutral over CDP's `Network.deleteCookies` and
345
+ * BiDi's `storage.deleteCookies` filter.
346
+ *
347
+ * `name` is required and there is no wildcard: this deletes a named cookie, not
348
+ * a swathe of them. As with SetCookieParams, one of `url` or `domain` must be
349
+ * present, and the tool layer enforces it.
350
+ */
351
+ export interface DeleteCookiesFilter {
352
+ name: string;
353
+ url?: string;
354
+ domain?: string;
355
+ path?: string;
356
+ }
357
+
284
358
  export interface InterceptRule {
285
359
  /** Glob: `*` any run, `?` one char. Both drivers normalize to this. */
286
360
  urlPattern: string;
@@ -403,6 +477,38 @@ export interface PageDriver {
403
477
  opts?: { timeoutMs?: number; autoMs?: number },
404
478
  ): Promise<HandledDialogInfo | { handled: HandledDialogInfo[]; count: number }>;
405
479
 
480
+ /* cookies */
481
+ /**
482
+ * Every cookie visible to THIS page, httpOnly ones included.
483
+ *
484
+ * Deliberately page-scoped, not browser-scoped. Both protocols offer a
485
+ * browser-wide jar (CDP's `Storage.getCookies` with no browserContextId,
486
+ * BiDi's storageKey partition), and both would hand back every credential
487
+ * for every site the browser has ever visited on a call that named one tab.
488
+ * A tool scoped to a target returns that target's cookies; a caller who
489
+ * wants another site's cookies points at a page on that site.
490
+ */
491
+ getCookies(): Promise<BrowserCookie[]>;
492
+
493
+ /**
494
+ * Write one cookie into the store this page reads from.
495
+ *
496
+ * Resolves only when the backend confirms the write. A backend that reports
497
+ * a refusal (CDP's `Network.setCookie` answers `{success:false}` for a cookie
498
+ * it will not accept) must throw rather than resolve, because a resolved
499
+ * promise here reads as "the cookie is set" and a caller will believe it.
500
+ */
501
+ setCookie(params: SetCookieParams): Promise<void>;
502
+
503
+ /**
504
+ * Remove the cookies matching the filter from the store this page reads from.
505
+ *
506
+ * Neither backend reports how many cookies it removed, so this returns
507
+ * nothing rather than an invented count. Deleting a cookie that was never
508
+ * there is not an error on either backend.
509
+ */
510
+ deleteCookies(filter: DeleteCookiesFilter): Promise<void>;
511
+
406
512
  /* network */
407
513
  /** Begin retaining response bodies. REQUIRED before getResponseBody unless
408
514
  * the driver declares "network.responseBodyPostHoc". Returns a stop fn. */
@@ -1,5 +1,5 @@
1
1
  /**
2
- * The complete Firefox tool registry: the 20 tools shared with Chrome (src/shared-tools.ts), the
2
+ * The complete Firefox tool registry: the 23 tools shared with Chrome (src/shared-tools.ts), the
3
3
  * 7 Firefox-only console/network/mock tools (src/bidi-tools.ts), and the 3 lease tools
4
4
  * (src/leases-tools.ts), which are backend-neutral by construction. This is what src/neutral.ts
5
5
  * used to be; it now composes three files instead of reimplementing everything in one.
package/src/index.ts CHANGED
@@ -56,8 +56,11 @@ function onCdp<A>(fn: (driver: ReturnType<typeof createCdpDriver>, args: A) => P
56
56
  * their canonical MCP (snake_case) name, plus one convenience superset tool
57
57
  * (`performance_trace`, a robust single-call trace : the start/stop pair cannot
58
58
  * span two stateless CLI processes), plus a 3-tool network-mocking group
59
- * (mock_request/list_mocks/clear_mocks : a persistent per-target fake backend).
60
- * 36 entries total. Listed explicitly so the mapping is auditable at a glance and
59
+ * (mock_request/list_mocks/clear_mocks : a persistent per-target fake backend),
60
+ * plus a 3-tool cookie group (list_cookies/set_cookie/delete_cookies : the
61
+ * cookie store including httpOnly cookies, which no page script can read or
62
+ * write).
63
+ * 39 entries total. Listed explicitly so the mapping is auditable at a glance and
61
64
  * the CLI can `--list` it.
62
65
  *
63
66
  * 20 of the 29 MCP-parity tools (pages/navigation/evaluate/snapshot/interaction/
@@ -76,6 +79,10 @@ export const TOOLS = {
76
79
  wait_for: onCdp(SHARED_TOOLS.wait_for),
77
80
  // evaluate (1)
78
81
  evaluate_script: onCdp(SHARED_TOOLS.evaluate_script),
82
+ // cookies (3) : toolkit addition, reads and writes httpOnly cookies that document.cookie cannot touch
83
+ list_cookies: onCdp(SHARED_TOOLS.list_cookies),
84
+ set_cookie: onCdp(SHARED_TOOLS.set_cookie),
85
+ delete_cookies: onCdp(SHARED_TOOLS.delete_cookies),
79
86
  // snapshot (1)
80
87
  take_snapshot: onCdp(SHARED_TOOLS.take_snapshot),
81
88
  // interaction (8)
@@ -4,8 +4,10 @@
4
4
  * Firefox, exactly as the other 20 unified tools do.
5
5
  */
6
6
  import type { BrowserDriver } from "./driver.ts";
7
+ import { newTrackedPage } from "./origins.ts";
7
8
  import {
8
9
  claimLease,
10
+ defaultLabel,
9
11
  leaseTtlMs,
10
12
  listLeases,
11
13
  releaseLease,
@@ -41,12 +43,16 @@ export async function claimPage(
41
43
  args: { targetId?: string; url?: string; label?: string; ttlMs?: number } = {},
42
44
  ): Promise<ClaimPageResult> {
43
45
  const backend = backendOf(driver);
44
- const label = typeof args.label === "string" && args.label.length ? args.label : `pid-${process.pid}`;
46
+ const label = typeof args.label === "string" && args.label.length ? args.label : defaultLabel();
45
47
  const pages = await driver.listPages();
46
48
  let targetId = args.targetId;
47
49
  let url = args.url ?? "about:blank";
48
50
  if (targetId === undefined || targetId === "") {
49
- const page = await driver.newPage(args.url);
51
+ // Creation ledger, not the lease: this record survives release_page and
52
+ // expiry, so the tab stays attributable to `label` after the lease is gone.
53
+ // Claiming an EXISTING tab (the else branch) records nothing, because this
54
+ // toolkit did not create it and provenance is not ownership.
55
+ const page = await newTrackedPage(driver, backend, { url: args.url, label });
50
56
  targetId = page.id;
51
57
  url = page.url;
52
58
  } else {
package/src/leases.ts CHANGED
@@ -65,6 +65,14 @@ export function leaseTtlMs(): number {
65
65
  return Number.isFinite(raw) && raw > 0 ? raw : DEFAULT_LEASE_TTL_MS;
66
66
  }
67
67
 
68
+ /** The label recorded when a caller supplies none. ONE definition, because it
69
+ * is now written by three call sites (claim_page, new_page, and the origin
70
+ * ledger) and a second rule would make the same tab describe itself two
71
+ * different ways depending on which of them wrote first. */
72
+ export function defaultLabel(): string {
73
+ return `pid-${process.pid}`;
74
+ }
75
+
68
76
  function safeId(id: string): string {
69
77
  return id.replace(/[^A-Za-z0-9._-]/g, "_");
70
78
  }