cdp-toolkit 3.4.0 → 3.6.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 +22 -0
- package/CONTRACT.md +1 -0
- package/README.md +54 -18
- package/dist/bidi/mux-daemon.js +184 -5
- package/dist/cli.js +732 -60
- package/dist/index.js +566 -21
- package/dist/mcp.js +763 -51
- package/package.json +4 -3
- package/src/cdp/driver.ts +75 -7
- package/src/cdp/hiddenTabs.ts +285 -0
- package/src/client.ts +12 -3
- package/src/driver.ts +11 -1
- package/src/focusPolicy.ts +16 -0
- package/src/index.ts +8 -1
- package/src/leases-tools.ts +6 -0
- package/src/leases.ts +6 -0
- package/src/manifest.ts +124 -0
- package/src/mcp.ts +4 -0
- package/src/origins.ts +4 -2
- package/src/policy.ts +4 -0
- package/src/shared-tools.ts +46 -10
- package/src/toolDocs.ts +38 -6
- package/src/toolGroups.ts +2 -1
- package/src/tools/screencast.ts +3 -1
- package/src/tools/tab-groups.ts +435 -0
- package/src/types.ts +3 -0
- package/src/version.ts +1 -1
package/dist/cli.js
CHANGED
|
@@ -323,6 +323,9 @@ function leaseTtlMs() {
|
|
|
323
323
|
function markLongLivedProcess(value = true) {
|
|
324
324
|
longLived = value;
|
|
325
325
|
}
|
|
326
|
+
function isLongLivedProcess() {
|
|
327
|
+
return longLived;
|
|
328
|
+
}
|
|
326
329
|
function requireLease() {
|
|
327
330
|
if (!longLived)
|
|
328
331
|
return false;
|
|
@@ -588,6 +591,15 @@ var init_leases = __esm(() => {
|
|
|
588
591
|
LEASE_FILE_RE = new RegExp(`^lease-(${BACKEND_KEY_SOURCE})-(.+)\\.json$`);
|
|
589
592
|
});
|
|
590
593
|
|
|
594
|
+
// src/focusPolicy.ts
|
|
595
|
+
function focusDenied() {
|
|
596
|
+
return TRUTHY.has((process.env.CDP_DENY_FOCUS ?? "").trim().toLowerCase());
|
|
597
|
+
}
|
|
598
|
+
var TRUTHY;
|
|
599
|
+
var init_focusPolicy = __esm(() => {
|
|
600
|
+
TRUTHY = new Set(["1", "true", "yes", "on"]);
|
|
601
|
+
});
|
|
602
|
+
|
|
591
603
|
// src/origins.ts
|
|
592
604
|
import { mkdir as mkdir2, readFile as readFile2, readdir as readdir2, unlink as unlink2, writeFile as writeFile2 } from "node:fs/promises";
|
|
593
605
|
import { join as join2 } from "node:path";
|
|
@@ -687,7 +699,7 @@ async function originIndex(backend, liveIds) {
|
|
|
687
699
|
return index;
|
|
688
700
|
}
|
|
689
701
|
async function newTrackedPage(driver, backend, opts = {}) {
|
|
690
|
-
const page = await driver.newPage(opts.url, { focus: opts.focus === true });
|
|
702
|
+
const page = await driver.newPage(opts.url, { focus: opts.focus === true && !focusDenied() });
|
|
691
703
|
await recordOrigin(backend, page.id, { label: opts.label });
|
|
692
704
|
return page;
|
|
693
705
|
}
|
|
@@ -714,6 +726,7 @@ async function resolveLiveLabel(backend, label, liveIds) {
|
|
|
714
726
|
}
|
|
715
727
|
var ORIGIN_FILE_RE;
|
|
716
728
|
var init_origins = __esm(() => {
|
|
729
|
+
init_focusPolicy();
|
|
717
730
|
init_leases();
|
|
718
731
|
ORIGIN_FILE_RE = new RegExp(`^origin-(${BACKEND_KEY_SOURCE})-(.+)\\.json$`);
|
|
719
732
|
});
|
|
@@ -1001,6 +1014,165 @@ var init_session = __esm(() => {
|
|
|
1001
1014
|
init_endpoint();
|
|
1002
1015
|
});
|
|
1003
1016
|
|
|
1017
|
+
// src/cdp/hiddenTabs.ts
|
|
1018
|
+
function hiddenTabsRequested() {
|
|
1019
|
+
return TRUTHY2.has((process.env.CDP_HIDDEN_TABS ?? "").trim().toLowerCase());
|
|
1020
|
+
}
|
|
1021
|
+
function hiddenTabsMax() {
|
|
1022
|
+
const raw = Number(process.env.CDP_HIDDEN_TABS_MAX);
|
|
1023
|
+
return Number.isFinite(raw) && raw >= 1 ? Math.floor(raw) : DEFAULT_HIDDEN_TABS_MAX;
|
|
1024
|
+
}
|
|
1025
|
+
|
|
1026
|
+
class HiddenTabOwner {
|
|
1027
|
+
deps;
|
|
1028
|
+
conn;
|
|
1029
|
+
connecting;
|
|
1030
|
+
tabs = new Map;
|
|
1031
|
+
reserved = 0;
|
|
1032
|
+
constructor(deps) {
|
|
1033
|
+
this.deps = deps;
|
|
1034
|
+
}
|
|
1035
|
+
sweep() {
|
|
1036
|
+
if (this.conn && !this.conn.isOpen) {
|
|
1037
|
+
this.conn = undefined;
|
|
1038
|
+
this.tabs.clear();
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
has(id) {
|
|
1042
|
+
this.sweep();
|
|
1043
|
+
return this.tabs.has(id);
|
|
1044
|
+
}
|
|
1045
|
+
ids() {
|
|
1046
|
+
this.sweep();
|
|
1047
|
+
return [...this.tabs.keys()];
|
|
1048
|
+
}
|
|
1049
|
+
async owner() {
|
|
1050
|
+
this.sweep();
|
|
1051
|
+
if (this.conn)
|
|
1052
|
+
return this.conn;
|
|
1053
|
+
if (!this.connecting) {
|
|
1054
|
+
this.connecting = (async () => {
|
|
1055
|
+
const conn = await this.deps.connect();
|
|
1056
|
+
conn.on("Target.targetDestroyed", (params) => {
|
|
1057
|
+
const id = params.targetId;
|
|
1058
|
+
if (typeof id === "string")
|
|
1059
|
+
this.tabs.delete(id);
|
|
1060
|
+
});
|
|
1061
|
+
this.conn = conn;
|
|
1062
|
+
return conn;
|
|
1063
|
+
})().finally(() => {
|
|
1064
|
+
this.connecting = undefined;
|
|
1065
|
+
});
|
|
1066
|
+
}
|
|
1067
|
+
return this.connecting;
|
|
1068
|
+
}
|
|
1069
|
+
async create(url) {
|
|
1070
|
+
this.sweep();
|
|
1071
|
+
const max = (this.deps.max ?? hiddenTabsMax)();
|
|
1072
|
+
if (this.tabs.size + this.reserved >= max)
|
|
1073
|
+
throw new HiddenTabCapError(max, [...this.tabs.keys()]);
|
|
1074
|
+
this.reserved++;
|
|
1075
|
+
try {
|
|
1076
|
+
const conn = await this.owner();
|
|
1077
|
+
const id = await this.deps.createSettled(conn, url, { hidden: true });
|
|
1078
|
+
try {
|
|
1079
|
+
const { sessionId } = await conn.send("Target.attachToTarget", { targetId: id, flatten: true }, { timeoutMs: OWNER_COMMAND_TIMEOUT_MS });
|
|
1080
|
+
const dpr = await conn.send("Runtime.evaluate", { expression: "devicePixelRatio", returnByValue: true }, { sessionId, timeoutMs: OWNER_COMMAND_TIMEOUT_MS }).then((r) => r.result?.value).catch(() => {
|
|
1081
|
+
return;
|
|
1082
|
+
});
|
|
1083
|
+
await conn.send("Emulation.setDeviceMetricsOverride", {
|
|
1084
|
+
width: HIDDEN_TAB_VIEWPORT.width,
|
|
1085
|
+
height: HIDDEN_TAB_VIEWPORT.height,
|
|
1086
|
+
deviceScaleFactor: typeof dpr === "number" && Number.isFinite(dpr) && dpr > 0 ? dpr : FALLBACK_DEVICE_SCALE_FACTOR,
|
|
1087
|
+
mobile: false
|
|
1088
|
+
}, { sessionId, timeoutMs: OWNER_COMMAND_TIMEOUT_MS });
|
|
1089
|
+
this.tabs.set(id, sessionId);
|
|
1090
|
+
return id;
|
|
1091
|
+
} catch (e) {
|
|
1092
|
+
await conn.send("Target.closeTarget", { targetId: id }, { timeoutMs: OWNER_COMMAND_TIMEOUT_MS }).catch(() => {
|
|
1093
|
+
return;
|
|
1094
|
+
});
|
|
1095
|
+
throw e;
|
|
1096
|
+
}
|
|
1097
|
+
} finally {
|
|
1098
|
+
this.reserved--;
|
|
1099
|
+
}
|
|
1100
|
+
}
|
|
1101
|
+
async close(id) {
|
|
1102
|
+
this.sweep();
|
|
1103
|
+
const conn = this.conn;
|
|
1104
|
+
const held = this.tabs.delete(id);
|
|
1105
|
+
if (!conn || !held)
|
|
1106
|
+
return { success: false };
|
|
1107
|
+
const res = await conn.send("Target.closeTarget", { targetId: id }, { timeoutMs: OWNER_COMMAND_TIMEOUT_MS });
|
|
1108
|
+
return { success: res.success ?? true };
|
|
1109
|
+
}
|
|
1110
|
+
async dispose() {
|
|
1111
|
+
const conn = this.conn;
|
|
1112
|
+
const ids = [...this.tabs.keys()];
|
|
1113
|
+
this.tabs.clear();
|
|
1114
|
+
this.conn = undefined;
|
|
1115
|
+
if (!conn)
|
|
1116
|
+
return;
|
|
1117
|
+
if (conn.isOpen) {
|
|
1118
|
+
await Promise.all(ids.map((targetId) => conn.send("Target.closeTarget", { targetId }, { timeoutMs: OWNER_COMMAND_TIMEOUT_MS }).catch(() => {
|
|
1119
|
+
return;
|
|
1120
|
+
})));
|
|
1121
|
+
}
|
|
1122
|
+
conn.close();
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
function hiddenTabOwner(base, deps) {
|
|
1126
|
+
let owner = owners.get(base);
|
|
1127
|
+
if (!owner) {
|
|
1128
|
+
owner = new HiddenTabOwner(deps());
|
|
1129
|
+
owners.set(base, owner);
|
|
1130
|
+
}
|
|
1131
|
+
return owner;
|
|
1132
|
+
}
|
|
1133
|
+
function existingHiddenTabOwner(base) {
|
|
1134
|
+
return owners.get(base);
|
|
1135
|
+
}
|
|
1136
|
+
function markHiddenTargets(base, targets) {
|
|
1137
|
+
const owner = owners.get(base);
|
|
1138
|
+
if (!owner)
|
|
1139
|
+
return targets;
|
|
1140
|
+
const hidden = new Set(owner.ids());
|
|
1141
|
+
if (hidden.size === 0)
|
|
1142
|
+
return targets;
|
|
1143
|
+
const visible = [];
|
|
1144
|
+
const marked = [];
|
|
1145
|
+
for (const t of targets) {
|
|
1146
|
+
if (hidden.has(t.id))
|
|
1147
|
+
marked.push({ ...t, type: "page", hidden: true });
|
|
1148
|
+
else
|
|
1149
|
+
visible.push(t);
|
|
1150
|
+
}
|
|
1151
|
+
return marked.length ? [...visible, ...marked] : targets;
|
|
1152
|
+
}
|
|
1153
|
+
async function disposeHiddenTabs() {
|
|
1154
|
+
const all = [...owners.values()];
|
|
1155
|
+
owners.clear();
|
|
1156
|
+
await Promise.all(all.map((o) => o.dispose()));
|
|
1157
|
+
}
|
|
1158
|
+
var DEFAULT_HIDDEN_TABS_MAX = 20, HIDDEN_TAB_VIEWPORT, FALLBACK_DEVICE_SCALE_FACTOR = 2, OWNER_COMMAND_TIMEOUT_MS = 5000, TRUTHY2, HiddenTabCapError, owners;
|
|
1159
|
+
var init_hiddenTabs = __esm(() => {
|
|
1160
|
+
HIDDEN_TAB_VIEWPORT = { width: 1280, height: 800 };
|
|
1161
|
+
TRUTHY2 = new Set(["1", "true", "yes", "on"]);
|
|
1162
|
+
HiddenTabCapError = class HiddenTabCapError extends Error {
|
|
1163
|
+
max;
|
|
1164
|
+
openIds;
|
|
1165
|
+
code = "page-error";
|
|
1166
|
+
constructor(max, openIds) {
|
|
1167
|
+
super(`hidden-tab cap reached: ${openIds.length} hidden tabs are open (CDP_HIDDEN_TABS_MAX=${max}). ` + `Close one with close_page (open hidden tabs, oldest first: ${openIds.join(", ")}), ` + `or pass focus:true to open a visible tab instead.`);
|
|
1168
|
+
this.max = max;
|
|
1169
|
+
this.openIds = openIds;
|
|
1170
|
+
this.name = "HiddenTabCapError";
|
|
1171
|
+
}
|
|
1172
|
+
};
|
|
1173
|
+
owners = new Map;
|
|
1174
|
+
});
|
|
1175
|
+
|
|
1004
1176
|
// src/client.ts
|
|
1005
1177
|
class CdpConnection {
|
|
1006
1178
|
wsUrl;
|
|
@@ -1119,6 +1291,9 @@ class CdpConnection {
|
|
|
1119
1291
|
});
|
|
1120
1292
|
});
|
|
1121
1293
|
}
|
|
1294
|
+
get isOpen() {
|
|
1295
|
+
return !this.closed && this.ws !== undefined;
|
|
1296
|
+
}
|
|
1122
1297
|
close() {
|
|
1123
1298
|
this.closed = true;
|
|
1124
1299
|
this.rejectAll(new CdpError("closed by caller"));
|
|
@@ -1147,11 +1322,11 @@ async function getTargetsOverBrowserWs() {
|
|
|
1147
1322
|
async function listTargets() {
|
|
1148
1323
|
const base = currentEndpoint().base;
|
|
1149
1324
|
if (knownTransports.get(base) === "browser-ws")
|
|
1150
|
-
return getTargetsOverBrowserWs();
|
|
1325
|
+
return markHiddenTargets(base, await getTargetsOverBrowserWs());
|
|
1151
1326
|
try {
|
|
1152
1327
|
const listing = await httpJson("/json/list");
|
|
1153
1328
|
knownTransports.set(base, "http");
|
|
1154
|
-
return listing;
|
|
1329
|
+
return markHiddenTargets(base, listing);
|
|
1155
1330
|
} catch (httpError) {
|
|
1156
1331
|
const detected = await detectEndpoint().catch(() => {
|
|
1157
1332
|
return;
|
|
@@ -1162,7 +1337,7 @@ async function listTargets() {
|
|
|
1162
1337
|
throw httpError;
|
|
1163
1338
|
});
|
|
1164
1339
|
knownTransports.set(base, "browser-ws");
|
|
1165
|
-
return targets;
|
|
1340
|
+
return markHiddenTargets(base, targets);
|
|
1166
1341
|
}
|
|
1167
1342
|
}
|
|
1168
1343
|
async function browserWsUrl() {
|
|
@@ -1275,6 +1450,7 @@ var init_client = __esm(() => {
|
|
|
1275
1450
|
init_frames();
|
|
1276
1451
|
init_endpoint();
|
|
1277
1452
|
init_session();
|
|
1453
|
+
init_hiddenTabs();
|
|
1278
1454
|
init_session();
|
|
1279
1455
|
BASE = (() => {
|
|
1280
1456
|
try {
|
|
@@ -1726,7 +1902,10 @@ var init_driver = __esm(() => {
|
|
|
1726
1902
|
focus_emulation: ["emulate.focus"],
|
|
1727
1903
|
click_focus_gated: ["emulate.focus"],
|
|
1728
1904
|
wait_for_download: ["browser.downloads"],
|
|
1729
|
-
grant_permissions: ["browser.permissions"]
|
|
1905
|
+
grant_permissions: ["browser.permissions"],
|
|
1906
|
+
list_tab_groups: ["browser.tabGroups"],
|
|
1907
|
+
group_tabs: ["browser.tabGroups"],
|
|
1908
|
+
ungroup_tabs: ["browser.tabGroups"]
|
|
1730
1909
|
};
|
|
1731
1910
|
});
|
|
1732
1911
|
|
|
@@ -2244,16 +2423,16 @@ var init_client2 = __esm(() => {
|
|
|
2244
2423
|
});
|
|
2245
2424
|
|
|
2246
2425
|
// src/bidi/session-lease.ts
|
|
2247
|
-
import { mkdir as
|
|
2248
|
-
import { join as
|
|
2426
|
+
import { mkdir as mkdir14, readFile as readFile10, rename as rename3, unlink as unlink5, writeFile as writeFile11 } from "node:fs/promises";
|
|
2427
|
+
import { join as join13 } from "node:path";
|
|
2249
2428
|
function safeEndpoint(endpoint) {
|
|
2250
2429
|
return endpoint.replace(/[^A-Za-z0-9._-]/g, "_");
|
|
2251
2430
|
}
|
|
2252
2431
|
function sessionSlotFile(endpoint) {
|
|
2253
|
-
return
|
|
2432
|
+
return join13(leaseDir(), `ff-session-${safeEndpoint(endpoint)}.json`);
|
|
2254
2433
|
}
|
|
2255
2434
|
function muxDaemonLogFile(endpoint) {
|
|
2256
|
-
return
|
|
2435
|
+
return join13(leaseDir(), `ff-mux-${safeEndpoint(endpoint)}.log`);
|
|
2257
2436
|
}
|
|
2258
2437
|
function sessionWaitMs() {
|
|
2259
2438
|
const raw = Number(process.env.CDP_FIREFOX_SESSION_WAIT_MS);
|
|
@@ -2262,7 +2441,7 @@ function sessionWaitMs() {
|
|
|
2262
2441
|
async function readSessionSlot(endpoint) {
|
|
2263
2442
|
let raw;
|
|
2264
2443
|
try {
|
|
2265
|
-
raw = await
|
|
2444
|
+
raw = await readFile10(sessionSlotFile(endpoint), "utf8");
|
|
2266
2445
|
} catch (err) {
|
|
2267
2446
|
if (err.code === "ENOENT")
|
|
2268
2447
|
return;
|
|
@@ -2291,7 +2470,7 @@ async function acquireSessionSlot(endpoint, opts) {
|
|
|
2291
2470
|
record.marionettePort = opts.marionettePort;
|
|
2292
2471
|
const handle = { endpoint, pid: process.pid, createdAt };
|
|
2293
2472
|
const payload = JSON.stringify(record);
|
|
2294
|
-
await
|
|
2473
|
+
await mkdir14(leaseDir(), { recursive: true });
|
|
2295
2474
|
const deadline = Date.now() + waitMs;
|
|
2296
2475
|
const maxAttempts = Math.max(100, Math.ceil(waitMs / pollMs) + 100);
|
|
2297
2476
|
let attempts = 0;
|
|
@@ -2301,7 +2480,7 @@ async function acquireSessionSlot(endpoint, opts) {
|
|
|
2301
2480
|
throw new SessionSlotBusyError(endpoint, lastLiveHolder);
|
|
2302
2481
|
attempts++;
|
|
2303
2482
|
try {
|
|
2304
|
-
await
|
|
2483
|
+
await writeFile11(file, payload, { flag: "wx" });
|
|
2305
2484
|
return { handle };
|
|
2306
2485
|
} catch (err) {
|
|
2307
2486
|
if (err.code !== "EEXIST")
|
|
@@ -2315,7 +2494,7 @@ async function acquireSessionSlot(endpoint, opts) {
|
|
|
2315
2494
|
return;
|
|
2316
2495
|
});
|
|
2317
2496
|
try {
|
|
2318
|
-
await
|
|
2497
|
+
await writeFile11(file, payload, { flag: "wx" });
|
|
2319
2498
|
return { handle, staleHolder: holder };
|
|
2320
2499
|
} catch (err) {
|
|
2321
2500
|
if (err.code !== "EEXIST")
|
|
@@ -2343,7 +2522,7 @@ async function advertiseMux(handle, muxEndpoint) {
|
|
|
2343
2522
|
const tmp = `${file}.tmp-${process.pid}`;
|
|
2344
2523
|
const next = { ...current, muxEndpoint };
|
|
2345
2524
|
try {
|
|
2346
|
-
await
|
|
2525
|
+
await writeFile11(tmp, JSON.stringify(next), "utf8");
|
|
2347
2526
|
await rename3(tmp, file);
|
|
2348
2527
|
} catch {
|
|
2349
2528
|
await unlink5(tmp).catch(() => {
|
|
@@ -2389,9 +2568,9 @@ var init_session_lease = __esm(() => {
|
|
|
2389
2568
|
|
|
2390
2569
|
// src/bidi/mux.ts
|
|
2391
2570
|
import { createServer } from "node:net";
|
|
2392
|
-
import { createHash } from "node:crypto";
|
|
2571
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
2393
2572
|
function acceptKey(key) {
|
|
2394
|
-
return
|
|
2573
|
+
return createHash2("sha1").update(key + WS_GUID).digest("base64");
|
|
2395
2574
|
}
|
|
2396
2575
|
function encodeFrame(opcode, payload) {
|
|
2397
2576
|
const len = payload.length;
|
|
@@ -4530,6 +4709,7 @@ init_client();
|
|
|
4530
4709
|
init_session();
|
|
4531
4710
|
init_frontApp();
|
|
4532
4711
|
init_leases();
|
|
4712
|
+
init_hiddenTabs();
|
|
4533
4713
|
init_endpoints();
|
|
4534
4714
|
init_activity();
|
|
4535
4715
|
|
|
@@ -5040,6 +5220,7 @@ var CDP_CAPABILITIES = new Set([
|
|
|
5040
5220
|
"emulate.focus",
|
|
5041
5221
|
"browser.downloads",
|
|
5042
5222
|
"browser.permissions",
|
|
5223
|
+
"browser.tabGroups",
|
|
5043
5224
|
"worker.targets",
|
|
5044
5225
|
"frame.targets"
|
|
5045
5226
|
]);
|
|
@@ -5730,8 +5911,10 @@ async function createSettledTarget(conn, url, settleMs = NEW_TARGET_SETTLE_MS, o
|
|
|
5730
5911
|
await conn.send("Target.setDiscoverTargets", { discover: true }).catch(() => {
|
|
5731
5912
|
return;
|
|
5732
5913
|
});
|
|
5733
|
-
const
|
|
5734
|
-
const
|
|
5914
|
+
const hidden = opts.hidden === true;
|
|
5915
|
+
const params = hidden ? { url, background: true, hidden: true } : { url, background: opts.focus !== true };
|
|
5916
|
+
const create = () => conn.send("Target.createTarget", params);
|
|
5917
|
+
const { targetId } = opts.focus === true || hidden ? await create() : await keepFrontApp(create);
|
|
5735
5918
|
if (!targetId)
|
|
5736
5919
|
throw driverError("page-error", "Target.createTarget returned no targetId");
|
|
5737
5920
|
id = targetId;
|
|
@@ -5749,6 +5932,19 @@ async function createSettledTarget(conn, url, settleMs = NEW_TARGET_SETTLE_MS, o
|
|
|
5749
5932
|
off();
|
|
5750
5933
|
}
|
|
5751
5934
|
}
|
|
5935
|
+
function hiddenTabsEnabled() {
|
|
5936
|
+
return hiddenTabsRequested() && isLongLivedProcess();
|
|
5937
|
+
}
|
|
5938
|
+
function currentHiddenOwner() {
|
|
5939
|
+
return hiddenTabOwner(currentEndpoint().base, () => ({
|
|
5940
|
+
connect: () => openBrowser(),
|
|
5941
|
+
createSettled: (conn, url, opts) => createSettledTarget(conn, url, NEW_TARGET_SETTLE_MS, opts)
|
|
5942
|
+
}));
|
|
5943
|
+
}
|
|
5944
|
+
function hiddenOwnerOf(id) {
|
|
5945
|
+
const owner = existingHiddenTabOwner(currentEndpoint().base);
|
|
5946
|
+
return owner?.has(id) ? owner : undefined;
|
|
5947
|
+
}
|
|
5752
5948
|
|
|
5753
5949
|
class CdpBrowserDriver {
|
|
5754
5950
|
scheme = "cdp";
|
|
@@ -5759,15 +5955,26 @@ class CdpBrowserDriver {
|
|
|
5759
5955
|
async listPages(opts) {
|
|
5760
5956
|
const targets = await listTargets();
|
|
5761
5957
|
const filtered = opts?.all ? targets : targets.filter((t) => t.type === "page");
|
|
5762
|
-
return filtered.map((t) => ({ id: t.id, url: t.url, title: t.title, type: t.type }));
|
|
5958
|
+
return filtered.map((t) => ({ id: t.id, url: t.url, title: t.title, type: t.type, ...t.hidden ? { hidden: true } : {} }));
|
|
5763
5959
|
}
|
|
5764
5960
|
async newPage(url, opts) {
|
|
5961
|
+
if (opts?.focus !== true && hiddenTabsEnabled()) {
|
|
5962
|
+
const id = await currentHiddenOwner().create(url ?? "about:blank");
|
|
5963
|
+
return { id, url: url ?? "about:blank", title: "", hidden: true };
|
|
5964
|
+
}
|
|
5765
5965
|
return withBrowserConn(async (conn) => {
|
|
5766
5966
|
const targetId = await createSettledTarget(conn, url ?? "about:blank", NEW_TARGET_SETTLE_MS, { focus: opts?.focus === true });
|
|
5767
5967
|
return { id: targetId, url: url ?? "about:blank", title: "" };
|
|
5768
5968
|
});
|
|
5769
5969
|
}
|
|
5770
5970
|
async closePage(id) {
|
|
5971
|
+
const owner = hiddenOwnerOf(id);
|
|
5972
|
+
if (owner) {
|
|
5973
|
+
const res = await owner.close(id);
|
|
5974
|
+
if (res.success)
|
|
5975
|
+
beaconSessions.drop(beaconKey(id));
|
|
5976
|
+
return res;
|
|
5977
|
+
}
|
|
5771
5978
|
return withBrowserConn(async (conn) => {
|
|
5772
5979
|
const res = await keepFrontApp(() => conn.send("Target.closeTarget", { targetId: id }));
|
|
5773
5980
|
if (res.success !== false)
|
|
@@ -5777,6 +5984,16 @@ class CdpBrowserDriver {
|
|
|
5777
5984
|
}
|
|
5778
5985
|
async activatePage(id) {
|
|
5779
5986
|
const target = await resolveTarget(id).catch(noSuchTarget);
|
|
5987
|
+
const owner = hiddenOwnerOf(target.id);
|
|
5988
|
+
if (owner) {
|
|
5989
|
+
const url = target.url || "about:blank";
|
|
5990
|
+
const newId = await withBrowserConn((conn) => createSettledTarget(conn, url, NEW_TARGET_SETTLE_MS, { focus: true }));
|
|
5991
|
+
await owner.close(target.id).catch(() => {
|
|
5992
|
+
return;
|
|
5993
|
+
});
|
|
5994
|
+
beaconSessions.drop(beaconKey(target.id));
|
|
5995
|
+
return { id: newId, url, title: target.title, revealedFrom: target.id };
|
|
5996
|
+
}
|
|
5780
5997
|
await withBrowserConn((conn) => conn.send("Target.activateTarget", { targetId: target.id }));
|
|
5781
5998
|
return { id: target.id, url: target.url, title: target.title };
|
|
5782
5999
|
}
|
|
@@ -5850,6 +6067,7 @@ class CdpBrowserDriver {
|
|
|
5850
6067
|
}
|
|
5851
6068
|
async dispose() {
|
|
5852
6069
|
beaconSessions.clear();
|
|
6070
|
+
await disposeHiddenTabs();
|
|
5853
6071
|
}
|
|
5854
6072
|
}
|
|
5855
6073
|
function createCdpDriver() {
|
|
@@ -5915,6 +6133,7 @@ async function reapStaleAgentTabs(driver, backend) {
|
|
|
5915
6133
|
}
|
|
5916
6134
|
|
|
5917
6135
|
// src/shared-tools.ts
|
|
6136
|
+
init_focusPolicy();
|
|
5918
6137
|
init_driver();
|
|
5919
6138
|
import { mkdir as mkdir5, writeFile as writeFile4 } from "node:fs/promises";
|
|
5920
6139
|
import { dirname as dirname2, join as join5 } from "node:path";
|
|
@@ -6598,16 +6817,20 @@ async function listPagesOne(driver, args = {}) {
|
|
|
6598
6817
|
async function newPage(driver, args = {}) {
|
|
6599
6818
|
const label = typeof args.label === "string" && args.label.length ? args.label : defaultLabel();
|
|
6600
6819
|
const p = await newTrackedPage(driver, backendOf(driver), { url: args.url, label, focus: args.focus === true });
|
|
6820
|
+
const hidden = {
|
|
6821
|
+
...p.hidden === true ? { hidden: true } : {},
|
|
6822
|
+
...args.focus === true && focusDenied() ? { focusDenied: true } : {}
|
|
6823
|
+
};
|
|
6601
6824
|
const explicit = args.claim === true;
|
|
6602
6825
|
if (!explicit && !requireLease())
|
|
6603
|
-
return { targetId: p.id, url: p.url };
|
|
6826
|
+
return { targetId: p.id, url: p.url, ...hidden };
|
|
6604
6827
|
const { record, token } = await claimLease(backendOf(driver), p.id, {
|
|
6605
6828
|
label,
|
|
6606
6829
|
ttlMs: typeof args.ttlMs === "number" && args.ttlMs > 0 ? args.ttlMs : leaseTtlMs(),
|
|
6607
6830
|
auto: !explicit
|
|
6608
6831
|
});
|
|
6609
6832
|
await installBeacon(driver, p.id);
|
|
6610
|
-
return { targetId: p.id, url: p.url, lease: token, label: record.label, expiresAt: record.lastUsedAt + record.ttlMs };
|
|
6833
|
+
return { targetId: p.id, url: p.url, ...hidden, lease: token, label: record.label, expiresAt: record.lastUsedAt + record.ttlMs };
|
|
6611
6834
|
}
|
|
6612
6835
|
async function closePage(driver, args) {
|
|
6613
6836
|
if (args.target === undefined || args.target === "")
|
|
@@ -6628,9 +6851,33 @@ async function selectPage(driver, args) {
|
|
|
6628
6851
|
if (args.target === undefined || args.target === "")
|
|
6629
6852
|
throw new SharedToolError("select_page requires an explicit target");
|
|
6630
6853
|
const p = await resolvePage(driver, args.target);
|
|
6631
|
-
|
|
6632
|
-
|
|
6633
|
-
|
|
6854
|
+
if (args.focus !== true || focusDenied()) {
|
|
6855
|
+
await writeSelectedFile(p.id);
|
|
6856
|
+
return { selected: p.id, focused: false, ...args.focus === true ? { focusDenied: true } : {} };
|
|
6857
|
+
}
|
|
6858
|
+
const shown = await driver.activatePage(p.id);
|
|
6859
|
+
if (shown.revealedFrom === undefined || shown.id === p.id) {
|
|
6860
|
+
await writeSelectedFile(shown.id);
|
|
6861
|
+
return { selected: shown.id, focused: true };
|
|
6862
|
+
}
|
|
6863
|
+
const moved = await moveRevealedTab(backendOf(driver), shown.revealedFrom, shown.id);
|
|
6864
|
+
await writeSelectedFile(shown.id);
|
|
6865
|
+
return { selected: shown.id, focused: true, revealedFrom: shown.revealedFrom, ...moved.lease ? { lease: moved.lease } : {} };
|
|
6866
|
+
}
|
|
6867
|
+
async function moveRevealedTab(backend, fromId, toId) {
|
|
6868
|
+
const origin = await readOrigin(backend, fromId).catch(() => {
|
|
6869
|
+
return;
|
|
6870
|
+
});
|
|
6871
|
+
if (origin)
|
|
6872
|
+
await recordOrigin(backend, toId, { label: origin.label, now: origin.createdAt });
|
|
6873
|
+
const lease = await readLease(backend, fromId).catch(() => {
|
|
6874
|
+
return;
|
|
6875
|
+
});
|
|
6876
|
+
if (!lease)
|
|
6877
|
+
return {};
|
|
6878
|
+
await releaseLeaseFor(backend, fromId);
|
|
6879
|
+
const { token } = await claimLease(backend, toId, { label: lease.label, ttlMs: lease.ttlMs, auto: lease.auto === true });
|
|
6880
|
+
return { lease: token };
|
|
6634
6881
|
}
|
|
6635
6882
|
function toLegacyWaitedFor(w) {
|
|
6636
6883
|
if (w === "committed")
|
|
@@ -7041,7 +7288,7 @@ async function pressKey(driver, args) {
|
|
|
7041
7288
|
pressed: args.key,
|
|
7042
7289
|
modifiers,
|
|
7043
7290
|
delivered: false,
|
|
7044
|
-
note: "the page saw no keydown: a background tab gets no trusted keyboard input. A click on the tab's page (click tool) usually gives it focus so keys land; or open the tab with new_page focus:true. A key handled inside a cross-origin iframe also reads as not delivered."
|
|
7291
|
+
note: "the page saw no keydown: a background tab gets no trusted keyboard input. A click on the tab's page (click tool) usually gives it focus so keys land; or open the tab with new_page focus:true (which raises the browser over the user's work; refused under CDP_DENY_FOCUS). A key handled inside a cross-origin iframe also reads as not delivered."
|
|
7045
7292
|
};
|
|
7046
7293
|
}
|
|
7047
7294
|
return { pressed: args.key, modifiers };
|
|
@@ -7296,6 +7543,7 @@ async function claimPage(driver, args = {}) {
|
|
|
7296
7543
|
let targetId;
|
|
7297
7544
|
let url;
|
|
7298
7545
|
let opened;
|
|
7546
|
+
let hidden = false;
|
|
7299
7547
|
if (hasTarget) {
|
|
7300
7548
|
const hit = await pickPage(driver, pages, args.target).catch((err) => {
|
|
7301
7549
|
throw new LeaseToolError(`claim_page: no open tab matches target '${args.target}' (${err.message}). No tab was opened: claim_page never creates one when 'target' is given.`);
|
|
@@ -7315,6 +7563,7 @@ async function claimPage(driver, args = {}) {
|
|
|
7315
7563
|
targetId = page.id;
|
|
7316
7564
|
url = page.url;
|
|
7317
7565
|
opened = true;
|
|
7566
|
+
hidden = page.hidden === true;
|
|
7318
7567
|
}
|
|
7319
7568
|
const humanMs = opened ? null : await readHumanActiveMs(driver, backend, targetId);
|
|
7320
7569
|
const liveIds = [...pages.map((p) => p.id), targetId];
|
|
@@ -7333,6 +7582,7 @@ async function claimPage(driver, args = {}) {
|
|
|
7333
7582
|
ttlMs: record.ttlMs,
|
|
7334
7583
|
expiresAt: record.lastUsedAt + record.ttlMs,
|
|
7335
7584
|
opened,
|
|
7585
|
+
...hidden ? { hidden: true } : {},
|
|
7336
7586
|
...beaconSupported(driver) ? { humanActiveMs: humanMs } : {},
|
|
7337
7587
|
...contention !== undefined ? { contention } : {}
|
|
7338
7588
|
};
|
|
@@ -8040,6 +8290,7 @@ async function performanceAnalyzeInsight(args = {}) {
|
|
|
8040
8290
|
}
|
|
8041
8291
|
|
|
8042
8292
|
// src/tools/screencast.ts
|
|
8293
|
+
init_focusPolicy();
|
|
8043
8294
|
init_client();
|
|
8044
8295
|
import { spawn } from "node:child_process";
|
|
8045
8296
|
import { mkdir as mkdir8, rm as rm2, stat as stat2, writeFile as writeFile7 } from "node:fs/promises";
|
|
@@ -8340,7 +8591,7 @@ async function startScreenRecording(args = {}) {
|
|
|
8340
8591
|
});
|
|
8341
8592
|
try {
|
|
8342
8593
|
await conn.send("Page.enable");
|
|
8343
|
-
if (args.bringToFront)
|
|
8594
|
+
if (args.bringToFront && !focusDenied())
|
|
8344
8595
|
await conn.send("Page.bringToFront").catch(() => {});
|
|
8345
8596
|
const params = { format };
|
|
8346
8597
|
if (format === "jpeg" && args.quality !== undefined)
|
|
@@ -8986,11 +9237,302 @@ async function grantPermissions(args = {}) {
|
|
|
8986
9237
|
return { granted: [...permissions], origin, ...reset ? { reset: true } : {}, target };
|
|
8987
9238
|
}
|
|
8988
9239
|
|
|
8989
|
-
// src/tools/
|
|
9240
|
+
// src/tools/tab-groups.ts
|
|
8990
9241
|
init_client();
|
|
8991
|
-
import {
|
|
8992
|
-
import {
|
|
9242
|
+
import { createHash } from "node:crypto";
|
|
9243
|
+
import { mkdir as mkdir12, readFile as readFile9, writeFile as writeFile9 } from "node:fs/promises";
|
|
9244
|
+
import { join as join11 } from "node:path";
|
|
8993
9245
|
var ARTIFACT_DIR7 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
|
|
9246
|
+
var HELPER_DIR = join11(ARTIFACT_DIR7, "tab-groups-helper");
|
|
9247
|
+
var TAB_GROUP_COLORS = ["grey", "blue", "red", "yellow", "green", "pink", "purple", "cyan", "orange"];
|
|
9248
|
+
var HELPER_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqesYyi7LmBxzWP7VFJGlH2khinCz0uU2z3KNDvZ3Kb8gTLPpthgRWp27pu5/Wk2nvQJdcrunf6u5vqomH2xhvXIqjgXtth2o1GrE6oJMWRUqEoC7I4YUXdSieRpxAxtG37KiSFOyFOU59Som3gGOM2j1qlQIsID0QwRCeRs095SLoTtkA6YwZxtOETgvZAhbbpkmYwkXjTzgY85sS1JfMYj67cmfyz/Nt6yfORSJYEmWAfGCjQnvtOn9TjCazZvmoASUhsKZNZVWckAg+Md+ZKBPbl14/UUwLmWHQ7SDcJozHZtFeLFXySwvmBm3NhP1rK5vd/v+modsQY3M3DbqLQIDAQAB";
|
|
9249
|
+
var HELPER_MANIFEST = {
|
|
9250
|
+
manifest_version: 3,
|
|
9251
|
+
name: "cdp-toolkit tab groups",
|
|
9252
|
+
description: "Helper installed by cdp-toolkit's tab-group tools (list_tab_groups, group_tabs, ungroup_tabs). No UI, no state.",
|
|
9253
|
+
version: "1.0.0",
|
|
9254
|
+
key: HELPER_KEY,
|
|
9255
|
+
permissions: ["tabs", "tabGroups", "debugger"],
|
|
9256
|
+
background: { service_worker: "sw.js" }
|
|
9257
|
+
};
|
|
9258
|
+
function extensionIdFromKey(keyBase64) {
|
|
9259
|
+
const hex = createHash("sha256").update(Buffer.from(keyBase64, "base64")).digest("hex").slice(0, 32);
|
|
9260
|
+
return [...hex].map((c) => String.fromCharCode(97 + parseInt(c, 16))).join("");
|
|
9261
|
+
}
|
|
9262
|
+
var HELPER_EXTENSION_ID = extensionIdFromKey(HELPER_KEY);
|
|
9263
|
+
var HELPER_SW_BODY = String.raw`
|
|
9264
|
+
const NONE = -1;
|
|
9265
|
+
|
|
9266
|
+
async function targetIdsByTab() {
|
|
9267
|
+
const m = new Map();
|
|
9268
|
+
try {
|
|
9269
|
+
for (const t of await chrome.debugger.getTargets()) {
|
|
9270
|
+
if (t.type === "page" && typeof t.tabId === "number") m.set(t.tabId, t.id);
|
|
9271
|
+
}
|
|
9272
|
+
} catch (e) {
|
|
9273
|
+
// No mapping is a degraded answer (rows lack targetId), not a failure of the listing.
|
|
9274
|
+
}
|
|
9275
|
+
return m;
|
|
9276
|
+
}
|
|
9277
|
+
|
|
9278
|
+
function row(t, m) {
|
|
9279
|
+
return { tabId: t.id, targetId: m.get(t.id), index: t.index, url: t.url || t.pendingUrl || "", title: t.title || "" };
|
|
9280
|
+
}
|
|
9281
|
+
|
|
9282
|
+
const byPlace = (a, b) => a.windowId - b.windowId || a.index - b.index;
|
|
9283
|
+
|
|
9284
|
+
async function list(args) {
|
|
9285
|
+
const q = args && args.windowId !== undefined ? { windowId: args.windowId } : {};
|
|
9286
|
+
const [tabs, groups, m] = await Promise.all([chrome.tabs.query(q), chrome.tabGroups.query(q), targetIdsByTab()]);
|
|
9287
|
+
const wins = new Map();
|
|
9288
|
+
for (const t of tabs.slice().sort(byPlace)) {
|
|
9289
|
+
let w = wins.get(t.windowId);
|
|
9290
|
+
if (!w) wins.set(t.windowId, (w = { windowId: t.windowId, tabCount: 0, ungrouped: 0, groups: [] }));
|
|
9291
|
+
w.tabCount++;
|
|
9292
|
+
if (t.groupId === NONE || t.groupId === undefined) {
|
|
9293
|
+
w.ungrouped++;
|
|
9294
|
+
if (args && args.includeUngrouped) (w.ungroupedTabs || (w.ungroupedTabs = [])).push(row(t, m));
|
|
9295
|
+
continue;
|
|
9296
|
+
}
|
|
9297
|
+
let g = w.groups.find((x) => x.groupId === t.groupId);
|
|
9298
|
+
if (!g) {
|
|
9299
|
+
const info = groups.find((x) => x.id === t.groupId) || {};
|
|
9300
|
+
g = { groupId: t.groupId, title: info.title || "", color: info.color, collapsed: !!info.collapsed, tabs: [] };
|
|
9301
|
+
w.groups.push(g);
|
|
9302
|
+
}
|
|
9303
|
+
g.tabs.push(row(t, m));
|
|
9304
|
+
}
|
|
9305
|
+
const windows = [...wins.values()];
|
|
9306
|
+
return {
|
|
9307
|
+
windows,
|
|
9308
|
+
groupCount: windows.reduce((n, w) => n + w.groups.length, 0),
|
|
9309
|
+
tabCount: tabs.length,
|
|
9310
|
+
};
|
|
9311
|
+
}
|
|
9312
|
+
|
|
9313
|
+
async function selectTabs(args, m) {
|
|
9314
|
+
if (Array.isArray(args.tabIds)) {
|
|
9315
|
+
const out = [];
|
|
9316
|
+
for (const id of args.tabIds) {
|
|
9317
|
+
try { out.push(await chrome.tabs.get(id)); }
|
|
9318
|
+
catch (e) { throw new Error("no tab with tabId " + id + " (tab ids come from list_tab_groups)"); }
|
|
9319
|
+
}
|
|
9320
|
+
return out;
|
|
9321
|
+
}
|
|
9322
|
+
if (Array.isArray(args.targetIds)) {
|
|
9323
|
+
const byTarget = new Map([...m].map(([tabId, targetId]) => [targetId, tabId]));
|
|
9324
|
+
const out = [];
|
|
9325
|
+
for (const tid of args.targetIds) {
|
|
9326
|
+
const id = byTarget.get(tid);
|
|
9327
|
+
if (id === undefined) throw new Error("no tab with targetId " + tid + " (a page's CDP target id, as list_pages shows it)");
|
|
9328
|
+
out.push(await chrome.tabs.get(id));
|
|
9329
|
+
}
|
|
9330
|
+
return out;
|
|
9331
|
+
}
|
|
9332
|
+
const all = (await chrome.tabs.query({})).sort(byPlace);
|
|
9333
|
+
if (typeof args.urlMatch === "string") {
|
|
9334
|
+
const hit = all.filter((t) => (t.url || "").includes(args.urlMatch) || (t.pendingUrl || "").includes(args.urlMatch));
|
|
9335
|
+
if (!hit.length) throw new Error("urlMatch " + JSON.stringify(args.urlMatch) + " matched no tab");
|
|
9336
|
+
return hit;
|
|
9337
|
+
}
|
|
9338
|
+
if (typeof args.groupId === "number") {
|
|
9339
|
+
await chrome.tabGroups.get(args.groupId).catch(() => { throw new Error("no tab group with groupId " + args.groupId); });
|
|
9340
|
+
return all.filter((t) => t.groupId === args.groupId);
|
|
9341
|
+
}
|
|
9342
|
+
throw new Error("no tab selector given");
|
|
9343
|
+
}
|
|
9344
|
+
|
|
9345
|
+
async function group(args) {
|
|
9346
|
+
const m = await targetIdsByTab();
|
|
9347
|
+
const tabs = await selectTabs(args, m);
|
|
9348
|
+
let win;
|
|
9349
|
+
if (args.groupId !== undefined) {
|
|
9350
|
+
win = (await chrome.tabGroups.get(args.groupId).catch(() => { throw new Error("no tab group with groupId " + args.groupId); })).windowId;
|
|
9351
|
+
} else if (args.windowId !== undefined) {
|
|
9352
|
+
win = args.windowId;
|
|
9353
|
+
} else {
|
|
9354
|
+
const ws = [...new Set(tabs.map((t) => t.windowId))];
|
|
9355
|
+
if (ws.length > 1) {
|
|
9356
|
+
throw new Error(
|
|
9357
|
+
"the selected tabs are in " + ws.length + " windows (" + ws.join(", ") + "); pass windowId to name the window the group goes in " +
|
|
9358
|
+
"(tabs from other windows are moved there). Without it Chrome would move them all into the last-focused window.",
|
|
9359
|
+
);
|
|
9360
|
+
}
|
|
9361
|
+
win = ws[0];
|
|
9362
|
+
}
|
|
9363
|
+
const moved = tabs.filter((t) => t.windowId !== win).map((t) => ({ tabId: t.id, fromWindowId: t.windowId }));
|
|
9364
|
+
const opts = { tabIds: tabs.map((t) => t.id) };
|
|
9365
|
+
if (args.groupId !== undefined) opts.groupId = args.groupId;
|
|
9366
|
+
else opts.createProperties = { windowId: win };
|
|
9367
|
+
const gid = await chrome.tabs.group(opts);
|
|
9368
|
+
const upd = {};
|
|
9369
|
+
if (args.title !== undefined) upd.title = args.title;
|
|
9370
|
+
if (args.color !== undefined) upd.color = args.color;
|
|
9371
|
+
if (args.collapsed !== undefined) upd.collapsed = args.collapsed;
|
|
9372
|
+
const g = Object.keys(upd).length ? await chrome.tabGroups.update(gid, upd) : await chrome.tabGroups.get(gid);
|
|
9373
|
+
const members = g.windowId > 0 ? (await chrome.tabs.query({ windowId: g.windowId })).filter((t) => t.groupId === gid).sort(byPlace) : [];
|
|
9374
|
+
if (members.length === 0) {
|
|
9375
|
+
// Vivaldi answers chrome.tabs.group with an id but keeps its own tab stacks: the "group" has
|
|
9376
|
+
// windowId -1 and no tabs. Fail loudly rather than report a group that does not exist.
|
|
9377
|
+
throw new Error("the browser accepted chrome.tabs.group but created no visible group (windowId " + g.windowId + ", 0 tabs); this browser does not support Chrome tab groups (Vivaldi uses its own tab stacks)");
|
|
9378
|
+
}
|
|
9379
|
+
return { groupId: gid, windowId: g.windowId, title: g.title || "", color: g.color, collapsed: !!g.collapsed, tabs: members.map((t) => row(t, m)), moved };
|
|
9380
|
+
}
|
|
9381
|
+
|
|
9382
|
+
async function ungroup(args) {
|
|
9383
|
+
const m = await targetIdsByTab();
|
|
9384
|
+
const tabs = await selectTabs(args, m);
|
|
9385
|
+
const grouped = tabs.filter((t) => t.groupId !== NONE && t.groupId !== undefined);
|
|
9386
|
+
if (grouped.length) await chrome.tabs.ungroup(grouped.map((t) => t.id));
|
|
9387
|
+
return {
|
|
9388
|
+
ungrouped: grouped.map((t) => Object.assign(row(t, m), { fromGroupId: t.groupId })),
|
|
9389
|
+
alreadyUngrouped: tabs.filter((t) => !grouped.includes(t)).map((t) => t.id),
|
|
9390
|
+
};
|
|
9391
|
+
}
|
|
9392
|
+
|
|
9393
|
+
self.cdpToolkitTabGroups = { version: VERSION, list, group, ungroup };
|
|
9394
|
+
`;
|
|
9395
|
+
var HELPER_VERSION = createHash("sha256").update(HELPER_SW_BODY).digest("hex").slice(0, 12);
|
|
9396
|
+
var HELPER_SW_SOURCE = `"use strict";
|
|
9397
|
+
const VERSION = ${JSON.stringify(HELPER_VERSION)};
|
|
9398
|
+
${HELPER_SW_BODY}`;
|
|
9399
|
+
var isInt = (v) => typeof v === "number" && Number.isInteger(v);
|
|
9400
|
+
function checkInt(tool, name, v) {
|
|
9401
|
+
if (v !== undefined && !isInt(v))
|
|
9402
|
+
throw new Error(`${tool}: '${name}' must be an integer (got ${JSON.stringify(v)})`);
|
|
9403
|
+
}
|
|
9404
|
+
function checkSelector(tool, a, withGroupId) {
|
|
9405
|
+
const given = [
|
|
9406
|
+
a.tabIds !== undefined && "tabIds",
|
|
9407
|
+
a.targetIds !== undefined && "targetIds",
|
|
9408
|
+
typeof a.urlMatch === "string" && a.urlMatch !== "" && "urlMatch",
|
|
9409
|
+
withGroupId && a.groupId !== undefined && "groupId"
|
|
9410
|
+
].filter(Boolean);
|
|
9411
|
+
const names = withGroupId ? "tabIds, targetIds, urlMatch or groupId" : "tabIds, targetIds or urlMatch";
|
|
9412
|
+
if (given.length !== 1)
|
|
9413
|
+
throw new Error(`${tool}: give exactly one of ${names} (got ${given.length ? given.join(" + ") : "none"})`);
|
|
9414
|
+
if (a.tabIds !== undefined) {
|
|
9415
|
+
if (!Array.isArray(a.tabIds) || a.tabIds.length === 0 || !a.tabIds.every(isInt)) {
|
|
9416
|
+
throw new Error(`${tool}: 'tabIds' must be a non-empty array of integer chrome tab ids (got ${JSON.stringify(a.tabIds)})`);
|
|
9417
|
+
}
|
|
9418
|
+
}
|
|
9419
|
+
if (a.targetIds !== undefined) {
|
|
9420
|
+
if (!Array.isArray(a.targetIds) || a.targetIds.length === 0 || !a.targetIds.every((t) => typeof t === "string" && t !== "")) {
|
|
9421
|
+
throw new Error(`${tool}: 'targetIds' must be a non-empty array of CDP target id strings (got ${JSON.stringify(a.targetIds)})`);
|
|
9422
|
+
}
|
|
9423
|
+
}
|
|
9424
|
+
}
|
|
9425
|
+
function validateListTabGroupsArgs(a) {
|
|
9426
|
+
checkInt("list_tab_groups", "windowId", a.windowId);
|
|
9427
|
+
if (a.includeUngrouped !== undefined && typeof a.includeUngrouped !== "boolean") {
|
|
9428
|
+
throw new Error("list_tab_groups: 'includeUngrouped' must be a boolean");
|
|
9429
|
+
}
|
|
9430
|
+
}
|
|
9431
|
+
function validateGroupTabsArgs(a) {
|
|
9432
|
+
const tool = "group_tabs";
|
|
9433
|
+
checkSelector(tool, a, false);
|
|
9434
|
+
checkInt(tool, "groupId", a.groupId);
|
|
9435
|
+
checkInt(tool, "windowId", a.windowId);
|
|
9436
|
+
if (a.groupId !== undefined && a.windowId !== undefined) {
|
|
9437
|
+
throw new Error(`${tool}: give groupId (add to that group, in its window) or windowId (new group in that window), not both`);
|
|
9438
|
+
}
|
|
9439
|
+
if (a.title !== undefined && typeof a.title !== "string")
|
|
9440
|
+
throw new Error(`${tool}: 'title' must be a string`);
|
|
9441
|
+
if (a.collapsed !== undefined && typeof a.collapsed !== "boolean")
|
|
9442
|
+
throw new Error(`${tool}: 'collapsed' must be a boolean`);
|
|
9443
|
+
if (a.color !== undefined && !TAB_GROUP_COLORS.includes(a.color)) {
|
|
9444
|
+
throw new Error(`${tool}: 'color' must be one of ${TAB_GROUP_COLORS.join(", ")} (got ${JSON.stringify(a.color)})`);
|
|
9445
|
+
}
|
|
9446
|
+
}
|
|
9447
|
+
function validateUngroupTabsArgs(a) {
|
|
9448
|
+
checkSelector("ungroup_tabs", a, true);
|
|
9449
|
+
checkInt("ungroup_tabs", "groupId", a.groupId);
|
|
9450
|
+
}
|
|
9451
|
+
var SW_URL_PREFIX = `chrome-extension://${HELPER_EXTENSION_ID}/`;
|
|
9452
|
+
var WORKER_WAIT_MS = 5000;
|
|
9453
|
+
async function helperWorker() {
|
|
9454
|
+
return (await listTargets()).find((t) => t.type === "service_worker" && t.url.startsWith(SW_URL_PREFIX));
|
|
9455
|
+
}
|
|
9456
|
+
async function writeHelper() {
|
|
9457
|
+
await mkdir12(HELPER_DIR, { recursive: true });
|
|
9458
|
+
const files = {
|
|
9459
|
+
"manifest.json": JSON.stringify(HELPER_MANIFEST, null, 2),
|
|
9460
|
+
"sw.js": HELPER_SW_SOURCE
|
|
9461
|
+
};
|
|
9462
|
+
for (const [name, body] of Object.entries(files)) {
|
|
9463
|
+
const path = join11(HELPER_DIR, name);
|
|
9464
|
+
const current = await readFile9(path, "utf8").catch(() => {
|
|
9465
|
+
return;
|
|
9466
|
+
});
|
|
9467
|
+
if (current !== body)
|
|
9468
|
+
await writeFile9(path, body);
|
|
9469
|
+
}
|
|
9470
|
+
}
|
|
9471
|
+
async function evalIn(workerId, expression) {
|
|
9472
|
+
return withPage(workerId, async (conn) => {
|
|
9473
|
+
const r = await conn.send("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true });
|
|
9474
|
+
if (r.exceptionDetails) {
|
|
9475
|
+
const d = r.exceptionDetails.exception?.description ?? r.exceptionDetails.text ?? "error";
|
|
9476
|
+
throw new Error(d.split(`
|
|
9477
|
+
`)[0].replace(/^Error: /, ""));
|
|
9478
|
+
}
|
|
9479
|
+
return r.result?.value;
|
|
9480
|
+
});
|
|
9481
|
+
}
|
|
9482
|
+
async function currentHelperWorker() {
|
|
9483
|
+
const w = await helperWorker();
|
|
9484
|
+
if (!w)
|
|
9485
|
+
return;
|
|
9486
|
+
const v = await evalIn(w.id, "self.cdpToolkitTabGroups && self.cdpToolkitTabGroups.version").catch(() => {
|
|
9487
|
+
return;
|
|
9488
|
+
});
|
|
9489
|
+
return v === HELPER_VERSION ? w.id : undefined;
|
|
9490
|
+
}
|
|
9491
|
+
async function ensureHelper() {
|
|
9492
|
+
const existing = await currentHelperWorker();
|
|
9493
|
+
if (existing)
|
|
9494
|
+
return existing;
|
|
9495
|
+
await writeHelper();
|
|
9496
|
+
const conn = await openBrowser();
|
|
9497
|
+
try {
|
|
9498
|
+
await conn.send("Extensions.loadUnpacked", { path: HELPER_DIR });
|
|
9499
|
+
} catch (e) {
|
|
9500
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
9501
|
+
throw new CdpError(`tab-group tools could not install their helper extension (Extensions.loadUnpacked: ${msg}). ` + `They need a Chromium that allows loadUnpacked over CDP, with ${HELPER_DIR} on the browser's own machine.`);
|
|
9502
|
+
} finally {
|
|
9503
|
+
conn.close();
|
|
9504
|
+
}
|
|
9505
|
+
const deadline = Date.now() + WORKER_WAIT_MS;
|
|
9506
|
+
while (Date.now() < deadline) {
|
|
9507
|
+
const id = await currentHelperWorker();
|
|
9508
|
+
if (id)
|
|
9509
|
+
return id;
|
|
9510
|
+
await new Promise((r) => setTimeout(r, 100));
|
|
9511
|
+
}
|
|
9512
|
+
throw new CdpError(`the tab-groups helper extension installed but its service worker did not start within ${WORKER_WAIT_MS} ms`);
|
|
9513
|
+
}
|
|
9514
|
+
async function callHelper(op, args) {
|
|
9515
|
+
const id = await ensureHelper();
|
|
9516
|
+
return await evalIn(id, `self.cdpToolkitTabGroups.${op}(${JSON.stringify(args)})`);
|
|
9517
|
+
}
|
|
9518
|
+
async function listTabGroups(args = {}) {
|
|
9519
|
+
validateListTabGroupsArgs(args);
|
|
9520
|
+
return callHelper("list", { windowId: args.windowId, includeUngrouped: args.includeUngrouped });
|
|
9521
|
+
}
|
|
9522
|
+
async function groupTabs(args = {}) {
|
|
9523
|
+
validateGroupTabsArgs(args);
|
|
9524
|
+
return callHelper("group", args);
|
|
9525
|
+
}
|
|
9526
|
+
async function ungroupTabs(args = {}) {
|
|
9527
|
+
validateUngroupTabsArgs(args);
|
|
9528
|
+
return callHelper("ungroup", args);
|
|
9529
|
+
}
|
|
9530
|
+
|
|
9531
|
+
// src/tools/extract.ts
|
|
9532
|
+
init_client();
|
|
9533
|
+
import { mkdir as mkdir13, writeFile as writeFile10 } from "node:fs/promises";
|
|
9534
|
+
import { dirname as dirname3, join as join12 } from "node:path";
|
|
9535
|
+
var ARTIFACT_DIR8 = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit";
|
|
8994
9536
|
var DEFAULT_BASE_URL = "http://127.0.0.1:8090/v1";
|
|
8995
9537
|
var DEFAULT_MODEL = "schematron";
|
|
8996
9538
|
var DEFAULT_TIMEOUT_MS2 = 90000;
|
|
@@ -9390,10 +9932,10 @@ async function extractPage(driver, args) {
|
|
|
9390
9932
|
};
|
|
9391
9933
|
if (args.savePath === undefined || args.savePath === "")
|
|
9392
9934
|
return result;
|
|
9393
|
-
const path = args.savePath.startsWith("/") ? args.savePath :
|
|
9394
|
-
await
|
|
9935
|
+
const path = args.savePath.startsWith("/") ? args.savePath : join12(ARTIFACT_DIR8, args.savePath);
|
|
9936
|
+
await mkdir13(dirname3(path), { recursive: true });
|
|
9395
9937
|
const json = JSON.stringify(result, null, 2);
|
|
9396
|
-
await
|
|
9938
|
+
await writeFile10(path, json, "utf8");
|
|
9397
9939
|
const saved = {
|
|
9398
9940
|
path,
|
|
9399
9941
|
bytes: Buffer.byteLength(json, "utf8"),
|
|
@@ -9456,6 +9998,9 @@ var TOOLS = {
|
|
|
9456
9998
|
click_focus_gated: clickFocusGated,
|
|
9457
9999
|
wait_for_download: waitForDownload,
|
|
9458
10000
|
grant_permissions: grantPermissions,
|
|
10001
|
+
list_tab_groups: listTabGroups,
|
|
10002
|
+
group_tabs: groupTabs,
|
|
10003
|
+
ungroup_tabs: ungroupTabs,
|
|
9459
10004
|
extract_page: onCdp(extractPage),
|
|
9460
10005
|
claim_page: onCdp(LEASE_TOOLS.claim_page),
|
|
9461
10006
|
release_page: onCdp(LEASE_TOOLS.release_page),
|
|
@@ -9471,7 +10016,7 @@ import { spawn as spawn4 } from "node:child_process";
|
|
|
9471
10016
|
import { existsSync as existsSync2, mkdtempSync, readFileSync as readFileSync2, rmSync, writeFileSync } from "node:fs";
|
|
9472
10017
|
import { createConnection, createServer as createServer2 } from "node:net";
|
|
9473
10018
|
import { tmpdir } from "node:os";
|
|
9474
|
-
import { join as
|
|
10019
|
+
import { join as join14 } from "node:path";
|
|
9475
10020
|
function resolveBinary() {
|
|
9476
10021
|
const candidates = [
|
|
9477
10022
|
process.env.FIREFOX_BIN,
|
|
@@ -9551,7 +10096,7 @@ var LAUNCH_USER_JS_PREFS = {
|
|
|
9551
10096
|
"dom.file.createInChild": true
|
|
9552
10097
|
};
|
|
9553
10098
|
function writeLaunchUserJs(profilePath) {
|
|
9554
|
-
const target =
|
|
10099
|
+
const target = join14(profilePath, "user.js");
|
|
9555
10100
|
const existing = existsSync2(target) ? readFileSync2(target, "utf8") : "";
|
|
9556
10101
|
const present = new Set;
|
|
9557
10102
|
for (const line of existing.split(`
|
|
@@ -9573,7 +10118,7 @@ async function launchFirefox(opts = {}) {
|
|
|
9573
10118
|
const binary = resolveBinary();
|
|
9574
10119
|
const port = await pickPort(opts.port);
|
|
9575
10120
|
const isThrowaway = opts.profilePath === undefined;
|
|
9576
|
-
const profilePath = opts.profilePath ?? mkdtempSync(
|
|
10121
|
+
const profilePath = opts.profilePath ?? mkdtempSync(join14(tmpdir(), "cdp-toolkit-ff-profile-"));
|
|
9577
10122
|
if (isThrowaway)
|
|
9578
10123
|
writeLaunchUserJs(profilePath);
|
|
9579
10124
|
const args = ["--profile", profilePath, "--remote-debugging-port", String(port), "--no-remote"];
|
|
@@ -9943,8 +10488,8 @@ var BIDI_ONLY_TOOLS = {
|
|
|
9943
10488
|
|
|
9944
10489
|
// src/bidi-browser-tools.ts
|
|
9945
10490
|
init_driver2();
|
|
9946
|
-
import { mkdir as
|
|
9947
|
-
import { basename as basename2, dirname as dirname4, join as
|
|
10491
|
+
import { mkdir as mkdir15, readdir as readdir4, realpath, rename as rename4, stat as stat5 } from "node:fs/promises";
|
|
10492
|
+
import { basename as basename2, dirname as dirname4, join as join15, resolve } from "node:path";
|
|
9948
10493
|
function unsupported(message) {
|
|
9949
10494
|
return Object.assign(new Error(message), { code: "unsupported" });
|
|
9950
10495
|
}
|
|
@@ -9963,7 +10508,7 @@ async function targetOf(driver, target) {
|
|
|
9963
10508
|
await page.release();
|
|
9964
10509
|
}
|
|
9965
10510
|
}
|
|
9966
|
-
var FIREFOX_DOWNLOAD_STAGING_DIR =
|
|
10511
|
+
var FIREFOX_DOWNLOAD_STAGING_DIR = join15(dirname4(DOWNLOADS_DIR), "downloads-firefox-staging");
|
|
9967
10512
|
var downloadStates = new WeakMap;
|
|
9968
10513
|
function downloadId(p) {
|
|
9969
10514
|
const v = p.download ?? p.navigation;
|
|
@@ -10007,7 +10552,7 @@ function downloadStateFor(conn) {
|
|
|
10007
10552
|
if (!state.stagingDirs.has(resolve(dirname4(p.filepath))))
|
|
10008
10553
|
return;
|
|
10009
10554
|
rec.url ??= p.url;
|
|
10010
|
-
const held =
|
|
10555
|
+
const held = join15(dirname4(p.filepath), `${id.replace(/[^A-Za-z0-9-]/g, "_")}.download`);
|
|
10011
10556
|
rename4(p.filepath, held).then(() => {
|
|
10012
10557
|
rec.filePath = held;
|
|
10013
10558
|
}, () => {
|
|
@@ -10017,8 +10562,8 @@ function downloadStateFor(conn) {
|
|
|
10017
10562
|
return state;
|
|
10018
10563
|
}
|
|
10019
10564
|
async function armFirefoxDownloads(conn, s, scope) {
|
|
10020
|
-
await
|
|
10021
|
-
await
|
|
10565
|
+
await mkdir15(FIREFOX_DOWNLOAD_STAGING_DIR, { recursive: true });
|
|
10566
|
+
await mkdir15(DOWNLOADS_DIR, { recursive: true });
|
|
10022
10567
|
s.stagingDirs.add(resolve(await realpath(FIREFOX_DOWNLOAD_STAGING_DIR)));
|
|
10023
10568
|
scope.setDisposeHook("browser.downloads", async (c) => {
|
|
10024
10569
|
await c.send("browser.setDownloadBehavior", { downloadBehavior: null });
|
|
@@ -10076,7 +10621,7 @@ async function waitForDownloadFirefox(driver, args = {}) {
|
|
|
10076
10621
|
const taken = new Set(await readdir4(DOWNLOADS_DIR).catch(() => []));
|
|
10077
10622
|
taken.delete(basename2(rec.filePath));
|
|
10078
10623
|
const finalName = nextFreeName(suggestedFilename, taken);
|
|
10079
|
-
const path =
|
|
10624
|
+
const path = join15(DOWNLOADS_DIR, finalName);
|
|
10080
10625
|
await rename4(rec.filePath, path);
|
|
10081
10626
|
const bytes = (await stat5(path)).size;
|
|
10082
10627
|
return { path, suggestedFilename, bytes, ...rec.url ? { url: rec.url } : {}, target };
|
|
@@ -10976,6 +11521,130 @@ var MANIFEST = [
|
|
|
10976
11521
|
additionalProperties: false
|
|
10977
11522
|
}
|
|
10978
11523
|
},
|
|
11524
|
+
{
|
|
11525
|
+
name: "list_tab_groups",
|
|
11526
|
+
description: "List tab groups per window with member tabs (Chrome only, via a helper extension).",
|
|
11527
|
+
inputSchema: {
|
|
11528
|
+
type: "object",
|
|
11529
|
+
properties: {
|
|
11530
|
+
endpoint: {
|
|
11531
|
+
type: "string",
|
|
11532
|
+
description: "Named CDP endpoint (CDP_ENDPOINTS); default endpoint when omitted."
|
|
11533
|
+
},
|
|
11534
|
+
windowId: {
|
|
11535
|
+
type: "integer",
|
|
11536
|
+
description: "Only this window."
|
|
11537
|
+
},
|
|
11538
|
+
includeUngrouped: {
|
|
11539
|
+
type: "boolean",
|
|
11540
|
+
description: "Also list ungrouped tabs per window."
|
|
11541
|
+
}
|
|
11542
|
+
},
|
|
11543
|
+
required: [],
|
|
11544
|
+
additionalProperties: false
|
|
11545
|
+
}
|
|
11546
|
+
},
|
|
11547
|
+
{
|
|
11548
|
+
name: "group_tabs",
|
|
11549
|
+
description: "Group tabs (new or existing group) and set title/color/collapsed (Chrome only).",
|
|
11550
|
+
inputSchema: {
|
|
11551
|
+
type: "object",
|
|
11552
|
+
properties: {
|
|
11553
|
+
endpoint: {
|
|
11554
|
+
type: "string",
|
|
11555
|
+
description: "Named CDP endpoint (CDP_ENDPOINTS); default endpoint when omitted."
|
|
11556
|
+
},
|
|
11557
|
+
tabIds: {
|
|
11558
|
+
type: "array",
|
|
11559
|
+
items: {
|
|
11560
|
+
type: "integer"
|
|
11561
|
+
},
|
|
11562
|
+
description: "Chrome tab ids (from list_tab_groups)."
|
|
11563
|
+
},
|
|
11564
|
+
targetIds: {
|
|
11565
|
+
type: "array",
|
|
11566
|
+
items: {
|
|
11567
|
+
type: "string"
|
|
11568
|
+
},
|
|
11569
|
+
description: "CDP target ids (list_pages ids)."
|
|
11570
|
+
},
|
|
11571
|
+
urlMatch: {
|
|
11572
|
+
type: "string",
|
|
11573
|
+
description: "URL substring; matches tabs in every window."
|
|
11574
|
+
},
|
|
11575
|
+
title: {
|
|
11576
|
+
type: "string",
|
|
11577
|
+
description: "Group title."
|
|
11578
|
+
},
|
|
11579
|
+
color: {
|
|
11580
|
+
type: "string",
|
|
11581
|
+
enum: [
|
|
11582
|
+
"grey",
|
|
11583
|
+
"blue",
|
|
11584
|
+
"red",
|
|
11585
|
+
"yellow",
|
|
11586
|
+
"green",
|
|
11587
|
+
"pink",
|
|
11588
|
+
"purple",
|
|
11589
|
+
"cyan",
|
|
11590
|
+
"orange"
|
|
11591
|
+
],
|
|
11592
|
+
description: "Group color."
|
|
11593
|
+
},
|
|
11594
|
+
collapsed: {
|
|
11595
|
+
type: "boolean",
|
|
11596
|
+
description: "Collapse the group."
|
|
11597
|
+
},
|
|
11598
|
+
groupId: {
|
|
11599
|
+
type: "integer",
|
|
11600
|
+
description: "Add to this existing group."
|
|
11601
|
+
},
|
|
11602
|
+
windowId: {
|
|
11603
|
+
type: "integer",
|
|
11604
|
+
description: "Window for the new group; tabs elsewhere move there."
|
|
11605
|
+
}
|
|
11606
|
+
},
|
|
11607
|
+
required: [],
|
|
11608
|
+
additionalProperties: false
|
|
11609
|
+
}
|
|
11610
|
+
},
|
|
11611
|
+
{
|
|
11612
|
+
name: "ungroup_tabs",
|
|
11613
|
+
description: "Remove tabs from their tab groups (Chrome only).",
|
|
11614
|
+
inputSchema: {
|
|
11615
|
+
type: "object",
|
|
11616
|
+
properties: {
|
|
11617
|
+
endpoint: {
|
|
11618
|
+
type: "string",
|
|
11619
|
+
description: "Named CDP endpoint (CDP_ENDPOINTS); default endpoint when omitted."
|
|
11620
|
+
},
|
|
11621
|
+
tabIds: {
|
|
11622
|
+
type: "array",
|
|
11623
|
+
items: {
|
|
11624
|
+
type: "integer"
|
|
11625
|
+
},
|
|
11626
|
+
description: "Chrome tab ids (from list_tab_groups)."
|
|
11627
|
+
},
|
|
11628
|
+
targetIds: {
|
|
11629
|
+
type: "array",
|
|
11630
|
+
items: {
|
|
11631
|
+
type: "string"
|
|
11632
|
+
},
|
|
11633
|
+
description: "CDP target ids (list_pages ids)."
|
|
11634
|
+
},
|
|
11635
|
+
urlMatch: {
|
|
11636
|
+
type: "string",
|
|
11637
|
+
description: "URL substring; matches tabs in every window."
|
|
11638
|
+
},
|
|
11639
|
+
groupId: {
|
|
11640
|
+
type: "integer",
|
|
11641
|
+
description: "Ungroup every tab of this group."
|
|
11642
|
+
}
|
|
11643
|
+
},
|
|
11644
|
+
required: [],
|
|
11645
|
+
additionalProperties: false
|
|
11646
|
+
}
|
|
11647
|
+
},
|
|
10979
11648
|
{
|
|
10980
11649
|
name: "fill",
|
|
10981
11650
|
description: "Replace an element contents; provide exactly one of UID or selector.",
|
|
@@ -12071,6 +12740,9 @@ var MUTATING_TOOLS = new Set([
|
|
|
12071
12740
|
"click_focus_gated",
|
|
12072
12741
|
"wait_for_download",
|
|
12073
12742
|
"grant_permissions",
|
|
12743
|
+
"list_tab_groups",
|
|
12744
|
+
"group_tabs",
|
|
12745
|
+
"ungroup_tabs",
|
|
12074
12746
|
"claim_page",
|
|
12075
12747
|
"release_page"
|
|
12076
12748
|
]);
|
|
@@ -12120,13 +12792,13 @@ function toolAnnotations(name) {
|
|
|
12120
12792
|
// src/install/wizard.ts
|
|
12121
12793
|
import { createInterface } from "node:readline";
|
|
12122
12794
|
import { homedir as homedir3 } from "node:os";
|
|
12123
|
-
import { join as
|
|
12795
|
+
import { join as join18 } from "node:path";
|
|
12124
12796
|
|
|
12125
12797
|
// src/install/browser.ts
|
|
12126
12798
|
import { existsSync as existsSync3 } from "node:fs";
|
|
12127
|
-
import { mkdir as
|
|
12799
|
+
import { mkdir as mkdir16, readFile as readFile11, writeFile as writeFile12 } from "node:fs/promises";
|
|
12128
12800
|
import { homedir } from "node:os";
|
|
12129
|
-
import { delimiter, dirname as dirname5, join as
|
|
12801
|
+
import { delimiter, dirname as dirname5, join as join16 } from "node:path";
|
|
12130
12802
|
var CANDIDATE_BUILDERS = {
|
|
12131
12803
|
chrome: () => [
|
|
12132
12804
|
process.env.CHROME_BIN,
|
|
@@ -12156,7 +12828,7 @@ function existsOnPath(cmd) {
|
|
|
12156
12828
|
for (const dir of pathEnv.split(delimiter)) {
|
|
12157
12829
|
if (!dir)
|
|
12158
12830
|
continue;
|
|
12159
|
-
if (existsSync3(
|
|
12831
|
+
if (existsSync3(join16(dir, cmd)))
|
|
12160
12832
|
return true;
|
|
12161
12833
|
}
|
|
12162
12834
|
return false;
|
|
@@ -12206,10 +12878,10 @@ function aliasLine(o) {
|
|
|
12206
12878
|
function detectShellRc() {
|
|
12207
12879
|
const shell = process.env.SHELL ?? "";
|
|
12208
12880
|
if (shell.endsWith("zsh"))
|
|
12209
|
-
return
|
|
12881
|
+
return join16(homedir(), ".zshrc");
|
|
12210
12882
|
if (shell.endsWith("bash"))
|
|
12211
|
-
return
|
|
12212
|
-
return
|
|
12883
|
+
return join16(homedir(), ".bashrc");
|
|
12884
|
+
return join16(homedir(), process.platform === "darwin" ? ".zshrc" : ".bashrc");
|
|
12213
12885
|
}
|
|
12214
12886
|
var MARKER_START = "# >>> cdp-toolkit alias >>>";
|
|
12215
12887
|
var MARKER_END = "# <<< cdp-toolkit alias <<<";
|
|
@@ -12221,7 +12893,7 @@ function ensureTrailingNewline(s) {
|
|
|
12221
12893
|
async function appendAliasToRc(rcPath, aliasBlockBody) {
|
|
12222
12894
|
let existing = "";
|
|
12223
12895
|
try {
|
|
12224
|
-
existing = await
|
|
12896
|
+
existing = await readFile11(rcPath, "utf8");
|
|
12225
12897
|
} catch (err) {
|
|
12226
12898
|
if (err.code !== "ENOENT")
|
|
12227
12899
|
throw err;
|
|
@@ -12242,24 +12914,24 @@ ${MARKER_END}`;
|
|
|
12242
12914
|
}
|
|
12243
12915
|
const next = ensureTrailingNewline(`${before}${block}
|
|
12244
12916
|
${after}`);
|
|
12245
|
-
await
|
|
12917
|
+
await writeFile12(rcPath, next, "utf8");
|
|
12246
12918
|
return { rcPath, action: "replaced-block" };
|
|
12247
12919
|
}
|
|
12248
|
-
await
|
|
12920
|
+
await mkdir16(dirname5(rcPath), { recursive: true });
|
|
12249
12921
|
const sep = existing.length === 0 || existing.endsWith(`
|
|
12250
12922
|
`) ? "" : `
|
|
12251
12923
|
`;
|
|
12252
12924
|
const next = `${existing}${sep}${block}
|
|
12253
12925
|
`;
|
|
12254
|
-
await
|
|
12926
|
+
await writeFile12(rcPath, next, "utf8");
|
|
12255
12927
|
return { rcPath, action: "created-block" };
|
|
12256
12928
|
}
|
|
12257
12929
|
|
|
12258
12930
|
// src/install/harness.ts
|
|
12259
12931
|
import { spawnSync } from "node:child_process";
|
|
12260
|
-
import { mkdir as
|
|
12932
|
+
import { mkdir as mkdir17, readFile as readFile12, writeFile as writeFile13 } from "node:fs/promises";
|
|
12261
12933
|
import { homedir as homedir2 } from "node:os";
|
|
12262
|
-
import { dirname as dirname6, join as
|
|
12934
|
+
import { dirname as dirname6, join as join17 } from "node:path";
|
|
12263
12935
|
async function installMcpServer(harness, name, cfg, opts = {}) {
|
|
12264
12936
|
switch (harness) {
|
|
12265
12937
|
case "claude":
|
|
@@ -12275,11 +12947,11 @@ async function installMcpServer(harness, name, cfg, opts = {}) {
|
|
|
12275
12947
|
}
|
|
12276
12948
|
}
|
|
12277
12949
|
async function installClaude(name, cfg, opts) {
|
|
12278
|
-
const path = opts.configPath ??
|
|
12950
|
+
const path = opts.configPath ?? join17(opts.homeDir ?? homedir2(), ".claude.json");
|
|
12279
12951
|
let root;
|
|
12280
12952
|
let fileExisted;
|
|
12281
12953
|
try {
|
|
12282
|
-
const text = await
|
|
12954
|
+
const text = await readFile12(path, "utf8");
|
|
12283
12955
|
const parsed = JSON.parse(text);
|
|
12284
12956
|
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
12285
12957
|
throw new Error(`${path} does not contain a JSON object at its top level`);
|
|
@@ -12306,8 +12978,8 @@ async function installClaude(name, cfg, opts) {
|
|
|
12306
12978
|
if (action === "unchanged") {
|
|
12307
12979
|
return { harness: "claude", method: "file", path, action, detail: "no change needed" };
|
|
12308
12980
|
}
|
|
12309
|
-
await
|
|
12310
|
-
await
|
|
12981
|
+
await mkdir17(dirname6(path), { recursive: true });
|
|
12982
|
+
await writeFile13(path, JSON.stringify(root, null, 2) + `
|
|
12311
12983
|
`, "utf8");
|
|
12312
12984
|
return {
|
|
12313
12985
|
harness: "claude",
|
|
@@ -12543,7 +13215,7 @@ async function promptPort(def) {
|
|
|
12543
13215
|
}
|
|
12544
13216
|
function harnessTargetDesc(harness, io) {
|
|
12545
13217
|
if (harness === "claude") {
|
|
12546
|
-
return io.configPath ??
|
|
13218
|
+
return io.configPath ?? join18(io.homeDir ?? homedir3(), ".claude.json");
|
|
12547
13219
|
}
|
|
12548
13220
|
return `via \`${harness} mcp add\``;
|
|
12549
13221
|
}
|