dsh-browser-cdp 1.7.11 → 1.9.6
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.de.md +350 -0
- package/CHANGELOG.es.md +350 -0
- package/CHANGELOG.fr.md +350 -0
- package/CHANGELOG.it.md +350 -0
- package/CHANGELOG.md +966 -0
- package/CHANGELOG.ru.md +350 -0
- package/README.md +56 -19
- package/bin/cdp-cast-worker.mjs +223 -2
- package/bin/cdp-render-worker.mjs +57 -4
- package/dsh-plugin.json +2 -2
- package/lib/client.js +936 -36
- package/lib/index.js +1747 -386
- package/locale/de.json +6 -0
- package/locale/en.json +6 -0
- package/locale/es.json +6 -0
- package/locale/fr.json +6 -0
- package/locale/it.json +6 -0
- package/locale/ja.json +6 -0
- package/locale/ko.json +6 -0
- package/locale/ru.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +26 -12
- package/runtime/ego-linux/src/chrome.mjs +66 -6
- package/runtime/ego-linux/src/paths.mjs +14 -6
package/lib/index.js
CHANGED
|
@@ -10,8 +10,8 @@ import { execFile, spawn } from "node:child_process";
|
|
|
10
10
|
import { promisify } from "node:util";
|
|
11
11
|
import { request } from "node:http";
|
|
12
12
|
import { isIP } from "node:net";
|
|
13
|
-
import z from "@deepseek-ai/schemastery";
|
|
14
13
|
import { createHash, randomUUID } from "node:crypto";
|
|
14
|
+
import z from "@deepseek-ai/schemastery";
|
|
15
15
|
import { pipeline } from "node:stream/promises";
|
|
16
16
|
import { createGunzip } from "node:zlib";
|
|
17
17
|
|
|
@@ -1971,42 +1971,82 @@ function markEgoToolCall(sessionId) {
|
|
|
1971
1971
|
sseClients.delete(res);
|
|
1972
1972
|
}
|
|
1973
1973
|
}
|
|
1974
|
-
|
|
1975
|
-
|
|
1976
|
-
|
|
1977
|
-
|
|
1978
|
-
|
|
1979
|
-
|
|
1980
|
-
|
|
1981
|
-
|
|
1982
|
-
|
|
1983
|
-
|
|
1984
|
-
*
|
|
1985
|
-
|
|
1986
|
-
|
|
1974
|
+
function broadcastCliFrame(frame, spaces) {
|
|
1975
|
+
broadcastCliFrames([{
|
|
1976
|
+
targetId: frame.targetId ?? "",
|
|
1977
|
+
png: frame.png,
|
|
1978
|
+
fmt: frame.fmt,
|
|
1979
|
+
url: frame.url,
|
|
1980
|
+
title: frame.title
|
|
1981
|
+
}], spaces, frame.updatedAt);
|
|
1982
|
+
}
|
|
1983
|
+
/**
|
|
1984
|
+
* Push one capture CYCLE into the live stream: 全模式 sends one image per tab,
|
|
1985
|
+
* 仅激活 sends exactly one. Every image is its own `frame` event keyed by
|
|
1986
|
+
* `targetId`, so the client caches a picture per tab and the strip can show the
|
|
1987
|
+
* right one when the user switches — the active tab's image is the one the
|
|
1988
|
+
* panel outlines.
|
|
1989
|
+
*/
|
|
1990
|
+
function broadcastCliFrames(images, spaces, at) {
|
|
1991
|
+
if (images.length === 0) return;
|
|
1992
|
+
const stamp = at ?? Date.now();
|
|
1993
|
+
lastCliFrames = images;
|
|
1994
|
+
lastCliFrameAt = stamp;
|
|
1995
|
+
lastCliSpaces = spaces && spaces.length > 0 ? spaces : null;
|
|
1996
|
+
writeCliImages(images, stamp);
|
|
1997
|
+
}
|
|
1998
|
+
/** Tab inventory supplied by the newest frame broadcast (null = synthetic row). */
|
|
1999
|
+
let lastCliSpaces = null;
|
|
2000
|
+
/** Newest capture cycle, replayed by the 1s hold timer in initCastServer. */
|
|
2001
|
+
let lastCliFrames = null;
|
|
2002
|
+
/** Wall-clock of the last broadcast/replay; the hold timer only fills >1s gaps. */
|
|
2003
|
+
let lastCliFrameAt = 0;
|
|
2004
|
+
/** Push one capture cycle to every SSE client. `includeSpaces` also re-emits the
|
|
2005
|
+
* spaces list (real captures do; the 1s hold replay only refreshes the images
|
|
2006
|
+
* to avoid churning the client's store/render every second). */
|
|
2007
|
+
function writeCliImages(images, at, includeSpaces = true) {
|
|
1987
2008
|
if (sseClients.size === 0) return;
|
|
1988
|
-
const
|
|
2009
|
+
const first = images[0];
|
|
2010
|
+
const rows = lastCliSpaces ?? [{
|
|
1989
2011
|
targetId: CLI_FRAME_TARGET_ID,
|
|
1990
|
-
url:
|
|
1991
|
-
title:
|
|
2012
|
+
url: first.url ?? "",
|
|
2013
|
+
title: first.title ?? "",
|
|
1992
2014
|
active: true,
|
|
1993
|
-
lastActive:
|
|
2015
|
+
lastActive: at
|
|
1994
2016
|
}];
|
|
1995
|
-
const spacesFrame = `event: spaces\ndata: ${JSON.stringify(
|
|
1996
|
-
const
|
|
1997
|
-
|
|
1998
|
-
|
|
1999
|
-
|
|
2000
|
-
|
|
2001
|
-
|
|
2002
|
-
|
|
2017
|
+
const spacesFrame = `event: spaces\ndata: ${JSON.stringify(rows)}\n\n`;
|
|
2018
|
+
const activeRow = rows.find((row) => row.active) ?? rows[0];
|
|
2019
|
+
const events = [];
|
|
2020
|
+
for (const image of images) {
|
|
2021
|
+
const targetId = image.targetId || activeRow?.targetId || CLI_FRAME_TARGET_ID;
|
|
2022
|
+
events.push(`event: frame\ndata: ${JSON.stringify({
|
|
2023
|
+
targetId,
|
|
2024
|
+
data: image.png.toString("base64"),
|
|
2025
|
+
fmt: image.fmt ?? "png",
|
|
2026
|
+
ts: at
|
|
2027
|
+
})}\n\n`);
|
|
2028
|
+
}
|
|
2003
2029
|
for (const res of sseClients) try {
|
|
2004
|
-
res.write(spacesFrame);
|
|
2005
|
-
res.write(
|
|
2030
|
+
if (includeSpaces) res.write(spacesFrame);
|
|
2031
|
+
for (const event of events) res.write(event);
|
|
2006
2032
|
} catch {
|
|
2007
2033
|
sseClients.delete(res);
|
|
2008
2034
|
}
|
|
2009
2035
|
}
|
|
2036
|
+
/** 全模式 session override: null = follow the persisted `tabTracking` setting. */
|
|
2037
|
+
let cliTrackOverride = null;
|
|
2038
|
+
/** @internal effective tracking mode (panel toggle first, then the setting). */
|
|
2039
|
+
function getCliTrackAll(fallback) {
|
|
2040
|
+
return cliTrackOverride === null ? fallback === true : cliTrackOverride;
|
|
2041
|
+
}
|
|
2042
|
+
/** @internal */
|
|
2043
|
+
function setCliTrackAll(next) {
|
|
2044
|
+
cliTrackOverride = typeof next === "boolean" ? next : null;
|
|
2045
|
+
}
|
|
2046
|
+
/** @internal drop the session override so the saved setting wins again. */
|
|
2047
|
+
function clearCliTrackOverride() {
|
|
2048
|
+
cliTrackOverride = null;
|
|
2049
|
+
}
|
|
2010
2050
|
function castStatePath() {
|
|
2011
2051
|
const e = process.env;
|
|
2012
2052
|
const isWin = process.platform === "win32";
|
|
@@ -2379,10 +2419,18 @@ function initCastServer(ctx, cfg, bridge, ffmpegManager, openAgentWindow$1 = asy
|
|
|
2379
2419
|
}), loginImport = async () => ({
|
|
2380
2420
|
ok: false,
|
|
2381
2421
|
error: "login import not supported by this host build"
|
|
2382
|
-
}), cliPoller = null) {
|
|
2422
|
+
}), cliPoller = null, panelActions = null, tabbitSpaces = null) {
|
|
2383
2423
|
const ensureWorker = makeEnsureWorker(ctx, cfg, ffmpegManager);
|
|
2384
2424
|
const pushConfig = makePushConfig(ensureWorker, ffmpegManager);
|
|
2385
2425
|
activeCliPoller = cliPoller;
|
|
2426
|
+
const activeLinkInfo = () => {
|
|
2427
|
+
const eff = resolveEffectiveLink(cfg.links, cfg.activeTargetId);
|
|
2428
|
+
return {
|
|
2429
|
+
kind: eff?.link.kind ?? "",
|
|
2430
|
+
label: (eff?.link)?.label ?? "",
|
|
2431
|
+
engine: getAttachEngine()
|
|
2432
|
+
};
|
|
2433
|
+
};
|
|
2386
2434
|
const rawServer = ctx.get?.("webServer");
|
|
2387
2435
|
if (!rawServer || typeof rawServer.register !== "function") return;
|
|
2388
2436
|
const isTrustedRequest = (req) => /(?:^|;\s*)dsh-auth-[^=]+=/.test(String(req.headers.cookie ?? ""));
|
|
@@ -2403,6 +2451,7 @@ function initCastServer(ctx, cfg, bridge, ffmpegManager, openAgentWindow$1 = asy
|
|
|
2403
2451
|
}) });
|
|
2404
2452
|
if (typeof bridge?.onChange === "function") {
|
|
2405
2453
|
const off = bridge.onChange(() => {
|
|
2454
|
+
clearCliTrackOverride();
|
|
2406
2455
|
pushConfig(cfg);
|
|
2407
2456
|
});
|
|
2408
2457
|
if (typeof off === "function") ctx.effect?.(() => () => {
|
|
@@ -2419,23 +2468,44 @@ function initCastServer(ctx, cfg, bridge, ffmpegManager, openAgentWindow$1 = asy
|
|
|
2419
2468
|
const port = await ensureWorker();
|
|
2420
2469
|
if (port === null) {
|
|
2421
2470
|
const cliFrame = cliPoller && cliPoller.isRunning() ? cliPoller.getFrame() : null;
|
|
2422
|
-
if (cliFrame)
|
|
2423
|
-
|
|
2424
|
-
|
|
2425
|
-
|
|
2426
|
-
|
|
2427
|
-
|
|
2471
|
+
if (cliFrame) {
|
|
2472
|
+
const frameTabs = Array.isArray(cliFrame.tabs) ? cliFrame.tabs : [];
|
|
2473
|
+
const rows = frameTabs.length > 0 ? frameTabs.map((t) => ({
|
|
2474
|
+
targetId: t.targetId,
|
|
2475
|
+
url: t.url,
|
|
2476
|
+
title: t.title,
|
|
2477
|
+
active: t.active,
|
|
2478
|
+
lastActive: cliFrame.updatedAt
|
|
2479
|
+
})) : [{
|
|
2428
2480
|
targetId: CLI_FRAME_TARGET_ID,
|
|
2429
2481
|
url: cliFrame.url,
|
|
2430
2482
|
title: cliFrame.title,
|
|
2431
2483
|
active: true,
|
|
2432
2484
|
lastActive: cliFrame.updatedAt
|
|
2433
|
-
}]
|
|
2485
|
+
}];
|
|
2486
|
+
return sendJson(res, 200, {
|
|
2487
|
+
ok: true,
|
|
2488
|
+
toolCallCount,
|
|
2489
|
+
cliFrameMode: true,
|
|
2490
|
+
cliFrameIntervalMs: 3e3,
|
|
2491
|
+
cliFrameTargetId: cliFrame.targetId || CLI_FRAME_TARGET_ID,
|
|
2492
|
+
link: activeLinkInfo(),
|
|
2493
|
+
spaces: rows
|
|
2494
|
+
});
|
|
2495
|
+
}
|
|
2496
|
+
const tb = tabbitSpaces?.();
|
|
2497
|
+
if (tb && tb.tabs.length > 0 && Date.now() - tb.updatedAt < 2e4) return sendJson(res, 200, {
|
|
2498
|
+
ok: true,
|
|
2499
|
+
backend: "tabbit-cli",
|
|
2500
|
+
toolCallCount,
|
|
2501
|
+
link: activeLinkInfo(),
|
|
2502
|
+
spaces: tb.tabs
|
|
2434
2503
|
});
|
|
2435
2504
|
return sendJson(res, 200, {
|
|
2436
2505
|
ok: false,
|
|
2437
2506
|
spaces: [],
|
|
2438
2507
|
toolCallCount,
|
|
2508
|
+
link: activeLinkInfo(),
|
|
2439
2509
|
reason: "no live agent browser"
|
|
2440
2510
|
});
|
|
2441
2511
|
}
|
|
@@ -2444,10 +2514,12 @@ function initCastServer(ctx, cfg, bridge, ffmpegManager, openAgentWindow$1 = asy
|
|
|
2444
2514
|
ok: false,
|
|
2445
2515
|
spaces: [],
|
|
2446
2516
|
toolCallCount,
|
|
2517
|
+
link: activeLinkInfo(),
|
|
2447
2518
|
reason: "worker not ready"
|
|
2448
2519
|
});
|
|
2449
2520
|
return sendJson(res, 200, {
|
|
2450
2521
|
...data,
|
|
2522
|
+
link: activeLinkInfo(),
|
|
2451
2523
|
toolCallCount
|
|
2452
2524
|
});
|
|
2453
2525
|
}
|
|
@@ -2611,6 +2683,99 @@ function initCastServer(ctx, cfg, bridge, ffmpegManager, openAgentWindow$1 = asy
|
|
|
2611
2683
|
return sendJson(res, result.status, result.body);
|
|
2612
2684
|
}
|
|
2613
2685
|
});
|
|
2686
|
+
const disposeWindowSize = server.register({
|
|
2687
|
+
kind: "exact",
|
|
2688
|
+
path: "/api/bcdp/window-size",
|
|
2689
|
+
handler: async (reqRaw, resRaw) => {
|
|
2690
|
+
const req = reqRaw;
|
|
2691
|
+
const res = resRaw;
|
|
2692
|
+
const body = await readJsonBody$1(req).catch(() => ({}));
|
|
2693
|
+
const port = await ensureWorker();
|
|
2694
|
+
if (port === null) {
|
|
2695
|
+
if (panelActions === null) return sendJson(res, 409, {
|
|
2696
|
+
ok: false,
|
|
2697
|
+
error: "no live agent browser (size-sync needs the CDP worker or the ego-cli route)"
|
|
2698
|
+
});
|
|
2699
|
+
const out = await panelActions.windowSize(body);
|
|
2700
|
+
return sendJson(res, out.ok === true ? 200 : 502, out);
|
|
2701
|
+
}
|
|
2702
|
+
const result = await proxyPost(port, "/api/window-size", body);
|
|
2703
|
+
if (!result) return sendJson(res, 502, {
|
|
2704
|
+
ok: false,
|
|
2705
|
+
error: "window-size worker unavailable"
|
|
2706
|
+
});
|
|
2707
|
+
return sendJson(res, result.status, result.body);
|
|
2708
|
+
}
|
|
2709
|
+
});
|
|
2710
|
+
const disposeTracking = server.register({
|
|
2711
|
+
kind: "exact",
|
|
2712
|
+
path: "/api/bcdp/tracking",
|
|
2713
|
+
handler: async (reqRaw, resRaw) => {
|
|
2714
|
+
const req = reqRaw;
|
|
2715
|
+
const res = resRaw;
|
|
2716
|
+
if (req.method === "POST") {
|
|
2717
|
+
const body = await readJsonBody$1(req).catch(() => ({}));
|
|
2718
|
+
if (typeof body.all === "boolean") setCliTrackAll(body.all);
|
|
2719
|
+
}
|
|
2720
|
+
return sendJson(res, 200, {
|
|
2721
|
+
ok: true,
|
|
2722
|
+
all: getCliTrackAll(cfg.tabTracking === "all"),
|
|
2723
|
+
setting: cfg.tabTracking
|
|
2724
|
+
});
|
|
2725
|
+
}
|
|
2726
|
+
});
|
|
2727
|
+
const disposeSwitchTab = server.register({
|
|
2728
|
+
kind: "exact",
|
|
2729
|
+
path: "/api/bcdp/switch-tab",
|
|
2730
|
+
handler: async (reqRaw, resRaw) => {
|
|
2731
|
+
const req = reqRaw;
|
|
2732
|
+
const res = resRaw;
|
|
2733
|
+
const body = await readJsonBody$1(req).catch(() => ({}));
|
|
2734
|
+
if (typeof body.targetId !== "string" || body.targetId === "") return sendJson(res, 400, {
|
|
2735
|
+
ok: false,
|
|
2736
|
+
error: "targetId required"
|
|
2737
|
+
});
|
|
2738
|
+
const port = await ensureWorker();
|
|
2739
|
+
if (port === null) {
|
|
2740
|
+
if (panelActions === null) return sendJson(res, 409, {
|
|
2741
|
+
ok: false,
|
|
2742
|
+
error: "no live agent browser"
|
|
2743
|
+
});
|
|
2744
|
+
const out = await panelActions.switchTab(body);
|
|
2745
|
+
return sendJson(res, out.ok === true ? 200 : 502, out);
|
|
2746
|
+
}
|
|
2747
|
+
const result = await proxyPost(port, "/api/switch-tab", body);
|
|
2748
|
+
if (!result) return sendJson(res, 502, {
|
|
2749
|
+
ok: false,
|
|
2750
|
+
error: "switch-tab worker unavailable"
|
|
2751
|
+
});
|
|
2752
|
+
return sendJson(res, result.status, result.body);
|
|
2753
|
+
}
|
|
2754
|
+
});
|
|
2755
|
+
const disposePanelNavigate = server.register({
|
|
2756
|
+
kind: "exact",
|
|
2757
|
+
path: "/api/bcdp/navigate",
|
|
2758
|
+
handler: async (reqRaw, resRaw) => {
|
|
2759
|
+
const req = reqRaw;
|
|
2760
|
+
const res = resRaw;
|
|
2761
|
+
const body = await readJsonBody$1(req).catch(() => ({}));
|
|
2762
|
+
const port = await ensureWorker();
|
|
2763
|
+
if (port === null) {
|
|
2764
|
+
if (panelActions === null) return sendJson(res, 409, {
|
|
2765
|
+
ok: false,
|
|
2766
|
+
error: "no live agent browser"
|
|
2767
|
+
});
|
|
2768
|
+
const out = await panelActions.navigate(body);
|
|
2769
|
+
return sendJson(res, out.ok === true ? 200 : 502, out);
|
|
2770
|
+
}
|
|
2771
|
+
const result = await proxyPost(port, "/api/navigate", body);
|
|
2772
|
+
if (!result) return sendJson(res, 502, {
|
|
2773
|
+
ok: false,
|
|
2774
|
+
error: "navigate worker unavailable"
|
|
2775
|
+
});
|
|
2776
|
+
return sendJson(res, result.status, result.body);
|
|
2777
|
+
}
|
|
2778
|
+
});
|
|
2614
2779
|
const disposeRaise = server.register({
|
|
2615
2780
|
kind: "exact",
|
|
2616
2781
|
path: EGO_RAISE_ROUTE,
|
|
@@ -2729,6 +2894,21 @@ function initCastServer(ctx, cfg, bridge, ffmpegManager, openAgentWindow$1 = asy
|
|
|
2729
2894
|
proxyWorkerVideo(port, req, res);
|
|
2730
2895
|
}
|
|
2731
2896
|
});
|
|
2897
|
+
const cliFrameHoldTimer = setInterval(() => {
|
|
2898
|
+
if (sseClients.size === 0) return;
|
|
2899
|
+
if (getAttachEndpoint() !== null) return;
|
|
2900
|
+
if (lastCliFrames === null) return;
|
|
2901
|
+
if (Date.now() - lastCliFrameAt < 1e3) return;
|
|
2902
|
+
const at = Date.now();
|
|
2903
|
+
lastCliFrameAt = at;
|
|
2904
|
+
writeCliImages(lastCliFrames, at, false);
|
|
2905
|
+
}, 1e3);
|
|
2906
|
+
try {
|
|
2907
|
+
cliFrameHoldTimer.unref?.();
|
|
2908
|
+
} catch {}
|
|
2909
|
+
ctx.effect?.(() => () => {
|
|
2910
|
+
clearInterval(cliFrameHoldTimer);
|
|
2911
|
+
});
|
|
2732
2912
|
ctx.effect?.(() => () => {
|
|
2733
2913
|
try {
|
|
2734
2914
|
disposeSpaces();
|
|
@@ -2757,6 +2937,18 @@ function initCastServer(ctx, cfg, bridge, ffmpegManager, openAgentWindow$1 = asy
|
|
|
2757
2937
|
try {
|
|
2758
2938
|
disposeFlush();
|
|
2759
2939
|
} catch {}
|
|
2940
|
+
try {
|
|
2941
|
+
disposeWindowSize();
|
|
2942
|
+
} catch {}
|
|
2943
|
+
try {
|
|
2944
|
+
disposeSwitchTab();
|
|
2945
|
+
} catch {}
|
|
2946
|
+
try {
|
|
2947
|
+
disposeTracking();
|
|
2948
|
+
} catch {}
|
|
2949
|
+
try {
|
|
2950
|
+
disposePanelNavigate();
|
|
2951
|
+
} catch {}
|
|
2760
2952
|
try {
|
|
2761
2953
|
disposeRaise();
|
|
2762
2954
|
} catch {}
|
|
@@ -2838,10 +3030,53 @@ function parseFrameSentinel(stdout, seq, at) {
|
|
|
2838
3030
|
return null;
|
|
2839
3031
|
}
|
|
2840
3032
|
if (png.length === 0) return null;
|
|
3033
|
+
const tabs = Array.isArray(parsed.tabs) ? parsed.tabs.map((row) => {
|
|
3034
|
+
const rec = row ?? {};
|
|
3035
|
+
return {
|
|
3036
|
+
targetId: typeof rec.targetId === "string" ? rec.targetId : "",
|
|
3037
|
+
url: typeof rec.url === "string" ? rec.url : "",
|
|
3038
|
+
title: typeof rec.title === "string" ? rec.title : "",
|
|
3039
|
+
active: rec.active === true
|
|
3040
|
+
};
|
|
3041
|
+
}).filter((row) => row.targetId !== "") : [];
|
|
3042
|
+
const targetId = typeof parsed.targetId === "string" ? parsed.targetId : "";
|
|
3043
|
+
const fmt = parsed.fmt === "jpeg" ? "jpeg" : "png";
|
|
3044
|
+
const url = typeof parsed.url === "string" ? parsed.url : "";
|
|
3045
|
+
const title = typeof parsed.title === "string" ? parsed.title : "";
|
|
3046
|
+
const frames = [];
|
|
3047
|
+
if (Array.isArray(parsed.frames)) for (const row of parsed.frames) {
|
|
3048
|
+
const rec = row ?? {};
|
|
3049
|
+
if (typeof rec.png !== "string" || rec.png === "" || typeof rec.targetId !== "string" || rec.targetId === "") continue;
|
|
3050
|
+
let bytes;
|
|
3051
|
+
try {
|
|
3052
|
+
bytes = Buffer.from(rec.png, "base64");
|
|
3053
|
+
} catch {
|
|
3054
|
+
continue;
|
|
3055
|
+
}
|
|
3056
|
+
if (bytes.length === 0) continue;
|
|
3057
|
+
frames.push({
|
|
3058
|
+
targetId: rec.targetId,
|
|
3059
|
+
png: bytes,
|
|
3060
|
+
fmt: rec.fmt === "jpeg" ? "jpeg" : "png",
|
|
3061
|
+
url: typeof rec.url === "string" ? rec.url : "",
|
|
3062
|
+
title: typeof rec.title === "string" ? rec.title : ""
|
|
3063
|
+
});
|
|
3064
|
+
}
|
|
3065
|
+
if (frames.length === 0) frames.push({
|
|
3066
|
+
targetId,
|
|
3067
|
+
png,
|
|
3068
|
+
fmt,
|
|
3069
|
+
url,
|
|
3070
|
+
title
|
|
3071
|
+
});
|
|
2841
3072
|
return {
|
|
2842
3073
|
png,
|
|
2843
|
-
|
|
2844
|
-
|
|
3074
|
+
fmt,
|
|
3075
|
+
url,
|
|
3076
|
+
title,
|
|
3077
|
+
targetId,
|
|
3078
|
+
frames,
|
|
3079
|
+
tabs,
|
|
2845
3080
|
seq,
|
|
2846
3081
|
updatedAt: at
|
|
2847
3082
|
};
|
|
@@ -2882,32 +3117,925 @@ var CliFramePoller = class {
|
|
|
2882
3117
|
getFrame() {
|
|
2883
3118
|
return this.latest;
|
|
2884
3119
|
}
|
|
2885
|
-
async tick() {
|
|
2886
|
-
if (this.inFlight) return;
|
|
2887
|
-
if (this.opts.isBusy && this.opts.isBusy()) return;
|
|
2888
|
-
this.inFlight = true;
|
|
3120
|
+
async tick() {
|
|
3121
|
+
if (this.inFlight) return;
|
|
3122
|
+
if (this.opts.isBusy && this.opts.isBusy()) return;
|
|
3123
|
+
this.inFlight = true;
|
|
3124
|
+
try {
|
|
3125
|
+
const frame = parseFrameSentinel(await this.opts.capture(), ++this.seq, (this.opts.now ?? Date.now)());
|
|
3126
|
+
if (frame !== null) {
|
|
3127
|
+
this.latest = frame;
|
|
3128
|
+
if (this.opts.onFrame) try {
|
|
3129
|
+
this.opts.onFrame(frame);
|
|
3130
|
+
} catch {}
|
|
3131
|
+
}
|
|
3132
|
+
} catch {} finally {
|
|
3133
|
+
this.inFlight = false;
|
|
3134
|
+
}
|
|
3135
|
+
}
|
|
3136
|
+
};
|
|
3137
|
+
/**
|
|
3138
|
+
* The capture heredoc.
|
|
3139
|
+
*
|
|
3140
|
+
* Two fixes over the old `page.screenshot()` script:
|
|
3141
|
+
* 1. It captures the browser's ACTIVE tab, not the ego SESSION's preferred
|
|
3142
|
+
* target. `bcdp_tab op=new` makes the new tab active in Chrome while the
|
|
3143
|
+
* session target can stay on the previous page — which is why the panel
|
|
3144
|
+
* used to track tab #1 forever while the inventory said #2 was active.
|
|
3145
|
+
* Capturing by an explicit `Target.attachToTarget` session also avoids
|
|
3146
|
+
* switching tabs (a passive observer must not steal the agent's target).
|
|
3147
|
+
* 2. It returns the FULL tab inventory, so the panel lists every tab instead
|
|
3148
|
+
* of one synthetic row.
|
|
3149
|
+
*
|
|
3150
|
+
* `all` turns on 全模式: every tab in the space is captured in ONE process (one
|
|
3151
|
+
* attach/shot per tab, capped at `maxTabs`) and returned as `frames[]`, so the
|
|
3152
|
+
* panel can show a live picture per tab and outline whichever is active. Off =
|
|
3153
|
+
* 仅激活: a single image for the active tab (what the panel had before).
|
|
3154
|
+
*
|
|
3155
|
+
* The old facade path stays as a fallback: a runtime whose `cdp()` rejects a
|
|
3156
|
+
* sessionId still yields a frame (bound to the session page), just without
|
|
3157
|
+
* per-tab targeting. Images are JPEG over CDP (no temp file); the fallback
|
|
3158
|
+
* keeps `page.screenshot()`'s PNG file.
|
|
3159
|
+
*/
|
|
3160
|
+
function buildFrameScript(spaceJson, opts = {}) {
|
|
3161
|
+
const all = opts.all === true;
|
|
3162
|
+
const maxTabs = Math.max(1, Math.min(8, opts.maxTabs ?? 6));
|
|
3163
|
+
return `const __task = await taskSpaces.useOrCreate(${spaceJson})\nlet __tabs = []\ntry { __tabs = await browser.listTabs() } catch { __tabs = [] }\nconst __blank = (u) => /^(about:|chrome:|chrome-extension:|edge:|devtools:|data:)/.test(String(u || ''))\nconst __active = __tabs.find((t) => t.active === true) || __tabs.find((t) => !__blank(t.url)) || __tabs[0] || null\nconst __all = ${all ? "true" : "false"}\nconst __cap = async (t) => {\n try {\n const __att = await cdp('Target.attachToTarget', { targetId: t.targetId, flatten: true })\n const __sid = __att && __att.sessionId\n if (!__sid) return null\n let __u = t.url || ''\n let __ti = t.title || ''\n try {\n const __m = await cdp('Runtime.evaluate', { expression: '({url: location.href, title: document.title})', returnByValue: true }, __sid)\n const __v = (__m && __m.result && __m.result.value) || {}\n __u = __v.url || __u\n __ti = __v.title || __ti\n } catch {}\n const __s = await cdp('Page.captureScreenshot', { format: 'jpeg', quality: 70, fromSurface: true }, __sid)\n try { await cdp('Target.detachFromTarget', { sessionId: __sid }) } catch {}\n if (!__s || !__s.data) return null\n return { targetId: t.targetId, png: __s.data, fmt: 'jpeg', url: __u, title: __ti }\n } catch { return null }\n}\nconst __frames = []\nconst __plan = __all ? __tabs.slice(0, ${maxTabs}) : (__active ? [__active] : [])\nfor (const __t of __plan) {\n const __img = await __cap(__t)\n if (__img) __frames.push(__img)\n}\nlet __png = ''\nlet __fmt = 'jpeg'\nlet __url = ''\nlet __title = ''\nlet __targetId = ''\nconst __actImg = __frames.find((f) => __active && f.targetId === __active.targetId) || __frames[0] || null\nif (__actImg) { __png = __actImg.png; __fmt = __actImg.fmt; __url = __actImg.url; __title = __actImg.title; __targetId = __actImg.targetId }\nif (__png === '') {\n let __info = {}\n try { __info = await page.info() } catch { __info = {} }\n const __p = await page.screenshot({ fullPage: false })\n const __fs = await import('node:fs/promises')\n __png = (await __fs.readFile(__p)).toString('base64')\n try { await __fs.unlink(__p) } catch {}\n __fmt = 'png'\n __url = __url || __info.url || ''\n __title = __title || __info.title || ''\n if (__targetId === '') {\n const __match = __tabs.find((t) => (__info.url || '') !== '' && t.url === __info.url)\n __targetId = (__match && __match.targetId) || ''\n }\n __frames.push({ targetId: __targetId, png: __png, fmt: __fmt, url: __url, title: __title })\n}\nconsole.log(${JSON.stringify(FRAME_SENTINEL)} + JSON.stringify({ png: __png, fmt: __fmt, url: __url, title: __title, targetId: __targetId, frames: __frames, tabs: __tabs.map((t) => ({ targetId: t.targetId, url: t.url || '', title: t.title || '', active: t.active === true })) }))\n`;
|
|
3164
|
+
}
|
|
3165
|
+
|
|
3166
|
+
//#endregion
|
|
3167
|
+
//#region src/worker/window-size.ts
|
|
3168
|
+
/** Chrome refuses slivers; below this a resize is not worth sending. */
|
|
3169
|
+
const MIN_VIEWPORT_WIDTH = 320;
|
|
3170
|
+
const MIN_VIEWPORT_HEIGHT = 200;
|
|
3171
|
+
/** A sanity ceiling; the OS clamps to the display anyway. */
|
|
3172
|
+
const MAX_VIEWPORT_WIDTH = 3840;
|
|
3173
|
+
const MAX_VIEWPORT_HEIGHT = 2160;
|
|
3174
|
+
/** Aspect-ratio presets offered by the panel (label → height/width ratio). */
|
|
3175
|
+
const ASPECT_RATIOS = {
|
|
3176
|
+
"16:9": 9 / 16,
|
|
3177
|
+
"4:3": 3 / 4,
|
|
3178
|
+
"21:9": 9 / 21,
|
|
3179
|
+
"1:1": 1,
|
|
3180
|
+
"9:16": 16 / 9
|
|
3181
|
+
};
|
|
3182
|
+
|
|
3183
|
+
//#endregion
|
|
3184
|
+
//#region src/cast/panel-actions.ts
|
|
3185
|
+
/** Sentinel the heredoc prints; carries the JSON outcome. */
|
|
3186
|
+
const PANEL_SENTINEL = "@@BCDP_PANEL@@";
|
|
3187
|
+
/**
|
|
3188
|
+
* Embed a value as a JS literal. `JSON.stringify` alone leaves U+2028/U+2029
|
|
3189
|
+
* raw, which is a syntax error inside the heredoc source.
|
|
3190
|
+
*/
|
|
3191
|
+
const js$1 = (v) => JSON.stringify(v).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
|
|
3192
|
+
/** Only well-typed, known fields reach the heredoc (a body is client input). */
|
|
3193
|
+
function pickTargetId(body) {
|
|
3194
|
+
return typeof body.targetId === "string" ? body.targetId.trim().slice(0, 200) : "";
|
|
3195
|
+
}
|
|
3196
|
+
/** Field whitelist for the window-size contract. */
|
|
3197
|
+
function pickWindowRequest(body) {
|
|
3198
|
+
const out = {};
|
|
3199
|
+
for (const key of [
|
|
3200
|
+
"width",
|
|
3201
|
+
"height",
|
|
3202
|
+
"delta",
|
|
3203
|
+
"dy"
|
|
3204
|
+
]) {
|
|
3205
|
+
const v = body[key];
|
|
3206
|
+
if (typeof v === "number" && Number.isFinite(v)) out[key] = v;
|
|
3207
|
+
}
|
|
3208
|
+
if (typeof body.aspect === "string" && body.aspect !== "") out.aspect = body.aspect;
|
|
3209
|
+
if (body.maximize === true) out.maximize = true;
|
|
3210
|
+
return out;
|
|
3211
|
+
}
|
|
3212
|
+
/** Same discipline as pickWindowRequest, for the navigate route. */
|
|
3213
|
+
function pickNavigateRequest(body) {
|
|
3214
|
+
const out = {};
|
|
3215
|
+
if (body.reload === true) out.reload = true;
|
|
3216
|
+
if (body.ignoreCache === true) out.ignoreCache = true;
|
|
3217
|
+
if (typeof body.url === "string") {
|
|
3218
|
+
const url = body.url.trim();
|
|
3219
|
+
if (url !== "") out.url = url.slice(0, 4096);
|
|
3220
|
+
}
|
|
3221
|
+
return out;
|
|
3222
|
+
}
|
|
3223
|
+
/**
|
|
3224
|
+
* Parse the newest sentinel line. Returns null when the script never reached
|
|
3225
|
+
* its log (a cold start, a CLI crash, a truncated frame, …) so the caller can
|
|
3226
|
+
* surface the runner's own error instead of a fake success.
|
|
3227
|
+
*/
|
|
3228
|
+
function parsePanelResult(stdout) {
|
|
3229
|
+
const lines = stdout.split("\n");
|
|
3230
|
+
for (let i = lines.length - 1; i >= 0; i--) {
|
|
3231
|
+
const idx = lines[i].indexOf(PANEL_SENTINEL);
|
|
3232
|
+
if (idx === -1) continue;
|
|
3233
|
+
const payload = lines[i].slice(idx + 14).trim();
|
|
3234
|
+
if (payload === "") continue;
|
|
3235
|
+
try {
|
|
3236
|
+
const parsed = JSON.parse(payload);
|
|
3237
|
+
if (parsed === null || typeof parsed !== "object") return null;
|
|
3238
|
+
return {
|
|
3239
|
+
...parsed,
|
|
3240
|
+
ok: parsed.ok === true
|
|
3241
|
+
};
|
|
3242
|
+
} catch {
|
|
3243
|
+
return null;
|
|
3244
|
+
}
|
|
3245
|
+
}
|
|
3246
|
+
return null;
|
|
3247
|
+
}
|
|
3248
|
+
/**
|
|
3249
|
+
* window-size heredoc. Mirrors the worker route arithmetic exactly:
|
|
3250
|
+
* drag deltas apply to the CURRENT page viewport, aspect presets derive the
|
|
3251
|
+
* height from the (possibly new) width, and the target window adds Chrome's own
|
|
3252
|
+
* frame delta (bounds − viewport) so the PAGE lands at the requested size.
|
|
3253
|
+
*
|
|
3254
|
+
* `Browser.setWindowBounds` refuses width/height while the window is maximized,
|
|
3255
|
+
* so a non-normal state is restored first.
|
|
3256
|
+
*/
|
|
3257
|
+
function buildEgoWindowSizeScript(spaceJson, body) {
|
|
3258
|
+
return `const __bcdpReq = ${js$1(pickWindowRequest(body))}\nconst __bcdpClampW = (w) => Math.min(${MAX_VIEWPORT_WIDTH}, Math.max(${MIN_VIEWPORT_WIDTH}, Math.round(w)))\nconst __bcdpClampH = (h) => Math.min(${MAX_VIEWPORT_HEIGHT}, Math.max(${MIN_VIEWPORT_HEIGHT}, Math.round(h)))\nconst __bcdpRatios = ${js$1(ASPECT_RATIOS)}\ntry {\n await taskSpaces.useOrCreate(${spaceJson})\n const __tab = await browser.currentTab()\n const __info = await page.info()\n let __win = null\n try { __win = await cdp('Browser.getWindowForTarget', { targetId: __tab.targetId }) }\n catch { __win = await cdp('Browser.getWindowForTarget', {}) }\n const __windowId = __win && __win.windowId\n if (typeof __windowId !== 'number') throw new Error('Browser.getWindowForTarget returned no windowId')\n const __b = (__win && __win.bounds) || {}\n if (__bcdpReq.maximize === true) {\n await cdp('Browser.setWindowBounds', { windowId: __windowId, bounds: { windowState: 'maximized' } })\n console.log(${js$1(PANEL_SENTINEL)} + JSON.stringify({ ok: true, maximized: true, windowId: __windowId, targetId: __tab.targetId, url: __info.url || '' }))\n } else {\n const __curW = Number(__info.w) || 0\n const __curH = Number(__info.h) || 0\n const __cfW = Math.max(0, (Number(__b.width) || 0) - __curW)\n const __cfH = Math.max(0, (Number(__b.height) || 0) - __curH)\n let __w = typeof __bcdpReq.width === 'number' ? __bcdpReq.width : (typeof __bcdpReq.delta === 'number' ? __curW + __bcdpReq.delta : __curW)\n let __h = typeof __bcdpReq.height === 'number' ? __bcdpReq.height : (typeof __bcdpReq.dy === 'number' ? __curH + __bcdpReq.dy : __curH)\n if (typeof __bcdpReq.aspect === 'string' && typeof __bcdpRatios[__bcdpReq.aspect] === 'number') __h = Math.round(__w * __bcdpRatios[__bcdpReq.aspect])\n __w = __bcdpClampW(__w)\n __h = __bcdpClampH(__h)\n if (__b.windowState && __b.windowState !== 'normal') {\n await cdp('Browser.setWindowBounds', { windowId: __windowId, bounds: { windowState: 'normal' } })\n }\n const __bounds = { width: __w + __cfW, height: __h + __cfH, windowState: 'normal' }\n if (typeof __b.left === 'number') __bounds.left = __b.left\n if (typeof __b.top === 'number') __bounds.top = __b.top\n await cdp('Browser.setWindowBounds', { windowId: __windowId, bounds: __bounds })\n console.log(${js$1(PANEL_SENTINEL)} + JSON.stringify({ ok: true, windowId: __windowId, targetId: __tab.targetId, viewport: { width: __w, height: __h } }))\n }\n} catch (__bcdpErr) {\n console.log(${js$1(PANEL_SENTINEL)} + JSON.stringify({ ok: false, error: String((__bcdpErr && __bcdpErr.message) || __bcdpErr) }))\n}\n`;
|
|
3259
|
+
}
|
|
3260
|
+
/**
|
|
3261
|
+
* switch-tab heredoc — the user clicked a tab in the panel.
|
|
3262
|
+
*
|
|
3263
|
+
* This is the ONE place a panel action deliberately mutates the browser: the
|
|
3264
|
+
* click means "show me that tab", so activating it is the intent. `switchTab`
|
|
3265
|
+
* also re-points the CLI session's preferred target, which keeps the agent and
|
|
3266
|
+
* the panel looking at the same page instead of silently diverging.
|
|
3267
|
+
*/
|
|
3268
|
+
function buildEgoSwitchTabScript(spaceJson, body) {
|
|
3269
|
+
return `const __bcdpTarget = ${js$1(pickTargetId(body))}\ntry {\n if (__bcdpTarget === '') throw new Error('targetId required')\n await taskSpaces.useOrCreate(${spaceJson})\n const __tabs = await browser.listTabs()\n const __hit = __tabs.find((t) => t.targetId === __bcdpTarget)\n if (!__hit) throw new Error('tab not found: ' + __bcdpTarget)\n if (__hit.active !== true) await browser.switchTab({ targetId: __bcdpTarget })\n console.log(${js$1(PANEL_SENTINEL)} + JSON.stringify({ ok: true, targetId: __bcdpTarget, url: __hit.url || '', title: __hit.title || '' }))\n} catch (__bcdpErr) {\n console.log(${js$1(PANEL_SENTINEL)} + JSON.stringify({ ok: false, error: String((__bcdpErr && __bcdpErr.message) || __bcdpErr) }))\n}\n`;
|
|
3270
|
+
}
|
|
3271
|
+
/**
|
|
3272
|
+
* navigate heredoc — panel refresh / manual URL. Uses the runtime facades
|
|
3273
|
+
* (`page.reload` / `page.goto`) rather than raw CDP so the CLI keeps its own
|
|
3274
|
+
* load-state semantics and navigation guards.
|
|
3275
|
+
*/
|
|
3276
|
+
function buildEgoNavigateScript(spaceJson, body) {
|
|
3277
|
+
return `const __bcdpReq = ${js$1(pickNavigateRequest(body))}\ntry {\n await taskSpaces.useOrCreate(${spaceJson})\n if (__bcdpReq.reload === true) {\n await page.reload({ ignoreCache: __bcdpReq.ignoreCache === true })\n let __u = ''\n try { __u = await page.url() } catch {}\n console.log(${js$1(PANEL_SENTINEL)} + JSON.stringify({ ok: true, reloaded: true, url: __u }))\n } else {\n const __target = typeof __bcdpReq.url === 'string' ? __bcdpReq.url.trim() : ''\n if (__target === '') throw new Error('url required')\n await page.goto(__target)\n let __after = ''\n try { __after = await page.url() } catch {}\n console.log(${js$1(PANEL_SENTINEL)} + JSON.stringify({ ok: true, url: __after || __target }))\n }\n} catch (__bcdpErr) {\n console.log(${js$1(PANEL_SENTINEL)} + JSON.stringify({ ok: false, error: String((__bcdpErr && __bcdpErr.message) || __bcdpErr) }))\n}\n`;
|
|
3278
|
+
}
|
|
3279
|
+
|
|
3280
|
+
//#endregion
|
|
3281
|
+
//#region src/jev/anchors.ts
|
|
3282
|
+
/** Fixed prefix so an anchor is recognizable in a transcript at a glance. */
|
|
3283
|
+
const ANCHOR_PREFIX = "sb-";
|
|
3284
|
+
/** Hex length after the prefix — half a sha256, collision-safe for this use. */
|
|
3285
|
+
const ANCHOR_HEX = 16;
|
|
3286
|
+
/**
|
|
3287
|
+
* Mint the anchor for one candidate inside one snapshot scope.
|
|
3288
|
+
*
|
|
3289
|
+
* `scope` is the frame identity (`frame.frameId`) in the current pipeline; any
|
|
3290
|
+
* caller with a different snapshot notion passes its own scope string — the
|
|
3291
|
+
* function only demands that different snapshots produce different scope
|
|
3292
|
+
* strings, which is exactly what frameId guarantees.
|
|
3293
|
+
*/
|
|
3294
|
+
function anchorFor(scope, backendNodeId) {
|
|
3295
|
+
return `${ANCHOR_PREFIX}${createHash("sha256").update(`${scope}\0${backendNodeId}`).digest("hex").slice(0, ANCHOR_HEX)}`;
|
|
3296
|
+
}
|
|
3297
|
+
|
|
3298
|
+
//#endregion
|
|
3299
|
+
//#region src/jev/frame.ts
|
|
3300
|
+
/** Roles worth numbering. Mirrors src/cdp/marks.ts so both paths agree. */
|
|
3301
|
+
const INTERACTIVE_ROLES = [
|
|
3302
|
+
"button",
|
|
3303
|
+
"link",
|
|
3304
|
+
"textbox",
|
|
3305
|
+
"searchbox",
|
|
3306
|
+
"combobox",
|
|
3307
|
+
"checkbox",
|
|
3308
|
+
"radio",
|
|
3309
|
+
"menuitem",
|
|
3310
|
+
"menuitemcheckbox",
|
|
3311
|
+
"menuitemradio",
|
|
3312
|
+
"tab",
|
|
3313
|
+
"option",
|
|
3314
|
+
"switch",
|
|
3315
|
+
"slider"
|
|
3316
|
+
];
|
|
3317
|
+
function isInteractiveRole(role) {
|
|
3318
|
+
return INTERACTIVE_ROLES.includes(role);
|
|
3319
|
+
}
|
|
3320
|
+
/**
|
|
3321
|
+
* A stable frame id.
|
|
3322
|
+
*
|
|
3323
|
+
* Built from facts that identify WHICH page state this is — target, document
|
|
3324
|
+
* revision, capture sequence — rather than from a timestamp, so the same state
|
|
3325
|
+
* captured twice hashes the same and a log can be re-derived. `seq` is what
|
|
3326
|
+
* keeps two captures of an unchanged document distinct.
|
|
3327
|
+
*/
|
|
3328
|
+
function frameIdFor(target, documentRevision, seq) {
|
|
3329
|
+
return createHash("sha256").update(`${target.targetId}\u0000${documentRevision}\u0000${seq}`).digest("hex").slice(0, 16);
|
|
3330
|
+
}
|
|
3331
|
+
/** Default candidate cap. Matches the chunk ceiling — see THRESHOLD_BUCKETS. */
|
|
3332
|
+
const DEFAULT_NODE_LIMIT = 20;
|
|
3333
|
+
/**
|
|
3334
|
+
* Number the interactive candidates and freeze them into a frame.
|
|
3335
|
+
*
|
|
3336
|
+
* Order is DOCUMENT order (the AX tree arrives in it), duplicates by backend
|
|
3337
|
+
* node id are dropped, and `limit` caps the set BEFORE numbering — so `n = 1..N`
|
|
3338
|
+
* is contiguous and a judge that answers `n = 7` is answering about a candidate
|
|
3339
|
+
* the caller can find by index, always.
|
|
3340
|
+
*/
|
|
3341
|
+
function buildFrame(input) {
|
|
3342
|
+
const limit = input.limit ?? DEFAULT_NODE_LIMIT;
|
|
3343
|
+
const now = input.now ?? (() => Date.now());
|
|
3344
|
+
const seen = /* @__PURE__ */ new Set();
|
|
3345
|
+
const nodes = [];
|
|
3346
|
+
let skipped = 0;
|
|
3347
|
+
for (const candidate of input.nodes) {
|
|
3348
|
+
if (nodes.length >= limit) break;
|
|
3349
|
+
if (!isInteractiveRole(candidate.role)) {
|
|
3350
|
+
skipped += 1;
|
|
3351
|
+
continue;
|
|
3352
|
+
}
|
|
3353
|
+
if (seen.has(candidate.backendNodeId)) continue;
|
|
3354
|
+
seen.add(candidate.backendNodeId);
|
|
3355
|
+
nodes.push({
|
|
3356
|
+
n: nodes.length + 1,
|
|
3357
|
+
backendNodeId: candidate.backendNodeId,
|
|
3358
|
+
role: candidate.role,
|
|
3359
|
+
name: candidate.name,
|
|
3360
|
+
rect: candidate.rect ?? null,
|
|
3361
|
+
state: {
|
|
3362
|
+
disabled: candidate.disabled === true,
|
|
3363
|
+
checked: candidate.checked === true,
|
|
3364
|
+
expanded: candidate.expanded === true,
|
|
3365
|
+
focusable: candidate.focusable === true
|
|
3366
|
+
},
|
|
3367
|
+
container: candidate.container ?? "page",
|
|
3368
|
+
containerLabel: candidate.containerLabel ?? "the page itself"
|
|
3369
|
+
});
|
|
3370
|
+
}
|
|
3371
|
+
const interactive = input.nodes.filter((candidate) => isInteractiveRole(candidate.role)).length;
|
|
3372
|
+
return {
|
|
3373
|
+
frame: {
|
|
3374
|
+
frameId: frameIdFor(input.target, input.documentRevision, input.seq),
|
|
3375
|
+
capturedAt: now(),
|
|
3376
|
+
target: input.target,
|
|
3377
|
+
viewport: input.viewport,
|
|
3378
|
+
image: input.image,
|
|
3379
|
+
dom: {
|
|
3380
|
+
nodes,
|
|
3381
|
+
total: interactive,
|
|
3382
|
+
truncated: false,
|
|
3383
|
+
source: "ax-tree"
|
|
3384
|
+
}
|
|
3385
|
+
},
|
|
3386
|
+
skippedNonInteractive: skipped
|
|
3387
|
+
};
|
|
3388
|
+
}
|
|
3389
|
+
/**
|
|
3390
|
+
* Decide whether this frame must be sliced.
|
|
3391
|
+
*
|
|
3392
|
+
* The order of the questions is deliberate: an image that fits and a candidate
|
|
3393
|
+
* list that fits means NO slicing, and most real pages land there (measured
|
|
3394
|
+
* 136.9 KiB / 26 candidates against a 1 MiB / 20-candidate set — the image is
|
|
3395
|
+
* fine, the candidates are not, which is why both are asked separately).
|
|
3396
|
+
*/
|
|
3397
|
+
function planChunks(input) {
|
|
3398
|
+
const chunkSize = Math.max(1, input.chunkSize ?? DEFAULT_NODE_LIMIT);
|
|
3399
|
+
const overImage = input.imageBytes !== null && input.maxBytes > 0 && input.imageBytes > input.maxBytes;
|
|
3400
|
+
const overCandidates = input.candidateCount > chunkSize;
|
|
3401
|
+
if (!overImage && !overCandidates) return {
|
|
3402
|
+
chunkTotal: 1,
|
|
3403
|
+
chunkSize,
|
|
3404
|
+
reason: "fits",
|
|
3405
|
+
sizes: [input.candidateCount]
|
|
3406
|
+
};
|
|
3407
|
+
if (overImage && !overCandidates) return {
|
|
3408
|
+
chunkTotal: 1,
|
|
3409
|
+
chunkSize,
|
|
3410
|
+
reason: "image-over-budget",
|
|
3411
|
+
sizes: [input.candidateCount]
|
|
3412
|
+
};
|
|
3413
|
+
const chunkTotal = Math.ceil(input.candidateCount / chunkSize);
|
|
3414
|
+
const sizes = [];
|
|
3415
|
+
let remaining = input.candidateCount;
|
|
3416
|
+
while (remaining > 0) {
|
|
3417
|
+
const take = Math.min(chunkSize, remaining);
|
|
3418
|
+
sizes.push(take);
|
|
3419
|
+
remaining -= take;
|
|
3420
|
+
}
|
|
3421
|
+
return {
|
|
3422
|
+
chunkTotal,
|
|
3423
|
+
chunkSize,
|
|
3424
|
+
reason: overImage ? "both" : "too-many-candidates",
|
|
3425
|
+
sizes
|
|
3426
|
+
};
|
|
3427
|
+
}
|
|
3428
|
+
/**
|
|
3429
|
+
* Slice a frame's candidates into chunks, preserving document order.
|
|
3430
|
+
*
|
|
3431
|
+
* Out-of-range chunk numbers return `null` rather than wrapping: a `next` at the
|
|
3432
|
+
* boundary must surface as `no_more_chunks`, because a silent wrap turns a
|
|
3433
|
+
* budget problem into an infinite loop.
|
|
3434
|
+
*/
|
|
3435
|
+
function sliceFrame(frame, plan, chunkIndex) {
|
|
3436
|
+
if (chunkIndex < 1 || chunkIndex > plan.chunkTotal) return null;
|
|
3437
|
+
const start = plan.sizes.slice(0, chunkIndex - 1).reduce((sum, size) => sum + size, 0);
|
|
3438
|
+
const count = plan.sizes[chunkIndex - 1] ?? 0;
|
|
3439
|
+
const nodes = frame.dom.nodes.slice(start, start + count);
|
|
3440
|
+
return {
|
|
3441
|
+
frameId: frame.frameId,
|
|
3442
|
+
chunkIndex,
|
|
3443
|
+
chunkTotal: plan.chunkTotal,
|
|
3444
|
+
itemCount: nodes.length,
|
|
3445
|
+
nodes,
|
|
3446
|
+
containerHint: dominantContainer(nodes)
|
|
3447
|
+
};
|
|
3448
|
+
}
|
|
3449
|
+
/** The container most of these nodes live in — the "is this chunk homogeneous" answer. */
|
|
3450
|
+
function dominantContainer(nodes) {
|
|
3451
|
+
if (nodes.length === 0) return "other";
|
|
3452
|
+
const counts = /* @__PURE__ */ new Map();
|
|
3453
|
+
for (const node of nodes) counts.set(node.container, (counts.get(node.container) ?? 0) + 1);
|
|
3454
|
+
let best = "other";
|
|
3455
|
+
let bestCount = -1;
|
|
3456
|
+
for (const [container, count] of counts) if (count > bestCount) {
|
|
3457
|
+
best = container;
|
|
3458
|
+
bestCount = count;
|
|
3459
|
+
}
|
|
3460
|
+
return best;
|
|
3461
|
+
}
|
|
3462
|
+
/**
|
|
3463
|
+
* Group candidates into chapters, in first-appearance order.
|
|
3464
|
+
*
|
|
3465
|
+
* Order is FIRST APPEARANCE, not alphabetical: a judge should be offered the
|
|
3466
|
+
* chapters in the order the page presents them, which is how a human reads it.
|
|
3467
|
+
*/
|
|
3468
|
+
function chaptersOf(nodes) {
|
|
3469
|
+
const byKey = /* @__PURE__ */ new Map();
|
|
3470
|
+
for (const node of nodes) {
|
|
3471
|
+
const existing = byKey.get(node.container);
|
|
3472
|
+
if (existing === void 0) {
|
|
3473
|
+
byKey.set(node.container, {
|
|
3474
|
+
key: node.container,
|
|
3475
|
+
label: node.containerLabel,
|
|
3476
|
+
nodes: [node]
|
|
3477
|
+
});
|
|
3478
|
+
continue;
|
|
3479
|
+
}
|
|
3480
|
+
existing.nodes.push(node);
|
|
3481
|
+
}
|
|
3482
|
+
return [...byKey.values()];
|
|
3483
|
+
}
|
|
3484
|
+
/**
|
|
3485
|
+
* Whether narrowing through a chapter question is worth a round trip.
|
|
3486
|
+
*
|
|
3487
|
+
* `false` when there is only ONE chapter: a question with a single option is not
|
|
3488
|
+
* a question, it is a round trip that can only be answered one way. Skipping it
|
|
3489
|
+
* keeps the loop at two rounds on simple pages and three on busy ones.
|
|
3490
|
+
*/
|
|
3491
|
+
function shouldAskChapter(nodes, chapterCount = chaptersOf(nodes).length) {
|
|
3492
|
+
return chapterCount > 1;
|
|
3493
|
+
}
|
|
3494
|
+
|
|
3495
|
+
//#endregion
|
|
3496
|
+
//#region src/cdp/session.ts
|
|
3497
|
+
var CdpSessionError = class extends Error {
|
|
3498
|
+
code;
|
|
3499
|
+
constructor(code, message) {
|
|
3500
|
+
super(message);
|
|
3501
|
+
this.name = "CdpSessionError";
|
|
3502
|
+
this.code = code;
|
|
3503
|
+
}
|
|
3504
|
+
};
|
|
3505
|
+
const DEFAULT_CONNECT_TIMEOUT_MS = 5e3;
|
|
3506
|
+
const DEFAULT_COMMAND_TIMEOUT_MS = 6e3;
|
|
3507
|
+
const DEFAULT_BACKOFF_SCHEDULE_MS = [
|
|
3508
|
+
250,
|
|
3509
|
+
500,
|
|
3510
|
+
1e3,
|
|
3511
|
+
2e3,
|
|
3512
|
+
4e3
|
|
3513
|
+
];
|
|
3514
|
+
const DEFAULT_TIMERS = {
|
|
3515
|
+
setTimeout: (fn, ms) => setTimeout(fn, ms),
|
|
3516
|
+
clearTimeout: (handle) => clearTimeout(handle)
|
|
3517
|
+
};
|
|
3518
|
+
function defaultCreateSocket(url) {
|
|
3519
|
+
const ctor = globalThis.WebSocket;
|
|
3520
|
+
if (ctor === void 0) throw new CdpSessionError("no-websocket", "no WebSocket implementation available — the host must supply createSocket (Node >= 22 provides a global WebSocket)");
|
|
3521
|
+
return new ctor(url);
|
|
3522
|
+
}
|
|
3523
|
+
var CdpSession = class {
|
|
3524
|
+
url;
|
|
3525
|
+
state = "idle";
|
|
3526
|
+
/** Replay failures from the most recent reconnect — surfaced, never swallowed. */
|
|
3527
|
+
lastReplayFailures = [];
|
|
3528
|
+
#options;
|
|
3529
|
+
#timers;
|
|
3530
|
+
#socket = null;
|
|
3531
|
+
#nextId = 0;
|
|
3532
|
+
#pending = /* @__PURE__ */ new Map();
|
|
3533
|
+
#events = /* @__PURE__ */ new Map();
|
|
3534
|
+
#replay = [];
|
|
3535
|
+
#attempt = 0;
|
|
3536
|
+
#intentionalClose = false;
|
|
3537
|
+
#reconnectTimer = null;
|
|
3538
|
+
constructor(options) {
|
|
3539
|
+
this.url = options.url;
|
|
3540
|
+
this.#options = {
|
|
3541
|
+
...options,
|
|
3542
|
+
connectTimeoutMs: options.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS,
|
|
3543
|
+
commandTimeoutMs: options.commandTimeoutMs ?? DEFAULT_COMMAND_TIMEOUT_MS
|
|
3544
|
+
};
|
|
3545
|
+
this.#timers = options.timers ?? DEFAULT_TIMERS;
|
|
3546
|
+
}
|
|
3547
|
+
/**
|
|
3548
|
+
* The ordered enable sequence re-issued after every successful (re)connect.
|
|
3549
|
+
* M0.3 owns the ordering rules (`DOM.enable` before `Overlay.enable`); this
|
|
3550
|
+
* class only replays what it is handed, in the order it is handed.
|
|
3551
|
+
*/
|
|
3552
|
+
setReplay(methods) {
|
|
3553
|
+
this.#replay = [...methods];
|
|
3554
|
+
}
|
|
3555
|
+
/**
|
|
3556
|
+
* Subscribe to one CDP event method, or to `'*'` for every event — M0.3
|
|
3557
|
+
* routes by domain, which needs a catch-all. A wildcard handler additionally
|
|
3558
|
+
* receives the fired method as its third argument.
|
|
3559
|
+
*/
|
|
3560
|
+
on(method, handler) {
|
|
3561
|
+
if (!this.#events.has(method)) this.#events.set(method, /* @__PURE__ */ new Set());
|
|
3562
|
+
this.#events.get(method).add(handler);
|
|
3563
|
+
return () => {
|
|
3564
|
+
this.#events.get(method)?.delete(handler);
|
|
3565
|
+
};
|
|
3566
|
+
}
|
|
3567
|
+
#setState(state, detail) {
|
|
3568
|
+
this.state = state;
|
|
3569
|
+
this.#options.onStateChange?.(state, detail);
|
|
3570
|
+
}
|
|
3571
|
+
/** Dial and resolve once the socket is open. Rejects with a structured code. */
|
|
3572
|
+
connect() {
|
|
3573
|
+
if (this.state === "open") return Promise.resolve();
|
|
3574
|
+
if (this.state === "closed") return Promise.reject(new CdpSessionError("closed", "session was closed; create a new one instead of reusing it"));
|
|
3575
|
+
this.#setState("connecting");
|
|
3576
|
+
return this.#dial(this.#options.connectTimeoutMs);
|
|
3577
|
+
}
|
|
3578
|
+
#dial(timeoutMs) {
|
|
3579
|
+
return new Promise((resolve$1, reject) => {
|
|
3580
|
+
let settled = false;
|
|
3581
|
+
const finish$1 = (error) => {
|
|
3582
|
+
if (settled) return;
|
|
3583
|
+
settled = true;
|
|
3584
|
+
this.#timers.clearTimeout(timer);
|
|
3585
|
+
if (error) reject(error);
|
|
3586
|
+
else resolve$1();
|
|
3587
|
+
};
|
|
3588
|
+
const timer = this.#timers.setTimeout(() => {
|
|
3589
|
+
this.#teardown();
|
|
3590
|
+
finish$1(new CdpSessionError("connect-timeout", `no CDP open event from ${this.url} within ${timeoutMs}ms`));
|
|
3591
|
+
}, timeoutMs);
|
|
3592
|
+
let socket;
|
|
3593
|
+
try {
|
|
3594
|
+
socket = (this.#options.createSocket ?? defaultCreateSocket)(this.url);
|
|
3595
|
+
} catch (error) {
|
|
3596
|
+
finish$1(error instanceof CdpSessionError ? error : new CdpSessionError("connect-failed", String(error)));
|
|
3597
|
+
return;
|
|
3598
|
+
}
|
|
3599
|
+
this.#socket = socket;
|
|
3600
|
+
socket.addEventListener("open", () => {
|
|
3601
|
+
if (settled || this.#socket !== socket) return;
|
|
3602
|
+
this.#attempt = 0;
|
|
3603
|
+
this.#setState("open");
|
|
3604
|
+
finish$1();
|
|
3605
|
+
this.#replaySequence();
|
|
3606
|
+
});
|
|
3607
|
+
socket.addEventListener("message", (event) => {
|
|
3608
|
+
if (this.#socket !== socket) return;
|
|
3609
|
+
this.#handleMessage(event);
|
|
3610
|
+
});
|
|
3611
|
+
socket.addEventListener("close", () => {
|
|
3612
|
+
if (this.#socket !== socket) return;
|
|
3613
|
+
this.#handleUnexpectedClose("socket closed");
|
|
3614
|
+
});
|
|
3615
|
+
socket.addEventListener("error", (event) => {
|
|
3616
|
+
if (this.#socket !== socket) return;
|
|
3617
|
+
if (!settled) {
|
|
3618
|
+
this.#teardown();
|
|
3619
|
+
finish$1(new CdpSessionError("connect-failed", event?.message || `socket error dialing ${this.url}`));
|
|
3620
|
+
return;
|
|
3621
|
+
}
|
|
3622
|
+
this.#handleUnexpectedClose(event?.message || "socket error");
|
|
3623
|
+
});
|
|
3624
|
+
});
|
|
3625
|
+
}
|
|
3626
|
+
/**
|
|
3627
|
+
* Re-issue the enable sequence. Failures are recorded on
|
|
3628
|
+
* `lastReplayFailures` and reported through `onReplayError` — a silently
|
|
3629
|
+
* disabled domain is exactly the bug this method exists to prevent.
|
|
3630
|
+
*/
|
|
3631
|
+
async #replaySequence() {
|
|
3632
|
+
if (this.#replay.length === 0) return;
|
|
3633
|
+
this.lastReplayFailures = [];
|
|
3634
|
+
for (const method of this.#replay) try {
|
|
3635
|
+
await this.call(method, {});
|
|
3636
|
+
} catch (error) {
|
|
3637
|
+
const failure = {
|
|
3638
|
+
method,
|
|
3639
|
+
message: error instanceof Error ? error.message : String(error)
|
|
3640
|
+
};
|
|
3641
|
+
this.lastReplayFailures.push(failure);
|
|
3642
|
+
this.#options.onReplayError?.(failure);
|
|
3643
|
+
}
|
|
3644
|
+
}
|
|
3645
|
+
#handleMessage(event) {
|
|
3646
|
+
let message;
|
|
3647
|
+
try {
|
|
3648
|
+
message = JSON.parse(typeof event.data === "string" ? event.data : String(event.data));
|
|
3649
|
+
} catch {
|
|
3650
|
+
return;
|
|
3651
|
+
}
|
|
3652
|
+
if (typeof message.id === "number" && this.#pending.has(message.id)) {
|
|
3653
|
+
const pending = this.#pending.get(message.id);
|
|
3654
|
+
this.#pending.delete(message.id);
|
|
3655
|
+
this.#timers.clearTimeout(pending.timer);
|
|
3656
|
+
if (message.error) {
|
|
3657
|
+
const error = new Error(message.error.message || `CDP error ${message.error.code}`);
|
|
3658
|
+
error.code = message.error.code;
|
|
3659
|
+
error.data = message.error.data;
|
|
3660
|
+
pending.reject(error);
|
|
3661
|
+
} else pending.resolve(message.result || {});
|
|
3662
|
+
return;
|
|
3663
|
+
}
|
|
3664
|
+
if (message.method === void 0) return;
|
|
3665
|
+
const method = message.method;
|
|
3666
|
+
const params = message.params || {};
|
|
3667
|
+
for (const key of [method, "*"]) for (const handler of this.#events.get(key) || []) try {
|
|
3668
|
+
handler(params, message.sessionId, method);
|
|
3669
|
+
} catch {}
|
|
3670
|
+
}
|
|
3671
|
+
#handleUnexpectedClose(detail) {
|
|
3672
|
+
this.#teardown();
|
|
3673
|
+
if (this.#intentionalClose || this.state === "closed") return;
|
|
3674
|
+
this.#scheduleReconnect(detail);
|
|
3675
|
+
}
|
|
3676
|
+
#scheduleReconnect(detail) {
|
|
3677
|
+
const schedule = this.#options.backoffScheduleMs ?? DEFAULT_BACKOFF_SCHEDULE_MS;
|
|
3678
|
+
const attempt = this.#attempt;
|
|
3679
|
+
if (attempt >= schedule.length) {
|
|
3680
|
+
this.#setState("closed", `reconnect exhausted after ${schedule.length} attempts (${detail})`);
|
|
3681
|
+
return;
|
|
3682
|
+
}
|
|
3683
|
+
this.#attempt = attempt + 1;
|
|
3684
|
+
const delay = schedule[attempt];
|
|
3685
|
+
this.#setState("reconnecting", `${detail}; retrying in ${delay}ms`);
|
|
3686
|
+
this.#reconnectTimer = this.#timers.setTimeout(() => {
|
|
3687
|
+
this.#reconnectTimer = null;
|
|
3688
|
+
this.#dial(this.#options.connectTimeoutMs).catch((error) => {
|
|
3689
|
+
this.#handleUnexpectedClose(error.message);
|
|
3690
|
+
});
|
|
3691
|
+
}, delay);
|
|
3692
|
+
}
|
|
3693
|
+
/** Reject everything in flight and forget the socket. Pending is never left hanging. */
|
|
3694
|
+
#teardown() {
|
|
3695
|
+
const socket = this.#socket;
|
|
3696
|
+
this.#socket = null;
|
|
3697
|
+
if (socket) try {
|
|
3698
|
+
socket.close();
|
|
3699
|
+
} catch {}
|
|
3700
|
+
for (const pending of this.#pending.values()) {
|
|
3701
|
+
this.#timers.clearTimeout(pending.timer);
|
|
3702
|
+
pending.reject(new CdpSessionError("socket-error", `CDP connection closed while ${pending.method} was in flight`));
|
|
3703
|
+
}
|
|
3704
|
+
this.#pending.clear();
|
|
3705
|
+
}
|
|
3706
|
+
/**
|
|
3707
|
+
* Send one command and await its reply.
|
|
3708
|
+
*
|
|
3709
|
+
* A call made while the socket is not open fails FAST with `not-open` rather
|
|
3710
|
+
* than queueing: a queued command would either run against a freshly
|
|
3711
|
+
* reconnected session (wrong domain state) or hang past the caller's own
|
|
3712
|
+
* deadline. Callers that can tolerate a reconnect should retry explicitly.
|
|
3713
|
+
*/
|
|
3714
|
+
call(method, params = {}, options = {}) {
|
|
3715
|
+
if (this.#socket === null || this.state !== "open") return Promise.reject(new CdpSessionError("not-open", `cannot ${method}: session is ${this.state}, not open`));
|
|
3716
|
+
const timeoutMs = options.timeoutMs ?? this.#options.commandTimeoutMs;
|
|
3717
|
+
const id = ++this.#nextId;
|
|
3718
|
+
const payload = {
|
|
3719
|
+
id,
|
|
3720
|
+
method,
|
|
3721
|
+
params
|
|
3722
|
+
};
|
|
3723
|
+
if (options.sessionId !== void 0) payload.sessionId = options.sessionId;
|
|
3724
|
+
return new Promise((resolve$1, reject) => {
|
|
3725
|
+
const timer = this.#timers.setTimeout(() => {
|
|
3726
|
+
this.#pending.delete(id);
|
|
3727
|
+
reject(new CdpSessionError("command-timeout", `CDP ${method} timed out after ${timeoutMs}ms`));
|
|
3728
|
+
}, timeoutMs);
|
|
3729
|
+
this.#pending.set(id, {
|
|
3730
|
+
method,
|
|
3731
|
+
resolve: resolve$1,
|
|
3732
|
+
reject,
|
|
3733
|
+
timer
|
|
3734
|
+
});
|
|
3735
|
+
try {
|
|
3736
|
+
this.#socket.send(JSON.stringify(payload));
|
|
3737
|
+
} catch (error) {
|
|
3738
|
+
this.#timers.clearTimeout(timer);
|
|
3739
|
+
this.#pending.delete(id);
|
|
3740
|
+
reject(new CdpSessionError("socket-error", error instanceof Error ? error.message : String(error)));
|
|
3741
|
+
}
|
|
3742
|
+
});
|
|
3743
|
+
}
|
|
3744
|
+
/** Intentional shutdown: no reconnect, no retry. */
|
|
3745
|
+
close() {
|
|
3746
|
+
this.#intentionalClose = true;
|
|
3747
|
+
if (this.#reconnectTimer !== null) {
|
|
3748
|
+
this.#timers.clearTimeout(this.#reconnectTimer);
|
|
3749
|
+
this.#reconnectTimer = null;
|
|
3750
|
+
}
|
|
3751
|
+
this.#teardown();
|
|
3752
|
+
if (this.state !== "closed") this.#setState("closed", "closed by caller");
|
|
3753
|
+
}
|
|
3754
|
+
};
|
|
3755
|
+
|
|
3756
|
+
//#endregion
|
|
3757
|
+
//#region src/cdp/dom.ts
|
|
3758
|
+
/** Flatten `Accessibility.getFullAXTree` into the semantics the judge consumes. */
|
|
3759
|
+
function flattenAxTree(nodes) {
|
|
3760
|
+
const out = [];
|
|
3761
|
+
for (const node of nodes) {
|
|
3762
|
+
const focusable = (node.properties ?? []).find((property) => property.name === "focusable");
|
|
3763
|
+
out.push({
|
|
3764
|
+
nodeId: typeof node.nodeId === "string" ? node.nodeId : "",
|
|
3765
|
+
backendNodeId: Number.parseInt(typeof node.nodeId === "string" ? node.nodeId : "", 10) || 0,
|
|
3766
|
+
role: typeof node.role?.value === "string" ? node.role.value : "",
|
|
3767
|
+
name: typeof node.name?.value === "string" ? node.name.value : "",
|
|
3768
|
+
ignored: node.ignored === true,
|
|
3769
|
+
keyboardFocusable: focusable?.value?.value === true
|
|
3770
|
+
});
|
|
3771
|
+
}
|
|
3772
|
+
return out;
|
|
3773
|
+
}
|
|
3774
|
+
async function accessibilityTree(call, sessionId, timeoutMs) {
|
|
3775
|
+
try {
|
|
3776
|
+
const result = await call("Accessibility.getFullAXTree", {}, {
|
|
3777
|
+
...sessionId === void 0 ? {} : { sessionId },
|
|
3778
|
+
...timeoutMs === void 0 ? {} : { timeoutMs }
|
|
3779
|
+
});
|
|
3780
|
+
if (!Array.isArray(result?.nodes)) return {
|
|
3781
|
+
ok: false,
|
|
3782
|
+
code: "ax-tree-missing",
|
|
3783
|
+
message: "Accessibility.getFullAXTree returned no nodes array"
|
|
3784
|
+
};
|
|
3785
|
+
return {
|
|
3786
|
+
ok: true,
|
|
3787
|
+
nodes: flattenAxTree(result.nodes)
|
|
3788
|
+
};
|
|
3789
|
+
} catch (error) {
|
|
3790
|
+
return {
|
|
3791
|
+
ok: false,
|
|
3792
|
+
code: "ax-tree-failed",
|
|
3793
|
+
message: error instanceof Error ? error.message : String(error)
|
|
3794
|
+
};
|
|
3795
|
+
}
|
|
3796
|
+
}
|
|
3797
|
+
|
|
3798
|
+
//#endregion
|
|
3799
|
+
//#region src/tab-report.ts
|
|
3800
|
+
/** Report type the dock card keys on (`obj.type === TAB_REPORT_TYPE`). */
|
|
3801
|
+
const TAB_REPORT_TYPE = "tab-anchor-report";
|
|
3802
|
+
/** Hard ceiling: a huge page is TRUNCATED and the reader is told, never trimmed silently. */
|
|
3803
|
+
const MAX_REPORT_ELEMENTS = 200;
|
|
3804
|
+
/** Per-capture CDP deadline (plan 约束 §: 单次抓取超时 15s → capture-timeout). */
|
|
3805
|
+
const TAB_REPORT_TIMEOUT_MS = 15e3;
|
|
3806
|
+
/** File-name prefix — must not collide with the pick archive (`picks-…`). */
|
|
3807
|
+
const TAB_REPORT_FILE_PREFIX = "tab-";
|
|
3808
|
+
/** Domains the report needs, in the order CDP requires them (F10: DOM before anything that reads nodes). */
|
|
3809
|
+
const REPORT_ENABLE_METHODS = ["DOM.enable", "Accessibility.enable"];
|
|
3810
|
+
/** Engines that cannot answer a node query; a report from one degrades to URL+title only. */
|
|
3811
|
+
const DEGRADED_ENGINE = "lightpanda";
|
|
3812
|
+
var TabReportError = class extends Error {
|
|
3813
|
+
code;
|
|
3814
|
+
constructor(code, message) {
|
|
3815
|
+
super(message);
|
|
3816
|
+
this.name = "TabReportError";
|
|
3817
|
+
this.code = code;
|
|
3818
|
+
}
|
|
3819
|
+
};
|
|
3820
|
+
/**
|
|
3821
|
+
* The capture identity. `frameId` in the JE loop is a content hash of the page
|
|
3822
|
+
* state; here there is no documentRevision to hash, so the plan's URL+timestamp
|
|
3823
|
+
* combination is what guarantees two captures of the same page mint different
|
|
3824
|
+
* anchors. Same page + same second = same scope (findings: accepted trade-off).
|
|
3825
|
+
*/
|
|
3826
|
+
function reportScope(pageUrl, capturedAt) {
|
|
3827
|
+
return createHash("sha256").update(`${pageUrl}\0${capturedAt}`).digest("hex").slice(0, 32);
|
|
3828
|
+
}
|
|
3829
|
+
/**
|
|
3830
|
+
* Number the interactive candidates of one AX snapshot, in document order.
|
|
3831
|
+
* Same rules as cdp/marks.ts: ignored nodes are skipped, duplicates dropped by
|
|
3832
|
+
* node id, the ceiling caps the set, and the cap is REPORTED as `truncated`.
|
|
3833
|
+
*/
|
|
3834
|
+
function numberReportNodes(nodes, scope, maxElements = MAX_REPORT_ELEMENTS) {
|
|
3835
|
+
const out = [];
|
|
3836
|
+
const seen = /* @__PURE__ */ new Set();
|
|
3837
|
+
let total = 0;
|
|
3838
|
+
for (const node of nodes) {
|
|
3839
|
+
if (node.ignored || !isInteractiveRole(node.role)) continue;
|
|
3840
|
+
if (node.backendNodeId === 0 || seen.has(node.backendNodeId)) continue;
|
|
3841
|
+
seen.add(node.backendNodeId);
|
|
3842
|
+
total += 1;
|
|
3843
|
+
if (out.length >= maxElements) continue;
|
|
3844
|
+
out.push({
|
|
3845
|
+
anchor: anchorFor(scope, node.backendNodeId),
|
|
3846
|
+
n: out.length + 1,
|
|
3847
|
+
role: node.role,
|
|
3848
|
+
name: node.name,
|
|
3849
|
+
backendNodeId: node.backendNodeId
|
|
3850
|
+
});
|
|
3851
|
+
}
|
|
3852
|
+
return {
|
|
3853
|
+
elements: out,
|
|
3854
|
+
total,
|
|
3855
|
+
truncated: total > maxElements
|
|
3856
|
+
};
|
|
3857
|
+
}
|
|
3858
|
+
/**
|
|
3859
|
+
* Open a SHORT-LIVED browser-level session, attach the one target, and read its
|
|
3860
|
+
* accessibility tree. This does NOT touch the resident cast worker: a second
|
|
3861
|
+
* CDP client on the same browser endpoint is normal (that is how the tools and
|
|
3862
|
+
* the screencast already coexist). The meta (url/title) comes from a single
|
|
3863
|
+
* `Runtime.evaluate` so the report is stamped at the SAME instant as its
|
|
3864
|
+
* elements, not from a possibly-stale spaces row.
|
|
3865
|
+
*/
|
|
3866
|
+
async function defaultFetchAx(input, deps = {}) {
|
|
3867
|
+
if (input.engine === DEGRADED_ENGINE) return {
|
|
3868
|
+
pageUrl: input.urlHint ?? "",
|
|
3869
|
+
pageTitle: input.titleHint ?? "",
|
|
3870
|
+
nodes: [],
|
|
3871
|
+
degraded: true
|
|
3872
|
+
};
|
|
3873
|
+
const session = new CdpSession({
|
|
3874
|
+
url: input.wsUrl,
|
|
3875
|
+
commandTimeoutMs: TAB_REPORT_TIMEOUT_MS,
|
|
3876
|
+
...deps.createSocket ? { createSocket: deps.createSocket } : {}
|
|
3877
|
+
});
|
|
3878
|
+
await session.connect();
|
|
3879
|
+
try {
|
|
3880
|
+
const attached = await session.call("Target.attachToTarget", {
|
|
3881
|
+
targetId: input.targetId,
|
|
3882
|
+
flatten: true
|
|
3883
|
+
});
|
|
3884
|
+
const sessionId = typeof attached?.sessionId === "string" ? attached.sessionId : "";
|
|
3885
|
+
if (sessionId === "") throw new TabReportError("invalid-target", `no CDP session resolved for target ${input.targetId}`);
|
|
3886
|
+
for (const method of REPORT_ENABLE_METHODS) await session.call(method, {}, {
|
|
3887
|
+
sessionId,
|
|
3888
|
+
timeoutMs: TAB_REPORT_TIMEOUT_MS
|
|
3889
|
+
}).catch(() => {});
|
|
3890
|
+
const call = (method, params, options) => session.call(method, params, {
|
|
3891
|
+
sessionId: options?.sessionId ?? sessionId,
|
|
3892
|
+
timeoutMs: options?.timeoutMs ?? TAB_REPORT_TIMEOUT_MS
|
|
3893
|
+
});
|
|
3894
|
+
const value = (await call("Runtime.evaluate", {
|
|
3895
|
+
expression: "({href: location.href, title: document.title})",
|
|
3896
|
+
returnByValue: true
|
|
3897
|
+
}))?.result?.value ?? {};
|
|
3898
|
+
const pageUrl = typeof value.href === "string" ? value.href : input.urlHint ?? "";
|
|
3899
|
+
const pageTitle = typeof value.title === "string" ? value.title : input.titleHint ?? "";
|
|
3900
|
+
const tree = await accessibilityTree(call, sessionId, TAB_REPORT_TIMEOUT_MS);
|
|
3901
|
+
if (!tree.ok) return {
|
|
3902
|
+
pageUrl,
|
|
3903
|
+
pageTitle,
|
|
3904
|
+
nodes: [],
|
|
3905
|
+
degraded: false
|
|
3906
|
+
};
|
|
3907
|
+
return {
|
|
3908
|
+
pageUrl,
|
|
3909
|
+
pageTitle,
|
|
3910
|
+
nodes: tree.nodes,
|
|
3911
|
+
degraded: false
|
|
3912
|
+
};
|
|
3913
|
+
} finally {
|
|
3914
|
+
session.close();
|
|
3915
|
+
}
|
|
3916
|
+
}
|
|
3917
|
+
/**
|
|
3918
|
+
* Build one tab-anchor report. Pure beyond the AX read: scope + numbering are
|
|
3919
|
+
* `reportScope` / `numberReportNodes`, both already unit-testable in isolation.
|
|
3920
|
+
*/
|
|
3921
|
+
async function captureTabReport(input, deps = {}) {
|
|
3922
|
+
const capturedAt = deps.now?.() ?? Date.now();
|
|
3923
|
+
const snapshot = await (deps.fetchAx ?? defaultFetchAx)(input, deps);
|
|
3924
|
+
const scope = reportScope(snapshot.pageUrl, capturedAt);
|
|
3925
|
+
const numbered = numberReportNodes(snapshot.nodes, scope, deps.maxElements ?? MAX_REPORT_ELEMENTS);
|
|
3926
|
+
return {
|
|
3927
|
+
type: TAB_REPORT_TYPE,
|
|
3928
|
+
cdpEndpoint: input.wsUrl,
|
|
3929
|
+
targetId: input.targetId,
|
|
3930
|
+
pageUrl: snapshot.pageUrl,
|
|
3931
|
+
pageTitle: snapshot.pageTitle,
|
|
3932
|
+
frameId: scope,
|
|
3933
|
+
capturedAt,
|
|
3934
|
+
elements: numbered.elements,
|
|
3935
|
+
truncated: numbered.truncated,
|
|
3936
|
+
...snapshot.degraded ? { degraded: "lightpanda" } : {}
|
|
3937
|
+
};
|
|
3938
|
+
}
|
|
3939
|
+
|
|
3940
|
+
//#endregion
|
|
3941
|
+
//#region src/cast/fallback-tab-report.ts
|
|
3942
|
+
/** Sentinel the ego heredoc prints; carries the snapshot JSON. */
|
|
3943
|
+
const AX_SENTINEL = "@@BCDP_AX@@";
|
|
3944
|
+
/** Hard cap on candidates collected in one pass (DOM scan is O(n)). */
|
|
3945
|
+
const MAX_COLLECTED = 400;
|
|
3946
|
+
/**
|
|
3947
|
+
* The in-page collector, shared byte-for-byte by the ego heredoc and the Tabbit
|
|
3948
|
+
* Playwright snippet. Deliberately framework-agnostic DOM: interactive tags plus
|
|
3949
|
+
* explicit ARIA roles, first 400 in document order, whitespace collapsed, name
|
|
3950
|
+
* capped at 120 chars. Nodes without any accessible label are dropped (a report
|
|
3951
|
+
* of unnamed buttons helps nobody).
|
|
3952
|
+
*/
|
|
3953
|
+
const COLLECT_FN_SOURCE = `() => {
|
|
3954
|
+
const sel = 'a[href],button,input,select,textarea,[role],[contenteditable="true"],[onclick],[tabindex]'
|
|
3955
|
+
const out = []
|
|
3956
|
+
const seen = new Set()
|
|
3957
|
+
for (const el of document.querySelectorAll(sel)) {
|
|
3958
|
+
if (out.length >= ${MAX_COLLECTED}) break\n if (seen.has(el)) continue\n seen.add(el)\n const role = String(el.getAttribute('role') || el.tagName.toLowerCase()).slice(0, 40)\n const raw = el.getAttribute('aria-label') || el.getAttribute('title') || el.getAttribute('placeholder') || el.innerText || el.value || ''\n const name = String(raw).replace(/\\s+/g, ' ').trim().slice(0, 120)\n if (name === '') continue\n out.push({ role: role, name: name })\n }\n return out\n}`;
|
|
3959
|
+
/** Embed a value as a JS literal (U+2028/2029 are syntax errors in a heredoc). */
|
|
3960
|
+
const js = (v) => JSON.stringify(v).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
|
|
3961
|
+
/**
|
|
3962
|
+
* ego heredoc: activate the agent's task space, read the CURRENT tab's url/title
|
|
3963
|
+
* plus the in-page candidates, and print one sentinel line. Errors are reported
|
|
3964
|
+
* through the sentinel (an `ok:false` line) so the host can distinguish "route
|
|
3965
|
+
* unavailable" from "page returned nothing".
|
|
3966
|
+
*/
|
|
3967
|
+
function buildEgoAxScript(spaceJson) {
|
|
3968
|
+
return `try {\n await taskSpaces.useOrCreate(${spaceJson})\n const __tab = await browser.currentTab()\n const __info = await page.info()\n const __nodes = await page.evaluate(${COLLECT_FN_SOURCE})\n console.log(${js(AX_SENTINEL)} + JSON.stringify({ ok: true, url: __info.url || '', title: __info.title || '', targetId: __tab.targetId || '', nodes: Array.isArray(__nodes) ? __nodes : [] }))\n} catch (__err) {\n console.log(${js(AX_SENTINEL)} + JSON.stringify({ ok: false, error: String((__err && __err.message) || __err) }))\n}\n`;
|
|
3969
|
+
}
|
|
3970
|
+
/**
|
|
3971
|
+
* Tabbit Playwright snippet. `page.evaluate` sees the same DOM the CLI's own
|
|
3972
|
+
* observe tool would; the receipt carries only plain JSON so nothing is
|
|
3973
|
+
* demoted to a resource.
|
|
3974
|
+
*/
|
|
3975
|
+
function buildTabbitAxSnippet() {
|
|
3976
|
+
return [`const __nodes = await page.evaluate(${COLLECT_FN_SOURCE});`, `return {url: page.url(), title: await page.title(), nodes: __nodes};`].join("\n");
|
|
3977
|
+
}
|
|
3978
|
+
/** Parse the newest sentinel line; null when the script never reached it. */
|
|
3979
|
+
function parseAxSentinel(stdout) {
|
|
3980
|
+
const lines = stdout.split("\n");
|
|
3981
|
+
for (let i = lines.length - 1; i >= 0; i--) {
|
|
3982
|
+
const idx = lines[i].indexOf(AX_SENTINEL);
|
|
3983
|
+
if (idx === -1) continue;
|
|
3984
|
+
const payload = lines[i].slice(idx + 11).trim();
|
|
3985
|
+
if (payload === "") continue;
|
|
2889
3986
|
try {
|
|
2890
|
-
const
|
|
2891
|
-
if (
|
|
2892
|
-
|
|
2893
|
-
|
|
2894
|
-
|
|
2895
|
-
|
|
2896
|
-
|
|
2897
|
-
|
|
2898
|
-
|
|
3987
|
+
const parsed = JSON.parse(payload);
|
|
3988
|
+
if (parsed === null || typeof parsed !== "object") return null;
|
|
3989
|
+
const nodes = Array.isArray(parsed.nodes) ? parsed.nodes.map((n) => {
|
|
3990
|
+
const rec = n ?? {};
|
|
3991
|
+
return {
|
|
3992
|
+
role: typeof rec.role === "string" ? rec.role : "",
|
|
3993
|
+
name: typeof rec.name === "string" ? rec.name : ""
|
|
3994
|
+
};
|
|
3995
|
+
}).filter((n) => n.name !== "") : [];
|
|
3996
|
+
return {
|
|
3997
|
+
ok: parsed.ok === true,
|
|
3998
|
+
...typeof parsed.url === "string" ? { url: parsed.url } : {},
|
|
3999
|
+
...typeof parsed.title === "string" ? { title: parsed.title } : {},
|
|
4000
|
+
...typeof parsed.targetId === "string" ? { targetId: parsed.targetId } : {},
|
|
4001
|
+
...typeof parsed.error === "string" ? { error: parsed.error } : {},
|
|
4002
|
+
nodes
|
|
4003
|
+
};
|
|
4004
|
+
} catch {
|
|
4005
|
+
return null;
|
|
2899
4006
|
}
|
|
2900
4007
|
}
|
|
2901
|
-
|
|
4008
|
+
return null;
|
|
4009
|
+
}
|
|
2902
4010
|
/**
|
|
2903
|
-
*
|
|
2904
|
-
*
|
|
2905
|
-
|
|
2906
|
-
|
|
2907
|
-
|
|
2908
|
-
|
|
2909
|
-
|
|
2910
|
-
|
|
4011
|
+
* Turn one collected snapshot into a TabAnchorReport. Numbering, anchors and the
|
|
4012
|
+
* truncation flag all come from the CDP path's own helpers so both routes agree.
|
|
4013
|
+
*/
|
|
4014
|
+
function composeFallbackReport(input) {
|
|
4015
|
+
const capturedAt = input.now ?? Date.now();
|
|
4016
|
+
const pageUrl = input.snapshot.url || "";
|
|
4017
|
+
const frameId = reportScope(pageUrl, capturedAt);
|
|
4018
|
+
const numbered = numberReportNodes(input.snapshot.nodes.map((n, i) => ({
|
|
4019
|
+
nodeId: String(i + 1),
|
|
4020
|
+
backendNodeId: i + 1,
|
|
4021
|
+
role: n.role || "generic",
|
|
4022
|
+
name: n.name,
|
|
4023
|
+
ignored: false,
|
|
4024
|
+
keyboardFocusable: false
|
|
4025
|
+
})), frameId, input.maxElements ?? MAX_REPORT_ELEMENTS);
|
|
4026
|
+
return {
|
|
4027
|
+
type: TAB_REPORT_TYPE,
|
|
4028
|
+
cdpEndpoint: input.route,
|
|
4029
|
+
targetId: input.snapshot.targetId || input.targetId,
|
|
4030
|
+
pageUrl,
|
|
4031
|
+
pageTitle: input.snapshot.title || "",
|
|
4032
|
+
frameId,
|
|
4033
|
+
capturedAt,
|
|
4034
|
+
elements: numbered.elements,
|
|
4035
|
+
truncated: numbered.truncated,
|
|
4036
|
+
source: input.route,
|
|
4037
|
+
...input.degraded ? { degraded: input.degraded } : {}
|
|
4038
|
+
};
|
|
2911
4039
|
}
|
|
2912
4040
|
|
|
2913
4041
|
//#endregion
|
|
@@ -2928,6 +4056,7 @@ const cdpMode = z.union([
|
|
|
2928
4056
|
"remote"
|
|
2929
4057
|
]);
|
|
2930
4058
|
const toolInjection = z.union(["lazy", "always"]);
|
|
4059
|
+
const tabTracking = z.union(["active", "all"]);
|
|
2931
4060
|
const DEFAULT_SPACE = "default";
|
|
2932
4061
|
const AUTO_SPACE_SENTINEL = ":auto";
|
|
2933
4062
|
const encoder = z.union([
|
|
@@ -2951,6 +4080,10 @@ const Config$1 = z.object({
|
|
|
2951
4080
|
cdpQuality: z.number().min(1).max(100).step(1).description("CDP JPEG quality.").volatile(),
|
|
2952
4081
|
cdpMaxWidth: z.number().min(320).max(1920).step(40).description("CDP frame max width.").volatile(),
|
|
2953
4082
|
cdpBackstopIntervalMs: z.number().min(1e3).max(1e4).step(100).description("CDP recovery screenshot interval.").volatile(),
|
|
4083
|
+
tabTracking: tabTracking.description("Watch-panel tab tracking: active = capture only the browser-active tab; all = capture every tab in the space (each gets its own picture, the active one is outlined green). CLI/Tabbit routes only.").volatile(),
|
|
4084
|
+
viewportWidth: z.number().min(0).max(3840).step(10).description("Fixed CSS viewport width for agent pages (e.g. 1440). 0 = use the browser window size.").volatile(),
|
|
4085
|
+
viewportHeight: z.number().min(0).max(2160).step(10).description("Fixed CSS viewport height for agent pages (e.g. 900). 0 = use the browser window size.").volatile(),
|
|
4086
|
+
deviceScaleFactor: z.number().min(0).max(4).step(.25).description("Device pixel ratio for the fixed viewport. 0 = the browser default.").volatile(),
|
|
2954
4087
|
ffmpegFps: z.number().min(5).max(30).step(1).description("FFmpeg video FPS.").volatile(),
|
|
2955
4088
|
ffmpegMaxWidth: z.number().min(320).max(1920).step(40).description("FFmpeg video max width.").volatile(),
|
|
2956
4089
|
ffmpegBitrateKbps: z.number().min(500).max(2e4).step(250).description("FFmpeg target video bitrate in kbps.").volatile(),
|
|
@@ -3277,6 +4410,10 @@ function resolveConfig(config = {}) {
|
|
|
3277
4410
|
cdpQuality: finiteIn(config.cdpQuality, 1, 100) ? config.cdpQuality : finiteIn(config.screencastQuality, 1, 100) ? config.screencastQuality : 55,
|
|
3278
4411
|
cdpMaxWidth: finiteIn(config.cdpMaxWidth, 320, 1920) ? config.cdpMaxWidth : finiteIn(config.screencastMaxWidth, 320, 1920) ? config.screencastMaxWidth : 960,
|
|
3279
4412
|
cdpBackstopIntervalMs: finiteIn(config.cdpBackstopIntervalMs, 1e3, 1e4) ? config.cdpBackstopIntervalMs : finiteIn(config.backstopIntervalMs, 200, 1e4) ? Math.max(1e3, config.backstopIntervalMs) : 3e3,
|
|
4413
|
+
tabTracking: config.tabTracking === "all" ? "all" : "active",
|
|
4414
|
+
viewportWidth: finiteIn(config.viewportWidth, 0, 3840) ? config.viewportWidth : 0,
|
|
4415
|
+
viewportHeight: finiteIn(config.viewportHeight, 0, 2160) ? config.viewportHeight : 0,
|
|
4416
|
+
deviceScaleFactor: finiteIn(config.deviceScaleFactor, 0, 4) ? config.deviceScaleFactor : 0,
|
|
3280
4417
|
ffmpegFps: finiteIn(config.ffmpegFps, 5, 30) ? config.ffmpegFps : profileDefaults.fps,
|
|
3281
4418
|
ffmpegMaxWidth: finiteIn(config.ffmpegMaxWidth, 320, 1920) ? config.ffmpegMaxWidth : profileDefaults.width,
|
|
3282
4419
|
ffmpegBitrateKbps: finiteIn(config.ffmpegBitrateKbps, 500, 2e4) ? config.ffmpegBitrateKbps : profileDefaults.bitrateKbps,
|
|
@@ -3505,6 +4642,59 @@ function registerEgoBrowserGateway(ctx, bridge, ffmpegManager, picks) {
|
|
|
3505
4642
|
} catch (error) {
|
|
3506
4643
|
writeJson(res, 404, envelopeError("not-found", error instanceof Error ? error.message : String(error)));
|
|
3507
4644
|
}
|
|
4645
|
+
} else if (method === "tab-anchor-report") {
|
|
4646
|
+
const repSession = typeof body.session === "string" ? body.session : void 0;
|
|
4647
|
+
const repDir = picks ? picks.resolveDir(repSession) : void 0;
|
|
4648
|
+
if (!repDir) {
|
|
4649
|
+
writeJson(res, 409, envelopeError("no-workspace", "no registered workspace resolves for this session"));
|
|
4650
|
+
return;
|
|
4651
|
+
}
|
|
4652
|
+
const repTargetId = typeof body.targetId === "string" ? body.targetId : "";
|
|
4653
|
+
if (repTargetId === "") {
|
|
4654
|
+
writeJson(res, 400, envelopeError("invalid-target", "targetId is required"));
|
|
4655
|
+
return;
|
|
4656
|
+
}
|
|
4657
|
+
const attach = defaultAttachCache.get();
|
|
4658
|
+
const urlHint = typeof body.url === "string" ? body.url : "";
|
|
4659
|
+
const titleHint = typeof body.title === "string" ? body.title : "";
|
|
4660
|
+
let report = null;
|
|
4661
|
+
try {
|
|
4662
|
+
if (attach.status === "ready" && attach.wsUrl !== "") report = await captureTabReport({
|
|
4663
|
+
wsUrl: attach.wsUrl,
|
|
4664
|
+
targetId: repTargetId,
|
|
4665
|
+
engine: attach.engine,
|
|
4666
|
+
urlHint,
|
|
4667
|
+
titleHint
|
|
4668
|
+
});
|
|
4669
|
+
else if (picks?.fallbackTabReport) report = await picks.fallbackTabReport({
|
|
4670
|
+
targetId: repTargetId,
|
|
4671
|
+
urlHint,
|
|
4672
|
+
titleHint
|
|
4673
|
+
});
|
|
4674
|
+
} catch (error) {
|
|
4675
|
+
const code = error?.code || "capture-failed";
|
|
4676
|
+
writeJson(res, code === "invalid-target" ? 409 : 502, envelopeError(code, error instanceof Error ? error.message : String(error)));
|
|
4677
|
+
return;
|
|
4678
|
+
}
|
|
4679
|
+
if (report === null) {
|
|
4680
|
+
writeJson(res, 409, envelopeError("attach-not-ready", "no live CDP attach and no CLI fallback; activate a target and let the probe finish first"));
|
|
4681
|
+
return;
|
|
4682
|
+
}
|
|
4683
|
+
const repFile = typeof body.file === "string" && /^[A-Za-z0-9._-]+\.json$/.test(body.file) ? body.file : `${TAB_REPORT_FILE_PREFIX}${(report.targetId || repTargetId).slice(0, 8)}-${Date.now()}.json`;
|
|
4684
|
+
await mkdir(repDir, { recursive: true });
|
|
4685
|
+
const repTargetPath = resolve(repDir, repFile);
|
|
4686
|
+
if (!repTargetPath.startsWith(resolve(repDir))) {
|
|
4687
|
+
writeJson(res, 400, envelopeError("invalid-path", "path escapes the picks dir"));
|
|
4688
|
+
return;
|
|
4689
|
+
}
|
|
4690
|
+
await writeFile(repTargetPath, JSON.stringify(report, null, 2), "utf8");
|
|
4691
|
+
writeJson(res, 200, envelopeOk({
|
|
4692
|
+
file: repFile,
|
|
4693
|
+
token: `@"picks/${repFile}"`,
|
|
4694
|
+
count: report.elements.length,
|
|
4695
|
+
truncated: report.truncated,
|
|
4696
|
+
degraded: report.degraded ?? null
|
|
4697
|
+
}));
|
|
3508
4698
|
} else writeJson(res, 404, envelopeError("not-found", `unknown ego-browser API method "${method}"`));
|
|
3509
4699
|
} catch (error) {
|
|
3510
4700
|
const e = error;
|
|
@@ -3915,6 +5105,7 @@ const POWER = [
|
|
|
3915
5105
|
];
|
|
3916
5106
|
const SESSION = [
|
|
3917
5107
|
"bcdp_captcha",
|
|
5108
|
+
"bcdp_wait_for_human",
|
|
3918
5109
|
"bcdp_auth_flush",
|
|
3919
5110
|
"bcdp_login_import"
|
|
3920
5111
|
];
|
|
@@ -4140,12 +5331,12 @@ function rewriteGithubUrl(url, mirror = "") {
|
|
|
4140
5331
|
try {
|
|
4141
5332
|
parsed = new URL(mirror);
|
|
4142
5333
|
} catch {
|
|
4143
|
-
throw codedError$
|
|
5334
|
+
throw codedError$3("ffmpeg-mirror-invalid", "GitHub mirror must be a valid HTTPS URL");
|
|
4144
5335
|
}
|
|
4145
|
-
if (parsed.protocol !== "https:" || parsed.username || parsed.password || parsed.search || parsed.hash) throw codedError$
|
|
5336
|
+
if (parsed.protocol !== "https:" || parsed.username || parsed.password || parsed.search || parsed.hash) throw codedError$3("ffmpeg-mirror-invalid", "GitHub mirror must be an HTTPS base URL without credentials, query, or fragment");
|
|
4146
5337
|
return `${parsed.toString().replace(/\/+$/, "")}${url.slice(18)}`;
|
|
4147
5338
|
}
|
|
4148
|
-
function codedError$
|
|
5339
|
+
function codedError$3(code, message) {
|
|
4149
5340
|
const error = new Error(message);
|
|
4150
5341
|
error.code = code;
|
|
4151
5342
|
return error;
|
|
@@ -4202,7 +5393,7 @@ function runFfmpegProbe(path, argv, { spawn: spawn$1 = spawn, timeoutMs = 3e3 }
|
|
|
4202
5393
|
}
|
|
4203
5394
|
async function probeFfmpeg(path, { platform = process.platform, env = process.env, spawn: spawn$1 = spawn, requestedEncoder = "auto" } = {}) {
|
|
4204
5395
|
const versionResult = await runFfmpegProbe(path, ["-version"], { spawn: spawn$1 });
|
|
4205
|
-
if (!versionResult.ok) throw codedError$
|
|
5396
|
+
if (!versionResult.ok) throw codedError$2("ffmpeg-not-executable", `FFmpeg is not executable: ${path}`);
|
|
4206
5397
|
const version = versionResult.output.split(/\r?\n/, 1)[0] || "FFmpeg";
|
|
4207
5398
|
if (platform === "win32") {
|
|
4208
5399
|
const support = await runFfmpegProbe(path, [
|
|
@@ -4210,14 +5401,14 @@ async function probeFfmpeg(path, { platform = process.platform, env = process.en
|
|
|
4210
5401
|
"-h",
|
|
4211
5402
|
"filter=gfxcapture"
|
|
4212
5403
|
], { spawn: spawn$1 });
|
|
4213
|
-
if (!support.ok || !/Filter gfxcapture\b/.test(support.output)) throw codedError$
|
|
5404
|
+
if (!support.ok || !/Filter gfxcapture\b/.test(support.output)) throw codedError$2("ffmpeg-gfxcapture-unavailable", "FFmpeg does not support Windows gfxcapture");
|
|
4214
5405
|
} else if (platform === "darwin") {
|
|
4215
5406
|
const devices = await runFfmpegProbe(path, ["-hide_banner", "-devices"], { spawn: spawn$1 });
|
|
4216
|
-
if (!devices.ok || !/avfoundation/i.test(devices.output)) throw codedError$
|
|
5407
|
+
if (!devices.ok || !/avfoundation/i.test(devices.output)) throw codedError$2("ffmpeg-capture-input-unavailable", "FFmpeg does not support avfoundation capture");
|
|
4217
5408
|
} else if (platform === "linux") {
|
|
4218
|
-
if (env.XDG_SESSION_TYPE === "wayland" || env.WAYLAND_DISPLAY) throw codedError$
|
|
5409
|
+
if (env.XDG_SESSION_TYPE === "wayland" || env.WAYLAND_DISPLAY) throw codedError$2("ffmpeg-platform-unsupported", "Wayland capture is not supported");
|
|
4219
5410
|
const devices = await runFfmpegProbe(path, ["-hide_banner", "-devices"], { spawn: spawn$1 });
|
|
4220
|
-
if (!devices.ok || !/x11grab/i.test(devices.output)) throw codedError$
|
|
5411
|
+
if (!devices.ok || !/x11grab/i.test(devices.output)) throw codedError$2("ffmpeg-capture-input-unavailable", "FFmpeg does not support x11grab capture");
|
|
4221
5412
|
}
|
|
4222
5413
|
const encoders = requestedEncoder === "auto" ? platform === "win32" ? [
|
|
4223
5414
|
"h264_mf",
|
|
@@ -4253,9 +5444,9 @@ async function probeFfmpeg(path, { platform = process.platform, env = process.en
|
|
|
4253
5444
|
version,
|
|
4254
5445
|
encoder: encoder$1
|
|
4255
5446
|
};
|
|
4256
|
-
throw codedError$
|
|
5447
|
+
throw codedError$2("ffmpeg-encoder-unavailable", "FFmpeg has no usable H.264 encoder");
|
|
4257
5448
|
}
|
|
4258
|
-
function codedError$
|
|
5449
|
+
function codedError$2(code, message) {
|
|
4259
5450
|
const error = new Error(message);
|
|
4260
5451
|
error.code = code;
|
|
4261
5452
|
return error;
|
|
@@ -4431,7 +5622,7 @@ var FfmpegInstallationManager = class {
|
|
|
4431
5622
|
}
|
|
4432
5623
|
install({ githubMirror, configuredPath, requestedEncoder = "auto" } = {}) {
|
|
4433
5624
|
if (this.installPromise) return this.installPromise;
|
|
4434
|
-
if (!this.manifest) return Promise.reject(codedError("ffmpeg-platform-unsupported", `No managed FFmpeg build for ${this.platform}-${this.arch}`));
|
|
5625
|
+
if (!this.manifest) return Promise.reject(codedError$1("ffmpeg-platform-unsupported", `No managed FFmpeg build for ${this.platform}-${this.arch}`));
|
|
4435
5626
|
this.installPromise = this.#install(githubMirror ?? this.getConfig().githubMirror ?? "", configuredPath ?? this.getConfig().ffmpegPath ?? "", requestedEncoder).finally(() => {
|
|
4436
5627
|
this.installPromise = null;
|
|
4437
5628
|
});
|
|
@@ -4481,7 +5672,7 @@ var FfmpegInstallationManager = class {
|
|
|
4481
5672
|
state: "verifying",
|
|
4482
5673
|
progress: null
|
|
4483
5674
|
});
|
|
4484
|
-
if (digest !== manifest.sha256) throw codedError("ffmpeg-checksum-mismatch", "Downloaded FFmpeg archive failed SHA-256 verification");
|
|
5675
|
+
if (digest !== manifest.sha256) throw codedError$1("ffmpeg-checksum-mismatch", "Downloaded FFmpeg archive failed SHA-256 verification");
|
|
4485
5676
|
this.#set({ state: "extracting" });
|
|
4486
5677
|
if (manifest.archiveType === "gzip") await pipeline(createReadStream(archivePath), createGunzip(), createWriteStream(extractedPath, { mode: 493 }));
|
|
4487
5678
|
else await extractWithTar(archivePath, tempRoot, extractedPath, manifest.archiveExecutable, this.spawn);
|
|
@@ -4574,9 +5765,9 @@ async function acquireInstallLock(platformRoot) {
|
|
|
4574
5765
|
await rm(lockPath, { force: true });
|
|
4575
5766
|
continue;
|
|
4576
5767
|
}
|
|
4577
|
-
throw codedError("ffmpeg-install-busy", "Another FFmpeg installation is already running");
|
|
5768
|
+
throw codedError$1("ffmpeg-install-busy", "Another FFmpeg installation is already running");
|
|
4578
5769
|
}
|
|
4579
|
-
throw codedError("ffmpeg-install-busy", "Another FFmpeg installation is already running");
|
|
5770
|
+
throw codedError$1("ffmpeg-install-busy", "Another FFmpeg installation is already running");
|
|
4580
5771
|
}
|
|
4581
5772
|
function isProcessAlive(pid) {
|
|
4582
5773
|
try {
|
|
@@ -4618,13 +5809,13 @@ async function downloadFile(url, target, { fetchImpl = globalThis.fetch, expecte
|
|
|
4618
5809
|
308
|
|
4619
5810
|
].includes(response.status)) break;
|
|
4620
5811
|
const location = response.headers.get("location");
|
|
4621
|
-
if (!location) throw codedError("ffmpeg-download-failed", "FFmpeg download redirect omitted Location");
|
|
5812
|
+
if (!location) throw codedError$1("ffmpeg-download-failed", "FFmpeg download redirect omitted Location");
|
|
4622
5813
|
current = new URL(location, current).toString();
|
|
4623
5814
|
await response.body?.cancel().catch(() => {});
|
|
4624
|
-
if (!current.startsWith("https://")) throw codedError("ffmpeg-download-failed", "FFmpeg download refused a non-HTTPS redirect");
|
|
4625
|
-
if (redirects === 5) throw codedError("ffmpeg-download-failed", "Too many FFmpeg download redirects");
|
|
5815
|
+
if (!current.startsWith("https://")) throw codedError$1("ffmpeg-download-failed", "FFmpeg download refused a non-HTTPS redirect");
|
|
5816
|
+
if (redirects === 5) throw codedError$1("ffmpeg-download-failed", "Too many FFmpeg download redirects");
|
|
4626
5817
|
}
|
|
4627
|
-
if (!response?.ok || !response.body) throw codedError("ffmpeg-download-failed", `FFmpeg download failed with HTTP ${response?.status || 0}`);
|
|
5818
|
+
if (!response?.ok || !response.body) throw codedError$1("ffmpeg-download-failed", `FFmpeg download failed with HTTP ${response?.status || 0}`);
|
|
4628
5819
|
const declared = Number(response.headers.get("content-length")) || expectedSize || null;
|
|
4629
5820
|
const hash = createHash("sha256");
|
|
4630
5821
|
const file = await open(target, "w");
|
|
@@ -4636,7 +5827,7 @@ async function downloadFile(url, target, { fetchImpl = globalThis.fetch, expecte
|
|
|
4636
5827
|
if (done) break;
|
|
4637
5828
|
const buffer = Buffer.from(value);
|
|
4638
5829
|
received += buffer.length;
|
|
4639
|
-
if (received > maxBytes) throw codedError("ffmpeg-download-failed", "FFmpeg archive exceeds the allowed size");
|
|
5830
|
+
if (received > maxBytes) throw codedError$1("ffmpeg-download-failed", "FFmpeg archive exceeds the allowed size");
|
|
4640
5831
|
hash.update(buffer);
|
|
4641
5832
|
await file.write(buffer);
|
|
4642
5833
|
onProgress({
|
|
@@ -4655,13 +5846,13 @@ async function ensureTarAvailable(spawn$1) {
|
|
|
4655
5846
|
try {
|
|
4656
5847
|
await runCommand("tar", ["--version"], spawn$1, 5e3);
|
|
4657
5848
|
} catch {
|
|
4658
|
-
throw codedError("ffmpeg-extractor-unavailable", "The managed FFmpeg archive requires the system tar extractor");
|
|
5849
|
+
throw codedError$1("ffmpeg-extractor-unavailable", "The managed FFmpeg archive requires the system tar extractor");
|
|
4659
5850
|
}
|
|
4660
5851
|
}
|
|
4661
5852
|
function assertSafeDownloadUrl(value) {
|
|
4662
5853
|
const url = new URL(value);
|
|
4663
5854
|
const host = url.hostname.toLowerCase().replace(/^\[|\]$/g, "");
|
|
4664
|
-
if (url.protocol !== "https:" || host === "localhost" || host.endsWith(".localhost") || isPrivateIp(host)) throw codedError("ffmpeg-download-failed", "FFmpeg downloads require a public HTTPS destination");
|
|
5855
|
+
if (url.protocol !== "https:" || host === "localhost" || host.endsWith(".localhost") || isPrivateIp(host)) throw codedError$1("ffmpeg-download-failed", "FFmpeg downloads require a public HTTPS destination");
|
|
4665
5856
|
}
|
|
4666
5857
|
function isPrivateIp(host) {
|
|
4667
5858
|
const family = isIP(host);
|
|
@@ -4674,7 +5865,7 @@ function isPrivateIp(host) {
|
|
|
4674
5865
|
}
|
|
4675
5866
|
async function extractWithTar(archivePath, tempRoot, destination, matcher, spawn$1) {
|
|
4676
5867
|
const matches = (await runCommand("tar", ["-tf", archivePath], spawn$1, 15e3)).stdout.split(/\r?\n/).filter(Boolean).filter((entry$1) => safeArchiveEntry(entry$1) && matcher.test(entry$1));
|
|
4677
|
-
if (matches.length !== 1) throw codedError("ffmpeg-executable-missing", `Expected one FFmpeg executable in archive, found ${matches.length}`);
|
|
5868
|
+
if (matches.length !== 1) throw codedError$1("ffmpeg-executable-missing", `Expected one FFmpeg executable in archive, found ${matches.length}`);
|
|
4678
5869
|
const entry = matches[0];
|
|
4679
5870
|
await runCommand("tar", [
|
|
4680
5871
|
"-xf",
|
|
@@ -4684,7 +5875,7 @@ async function extractWithTar(archivePath, tempRoot, destination, matcher, spawn
|
|
|
4684
5875
|
entry
|
|
4685
5876
|
], spawn$1, 6e4);
|
|
4686
5877
|
const extracted = resolve(tempRoot, normalize(entry));
|
|
4687
|
-
if (!extracted.startsWith(resolve(tempRoot) + sep)) throw codedError("ffmpeg-archive-unsafe", "FFmpeg archive path escaped the install directory");
|
|
5878
|
+
if (!extracted.startsWith(resolve(tempRoot) + sep)) throw codedError$1("ffmpeg-archive-unsafe", "FFmpeg archive path escaped the install directory");
|
|
4688
5879
|
await copyFile(extracted, destination);
|
|
4689
5880
|
}
|
|
4690
5881
|
function safeArchiveEntry(entry) {
|
|
@@ -4711,7 +5902,7 @@ async function hashFile(path) {
|
|
|
4711
5902
|
}
|
|
4712
5903
|
function readChunk(reader, timeoutMs) {
|
|
4713
5904
|
return new Promise((resolvePromise, reject) => {
|
|
4714
|
-
const timer = setTimeout(() => reject(codedError("ffmpeg-download-timeout", "FFmpeg download stalled")), timeoutMs);
|
|
5905
|
+
const timer = setTimeout(() => reject(codedError$1("ffmpeg-download-timeout", "FFmpeg download stalled")), timeoutMs);
|
|
4715
5906
|
reader.read().then((value) => {
|
|
4716
5907
|
clearTimeout(timer);
|
|
4717
5908
|
resolvePromise(value);
|
|
@@ -4751,16 +5942,16 @@ function runCommand(command, argv, spawn$1, timeoutMs) {
|
|
|
4751
5942
|
child.once("exit", (code) => code === 0 ? finish$1(resolvePromise, {
|
|
4752
5943
|
stdout,
|
|
4753
5944
|
stderr
|
|
4754
|
-
}) : finish$1(reject, codedError("ffmpeg-archive-invalid", stderr || `${command} exited with ${code}`)));
|
|
5945
|
+
}) : finish$1(reject, codedError$1("ffmpeg-archive-invalid", stderr || `${command} exited with ${code}`)));
|
|
4755
5946
|
const timer = setTimeout(() => {
|
|
4756
5947
|
try {
|
|
4757
5948
|
child.kill("SIGKILL");
|
|
4758
5949
|
} catch {}
|
|
4759
|
-
finish$1(reject, codedError("ffmpeg-archive-invalid", `${command} timed out`));
|
|
5950
|
+
finish$1(reject, codedError$1("ffmpeg-archive-invalid", `${command} timed out`));
|
|
4760
5951
|
}, timeoutMs);
|
|
4761
5952
|
});
|
|
4762
5953
|
}
|
|
4763
|
-
function codedError(code, message) {
|
|
5954
|
+
function codedError$1(code, message) {
|
|
4764
5955
|
const error = new Error(message);
|
|
4765
5956
|
error.code = code;
|
|
4766
5957
|
return error;
|
|
@@ -5818,259 +7009,62 @@ const httpConfig = (baseUrl, apiKey, model) => ({
|
|
|
5818
7009
|
timeoutMs: 15e3
|
|
5819
7010
|
});
|
|
5820
7011
|
/**
|
|
5821
|
-
* Assemble the request body for one hop.
|
|
5822
|
-
*
|
|
5823
|
-
* Returns the issues ALONGSIDE the body rather than throwing: a caller that is
|
|
5824
|
-
* previewing a body (`dryRun`) wants to see what is wrong with it, and a caller
|
|
5825
|
-
* about to send needs to refuse. Splitting those two decisions between the
|
|
5826
|
-
* assembler and the sender is what keeps "preview" and "send" from drifting into
|
|
5827
|
-
* two different encoders.
|
|
5828
|
-
*/
|
|
5829
|
-
function assembleSystemOneBody(input, hop) {
|
|
5830
|
-
return {
|
|
5831
|
-
body: buildSystemOneRequest(input.state, input.questions, input.model),
|
|
5832
|
-
issues: validateQuestions(input.questions),
|
|
5833
|
-
url: `${hop.baseUrl.replace(/\/+$/, "")}/v1/systemone`
|
|
5834
|
-
};
|
|
5835
|
-
}
|
|
5836
|
-
/** Send one already-assembled body through the chain, refusing an invalid one. */
|
|
5837
|
-
async function sendJudge(runtime, request$1) {
|
|
5838
|
-
const fatal = validateQuestions(request$1.questions).filter((issue) => issue.code !== "choice-criteria-over-limit");
|
|
5839
|
-
if (fatal.length > 0) return {
|
|
5840
|
-
answers: {},
|
|
5841
|
-
provider: "refuse",
|
|
5842
|
-
model: "",
|
|
5843
|
-
latencyMs: 0,
|
|
5844
|
-
degraded: true,
|
|
5845
|
-
trace: fatal.map((issue) => `invalid-questions:${issue.code}:${issue.questionId}`),
|
|
5846
|
-
warnings: [],
|
|
5847
|
-
dropped: [],
|
|
5848
|
-
missing: Object.keys(request$1.questions),
|
|
5849
|
-
chain: ["local:refused"]
|
|
5850
|
-
};
|
|
5851
|
-
return runtime.chain.decide(request$1);
|
|
5852
|
-
}
|
|
5853
|
-
/**
|
|
5854
|
-
* A one-line-per-hop description of the chain, for `bcdp_jev_status`.
|
|
5855
|
-
*
|
|
5856
|
-
* Computed WITHOUT calling anything, because a status tool that performs a
|
|
5857
|
-
* request every time it is asked for status is a status tool nobody runs.
|
|
5858
|
-
*/
|
|
5859
|
-
function describeJudge(runtime) {
|
|
5860
|
-
const lines = [];
|
|
5861
|
-
const resolved = runtime.chain.resolve();
|
|
5862
|
-
for (const name$1 of runtime.order) {
|
|
5863
|
-
if (name$1 === "refuse") {
|
|
5864
|
-
lines.push("refuse terminal (always available; a refusal is a result, not an error)");
|
|
5865
|
-
continue;
|
|
5866
|
-
}
|
|
5867
|
-
const hop = resolved.find((entry) => entry.provider.name === name$1);
|
|
5868
|
-
if (hop === void 0) {
|
|
5869
|
-
lines.push(`${pad(name$1)} not configured`);
|
|
5870
|
-
continue;
|
|
5871
|
-
}
|
|
5872
|
-
lines.push(hop.available ? `${pad(name$1)} ready` : `${pad(name$1)} SKIPPED (${hop.reason})`);
|
|
5873
|
-
}
|
|
5874
|
-
return lines;
|
|
5875
|
-
}
|
|
5876
|
-
const pad = (name$1) => (name$1 + " ").slice(0, 9);
|
|
5877
|
-
|
|
5878
|
-
//#endregion
|
|
5879
|
-
//#region src/jev/frame.ts
|
|
5880
|
-
/** Roles worth numbering. Mirrors src/cdp/marks.ts so both paths agree. */
|
|
5881
|
-
const INTERACTIVE_ROLES = [
|
|
5882
|
-
"button",
|
|
5883
|
-
"link",
|
|
5884
|
-
"textbox",
|
|
5885
|
-
"searchbox",
|
|
5886
|
-
"combobox",
|
|
5887
|
-
"checkbox",
|
|
5888
|
-
"radio",
|
|
5889
|
-
"menuitem",
|
|
5890
|
-
"menuitemcheckbox",
|
|
5891
|
-
"menuitemradio",
|
|
5892
|
-
"tab",
|
|
5893
|
-
"option",
|
|
5894
|
-
"switch",
|
|
5895
|
-
"slider"
|
|
5896
|
-
];
|
|
5897
|
-
function isInteractiveRole(role) {
|
|
5898
|
-
return INTERACTIVE_ROLES.includes(role);
|
|
5899
|
-
}
|
|
5900
|
-
/**
|
|
5901
|
-
* A stable frame id.
|
|
5902
|
-
*
|
|
5903
|
-
* Built from facts that identify WHICH page state this is — target, document
|
|
5904
|
-
* revision, capture sequence — rather than from a timestamp, so the same state
|
|
5905
|
-
* captured twice hashes the same and a log can be re-derived. `seq` is what
|
|
5906
|
-
* keeps two captures of an unchanged document distinct.
|
|
5907
|
-
*/
|
|
5908
|
-
function frameIdFor(target, documentRevision, seq) {
|
|
5909
|
-
return createHash("sha256").update(`${target.targetId}\u0000${documentRevision}\u0000${seq}`).digest("hex").slice(0, 16);
|
|
5910
|
-
}
|
|
5911
|
-
/** Default candidate cap. Matches the chunk ceiling — see THRESHOLD_BUCKETS. */
|
|
5912
|
-
const DEFAULT_NODE_LIMIT = 20;
|
|
5913
|
-
/**
|
|
5914
|
-
* Number the interactive candidates and freeze them into a frame.
|
|
5915
|
-
*
|
|
5916
|
-
* Order is DOCUMENT order (the AX tree arrives in it), duplicates by backend
|
|
5917
|
-
* node id are dropped, and `limit` caps the set BEFORE numbering — so `n = 1..N`
|
|
5918
|
-
* is contiguous and a judge that answers `n = 7` is answering about a candidate
|
|
5919
|
-
* the caller can find by index, always.
|
|
5920
|
-
*/
|
|
5921
|
-
function buildFrame(input) {
|
|
5922
|
-
const limit = input.limit ?? DEFAULT_NODE_LIMIT;
|
|
5923
|
-
const now = input.now ?? (() => Date.now());
|
|
5924
|
-
const seen = /* @__PURE__ */ new Set();
|
|
5925
|
-
const nodes = [];
|
|
5926
|
-
let skipped = 0;
|
|
5927
|
-
for (const candidate of input.nodes) {
|
|
5928
|
-
if (nodes.length >= limit) break;
|
|
5929
|
-
if (!isInteractiveRole(candidate.role)) {
|
|
5930
|
-
skipped += 1;
|
|
5931
|
-
continue;
|
|
5932
|
-
}
|
|
5933
|
-
if (seen.has(candidate.backendNodeId)) continue;
|
|
5934
|
-
seen.add(candidate.backendNodeId);
|
|
5935
|
-
nodes.push({
|
|
5936
|
-
n: nodes.length + 1,
|
|
5937
|
-
backendNodeId: candidate.backendNodeId,
|
|
5938
|
-
role: candidate.role,
|
|
5939
|
-
name: candidate.name,
|
|
5940
|
-
rect: candidate.rect ?? null,
|
|
5941
|
-
state: {
|
|
5942
|
-
disabled: candidate.disabled === true,
|
|
5943
|
-
checked: candidate.checked === true,
|
|
5944
|
-
expanded: candidate.expanded === true,
|
|
5945
|
-
focusable: candidate.focusable === true
|
|
5946
|
-
},
|
|
5947
|
-
container: candidate.container ?? "page",
|
|
5948
|
-
containerLabel: candidate.containerLabel ?? "the page itself"
|
|
5949
|
-
});
|
|
5950
|
-
}
|
|
5951
|
-
const interactive = input.nodes.filter((candidate) => isInteractiveRole(candidate.role)).length;
|
|
5952
|
-
return {
|
|
5953
|
-
frame: {
|
|
5954
|
-
frameId: frameIdFor(input.target, input.documentRevision, input.seq),
|
|
5955
|
-
capturedAt: now(),
|
|
5956
|
-
target: input.target,
|
|
5957
|
-
viewport: input.viewport,
|
|
5958
|
-
image: input.image,
|
|
5959
|
-
dom: {
|
|
5960
|
-
nodes,
|
|
5961
|
-
total: interactive,
|
|
5962
|
-
truncated: false,
|
|
5963
|
-
source: "ax-tree"
|
|
5964
|
-
}
|
|
5965
|
-
},
|
|
5966
|
-
skippedNonInteractive: skipped
|
|
5967
|
-
};
|
|
5968
|
-
}
|
|
5969
|
-
/**
|
|
5970
|
-
* Decide whether this frame must be sliced.
|
|
5971
|
-
*
|
|
5972
|
-
* The order of the questions is deliberate: an image that fits and a candidate
|
|
5973
|
-
* list that fits means NO slicing, and most real pages land there (measured
|
|
5974
|
-
* 136.9 KiB / 26 candidates against a 1 MiB / 20-candidate set — the image is
|
|
5975
|
-
* fine, the candidates are not, which is why both are asked separately).
|
|
5976
|
-
*/
|
|
5977
|
-
function planChunks(input) {
|
|
5978
|
-
const chunkSize = Math.max(1, input.chunkSize ?? DEFAULT_NODE_LIMIT);
|
|
5979
|
-
const overImage = input.imageBytes !== null && input.maxBytes > 0 && input.imageBytes > input.maxBytes;
|
|
5980
|
-
const overCandidates = input.candidateCount > chunkSize;
|
|
5981
|
-
if (!overImage && !overCandidates) return {
|
|
5982
|
-
chunkTotal: 1,
|
|
5983
|
-
chunkSize,
|
|
5984
|
-
reason: "fits",
|
|
5985
|
-
sizes: [input.candidateCount]
|
|
5986
|
-
};
|
|
5987
|
-
if (overImage && !overCandidates) return {
|
|
5988
|
-
chunkTotal: 1,
|
|
5989
|
-
chunkSize,
|
|
5990
|
-
reason: "image-over-budget",
|
|
5991
|
-
sizes: [input.candidateCount]
|
|
5992
|
-
};
|
|
5993
|
-
const chunkTotal = Math.ceil(input.candidateCount / chunkSize);
|
|
5994
|
-
const sizes = [];
|
|
5995
|
-
let remaining = input.candidateCount;
|
|
5996
|
-
while (remaining > 0) {
|
|
5997
|
-
const take = Math.min(chunkSize, remaining);
|
|
5998
|
-
sizes.push(take);
|
|
5999
|
-
remaining -= take;
|
|
6000
|
-
}
|
|
6001
|
-
return {
|
|
6002
|
-
chunkTotal,
|
|
6003
|
-
chunkSize,
|
|
6004
|
-
reason: overImage ? "both" : "too-many-candidates",
|
|
6005
|
-
sizes
|
|
6006
|
-
};
|
|
6007
|
-
}
|
|
6008
|
-
/**
|
|
6009
|
-
* Slice a frame's candidates into chunks, preserving document order.
|
|
6010
|
-
*
|
|
6011
|
-
* Out-of-range chunk numbers return `null` rather than wrapping: a `next` at the
|
|
6012
|
-
* boundary must surface as `no_more_chunks`, because a silent wrap turns a
|
|
6013
|
-
* budget problem into an infinite loop.
|
|
7012
|
+
* Assemble the request body for one hop.
|
|
7013
|
+
*
|
|
7014
|
+
* Returns the issues ALONGSIDE the body rather than throwing: a caller that is
|
|
7015
|
+
* previewing a body (`dryRun`) wants to see what is wrong with it, and a caller
|
|
7016
|
+
* about to send needs to refuse. Splitting those two decisions between the
|
|
7017
|
+
* assembler and the sender is what keeps "preview" and "send" from drifting into
|
|
7018
|
+
* two different encoders.
|
|
6014
7019
|
*/
|
|
6015
|
-
function
|
|
6016
|
-
if (chunkIndex < 1 || chunkIndex > plan.chunkTotal) return null;
|
|
6017
|
-
const start = plan.sizes.slice(0, chunkIndex - 1).reduce((sum, size) => sum + size, 0);
|
|
6018
|
-
const count = plan.sizes[chunkIndex - 1] ?? 0;
|
|
6019
|
-
const nodes = frame.dom.nodes.slice(start, start + count);
|
|
7020
|
+
function assembleSystemOneBody(input, hop) {
|
|
6020
7021
|
return {
|
|
6021
|
-
|
|
6022
|
-
|
|
6023
|
-
|
|
6024
|
-
itemCount: nodes.length,
|
|
6025
|
-
nodes,
|
|
6026
|
-
containerHint: dominantContainer(nodes)
|
|
7022
|
+
body: buildSystemOneRequest(input.state, input.questions, input.model),
|
|
7023
|
+
issues: validateQuestions(input.questions),
|
|
7024
|
+
url: `${hop.baseUrl.replace(/\/+$/, "")}/v1/systemone`
|
|
6027
7025
|
};
|
|
6028
7026
|
}
|
|
6029
|
-
/**
|
|
6030
|
-
function
|
|
6031
|
-
|
|
6032
|
-
|
|
6033
|
-
|
|
6034
|
-
|
|
6035
|
-
|
|
6036
|
-
|
|
6037
|
-
|
|
6038
|
-
|
|
6039
|
-
|
|
6040
|
-
|
|
7027
|
+
/** Send one already-assembled body through the chain, refusing an invalid one. */
|
|
7028
|
+
async function sendJudge(runtime, request$1) {
|
|
7029
|
+
const fatal = validateQuestions(request$1.questions).filter((issue) => issue.code !== "choice-criteria-over-limit");
|
|
7030
|
+
if (fatal.length > 0) return {
|
|
7031
|
+
answers: {},
|
|
7032
|
+
provider: "refuse",
|
|
7033
|
+
model: "",
|
|
7034
|
+
latencyMs: 0,
|
|
7035
|
+
degraded: true,
|
|
7036
|
+
trace: fatal.map((issue) => `invalid-questions:${issue.code}:${issue.questionId}`),
|
|
7037
|
+
warnings: [],
|
|
7038
|
+
dropped: [],
|
|
7039
|
+
missing: Object.keys(request$1.questions),
|
|
7040
|
+
chain: ["local:refused"]
|
|
7041
|
+
};
|
|
7042
|
+
return runtime.chain.decide(request$1);
|
|
6041
7043
|
}
|
|
6042
7044
|
/**
|
|
6043
|
-
*
|
|
7045
|
+
* A one-line-per-hop description of the chain, for `bcdp_jev_status`.
|
|
6044
7046
|
*
|
|
6045
|
-
*
|
|
6046
|
-
*
|
|
7047
|
+
* Computed WITHOUT calling anything, because a status tool that performs a
|
|
7048
|
+
* request every time it is asked for status is a status tool nobody runs.
|
|
6047
7049
|
*/
|
|
6048
|
-
function
|
|
6049
|
-
const
|
|
6050
|
-
|
|
6051
|
-
|
|
6052
|
-
if (
|
|
6053
|
-
|
|
6054
|
-
key: node.container,
|
|
6055
|
-
label: node.containerLabel,
|
|
6056
|
-
nodes: [node]
|
|
6057
|
-
});
|
|
7050
|
+
function describeJudge(runtime) {
|
|
7051
|
+
const lines = [];
|
|
7052
|
+
const resolved = runtime.chain.resolve();
|
|
7053
|
+
for (const name$1 of runtime.order) {
|
|
7054
|
+
if (name$1 === "refuse") {
|
|
7055
|
+
lines.push("refuse terminal (always available; a refusal is a result, not an error)");
|
|
6058
7056
|
continue;
|
|
6059
7057
|
}
|
|
6060
|
-
|
|
7058
|
+
const hop = resolved.find((entry) => entry.provider.name === name$1);
|
|
7059
|
+
if (hop === void 0) {
|
|
7060
|
+
lines.push(`${pad(name$1)} not configured`);
|
|
7061
|
+
continue;
|
|
7062
|
+
}
|
|
7063
|
+
lines.push(hop.available ? `${pad(name$1)} ready` : `${pad(name$1)} SKIPPED (${hop.reason})`);
|
|
6061
7064
|
}
|
|
6062
|
-
return
|
|
6063
|
-
}
|
|
6064
|
-
/**
|
|
6065
|
-
* Whether narrowing through a chapter question is worth a round trip.
|
|
6066
|
-
*
|
|
6067
|
-
* `false` when there is only ONE chapter: a question with a single option is not
|
|
6068
|
-
* a question, it is a round trip that can only be answered one way. Skipping it
|
|
6069
|
-
* keeps the loop at two rounds on simple pages and three on busy ones.
|
|
6070
|
-
*/
|
|
6071
|
-
function shouldAskChapter(nodes, chapterCount = chaptersOf(nodes).length) {
|
|
6072
|
-
return chapterCount > 1;
|
|
7065
|
+
return lines;
|
|
6073
7066
|
}
|
|
7067
|
+
const pad = (name$1) => (name$1 + " ").slice(0, 9);
|
|
6074
7068
|
|
|
6075
7069
|
//#endregion
|
|
6076
7070
|
//#region src/jev/prompt.ts
|
|
@@ -6435,7 +7429,7 @@ async function runRenderCall(subprocess, options) {
|
|
|
6435
7429
|
};
|
|
6436
7430
|
const spec = {
|
|
6437
7431
|
argv: [options.nodePath ?? defaultNodePath(), options.workerPath],
|
|
6438
|
-
|
|
7432
|
+
cwd: options.cwd ?? process.cwd(),
|
|
6439
7433
|
...options.env === void 0 ? {} : { env: options.env },
|
|
6440
7434
|
stdio: {
|
|
6441
7435
|
stdin: { data: buildWorkerScript(options) },
|
|
@@ -6730,24 +7724,6 @@ function codeOf(code) {
|
|
|
6730
7724
|
}
|
|
6731
7725
|
const messageOf$1 = (value) => value instanceof Error ? value.message : String(value);
|
|
6732
7726
|
|
|
6733
|
-
//#endregion
|
|
6734
|
-
//#region src/jev/anchors.ts
|
|
6735
|
-
/** Fixed prefix so an anchor is recognizable in a transcript at a glance. */
|
|
6736
|
-
const ANCHOR_PREFIX = "sb-";
|
|
6737
|
-
/** Hex length after the prefix — half a sha256, collision-safe for this use. */
|
|
6738
|
-
const ANCHOR_HEX = 16;
|
|
6739
|
-
/**
|
|
6740
|
-
* Mint the anchor for one candidate inside one snapshot scope.
|
|
6741
|
-
*
|
|
6742
|
-
* `scope` is the frame identity (`frame.frameId`) in the current pipeline; any
|
|
6743
|
-
* caller with a different snapshot notion passes its own scope string — the
|
|
6744
|
-
* function only demands that different snapshots produce different scope
|
|
6745
|
-
* strings, which is exactly what frameId guarantees.
|
|
6746
|
-
*/
|
|
6747
|
-
function anchorFor(scope, backendNodeId) {
|
|
6748
|
-
return `${ANCHOR_PREFIX}${createHash("sha256").update(`${scope}\0${backendNodeId}`).digest("hex").slice(0, ANCHOR_HEX)}`;
|
|
6749
|
-
}
|
|
6750
|
-
|
|
6751
7727
|
//#endregion
|
|
6752
7728
|
//#region src/jev/attempt.ts
|
|
6753
7729
|
/** Fixed question id; the judge's answer key for every round. */
|
|
@@ -7886,6 +8862,21 @@ const TOOL_TIMEOUT_MS = 12e4;
|
|
|
7886
8862
|
function humanCheckScript(space) {
|
|
7887
8863
|
return `${useSpace(space)}${ensureRealTab()}let __hc = null\ntry { __hc = await page.evaluate(${j(HUMAN_CHECK_PROBE)}) } catch { __hc = null }\nconsole.log('${SENTINEL}' + JSON.stringify({ ok: true, humanCheck: __hc }))\n`;
|
|
7888
8864
|
}
|
|
8865
|
+
/**
|
|
8866
|
+
* Script that blocks until the human clears a challenge.
|
|
8867
|
+
*
|
|
8868
|
+
* Polls the page (rather than sleeping once) so it returns as soon as the user
|
|
8869
|
+
* solves the CAPTCHA or completes the login. When `selector` is given, that
|
|
8870
|
+
* element must also exist — the usual "logged in now" signal. Returns a
|
|
8871
|
+
* structured payload, never an error: `resolved:false` is the honest answer
|
|
8872
|
+
* when the deadline passes.
|
|
8873
|
+
*/
|
|
8874
|
+
function waitForHumanScript(space, opts) {
|
|
8875
|
+
const pollMs = opts.pollMs ?? 2e3;
|
|
8876
|
+
const selector = opts.selector ?? "";
|
|
8877
|
+
const selectorCheck = selector === "" ? " const __selOk = true\n" : ` let __selOk = false\n try { __selOk = !!(await page.evaluate(${j(`document.querySelector(${JSON.stringify(selector)}) != null`)})) } catch { __selOk = false }\n`;
|
|
8878
|
+
return `${useSpace(space)}${ensureRealTab()}const __wb = Date.now()\nlet __saw = false, __resolved = false, __polls = 0, __last = null\nfor (;;) {\n let __hc = null\n try { __hc = await page.evaluate(${j(HUMAN_CHECK_PROBE)}) } catch { __hc = null }\n if (__hc && __hc.detected) __saw = true\n __last = __hc\n` + selectorCheck + ` if (!(__hc && __hc.detected) && __selOk) { __resolved = true; break }\n if (Date.now() - __wb >= ${opts.timeoutMs}) break\n __polls++\n await page.waitForTimeout(${pollMs})\n}\nconsole.log('${SENTINEL}' + JSON.stringify({ ok: true, needed: __saw, resolved: __resolved, waitedMs: Date.now() - __wb, polls: __polls, detected: !!(__last && __last.detected), kind: (__last && __last.kind) || null, url: await page.url().catch(() => null) }))\n`;
|
|
8879
|
+
}
|
|
7889
8880
|
function createActiveSpaceTracker(defaultSpace = DEFAULT_SPACE) {
|
|
7890
8881
|
let activeSpace = defaultSpace;
|
|
7891
8882
|
let activeName = typeof defaultSpace === "string" ? defaultSpace : null;
|
|
@@ -8099,6 +9090,7 @@ function withEgoLock(fn) {
|
|
|
8099
9090
|
const RENDER_WORKER_BIN = fileURLToPath(new URL("../bin/cdp-render-worker.mjs", import.meta.url));
|
|
8100
9091
|
const BUNDLED_WRAPPER = fileURLToPath(new URL("../bin/cdp-chrome-wrapper.sh", import.meta.url));
|
|
8101
9092
|
const IS_WIN = process.platform === "win32";
|
|
9093
|
+
const IS_DARWIN = process.platform === "darwin";
|
|
8102
9094
|
const AUTO_ADAPT_OFF = /^(0|false|no)$/i.test(process.env.EGO_BROWSER_AUTO_ADAPT ?? "");
|
|
8103
9095
|
const COMMON_CHROME_BINS = [
|
|
8104
9096
|
"google-chrome-stable",
|
|
@@ -8129,6 +9121,28 @@ function windowsChromeCandidates() {
|
|
|
8129
9121
|
b(local) + "\\BraveSoftware\\Brave-Browser\\Application\\brave.exe"
|
|
8130
9122
|
].filter(Boolean);
|
|
8131
9123
|
}
|
|
9124
|
+
/**
|
|
9125
|
+
* macOS registry-free probe of the usual `.app` bundles (no subprocess).
|
|
9126
|
+
*
|
|
9127
|
+
* Chrome on macOS is never on PATH: the launcher lives inside the bundle at
|
|
9128
|
+
* `<App>.app/Contents/MacOS/<binary>`. Both the system-wide and per-user
|
|
9129
|
+
* `/Applications` locations are probed, Chrome first so that a machine with
|
|
9130
|
+
* several browsers picks the same one the README documents.
|
|
9131
|
+
*/
|
|
9132
|
+
function darwinChromeCandidates() {
|
|
9133
|
+
const roots = ["/Applications"];
|
|
9134
|
+
if (process.env.HOME) roots.push(`${process.env.HOME}/Applications`);
|
|
9135
|
+
const bundles = [
|
|
9136
|
+
"Google Chrome.app/Contents/MacOS/Google Chrome",
|
|
9137
|
+
"Chromium.app/Contents/MacOS/Chromium",
|
|
9138
|
+
"Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
|
|
9139
|
+
"Brave Browser.app/Contents/MacOS/Brave Browser",
|
|
9140
|
+
"Tungsten Edge.app/Contents/MacOS/Tungsten Edge"
|
|
9141
|
+
];
|
|
9142
|
+
const out = [];
|
|
9143
|
+
for (const root of roots) for (const bundle of bundles) out.push(`${root}/${bundle}`);
|
|
9144
|
+
return out;
|
|
9145
|
+
}
|
|
8132
9146
|
/** Find a usable Chrome binary by scanning PATH + common fixed locations. */
|
|
8133
9147
|
function findChromeBinary() {
|
|
8134
9148
|
if (process.env.EGO_LINUX_CHROME) return process.env.EGO_LINUX_CHROME;
|
|
@@ -8148,6 +9162,12 @@ function findChromeBinary() {
|
|
|
8148
9162
|
} catch {}
|
|
8149
9163
|
return;
|
|
8150
9164
|
}
|
|
9165
|
+
if (IS_DARWIN) {
|
|
9166
|
+
for (const p of darwinChromeCandidates()) try {
|
|
9167
|
+
if (existsSync(p)) return p;
|
|
9168
|
+
} catch {}
|
|
9169
|
+
return;
|
|
9170
|
+
}
|
|
8151
9171
|
for (const name$1 of COMMON_CHROME_BINS) if (name$1.includes("/")) try {
|
|
8152
9172
|
if (existsSync(name$1)) return name$1;
|
|
8153
9173
|
} catch {}
|
|
@@ -8183,7 +9203,7 @@ function resolveEgoEnv(cfg, { platform = process.platform, baseEnv = process.env
|
|
|
8183
9203
|
const configChrome = cfg?.chromePath;
|
|
8184
9204
|
if (env.EGO_LINUX_CHROME === void 0 && configChrome) env.EGO_LINUX_CHROME = configChrome;
|
|
8185
9205
|
if (env.EGO_LINUX_CHROME === void 0 && isPosixRoot(platform) && chrome) env.EGO_LINUX_CHROME = BUNDLED_WRAPPER;
|
|
8186
|
-
if (env.EGO_LINUX_CHROME === void 0 && platform === "win32" && chrome) env.EGO_LINUX_CHROME = chrome;
|
|
9206
|
+
if (env.EGO_LINUX_CHROME === void 0 && (platform === "win32" || platform === "darwin") && chrome) env.EGO_LINUX_CHROME = chrome;
|
|
8187
9207
|
if (env.EGO_LINUX_HEADLESS === void 0 && isHeadlessDetected(platform, env)) env.EGO_LINUX_HEADLESS = "1";
|
|
8188
9208
|
const configChromeArgs = cfg?.chromeArgs;
|
|
8189
9209
|
if (env.EGO_LINUX_EXTRA_ARGS === void 0 && typeof configChromeArgs === "string" && configChromeArgs.trim() !== "") env.EGO_LINUX_EXTRA_ARGS = configChromeArgs;
|
|
@@ -8355,8 +9375,26 @@ async function runWithStaleSpaceRetry(ctx, cfg, exec, buildScript, graceOverride
|
|
|
8355
9375
|
if (!result.ok && CDP_CONNECT_FAIL_RE.test(result.error ?? "")) {
|
|
8356
9376
|
if (await cfg.refreshAttach?.() === true) result = await withWarmupRetry(() => runEgoScript(ctx.subprocess, buildScript(), exec, cfg, graceOverrideMs));
|
|
8357
9377
|
}
|
|
9378
|
+
if (result.ok) maybeKickCliPoller(cfg);
|
|
8358
9379
|
return result;
|
|
8359
9380
|
}
|
|
9381
|
+
/** Last time we nudged a re-probe to start the degraded CLI frame poller. */
|
|
9382
|
+
let lastCliPollerKick = 0;
|
|
9383
|
+
/**
|
|
9384
|
+
* Start the ego-cli 3s frame poller after a successful tool call when it failed
|
|
9385
|
+
* to start at mount (browser cold-started by the tool, not by the probe).
|
|
9386
|
+
* No-op for the screencast route (a resolved CDP ws serves frames itself) and
|
|
9387
|
+
* while the poller is already running. Coalesced to at most once per 5s so a
|
|
9388
|
+
* burst of tool calls cannot re-probe repeatedly.
|
|
9389
|
+
*/
|
|
9390
|
+
function maybeKickCliPoller(cfg) {
|
|
9391
|
+
if (getAttachEndpoint() !== null) return;
|
|
9392
|
+
if (getCliPollStatus().running) return;
|
|
9393
|
+
const now = Date.now();
|
|
9394
|
+
if (now - lastCliPollerKick < 5e3) return;
|
|
9395
|
+
lastCliPollerKick = now;
|
|
9396
|
+
cfg.refreshAttach?.();
|
|
9397
|
+
}
|
|
8360
9398
|
/**
|
|
8361
9399
|
* F — navigate self-heal. A page whose renderer/main thread is wedged makes
|
|
8362
9400
|
* `page.goto`/`page.reload` hang until the subprocess times out, and the SAME
|
|
@@ -8627,10 +9665,182 @@ async function runEgoScript(subprocess, script, exec, cfg, graceOverrideMs) {
|
|
|
8627
9665
|
* the panel.
|
|
8628
9666
|
*/
|
|
8629
9667
|
const CLI_FRAME_MAX_BYTES = 12 * 1024 * 1024;
|
|
9668
|
+
let lastCliFrameDiag = null;
|
|
9669
|
+
/** @internal last ego-cli frame capture diagnostic (null until one runs). */
|
|
9670
|
+
function getCliFrameDiag() {
|
|
9671
|
+
return lastCliFrameDiag;
|
|
9672
|
+
}
|
|
9673
|
+
/**
|
|
9674
|
+
* Which task space a host-initiated ego-cli script should drive.
|
|
9675
|
+
*
|
|
9676
|
+
* Both the passive frame poller and the panel actions (size sync / navigate)
|
|
9677
|
+
* must observe the SAME space the calling session's tools act on, so the rule
|
|
9678
|
+
* lives in one place: use the tracker's last active space, and when it lagged
|
|
9679
|
+
* (no tool has run yet in this session) derive the per-session namespace
|
|
9680
|
+
* `dsh-agent-<sid8>` from the persisted current session. A global/unknown
|
|
9681
|
+
* session yields null: the caller then skips rather than binding the shared
|
|
9682
|
+
* `default` slot.
|
|
9683
|
+
* @internal exported for tests
|
|
9684
|
+
*/
|
|
9685
|
+
function resolveCliPanelSpace(cfg, space) {
|
|
9686
|
+
let next = space ?? cfg.spaceTracker.lastActiveSpace();
|
|
9687
|
+
if (next === null || next === void 0 || next === "") {
|
|
9688
|
+
const sid = cfg.spaceTracker.currentSession();
|
|
9689
|
+
if (sid !== void 0 && sid !== "" && sid !== GLOBAL_SESSION_KEY) next = deriveSlotDefaultName({
|
|
9690
|
+
defaultSpace: cfg.defaultSpace,
|
|
9691
|
+
isolateSpaces: cfg.isolateSpaces
|
|
9692
|
+
}, sid);
|
|
9693
|
+
}
|
|
9694
|
+
return next === null || next === void 0 || next === "" ? null : next;
|
|
9695
|
+
}
|
|
9696
|
+
/**
|
|
9697
|
+
* ego-cli panel actions (size sync / presets / maximize / refresh / URL).
|
|
9698
|
+
*
|
|
9699
|
+
* The CDP-worker route answers /api/window-size + /api/navigate natively; an
|
|
9700
|
+
* `ego-cli` link injects no websocket, so the same two operations run as short
|
|
9701
|
+
* heredocs on the exact channel real tools use (see cast/panel-actions.ts).
|
|
9702
|
+
* Serialized behind the plugin lock so a drag never races a tool call, and the
|
|
9703
|
+
* poller (which skips while busy) cannot screenshot a half-resized window.
|
|
9704
|
+
*/
|
|
9705
|
+
function makePanelActions(ctx, cfg) {
|
|
9706
|
+
const run = (build) => {
|
|
9707
|
+
const space = resolveCliPanelSpace(cfg);
|
|
9708
|
+
if (space === null) return Promise.resolve({
|
|
9709
|
+
ok: false,
|
|
9710
|
+
error: "no agent browser page yet — run a bcdp_* tool to open one first"
|
|
9711
|
+
});
|
|
9712
|
+
const script = build(j(space));
|
|
9713
|
+
return withEgoLock(async () => {
|
|
9714
|
+
const result = await runEgoScript(ctx.subprocess, script, {}, cfg);
|
|
9715
|
+
const parsed = parsePanelResult(mergeCliOutput({
|
|
9716
|
+
stdout: result.stdout ?? "",
|
|
9717
|
+
stderr: result.stderr ?? ""
|
|
9718
|
+
}));
|
|
9719
|
+
if (parsed !== null) return parsed;
|
|
9720
|
+
return {
|
|
9721
|
+
ok: false,
|
|
9722
|
+
error: result.error ?? "panel action produced no result (ego-cli sentinel missing)"
|
|
9723
|
+
};
|
|
9724
|
+
});
|
|
9725
|
+
};
|
|
9726
|
+
return {
|
|
9727
|
+
windowSize: (body) => run((spaceJson) => buildEgoWindowSizeScript(spaceJson, body)),
|
|
9728
|
+
navigate: (body) => run((spaceJson) => buildEgoNavigateScript(spaceJson, body)),
|
|
9729
|
+
switchTab: (body) => run((spaceJson) => buildEgoSwitchTabScript(spaceJson, body))
|
|
9730
|
+
};
|
|
9731
|
+
}
|
|
9732
|
+
/**
|
|
9733
|
+
* Tabbit's available tabs, for the panel's shared tab bucket.
|
|
9734
|
+
*
|
|
9735
|
+
* The 3s inventory poller already caches them (`_tabbitTabCache`); the watch
|
|
9736
|
+
* panel had no idea they existed, so a Tabbit session showed an empty strip and
|
|
9737
|
+
* nothing to @-quote. Rows use the CLI's `tabId` as targetId so a quote can be
|
|
9738
|
+
* traced back to the exact tab.
|
|
9739
|
+
*/
|
|
9740
|
+
function tabbitSpaceRows() {
|
|
9741
|
+
const updatedAt = _tabbitTabCache.updatedAt;
|
|
9742
|
+
return {
|
|
9743
|
+
tabs: _tabbitTabCache.tabs.map((t) => ({
|
|
9744
|
+
targetId: String(t.tabId),
|
|
9745
|
+
url: t.url || "",
|
|
9746
|
+
title: t.title || "",
|
|
9747
|
+
active: t.active === true,
|
|
9748
|
+
lastActive: updatedAt
|
|
9749
|
+
})),
|
|
9750
|
+
updatedAt,
|
|
9751
|
+
complete: _tabbitTabCache.complete
|
|
9752
|
+
};
|
|
9753
|
+
}
|
|
9754
|
+
/** Error carrying the envelope code the gateway maps to a status. */
|
|
9755
|
+
function codedError(code, message) {
|
|
9756
|
+
return Object.assign(new Error(message), { code });
|
|
9757
|
+
}
|
|
9758
|
+
/**
|
|
9759
|
+
* Tab-anchor report for the routes that own no CDP websocket.
|
|
9760
|
+
*
|
|
9761
|
+
* The CDP route reads the Accessibility tree over a socket; ego-cli and Tabbit
|
|
9762
|
+
* cannot, so both collect interactive candidates with the SAME in-page DOM scan
|
|
9763
|
+
* (`cast/fallback-tab-report.ts`) and hand them to the CDP path's own numbering
|
|
9764
|
+
* + anchor helpers. A route that cannot read the page at all still returns a
|
|
9765
|
+
* URL+title report marked degraded — an @ object with no elements beats a 409.
|
|
9766
|
+
*/
|
|
9767
|
+
function makeFallbackTabReport(ctx, cfg) {
|
|
9768
|
+
return async (input) => {
|
|
9769
|
+
const { effective } = effectiveChannel(cfg);
|
|
9770
|
+
const kind = effective?.link.kind;
|
|
9771
|
+
if (kind === TABBIT_CLI_KIND) {
|
|
9772
|
+
const cli = resolveTabbitCli((effective?.link)?.cliPath);
|
|
9773
|
+
if (!cli.found) throw codedError("cli-not-found", `tabbit-cli not found: ${cli.error}`);
|
|
9774
|
+
const tabId = Number(input.targetId);
|
|
9775
|
+
const { receipt } = await runTabbitSnippet(ctx.subprocess, buildTabbitAxSnippet(), {
|
|
9776
|
+
cliPath: cli.cliPath,
|
|
9777
|
+
taskName: _tabbitLastTaskName || "dsh-browser-cdp",
|
|
9778
|
+
requestId: `anchor-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
|
|
9779
|
+
timeoutMs: 12e4,
|
|
9780
|
+
...Number.isFinite(tabId) && tabId > 0 ? { tabId } : {}
|
|
9781
|
+
});
|
|
9782
|
+
if (!receipt.ok) return composeFallbackReport({
|
|
9783
|
+
route: "tabbit-cli",
|
|
9784
|
+
targetId: input.targetId,
|
|
9785
|
+
degraded: "tabbit-cli",
|
|
9786
|
+
snapshot: {
|
|
9787
|
+
url: input.urlHint,
|
|
9788
|
+
title: input.titleHint,
|
|
9789
|
+
targetId: input.targetId,
|
|
9790
|
+
nodes: []
|
|
9791
|
+
}
|
|
9792
|
+
});
|
|
9793
|
+
const data = receipt.data || {};
|
|
9794
|
+
const snapshot = {
|
|
9795
|
+
url: str(data.url, input.urlHint),
|
|
9796
|
+
title: str(data.title, input.titleHint),
|
|
9797
|
+
targetId: input.targetId,
|
|
9798
|
+
nodes: Array.isArray(data.nodes) ? data.nodes : []
|
|
9799
|
+
};
|
|
9800
|
+
return composeFallbackReport({
|
|
9801
|
+
route: "tabbit-cli",
|
|
9802
|
+
targetId: input.targetId,
|
|
9803
|
+
snapshot
|
|
9804
|
+
});
|
|
9805
|
+
}
|
|
9806
|
+
if (kind === EGO_CLI_KIND) {
|
|
9807
|
+
const space = resolveCliPanelSpace(cfg);
|
|
9808
|
+
if (space === null) throw codedError("attach-not-ready", "no agent browser space yet — open a page with a bcdp_* tool first");
|
|
9809
|
+
const result = await withEgoLock(() => runEgoScript(ctx.subprocess, buildEgoAxScript(j(space)), {}, cfg));
|
|
9810
|
+
const parsed = parseAxSentinel(mergeCliOutput({
|
|
9811
|
+
stdout: result.stdout ?? "",
|
|
9812
|
+
stderr: result.stderr ?? ""
|
|
9813
|
+
}));
|
|
9814
|
+
if (parsed === null || parsed.ok !== true) return composeFallbackReport({
|
|
9815
|
+
route: "ego-cli",
|
|
9816
|
+
targetId: input.targetId,
|
|
9817
|
+
degraded: "ego-cli",
|
|
9818
|
+
snapshot: {
|
|
9819
|
+
url: input.urlHint,
|
|
9820
|
+
title: input.titleHint,
|
|
9821
|
+
targetId: input.targetId,
|
|
9822
|
+
nodes: []
|
|
9823
|
+
}
|
|
9824
|
+
});
|
|
9825
|
+
return composeFallbackReport({
|
|
9826
|
+
route: "ego-cli",
|
|
9827
|
+
targetId: input.targetId,
|
|
9828
|
+
snapshot: {
|
|
9829
|
+
url: parsed.url ?? input.urlHint,
|
|
9830
|
+
title: parsed.title ?? input.titleHint,
|
|
9831
|
+
targetId: parsed.targetId || input.targetId,
|
|
9832
|
+
nodes: parsed.nodes ?? []
|
|
9833
|
+
}
|
|
9834
|
+
});
|
|
9835
|
+
}
|
|
9836
|
+
throw codedError("attach-not-ready", "no live CDP attach and no CLI fallback for this link kind");
|
|
9837
|
+
};
|
|
9838
|
+
}
|
|
8630
9839
|
async function spawnCliFrameCapture(subprocess, cfg, space) {
|
|
8631
|
-
|
|
9840
|
+
space = resolveCliPanelSpace(cfg, space);
|
|
9841
|
+
if (space === null) return "";
|
|
8632
9842
|
const { attach } = effectiveChannel(cfg);
|
|
8633
|
-
const script = buildFrameScript(j(space));
|
|
9843
|
+
const script = buildFrameScript(j(space), { all: getCliTrackAll(cfg.tabTracking === "all") });
|
|
8634
9844
|
try {
|
|
8635
9845
|
const handle = subprocess.spawn({
|
|
8636
9846
|
argv: buildEgoToolArgv(cfg.egoArgvPrefix, attach, cfg.runtimeArgs ?? ""),
|
|
@@ -8649,11 +9859,21 @@ async function spawnCliFrameCapture(subprocess, cfg, space) {
|
|
|
8649
9859
|
},
|
|
8650
9860
|
graceMs: cfg.graceMs
|
|
8651
9861
|
});
|
|
8652
|
-
|
|
8653
|
-
|
|
8654
|
-
|
|
8655
|
-
|
|
9862
|
+
const outcome = await handle.done;
|
|
9863
|
+
const stdout = readAll(handle.collected.stdout);
|
|
9864
|
+
const stderr = readAll(handle.collected.stderr);
|
|
9865
|
+
const merged = mergeCliOutput({
|
|
9866
|
+
stdout,
|
|
9867
|
+
stderr
|
|
8656
9868
|
});
|
|
9869
|
+
lastCliFrameDiag = {
|
|
9870
|
+
at: Date.now(),
|
|
9871
|
+
exitCode: typeof outcome.exitCode === "number" ? outcome.exitCode : null,
|
|
9872
|
+
stdoutLen: stdout.length,
|
|
9873
|
+
hasSentinel: merged.includes(FRAME_SENTINEL),
|
|
9874
|
+
stderrTail: stderr.slice(-300)
|
|
9875
|
+
};
|
|
9876
|
+
return merged;
|
|
8657
9877
|
} catch {
|
|
8658
9878
|
return "";
|
|
8659
9879
|
}
|
|
@@ -8678,15 +9898,15 @@ function toolPayload(result) {
|
|
|
8678
9898
|
}
|
|
8679
9899
|
/** JS snippet that pins an action tool to one task space. */
|
|
8680
9900
|
const useSpace = (name$1) => `const task = await taskSpaces.useOrCreate(${j(name$1)})\n`;
|
|
8681
|
-
/**
|
|
8682
|
-
|
|
8683
|
-
|
|
8684
|
-
|
|
8685
|
-
|
|
8686
|
-
|
|
8687
|
-
|
|
8688
|
-
|
|
8689
|
-
const ensureRealTab = () => "const __tabs = await browser.listTabs()\nconst __real = __tabs.find(t => !t.url.
|
|
9901
|
+
/** Viewport applied by `ensureRealTab()` for the current buildScript call. */
|
|
9902
|
+
let pendingViewport;
|
|
9903
|
+
const viewportPrelude = (spec) => {
|
|
9904
|
+
const width = Math.round(spec.viewportWidth ?? 0);
|
|
9905
|
+
const height = Math.round(spec.viewportHeight ?? 0);
|
|
9906
|
+
if (!(width > 0) || !(height > 0)) return "";
|
|
9907
|
+
return `if (__real) { try { await cdp('Emulation.setDeviceMetricsOverride', { width: ${width}, height: ${height}, deviceScaleFactor: ${spec.deviceScaleFactor !== void 0 && spec.deviceScaleFactor > 0 ? spec.deviceScaleFactor : 1}, mobile: false }) } catch {} }\n`;
|
|
9908
|
+
};
|
|
9909
|
+
const ensureRealTab = () => "const __tabs = await browser.listTabs()\nconst __blank = (u) => /^(about:|chrome:|chrome-extension:|edge:|devtools:|data:)/.test(String(u || ''))\nconst __real = __tabs.find(t => t.active === true && !__blank(t.url))\n ?? __tabs.find(t => !__blank(t.url))\n ?? __tabs.find(t => t.active === true)\n ?? __tabs[0]\nif (__real && __real.active !== true) await browser.switchTab(__real.targetId)\n" + (pendingViewport !== void 0 ? viewportPrelude(pendingViewport) : "");
|
|
8690
9910
|
/**
|
|
8691
9911
|
* G �?a raw heredoc (`bcdp_script` with verbatim:true) that touches `page.*` without
|
|
8692
9912
|
* first selecting a task space dies with the runtime's "no active tab to attach
|
|
@@ -8854,9 +10074,9 @@ async function tryTabbitExecute(ctx, cfg, toolName, args, taskName) {
|
|
|
8854
10074
|
ok: false,
|
|
8855
10075
|
text: "bcdp_navigate: url is required"
|
|
8856
10076
|
};
|
|
8857
|
-
const js = buildNavigateSnippet(url, str(args.waitUntil, "domcontentloaded"));
|
|
10077
|
+
const js$2 = buildNavigateSnippet(url, str(args.waitUntil, "domcontentloaded"));
|
|
8858
10078
|
const navTabId = typeof args.tab === "number" ? args.tab : void 0;
|
|
8859
|
-
const { receipt } = await runTabbitSnippet(sub, js, {
|
|
10079
|
+
const { receipt } = await runTabbitSnippet(sub, js$2, {
|
|
8860
10080
|
cliPath: cli.cliPath,
|
|
8861
10081
|
taskName,
|
|
8862
10082
|
requestId: reqId,
|
|
@@ -9029,6 +10249,7 @@ function defineEgoTool(ctx, cfg, opts) {
|
|
|
9029
10249
|
execute: async (args, exec) => withEgoLock(async () => {
|
|
9030
10250
|
cfg.spaceTracker.setCurrentSession(callingSessionId(exec), resolveEffectiveLink(cfg.links, cfg.activeTargetId)?.link.id ?? "");
|
|
9031
10251
|
markEgoToolCall(callingSessionId(exec));
|
|
10252
|
+
pendingViewport = cfg;
|
|
9032
10253
|
if (typeof opts.gate === "function") {
|
|
9033
10254
|
const blocked = opts.gate(args);
|
|
9034
10255
|
if (blocked !== null && blocked !== "") return {
|
|
@@ -9156,6 +10377,18 @@ function apply(ctx, config = {}) {
|
|
|
9156
10377
|
get cdpBackstopIntervalMs() {
|
|
9157
10378
|
return resolveConfig(bridge.source()).cdpBackstopIntervalMs;
|
|
9158
10379
|
},
|
|
10380
|
+
get tabTracking() {
|
|
10381
|
+
return resolveConfig(bridge.source()).tabTracking;
|
|
10382
|
+
},
|
|
10383
|
+
get viewportWidth() {
|
|
10384
|
+
return resolveConfig(bridge.source()).viewportWidth;
|
|
10385
|
+
},
|
|
10386
|
+
get viewportHeight() {
|
|
10387
|
+
return resolveConfig(bridge.source()).viewportHeight;
|
|
10388
|
+
},
|
|
10389
|
+
get deviceScaleFactor() {
|
|
10390
|
+
return resolveConfig(bridge.source()).deviceScaleFactor;
|
|
10391
|
+
},
|
|
9159
10392
|
get ffmpegFps() {
|
|
9160
10393
|
return resolveConfig(bridge.source()).ffmpegFps;
|
|
9161
10394
|
},
|
|
@@ -9430,7 +10663,19 @@ function apply(ctx, config = {}) {
|
|
|
9430
10663
|
intervalMs: 3e3,
|
|
9431
10664
|
capture: () => spawnCliFrameCapture(ctx.subprocess, cfg, cfg.spaceTracker.lastActiveSpace()),
|
|
9432
10665
|
isBusy: egoLockBusy,
|
|
9433
|
-
onFrame: (frame) =>
|
|
10666
|
+
onFrame: (frame) => broadcastCliFrames(frame.frames.map((f) => ({
|
|
10667
|
+
targetId: f.targetId,
|
|
10668
|
+
png: f.png,
|
|
10669
|
+
fmt: f.fmt,
|
|
10670
|
+
url: f.url,
|
|
10671
|
+
title: f.title
|
|
10672
|
+
})), frame.tabs.length > 0 ? frame.tabs.map((t) => ({
|
|
10673
|
+
targetId: t.targetId,
|
|
10674
|
+
url: t.url,
|
|
10675
|
+
title: t.title,
|
|
10676
|
+
active: t.active,
|
|
10677
|
+
lastActive: frame.updatedAt
|
|
10678
|
+
})) : void 0, frame.updatedAt)
|
|
9434
10679
|
});
|
|
9435
10680
|
ctx.effect?.(() => () => cliPoller.stop());
|
|
9436
10681
|
const tabbitTabTimer = setInterval(async () => {
|
|
@@ -9460,9 +10705,9 @@ function apply(ctx, config = {}) {
|
|
|
9460
10705
|
tabbitFrameInFlight = true;
|
|
9461
10706
|
try {
|
|
9462
10707
|
const reqId = `frame-${Date.now()}`;
|
|
9463
|
-
const js = buildFrameCaptureSnippet(tabbitFramePath);
|
|
10708
|
+
const js$2 = buildFrameCaptureSnippet(tabbitFramePath);
|
|
9464
10709
|
const target = _tabbitLastActiveTabId ?? _tabbitTabCache.tabs.find((t) => t.active === true)?.tabId;
|
|
9465
|
-
const { receipt } = await runTabbitSnippet(ctx.subprocess, js, {
|
|
10710
|
+
const { receipt } = await runTabbitSnippet(ctx.subprocess, js$2, {
|
|
9466
10711
|
cliPath: cli.cliPath,
|
|
9467
10712
|
taskName: _tabbitLastTaskName,
|
|
9468
10713
|
requestId: reqId,
|
|
@@ -9488,7 +10733,7 @@ function apply(ctx, config = {}) {
|
|
|
9488
10733
|
seq: tabbitFrameSeq,
|
|
9489
10734
|
updatedAt: Date.now(),
|
|
9490
10735
|
fmt: "jpeg"
|
|
9491
|
-
});
|
|
10736
|
+
}, tabbitSpaceRows().tabs);
|
|
9492
10737
|
return;
|
|
9493
10738
|
}
|
|
9494
10739
|
if (receipt.ok) ctx.logger?.warn?.(`dsh-browser-cdp: tabbit frame receipt carried no path (status=${receipt.status}, data=${JSON.stringify(data ?? null).slice(0, 120)})`);
|
|
@@ -9573,26 +10818,29 @@ function apply(ctx, config = {}) {
|
|
|
9573
10818
|
});
|
|
9574
10819
|
ctx.inject?.(["webServer"], (wctx) => {
|
|
9575
10820
|
try {
|
|
9576
|
-
initCastServer(wctx, cfg, bridge, ffmpegManager, () => openAgentWindow(ctx, cfg), (opts) => importLoginCookies(opts, { subprocess: ctx.subprocess }), cliPoller);
|
|
10821
|
+
initCastServer(wctx, cfg, bridge, ffmpegManager, () => openAgentWindow(ctx, cfg), (opts) => importLoginCookies(opts, { subprocess: ctx.subprocess }), cliPoller, makePanelActions(ctx, cfg), () => tabbitSpaceRows());
|
|
9577
10822
|
} catch (err) {
|
|
9578
10823
|
ctx.logger?.warn?.(`dsh-browser-cdp: cast server init failed: ${err?.message ?? err}`);
|
|
9579
10824
|
}
|
|
9580
10825
|
try {
|
|
9581
|
-
registerEgoBrowserGateway(wctx, bridge, ffmpegManager, {
|
|
9582
|
-
|
|
9583
|
-
|
|
9584
|
-
|
|
9585
|
-
|
|
9586
|
-
|
|
9587
|
-
|
|
9588
|
-
|
|
10826
|
+
registerEgoBrowserGateway(wctx, bridge, ffmpegManager, {
|
|
10827
|
+
resolveDir: (sessionId) => {
|
|
10828
|
+
try {
|
|
10829
|
+
const registry = typeof ctx.get === "function" ? ctx.get("workspaceRegistry") : void 0;
|
|
10830
|
+
const workspaces = (registry ? registry.list() : []) ?? [];
|
|
10831
|
+
if (workspaces.length === 0) return void 0;
|
|
10832
|
+
if (sessionId) {
|
|
10833
|
+
const owned = workspaces.find((w) => w.sessionIds.includes(sessionId));
|
|
10834
|
+
if (owned) return owned.path + "/picks";
|
|
10835
|
+
}
|
|
10836
|
+
if (workspaces.length === 1) return workspaces[0].path + "/picks";
|
|
10837
|
+
return;
|
|
10838
|
+
} catch {
|
|
10839
|
+
return;
|
|
9589
10840
|
}
|
|
9590
|
-
|
|
9591
|
-
|
|
9592
|
-
|
|
9593
|
-
return;
|
|
9594
|
-
}
|
|
9595
|
-
} });
|
|
10841
|
+
},
|
|
10842
|
+
fallbackTabReport: makeFallbackTabReport(ctx, cfg)
|
|
10843
|
+
});
|
|
9596
10844
|
} catch (err) {
|
|
9597
10845
|
ctx.logger?.warn?.(`dsh-browser-cdp: capability gateway init failed: ${err?.message ?? err}`);
|
|
9598
10846
|
}
|
|
@@ -9719,6 +10967,7 @@ function registerEgoStatus(ctx, cfg, reg, tiers) {
|
|
|
9719
10967
|
timeoutMs: 15e3,
|
|
9720
10968
|
execute: async (_args, exec) => {
|
|
9721
10969
|
tiers.pulse(callingSessionId(exec));
|
|
10970
|
+
cfg.spaceTracker.setCurrentSession(callingSessionId(exec), resolveEffectiveLink(cfg.links, cfg.activeTargetId)?.link.id ?? "");
|
|
9722
10971
|
return withEgoLock(async () => {
|
|
9723
10972
|
try {
|
|
9724
10973
|
const { attach } = effectiveChannel(cfg);
|
|
@@ -10150,13 +11399,18 @@ function registerActionTools(ctx, cfg, reg) {
|
|
|
10150
11399
|
type: "string",
|
|
10151
11400
|
description: "Optional absolute output path for the PNG."
|
|
10152
11401
|
},
|
|
11402
|
+
hideCursor: {
|
|
11403
|
+
type: "boolean",
|
|
11404
|
+
description: "Hide the agent cursor overlay during capture (default true) so the PNG is clean."
|
|
11405
|
+
},
|
|
10153
11406
|
space: spaceParam
|
|
10154
11407
|
},
|
|
10155
11408
|
buildScript: (args) => {
|
|
10156
11409
|
const sel = str(args.selector, "");
|
|
10157
11410
|
const pth = str(args.path, "");
|
|
11411
|
+
const hideCursor = args.hideCursor !== false;
|
|
10158
11412
|
const shot = sel !== "" ? `await page.locator(${j(sel)}).screenshot(${pth ? `{ path: ${j(pth)} }` : ""})` : `await page.screenshot(${pth ? `{ path: ${j(pth)} }` : ""})`;
|
|
10159
|
-
return `${useSpace(str(args.space, cfg.activeSpace))}${ensureRealTab()}
|
|
11413
|
+
return `${useSpace(str(args.space, cfg.activeSpace))}${ensureRealTab()}${hideCursor ? `try { if (ego && ego.hideCursor) await ego.hideCursor() } catch {}\nawait new Promise(r => setTimeout(r, 60))\n` : ""}let path\ntry { path = ${shot} } finally { ${hideCursor ? `try { if (ego && ego.showCursor) await ego.showCursor() } catch {}` : ""} }\nconsole.log('${SENTINEL}' + JSON.stringify({ ok: true, path }))\n`;
|
|
10160
11414
|
}
|
|
10161
11415
|
}));
|
|
10162
11416
|
reg(t({
|
|
@@ -10652,6 +11906,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
|
|
|
10652
11906
|
execute: async (args, exec) => withEgoLock(async () => {
|
|
10653
11907
|
cfg.spaceTracker.setCurrentSession(callingSessionId(exec), resolveEffectiveLink(cfg.links, cfg.activeTargetId)?.link.id ?? "");
|
|
10654
11908
|
markEgoToolCall(callingSessionId(exec));
|
|
11909
|
+
pendingViewport = cfg;
|
|
10655
11910
|
const result = await runWithStaleSpaceRetry(ctx, cfg, { signal: exec?.signal }, () => humanCheckScript(str(args.space, cfg.activeSpace)));
|
|
10656
11911
|
if (!result.ok) return {
|
|
10657
11912
|
ok: false,
|
|
@@ -10677,6 +11932,101 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
|
|
|
10677
11932
|
rawInput: null
|
|
10678
11933
|
})
|
|
10679
11934
|
}));
|
|
11935
|
+
reg(defineTool({
|
|
11936
|
+
name: "bcdp_wait_for_human",
|
|
11937
|
+
description: "Block until a human clears a CAPTCHA / completes a login or 2FA on the page, and (optionally) until `selector` appears as the \"done\" signal. Say what you need in the conversation FIRST (\"solve it in the agent browser window, I will wait\"), then call this. Returns { needed, resolved, waitedMs, polls, detected, kind, url }. A timeout is NOT an error: resolved=false means \"still not done\" — report back and call again, or escalate with bcdp_space({op:\"handoff\"}) for a full takeover. This is a deliberate blocking poll, NOT an approval flow.",
|
|
11938
|
+
parameters: {
|
|
11939
|
+
space: {
|
|
11940
|
+
type: "string",
|
|
11941
|
+
description: "Task-space name or numeric id; defaults to the active space."
|
|
11942
|
+
},
|
|
11943
|
+
selector: {
|
|
11944
|
+
type: "string",
|
|
11945
|
+
description: "Optional CSS selector that signals completion (e.g. \".dashboard\"); the poll succeeds once the challenge is gone AND this element exists."
|
|
11946
|
+
},
|
|
11947
|
+
timeoutMs: {
|
|
11948
|
+
type: "number",
|
|
11949
|
+
description: "Max wait in ms (default 120000, capped at 300000)."
|
|
11950
|
+
},
|
|
11951
|
+
reason: {
|
|
11952
|
+
type: "string",
|
|
11953
|
+
description: "Short human-readable reason (shown in the tool card; not enforced)."
|
|
11954
|
+
}
|
|
11955
|
+
},
|
|
11956
|
+
output: {
|
|
11957
|
+
schema: {
|
|
11958
|
+
type: "object",
|
|
11959
|
+
additionalProperties: false,
|
|
11960
|
+
properties: {
|
|
11961
|
+
ok: {
|
|
11962
|
+
type: "boolean",
|
|
11963
|
+
required: true
|
|
11964
|
+
},
|
|
11965
|
+
needed: {
|
|
11966
|
+
type: "boolean",
|
|
11967
|
+
required: true
|
|
11968
|
+
},
|
|
11969
|
+
resolved: {
|
|
11970
|
+
type: "boolean",
|
|
11971
|
+
required: true
|
|
11972
|
+
},
|
|
11973
|
+
waitedMs: {
|
|
11974
|
+
type: "number",
|
|
11975
|
+
required: true
|
|
11976
|
+
},
|
|
11977
|
+
polls: { type: "number" },
|
|
11978
|
+
detected: { type: "boolean" },
|
|
11979
|
+
kind: { oneOf: [{ type: "string" }, { type: "null" }] },
|
|
11980
|
+
url: { oneOf: [{ type: "string" }, { type: "null" }] },
|
|
11981
|
+
hint: { type: "string" }
|
|
11982
|
+
}
|
|
11983
|
+
},
|
|
11984
|
+
render: renderText
|
|
11985
|
+
},
|
|
11986
|
+
timeoutMs: 32e4,
|
|
11987
|
+
execute: async (args, exec) => withEgoLock(async () => {
|
|
11988
|
+
cfg.spaceTracker.setCurrentSession(callingSessionId(exec), resolveEffectiveLink(cfg.links, cfg.activeTargetId)?.link.id ?? "");
|
|
11989
|
+
markEgoToolCall(callingSessionId(exec));
|
|
11990
|
+
pendingViewport = cfg;
|
|
11991
|
+
const timeoutMs = Math.max(1e3, Math.min(3e5, num(args.timeoutMs, 12e4)));
|
|
11992
|
+
const selector = str(args.selector, "");
|
|
11993
|
+
const result = await runWithStaleSpaceRetry(ctx, cfg, { signal: exec?.signal }, () => waitForHumanScript(str(args.space, cfg.activeSpace), {
|
|
11994
|
+
timeoutMs,
|
|
11995
|
+
selector
|
|
11996
|
+
}));
|
|
11997
|
+
if (!result.ok) return {
|
|
11998
|
+
ok: false,
|
|
11999
|
+
needed: false,
|
|
12000
|
+
resolved: false,
|
|
12001
|
+
waitedMs: 0,
|
|
12002
|
+
polls: 0,
|
|
12003
|
+
error: result.error,
|
|
12004
|
+
hint: "the wait call failed before polling; retry once"
|
|
12005
|
+
};
|
|
12006
|
+
const p = parseSentinel(mergeCliOutput(result)) || {};
|
|
12007
|
+
const resolved = !!p.resolved;
|
|
12008
|
+
return {
|
|
12009
|
+
ok: true,
|
|
12010
|
+
needed: !!p.needed,
|
|
12011
|
+
resolved,
|
|
12012
|
+
waitedMs: typeof p.waitedMs === "number" ? p.waitedMs : 0,
|
|
12013
|
+
polls: typeof p.polls === "number" ? p.polls : 0,
|
|
12014
|
+
detected: !!p.detected,
|
|
12015
|
+
kind: p.kind ?? null,
|
|
12016
|
+
url: p.url ?? null,
|
|
12017
|
+
hint: resolved ? "human cleared the challenge; continue with the task" : "still waiting — ask the user again, call bcdp_wait_for_human again, or use bcdp_space op=handoff for a full takeover"
|
|
12018
|
+
};
|
|
12019
|
+
}),
|
|
12020
|
+
presentCall: (args) => {
|
|
12021
|
+
const r = str(args?.reason, "");
|
|
12022
|
+
return {
|
|
12023
|
+
card: "generic",
|
|
12024
|
+
title: r ? `bcdp_wait_for_human — ${r}` : "bcdp_wait_for_human",
|
|
12025
|
+
kind: "other",
|
|
12026
|
+
rawInput: null
|
|
12027
|
+
};
|
|
12028
|
+
}
|
|
12029
|
+
}));
|
|
10680
12030
|
reg(defineTool({
|
|
10681
12031
|
name: "bcdp_help",
|
|
10682
12032
|
description: "Query the built-in ego-browser tool guide. `topic` may be a category (overview/tools/navigate/observe/input/keyboard-mouse/form/wait/network/login/script/doctor) or a specific tool name (e.g. bcdp_click). Returns the matching usage notes. Call this when unsure which eyebrow tool to use. If a bcdp_* tool is missing from your list, ask topic=injection.",
|
|
@@ -10748,6 +12098,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
|
|
|
10748
12098
|
timeoutMs: 25e3,
|
|
10749
12099
|
execute: async (_args, exec) => {
|
|
10750
12100
|
tiers.pulse(callingSessionId(exec));
|
|
12101
|
+
cfg.spaceTracker.setCurrentSession(callingSessionId(exec), resolveEffectiveLink(cfg.links, cfg.activeTargetId)?.link.id ?? "");
|
|
10751
12102
|
const lines = [];
|
|
10752
12103
|
{
|
|
10753
12104
|
const s = tiers.surface();
|
|
@@ -10779,6 +12130,10 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
|
|
|
10779
12130
|
const cliPoll = getCliPollStatus();
|
|
10780
12131
|
const frameSource = getAttachEndpoint() ? "screencast (CDP)" : cliPoll.running ? `cli-poll (3s interval, seq ${cliPoll.frameSeq}${cliPoll.lastFrameAgeMs !== null ? `, last frame ${cliPoll.lastFrameAgeMs}ms ago` : ", no frame yet"})` : cfg.cliFramePollEnabled === false ? "none (cliFramePollEnabled off)" : "none";
|
|
10781
12132
|
lines.push(`frame source: ${frameSource}`);
|
|
12133
|
+
{
|
|
12134
|
+
const d = getCliFrameDiag();
|
|
12135
|
+
if (d !== null) lines.push(`last frame try: exit=${d.exitCode ?? "n/a"} stdout=${d.stdoutLen}B sentinel=${d.hasSentinel}${d.stderrTail !== "" ? ` stderr=${JSON.stringify(d.stderrTail)}` : ""}`);
|
|
12136
|
+
}
|
|
10782
12137
|
{
|
|
10783
12138
|
const sid = callingSessionId(exec);
|
|
10784
12139
|
const pollSpace = cfg.spaceTracker.lastActiveSpace();
|
|
@@ -10910,6 +12265,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
|
|
|
10910
12265
|
execute: async (args, exec) => {
|
|
10911
12266
|
cfg.spaceTracker.setCurrentSession(callingSessionId(exec), resolveEffectiveLink(cfg.links, cfg.activeTargetId)?.link.id ?? "");
|
|
10912
12267
|
markEgoToolCall(callingSessionId(exec));
|
|
12268
|
+
pendingViewport = cfg;
|
|
10913
12269
|
const timeoutMs = typeof args.timeoutMs === "number" && Number.isFinite(args.timeoutMs) && args.timeoutMs > 0 ? args.timeoutMs : void 0;
|
|
10914
12270
|
const start = Date.now();
|
|
10915
12271
|
const verbatimMode = bool(args.verbatim, false);
|
|
@@ -11044,6 +12400,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
|
|
|
11044
12400
|
execute: async (_args, exec) => {
|
|
11045
12401
|
cfg.spaceTracker.setCurrentSession(callingSessionId(exec), resolveEffectiveLink(cfg.links, cfg.activeTargetId)?.link.id ?? "");
|
|
11046
12402
|
markEgoToolCall(callingSessionId(exec));
|
|
12403
|
+
pendingViewport = cfg;
|
|
11047
12404
|
const judge = judgeCfg();
|
|
11048
12405
|
const runtime = judgeRuntimeOf();
|
|
11049
12406
|
const { attach } = effectiveChannel(cfg);
|
|
@@ -11144,6 +12501,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
|
|
|
11144
12501
|
execute: async (args, exec) => {
|
|
11145
12502
|
cfg.spaceTracker.setCurrentSession(callingSessionId(exec), resolveEffectiveLink(cfg.links, cfg.activeTargetId)?.link.id ?? "");
|
|
11146
12503
|
markEgoToolCall(callingSessionId(exec));
|
|
12504
|
+
pendingViewport = cfg;
|
|
11147
12505
|
const blocked = attachGate();
|
|
11148
12506
|
if (blocked !== "") return {
|
|
11149
12507
|
ok: false,
|
|
@@ -11283,6 +12641,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
|
|
|
11283
12641
|
execute: async (args, exec) => {
|
|
11284
12642
|
cfg.spaceTracker.setCurrentSession(callingSessionId(exec), resolveEffectiveLink(cfg.links, cfg.activeTargetId)?.link.id ?? "");
|
|
11285
12643
|
markEgoToolCall(callingSessionId(exec));
|
|
12644
|
+
pendingViewport = cfg;
|
|
11286
12645
|
const blocked = attachGate();
|
|
11287
12646
|
if (blocked !== "") return {
|
|
11288
12647
|
ok: false,
|
|
@@ -11393,6 +12752,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
|
|
|
11393
12752
|
execute: async (args, exec) => {
|
|
11394
12753
|
cfg.spaceTracker.setCurrentSession(callingSessionId(exec), resolveEffectiveLink(cfg.links, cfg.activeTargetId)?.link.id ?? "");
|
|
11395
12754
|
markEgoToolCall(callingSessionId(exec));
|
|
12755
|
+
pendingViewport = cfg;
|
|
11396
12756
|
const blocked = attachGate();
|
|
11397
12757
|
if (blocked !== "") return {
|
|
11398
12758
|
ok: false,
|
|
@@ -11491,6 +12851,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
|
|
|
11491
12851
|
execute: async (args, exec) => {
|
|
11492
12852
|
cfg.spaceTracker.setCurrentSession(callingSessionId(exec), resolveEffectiveLink(cfg.links, cfg.activeTargetId)?.link.id ?? "");
|
|
11493
12853
|
markEgoToolCall(callingSessionId(exec));
|
|
12854
|
+
pendingViewport = cfg;
|
|
11494
12855
|
const blocked = attachGate();
|
|
11495
12856
|
if (blocked !== "") return {
|
|
11496
12857
|
ok: false,
|
|
@@ -11556,4 +12917,4 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
|
|
|
11556
12917
|
}
|
|
11557
12918
|
|
|
11558
12919
|
//#endregion
|
|
11559
|
-
export { ATTACH_SESSION_HINT, CDP_CONNECT_FAIL_RE, Config, GLOBAL_SESSION_KEY, STATUS_FACADE_SCRIPT, STATUS_FACADE_SENTINEL, TAB_STUCK_RE, apply, attachSessionHint, buildEgoToolArgv, cdpAttachError, createActiveSpaceTracker, createSessionSpaceTracker, decideCdpAttach, deriveSlotDefaultName, effectiveChannel, egoLockBusy, findChromeBinary, findUpstreamPluginInstall, inject, isTabStuckFailure, name, parseSentinel, parseStatusFacades, resolveEgoEnv, runWithStaleSpaceRetry, runWithTabRevive, sessionSpaceToken, shouldReapBrowser };
|
|
12920
|
+
export { ATTACH_SESSION_HINT, CDP_CONNECT_FAIL_RE, Config, GLOBAL_SESSION_KEY, STATUS_FACADE_SCRIPT, STATUS_FACADE_SENTINEL, TAB_STUCK_RE, apply, attachSessionHint, buildEgoToolArgv, cdpAttachError, createActiveSpaceTracker, createSessionSpaceTracker, decideCdpAttach, deriveSlotDefaultName, effectiveChannel, egoLockBusy, findChromeBinary, findUpstreamPluginInstall, getCliFrameDiag, inject, isTabStuckFailure, name, parseSentinel, parseStatusFacades, resolveCliPanelSpace, resolveEgoEnv, runWithStaleSpaceRetry, runWithTabRevive, sessionSpaceToken, shouldReapBrowser, tabbitSpaceRows, waitForHumanScript };
|