dsh-browser-cdp 1.7.12 → 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 +26 -11
- 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 +779 -32
- package/lib/index.js +1527 -659
- 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 +16 -2
- 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
|
};
|
|
@@ -2900,520 +3135,208 @@ var CliFramePoller = class {
|
|
|
2900
3135
|
}
|
|
2901
3136
|
};
|
|
2902
3137
|
/**
|
|
2903
|
-
* The capture heredoc.
|
|
2904
|
-
*
|
|
2905
|
-
*
|
|
2906
|
-
*
|
|
2907
|
-
*
|
|
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.
|
|
2908
3159
|
*/
|
|
2909
|
-
function buildFrameScript(spaceJson) {
|
|
2910
|
-
|
|
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`;
|
|
2911
3164
|
}
|
|
2912
3165
|
|
|
2913
3166
|
//#endregion
|
|
2914
|
-
//#region src/
|
|
2915
|
-
|
|
2916
|
-
|
|
2917
|
-
|
|
2918
|
-
|
|
2919
|
-
|
|
2920
|
-
const
|
|
2921
|
-
|
|
2922
|
-
|
|
2923
|
-
"
|
|
2924
|
-
|
|
2925
|
-
|
|
2926
|
-
"
|
|
2927
|
-
"
|
|
2928
|
-
|
|
2929
|
-
|
|
2930
|
-
|
|
2931
|
-
|
|
2932
|
-
|
|
2933
|
-
const
|
|
2934
|
-
"auto",
|
|
2935
|
-
"software",
|
|
2936
|
-
"h264_mf",
|
|
2937
|
-
"h264_nvenc",
|
|
2938
|
-
"h264_qsv",
|
|
2939
|
-
"h264_amf",
|
|
2940
|
-
"h264_videotoolbox",
|
|
2941
|
-
"h264_vaapi"
|
|
2942
|
-
]);
|
|
2943
|
-
const Config$1 = z.object({
|
|
2944
|
-
isolateSpaces: z.boolean().description("Space isolation: false = persistent profile (keep logins across restarts); true = isolated sandbox.").volatile(),
|
|
2945
|
-
defaultSpace: z.string().description("Task space used when an bcdp_* call omits `space`. Default `:auto` = derive a per-session space `dsh-agent-<sessionId8>`, so concurrent sessions never share or hijack each other's browsing context. Set a fixed name (e.g. `default`) to reuse ONE shared slot across sessions — pass `space: \"default\"` on a single call for the same effect. Note this only names spaces; whether the browser profile itself persists is controlled by isolateSpaces.").volatile(),
|
|
2946
|
-
idleTimeoutMin: z.number().min(0).max(1440).step(1).description("Auto-stop the backing browser after N minutes without an bcdp_* call (0 = off). Relaunches on demand at the next call.").volatile(),
|
|
2947
|
-
chromePath: z.string().description("Path to Chrome/Chromium. Empty = auto-detect.").volatile(),
|
|
2948
|
-
captureBackend: backend.description("Capture backend: auto, cdp, or ffmpeg.").volatile(),
|
|
2949
|
-
streamProfile: profile.description("Capture quality profile.").volatile(),
|
|
2950
|
-
cdpFps: z.number().min(5).max(30).step(1).description("CDP preview FPS.").volatile(),
|
|
2951
|
-
cdpQuality: z.number().min(1).max(100).step(1).description("CDP JPEG quality.").volatile(),
|
|
2952
|
-
cdpMaxWidth: z.number().min(320).max(1920).step(40).description("CDP frame max width.").volatile(),
|
|
2953
|
-
cdpBackstopIntervalMs: z.number().min(1e3).max(1e4).step(100).description("CDP recovery screenshot interval.").volatile(),
|
|
2954
|
-
ffmpegFps: z.number().min(5).max(30).step(1).description("FFmpeg video FPS.").volatile(),
|
|
2955
|
-
ffmpegMaxWidth: z.number().min(320).max(1920).step(40).description("FFmpeg video max width.").volatile(),
|
|
2956
|
-
ffmpegBitrateKbps: z.number().min(500).max(2e4).step(250).description("FFmpeg target video bitrate in kbps.").volatile(),
|
|
2957
|
-
ffmpegEncoder: encoder.description("FFmpeg H.264 encoder.").volatile(),
|
|
2958
|
-
ffmpegPath: z.string().description("Custom FFmpeg path. Empty = detect PATH or managed install.").volatile(),
|
|
2959
|
-
githubMirror: z.string().description("HTTPS base replacing https://github.com for managed downloads.").volatile(),
|
|
2960
|
-
runtimeArgs: z.string().description("Extra args appended to the vendored runtime argv. Takes effect on the next bcdp_* call.").volatile(),
|
|
2961
|
-
chromeArgs: z.string().description("Extra args appended to the Chrome launch argv. Takes effect on the next browser cold start (the browser is a singleton).").volatile(),
|
|
2962
|
-
links: z.array(z.union([
|
|
2963
|
-
z.object({
|
|
2964
|
-
kind: z.string(),
|
|
2965
|
-
id: z.string(),
|
|
2966
|
-
label: z.string(),
|
|
2967
|
-
endpoint: z.string(),
|
|
2968
|
-
enabled: z.boolean(),
|
|
2969
|
-
note: z.string(),
|
|
2970
|
-
probeStatus: z.union([
|
|
2971
|
-
"unknown",
|
|
2972
|
-
"ok",
|
|
2973
|
-
"error"
|
|
2974
|
-
]),
|
|
2975
|
-
probeLatencyMs: z.number(),
|
|
2976
|
-
probeError: z.string(),
|
|
2977
|
-
probeCode: z.string(),
|
|
2978
|
-
probeAt: z.number(),
|
|
2979
|
-
probeEngine: z.union([
|
|
2980
|
-
"chrome",
|
|
2981
|
-
"lightpanda",
|
|
2982
|
-
"tabbit",
|
|
2983
|
-
"unknown"
|
|
2984
|
-
])
|
|
2985
|
-
}),
|
|
2986
|
-
z.object({
|
|
2987
|
-
kind: z.string(),
|
|
2988
|
-
id: z.string(),
|
|
2989
|
-
label: z.string(),
|
|
2990
|
-
cliPath: z.string(),
|
|
2991
|
-
useSdkPath: z.boolean().description("Deprecated: ALWAYS treated as true since v1.7.1-rc.5 — the native ego CLI has no taskSpaces facade, so without the bundled harness every call fails. Kept in the row shape so old profiles still validate; a stored false is healed on read."),
|
|
2992
|
-
enabled: z.boolean(),
|
|
2993
|
-
note: z.string(),
|
|
2994
|
-
probeStatus: z.union([
|
|
2995
|
-
"unknown",
|
|
2996
|
-
"ok",
|
|
2997
|
-
"error"
|
|
2998
|
-
]),
|
|
2999
|
-
probeLatencyMs: z.number(),
|
|
3000
|
-
probeError: z.string(),
|
|
3001
|
-
probeCode: z.string(),
|
|
3002
|
-
probeAt: z.number(),
|
|
3003
|
-
probeEngine: z.union([
|
|
3004
|
-
"chrome",
|
|
3005
|
-
"lightpanda",
|
|
3006
|
-
"tabbit",
|
|
3007
|
-
"unknown"
|
|
3008
|
-
])
|
|
3009
|
-
}),
|
|
3010
|
-
z.object({
|
|
3011
|
-
kind: z.string(),
|
|
3012
|
-
id: z.string(),
|
|
3013
|
-
label: z.string(),
|
|
3014
|
-
servePath: z.string(),
|
|
3015
|
-
enabled: z.boolean(),
|
|
3016
|
-
note: z.string(),
|
|
3017
|
-
probeStatus: z.union([
|
|
3018
|
-
"unknown",
|
|
3019
|
-
"ok",
|
|
3020
|
-
"error"
|
|
3021
|
-
]),
|
|
3022
|
-
probeLatencyMs: z.number(),
|
|
3023
|
-
probeError: z.string(),
|
|
3024
|
-
probeCode: z.string(),
|
|
3025
|
-
probeAt: z.number(),
|
|
3026
|
-
probeEngine: z.union([
|
|
3027
|
-
"chrome",
|
|
3028
|
-
"lightpanda",
|
|
3029
|
-
"tabbit",
|
|
3030
|
-
"unknown"
|
|
3031
|
-
])
|
|
3032
|
-
})
|
|
3033
|
-
])).description("Ordered connection sequence: CDP endpoints and (at most one) local ego CLI link. The ACTIVATED entry receives every bcdp_* call; if the activation points at a disabled or removed entry, the FIRST enabled link in this order takes over (logged and shown by bcdp_doctor). Order IS the priority order.").volatile(),
|
|
3034
|
-
activeTargetId: z.string().description("Id of the activated entry in links. Empty = nothing activated (no silent adoption). A disabled/removed entry here falls back to the first enabled link in order.").volatile(),
|
|
3035
|
-
cdpMode: cdpMode.description("auto = use the activated target and never start a local browser silently; remote = only ever connect to the activated target; local = always use local browser control.").volatile(),
|
|
3036
|
-
cdpProbeTimeoutMs: z.number().min(200).max(3e4).step(100).description("Timeout for one CDP endpoint probe (http endpoints answer /json/version)."),
|
|
3037
|
-
cursorHud: z.boolean().description("Draw the agent cursor HUD into screenshots."),
|
|
3038
|
-
cursorName: z.string().description("Name label shown in the cursor HUD."),
|
|
3039
|
-
allowLocalFallback: z.boolean().description("auto mode may fall back to launching a local browser when the activated target is unreachable. Off by default: the fallback must be explicit.").volatile(),
|
|
3040
|
-
legacyEgoToolNames: z.boolean().description("ALSO register the tools under their old ego_* names for scripts written before the bcdp_* rename. Off by default; mutually exclusive with installing the upstream ego-browser plugin (same tool names)."),
|
|
3041
|
-
toolInjection: toolInjection.default("lazy").description("lazy = keep only bcdp_status resident (it is the unlock entry: the rest are injected after the first bcdp_* activity, and the idle reaper seals them back); always = register every allowed tool at mount (the historical behaviour).").volatile(),
|
|
3042
|
-
toolBrowse: z.boolean().default(true).description("Basic browsing tiers — act + observe + wait (19 tools: space / navigate / click / fill / key / hover / scroll / select / check / drag / tab / help / doctor / screenshot / page_info / read_element / js / snapshot / wait). Internally released in three waves. Off = sealed: removed from the model tool list.").volatile(),
|
|
3043
|
-
toolExtended: z.boolean().default(true).description("Extended tiers — power + session (8 tools: raw CDP / http / upload / download / dialog / captcha / auth_flush / login_import). Off = sealed even after browser activity.").volatile(),
|
|
3044
|
-
toolEscape: z.boolean().default(true).description("Escape-hatch tier (1 tool: script — run an arbitrary heredoc with page/browser/taskSpaces/fetch/cdp preloaded; verbatim:true reproduces the old bare-heredoc cli behaviour). Sealed until browser activity like every other non-core tier: call bcdp_status first, then it appears. Off = sealed.").volatile(),
|
|
3045
|
-
toolJudge: z.boolean().default(true).description("Judgement tier (5 bcdp_jev_* tools). On still requires a JEV or Laya key: without one they can only answer \"not configured\", so they stay sealed anyway.").volatile(),
|
|
3046
|
-
sessionScopedPulse: z.boolean().default(true).description("Per-session unlock: when on, calling bcdp_status in session A only unlocks tools for session A — other sessions stay at their own depth. When off, any session's unlock is process-wide (historical behaviour). Falls back to off when the host does not expose agent-scoped tool restriction.").volatile(),
|
|
3047
|
-
localHeadless: z.boolean().description("Run the locally launched browser headless."),
|
|
3048
|
-
remoteEnabled: z.boolean().description("Master switch for REMOTE attach. Off = the configured target sequence is preserved but inert (nothing probes or connects remotely); flip back on any time. Does not affect cdpMode=local.").volatile(),
|
|
3049
|
-
allowProbeColdStart: z.boolean().description("Allow the ego-cli readiness probe to cold-start the backing browser. Off (default): the probe never launches the browser — when --status cannot prove the browser is already up, the heredoc round-trip is skipped and the browser starts on the first real bcdp_* call instead (no browser window at plugin startup). On: the probe verifies the SDK harness up front, which may launch the browser.").volatile(),
|
|
3050
|
-
cliFramePollEnabled: z.boolean().default(true).description("Degraded watch-panel frame source for the local ego-cli link: with no CDP screencast available, capture one viewport screenshot every 5s through the CLI channel and serve it to the panel. On (default): the poller runs while an ego-cli link owns routing. Off: the panel keeps its placeholder and no screenshot subprocess is spawned. Hot-applies without reloading the plugin.").volatile(),
|
|
3051
|
-
localUserDataDir: z.string().description("Profile dir for the locally launched browser. Empty = managed dir; never point at your daily Chrome profile."),
|
|
3052
|
-
lightpandaArgs: z.string().description("Extra args appended to a managed `lightpanda serve` argv. --host/--port are managed and cannot be overridden.").volatile(),
|
|
3053
|
-
castFpsCap: z.number().min(0).max(60).step(1),
|
|
3054
|
-
screencastQuality: z.number().min(1).max(100).step(1),
|
|
3055
|
-
screencastMaxWidth: z.number().min(320).max(1920).step(40),
|
|
3056
|
-
backstopIntervalMs: z.number().min(200).max(1e4).step(100),
|
|
3057
|
-
jevUrl: z.string().description("JEV judge base URL, no path. Leave EMPTY: JEV cannot currently be registered, so the hop would only ever be skipped. Add it (and jev to the hop order) when registration opens.").volatile(),
|
|
3058
|
-
jevKey: z.string().description("Bearer key for the JEV judge. Empty = the jev hop is skipped (never sent, so no 401 round trip).").volatile(),
|
|
3059
|
-
jevModel: z.string().description("Model name sent in the request body.").volatile(),
|
|
3060
|
-
layaUrl: z.string().description("Laya judge base URL. The sidecar serves 8000; 7789 is a different tool and will not answer.").volatile(),
|
|
3061
|
-
layaKey: z.string().description("Bearer key for the Laya judge. REQUIRED: laya-api has no anonymous branch, so a keyless call is a guaranteed 401.").volatile(),
|
|
3062
|
-
layaModel: z.string().description("Model name sent to the Laya judge.").volatile(),
|
|
3063
|
-
judgePrefer: z.string().description("Judgement hop order, comma separated. Defaults to \"laya,rule\" because JEV cannot currently be registered. Unknown names are dropped; the terminal refusal hop cannot be removed.").volatile(),
|
|
3064
|
-
jevChunkSize: z.number().min(1).max(255).step(1).description("Candidate ceiling per judgement round. Bound to the probability threshold bucket, so raising it also tightens the gate.").volatile(),
|
|
3065
|
-
jevMaxImageBytes: z.number().min(0).step(1024).description("Frame byte budget. 0 = unbounded, which is the measured default: a full-page JPEG was 137 KiB, so chunking for bytes alone slices static pages for nothing.").volatile(),
|
|
3066
|
-
jevHistoryLimit: z.number().min(0).max(20).step(1).description("How many recent steps the judge is shown. Recency beats completeness in a loop.").volatile(),
|
|
3067
|
-
jevArchiveImage: z.boolean().description("Embed the base64 screenshot in the archived Laya bundle. Off by default: a bundle that always carries hundreds of KiB is a bundle nobody keeps.").volatile(),
|
|
3068
|
-
jevEvaluate: z.boolean().description("After every action, ask the judge whether the step actually advanced: inprogress / done / fail. inprogress continues silently; done is checked against successCriteria; fail hands back to the model for recovery (reload, re-capture, ...). Costs one judgement call per action.").volatile(),
|
|
3069
|
-
jevStepBudget: z.number().min(1).max(200).step(1).description("Judgement rounds allowed in one bcdp_jev_run before it stops as exhausted.").volatile(),
|
|
3070
|
-
jevWallMs: z.number().min(1e3).max(36e5).step(1e3).description("Wall-clock ceiling for one bcdp_jev_run, in ms.").volatile()
|
|
3071
|
-
});
|
|
3072
|
-
/** True when the value is a live volatile reference rather than plain data. */
|
|
3073
|
-
function isVolatileRef(value) {
|
|
3074
|
-
return typeof value === "object" && value !== null && typeof value.get === "function";
|
|
3075
|
-
}
|
|
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@@";
|
|
3076
3187
|
/**
|
|
3077
|
-
*
|
|
3078
|
-
*
|
|
3079
|
-
* updates (no plugin remount), so every read path must deref before the
|
|
3080
|
-
* plain-value `typeof` gates in `resolveConfig` can see real data.
|
|
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.
|
|
3081
3190
|
*/
|
|
3082
|
-
|
|
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) {
|
|
3083
3198
|
const out = {};
|
|
3084
|
-
for (const
|
|
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
|
+
}
|
|
3085
3221
|
return out;
|
|
3086
3222
|
}
|
|
3087
3223
|
/**
|
|
3088
|
-
*
|
|
3089
|
-
*
|
|
3090
|
-
*
|
|
3091
|
-
* `--headless` is managed by EGO_LINUX_HEADLESS; `--sdk-path` is allowed.
|
|
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.
|
|
3092
3227
|
*/
|
|
3093
|
-
|
|
3094
|
-
"
|
|
3095
|
-
|
|
3096
|
-
|
|
3097
|
-
|
|
3098
|
-
|
|
3099
|
-
|
|
3100
|
-
|
|
3101
|
-
|
|
3102
|
-
|
|
3103
|
-
|
|
3104
|
-
|
|
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
|
+
}
|
|
3105
3248
|
/**
|
|
3106
|
-
*
|
|
3107
|
-
*
|
|
3108
|
-
*
|
|
3109
|
-
*
|
|
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.
|
|
3110
3256
|
*/
|
|
3111
|
-
|
|
3112
|
-
|
|
3113
|
-
|
|
3114
|
-
"--remote-allow-origins",
|
|
3115
|
-
"--headless",
|
|
3116
|
-
"--no-startup-window",
|
|
3117
|
-
"--proxy-server",
|
|
3118
|
-
"--proxy-bypass-list"
|
|
3119
|
-
]);
|
|
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
|
+
}
|
|
3120
3260
|
/**
|
|
3121
|
-
*
|
|
3122
|
-
*
|
|
3123
|
-
*
|
|
3124
|
-
*
|
|
3125
|
-
*
|
|
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.
|
|
3126
3267
|
*/
|
|
3127
|
-
function
|
|
3128
|
-
if (
|
|
3129
|
-
const out = [];
|
|
3130
|
-
let cur = "";
|
|
3131
|
-
let i = 0;
|
|
3132
|
-
let quote = null;
|
|
3133
|
-
while (i < input.length) {
|
|
3134
|
-
const c = input[i];
|
|
3135
|
-
if (quote) {
|
|
3136
|
-
if (c === "\\") {
|
|
3137
|
-
const next = input[i + 1];
|
|
3138
|
-
if (next !== void 0) {
|
|
3139
|
-
cur += next;
|
|
3140
|
-
i += 2;
|
|
3141
|
-
continue;
|
|
3142
|
-
}
|
|
3143
|
-
} else if (c === quote) {
|
|
3144
|
-
quote = null;
|
|
3145
|
-
i += 1;
|
|
3146
|
-
continue;
|
|
3147
|
-
}
|
|
3148
|
-
cur += c;
|
|
3149
|
-
i += 1;
|
|
3150
|
-
continue;
|
|
3151
|
-
}
|
|
3152
|
-
if (c === "\"" || c === "'") {
|
|
3153
|
-
quote = c;
|
|
3154
|
-
i += 1;
|
|
3155
|
-
continue;
|
|
3156
|
-
}
|
|
3157
|
-
if (c === "\\") {
|
|
3158
|
-
const next = input[i + 1];
|
|
3159
|
-
if (next !== void 0) {
|
|
3160
|
-
cur += next;
|
|
3161
|
-
i += 2;
|
|
3162
|
-
continue;
|
|
3163
|
-
}
|
|
3164
|
-
i += 1;
|
|
3165
|
-
continue;
|
|
3166
|
-
}
|
|
3167
|
-
if (c === " " || c === " " || c === "\n" || c === "\r") {
|
|
3168
|
-
if (cur !== "") {
|
|
3169
|
-
out.push(cur);
|
|
3170
|
-
cur = "";
|
|
3171
|
-
}
|
|
3172
|
-
i += 1;
|
|
3173
|
-
continue;
|
|
3174
|
-
}
|
|
3175
|
-
cur += c;
|
|
3176
|
-
i += 1;
|
|
3177
|
-
}
|
|
3178
|
-
if (cur !== "") out.push(cur);
|
|
3179
|
-
return out;
|
|
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`;
|
|
3180
3270
|
}
|
|
3181
3271
|
/**
|
|
3182
|
-
*
|
|
3183
|
-
*
|
|
3184
|
-
*
|
|
3185
|
-
* tokens. Exposed for tests and for the runtime to mirror.
|
|
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.
|
|
3186
3275
|
*/
|
|
3187
|
-
function
|
|
3188
|
-
const
|
|
3189
|
-
const kept = [];
|
|
3190
|
-
for (let i = 0; i < tokens.length; i++) {
|
|
3191
|
-
const tok = tokens[i];
|
|
3192
|
-
const key = tok.includes("=") ? tok.slice(0, tok.indexOf("=")) : tok;
|
|
3193
|
-
if (blocked.has(key)) {
|
|
3194
|
-
if (!tok.includes("=") && i + 1 < tokens.length && !tokens[i + 1].startsWith("-")) i += 1;
|
|
3195
|
-
continue;
|
|
3196
|
-
}
|
|
3197
|
-
kept.push(tok);
|
|
3198
|
-
}
|
|
3199
|
-
return kept;
|
|
3200
|
-
}
|
|
3201
|
-
const finiteIn = (value, min, max) => typeof value === "number" && Number.isFinite(value) && value >= min && value <= max;
|
|
3202
|
-
function oneOf(value, values, fallback) {
|
|
3203
|
-
return typeof value === "string" && values.includes(value) ? value : fallback;
|
|
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`;
|
|
3204
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;
|
|
3205
3286
|
/**
|
|
3206
|
-
*
|
|
3287
|
+
* Mint the anchor for one candidate inside one snapshot scope.
|
|
3207
3288
|
*
|
|
3208
|
-
*
|
|
3209
|
-
*
|
|
3210
|
-
*
|
|
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.
|
|
3211
3293
|
*/
|
|
3212
|
-
|
|
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
|
+
}
|
|
3213
3320
|
/**
|
|
3214
|
-
*
|
|
3321
|
+
* A stable frame id.
|
|
3215
3322
|
*
|
|
3216
|
-
*
|
|
3217
|
-
*
|
|
3218
|
-
*
|
|
3219
|
-
*
|
|
3220
|
-
* removed) lives in `src/jev/client.ts`, where it is unit-tested.
|
|
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.
|
|
3221
3327
|
*/
|
|
3222
|
-
function
|
|
3223
|
-
return {
|
|
3224
|
-
jevUrl: config.jevUrl,
|
|
3225
|
-
jevKey: config.jevKey,
|
|
3226
|
-
jevModel: config.jevModel,
|
|
3227
|
-
layaUrl: config.layaUrl,
|
|
3228
|
-
layaKey: config.layaKey,
|
|
3229
|
-
layaModel: config.layaModel,
|
|
3230
|
-
prefer: config.judgePrefer,
|
|
3231
|
-
chunkSize: config.jevChunkSize,
|
|
3232
|
-
maxImageBytes: config.jevMaxImageBytes,
|
|
3233
|
-
historyLimit: config.jevHistoryLimit,
|
|
3234
|
-
archiveImage: config.jevArchiveImage,
|
|
3235
|
-
evaluate: config.jevEvaluate,
|
|
3236
|
-
stepBudget: config.jevStepBudget,
|
|
3237
|
-
wallMs: config.jevWallMs
|
|
3238
|
-
};
|
|
3328
|
+
function frameIdFor(target, documentRevision, seq) {
|
|
3329
|
+
return createHash("sha256").update(`${target.targetId}\u0000${documentRevision}\u0000${seq}`).digest("hex").slice(0, 16);
|
|
3239
3330
|
}
|
|
3331
|
+
/** Default candidate cap. Matches the chunk ceiling — see THRESHOLD_BUCKETS. */
|
|
3332
|
+
const DEFAULT_NODE_LIMIT = 20;
|
|
3240
3333
|
/**
|
|
3241
|
-
*
|
|
3242
|
-
*
|
|
3243
|
-
*
|
|
3244
|
-
*
|
|
3245
|
-
|
|
3246
|
-
|
|
3247
|
-
function resolveConfig(config = {}) {
|
|
3248
|
-
config = derefVolatileConfig(config);
|
|
3249
|
-
const legacyFps = finiteIn(config.castFpsCap, 0, 60) ? config.castFpsCap === 0 ? 20 : Math.max(5, Math.min(30, config.castFpsCap)) : 20;
|
|
3250
|
-
const selectedProfile = oneOf(config.streamProfile, [
|
|
3251
|
-
"low",
|
|
3252
|
-
"balanced",
|
|
3253
|
-
"high"
|
|
3254
|
-
], "balanced");
|
|
3255
|
-
const profileDefaults = selectedProfile === "low" ? {
|
|
3256
|
-
fps: 15,
|
|
3257
|
-
width: 960,
|
|
3258
|
-
bitrateKbps: 2e3
|
|
3259
|
-
} : selectedProfile === "high" ? {
|
|
3260
|
-
fps: 30,
|
|
3261
|
-
width: 1600,
|
|
3262
|
-
bitrateKbps: 8e3
|
|
3263
|
-
} : {
|
|
3264
|
-
fps: 20,
|
|
3265
|
-
width: 1280,
|
|
3266
|
-
bitrateKbps: 4e3
|
|
3267
|
-
};
|
|
3268
|
-
return {
|
|
3269
|
-
chromePath: typeof config.chromePath === "string" ? config.chromePath : "",
|
|
3270
|
-
captureBackend: oneOf(config.captureBackend, [
|
|
3271
|
-
"auto",
|
|
3272
|
-
"cdp",
|
|
3273
|
-
"ffmpeg"
|
|
3274
|
-
], "auto"),
|
|
3275
|
-
streamProfile: selectedProfile,
|
|
3276
|
-
cdpFps: finiteIn(config.cdpFps, 5, 30) ? config.cdpFps : legacyFps,
|
|
3277
|
-
cdpQuality: finiteIn(config.cdpQuality, 1, 100) ? config.cdpQuality : finiteIn(config.screencastQuality, 1, 100) ? config.screencastQuality : 55,
|
|
3278
|
-
cdpMaxWidth: finiteIn(config.cdpMaxWidth, 320, 1920) ? config.cdpMaxWidth : finiteIn(config.screencastMaxWidth, 320, 1920) ? config.screencastMaxWidth : 960,
|
|
3279
|
-
cdpBackstopIntervalMs: finiteIn(config.cdpBackstopIntervalMs, 1e3, 1e4) ? config.cdpBackstopIntervalMs : finiteIn(config.backstopIntervalMs, 200, 1e4) ? Math.max(1e3, config.backstopIntervalMs) : 3e3,
|
|
3280
|
-
ffmpegFps: finiteIn(config.ffmpegFps, 5, 30) ? config.ffmpegFps : profileDefaults.fps,
|
|
3281
|
-
ffmpegMaxWidth: finiteIn(config.ffmpegMaxWidth, 320, 1920) ? config.ffmpegMaxWidth : profileDefaults.width,
|
|
3282
|
-
ffmpegBitrateKbps: finiteIn(config.ffmpegBitrateKbps, 500, 2e4) ? config.ffmpegBitrateKbps : profileDefaults.bitrateKbps,
|
|
3283
|
-
ffmpegEncoder: oneOf(config.ffmpegEncoder, [
|
|
3284
|
-
"auto",
|
|
3285
|
-
"software",
|
|
3286
|
-
"h264_mf",
|
|
3287
|
-
"h264_nvenc",
|
|
3288
|
-
"h264_qsv",
|
|
3289
|
-
"h264_amf",
|
|
3290
|
-
"h264_videotoolbox",
|
|
3291
|
-
"h264_vaapi"
|
|
3292
|
-
], "auto"),
|
|
3293
|
-
ffmpegPath: typeof config.ffmpegPath === "string" ? config.ffmpegPath : "",
|
|
3294
|
-
githubMirror: typeof config.githubMirror === "string" ? config.githubMirror : "",
|
|
3295
|
-
runtimeArgs: typeof config.runtimeArgs === "string" ? config.runtimeArgs : typeof config.egoCliArgs === "string" ? config.egoCliArgs : "",
|
|
3296
|
-
chromeArgs: typeof config.chromeArgs === "string" ? config.chromeArgs : "",
|
|
3297
|
-
isolateSpaces: typeof config.isolateSpaces === "boolean" ? config.isolateSpaces : config.isolateSpaces === "true" || config.isolateSpaces === "1" || config.isolateSpaces === 1,
|
|
3298
|
-
defaultSpace: typeof config.defaultSpace === "string" && config.defaultSpace.trim() !== "" ? config.defaultSpace.trim() : AUTO_SPACE_SENTINEL,
|
|
3299
|
-
idleTimeoutMin: finiteIn(config.idleTimeoutMin, 0, 1440) ? config.idleTimeoutMin : 0,
|
|
3300
|
-
links: sanitizeLinks(config.links ?? config.cdpTargets).links.map(normalizeProbeState),
|
|
3301
|
-
activeTargetId: typeof config.activeTargetId === "string" ? config.activeTargetId : "",
|
|
3302
|
-
cdpMode: oneOf(config.cdpMode, [
|
|
3303
|
-
"auto",
|
|
3304
|
-
"local",
|
|
3305
|
-
"remote"
|
|
3306
|
-
], "auto"),
|
|
3307
|
-
cdpProbeTimeoutMs: finiteIn(config.cdpProbeTimeoutMs, 200, 3e4) ? config.cdpProbeTimeoutMs : 3e3,
|
|
3308
|
-
cursorHud: config.cursorHud === void 0 ? true : Boolean(config.cursorHud),
|
|
3309
|
-
cursorName: typeof config.cursorName === "string" && config.cursorName.trim() !== "" ? config.cursorName : "DeepSeek",
|
|
3310
|
-
allowLocalFallback: config.allowLocalFallback === void 0 ? false : Boolean(config.allowLocalFallback),
|
|
3311
|
-
legacyEgoToolNames: Boolean(config.legacyEgoToolNames),
|
|
3312
|
-
toolInjection: oneOf(config.toolInjection, ["lazy", "always"], "lazy"),
|
|
3313
|
-
toolBrowse: tierOpenByDefault(config.toolBrowse),
|
|
3314
|
-
toolExtended: tierOpenByDefault(config.toolExtended),
|
|
3315
|
-
toolEscape: tierOpenByDefault(config.toolEscape),
|
|
3316
|
-
toolJudge: tierOpenByDefault(config.toolJudge),
|
|
3317
|
-
sessionScopedPulse: tierOpenByDefault(config.sessionScopedPulse),
|
|
3318
|
-
localHeadless: config.localHeadless === void 0 ? false : Boolean(config.localHeadless),
|
|
3319
|
-
localUserDataDir: typeof config.localUserDataDir === "string" ? config.localUserDataDir : "",
|
|
3320
|
-
lightpandaArgs: trimmed(config.lightpandaArgs),
|
|
3321
|
-
remoteEnabled: config.remoteEnabled === void 0 ? true : Boolean(config.remoteEnabled),
|
|
3322
|
-
allowProbeColdStart: config.allowProbeColdStart === true || config.allowProbeColdStart === "true",
|
|
3323
|
-
cliFramePollEnabled: config.cliFramePollEnabled !== false && config.cliFramePollEnabled !== "false",
|
|
3324
|
-
jevUrl: trimmed(config.jevUrl),
|
|
3325
|
-
jevKey: trimmed(config.jevKey),
|
|
3326
|
-
jevModel: trimmed(config.jevModel) === "" ? "jev" : trimmed(config.jevModel),
|
|
3327
|
-
layaUrl: trimmed(config.layaUrl) === "" ? "http://127.0.0.1:8000" : trimmed(config.layaUrl),
|
|
3328
|
-
layaKey: trimmed(config.layaKey),
|
|
3329
|
-
layaModel: trimmed(config.layaModel) === "" ? "laya" : trimmed(config.layaModel),
|
|
3330
|
-
judgePrefer: trimmed(config.judgePrefer) === "" ? "laya,rule" : trimmed(config.judgePrefer),
|
|
3331
|
-
jevChunkSize: finiteIn(config.jevChunkSize, 1, 255) ? config.jevChunkSize : 20,
|
|
3332
|
-
jevMaxImageBytes: finiteIn(config.jevMaxImageBytes, 0, 512 * 1024 * 1024) ? config.jevMaxImageBytes : 0,
|
|
3333
|
-
jevHistoryLimit: finiteIn(config.jevHistoryLimit, 0, 20) ? config.jevHistoryLimit : 5,
|
|
3334
|
-
jevArchiveImage: config.jevArchiveImage === void 0 ? false : Boolean(config.jevArchiveImage),
|
|
3335
|
-
jevEvaluate: config.jevEvaluate === void 0 ? true : Boolean(config.jevEvaluate),
|
|
3336
|
-
jevStepBudget: finiteIn(config.jevStepBudget, 1, 200) ? config.jevStepBudget : 20,
|
|
3337
|
-
jevWallMs: finiteIn(config.jevWallMs, 1e3, 36e5) ? config.jevWallMs : 12e4
|
|
3338
|
-
};
|
|
3339
|
-
}
|
|
3340
|
-
/**
|
|
3341
|
-
* Fill the per-link probe fields so downstream code (panel badge, doctor
|
|
3342
|
-
* output) can read them without a null-check ladder. Generic over the link
|
|
3343
|
-
* union so the discriminating `kind` (and every kind-specific field) survives.
|
|
3344
|
-
*/
|
|
3345
|
-
function normalizeProbeState(link) {
|
|
3346
|
-
return {
|
|
3347
|
-
...link,
|
|
3348
|
-
probeStatus: link.probeStatus === "ok" || link.probeStatus === "error" ? link.probeStatus : "unknown",
|
|
3349
|
-
probeLatencyMs: typeof link.probeLatencyMs === "number" && Number.isFinite(link.probeLatencyMs) ? link.probeLatencyMs : 0,
|
|
3350
|
-
probeError: typeof link.probeError === "string" ? link.probeError : "",
|
|
3351
|
-
probeCode: typeof link.probeCode === "string" ? link.probeCode : "",
|
|
3352
|
-
probeAt: typeof link.probeAt === "number" && Number.isFinite(link.probeAt) ? link.probeAt : 0,
|
|
3353
|
-
probeEngine: link.probeEngine === "chrome" || link.probeEngine === "lightpanda" || link.probeEngine === "tabbit" ? link.probeEngine : "unknown"
|
|
3354
|
-
};
|
|
3355
|
-
}
|
|
3356
|
-
|
|
3357
|
-
//#endregion
|
|
3358
|
-
//#region src/jev/anchors.ts
|
|
3359
|
-
/** Fixed prefix so an anchor is recognizable in a transcript at a glance. */
|
|
3360
|
-
const ANCHOR_PREFIX = "sb-";
|
|
3361
|
-
/** Hex length after the prefix — half a sha256, collision-safe for this use. */
|
|
3362
|
-
const ANCHOR_HEX = 16;
|
|
3363
|
-
/**
|
|
3364
|
-
* Mint the anchor for one candidate inside one snapshot scope.
|
|
3365
|
-
*
|
|
3366
|
-
* `scope` is the frame identity (`frame.frameId`) in the current pipeline; any
|
|
3367
|
-
* caller with a different snapshot notion passes its own scope string — the
|
|
3368
|
-
* function only demands that different snapshots produce different scope
|
|
3369
|
-
* strings, which is exactly what frameId guarantees.
|
|
3370
|
-
*/
|
|
3371
|
-
function anchorFor(scope, backendNodeId) {
|
|
3372
|
-
return `${ANCHOR_PREFIX}${createHash("sha256").update(`${scope}\0${backendNodeId}`).digest("hex").slice(0, ANCHOR_HEX)}`;
|
|
3373
|
-
}
|
|
3374
|
-
|
|
3375
|
-
//#endregion
|
|
3376
|
-
//#region src/jev/frame.ts
|
|
3377
|
-
/** Roles worth numbering. Mirrors src/cdp/marks.ts so both paths agree. */
|
|
3378
|
-
const INTERACTIVE_ROLES = [
|
|
3379
|
-
"button",
|
|
3380
|
-
"link",
|
|
3381
|
-
"textbox",
|
|
3382
|
-
"searchbox",
|
|
3383
|
-
"combobox",
|
|
3384
|
-
"checkbox",
|
|
3385
|
-
"radio",
|
|
3386
|
-
"menuitem",
|
|
3387
|
-
"menuitemcheckbox",
|
|
3388
|
-
"menuitemradio",
|
|
3389
|
-
"tab",
|
|
3390
|
-
"option",
|
|
3391
|
-
"switch",
|
|
3392
|
-
"slider"
|
|
3393
|
-
];
|
|
3394
|
-
function isInteractiveRole(role) {
|
|
3395
|
-
return INTERACTIVE_ROLES.includes(role);
|
|
3396
|
-
}
|
|
3397
|
-
/**
|
|
3398
|
-
* A stable frame id.
|
|
3399
|
-
*
|
|
3400
|
-
* Built from facts that identify WHICH page state this is — target, document
|
|
3401
|
-
* revision, capture sequence — rather than from a timestamp, so the same state
|
|
3402
|
-
* captured twice hashes the same and a log can be re-derived. `seq` is what
|
|
3403
|
-
* keeps two captures of an unchanged document distinct.
|
|
3404
|
-
*/
|
|
3405
|
-
function frameIdFor(target, documentRevision, seq) {
|
|
3406
|
-
return createHash("sha256").update(`${target.targetId}\u0000${documentRevision}\u0000${seq}`).digest("hex").slice(0, 16);
|
|
3407
|
-
}
|
|
3408
|
-
/** Default candidate cap. Matches the chunk ceiling — see THRESHOLD_BUCKETS. */
|
|
3409
|
-
const DEFAULT_NODE_LIMIT = 20;
|
|
3410
|
-
/**
|
|
3411
|
-
* Number the interactive candidates and freeze them into a frame.
|
|
3412
|
-
*
|
|
3413
|
-
* Order is DOCUMENT order (the AX tree arrives in it), duplicates by backend
|
|
3414
|
-
* node id are dropped, and `limit` caps the set BEFORE numbering — so `n = 1..N`
|
|
3415
|
-
* is contiguous and a judge that answers `n = 7` is answering about a candidate
|
|
3416
|
-
* the caller can find by index, always.
|
|
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.
|
|
3417
3340
|
*/
|
|
3418
3341
|
function buildFrame(input) {
|
|
3419
3342
|
const limit = input.limit ?? DEFAULT_NODE_LIMIT;
|
|
@@ -3947,70 +3870,624 @@ async function defaultFetchAx(input, deps = {}) {
|
|
|
3947
3870
|
nodes: [],
|
|
3948
3871
|
degraded: true
|
|
3949
3872
|
};
|
|
3950
|
-
const session = new CdpSession({
|
|
3951
|
-
url: input.wsUrl,
|
|
3952
|
-
commandTimeoutMs: TAB_REPORT_TIMEOUT_MS,
|
|
3953
|
-
...deps.createSocket ? { createSocket: deps.createSocket } : {}
|
|
3954
|
-
});
|
|
3955
|
-
await session.connect();
|
|
3956
|
-
try {
|
|
3957
|
-
const attached = await session.call("Target.attachToTarget", {
|
|
3958
|
-
targetId: input.targetId,
|
|
3959
|
-
flatten: true
|
|
3960
|
-
});
|
|
3961
|
-
const sessionId = typeof attached?.sessionId === "string" ? attached.sessionId : "";
|
|
3962
|
-
if (sessionId === "") throw new TabReportError("invalid-target", `no CDP session resolved for target ${input.targetId}`);
|
|
3963
|
-
for (const method of REPORT_ENABLE_METHODS) await session.call(method, {}, {
|
|
3964
|
-
sessionId,
|
|
3965
|
-
timeoutMs: TAB_REPORT_TIMEOUT_MS
|
|
3966
|
-
}).catch(() => {});
|
|
3967
|
-
const call = (method, params, options) => session.call(method, params, {
|
|
3968
|
-
sessionId: options?.sessionId ?? sessionId,
|
|
3969
|
-
timeoutMs: options?.timeoutMs ?? TAB_REPORT_TIMEOUT_MS
|
|
3970
|
-
});
|
|
3971
|
-
const value = (await call("Runtime.evaluate", {
|
|
3972
|
-
expression: "({href: location.href, title: document.title})",
|
|
3973
|
-
returnByValue: true
|
|
3974
|
-
}))?.result?.value ?? {};
|
|
3975
|
-
const pageUrl = typeof value.href === "string" ? value.href : input.urlHint ?? "";
|
|
3976
|
-
const pageTitle = typeof value.title === "string" ? value.title : input.titleHint ?? "";
|
|
3977
|
-
const tree = await accessibilityTree(call, sessionId, TAB_REPORT_TIMEOUT_MS);
|
|
3978
|
-
if (!tree.ok) return {
|
|
3979
|
-
pageUrl,
|
|
3980
|
-
pageTitle,
|
|
3981
|
-
nodes: [],
|
|
3982
|
-
degraded: false
|
|
3983
|
-
};
|
|
3984
|
-
return {
|
|
3985
|
-
pageUrl,
|
|
3986
|
-
pageTitle,
|
|
3987
|
-
nodes: tree.nodes,
|
|
3988
|
-
degraded: false
|
|
3989
|
-
};
|
|
3990
|
-
} finally {
|
|
3991
|
-
session.close();
|
|
3992
|
-
}
|
|
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;
|
|
3986
|
+
try {
|
|
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;
|
|
4006
|
+
}
|
|
4007
|
+
}
|
|
4008
|
+
return null;
|
|
4009
|
+
}
|
|
4010
|
+
/**
|
|
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
|
+
};
|
|
4039
|
+
}
|
|
4040
|
+
|
|
4041
|
+
//#endregion
|
|
4042
|
+
//#region src/config.ts
|
|
4043
|
+
const backend = z.union([
|
|
4044
|
+
"auto",
|
|
4045
|
+
"cdp",
|
|
4046
|
+
"ffmpeg"
|
|
4047
|
+
]);
|
|
4048
|
+
const profile = z.union([
|
|
4049
|
+
"low",
|
|
4050
|
+
"balanced",
|
|
4051
|
+
"high"
|
|
4052
|
+
]);
|
|
4053
|
+
const cdpMode = z.union([
|
|
4054
|
+
"auto",
|
|
4055
|
+
"local",
|
|
4056
|
+
"remote"
|
|
4057
|
+
]);
|
|
4058
|
+
const toolInjection = z.union(["lazy", "always"]);
|
|
4059
|
+
const tabTracking = z.union(["active", "all"]);
|
|
4060
|
+
const DEFAULT_SPACE = "default";
|
|
4061
|
+
const AUTO_SPACE_SENTINEL = ":auto";
|
|
4062
|
+
const encoder = z.union([
|
|
4063
|
+
"auto",
|
|
4064
|
+
"software",
|
|
4065
|
+
"h264_mf",
|
|
4066
|
+
"h264_nvenc",
|
|
4067
|
+
"h264_qsv",
|
|
4068
|
+
"h264_amf",
|
|
4069
|
+
"h264_videotoolbox",
|
|
4070
|
+
"h264_vaapi"
|
|
4071
|
+
]);
|
|
4072
|
+
const Config$1 = z.object({
|
|
4073
|
+
isolateSpaces: z.boolean().description("Space isolation: false = persistent profile (keep logins across restarts); true = isolated sandbox.").volatile(),
|
|
4074
|
+
defaultSpace: z.string().description("Task space used when an bcdp_* call omits `space`. Default `:auto` = derive a per-session space `dsh-agent-<sessionId8>`, so concurrent sessions never share or hijack each other's browsing context. Set a fixed name (e.g. `default`) to reuse ONE shared slot across sessions — pass `space: \"default\"` on a single call for the same effect. Note this only names spaces; whether the browser profile itself persists is controlled by isolateSpaces.").volatile(),
|
|
4075
|
+
idleTimeoutMin: z.number().min(0).max(1440).step(1).description("Auto-stop the backing browser after N minutes without an bcdp_* call (0 = off). Relaunches on demand at the next call.").volatile(),
|
|
4076
|
+
chromePath: z.string().description("Path to Chrome/Chromium. Empty = auto-detect.").volatile(),
|
|
4077
|
+
captureBackend: backend.description("Capture backend: auto, cdp, or ffmpeg.").volatile(),
|
|
4078
|
+
streamProfile: profile.description("Capture quality profile.").volatile(),
|
|
4079
|
+
cdpFps: z.number().min(5).max(30).step(1).description("CDP preview FPS.").volatile(),
|
|
4080
|
+
cdpQuality: z.number().min(1).max(100).step(1).description("CDP JPEG quality.").volatile(),
|
|
4081
|
+
cdpMaxWidth: z.number().min(320).max(1920).step(40).description("CDP frame max width.").volatile(),
|
|
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(),
|
|
4087
|
+
ffmpegFps: z.number().min(5).max(30).step(1).description("FFmpeg video FPS.").volatile(),
|
|
4088
|
+
ffmpegMaxWidth: z.number().min(320).max(1920).step(40).description("FFmpeg video max width.").volatile(),
|
|
4089
|
+
ffmpegBitrateKbps: z.number().min(500).max(2e4).step(250).description("FFmpeg target video bitrate in kbps.").volatile(),
|
|
4090
|
+
ffmpegEncoder: encoder.description("FFmpeg H.264 encoder.").volatile(),
|
|
4091
|
+
ffmpegPath: z.string().description("Custom FFmpeg path. Empty = detect PATH or managed install.").volatile(),
|
|
4092
|
+
githubMirror: z.string().description("HTTPS base replacing https://github.com for managed downloads.").volatile(),
|
|
4093
|
+
runtimeArgs: z.string().description("Extra args appended to the vendored runtime argv. Takes effect on the next bcdp_* call.").volatile(),
|
|
4094
|
+
chromeArgs: z.string().description("Extra args appended to the Chrome launch argv. Takes effect on the next browser cold start (the browser is a singleton).").volatile(),
|
|
4095
|
+
links: z.array(z.union([
|
|
4096
|
+
z.object({
|
|
4097
|
+
kind: z.string(),
|
|
4098
|
+
id: z.string(),
|
|
4099
|
+
label: z.string(),
|
|
4100
|
+
endpoint: z.string(),
|
|
4101
|
+
enabled: z.boolean(),
|
|
4102
|
+
note: z.string(),
|
|
4103
|
+
probeStatus: z.union([
|
|
4104
|
+
"unknown",
|
|
4105
|
+
"ok",
|
|
4106
|
+
"error"
|
|
4107
|
+
]),
|
|
4108
|
+
probeLatencyMs: z.number(),
|
|
4109
|
+
probeError: z.string(),
|
|
4110
|
+
probeCode: z.string(),
|
|
4111
|
+
probeAt: z.number(),
|
|
4112
|
+
probeEngine: z.union([
|
|
4113
|
+
"chrome",
|
|
4114
|
+
"lightpanda",
|
|
4115
|
+
"tabbit",
|
|
4116
|
+
"unknown"
|
|
4117
|
+
])
|
|
4118
|
+
}),
|
|
4119
|
+
z.object({
|
|
4120
|
+
kind: z.string(),
|
|
4121
|
+
id: z.string(),
|
|
4122
|
+
label: z.string(),
|
|
4123
|
+
cliPath: z.string(),
|
|
4124
|
+
useSdkPath: z.boolean().description("Deprecated: ALWAYS treated as true since v1.7.1-rc.5 — the native ego CLI has no taskSpaces facade, so without the bundled harness every call fails. Kept in the row shape so old profiles still validate; a stored false is healed on read."),
|
|
4125
|
+
enabled: z.boolean(),
|
|
4126
|
+
note: z.string(),
|
|
4127
|
+
probeStatus: z.union([
|
|
4128
|
+
"unknown",
|
|
4129
|
+
"ok",
|
|
4130
|
+
"error"
|
|
4131
|
+
]),
|
|
4132
|
+
probeLatencyMs: z.number(),
|
|
4133
|
+
probeError: z.string(),
|
|
4134
|
+
probeCode: z.string(),
|
|
4135
|
+
probeAt: z.number(),
|
|
4136
|
+
probeEngine: z.union([
|
|
4137
|
+
"chrome",
|
|
4138
|
+
"lightpanda",
|
|
4139
|
+
"tabbit",
|
|
4140
|
+
"unknown"
|
|
4141
|
+
])
|
|
4142
|
+
}),
|
|
4143
|
+
z.object({
|
|
4144
|
+
kind: z.string(),
|
|
4145
|
+
id: z.string(),
|
|
4146
|
+
label: z.string(),
|
|
4147
|
+
servePath: z.string(),
|
|
4148
|
+
enabled: z.boolean(),
|
|
4149
|
+
note: z.string(),
|
|
4150
|
+
probeStatus: z.union([
|
|
4151
|
+
"unknown",
|
|
4152
|
+
"ok",
|
|
4153
|
+
"error"
|
|
4154
|
+
]),
|
|
4155
|
+
probeLatencyMs: z.number(),
|
|
4156
|
+
probeError: z.string(),
|
|
4157
|
+
probeCode: z.string(),
|
|
4158
|
+
probeAt: z.number(),
|
|
4159
|
+
probeEngine: z.union([
|
|
4160
|
+
"chrome",
|
|
4161
|
+
"lightpanda",
|
|
4162
|
+
"tabbit",
|
|
4163
|
+
"unknown"
|
|
4164
|
+
])
|
|
4165
|
+
})
|
|
4166
|
+
])).description("Ordered connection sequence: CDP endpoints and (at most one) local ego CLI link. The ACTIVATED entry receives every bcdp_* call; if the activation points at a disabled or removed entry, the FIRST enabled link in this order takes over (logged and shown by bcdp_doctor). Order IS the priority order.").volatile(),
|
|
4167
|
+
activeTargetId: z.string().description("Id of the activated entry in links. Empty = nothing activated (no silent adoption). A disabled/removed entry here falls back to the first enabled link in order.").volatile(),
|
|
4168
|
+
cdpMode: cdpMode.description("auto = use the activated target and never start a local browser silently; remote = only ever connect to the activated target; local = always use local browser control.").volatile(),
|
|
4169
|
+
cdpProbeTimeoutMs: z.number().min(200).max(3e4).step(100).description("Timeout for one CDP endpoint probe (http endpoints answer /json/version)."),
|
|
4170
|
+
cursorHud: z.boolean().description("Draw the agent cursor HUD into screenshots."),
|
|
4171
|
+
cursorName: z.string().description("Name label shown in the cursor HUD."),
|
|
4172
|
+
allowLocalFallback: z.boolean().description("auto mode may fall back to launching a local browser when the activated target is unreachable. Off by default: the fallback must be explicit.").volatile(),
|
|
4173
|
+
legacyEgoToolNames: z.boolean().description("ALSO register the tools under their old ego_* names for scripts written before the bcdp_* rename. Off by default; mutually exclusive with installing the upstream ego-browser plugin (same tool names)."),
|
|
4174
|
+
toolInjection: toolInjection.default("lazy").description("lazy = keep only bcdp_status resident (it is the unlock entry: the rest are injected after the first bcdp_* activity, and the idle reaper seals them back); always = register every allowed tool at mount (the historical behaviour).").volatile(),
|
|
4175
|
+
toolBrowse: z.boolean().default(true).description("Basic browsing tiers — act + observe + wait (19 tools: space / navigate / click / fill / key / hover / scroll / select / check / drag / tab / help / doctor / screenshot / page_info / read_element / js / snapshot / wait). Internally released in three waves. Off = sealed: removed from the model tool list.").volatile(),
|
|
4176
|
+
toolExtended: z.boolean().default(true).description("Extended tiers — power + session (8 tools: raw CDP / http / upload / download / dialog / captcha / auth_flush / login_import). Off = sealed even after browser activity.").volatile(),
|
|
4177
|
+
toolEscape: z.boolean().default(true).description("Escape-hatch tier (1 tool: script — run an arbitrary heredoc with page/browser/taskSpaces/fetch/cdp preloaded; verbatim:true reproduces the old bare-heredoc cli behaviour). Sealed until browser activity like every other non-core tier: call bcdp_status first, then it appears. Off = sealed.").volatile(),
|
|
4178
|
+
toolJudge: z.boolean().default(true).description("Judgement tier (5 bcdp_jev_* tools). On still requires a JEV or Laya key: without one they can only answer \"not configured\", so they stay sealed anyway.").volatile(),
|
|
4179
|
+
sessionScopedPulse: z.boolean().default(true).description("Per-session unlock: when on, calling bcdp_status in session A only unlocks tools for session A — other sessions stay at their own depth. When off, any session's unlock is process-wide (historical behaviour). Falls back to off when the host does not expose agent-scoped tool restriction.").volatile(),
|
|
4180
|
+
localHeadless: z.boolean().description("Run the locally launched browser headless."),
|
|
4181
|
+
remoteEnabled: z.boolean().description("Master switch for REMOTE attach. Off = the configured target sequence is preserved but inert (nothing probes or connects remotely); flip back on any time. Does not affect cdpMode=local.").volatile(),
|
|
4182
|
+
allowProbeColdStart: z.boolean().description("Allow the ego-cli readiness probe to cold-start the backing browser. Off (default): the probe never launches the browser — when --status cannot prove the browser is already up, the heredoc round-trip is skipped and the browser starts on the first real bcdp_* call instead (no browser window at plugin startup). On: the probe verifies the SDK harness up front, which may launch the browser.").volatile(),
|
|
4183
|
+
cliFramePollEnabled: z.boolean().default(true).description("Degraded watch-panel frame source for the local ego-cli link: with no CDP screencast available, capture one viewport screenshot every 5s through the CLI channel and serve it to the panel. On (default): the poller runs while an ego-cli link owns routing. Off: the panel keeps its placeholder and no screenshot subprocess is spawned. Hot-applies without reloading the plugin.").volatile(),
|
|
4184
|
+
localUserDataDir: z.string().description("Profile dir for the locally launched browser. Empty = managed dir; never point at your daily Chrome profile."),
|
|
4185
|
+
lightpandaArgs: z.string().description("Extra args appended to a managed `lightpanda serve` argv. --host/--port are managed and cannot be overridden.").volatile(),
|
|
4186
|
+
castFpsCap: z.number().min(0).max(60).step(1),
|
|
4187
|
+
screencastQuality: z.number().min(1).max(100).step(1),
|
|
4188
|
+
screencastMaxWidth: z.number().min(320).max(1920).step(40),
|
|
4189
|
+
backstopIntervalMs: z.number().min(200).max(1e4).step(100),
|
|
4190
|
+
jevUrl: z.string().description("JEV judge base URL, no path. Leave EMPTY: JEV cannot currently be registered, so the hop would only ever be skipped. Add it (and jev to the hop order) when registration opens.").volatile(),
|
|
4191
|
+
jevKey: z.string().description("Bearer key for the JEV judge. Empty = the jev hop is skipped (never sent, so no 401 round trip).").volatile(),
|
|
4192
|
+
jevModel: z.string().description("Model name sent in the request body.").volatile(),
|
|
4193
|
+
layaUrl: z.string().description("Laya judge base URL. The sidecar serves 8000; 7789 is a different tool and will not answer.").volatile(),
|
|
4194
|
+
layaKey: z.string().description("Bearer key for the Laya judge. REQUIRED: laya-api has no anonymous branch, so a keyless call is a guaranteed 401.").volatile(),
|
|
4195
|
+
layaModel: z.string().description("Model name sent to the Laya judge.").volatile(),
|
|
4196
|
+
judgePrefer: z.string().description("Judgement hop order, comma separated. Defaults to \"laya,rule\" because JEV cannot currently be registered. Unknown names are dropped; the terminal refusal hop cannot be removed.").volatile(),
|
|
4197
|
+
jevChunkSize: z.number().min(1).max(255).step(1).description("Candidate ceiling per judgement round. Bound to the probability threshold bucket, so raising it also tightens the gate.").volatile(),
|
|
4198
|
+
jevMaxImageBytes: z.number().min(0).step(1024).description("Frame byte budget. 0 = unbounded, which is the measured default: a full-page JPEG was 137 KiB, so chunking for bytes alone slices static pages for nothing.").volatile(),
|
|
4199
|
+
jevHistoryLimit: z.number().min(0).max(20).step(1).description("How many recent steps the judge is shown. Recency beats completeness in a loop.").volatile(),
|
|
4200
|
+
jevArchiveImage: z.boolean().description("Embed the base64 screenshot in the archived Laya bundle. Off by default: a bundle that always carries hundreds of KiB is a bundle nobody keeps.").volatile(),
|
|
4201
|
+
jevEvaluate: z.boolean().description("After every action, ask the judge whether the step actually advanced: inprogress / done / fail. inprogress continues silently; done is checked against successCriteria; fail hands back to the model for recovery (reload, re-capture, ...). Costs one judgement call per action.").volatile(),
|
|
4202
|
+
jevStepBudget: z.number().min(1).max(200).step(1).description("Judgement rounds allowed in one bcdp_jev_run before it stops as exhausted.").volatile(),
|
|
4203
|
+
jevWallMs: z.number().min(1e3).max(36e5).step(1e3).description("Wall-clock ceiling for one bcdp_jev_run, in ms.").volatile()
|
|
4204
|
+
});
|
|
4205
|
+
/** True when the value is a live volatile reference rather than plain data. */
|
|
4206
|
+
function isVolatileRef(value) {
|
|
4207
|
+
return typeof value === "object" && value !== null && typeof value.get === "function";
|
|
4208
|
+
}
|
|
4209
|
+
/**
|
|
4210
|
+
* Shallow-copy a raw config entry, replacing every live volatile reference
|
|
4211
|
+
* with its current snapshot. 0.1.7 delivers volatile-only changes as ref
|
|
4212
|
+
* updates (no plugin remount), so every read path must deref before the
|
|
4213
|
+
* plain-value `typeof` gates in `resolveConfig` can see real data.
|
|
4214
|
+
*/
|
|
4215
|
+
function derefVolatileConfig(config) {
|
|
4216
|
+
const out = {};
|
|
4217
|
+
for (const [key, value] of Object.entries(config)) out[key] = isVolatileRef(value) ? value.get() : value;
|
|
4218
|
+
return out;
|
|
4219
|
+
}
|
|
4220
|
+
/**
|
|
4221
|
+
* Flags the user must NOT put in `runtimeArgs`: these runtime subcommands
|
|
4222
|
+
* exit before the heredoc runs (--status/--stop/--help/...) or steal the
|
|
4223
|
+
* browser window (--open), so appending them would break every bcdp_* tool.
|
|
4224
|
+
* `--headless` is managed by EGO_LINUX_HEADLESS; `--sdk-path` is allowed.
|
|
4225
|
+
*/
|
|
4226
|
+
const EGO_CLI_BLOCKED = new Set([
|
|
4227
|
+
"--status",
|
|
4228
|
+
"--stop",
|
|
4229
|
+
"--open",
|
|
4230
|
+
"--spaces",
|
|
4231
|
+
"--spaces-daemon",
|
|
4232
|
+
"--prune-spaces",
|
|
4233
|
+
"--import-chrome-profile",
|
|
4234
|
+
"--install-desktop-entry",
|
|
4235
|
+
"--help",
|
|
4236
|
+
"-h"
|
|
4237
|
+
]);
|
|
4238
|
+
/**
|
|
4239
|
+
* Flags the user must NOT put in `chromeArgs`: these are managed by the
|
|
4240
|
+
* launcher / EGO_LINUX_PROXY and overriding them would break CDP control,
|
|
4241
|
+
* profile isolation, or the proxy bypass list. `--proxy-server` should go
|
|
4242
|
+
* through EGO_LINUX_PROXY (which also sets the bypass list).
|
|
4243
|
+
*/
|
|
4244
|
+
const CHROME_BLOCKED = new Set([
|
|
4245
|
+
"--user-data-dir",
|
|
4246
|
+
"--remote-debugging-port",
|
|
4247
|
+
"--remote-allow-origins",
|
|
4248
|
+
"--headless",
|
|
4249
|
+
"--no-startup-window",
|
|
4250
|
+
"--proxy-server",
|
|
4251
|
+
"--proxy-bypass-list"
|
|
4252
|
+
]);
|
|
4253
|
+
/**
|
|
4254
|
+
* Shell-like tokenizer for user-supplied arg strings. Handles single/double
|
|
4255
|
+
* quotes and backslash escapes; bare whitespace separates tokens. Returns []
|
|
4256
|
+
* for empty/whitespace-only input. Used for both `runtimeArgs` and `chromeArgs`
|
|
4257
|
+
* (mirrored in runtime/ego-linux/src/chrome.mjs for the Chrome side, since the
|
|
4258
|
+
* runtime must not import from src/).
|
|
4259
|
+
*/
|
|
4260
|
+
function tokenizeArgs(input) {
|
|
4261
|
+
if (typeof input !== "string") return [];
|
|
4262
|
+
const out = [];
|
|
4263
|
+
let cur = "";
|
|
4264
|
+
let i = 0;
|
|
4265
|
+
let quote = null;
|
|
4266
|
+
while (i < input.length) {
|
|
4267
|
+
const c = input[i];
|
|
4268
|
+
if (quote) {
|
|
4269
|
+
if (c === "\\") {
|
|
4270
|
+
const next = input[i + 1];
|
|
4271
|
+
if (next !== void 0) {
|
|
4272
|
+
cur += next;
|
|
4273
|
+
i += 2;
|
|
4274
|
+
continue;
|
|
4275
|
+
}
|
|
4276
|
+
} else if (c === quote) {
|
|
4277
|
+
quote = null;
|
|
4278
|
+
i += 1;
|
|
4279
|
+
continue;
|
|
4280
|
+
}
|
|
4281
|
+
cur += c;
|
|
4282
|
+
i += 1;
|
|
4283
|
+
continue;
|
|
4284
|
+
}
|
|
4285
|
+
if (c === "\"" || c === "'") {
|
|
4286
|
+
quote = c;
|
|
4287
|
+
i += 1;
|
|
4288
|
+
continue;
|
|
4289
|
+
}
|
|
4290
|
+
if (c === "\\") {
|
|
4291
|
+
const next = input[i + 1];
|
|
4292
|
+
if (next !== void 0) {
|
|
4293
|
+
cur += next;
|
|
4294
|
+
i += 2;
|
|
4295
|
+
continue;
|
|
4296
|
+
}
|
|
4297
|
+
i += 1;
|
|
4298
|
+
continue;
|
|
4299
|
+
}
|
|
4300
|
+
if (c === " " || c === " " || c === "\n" || c === "\r") {
|
|
4301
|
+
if (cur !== "") {
|
|
4302
|
+
out.push(cur);
|
|
4303
|
+
cur = "";
|
|
4304
|
+
}
|
|
4305
|
+
i += 1;
|
|
4306
|
+
continue;
|
|
4307
|
+
}
|
|
4308
|
+
cur += c;
|
|
4309
|
+
i += 1;
|
|
4310
|
+
}
|
|
4311
|
+
if (cur !== "") out.push(cur);
|
|
4312
|
+
return out;
|
|
4313
|
+
}
|
|
4314
|
+
/**
|
|
4315
|
+
* Split a raw arg string into tokens, dropping any token (and, for `--flag
|
|
4316
|
+
* value` pairs, its value) that appears in `blocked`. A "blocked" token with a
|
|
4317
|
+
* `=` attached (e.g. `--headless=new`) is also dropped. Returns the surviving
|
|
4318
|
+
* tokens. Exposed for tests and for the runtime to mirror.
|
|
4319
|
+
*/
|
|
4320
|
+
function filterArgs(raw, blocked) {
|
|
4321
|
+
const tokens = tokenizeArgs(raw);
|
|
4322
|
+
const kept = [];
|
|
4323
|
+
for (let i = 0; i < tokens.length; i++) {
|
|
4324
|
+
const tok = tokens[i];
|
|
4325
|
+
const key = tok.includes("=") ? tok.slice(0, tok.indexOf("=")) : tok;
|
|
4326
|
+
if (blocked.has(key)) {
|
|
4327
|
+
if (!tok.includes("=") && i + 1 < tokens.length && !tokens[i + 1].startsWith("-")) i += 1;
|
|
4328
|
+
continue;
|
|
4329
|
+
}
|
|
4330
|
+
kept.push(tok);
|
|
4331
|
+
}
|
|
4332
|
+
return kept;
|
|
4333
|
+
}
|
|
4334
|
+
const finiteIn = (value, min, max) => typeof value === "number" && Number.isFinite(value) && value >= min && value <= max;
|
|
4335
|
+
function oneOf(value, values, fallback) {
|
|
4336
|
+
return typeof value === "string" && values.includes(value) ? value : fallback;
|
|
4337
|
+
}
|
|
4338
|
+
/**
|
|
4339
|
+
* A non-string (undefined, null, a number from a hand-edited row) becomes ''.
|
|
4340
|
+
*
|
|
4341
|
+
* Trimmed as well, because these values come from a settings panel that a user
|
|
4342
|
+
* pastes URLs into, and `" http://…"` is a URL that fails to parse while looking
|
|
4343
|
+
* perfectly fine in the field.
|
|
4344
|
+
*/
|
|
4345
|
+
const trimmed = (value) => typeof value === "string" ? value.trim() : "";
|
|
4346
|
+
/**
|
|
4347
|
+
* Pick out the judge-facing settings.
|
|
4348
|
+
*
|
|
4349
|
+
* `prefer` is passed through UNFILTERED on purpose, matching how `runtimeArgs`
|
|
4350
|
+
* is handled: a saved preference is stored raw and filtered at the call site, so
|
|
4351
|
+
* a later change to the legal hop list cannot retroactively mangle what the user
|
|
4352
|
+
* typed. The filtering (and the rule that the terminal refusal hop cannot be
|
|
4353
|
+
* removed) lives in `src/jev/client.ts`, where it is unit-tested.
|
|
4354
|
+
*/
|
|
4355
|
+
function judgeSettingsOf(config) {
|
|
4356
|
+
return {
|
|
4357
|
+
jevUrl: config.jevUrl,
|
|
4358
|
+
jevKey: config.jevKey,
|
|
4359
|
+
jevModel: config.jevModel,
|
|
4360
|
+
layaUrl: config.layaUrl,
|
|
4361
|
+
layaKey: config.layaKey,
|
|
4362
|
+
layaModel: config.layaModel,
|
|
4363
|
+
prefer: config.judgePrefer,
|
|
4364
|
+
chunkSize: config.jevChunkSize,
|
|
4365
|
+
maxImageBytes: config.jevMaxImageBytes,
|
|
4366
|
+
historyLimit: config.jevHistoryLimit,
|
|
4367
|
+
archiveImage: config.jevArchiveImage,
|
|
4368
|
+
evaluate: config.jevEvaluate,
|
|
4369
|
+
stepBudget: config.jevStepBudget,
|
|
4370
|
+
wallMs: config.jevWallMs
|
|
4371
|
+
};
|
|
4372
|
+
}
|
|
4373
|
+
/**
|
|
4374
|
+
* 分级开关的默认极性 = 开放。只有显式的假值才是封印:`undefined`(用户从没碰
|
|
4375
|
+
* 过表单)与手改 YAML 写出的 `'false'` / `0` 都得认,否则一个空字段就会把
|
|
4376
|
+
* 14 个工具静默封掉。prime-memory 的 `v.toolRoom !== false` 同式,只是这里把
|
|
4377
|
+
* 手改形状一并接住。
|
|
4378
|
+
*/
|
|
4379
|
+
const tierOpenByDefault = (value) => !(value === false || value === "false" || value === 0);
|
|
4380
|
+
function resolveConfig(config = {}) {
|
|
4381
|
+
config = derefVolatileConfig(config);
|
|
4382
|
+
const legacyFps = finiteIn(config.castFpsCap, 0, 60) ? config.castFpsCap === 0 ? 20 : Math.max(5, Math.min(30, config.castFpsCap)) : 20;
|
|
4383
|
+
const selectedProfile = oneOf(config.streamProfile, [
|
|
4384
|
+
"low",
|
|
4385
|
+
"balanced",
|
|
4386
|
+
"high"
|
|
4387
|
+
], "balanced");
|
|
4388
|
+
const profileDefaults = selectedProfile === "low" ? {
|
|
4389
|
+
fps: 15,
|
|
4390
|
+
width: 960,
|
|
4391
|
+
bitrateKbps: 2e3
|
|
4392
|
+
} : selectedProfile === "high" ? {
|
|
4393
|
+
fps: 30,
|
|
4394
|
+
width: 1600,
|
|
4395
|
+
bitrateKbps: 8e3
|
|
4396
|
+
} : {
|
|
4397
|
+
fps: 20,
|
|
4398
|
+
width: 1280,
|
|
4399
|
+
bitrateKbps: 4e3
|
|
4400
|
+
};
|
|
4401
|
+
return {
|
|
4402
|
+
chromePath: typeof config.chromePath === "string" ? config.chromePath : "",
|
|
4403
|
+
captureBackend: oneOf(config.captureBackend, [
|
|
4404
|
+
"auto",
|
|
4405
|
+
"cdp",
|
|
4406
|
+
"ffmpeg"
|
|
4407
|
+
], "auto"),
|
|
4408
|
+
streamProfile: selectedProfile,
|
|
4409
|
+
cdpFps: finiteIn(config.cdpFps, 5, 30) ? config.cdpFps : legacyFps,
|
|
4410
|
+
cdpQuality: finiteIn(config.cdpQuality, 1, 100) ? config.cdpQuality : finiteIn(config.screencastQuality, 1, 100) ? config.screencastQuality : 55,
|
|
4411
|
+
cdpMaxWidth: finiteIn(config.cdpMaxWidth, 320, 1920) ? config.cdpMaxWidth : finiteIn(config.screencastMaxWidth, 320, 1920) ? config.screencastMaxWidth : 960,
|
|
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,
|
|
4417
|
+
ffmpegFps: finiteIn(config.ffmpegFps, 5, 30) ? config.ffmpegFps : profileDefaults.fps,
|
|
4418
|
+
ffmpegMaxWidth: finiteIn(config.ffmpegMaxWidth, 320, 1920) ? config.ffmpegMaxWidth : profileDefaults.width,
|
|
4419
|
+
ffmpegBitrateKbps: finiteIn(config.ffmpegBitrateKbps, 500, 2e4) ? config.ffmpegBitrateKbps : profileDefaults.bitrateKbps,
|
|
4420
|
+
ffmpegEncoder: oneOf(config.ffmpegEncoder, [
|
|
4421
|
+
"auto",
|
|
4422
|
+
"software",
|
|
4423
|
+
"h264_mf",
|
|
4424
|
+
"h264_nvenc",
|
|
4425
|
+
"h264_qsv",
|
|
4426
|
+
"h264_amf",
|
|
4427
|
+
"h264_videotoolbox",
|
|
4428
|
+
"h264_vaapi"
|
|
4429
|
+
], "auto"),
|
|
4430
|
+
ffmpegPath: typeof config.ffmpegPath === "string" ? config.ffmpegPath : "",
|
|
4431
|
+
githubMirror: typeof config.githubMirror === "string" ? config.githubMirror : "",
|
|
4432
|
+
runtimeArgs: typeof config.runtimeArgs === "string" ? config.runtimeArgs : typeof config.egoCliArgs === "string" ? config.egoCliArgs : "",
|
|
4433
|
+
chromeArgs: typeof config.chromeArgs === "string" ? config.chromeArgs : "",
|
|
4434
|
+
isolateSpaces: typeof config.isolateSpaces === "boolean" ? config.isolateSpaces : config.isolateSpaces === "true" || config.isolateSpaces === "1" || config.isolateSpaces === 1,
|
|
4435
|
+
defaultSpace: typeof config.defaultSpace === "string" && config.defaultSpace.trim() !== "" ? config.defaultSpace.trim() : AUTO_SPACE_SENTINEL,
|
|
4436
|
+
idleTimeoutMin: finiteIn(config.idleTimeoutMin, 0, 1440) ? config.idleTimeoutMin : 0,
|
|
4437
|
+
links: sanitizeLinks(config.links ?? config.cdpTargets).links.map(normalizeProbeState),
|
|
4438
|
+
activeTargetId: typeof config.activeTargetId === "string" ? config.activeTargetId : "",
|
|
4439
|
+
cdpMode: oneOf(config.cdpMode, [
|
|
4440
|
+
"auto",
|
|
4441
|
+
"local",
|
|
4442
|
+
"remote"
|
|
4443
|
+
], "auto"),
|
|
4444
|
+
cdpProbeTimeoutMs: finiteIn(config.cdpProbeTimeoutMs, 200, 3e4) ? config.cdpProbeTimeoutMs : 3e3,
|
|
4445
|
+
cursorHud: config.cursorHud === void 0 ? true : Boolean(config.cursorHud),
|
|
4446
|
+
cursorName: typeof config.cursorName === "string" && config.cursorName.trim() !== "" ? config.cursorName : "DeepSeek",
|
|
4447
|
+
allowLocalFallback: config.allowLocalFallback === void 0 ? false : Boolean(config.allowLocalFallback),
|
|
4448
|
+
legacyEgoToolNames: Boolean(config.legacyEgoToolNames),
|
|
4449
|
+
toolInjection: oneOf(config.toolInjection, ["lazy", "always"], "lazy"),
|
|
4450
|
+
toolBrowse: tierOpenByDefault(config.toolBrowse),
|
|
4451
|
+
toolExtended: tierOpenByDefault(config.toolExtended),
|
|
4452
|
+
toolEscape: tierOpenByDefault(config.toolEscape),
|
|
4453
|
+
toolJudge: tierOpenByDefault(config.toolJudge),
|
|
4454
|
+
sessionScopedPulse: tierOpenByDefault(config.sessionScopedPulse),
|
|
4455
|
+
localHeadless: config.localHeadless === void 0 ? false : Boolean(config.localHeadless),
|
|
4456
|
+
localUserDataDir: typeof config.localUserDataDir === "string" ? config.localUserDataDir : "",
|
|
4457
|
+
lightpandaArgs: trimmed(config.lightpandaArgs),
|
|
4458
|
+
remoteEnabled: config.remoteEnabled === void 0 ? true : Boolean(config.remoteEnabled),
|
|
4459
|
+
allowProbeColdStart: config.allowProbeColdStart === true || config.allowProbeColdStart === "true",
|
|
4460
|
+
cliFramePollEnabled: config.cliFramePollEnabled !== false && config.cliFramePollEnabled !== "false",
|
|
4461
|
+
jevUrl: trimmed(config.jevUrl),
|
|
4462
|
+
jevKey: trimmed(config.jevKey),
|
|
4463
|
+
jevModel: trimmed(config.jevModel) === "" ? "jev" : trimmed(config.jevModel),
|
|
4464
|
+
layaUrl: trimmed(config.layaUrl) === "" ? "http://127.0.0.1:8000" : trimmed(config.layaUrl),
|
|
4465
|
+
layaKey: trimmed(config.layaKey),
|
|
4466
|
+
layaModel: trimmed(config.layaModel) === "" ? "laya" : trimmed(config.layaModel),
|
|
4467
|
+
judgePrefer: trimmed(config.judgePrefer) === "" ? "laya,rule" : trimmed(config.judgePrefer),
|
|
4468
|
+
jevChunkSize: finiteIn(config.jevChunkSize, 1, 255) ? config.jevChunkSize : 20,
|
|
4469
|
+
jevMaxImageBytes: finiteIn(config.jevMaxImageBytes, 0, 512 * 1024 * 1024) ? config.jevMaxImageBytes : 0,
|
|
4470
|
+
jevHistoryLimit: finiteIn(config.jevHistoryLimit, 0, 20) ? config.jevHistoryLimit : 5,
|
|
4471
|
+
jevArchiveImage: config.jevArchiveImage === void 0 ? false : Boolean(config.jevArchiveImage),
|
|
4472
|
+
jevEvaluate: config.jevEvaluate === void 0 ? true : Boolean(config.jevEvaluate),
|
|
4473
|
+
jevStepBudget: finiteIn(config.jevStepBudget, 1, 200) ? config.jevStepBudget : 20,
|
|
4474
|
+
jevWallMs: finiteIn(config.jevWallMs, 1e3, 36e5) ? config.jevWallMs : 12e4
|
|
4475
|
+
};
|
|
3993
4476
|
}
|
|
3994
4477
|
/**
|
|
3995
|
-
*
|
|
3996
|
-
*
|
|
4478
|
+
* Fill the per-link probe fields so downstream code (panel badge, doctor
|
|
4479
|
+
* output) can read them without a null-check ladder. Generic over the link
|
|
4480
|
+
* union so the discriminating `kind` (and every kind-specific field) survives.
|
|
3997
4481
|
*/
|
|
3998
|
-
|
|
3999
|
-
const capturedAt = deps.now?.() ?? Date.now();
|
|
4000
|
-
const snapshot = await (deps.fetchAx ?? defaultFetchAx)(input, deps);
|
|
4001
|
-
const scope = reportScope(snapshot.pageUrl, capturedAt);
|
|
4002
|
-
const numbered = numberReportNodes(snapshot.nodes, scope, deps.maxElements ?? MAX_REPORT_ELEMENTS);
|
|
4482
|
+
function normalizeProbeState(link) {
|
|
4003
4483
|
return {
|
|
4004
|
-
|
|
4005
|
-
|
|
4006
|
-
|
|
4007
|
-
|
|
4008
|
-
|
|
4009
|
-
|
|
4010
|
-
|
|
4011
|
-
elements: numbered.elements,
|
|
4012
|
-
truncated: numbered.truncated,
|
|
4013
|
-
...snapshot.degraded ? { degraded: "lightpanda" } : {}
|
|
4484
|
+
...link,
|
|
4485
|
+
probeStatus: link.probeStatus === "ok" || link.probeStatus === "error" ? link.probeStatus : "unknown",
|
|
4486
|
+
probeLatencyMs: typeof link.probeLatencyMs === "number" && Number.isFinite(link.probeLatencyMs) ? link.probeLatencyMs : 0,
|
|
4487
|
+
probeError: typeof link.probeError === "string" ? link.probeError : "",
|
|
4488
|
+
probeCode: typeof link.probeCode === "string" ? link.probeCode : "",
|
|
4489
|
+
probeAt: typeof link.probeAt === "number" && Number.isFinite(link.probeAt) ? link.probeAt : 0,
|
|
4490
|
+
probeEngine: link.probeEngine === "chrome" || link.probeEngine === "lightpanda" || link.probeEngine === "tabbit" ? link.probeEngine : "unknown"
|
|
4014
4491
|
};
|
|
4015
4492
|
}
|
|
4016
4493
|
|
|
@@ -4178,27 +4655,32 @@ function registerEgoBrowserGateway(ctx, bridge, ffmpegManager, picks) {
|
|
|
4178
4655
|
return;
|
|
4179
4656
|
}
|
|
4180
4657
|
const attach = defaultAttachCache.get();
|
|
4181
|
-
if (attach.status !== "ready" || attach.wsUrl === "") {
|
|
4182
|
-
writeJson(res, 409, envelopeError("attach-not-ready", "no live CDP attach; activate a target and let the probe finish first"));
|
|
4183
|
-
return;
|
|
4184
|
-
}
|
|
4185
4658
|
const urlHint = typeof body.url === "string" ? body.url : "";
|
|
4186
4659
|
const titleHint = typeof body.title === "string" ? body.title : "";
|
|
4187
|
-
let report;
|
|
4660
|
+
let report = null;
|
|
4188
4661
|
try {
|
|
4189
|
-
report = await captureTabReport({
|
|
4662
|
+
if (attach.status === "ready" && attach.wsUrl !== "") report = await captureTabReport({
|
|
4190
4663
|
wsUrl: attach.wsUrl,
|
|
4191
4664
|
targetId: repTargetId,
|
|
4192
4665
|
engine: attach.engine,
|
|
4193
4666
|
urlHint,
|
|
4194
4667
|
titleHint
|
|
4195
4668
|
});
|
|
4669
|
+
else if (picks?.fallbackTabReport) report = await picks.fallbackTabReport({
|
|
4670
|
+
targetId: repTargetId,
|
|
4671
|
+
urlHint,
|
|
4672
|
+
titleHint
|
|
4673
|
+
});
|
|
4196
4674
|
} catch (error) {
|
|
4197
4675
|
const code = error?.code || "capture-failed";
|
|
4198
4676
|
writeJson(res, code === "invalid-target" ? 409 : 502, envelopeError(code, error instanceof Error ? error.message : String(error)));
|
|
4199
4677
|
return;
|
|
4200
4678
|
}
|
|
4201
|
-
|
|
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`;
|
|
4202
4684
|
await mkdir(repDir, { recursive: true });
|
|
4203
4685
|
const repTargetPath = resolve(repDir, repFile);
|
|
4204
4686
|
if (!repTargetPath.startsWith(resolve(repDir))) {
|
|
@@ -4623,6 +5105,7 @@ const POWER = [
|
|
|
4623
5105
|
];
|
|
4624
5106
|
const SESSION = [
|
|
4625
5107
|
"bcdp_captcha",
|
|
5108
|
+
"bcdp_wait_for_human",
|
|
4626
5109
|
"bcdp_auth_flush",
|
|
4627
5110
|
"bcdp_login_import"
|
|
4628
5111
|
];
|
|
@@ -4848,12 +5331,12 @@ function rewriteGithubUrl(url, mirror = "") {
|
|
|
4848
5331
|
try {
|
|
4849
5332
|
parsed = new URL(mirror);
|
|
4850
5333
|
} catch {
|
|
4851
|
-
throw codedError$
|
|
5334
|
+
throw codedError$3("ffmpeg-mirror-invalid", "GitHub mirror must be a valid HTTPS URL");
|
|
4852
5335
|
}
|
|
4853
|
-
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");
|
|
4854
5337
|
return `${parsed.toString().replace(/\/+$/, "")}${url.slice(18)}`;
|
|
4855
5338
|
}
|
|
4856
|
-
function codedError$
|
|
5339
|
+
function codedError$3(code, message) {
|
|
4857
5340
|
const error = new Error(message);
|
|
4858
5341
|
error.code = code;
|
|
4859
5342
|
return error;
|
|
@@ -4910,7 +5393,7 @@ function runFfmpegProbe(path, argv, { spawn: spawn$1 = spawn, timeoutMs = 3e3 }
|
|
|
4910
5393
|
}
|
|
4911
5394
|
async function probeFfmpeg(path, { platform = process.platform, env = process.env, spawn: spawn$1 = spawn, requestedEncoder = "auto" } = {}) {
|
|
4912
5395
|
const versionResult = await runFfmpegProbe(path, ["-version"], { spawn: spawn$1 });
|
|
4913
|
-
if (!versionResult.ok) throw codedError$
|
|
5396
|
+
if (!versionResult.ok) throw codedError$2("ffmpeg-not-executable", `FFmpeg is not executable: ${path}`);
|
|
4914
5397
|
const version = versionResult.output.split(/\r?\n/, 1)[0] || "FFmpeg";
|
|
4915
5398
|
if (platform === "win32") {
|
|
4916
5399
|
const support = await runFfmpegProbe(path, [
|
|
@@ -4918,14 +5401,14 @@ async function probeFfmpeg(path, { platform = process.platform, env = process.en
|
|
|
4918
5401
|
"-h",
|
|
4919
5402
|
"filter=gfxcapture"
|
|
4920
5403
|
], { spawn: spawn$1 });
|
|
4921
|
-
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");
|
|
4922
5405
|
} else if (platform === "darwin") {
|
|
4923
5406
|
const devices = await runFfmpegProbe(path, ["-hide_banner", "-devices"], { spawn: spawn$1 });
|
|
4924
|
-
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");
|
|
4925
5408
|
} else if (platform === "linux") {
|
|
4926
|
-
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");
|
|
4927
5410
|
const devices = await runFfmpegProbe(path, ["-hide_banner", "-devices"], { spawn: spawn$1 });
|
|
4928
|
-
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");
|
|
4929
5412
|
}
|
|
4930
5413
|
const encoders = requestedEncoder === "auto" ? platform === "win32" ? [
|
|
4931
5414
|
"h264_mf",
|
|
@@ -4961,9 +5444,9 @@ async function probeFfmpeg(path, { platform = process.platform, env = process.en
|
|
|
4961
5444
|
version,
|
|
4962
5445
|
encoder: encoder$1
|
|
4963
5446
|
};
|
|
4964
|
-
throw codedError$
|
|
5447
|
+
throw codedError$2("ffmpeg-encoder-unavailable", "FFmpeg has no usable H.264 encoder");
|
|
4965
5448
|
}
|
|
4966
|
-
function codedError$
|
|
5449
|
+
function codedError$2(code, message) {
|
|
4967
5450
|
const error = new Error(message);
|
|
4968
5451
|
error.code = code;
|
|
4969
5452
|
return error;
|
|
@@ -5139,7 +5622,7 @@ var FfmpegInstallationManager = class {
|
|
|
5139
5622
|
}
|
|
5140
5623
|
install({ githubMirror, configuredPath, requestedEncoder = "auto" } = {}) {
|
|
5141
5624
|
if (this.installPromise) return this.installPromise;
|
|
5142
|
-
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}`));
|
|
5143
5626
|
this.installPromise = this.#install(githubMirror ?? this.getConfig().githubMirror ?? "", configuredPath ?? this.getConfig().ffmpegPath ?? "", requestedEncoder).finally(() => {
|
|
5144
5627
|
this.installPromise = null;
|
|
5145
5628
|
});
|
|
@@ -5189,7 +5672,7 @@ var FfmpegInstallationManager = class {
|
|
|
5189
5672
|
state: "verifying",
|
|
5190
5673
|
progress: null
|
|
5191
5674
|
});
|
|
5192
|
-
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");
|
|
5193
5676
|
this.#set({ state: "extracting" });
|
|
5194
5677
|
if (manifest.archiveType === "gzip") await pipeline(createReadStream(archivePath), createGunzip(), createWriteStream(extractedPath, { mode: 493 }));
|
|
5195
5678
|
else await extractWithTar(archivePath, tempRoot, extractedPath, manifest.archiveExecutable, this.spawn);
|
|
@@ -5282,9 +5765,9 @@ async function acquireInstallLock(platformRoot) {
|
|
|
5282
5765
|
await rm(lockPath, { force: true });
|
|
5283
5766
|
continue;
|
|
5284
5767
|
}
|
|
5285
|
-
throw codedError("ffmpeg-install-busy", "Another FFmpeg installation is already running");
|
|
5768
|
+
throw codedError$1("ffmpeg-install-busy", "Another FFmpeg installation is already running");
|
|
5286
5769
|
}
|
|
5287
|
-
throw codedError("ffmpeg-install-busy", "Another FFmpeg installation is already running");
|
|
5770
|
+
throw codedError$1("ffmpeg-install-busy", "Another FFmpeg installation is already running");
|
|
5288
5771
|
}
|
|
5289
5772
|
function isProcessAlive(pid) {
|
|
5290
5773
|
try {
|
|
@@ -5326,13 +5809,13 @@ async function downloadFile(url, target, { fetchImpl = globalThis.fetch, expecte
|
|
|
5326
5809
|
308
|
|
5327
5810
|
].includes(response.status)) break;
|
|
5328
5811
|
const location = response.headers.get("location");
|
|
5329
|
-
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");
|
|
5330
5813
|
current = new URL(location, current).toString();
|
|
5331
5814
|
await response.body?.cancel().catch(() => {});
|
|
5332
|
-
if (!current.startsWith("https://")) throw codedError("ffmpeg-download-failed", "FFmpeg download refused a non-HTTPS redirect");
|
|
5333
|
-
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");
|
|
5334
5817
|
}
|
|
5335
|
-
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}`);
|
|
5336
5819
|
const declared = Number(response.headers.get("content-length")) || expectedSize || null;
|
|
5337
5820
|
const hash = createHash("sha256");
|
|
5338
5821
|
const file = await open(target, "w");
|
|
@@ -5344,7 +5827,7 @@ async function downloadFile(url, target, { fetchImpl = globalThis.fetch, expecte
|
|
|
5344
5827
|
if (done) break;
|
|
5345
5828
|
const buffer = Buffer.from(value);
|
|
5346
5829
|
received += buffer.length;
|
|
5347
|
-
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");
|
|
5348
5831
|
hash.update(buffer);
|
|
5349
5832
|
await file.write(buffer);
|
|
5350
5833
|
onProgress({
|
|
@@ -5363,13 +5846,13 @@ async function ensureTarAvailable(spawn$1) {
|
|
|
5363
5846
|
try {
|
|
5364
5847
|
await runCommand("tar", ["--version"], spawn$1, 5e3);
|
|
5365
5848
|
} catch {
|
|
5366
|
-
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");
|
|
5367
5850
|
}
|
|
5368
5851
|
}
|
|
5369
5852
|
function assertSafeDownloadUrl(value) {
|
|
5370
5853
|
const url = new URL(value);
|
|
5371
5854
|
const host = url.hostname.toLowerCase().replace(/^\[|\]$/g, "");
|
|
5372
|
-
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");
|
|
5373
5856
|
}
|
|
5374
5857
|
function isPrivateIp(host) {
|
|
5375
5858
|
const family = isIP(host);
|
|
@@ -5382,7 +5865,7 @@ function isPrivateIp(host) {
|
|
|
5382
5865
|
}
|
|
5383
5866
|
async function extractWithTar(archivePath, tempRoot, destination, matcher, spawn$1) {
|
|
5384
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));
|
|
5385
|
-
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}`);
|
|
5386
5869
|
const entry = matches[0];
|
|
5387
5870
|
await runCommand("tar", [
|
|
5388
5871
|
"-xf",
|
|
@@ -5392,7 +5875,7 @@ async function extractWithTar(archivePath, tempRoot, destination, matcher, spawn
|
|
|
5392
5875
|
entry
|
|
5393
5876
|
], spawn$1, 6e4);
|
|
5394
5877
|
const extracted = resolve(tempRoot, normalize(entry));
|
|
5395
|
-
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");
|
|
5396
5879
|
await copyFile(extracted, destination);
|
|
5397
5880
|
}
|
|
5398
5881
|
function safeArchiveEntry(entry) {
|
|
@@ -5419,7 +5902,7 @@ async function hashFile(path) {
|
|
|
5419
5902
|
}
|
|
5420
5903
|
function readChunk(reader, timeoutMs) {
|
|
5421
5904
|
return new Promise((resolvePromise, reject) => {
|
|
5422
|
-
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);
|
|
5423
5906
|
reader.read().then((value) => {
|
|
5424
5907
|
clearTimeout(timer);
|
|
5425
5908
|
resolvePromise(value);
|
|
@@ -5459,16 +5942,16 @@ function runCommand(command, argv, spawn$1, timeoutMs) {
|
|
|
5459
5942
|
child.once("exit", (code) => code === 0 ? finish$1(resolvePromise, {
|
|
5460
5943
|
stdout,
|
|
5461
5944
|
stderr
|
|
5462
|
-
}) : 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}`)));
|
|
5463
5946
|
const timer = setTimeout(() => {
|
|
5464
5947
|
try {
|
|
5465
5948
|
child.kill("SIGKILL");
|
|
5466
5949
|
} catch {}
|
|
5467
|
-
finish$1(reject, codedError("ffmpeg-archive-invalid", `${command} timed out`));
|
|
5950
|
+
finish$1(reject, codedError$1("ffmpeg-archive-invalid", `${command} timed out`));
|
|
5468
5951
|
}, timeoutMs);
|
|
5469
5952
|
});
|
|
5470
5953
|
}
|
|
5471
|
-
function codedError(code, message) {
|
|
5954
|
+
function codedError$1(code, message) {
|
|
5472
5955
|
const error = new Error(message);
|
|
5473
5956
|
error.code = code;
|
|
5474
5957
|
return error;
|
|
@@ -6946,7 +7429,7 @@ async function runRenderCall(subprocess, options) {
|
|
|
6946
7429
|
};
|
|
6947
7430
|
const spec = {
|
|
6948
7431
|
argv: [options.nodePath ?? defaultNodePath(), options.workerPath],
|
|
6949
|
-
|
|
7432
|
+
cwd: options.cwd ?? process.cwd(),
|
|
6950
7433
|
...options.env === void 0 ? {} : { env: options.env },
|
|
6951
7434
|
stdio: {
|
|
6952
7435
|
stdin: { data: buildWorkerScript(options) },
|
|
@@ -8379,6 +8862,21 @@ const TOOL_TIMEOUT_MS = 12e4;
|
|
|
8379
8862
|
function humanCheckScript(space) {
|
|
8380
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`;
|
|
8381
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
|
+
}
|
|
8382
8880
|
function createActiveSpaceTracker(defaultSpace = DEFAULT_SPACE) {
|
|
8383
8881
|
let activeSpace = defaultSpace;
|
|
8384
8882
|
let activeName = typeof defaultSpace === "string" ? defaultSpace : null;
|
|
@@ -8592,6 +9090,7 @@ function withEgoLock(fn) {
|
|
|
8592
9090
|
const RENDER_WORKER_BIN = fileURLToPath(new URL("../bin/cdp-render-worker.mjs", import.meta.url));
|
|
8593
9091
|
const BUNDLED_WRAPPER = fileURLToPath(new URL("../bin/cdp-chrome-wrapper.sh", import.meta.url));
|
|
8594
9092
|
const IS_WIN = process.platform === "win32";
|
|
9093
|
+
const IS_DARWIN = process.platform === "darwin";
|
|
8595
9094
|
const AUTO_ADAPT_OFF = /^(0|false|no)$/i.test(process.env.EGO_BROWSER_AUTO_ADAPT ?? "");
|
|
8596
9095
|
const COMMON_CHROME_BINS = [
|
|
8597
9096
|
"google-chrome-stable",
|
|
@@ -8622,6 +9121,28 @@ function windowsChromeCandidates() {
|
|
|
8622
9121
|
b(local) + "\\BraveSoftware\\Brave-Browser\\Application\\brave.exe"
|
|
8623
9122
|
].filter(Boolean);
|
|
8624
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
|
+
}
|
|
8625
9146
|
/** Find a usable Chrome binary by scanning PATH + common fixed locations. */
|
|
8626
9147
|
function findChromeBinary() {
|
|
8627
9148
|
if (process.env.EGO_LINUX_CHROME) return process.env.EGO_LINUX_CHROME;
|
|
@@ -8641,6 +9162,12 @@ function findChromeBinary() {
|
|
|
8641
9162
|
} catch {}
|
|
8642
9163
|
return;
|
|
8643
9164
|
}
|
|
9165
|
+
if (IS_DARWIN) {
|
|
9166
|
+
for (const p of darwinChromeCandidates()) try {
|
|
9167
|
+
if (existsSync(p)) return p;
|
|
9168
|
+
} catch {}
|
|
9169
|
+
return;
|
|
9170
|
+
}
|
|
8644
9171
|
for (const name$1 of COMMON_CHROME_BINS) if (name$1.includes("/")) try {
|
|
8645
9172
|
if (existsSync(name$1)) return name$1;
|
|
8646
9173
|
} catch {}
|
|
@@ -8676,7 +9203,7 @@ function resolveEgoEnv(cfg, { platform = process.platform, baseEnv = process.env
|
|
|
8676
9203
|
const configChrome = cfg?.chromePath;
|
|
8677
9204
|
if (env.EGO_LINUX_CHROME === void 0 && configChrome) env.EGO_LINUX_CHROME = configChrome;
|
|
8678
9205
|
if (env.EGO_LINUX_CHROME === void 0 && isPosixRoot(platform) && chrome) env.EGO_LINUX_CHROME = BUNDLED_WRAPPER;
|
|
8679
|
-
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;
|
|
8680
9207
|
if (env.EGO_LINUX_HEADLESS === void 0 && isHeadlessDetected(platform, env)) env.EGO_LINUX_HEADLESS = "1";
|
|
8681
9208
|
const configChromeArgs = cfg?.chromeArgs;
|
|
8682
9209
|
if (env.EGO_LINUX_EXTRA_ARGS === void 0 && typeof configChromeArgs === "string" && configChromeArgs.trim() !== "") env.EGO_LINUX_EXTRA_ARGS = configChromeArgs;
|
|
@@ -8848,8 +9375,26 @@ async function runWithStaleSpaceRetry(ctx, cfg, exec, buildScript, graceOverride
|
|
|
8848
9375
|
if (!result.ok && CDP_CONNECT_FAIL_RE.test(result.error ?? "")) {
|
|
8849
9376
|
if (await cfg.refreshAttach?.() === true) result = await withWarmupRetry(() => runEgoScript(ctx.subprocess, buildScript(), exec, cfg, graceOverrideMs));
|
|
8850
9377
|
}
|
|
9378
|
+
if (result.ok) maybeKickCliPoller(cfg);
|
|
8851
9379
|
return result;
|
|
8852
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
|
+
}
|
|
8853
9398
|
/**
|
|
8854
9399
|
* F — navigate self-heal. A page whose renderer/main thread is wedged makes
|
|
8855
9400
|
* `page.goto`/`page.reload` hang until the subprocess times out, and the SAME
|
|
@@ -9120,10 +9665,182 @@ async function runEgoScript(subprocess, script, exec, cfg, graceOverrideMs) {
|
|
|
9120
9665
|
* the panel.
|
|
9121
9666
|
*/
|
|
9122
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
|
+
}
|
|
9123
9839
|
async function spawnCliFrameCapture(subprocess, cfg, space) {
|
|
9124
|
-
|
|
9840
|
+
space = resolveCliPanelSpace(cfg, space);
|
|
9841
|
+
if (space === null) return "";
|
|
9125
9842
|
const { attach } = effectiveChannel(cfg);
|
|
9126
|
-
const script = buildFrameScript(j(space));
|
|
9843
|
+
const script = buildFrameScript(j(space), { all: getCliTrackAll(cfg.tabTracking === "all") });
|
|
9127
9844
|
try {
|
|
9128
9845
|
const handle = subprocess.spawn({
|
|
9129
9846
|
argv: buildEgoToolArgv(cfg.egoArgvPrefix, attach, cfg.runtimeArgs ?? ""),
|
|
@@ -9142,11 +9859,21 @@ async function spawnCliFrameCapture(subprocess, cfg, space) {
|
|
|
9142
9859
|
},
|
|
9143
9860
|
graceMs: cfg.graceMs
|
|
9144
9861
|
});
|
|
9145
|
-
|
|
9146
|
-
|
|
9147
|
-
|
|
9148
|
-
|
|
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
|
|
9149
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;
|
|
9150
9877
|
} catch {
|
|
9151
9878
|
return "";
|
|
9152
9879
|
}
|
|
@@ -9171,15 +9898,15 @@ function toolPayload(result) {
|
|
|
9171
9898
|
}
|
|
9172
9899
|
/** JS snippet that pins an action tool to one task space. */
|
|
9173
9900
|
const useSpace = (name$1) => `const task = await taskSpaces.useOrCreate(${j(name$1)})\n`;
|
|
9174
|
-
/**
|
|
9175
|
-
|
|
9176
|
-
|
|
9177
|
-
|
|
9178
|
-
|
|
9179
|
-
|
|
9180
|
-
|
|
9181
|
-
|
|
9182
|
-
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) : "");
|
|
9183
9910
|
/**
|
|
9184
9911
|
* G �?a raw heredoc (`bcdp_script` with verbatim:true) that touches `page.*` without
|
|
9185
9912
|
* first selecting a task space dies with the runtime's "no active tab to attach
|
|
@@ -9347,9 +10074,9 @@ async function tryTabbitExecute(ctx, cfg, toolName, args, taskName) {
|
|
|
9347
10074
|
ok: false,
|
|
9348
10075
|
text: "bcdp_navigate: url is required"
|
|
9349
10076
|
};
|
|
9350
|
-
const js = buildNavigateSnippet(url, str(args.waitUntil, "domcontentloaded"));
|
|
10077
|
+
const js$2 = buildNavigateSnippet(url, str(args.waitUntil, "domcontentloaded"));
|
|
9351
10078
|
const navTabId = typeof args.tab === "number" ? args.tab : void 0;
|
|
9352
|
-
const { receipt } = await runTabbitSnippet(sub, js, {
|
|
10079
|
+
const { receipt } = await runTabbitSnippet(sub, js$2, {
|
|
9353
10080
|
cliPath: cli.cliPath,
|
|
9354
10081
|
taskName,
|
|
9355
10082
|
requestId: reqId,
|
|
@@ -9522,6 +10249,7 @@ function defineEgoTool(ctx, cfg, opts) {
|
|
|
9522
10249
|
execute: async (args, exec) => withEgoLock(async () => {
|
|
9523
10250
|
cfg.spaceTracker.setCurrentSession(callingSessionId(exec), resolveEffectiveLink(cfg.links, cfg.activeTargetId)?.link.id ?? "");
|
|
9524
10251
|
markEgoToolCall(callingSessionId(exec));
|
|
10252
|
+
pendingViewport = cfg;
|
|
9525
10253
|
if (typeof opts.gate === "function") {
|
|
9526
10254
|
const blocked = opts.gate(args);
|
|
9527
10255
|
if (blocked !== null && blocked !== "") return {
|
|
@@ -9649,6 +10377,18 @@ function apply(ctx, config = {}) {
|
|
|
9649
10377
|
get cdpBackstopIntervalMs() {
|
|
9650
10378
|
return resolveConfig(bridge.source()).cdpBackstopIntervalMs;
|
|
9651
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
|
+
},
|
|
9652
10392
|
get ffmpegFps() {
|
|
9653
10393
|
return resolveConfig(bridge.source()).ffmpegFps;
|
|
9654
10394
|
},
|
|
@@ -9923,7 +10663,19 @@ function apply(ctx, config = {}) {
|
|
|
9923
10663
|
intervalMs: 3e3,
|
|
9924
10664
|
capture: () => spawnCliFrameCapture(ctx.subprocess, cfg, cfg.spaceTracker.lastActiveSpace()),
|
|
9925
10665
|
isBusy: egoLockBusy,
|
|
9926
|
-
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)
|
|
9927
10679
|
});
|
|
9928
10680
|
ctx.effect?.(() => () => cliPoller.stop());
|
|
9929
10681
|
const tabbitTabTimer = setInterval(async () => {
|
|
@@ -9953,9 +10705,9 @@ function apply(ctx, config = {}) {
|
|
|
9953
10705
|
tabbitFrameInFlight = true;
|
|
9954
10706
|
try {
|
|
9955
10707
|
const reqId = `frame-${Date.now()}`;
|
|
9956
|
-
const js = buildFrameCaptureSnippet(tabbitFramePath);
|
|
10708
|
+
const js$2 = buildFrameCaptureSnippet(tabbitFramePath);
|
|
9957
10709
|
const target = _tabbitLastActiveTabId ?? _tabbitTabCache.tabs.find((t) => t.active === true)?.tabId;
|
|
9958
|
-
const { receipt } = await runTabbitSnippet(ctx.subprocess, js, {
|
|
10710
|
+
const { receipt } = await runTabbitSnippet(ctx.subprocess, js$2, {
|
|
9959
10711
|
cliPath: cli.cliPath,
|
|
9960
10712
|
taskName: _tabbitLastTaskName,
|
|
9961
10713
|
requestId: reqId,
|
|
@@ -9981,7 +10733,7 @@ function apply(ctx, config = {}) {
|
|
|
9981
10733
|
seq: tabbitFrameSeq,
|
|
9982
10734
|
updatedAt: Date.now(),
|
|
9983
10735
|
fmt: "jpeg"
|
|
9984
|
-
});
|
|
10736
|
+
}, tabbitSpaceRows().tabs);
|
|
9985
10737
|
return;
|
|
9986
10738
|
}
|
|
9987
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)})`);
|
|
@@ -10066,26 +10818,29 @@ function apply(ctx, config = {}) {
|
|
|
10066
10818
|
});
|
|
10067
10819
|
ctx.inject?.(["webServer"], (wctx) => {
|
|
10068
10820
|
try {
|
|
10069
|
-
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());
|
|
10070
10822
|
} catch (err) {
|
|
10071
10823
|
ctx.logger?.warn?.(`dsh-browser-cdp: cast server init failed: ${err?.message ?? err}`);
|
|
10072
10824
|
}
|
|
10073
10825
|
try {
|
|
10074
|
-
registerEgoBrowserGateway(wctx, bridge, ffmpegManager, {
|
|
10075
|
-
|
|
10076
|
-
|
|
10077
|
-
|
|
10078
|
-
|
|
10079
|
-
|
|
10080
|
-
|
|
10081
|
-
|
|
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;
|
|
10082
10840
|
}
|
|
10083
|
-
|
|
10084
|
-
|
|
10085
|
-
|
|
10086
|
-
return;
|
|
10087
|
-
}
|
|
10088
|
-
} });
|
|
10841
|
+
},
|
|
10842
|
+
fallbackTabReport: makeFallbackTabReport(ctx, cfg)
|
|
10843
|
+
});
|
|
10089
10844
|
} catch (err) {
|
|
10090
10845
|
ctx.logger?.warn?.(`dsh-browser-cdp: capability gateway init failed: ${err?.message ?? err}`);
|
|
10091
10846
|
}
|
|
@@ -10212,6 +10967,7 @@ function registerEgoStatus(ctx, cfg, reg, tiers) {
|
|
|
10212
10967
|
timeoutMs: 15e3,
|
|
10213
10968
|
execute: async (_args, exec) => {
|
|
10214
10969
|
tiers.pulse(callingSessionId(exec));
|
|
10970
|
+
cfg.spaceTracker.setCurrentSession(callingSessionId(exec), resolveEffectiveLink(cfg.links, cfg.activeTargetId)?.link.id ?? "");
|
|
10215
10971
|
return withEgoLock(async () => {
|
|
10216
10972
|
try {
|
|
10217
10973
|
const { attach } = effectiveChannel(cfg);
|
|
@@ -10643,13 +11399,18 @@ function registerActionTools(ctx, cfg, reg) {
|
|
|
10643
11399
|
type: "string",
|
|
10644
11400
|
description: "Optional absolute output path for the PNG."
|
|
10645
11401
|
},
|
|
11402
|
+
hideCursor: {
|
|
11403
|
+
type: "boolean",
|
|
11404
|
+
description: "Hide the agent cursor overlay during capture (default true) so the PNG is clean."
|
|
11405
|
+
},
|
|
10646
11406
|
space: spaceParam
|
|
10647
11407
|
},
|
|
10648
11408
|
buildScript: (args) => {
|
|
10649
11409
|
const sel = str(args.selector, "");
|
|
10650
11410
|
const pth = str(args.path, "");
|
|
11411
|
+
const hideCursor = args.hideCursor !== false;
|
|
10651
11412
|
const shot = sel !== "" ? `await page.locator(${j(sel)}).screenshot(${pth ? `{ path: ${j(pth)} }` : ""})` : `await page.screenshot(${pth ? `{ path: ${j(pth)} }` : ""})`;
|
|
10652
|
-
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`;
|
|
10653
11414
|
}
|
|
10654
11415
|
}));
|
|
10655
11416
|
reg(t({
|
|
@@ -11145,6 +11906,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
|
|
|
11145
11906
|
execute: async (args, exec) => withEgoLock(async () => {
|
|
11146
11907
|
cfg.spaceTracker.setCurrentSession(callingSessionId(exec), resolveEffectiveLink(cfg.links, cfg.activeTargetId)?.link.id ?? "");
|
|
11147
11908
|
markEgoToolCall(callingSessionId(exec));
|
|
11909
|
+
pendingViewport = cfg;
|
|
11148
11910
|
const result = await runWithStaleSpaceRetry(ctx, cfg, { signal: exec?.signal }, () => humanCheckScript(str(args.space, cfg.activeSpace)));
|
|
11149
11911
|
if (!result.ok) return {
|
|
11150
11912
|
ok: false,
|
|
@@ -11170,6 +11932,101 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
|
|
|
11170
11932
|
rawInput: null
|
|
11171
11933
|
})
|
|
11172
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
|
+
}));
|
|
11173
12030
|
reg(defineTool({
|
|
11174
12031
|
name: "bcdp_help",
|
|
11175
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.",
|
|
@@ -11241,6 +12098,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
|
|
|
11241
12098
|
timeoutMs: 25e3,
|
|
11242
12099
|
execute: async (_args, exec) => {
|
|
11243
12100
|
tiers.pulse(callingSessionId(exec));
|
|
12101
|
+
cfg.spaceTracker.setCurrentSession(callingSessionId(exec), resolveEffectiveLink(cfg.links, cfg.activeTargetId)?.link.id ?? "");
|
|
11244
12102
|
const lines = [];
|
|
11245
12103
|
{
|
|
11246
12104
|
const s = tiers.surface();
|
|
@@ -11272,6 +12130,10 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
|
|
|
11272
12130
|
const cliPoll = getCliPollStatus();
|
|
11273
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";
|
|
11274
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
|
+
}
|
|
11275
12137
|
{
|
|
11276
12138
|
const sid = callingSessionId(exec);
|
|
11277
12139
|
const pollSpace = cfg.spaceTracker.lastActiveSpace();
|
|
@@ -11403,6 +12265,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
|
|
|
11403
12265
|
execute: async (args, exec) => {
|
|
11404
12266
|
cfg.spaceTracker.setCurrentSession(callingSessionId(exec), resolveEffectiveLink(cfg.links, cfg.activeTargetId)?.link.id ?? "");
|
|
11405
12267
|
markEgoToolCall(callingSessionId(exec));
|
|
12268
|
+
pendingViewport = cfg;
|
|
11406
12269
|
const timeoutMs = typeof args.timeoutMs === "number" && Number.isFinite(args.timeoutMs) && args.timeoutMs > 0 ? args.timeoutMs : void 0;
|
|
11407
12270
|
const start = Date.now();
|
|
11408
12271
|
const verbatimMode = bool(args.verbatim, false);
|
|
@@ -11537,6 +12400,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
|
|
|
11537
12400
|
execute: async (_args, exec) => {
|
|
11538
12401
|
cfg.spaceTracker.setCurrentSession(callingSessionId(exec), resolveEffectiveLink(cfg.links, cfg.activeTargetId)?.link.id ?? "");
|
|
11539
12402
|
markEgoToolCall(callingSessionId(exec));
|
|
12403
|
+
pendingViewport = cfg;
|
|
11540
12404
|
const judge = judgeCfg();
|
|
11541
12405
|
const runtime = judgeRuntimeOf();
|
|
11542
12406
|
const { attach } = effectiveChannel(cfg);
|
|
@@ -11637,6 +12501,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
|
|
|
11637
12501
|
execute: async (args, exec) => {
|
|
11638
12502
|
cfg.spaceTracker.setCurrentSession(callingSessionId(exec), resolveEffectiveLink(cfg.links, cfg.activeTargetId)?.link.id ?? "");
|
|
11639
12503
|
markEgoToolCall(callingSessionId(exec));
|
|
12504
|
+
pendingViewport = cfg;
|
|
11640
12505
|
const blocked = attachGate();
|
|
11641
12506
|
if (blocked !== "") return {
|
|
11642
12507
|
ok: false,
|
|
@@ -11776,6 +12641,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
|
|
|
11776
12641
|
execute: async (args, exec) => {
|
|
11777
12642
|
cfg.spaceTracker.setCurrentSession(callingSessionId(exec), resolveEffectiveLink(cfg.links, cfg.activeTargetId)?.link.id ?? "");
|
|
11778
12643
|
markEgoToolCall(callingSessionId(exec));
|
|
12644
|
+
pendingViewport = cfg;
|
|
11779
12645
|
const blocked = attachGate();
|
|
11780
12646
|
if (blocked !== "") return {
|
|
11781
12647
|
ok: false,
|
|
@@ -11886,6 +12752,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
|
|
|
11886
12752
|
execute: async (args, exec) => {
|
|
11887
12753
|
cfg.spaceTracker.setCurrentSession(callingSessionId(exec), resolveEffectiveLink(cfg.links, cfg.activeTargetId)?.link.id ?? "");
|
|
11888
12754
|
markEgoToolCall(callingSessionId(exec));
|
|
12755
|
+
pendingViewport = cfg;
|
|
11889
12756
|
const blocked = attachGate();
|
|
11890
12757
|
if (blocked !== "") return {
|
|
11891
12758
|
ok: false,
|
|
@@ -11984,6 +12851,7 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
|
|
|
11984
12851
|
execute: async (args, exec) => {
|
|
11985
12852
|
cfg.spaceTracker.setCurrentSession(callingSessionId(exec), resolveEffectiveLink(cfg.links, cfg.activeTargetId)?.link.id ?? "");
|
|
11986
12853
|
markEgoToolCall(callingSessionId(exec));
|
|
12854
|
+
pendingViewport = cfg;
|
|
11987
12855
|
const blocked = attachGate();
|
|
11988
12856
|
if (blocked !== "") return {
|
|
11989
12857
|
ok: false,
|
|
@@ -12049,4 +12917,4 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
|
|
|
12049
12917
|
}
|
|
12050
12918
|
|
|
12051
12919
|
//#endregion
|
|
12052
|
-
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 };
|