cdp-toolkit 3.3.0 → 3.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/CHANGELOG.md +14 -0
- package/CONTRACT.md +1 -1
- package/README.md +4 -3
- package/dist/bidi/mux-daemon.js +62 -7
- package/dist/cli.js +171 -46
- package/dist/index.js +142 -37
- package/dist/mcp.js +187 -59
- package/package.json +1 -1
- package/src/bidi/driver.ts +21 -6
- package/src/cdp/driver.ts +118 -17
- package/src/driver.ts +20 -5
- package/src/frontApp.ts +62 -0
- package/src/leases-tools.ts +3 -2
- package/src/manifest.ts +15 -3
- package/src/origins.ts +3 -2
- package/src/policy.ts +2 -1
- package/src/shared-tools.ts +43 -21
- package/src/toolDocs.ts +13 -10
- package/src/version.ts +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,20 @@ and this project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.ht
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [3.4.0] - 2026-11-18
|
|
11
|
+
|
|
12
|
+
### Changed
|
|
13
|
+
|
|
14
|
+
- **Nothing the toolkit does implicitly takes focus or switches the user's visible tab any more.** This is a behavior change:
|
|
15
|
+
- `new_page`, and `claim_page` when it opens a fresh tab, now open the tab in the background (CDP `Target.createTarget` `background:true`; Firefox `browsingContext.create` `background:true`). Before, Chromium browsers foregrounded every new tab. New optional `focus` boolean (default false) opens it in the foreground as before. `claim_page` ignores `focus` on takeover.
|
|
16
|
+
- On macOS a background `Target.createTarget` still brings the browser app in front of the user's current app (measured on Vivaldi: the active tab stays put, the window comes forward). `new_page` / `claim_page` (opening a background tab) and `close_page` (closing a tab, which raises the app too) now note the frontmost app first and put it back if it lost the front (`lsappinfo` to read, System Events to restore). `CDP_RESTORE_FRONT_APP=0` turns this off; it never runs off macOS or with `focus:true`.
|
|
17
|
+
- `select_page` now only writes the selected-state file by default and no longer sends `Target.activateTarget` / `browsingContext.activate`. New optional `focus` boolean (default false) raises the tab as before. The result gains `focused`.
|
|
18
|
+
|
|
19
|
+
### Fixed
|
|
20
|
+
|
|
21
|
+
- **Text input on a background tab (Chrome).** A background tab that never had a trusted click receives no trusted keyboard input at all (measured on Vivaldi: `Input.insertText` and `Input.dispatchKeyEvent` changed nothing and fired no keydown, with or without focus emulation), so `fill` reported success while the field stayed empty. `fill`, `fill_form` and `type_text` still try the trusted commit first, then verify it (text changed, or a `beforeinput`/`input` event fired) and fall back in-page: `document.execCommand('insertText')`, else the native value setter plus `input`/`change` events. The result carries `inputPath` (`inputPaths` for `fill_form`) only when the fallback ran or `type_text` skipped the element (disabled, read-only, non-text); a fallback that changes nothing is an error. `press_key` fakes nothing: on a definite miss the result says `delivered:false` with a note. A trusted `click` on the page gives the tab focus, after which trusted keys land (measured). Firefox is unchanged and not measured live.
|
|
22
|
+
- **`fill` / `fill_form` on a disabled or read-only field.** The clear step ran before the edit check, so the field's value was wiped and the result still said `filled:true` (`inputPath:"skipped"`). Both drivers now refuse such a field before touching it, with a `page-error` ("cannot fill a readonly field: it was left unchanged"); `fill_form` stops at that field.
|
|
23
|
+
|
|
10
24
|
## [3.3.0] - 2026-11-16
|
|
11
25
|
|
|
12
26
|
### Added
|
package/CONTRACT.md
CHANGED
|
@@ -166,7 +166,7 @@ A `Uid` **is** a CDP `backendDOMNodeId` (a number). This makes refs stateless:
|
|
|
166
166
|
|
|
167
167
|
| Module file | Tools (MCP name → fn) | Notes |
|
|
168
168
|
|---|---|---|
|
|
169
|
-
| `src/tools/pages.ts` | `list_pages`→`listPages`, `new_page`→`newPage`, `close_page`→`closePage`, `select_page`→`selectPage` | **Browser endpoint** (`openBrowser`, `Target.*`). `new_page`=`Target.createTarget
|
|
169
|
+
| `src/tools/pages.ts` | `list_pages`→`listPages`, `new_page`→`newPage`, `close_page`→`closePage`, `select_page`→`selectPage` | **Browser endpoint** (`openBrowser`, `Target.*`). `new_page`=`Target.createTarget` with `background:true` (foreground only on `focus:true`). `close_page`=`Target.closeTarget`. `select_page`=write selected state file, plus `Target.activateTarget` only on `focus:true`. `list_pages` may reuse `listTargets()`. |
|
|
170
170
|
| `src/tools/navigation.ts` | `navigate_page`→`navigatePage`, `wait_for`→`waitForText` (export as `waitFor` too) | `Page.enable` then `Page.navigate` (or `Page.reload` + `Page.getFrameTree` when `reload:true`; `ignoreCache:true` = hard reload); await `Page.frameStoppedLoading`/`Page.loadEventFired`. `wait_for` polls `Runtime.evaluate` for `document.body.innerText.includes(text)` with timeout, OR waits for a given event. |
|
|
171
171
|
| `src/tools/evaluate.ts` | `evaluate_script`→`evaluateScript` | `Runtime.enable` + `Runtime.evaluate` (`returnByValue`, `awaitPromise`). Support optional `args` via `Runtime.callFunctionOn` on a uid/selector. Surface `exceptionDetails` as thrown error. |
|
|
172
172
|
| `src/tools/snapshot.ts` | `take_snapshot`→`takeSnapshot` **+ export `resolveUid`** | a11y tree + ref scheme above. |
|
package/README.md
CHANGED
|
@@ -243,6 +243,7 @@ await TOOLS.navigate_page({ target: "index:0", url: "https://example.com" });
|
|
|
243
243
|
| `CDP_USER_DATA_DIR` | unset | Profile directory to read `DevToolsActivePort` from, to find that browser socket without naming its uuid. Opt-in on purpose: nothing is scanned unless you name it. |
|
|
244
244
|
| `CDP_ARTIFACT_DIR` | `/tmp/cdp-toolkit` | Screenshots, traces, heap snapshots, lighthouse reports, recorder buffers. |
|
|
245
245
|
| `CDP_STATE_DIR` | `/tmp/cdp-toolkit` | `select_page` selected-target file, in-flight trace state. |
|
|
246
|
+
| `CDP_RESTORE_FRONT_APP` | on (macOS only) | `0` stops `new_page` / `claim_page` / `close_page` from putting the user's frontmost app back after a background tab brings the browser forward. |
|
|
246
247
|
| `CDP_EXTRACT_BASE_URL` | `http://127.0.0.1:8090/v1` | `extract_page` only. Base URL of the OpenAI-compatible extraction endpoint (the server appends `/chat/completions`). The default is loopback llm-ferry, so page content never leaves the machine; overriding it sends page content wherever the operator points. |
|
|
247
248
|
| `CDP_EXTRACT_MODEL` | `schematron` | `extract_page` only. Model name for the extraction endpoint call. |
|
|
248
249
|
| `CDP_EXTRACT_API_KEY` | unset | `extract_page` only. Bearer token for the endpoint. Never logged and redacted from every error; the response never contains it. |
|
|
@@ -524,9 +525,9 @@ The 29 parity tools are 1:1 with `chrome-devtools-mcp`; the 19 superset tools (`
|
|
|
524
525
|
| MCP name | CDP method(s) | Parity notes / gaps |
|
|
525
526
|
|---|---|---|
|
|
526
527
|
| `list_pages` | `GET /json/list` | `all` flag also exposes worker/background and out-of-process (OOPIF) iframe targets; MCP lists only page tabs. A non-page targetId from this listing is accepted by any tool's `target` param as a bare id, and `take_snapshot` marks a cross-origin iframe node with `frame:"<targetId>"` (input inside such an iframe is invisible to the activity beacon — see "Staleness" below — but the frame itself is fully driveable as its own target). Each row additionally carries `origin` (`agent` or `unknown`, never `human`) plus `label`/`createdAt` for tabs this toolkit created, and, for a tab under an active lease of this backend, a `lease:{label,pid,idleMs,expiresAt,stale}` field (unconditional on `probe`). `probe:true` pings each page-type target's renderer (one bounded 500ms `Runtime.evaluate`, never more) and adds `responsive:boolean` plus `humanActiveMs` where that round trip found human-attributed input; a wedged/unreachable tab reports `responsive:false`, never an error for the whole call. Under `CDP_REQUIRE_LEASE` also reaps abandoned agent tabs first (destructively, only once a lease is `CDP_REAP_GRACE_MS` past its TTL — see "Staleness" below), reporting closures in an additive `reaped` array. |
|
|
527
|
-
| `new_page` | `Target.createTarget` (+ lease file) | Returns `{targetId,url}`; does not await navigation (use `navigate_page`). `claim:true` also claims the new tab and returns a `lease` token (`label`/`ttlMs` optional). Under `CDP_REQUIRE_LEASE` the tab is claimed and a `lease` returned even without `claim:true`. |
|
|
528
|
+
| `new_page` | `Target.createTarget` (+ lease file) | Opens the tab in the background (`background:true`), so the user's visible tab and focus stay put; `focus:true` opens it in the foreground. Returns `{targetId,url}`; does not await navigation (use `navigate_page`). `claim:true` also claims the new tab and returns a `lease` token (`label`/`ttlMs` optional). Under `CDP_REQUIRE_LEASE` the tab is claimed and a `lease` returned even without `claim:true`. |
|
|
528
529
|
| `close_page` | `Target.closeTarget` (+ lease file) | Reports `success:true` on the empty result newer Chromium returns. A successful close also releases that tab's lease; a failed close leaves it in place. |
|
|
529
|
-
| `select_page` | `Target.activateTarget`
|
|
530
|
+
| `select_page` | selected-state file (+ `Target.activateTarget` with `focus:true`) | Writes a flat-file selected target and returns `{selected,focused}`; it raises the tab only with `focus:true`; `resolveTarget` does not read it, so `active` still means `index:0` unless a tool opts in. |
|
|
530
531
|
| `navigate_page` | `Page.navigate` / `Page.reload` + load events, or `history:'back'\|'forward'` (Chrome: `Page.getNavigationHistory` + `Page.navigateToHistoryEntry`; Firefox: `browsingContext.traverseHistory`) | Returns `{url,frameId,waitedFor}` (no auto-snapshot; a history move also returns `traversed:'back'\|'forward'`). `waitUntil` supports `load`/`domcontentloaded`. `reload:true` (+ `ignoreCache:true` for a hard reload). `url`/`reload`/`history` are mutually exclusive; going back from the first entry (or forward from the last) is an error naming the direction, never a silent no-op. Works on both backends. |
|
|
531
532
|
| `wait_for` | `Runtime.evaluate` (poll `innerText`) | Text-substring waiting only; throws on timeout rather than returning `{found:false}`. |
|
|
532
533
|
| `evaluate_script` | `Runtime.evaluate` / `callFunctionOn` | No live `page`/element handle; `args` are plain JSON. Main-world context only. Toolkit addition: optional `savePath` writes the value to a JSON file and keeps it out of the response entirely. If `expression` is missing/empty and the call instead carries `function`/`code`/`js`/`script`/`fn`/`body`, the error names the wrong key and points at `expression`. One of four tools that also accept `target: "worker:<substring>"` (Chrome only, capability `worker.targets`) to reach an MV3 extension's background service worker — see "Driving MV3 extensions" below. |
|
|
@@ -565,7 +566,7 @@ The 29 parity tools are 1:1 with `chrome-devtools-mcp`; the 19 superset tools (`
|
|
|
565
566
|
| `mock_request` *(superset)* | `Fetch.*` (+ `Page.reload`) | **A fake backend.** Registers a rule on a target's persistent session: fulfill with a canned response, fail, or continue (with optional `delayMs`/`failRate`). Persists across reloads until `clear_mocks`. Request-stage only. Cached requests aren't intercepted (use `reload:true`). |
|
|
566
567
|
| `list_mocks` *(superset)* | `Runtime.evaluate` (liveness probe) | Lists active mock sessions with rules + hit counts; prunes sessions whose tab closed. |
|
|
567
568
|
| `clear_mocks` *(superset)* | `Fetch.disable` | Tears down the resolved target's mock session (or all with `all:true`). |
|
|
568
|
-
| `claim_page` *(superset)* | `Target.createTarget` + lease file | Opens a fresh tab and claims it (no `target`/`targetId`), or takes over a tab that is already open (`target`, any selector, or the exact-id `targetId`) and returns an opaque lease token plus `opened` (true only when this call created the tab). Never steals a tab another live process holds. Also returns `humanActiveMs` (ms since input this server did not dispatch; `null` means no data, never "no human") and, on a takeover of a tab a human used within the last 30s, a `contention` warning
|
|
569
|
+
| `claim_page` *(superset)* | `Target.createTarget` + lease file | Opens a fresh tab in the background and claims it (no `target`/`targetId`; `focus:true` opens it in the foreground), or takes over a tab that is already open (`target`, any selector, or the exact-id `targetId`) and returns an opaque lease token plus `opened` (true only when this call created the tab). Never steals a tab another live process holds. Also returns `humanActiveMs` (ms since input this server did not dispatch; `null` means no data, never "no human") and, on a takeover of a tab a human used within the last 30s, a `contention` warning; the claim is never refused for it. MCP only; the CLI refuses it. The `search_tools` and `call_tool` meta-tools are likewise MCP-only. |
|
|
569
570
|
| `release_page` *(superset)* | lease file | Gives a lease back via `lease` (the token) or `target` (a selector, for a lease the gate auto-acquired and so never handed out a token for). Idempotent. Closes the tab by default when this toolkit's creation ledger says it opened it; leaves a merely-claimed tab open. Override either way with `close`. |
|
|
570
571
|
| `list_leases` *(superset)* | lease file | Who holds what, with pid liveness and reclaimability, plus computed `idleMs`/`expiresAt` and, where the tab's beacon answers, `humanActiveMs` (absent, not null, when there's no answer). Needs no token; never returns the nonce. A lease file that could not be read or parsed is reported as an `unreadable` row instead of being skipped (with `idleMs`/`expiresAt` omitted). Under `CDP_REQUIRE_LEASE` also reaps abandoned agent tabs, reporting closures in an additive `reaped` array. |
|
|
571
572
|
| `wait_for_download` *(superset)* | `Browser.setDownloadBehavior` + `Browser.downloadWillBegin`/`downloadProgress` on a standing browser-endpoint connection | Waits for a download to finish and returns it as a real file on disk: `{path,suggestedFilename,bytes,url,target}`. **Ordering rule, not optional:** call `wait_for_download{arm:true}` *before* the click that starts the download, then click, then call `wait_for_download` again to collect it — arming this late is not a preference, it's because Chrome reverts the download-behavior override the instant the arming client disconnects, and denies an unarmed download outright. **Browser-global side effect:** while armed, *every* download in the browser is redirected into the toolkit's downloads directory. **MCP-server only:** the arm lives on a connection this server process holds open; the one-shot CLI's connection dies with the process, so nothing is captured there. Firefox 160+ too (`browser.setDownloadBehavior`), where each call re-arms and the profile's normal download folder is restored when it returns. |
|
package/dist/bidi/mux-daemon.js
CHANGED
|
@@ -731,6 +731,53 @@ var init_session_lease = __esm(() => {
|
|
|
731
731
|
};
|
|
732
732
|
});
|
|
733
733
|
|
|
734
|
+
// src/frontApp.ts
|
|
735
|
+
import { execFile } from "node:child_process";
|
|
736
|
+
function run(cmd, args) {
|
|
737
|
+
return new Promise((resolve) => {
|
|
738
|
+
execFile(cmd, args, { timeout: 2000 }, (err, stdout) => resolve(err ? "" : String(stdout)));
|
|
739
|
+
});
|
|
740
|
+
}
|
|
741
|
+
function restoreFrontAppEnabled(platform = process.platform) {
|
|
742
|
+
return platform === "darwin" && (process.env.CDP_RESTORE_FRONT_APP ?? "").trim() !== "0";
|
|
743
|
+
}
|
|
744
|
+
async function keepFrontApp(fn, opts = {}) {
|
|
745
|
+
const enabled = opts.enabled ?? restoreFrontAppEnabled();
|
|
746
|
+
if (!enabled)
|
|
747
|
+
return fn();
|
|
748
|
+
const ops = opts.ops ?? macFrontAppOps;
|
|
749
|
+
const before = await ops.front().catch(() => null);
|
|
750
|
+
const result = await fn();
|
|
751
|
+
if (before === null)
|
|
752
|
+
return result;
|
|
753
|
+
const fix = async () => {
|
|
754
|
+
const now = await ops.front().catch(() => null);
|
|
755
|
+
if (now !== null && now !== before)
|
|
756
|
+
await ops.setFront(before).catch(() => {
|
|
757
|
+
return;
|
|
758
|
+
});
|
|
759
|
+
};
|
|
760
|
+
await fix();
|
|
761
|
+
await new Promise((r) => setTimeout(r, opts.recheckMs ?? 250));
|
|
762
|
+
await fix();
|
|
763
|
+
return result;
|
|
764
|
+
}
|
|
765
|
+
var macFrontAppOps;
|
|
766
|
+
var init_frontApp = __esm(() => {
|
|
767
|
+
macFrontAppOps = {
|
|
768
|
+
async front() {
|
|
769
|
+
const asn = (await run("lsappinfo", ["front"])).trim();
|
|
770
|
+
if (!asn)
|
|
771
|
+
return null;
|
|
772
|
+
const m = /"?pid"?\s*=\s*(\d+)/.exec(await run("lsappinfo", ["info", "-only", "pid", asn]));
|
|
773
|
+
return m ? Number(m[1]) : null;
|
|
774
|
+
},
|
|
775
|
+
async setFront(pid) {
|
|
776
|
+
await run("osascript", ["-e", `tell application "System Events" to set frontmost of (first process whose unix id is ${pid}) to true`]);
|
|
777
|
+
}
|
|
778
|
+
};
|
|
779
|
+
});
|
|
780
|
+
|
|
734
781
|
// src/driver.ts
|
|
735
782
|
import { mkdir as mkdir3, readFile as readFile3, unlink as unlink3, writeFile as writeFile3 } from "node:fs/promises";
|
|
736
783
|
import { join as join3 } from "node:path";
|
|
@@ -903,7 +950,7 @@ async function originIndex(backend, liveIds) {
|
|
|
903
950
|
return index;
|
|
904
951
|
}
|
|
905
952
|
async function newTrackedPage(driver, backend, opts = {}) {
|
|
906
|
-
const page = await driver.newPage(opts.url);
|
|
953
|
+
const page = await driver.newPage(opts.url, { focus: opts.focus === true });
|
|
907
954
|
await recordOrigin(backend, page.id, { label: opts.label });
|
|
908
955
|
return page;
|
|
909
956
|
}
|
|
@@ -3505,6 +3552,9 @@ async function pickContext(conn, contexts, selector) {
|
|
|
3505
3552
|
return exact;
|
|
3506
3553
|
throw driverError("no-such-target", `no context matching '${selector}'`);
|
|
3507
3554
|
}
|
|
3555
|
+
function bidiCreateTabParams(opts) {
|
|
3556
|
+
return { type: "tab", background: opts?.focus !== true };
|
|
3557
|
+
}
|
|
3508
3558
|
|
|
3509
3559
|
class BidiBrowserDriver {
|
|
3510
3560
|
endpoint;
|
|
@@ -3531,12 +3581,13 @@ class BidiBrowserDriver {
|
|
|
3531
3581
|
conn.release();
|
|
3532
3582
|
}
|
|
3533
3583
|
}
|
|
3534
|
-
async newPage(url) {
|
|
3584
|
+
async newPage(url, opts) {
|
|
3535
3585
|
const conn = await getConnection(this.endpoint, this.timeoutMs, this.attached);
|
|
3536
3586
|
try {
|
|
3537
|
-
const
|
|
3587
|
+
const create = () => conn.send("browsingContext.create", bidiCreateTabParams(opts)).catch((e) => {
|
|
3538
3588
|
throw mapBidiError(e);
|
|
3539
3589
|
});
|
|
3590
|
+
const { context } = opts?.focus === true ? await create() : await keepFrontApp(create);
|
|
3540
3591
|
if (url)
|
|
3541
3592
|
await conn.send("browsingContext.navigate", { context, url, wait: "complete" }).catch((e) => {
|
|
3542
3593
|
throw mapBidiError(e);
|
|
@@ -3549,9 +3600,9 @@ class BidiBrowserDriver {
|
|
|
3549
3600
|
async closePage(id) {
|
|
3550
3601
|
const conn = await getConnection(this.endpoint, this.timeoutMs, this.attached);
|
|
3551
3602
|
try {
|
|
3552
|
-
await conn.send("browsingContext.close", { context: id }).catch((e) => {
|
|
3603
|
+
await keepFrontApp(() => conn.send("browsingContext.close", { context: id }).catch((e) => {
|
|
3553
3604
|
throw mapBidiError(e);
|
|
3554
|
-
});
|
|
3605
|
+
}));
|
|
3555
3606
|
return { success: true };
|
|
3556
3607
|
} finally {
|
|
3557
3608
|
conn.release();
|
|
@@ -3735,6 +3786,7 @@ function createFirefoxDriverForEndpoint(wsUrl, opts) {
|
|
|
3735
3786
|
}
|
|
3736
3787
|
var LINE_RE, INTERACTIVE_ROLES, STAMP_ONE_SOURCE, KEY_VALUES, MODIFIER_VALUES, BUTTON_CODES, RAW_MOUSE_SOURCE_ID = "cdp-raw-mouse", ARM_SCROLL_SETTLE_WATCH_SOURCE, AWAIT_SCROLL_SETTLE_SOURCE = "function(){return window.__cdpScrollSettle;}", BIDI_CAPABILITY_MIN_FIREFOX, POST_HOC_BODY_MAX_BYTES, BIDI_CAPABILITIES, connections, slotHandles, muxes, joined, connecting, sessionEpochs, connEndpoints, disposeHooks, STALE_ID_HINT, sleep2 = (ms) => new Promise((r) => setTimeout(r, ms)), slotLabelOverride, bidiBeaconScripts, BidiPageDriver;
|
|
3737
3788
|
var init_driver2 = __esm(() => {
|
|
3789
|
+
init_frontApp();
|
|
3738
3790
|
init_driver();
|
|
3739
3791
|
init_leases();
|
|
3740
3792
|
init_origins();
|
|
@@ -4076,8 +4128,11 @@ var init_driver2 = __esm(() => {
|
|
|
4076
4128
|
await this.callFunctionValue(BidiPageDriver.INSERT_TEXT_SOURCE, [value, false], ref);
|
|
4077
4129
|
return;
|
|
4078
4130
|
}
|
|
4079
|
-
const clear = "function(){this.focus&&this.focus();if('value' in this){this.value='';this.dispatchEvent(new Event('input',{bubbles:true}));}}";
|
|
4080
|
-
await this.callFunctionValue(clear, [], ref);
|
|
4131
|
+
const clear = "function(){if(this.disabled||this.readOnly)return this.disabled?'disabled':'readonly';this.focus&&this.focus();if('value' in this){this.value='';this.dispatchEvent(new Event('input',{bubbles:true}));}return 'ok';}";
|
|
4132
|
+
const state = await this.callFunctionValue(clear, [], ref);
|
|
4133
|
+
if (state === "disabled" || state === "readonly") {
|
|
4134
|
+
throw driverError("page-error", `cannot fill a ${state} field: it was left unchanged`);
|
|
4135
|
+
}
|
|
4081
4136
|
await this.sendKeys(value);
|
|
4082
4137
|
}
|
|
4083
4138
|
async typeText(loc, text) {
|