dsh-browser-cdp 1.7.11 → 1.7.12

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/lib/index.js CHANGED
@@ -3354,6 +3354,666 @@ function normalizeProbeState(link) {
3354
3354
  };
3355
3355
  }
3356
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.
3417
+ */
3418
+ function buildFrame(input) {
3419
+ const limit = input.limit ?? DEFAULT_NODE_LIMIT;
3420
+ const now = input.now ?? (() => Date.now());
3421
+ const seen = /* @__PURE__ */ new Set();
3422
+ const nodes = [];
3423
+ let skipped = 0;
3424
+ for (const candidate of input.nodes) {
3425
+ if (nodes.length >= limit) break;
3426
+ if (!isInteractiveRole(candidate.role)) {
3427
+ skipped += 1;
3428
+ continue;
3429
+ }
3430
+ if (seen.has(candidate.backendNodeId)) continue;
3431
+ seen.add(candidate.backendNodeId);
3432
+ nodes.push({
3433
+ n: nodes.length + 1,
3434
+ backendNodeId: candidate.backendNodeId,
3435
+ role: candidate.role,
3436
+ name: candidate.name,
3437
+ rect: candidate.rect ?? null,
3438
+ state: {
3439
+ disabled: candidate.disabled === true,
3440
+ checked: candidate.checked === true,
3441
+ expanded: candidate.expanded === true,
3442
+ focusable: candidate.focusable === true
3443
+ },
3444
+ container: candidate.container ?? "page",
3445
+ containerLabel: candidate.containerLabel ?? "the page itself"
3446
+ });
3447
+ }
3448
+ const interactive = input.nodes.filter((candidate) => isInteractiveRole(candidate.role)).length;
3449
+ return {
3450
+ frame: {
3451
+ frameId: frameIdFor(input.target, input.documentRevision, input.seq),
3452
+ capturedAt: now(),
3453
+ target: input.target,
3454
+ viewport: input.viewport,
3455
+ image: input.image,
3456
+ dom: {
3457
+ nodes,
3458
+ total: interactive,
3459
+ truncated: false,
3460
+ source: "ax-tree"
3461
+ }
3462
+ },
3463
+ skippedNonInteractive: skipped
3464
+ };
3465
+ }
3466
+ /**
3467
+ * Decide whether this frame must be sliced.
3468
+ *
3469
+ * The order of the questions is deliberate: an image that fits and a candidate
3470
+ * list that fits means NO slicing, and most real pages land there (measured
3471
+ * 136.9 KiB / 26 candidates against a 1 MiB / 20-candidate set — the image is
3472
+ * fine, the candidates are not, which is why both are asked separately).
3473
+ */
3474
+ function planChunks(input) {
3475
+ const chunkSize = Math.max(1, input.chunkSize ?? DEFAULT_NODE_LIMIT);
3476
+ const overImage = input.imageBytes !== null && input.maxBytes > 0 && input.imageBytes > input.maxBytes;
3477
+ const overCandidates = input.candidateCount > chunkSize;
3478
+ if (!overImage && !overCandidates) return {
3479
+ chunkTotal: 1,
3480
+ chunkSize,
3481
+ reason: "fits",
3482
+ sizes: [input.candidateCount]
3483
+ };
3484
+ if (overImage && !overCandidates) return {
3485
+ chunkTotal: 1,
3486
+ chunkSize,
3487
+ reason: "image-over-budget",
3488
+ sizes: [input.candidateCount]
3489
+ };
3490
+ const chunkTotal = Math.ceil(input.candidateCount / chunkSize);
3491
+ const sizes = [];
3492
+ let remaining = input.candidateCount;
3493
+ while (remaining > 0) {
3494
+ const take = Math.min(chunkSize, remaining);
3495
+ sizes.push(take);
3496
+ remaining -= take;
3497
+ }
3498
+ return {
3499
+ chunkTotal,
3500
+ chunkSize,
3501
+ reason: overImage ? "both" : "too-many-candidates",
3502
+ sizes
3503
+ };
3504
+ }
3505
+ /**
3506
+ * Slice a frame's candidates into chunks, preserving document order.
3507
+ *
3508
+ * Out-of-range chunk numbers return `null` rather than wrapping: a `next` at the
3509
+ * boundary must surface as `no_more_chunks`, because a silent wrap turns a
3510
+ * budget problem into an infinite loop.
3511
+ */
3512
+ function sliceFrame(frame, plan, chunkIndex) {
3513
+ if (chunkIndex < 1 || chunkIndex > plan.chunkTotal) return null;
3514
+ const start = plan.sizes.slice(0, chunkIndex - 1).reduce((sum, size) => sum + size, 0);
3515
+ const count = plan.sizes[chunkIndex - 1] ?? 0;
3516
+ const nodes = frame.dom.nodes.slice(start, start + count);
3517
+ return {
3518
+ frameId: frame.frameId,
3519
+ chunkIndex,
3520
+ chunkTotal: plan.chunkTotal,
3521
+ itemCount: nodes.length,
3522
+ nodes,
3523
+ containerHint: dominantContainer(nodes)
3524
+ };
3525
+ }
3526
+ /** The container most of these nodes live in — the "is this chunk homogeneous" answer. */
3527
+ function dominantContainer(nodes) {
3528
+ if (nodes.length === 0) return "other";
3529
+ const counts = /* @__PURE__ */ new Map();
3530
+ for (const node of nodes) counts.set(node.container, (counts.get(node.container) ?? 0) + 1);
3531
+ let best = "other";
3532
+ let bestCount = -1;
3533
+ for (const [container, count] of counts) if (count > bestCount) {
3534
+ best = container;
3535
+ bestCount = count;
3536
+ }
3537
+ return best;
3538
+ }
3539
+ /**
3540
+ * Group candidates into chapters, in first-appearance order.
3541
+ *
3542
+ * Order is FIRST APPEARANCE, not alphabetical: a judge should be offered the
3543
+ * chapters in the order the page presents them, which is how a human reads it.
3544
+ */
3545
+ function chaptersOf(nodes) {
3546
+ const byKey = /* @__PURE__ */ new Map();
3547
+ for (const node of nodes) {
3548
+ const existing = byKey.get(node.container);
3549
+ if (existing === void 0) {
3550
+ byKey.set(node.container, {
3551
+ key: node.container,
3552
+ label: node.containerLabel,
3553
+ nodes: [node]
3554
+ });
3555
+ continue;
3556
+ }
3557
+ existing.nodes.push(node);
3558
+ }
3559
+ return [...byKey.values()];
3560
+ }
3561
+ /**
3562
+ * Whether narrowing through a chapter question is worth a round trip.
3563
+ *
3564
+ * `false` when there is only ONE chapter: a question with a single option is not
3565
+ * a question, it is a round trip that can only be answered one way. Skipping it
3566
+ * keeps the loop at two rounds on simple pages and three on busy ones.
3567
+ */
3568
+ function shouldAskChapter(nodes, chapterCount = chaptersOf(nodes).length) {
3569
+ return chapterCount > 1;
3570
+ }
3571
+
3572
+ //#endregion
3573
+ //#region src/cdp/session.ts
3574
+ var CdpSessionError = class extends Error {
3575
+ code;
3576
+ constructor(code, message) {
3577
+ super(message);
3578
+ this.name = "CdpSessionError";
3579
+ this.code = code;
3580
+ }
3581
+ };
3582
+ const DEFAULT_CONNECT_TIMEOUT_MS = 5e3;
3583
+ const DEFAULT_COMMAND_TIMEOUT_MS = 6e3;
3584
+ const DEFAULT_BACKOFF_SCHEDULE_MS = [
3585
+ 250,
3586
+ 500,
3587
+ 1e3,
3588
+ 2e3,
3589
+ 4e3
3590
+ ];
3591
+ const DEFAULT_TIMERS = {
3592
+ setTimeout: (fn, ms) => setTimeout(fn, ms),
3593
+ clearTimeout: (handle) => clearTimeout(handle)
3594
+ };
3595
+ function defaultCreateSocket(url) {
3596
+ const ctor = globalThis.WebSocket;
3597
+ if (ctor === void 0) throw new CdpSessionError("no-websocket", "no WebSocket implementation available — the host must supply createSocket (Node >= 22 provides a global WebSocket)");
3598
+ return new ctor(url);
3599
+ }
3600
+ var CdpSession = class {
3601
+ url;
3602
+ state = "idle";
3603
+ /** Replay failures from the most recent reconnect — surfaced, never swallowed. */
3604
+ lastReplayFailures = [];
3605
+ #options;
3606
+ #timers;
3607
+ #socket = null;
3608
+ #nextId = 0;
3609
+ #pending = /* @__PURE__ */ new Map();
3610
+ #events = /* @__PURE__ */ new Map();
3611
+ #replay = [];
3612
+ #attempt = 0;
3613
+ #intentionalClose = false;
3614
+ #reconnectTimer = null;
3615
+ constructor(options) {
3616
+ this.url = options.url;
3617
+ this.#options = {
3618
+ ...options,
3619
+ connectTimeoutMs: options.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS,
3620
+ commandTimeoutMs: options.commandTimeoutMs ?? DEFAULT_COMMAND_TIMEOUT_MS
3621
+ };
3622
+ this.#timers = options.timers ?? DEFAULT_TIMERS;
3623
+ }
3624
+ /**
3625
+ * The ordered enable sequence re-issued after every successful (re)connect.
3626
+ * M0.3 owns the ordering rules (`DOM.enable` before `Overlay.enable`); this
3627
+ * class only replays what it is handed, in the order it is handed.
3628
+ */
3629
+ setReplay(methods) {
3630
+ this.#replay = [...methods];
3631
+ }
3632
+ /**
3633
+ * Subscribe to one CDP event method, or to `'*'` for every event — M0.3
3634
+ * routes by domain, which needs a catch-all. A wildcard handler additionally
3635
+ * receives the fired method as its third argument.
3636
+ */
3637
+ on(method, handler) {
3638
+ if (!this.#events.has(method)) this.#events.set(method, /* @__PURE__ */ new Set());
3639
+ this.#events.get(method).add(handler);
3640
+ return () => {
3641
+ this.#events.get(method)?.delete(handler);
3642
+ };
3643
+ }
3644
+ #setState(state, detail) {
3645
+ this.state = state;
3646
+ this.#options.onStateChange?.(state, detail);
3647
+ }
3648
+ /** Dial and resolve once the socket is open. Rejects with a structured code. */
3649
+ connect() {
3650
+ if (this.state === "open") return Promise.resolve();
3651
+ if (this.state === "closed") return Promise.reject(new CdpSessionError("closed", "session was closed; create a new one instead of reusing it"));
3652
+ this.#setState("connecting");
3653
+ return this.#dial(this.#options.connectTimeoutMs);
3654
+ }
3655
+ #dial(timeoutMs) {
3656
+ return new Promise((resolve$1, reject) => {
3657
+ let settled = false;
3658
+ const finish$1 = (error) => {
3659
+ if (settled) return;
3660
+ settled = true;
3661
+ this.#timers.clearTimeout(timer);
3662
+ if (error) reject(error);
3663
+ else resolve$1();
3664
+ };
3665
+ const timer = this.#timers.setTimeout(() => {
3666
+ this.#teardown();
3667
+ finish$1(new CdpSessionError("connect-timeout", `no CDP open event from ${this.url} within ${timeoutMs}ms`));
3668
+ }, timeoutMs);
3669
+ let socket;
3670
+ try {
3671
+ socket = (this.#options.createSocket ?? defaultCreateSocket)(this.url);
3672
+ } catch (error) {
3673
+ finish$1(error instanceof CdpSessionError ? error : new CdpSessionError("connect-failed", String(error)));
3674
+ return;
3675
+ }
3676
+ this.#socket = socket;
3677
+ socket.addEventListener("open", () => {
3678
+ if (settled || this.#socket !== socket) return;
3679
+ this.#attempt = 0;
3680
+ this.#setState("open");
3681
+ finish$1();
3682
+ this.#replaySequence();
3683
+ });
3684
+ socket.addEventListener("message", (event) => {
3685
+ if (this.#socket !== socket) return;
3686
+ this.#handleMessage(event);
3687
+ });
3688
+ socket.addEventListener("close", () => {
3689
+ if (this.#socket !== socket) return;
3690
+ this.#handleUnexpectedClose("socket closed");
3691
+ });
3692
+ socket.addEventListener("error", (event) => {
3693
+ if (this.#socket !== socket) return;
3694
+ if (!settled) {
3695
+ this.#teardown();
3696
+ finish$1(new CdpSessionError("connect-failed", event?.message || `socket error dialing ${this.url}`));
3697
+ return;
3698
+ }
3699
+ this.#handleUnexpectedClose(event?.message || "socket error");
3700
+ });
3701
+ });
3702
+ }
3703
+ /**
3704
+ * Re-issue the enable sequence. Failures are recorded on
3705
+ * `lastReplayFailures` and reported through `onReplayError` — a silently
3706
+ * disabled domain is exactly the bug this method exists to prevent.
3707
+ */
3708
+ async #replaySequence() {
3709
+ if (this.#replay.length === 0) return;
3710
+ this.lastReplayFailures = [];
3711
+ for (const method of this.#replay) try {
3712
+ await this.call(method, {});
3713
+ } catch (error) {
3714
+ const failure = {
3715
+ method,
3716
+ message: error instanceof Error ? error.message : String(error)
3717
+ };
3718
+ this.lastReplayFailures.push(failure);
3719
+ this.#options.onReplayError?.(failure);
3720
+ }
3721
+ }
3722
+ #handleMessage(event) {
3723
+ let message;
3724
+ try {
3725
+ message = JSON.parse(typeof event.data === "string" ? event.data : String(event.data));
3726
+ } catch {
3727
+ return;
3728
+ }
3729
+ if (typeof message.id === "number" && this.#pending.has(message.id)) {
3730
+ const pending = this.#pending.get(message.id);
3731
+ this.#pending.delete(message.id);
3732
+ this.#timers.clearTimeout(pending.timer);
3733
+ if (message.error) {
3734
+ const error = new Error(message.error.message || `CDP error ${message.error.code}`);
3735
+ error.code = message.error.code;
3736
+ error.data = message.error.data;
3737
+ pending.reject(error);
3738
+ } else pending.resolve(message.result || {});
3739
+ return;
3740
+ }
3741
+ if (message.method === void 0) return;
3742
+ const method = message.method;
3743
+ const params = message.params || {};
3744
+ for (const key of [method, "*"]) for (const handler of this.#events.get(key) || []) try {
3745
+ handler(params, message.sessionId, method);
3746
+ } catch {}
3747
+ }
3748
+ #handleUnexpectedClose(detail) {
3749
+ this.#teardown();
3750
+ if (this.#intentionalClose || this.state === "closed") return;
3751
+ this.#scheduleReconnect(detail);
3752
+ }
3753
+ #scheduleReconnect(detail) {
3754
+ const schedule = this.#options.backoffScheduleMs ?? DEFAULT_BACKOFF_SCHEDULE_MS;
3755
+ const attempt = this.#attempt;
3756
+ if (attempt >= schedule.length) {
3757
+ this.#setState("closed", `reconnect exhausted after ${schedule.length} attempts (${detail})`);
3758
+ return;
3759
+ }
3760
+ this.#attempt = attempt + 1;
3761
+ const delay = schedule[attempt];
3762
+ this.#setState("reconnecting", `${detail}; retrying in ${delay}ms`);
3763
+ this.#reconnectTimer = this.#timers.setTimeout(() => {
3764
+ this.#reconnectTimer = null;
3765
+ this.#dial(this.#options.connectTimeoutMs).catch((error) => {
3766
+ this.#handleUnexpectedClose(error.message);
3767
+ });
3768
+ }, delay);
3769
+ }
3770
+ /** Reject everything in flight and forget the socket. Pending is never left hanging. */
3771
+ #teardown() {
3772
+ const socket = this.#socket;
3773
+ this.#socket = null;
3774
+ if (socket) try {
3775
+ socket.close();
3776
+ } catch {}
3777
+ for (const pending of this.#pending.values()) {
3778
+ this.#timers.clearTimeout(pending.timer);
3779
+ pending.reject(new CdpSessionError("socket-error", `CDP connection closed while ${pending.method} was in flight`));
3780
+ }
3781
+ this.#pending.clear();
3782
+ }
3783
+ /**
3784
+ * Send one command and await its reply.
3785
+ *
3786
+ * A call made while the socket is not open fails FAST with `not-open` rather
3787
+ * than queueing: a queued command would either run against a freshly
3788
+ * reconnected session (wrong domain state) or hang past the caller's own
3789
+ * deadline. Callers that can tolerate a reconnect should retry explicitly.
3790
+ */
3791
+ call(method, params = {}, options = {}) {
3792
+ if (this.#socket === null || this.state !== "open") return Promise.reject(new CdpSessionError("not-open", `cannot ${method}: session is ${this.state}, not open`));
3793
+ const timeoutMs = options.timeoutMs ?? this.#options.commandTimeoutMs;
3794
+ const id = ++this.#nextId;
3795
+ const payload = {
3796
+ id,
3797
+ method,
3798
+ params
3799
+ };
3800
+ if (options.sessionId !== void 0) payload.sessionId = options.sessionId;
3801
+ return new Promise((resolve$1, reject) => {
3802
+ const timer = this.#timers.setTimeout(() => {
3803
+ this.#pending.delete(id);
3804
+ reject(new CdpSessionError("command-timeout", `CDP ${method} timed out after ${timeoutMs}ms`));
3805
+ }, timeoutMs);
3806
+ this.#pending.set(id, {
3807
+ method,
3808
+ resolve: resolve$1,
3809
+ reject,
3810
+ timer
3811
+ });
3812
+ try {
3813
+ this.#socket.send(JSON.stringify(payload));
3814
+ } catch (error) {
3815
+ this.#timers.clearTimeout(timer);
3816
+ this.#pending.delete(id);
3817
+ reject(new CdpSessionError("socket-error", error instanceof Error ? error.message : String(error)));
3818
+ }
3819
+ });
3820
+ }
3821
+ /** Intentional shutdown: no reconnect, no retry. */
3822
+ close() {
3823
+ this.#intentionalClose = true;
3824
+ if (this.#reconnectTimer !== null) {
3825
+ this.#timers.clearTimeout(this.#reconnectTimer);
3826
+ this.#reconnectTimer = null;
3827
+ }
3828
+ this.#teardown();
3829
+ if (this.state !== "closed") this.#setState("closed", "closed by caller");
3830
+ }
3831
+ };
3832
+
3833
+ //#endregion
3834
+ //#region src/cdp/dom.ts
3835
+ /** Flatten `Accessibility.getFullAXTree` into the semantics the judge consumes. */
3836
+ function flattenAxTree(nodes) {
3837
+ const out = [];
3838
+ for (const node of nodes) {
3839
+ const focusable = (node.properties ?? []).find((property) => property.name === "focusable");
3840
+ out.push({
3841
+ nodeId: typeof node.nodeId === "string" ? node.nodeId : "",
3842
+ backendNodeId: Number.parseInt(typeof node.nodeId === "string" ? node.nodeId : "", 10) || 0,
3843
+ role: typeof node.role?.value === "string" ? node.role.value : "",
3844
+ name: typeof node.name?.value === "string" ? node.name.value : "",
3845
+ ignored: node.ignored === true,
3846
+ keyboardFocusable: focusable?.value?.value === true
3847
+ });
3848
+ }
3849
+ return out;
3850
+ }
3851
+ async function accessibilityTree(call, sessionId, timeoutMs) {
3852
+ try {
3853
+ const result = await call("Accessibility.getFullAXTree", {}, {
3854
+ ...sessionId === void 0 ? {} : { sessionId },
3855
+ ...timeoutMs === void 0 ? {} : { timeoutMs }
3856
+ });
3857
+ if (!Array.isArray(result?.nodes)) return {
3858
+ ok: false,
3859
+ code: "ax-tree-missing",
3860
+ message: "Accessibility.getFullAXTree returned no nodes array"
3861
+ };
3862
+ return {
3863
+ ok: true,
3864
+ nodes: flattenAxTree(result.nodes)
3865
+ };
3866
+ } catch (error) {
3867
+ return {
3868
+ ok: false,
3869
+ code: "ax-tree-failed",
3870
+ message: error instanceof Error ? error.message : String(error)
3871
+ };
3872
+ }
3873
+ }
3874
+
3875
+ //#endregion
3876
+ //#region src/tab-report.ts
3877
+ /** Report type the dock card keys on (`obj.type === TAB_REPORT_TYPE`). */
3878
+ const TAB_REPORT_TYPE = "tab-anchor-report";
3879
+ /** Hard ceiling: a huge page is TRUNCATED and the reader is told, never trimmed silently. */
3880
+ const MAX_REPORT_ELEMENTS = 200;
3881
+ /** Per-capture CDP deadline (plan 约束 §: 单次抓取超时 15s → capture-timeout). */
3882
+ const TAB_REPORT_TIMEOUT_MS = 15e3;
3883
+ /** File-name prefix — must not collide with the pick archive (`picks-…`). */
3884
+ const TAB_REPORT_FILE_PREFIX = "tab-";
3885
+ /** Domains the report needs, in the order CDP requires them (F10: DOM before anything that reads nodes). */
3886
+ const REPORT_ENABLE_METHODS = ["DOM.enable", "Accessibility.enable"];
3887
+ /** Engines that cannot answer a node query; a report from one degrades to URL+title only. */
3888
+ const DEGRADED_ENGINE = "lightpanda";
3889
+ var TabReportError = class extends Error {
3890
+ code;
3891
+ constructor(code, message) {
3892
+ super(message);
3893
+ this.name = "TabReportError";
3894
+ this.code = code;
3895
+ }
3896
+ };
3897
+ /**
3898
+ * The capture identity. `frameId` in the JE loop is a content hash of the page
3899
+ * state; here there is no documentRevision to hash, so the plan's URL+timestamp
3900
+ * combination is what guarantees two captures of the same page mint different
3901
+ * anchors. Same page + same second = same scope (findings: accepted trade-off).
3902
+ */
3903
+ function reportScope(pageUrl, capturedAt) {
3904
+ return createHash("sha256").update(`${pageUrl}\0${capturedAt}`).digest("hex").slice(0, 32);
3905
+ }
3906
+ /**
3907
+ * Number the interactive candidates of one AX snapshot, in document order.
3908
+ * Same rules as cdp/marks.ts: ignored nodes are skipped, duplicates dropped by
3909
+ * node id, the ceiling caps the set, and the cap is REPORTED as `truncated`.
3910
+ */
3911
+ function numberReportNodes(nodes, scope, maxElements = MAX_REPORT_ELEMENTS) {
3912
+ const out = [];
3913
+ const seen = /* @__PURE__ */ new Set();
3914
+ let total = 0;
3915
+ for (const node of nodes) {
3916
+ if (node.ignored || !isInteractiveRole(node.role)) continue;
3917
+ if (node.backendNodeId === 0 || seen.has(node.backendNodeId)) continue;
3918
+ seen.add(node.backendNodeId);
3919
+ total += 1;
3920
+ if (out.length >= maxElements) continue;
3921
+ out.push({
3922
+ anchor: anchorFor(scope, node.backendNodeId),
3923
+ n: out.length + 1,
3924
+ role: node.role,
3925
+ name: node.name,
3926
+ backendNodeId: node.backendNodeId
3927
+ });
3928
+ }
3929
+ return {
3930
+ elements: out,
3931
+ total,
3932
+ truncated: total > maxElements
3933
+ };
3934
+ }
3935
+ /**
3936
+ * Open a SHORT-LIVED browser-level session, attach the one target, and read its
3937
+ * accessibility tree. This does NOT touch the resident cast worker: a second
3938
+ * CDP client on the same browser endpoint is normal (that is how the tools and
3939
+ * the screencast already coexist). The meta (url/title) comes from a single
3940
+ * `Runtime.evaluate` so the report is stamped at the SAME instant as its
3941
+ * elements, not from a possibly-stale spaces row.
3942
+ */
3943
+ async function defaultFetchAx(input, deps = {}) {
3944
+ if (input.engine === DEGRADED_ENGINE) return {
3945
+ pageUrl: input.urlHint ?? "",
3946
+ pageTitle: input.titleHint ?? "",
3947
+ nodes: [],
3948
+ degraded: true
3949
+ };
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
+ }
3993
+ }
3994
+ /**
3995
+ * Build one tab-anchor report. Pure beyond the AX read: scope + numbering are
3996
+ * `reportScope` / `numberReportNodes`, both already unit-testable in isolation.
3997
+ */
3998
+ async function captureTabReport(input, deps = {}) {
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);
4003
+ return {
4004
+ type: TAB_REPORT_TYPE,
4005
+ cdpEndpoint: input.wsUrl,
4006
+ targetId: input.targetId,
4007
+ pageUrl: snapshot.pageUrl,
4008
+ pageTitle: snapshot.pageTitle,
4009
+ frameId: scope,
4010
+ capturedAt,
4011
+ elements: numbered.elements,
4012
+ truncated: numbered.truncated,
4013
+ ...snapshot.degraded ? { degraded: "lightpanda" } : {}
4014
+ };
4015
+ }
4016
+
3357
4017
  //#endregion
3358
4018
  //#region src/gateway.ts
3359
4019
  /** HTTP route prefix owning every ego-browser API request. */
@@ -3505,6 +4165,54 @@ function registerEgoBrowserGateway(ctx, bridge, ffmpegManager, picks) {
3505
4165
  } catch (error) {
3506
4166
  writeJson(res, 404, envelopeError("not-found", error instanceof Error ? error.message : String(error)));
3507
4167
  }
4168
+ } else if (method === "tab-anchor-report") {
4169
+ const repSession = typeof body.session === "string" ? body.session : void 0;
4170
+ const repDir = picks ? picks.resolveDir(repSession) : void 0;
4171
+ if (!repDir) {
4172
+ writeJson(res, 409, envelopeError("no-workspace", "no registered workspace resolves for this session"));
4173
+ return;
4174
+ }
4175
+ const repTargetId = typeof body.targetId === "string" ? body.targetId : "";
4176
+ if (repTargetId === "") {
4177
+ writeJson(res, 400, envelopeError("invalid-target", "targetId is required"));
4178
+ return;
4179
+ }
4180
+ 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
+ const urlHint = typeof body.url === "string" ? body.url : "";
4186
+ const titleHint = typeof body.title === "string" ? body.title : "";
4187
+ let report;
4188
+ try {
4189
+ report = await captureTabReport({
4190
+ wsUrl: attach.wsUrl,
4191
+ targetId: repTargetId,
4192
+ engine: attach.engine,
4193
+ urlHint,
4194
+ titleHint
4195
+ });
4196
+ } catch (error) {
4197
+ const code = error?.code || "capture-failed";
4198
+ writeJson(res, code === "invalid-target" ? 409 : 502, envelopeError(code, error instanceof Error ? error.message : String(error)));
4199
+ return;
4200
+ }
4201
+ const repFile = typeof body.file === "string" && /^[A-Za-z0-9._-]+\.json$/.test(body.file) ? body.file : `${TAB_REPORT_FILE_PREFIX}${repTargetId.slice(0, 8)}-${Date.now()}.json`;
4202
+ await mkdir(repDir, { recursive: true });
4203
+ const repTargetPath = resolve(repDir, repFile);
4204
+ if (!repTargetPath.startsWith(resolve(repDir))) {
4205
+ writeJson(res, 400, envelopeError("invalid-path", "path escapes the picks dir"));
4206
+ return;
4207
+ }
4208
+ await writeFile(repTargetPath, JSON.stringify(report, null, 2), "utf8");
4209
+ writeJson(res, 200, envelopeOk({
4210
+ file: repFile,
4211
+ token: `@"picks/${repFile}"`,
4212
+ count: report.elements.length,
4213
+ truncated: report.truncated,
4214
+ degraded: report.degraded ?? null
4215
+ }));
3508
4216
  } else writeJson(res, 404, envelopeError("not-found", `unknown ego-browser API method "${method}"`));
3509
4217
  } catch (error) {
3510
4218
  const e = error;
@@ -5875,203 +6583,6 @@ function describeJudge(runtime) {
5875
6583
  }
5876
6584
  const pad = (name$1) => (name$1 + " ").slice(0, 9);
5877
6585
 
5878
- //#endregion
5879
- //#region src/jev/frame.ts
5880
- /** Roles worth numbering. Mirrors src/cdp/marks.ts so both paths agree. */
5881
- const INTERACTIVE_ROLES = [
5882
- "button",
5883
- "link",
5884
- "textbox",
5885
- "searchbox",
5886
- "combobox",
5887
- "checkbox",
5888
- "radio",
5889
- "menuitem",
5890
- "menuitemcheckbox",
5891
- "menuitemradio",
5892
- "tab",
5893
- "option",
5894
- "switch",
5895
- "slider"
5896
- ];
5897
- function isInteractiveRole(role) {
5898
- return INTERACTIVE_ROLES.includes(role);
5899
- }
5900
- /**
5901
- * A stable frame id.
5902
- *
5903
- * Built from facts that identify WHICH page state this is — target, document
5904
- * revision, capture sequence — rather than from a timestamp, so the same state
5905
- * captured twice hashes the same and a log can be re-derived. `seq` is what
5906
- * keeps two captures of an unchanged document distinct.
5907
- */
5908
- function frameIdFor(target, documentRevision, seq) {
5909
- return createHash("sha256").update(`${target.targetId}\u0000${documentRevision}\u0000${seq}`).digest("hex").slice(0, 16);
5910
- }
5911
- /** Default candidate cap. Matches the chunk ceiling — see THRESHOLD_BUCKETS. */
5912
- const DEFAULT_NODE_LIMIT = 20;
5913
- /**
5914
- * Number the interactive candidates and freeze them into a frame.
5915
- *
5916
- * Order is DOCUMENT order (the AX tree arrives in it), duplicates by backend
5917
- * node id are dropped, and `limit` caps the set BEFORE numbering — so `n = 1..N`
5918
- * is contiguous and a judge that answers `n = 7` is answering about a candidate
5919
- * the caller can find by index, always.
5920
- */
5921
- function buildFrame(input) {
5922
- const limit = input.limit ?? DEFAULT_NODE_LIMIT;
5923
- const now = input.now ?? (() => Date.now());
5924
- const seen = /* @__PURE__ */ new Set();
5925
- const nodes = [];
5926
- let skipped = 0;
5927
- for (const candidate of input.nodes) {
5928
- if (nodes.length >= limit) break;
5929
- if (!isInteractiveRole(candidate.role)) {
5930
- skipped += 1;
5931
- continue;
5932
- }
5933
- if (seen.has(candidate.backendNodeId)) continue;
5934
- seen.add(candidate.backendNodeId);
5935
- nodes.push({
5936
- n: nodes.length + 1,
5937
- backendNodeId: candidate.backendNodeId,
5938
- role: candidate.role,
5939
- name: candidate.name,
5940
- rect: candidate.rect ?? null,
5941
- state: {
5942
- disabled: candidate.disabled === true,
5943
- checked: candidate.checked === true,
5944
- expanded: candidate.expanded === true,
5945
- focusable: candidate.focusable === true
5946
- },
5947
- container: candidate.container ?? "page",
5948
- containerLabel: candidate.containerLabel ?? "the page itself"
5949
- });
5950
- }
5951
- const interactive = input.nodes.filter((candidate) => isInteractiveRole(candidate.role)).length;
5952
- return {
5953
- frame: {
5954
- frameId: frameIdFor(input.target, input.documentRevision, input.seq),
5955
- capturedAt: now(),
5956
- target: input.target,
5957
- viewport: input.viewport,
5958
- image: input.image,
5959
- dom: {
5960
- nodes,
5961
- total: interactive,
5962
- truncated: false,
5963
- source: "ax-tree"
5964
- }
5965
- },
5966
- skippedNonInteractive: skipped
5967
- };
5968
- }
5969
- /**
5970
- * Decide whether this frame must be sliced.
5971
- *
5972
- * The order of the questions is deliberate: an image that fits and a candidate
5973
- * list that fits means NO slicing, and most real pages land there (measured
5974
- * 136.9 KiB / 26 candidates against a 1 MiB / 20-candidate set — the image is
5975
- * fine, the candidates are not, which is why both are asked separately).
5976
- */
5977
- function planChunks(input) {
5978
- const chunkSize = Math.max(1, input.chunkSize ?? DEFAULT_NODE_LIMIT);
5979
- const overImage = input.imageBytes !== null && input.maxBytes > 0 && input.imageBytes > input.maxBytes;
5980
- const overCandidates = input.candidateCount > chunkSize;
5981
- if (!overImage && !overCandidates) return {
5982
- chunkTotal: 1,
5983
- chunkSize,
5984
- reason: "fits",
5985
- sizes: [input.candidateCount]
5986
- };
5987
- if (overImage && !overCandidates) return {
5988
- chunkTotal: 1,
5989
- chunkSize,
5990
- reason: "image-over-budget",
5991
- sizes: [input.candidateCount]
5992
- };
5993
- const chunkTotal = Math.ceil(input.candidateCount / chunkSize);
5994
- const sizes = [];
5995
- let remaining = input.candidateCount;
5996
- while (remaining > 0) {
5997
- const take = Math.min(chunkSize, remaining);
5998
- sizes.push(take);
5999
- remaining -= take;
6000
- }
6001
- return {
6002
- chunkTotal,
6003
- chunkSize,
6004
- reason: overImage ? "both" : "too-many-candidates",
6005
- sizes
6006
- };
6007
- }
6008
- /**
6009
- * Slice a frame's candidates into chunks, preserving document order.
6010
- *
6011
- * Out-of-range chunk numbers return `null` rather than wrapping: a `next` at the
6012
- * boundary must surface as `no_more_chunks`, because a silent wrap turns a
6013
- * budget problem into an infinite loop.
6014
- */
6015
- function sliceFrame(frame, plan, chunkIndex) {
6016
- if (chunkIndex < 1 || chunkIndex > plan.chunkTotal) return null;
6017
- const start = plan.sizes.slice(0, chunkIndex - 1).reduce((sum, size) => sum + size, 0);
6018
- const count = plan.sizes[chunkIndex - 1] ?? 0;
6019
- const nodes = frame.dom.nodes.slice(start, start + count);
6020
- return {
6021
- frameId: frame.frameId,
6022
- chunkIndex,
6023
- chunkTotal: plan.chunkTotal,
6024
- itemCount: nodes.length,
6025
- nodes,
6026
- containerHint: dominantContainer(nodes)
6027
- };
6028
- }
6029
- /** The container most of these nodes live in — the "is this chunk homogeneous" answer. */
6030
- function dominantContainer(nodes) {
6031
- if (nodes.length === 0) return "other";
6032
- const counts = /* @__PURE__ */ new Map();
6033
- for (const node of nodes) counts.set(node.container, (counts.get(node.container) ?? 0) + 1);
6034
- let best = "other";
6035
- let bestCount = -1;
6036
- for (const [container, count] of counts) if (count > bestCount) {
6037
- best = container;
6038
- bestCount = count;
6039
- }
6040
- return best;
6041
- }
6042
- /**
6043
- * Group candidates into chapters, in first-appearance order.
6044
- *
6045
- * Order is FIRST APPEARANCE, not alphabetical: a judge should be offered the
6046
- * chapters in the order the page presents them, which is how a human reads it.
6047
- */
6048
- function chaptersOf(nodes) {
6049
- const byKey = /* @__PURE__ */ new Map();
6050
- for (const node of nodes) {
6051
- const existing = byKey.get(node.container);
6052
- if (existing === void 0) {
6053
- byKey.set(node.container, {
6054
- key: node.container,
6055
- label: node.containerLabel,
6056
- nodes: [node]
6057
- });
6058
- continue;
6059
- }
6060
- existing.nodes.push(node);
6061
- }
6062
- return [...byKey.values()];
6063
- }
6064
- /**
6065
- * Whether narrowing through a chapter question is worth a round trip.
6066
- *
6067
- * `false` when there is only ONE chapter: a question with a single option is not
6068
- * a question, it is a round trip that can only be answered one way. Skipping it
6069
- * keeps the loop at two rounds on simple pages and three on busy ones.
6070
- */
6071
- function shouldAskChapter(nodes, chapterCount = chaptersOf(nodes).length) {
6072
- return chapterCount > 1;
6073
- }
6074
-
6075
6586
  //#endregion
6076
6587
  //#region src/jev/prompt.ts
6077
6588
  const DEFAULT_HISTORY_LIMIT = 5;
@@ -6730,24 +7241,6 @@ function codeOf(code) {
6730
7241
  }
6731
7242
  const messageOf$1 = (value) => value instanceof Error ? value.message : String(value);
6732
7243
 
6733
- //#endregion
6734
- //#region src/jev/anchors.ts
6735
- /** Fixed prefix so an anchor is recognizable in a transcript at a glance. */
6736
- const ANCHOR_PREFIX = "sb-";
6737
- /** Hex length after the prefix — half a sha256, collision-safe for this use. */
6738
- const ANCHOR_HEX = 16;
6739
- /**
6740
- * Mint the anchor for one candidate inside one snapshot scope.
6741
- *
6742
- * `scope` is the frame identity (`frame.frameId`) in the current pipeline; any
6743
- * caller with a different snapshot notion passes its own scope string — the
6744
- * function only demands that different snapshots produce different scope
6745
- * strings, which is exactly what frameId guarantees.
6746
- */
6747
- function anchorFor(scope, backendNodeId) {
6748
- return `${ANCHOR_PREFIX}${createHash("sha256").update(`${scope}\0${backendNodeId}`).digest("hex").slice(0, ANCHOR_HEX)}`;
6749
- }
6750
-
6751
7244
  //#endregion
6752
7245
  //#region src/jev/attempt.ts
6753
7246
  /** Fixed question id; the judge's answer key for every round. */