@tea-agent/loop-agent 0.55.0-next.2 → 0.55.0-next.4

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.
Files changed (95) hide show
  1. package/CHANGELOG.md +9 -1
  2. package/dist/build-stamp.json +3 -3
  3. package/dist/worker/console/chat/browser-automation.js +497 -23
  4. package/dist/worker/console/chat/browser-cdp.js +145 -0
  5. package/dist/worker/console/chat/browser-evaluation.js +26 -25
  6. package/dist/worker/console/chat/browser-exposure.js +7 -6
  7. package/dist/worker/console/chat/browser-la.js +266 -0
  8. package/dist/worker/console/chat/browser-policy.js +5 -4
  9. package/dist/worker/console/chat/browser-preload.js +119 -0
  10. package/dist/worker/console/chat/browser-preloads/vcp.js +417 -0
  11. package/dist/worker/console/chat/browser-region-fingerprint.js +36 -0
  12. package/dist/worker/console/chat/browser-run.js +97 -0
  13. package/dist/worker/console/chat/browser-screenshot-result.js +2 -2
  14. package/dist/worker/console/chat/browser-scripts.js +42 -4
  15. package/dist/worker/console/chat/browser-timeline.js +4 -0
  16. package/dist/worker/console/chat/pi-runtime/custom-tools/browser-tools.js +72 -9
  17. package/dist/worker/console/chat/pi-runtime/sdk-bindings.js +70 -0
  18. package/dist/worker/console/chat/pi-runtime.js +24 -3
  19. package/dist/worker/console/chat/png-fingerprint.js +189 -0
  20. package/dist/worker/console/chat/repo-browser.js +4 -1
  21. package/dist/worker/console/chat/routes.js +30 -38
  22. package/dist/worker/console/chat/session-store.js +7 -21
  23. package/dist/worker/console/chat/terminal-sessions.js +1 -1
  24. package/dist/worker/console/chat/terminal-tools.js +1 -0
  25. package/dist/worker/console/chat/tool-exposure-catalog.js +2 -2
  26. package/dist/worker/console/chat/tools.js +2 -0
  27. package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-C29lbS0T.js → abnfDiagram-N423BO3Z-DorTQneS.js} +1 -1
  28. package/dist/worker/console/static/assets/{arc--Vi-BzUR.js → arc-C9C1QC-T.js} +1 -1
  29. package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-DwdFPJd-.js → architectureDiagram-T3A2C74G-BjUOrgf8.js} +1 -1
  30. package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-BFuPq4yu.js → blockDiagram-VBNYF7ZC-BAGMZaHb.js} +1 -1
  31. package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-oKn9EfQa.js → c4Diagram-5PPSVZJV-CySIZtrC.js} +1 -1
  32. package/dist/worker/console/static/assets/channel-BG_uDZNA.js +1 -0
  33. package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-TwXtrEhU.js → chunk-2GRJ4B5K-BkmWz795.js} +1 -1
  34. package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-Cc3zFHjT.js → chunk-2Q5K7J3B-CRmOCK3j.js} +1 -1
  35. package/dist/worker/console/static/assets/{chunk-5RXB4S5H-xJfu4YKo.js → chunk-5RXB4S5H-B8niEWUo.js} +1 -1
  36. package/dist/worker/console/static/assets/{chunk-5VM5RSS4-VBNdtRqb.js → chunk-5VM5RSS4-Y8foS4t5.js} +1 -1
  37. package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-DxhJidW7.js → chunk-6Q2QTUOP-DJF0Bubr.js} +1 -1
  38. package/dist/worker/console/static/assets/{chunk-GF5L2VYU-P6N3qPX5.js → chunk-GF5L2VYU-EKpddtbq.js} +1 -1
  39. package/dist/worker/console/static/assets/{chunk-JWPE2WC7-LE21hHhq.js → chunk-JWPE2WC7-CIgPpaGU.js} +1 -1
  40. package/dist/worker/console/static/assets/{chunk-KBJHAD2P-CZmtvzKZ.js → chunk-KBJHAD2P-DYMTSX0m.js} +1 -1
  41. package/dist/worker/console/static/assets/{chunk-RYQCIY6F-BQrw57-q.js → chunk-RYQCIY6F-4Rc5-0f5.js} +1 -1
  42. package/dist/worker/console/static/assets/{chunk-XXDRQBXY-DSNQHlxO.js → chunk-XXDRQBXY-CEy2M6-D.js} +1 -1
  43. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-jTs8Eyzt.js +1 -0
  44. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-jTs8Eyzt.js +1 -0
  45. package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-Ckm2oC4s.js → cose-bilkent-JH36ORCC-C51nJqVR.js} +1 -1
  46. package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-B7ecDXon.js → cynefinDiagram-MW4NZA55-DPQzOJZA.js} +1 -1
  47. package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-Cx_kCtwr.js → dagre-VZM6K2ZE-CG8IAqCo.js} +1 -1
  48. package/dist/worker/console/static/assets/{diagram-7IWD3JNH-DTqfz-9k.js → diagram-7IWD3JNH-BG3tT1MS.js} +1 -1
  49. package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-BH8nNNYl.js → diagram-B4RE2ZJO-DKOhR49M.js} +1 -1
  50. package/dist/worker/console/static/assets/{diagram-LBJQPF4R-mwUmtiIR.js → diagram-LBJQPF4R--nGLO7eB.js} +1 -1
  51. package/dist/worker/console/static/assets/{diagram-Q27KOJAE-B6_cW-cc.js → diagram-Q27KOJAE-CNDuz0fc.js} +1 -1
  52. package/dist/worker/console/static/assets/{diagram-UB23O5K3-D1sGiHf5.js → diagram-UB23O5K3-BvEiy0I0.js} +1 -1
  53. package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR-C07tYieV.js → ebnfDiagram-BXEA7PRR-BvjtUlUv.js} +1 -1
  54. package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-eHwocxI1.js → erDiagram-JOGREHBK-B-r_PRCK.js} +1 -1
  55. package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-B1B-mb0t.js → flowDiagram-UKHOOZJN-DlGW_rBu.js} +1 -1
  56. package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-B2fpno6f.js → ganttDiagram-PKOTCBZU-CcJKXiNh.js} +1 -1
  57. package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-DcM98HR9.js → gitGraphDiagram-DS77QQ5N-BXWxDYEd.js} +1 -1
  58. package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-edHmAaaC.js → infoDiagram-6WML65LV-asY8RPy4.js} +1 -1
  59. package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-Df_rsjoZ.js → ishikawaDiagram-WSZJBQD7-6yhDpeCu.js} +1 -1
  60. package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-BqK30536.js → journeyDiagram-NVQOT4AX-KybqaztS.js} +1 -1
  61. package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-DCvcYw-F.js → kanban-definition-27J2QSJJ-BUdunoPK.js} +1 -1
  62. package/dist/worker/console/static/assets/{linear-4rMK0UAe.js → linear-BAwJ_AJw.js} +1 -1
  63. package/dist/worker/console/static/assets/main-CIG4h5Yv.css +1 -0
  64. package/dist/worker/console/static/assets/{main-CBjwyx0a.js → main-CoWJVNrX.js} +141 -141
  65. package/dist/worker/console/static/assets/{mermaid.core-CIeuqFlz.js → mermaid.core-BwGdPtCr.js} +4 -4
  66. package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-isklXv_u.js → mindmap-definition-FAOFIHXS-wo8SEwby.js} +1 -1
  67. package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-DufJ3B32.js → pegDiagram-VL7TDLO6-DeuXnF7o.js} +1 -1
  68. package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-e-dscJOX.js → pieDiagram-7S7Q4E2Y-Hn7SpOAL.js} +1 -1
  69. package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-BMXdwlfZ.js → quadrantDiagram-CIZ2JOQS-WZ9z9PP1.js} +1 -1
  70. package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-BkLHnA2m.js → railroadDiagram-AXF67PYL-Dl4Y5VeR.js} +1 -1
  71. package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-BzXmvm6l.js → requirementDiagram-LRYGKXZP-B-3z0VEC.js} +1 -1
  72. package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-BZuur-BM.js → sankeyDiagram-W5VNT64P-D5LDd4et.js} +1 -1
  73. package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-DbZxmtRn.js → sequenceDiagram-SI44F4Z6-CeeqbPrw.js} +1 -1
  74. package/dist/worker/console/static/assets/{sheet-workbook-D_6Enbgn.js → sheet-workbook-BVfUI4fR.js} +1 -1
  75. package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-BHbP5ADt.js → sizeCapture-X5ZJPWSS-DdhhZwAv.js} +1 -1
  76. package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-CGNrvQQV.js → stateDiagram-OKZ733FA-DNTAm9ba.js} +1 -1
  77. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-B5Xi7PDb.js +1 -0
  78. package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-BWNaMfHj.js → swimlanes-SLNWSIFB-D8Jdwx7C.js} +2 -2
  79. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-DaLAC9v3.js +8 -0
  80. package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-BhI167N4.js → timeline-definition-Z64GVDOM-BaI43sL9.js} +1 -1
  81. package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-BFHqLPNk.js → vennDiagram-T6HMQDX7-D5uEn-T3.js} +1 -1
  82. package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-D-ThxcCm.js → wardleyDiagram-T6FBY63Y-D76Tmp1x.js} +1 -1
  83. package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-CeUzoGed.js → xychartDiagram-ELKLHX3M-Bv8QF2pr.js} +1 -1
  84. package/dist/worker/console/static/index.html +2 -2
  85. package/dist/worker/console/static-src/operator-chat/useChatSessions.js +140 -34
  86. package/dist/worker/console/static-src/operator-chat/useChatStream.js +6 -0
  87. package/dist/worker/console/static-src/operator-chat/useChatThread.js +5 -0
  88. package/docs/architecture/runtime-boundaries.md +5 -0
  89. package/package.json +3 -3
  90. package/dist/worker/console/static/assets/channel-o_uspxIc.js +0 -1
  91. package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-BAMhQfS-.js +0 -1
  92. package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-BAMhQfS-.js +0 -1
  93. package/dist/worker/console/static/assets/main-CGnkpKqw.css +0 -1
  94. package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-Oa0mw2RA.js +0 -1
  95. package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-CylkK52a.js +0 -8
@@ -4,10 +4,14 @@
4
4
  * reused across Console restarts, so login state and downloads remain
5
5
  * isolated from the user's normal browser without contaminating the repo.
6
6
  */
7
+ import { BrowserCdpSocket, boundJsonResult, CdpEventLog, reconcileCdpDomains } from "./browser-cdp.js";
8
+ import { checkedIgnoreRects, fingerprintRegionPng, RegionFingerprintError } from "./browser-region-fingerprint.js";
7
9
  import { BrowserInspectionStore, BrowserInspectionError, inspectionViewport } from "./browser-inspection.js";
8
- import { randomUUID } from "node:crypto";
10
+ import { createHmac, randomUUID } from "node:crypto";
11
+ import { setTimeout as delay } from "node:timers/promises";
9
12
  import { constants } from "node:fs";
10
- import { mkdir, open, readFile, readdir, stat, rm, writeFile } from "node:fs/promises";
13
+ import { mkdirSync, readdirSync, statSync, unlinkSync, writeFileSync } from "node:fs";
14
+ import { mkdir, open, readFile, readlink, readdir, stat, rm, writeFile } from "node:fs/promises";
11
15
  import path from "node:path";
12
16
  import { decodeAriaRefEntry, retainBrowserObservation, projectBrowserObservation, validateObservationBudget, validateBrowserObserve } from "./browser-observation.js";
13
17
  import { chromium, } from "playwright-core";
@@ -15,7 +19,9 @@ import { pickBrowserElement, pickLivePageElement } from "./browser-pick.js";
15
19
  import { browserHtmlToMarkdown, captureBrowserHtml } from "./browser-content.js";
16
20
  import { exportBrowserStorage, mergeBrowserStorage, readBrowserStorage } from "./browser-storage.js";
17
21
  import { evaluateBrowserExpression, waitForBrowserOperation } from "./browser-evaluation.js";
22
+ import { bindRunLa, BROWSER_RUN_CODE_MAX, BROWSER_RUN_TIMEOUT_DEFAULT_MS, BROWSER_RUN_TIMEOUT_MAX_MS, createRunLog, invokeBrowserCode, materializeRunValue } from "./browser-run.js";
18
23
  import { BrowserOperationQueue } from "./browser-operation-queue.js";
24
+ import { installPreloadsFromEnv } from "./browser-preload.js";
19
25
  import { BrowserPerformance } from "./browser-performance.js";
20
26
  import { normalizeBrowserUrl } from "./browser-policy.js";
21
27
  import { ApiWorkbenchCapture } from "./api-workbench-capture.js";
@@ -48,6 +54,13 @@ const NAVIGATION_SETTLE_CAP_MS = 2_000;
48
54
  const SEARCH_RESULT_TIMEOUT_MS = 15_000;
49
55
  const MAX_SNAPSHOT_CHARS = 24_000;
50
56
  const MAX_SCREENSHOT_BYTES = 4 * 1024 * 1024;
57
+ /** Draft punctuation shared by the tool schema and runtime preflight; Enter/Tab/newlines stay excluded. */
58
+ export const BROWSER_DRAFT_KEY_PATTERN = "^(?:[a-zA-Z0-9]|Space|Backspace|[.\\-/=:,_])$";
59
+ export const BROWSER_CANVAS_ID_PATTERN = "^[a-zA-Z0-9_-]{1,80}$";
60
+ export const MAX_BROWSER_DRAFT_KEYS = 64;
61
+ export const BROWSER_DRAFT_REFOCUS_MODES = ["never", "body-once"];
62
+ /** Caret-sized rectangles, relative to the region, excluded from the fingerprint only. */
63
+ export { MAX_BROWSER_IGNORE_RECTS, MAX_BROWSER_IGNORE_WIDTH, MAX_BROWSER_IGNORE_HEIGHT } from "./browser-region-fingerprint.js";
51
64
  export class BrowserAutomationService {
52
65
  options;
53
66
  performance;
@@ -82,6 +95,14 @@ export class BrowserAutomationService {
82
95
  mirrorStarting;
83
96
  /** Remember a seatbelt failure so later launches skip the sandbox without another crash. */
84
97
  sandboxFallback = false;
98
+ /** Document-start scripts registered on the launched context (empty by default). */
99
+ preloads = [];
100
+ cdpEndpoint = null;
101
+ cdpEndpointError;
102
+ /** In-flight endpoint-file removal so dispose waits for the context-close cleanup. */
103
+ cdpCleanup = Promise.resolve();
104
+ pageCdp = new Map();
105
+ browserSocket;
85
106
  constructor(options) {
86
107
  this.options = options;
87
108
  this.performance = new BrowserPerformance(options.performance);
@@ -271,12 +292,13 @@ export class BrowserAutomationService {
271
292
  * encoding on every panel poll.
272
293
  */
273
294
  async state() {
295
+ const cdp = this.cdpEndpointState();
274
296
  if (!this.browserPromise && !this.disposed)
275
- return { ...emptyBrowserState(), headless: this.options.headless === true, sandboxFallback: this.sandboxFallback || undefined };
297
+ return { ...emptyBrowserState(), headless: this.options.headless === true, sandboxFallback: this.sandboxFallback || undefined, ...cdp };
276
298
  // Polling never starts a context, changes selection, or waits on a quarantined page.
277
299
  const page = this.operations.current?.target.page ?? this.activePage;
278
300
  if (!page || page.isClosed())
279
- return { ...emptyBrowserState(), running: !!this.browserPromise, headless: this.options.headless === true, sandboxFallback: this.sandboxFallback || undefined, tabs: await this.tabSummaries() };
301
+ return { ...emptyBrowserState(), running: !!this.browserPromise, headless: this.options.headless === true, sandboxFallback: this.sandboxFallback || undefined, tabs: await this.tabSummaries(), ...cdp };
280
302
  const state = {
281
303
  running: true,
282
304
  headless: this.options.headless === true,
@@ -287,9 +309,19 @@ export class BrowserAutomationService {
287
309
  tabs: await this.tabSummaries(),
288
310
  dialog: this.dialogFor(page),
289
311
  ariaSnapshot: "",
312
+ ...cdp,
290
313
  };
291
314
  return state;
292
315
  }
316
+ cdpEndpointState() {
317
+ if (this.cdpEndpoint)
318
+ return { cdpEndpoint: this.cdpEndpoint };
319
+ return { cdpEndpoint: null, ...(this.cdpEndpointError ? { cdpEndpointError: this.cdpEndpointError } : {}) };
320
+ }
321
+ /** Env for a shell of this workspace. Never written onto process.env. */
322
+ shellEnvironment() {
323
+ return this.cdpEndpoint ? { LOOP_BROWSER_CDP_ENDPOINT: this.cdpEndpoint.wsEndpoint } : {};
324
+ }
293
325
  /**
294
326
  * Passive screencast frame of the active page for the panel mirror view.
295
327
  * Like state(), polling never launches the browser and never touches the
@@ -642,6 +674,80 @@ export class BrowserAutomationService {
642
674
  await page.waitForLoadState("domcontentloaded", { timeout: 3_000 }).catch(() => undefined);
643
675
  return this.completeObservation(page, mode);
644
676
  }
677
+ /** Only draft keys are accepted; submission remains a separate action. */
678
+ async pressDraftKeys(input) {
679
+ const keyPattern = new RegExp(BROWSER_DRAFT_KEY_PATTERN);
680
+ if (typeof input.focusedCanvasId !== "string" || !new RegExp(BROWSER_CANVAS_ID_PATTERN).test(input.focusedCanvasId) || input.focusedCanvasId.trim() !== input.focusedCanvasId || !Array.isArray(input.keys) || input.keys.length < 1 || input.keys.length > MAX_BROWSER_DRAFT_KEYS || input.keys.some((key) => typeof key !== "string" || !keyPattern.test(key) || key.trim() !== key) || (input.refocus !== undefined && !BROWSER_DRAFT_REFOCUS_MODES.includes(input.refocus))) {
681
+ throw new BrowserAutomationError("INVALID_KEY_SEQUENCE", "expected 1–64 draft keys (ASCII letters, digits, Space, Backspace, . - / = : , _), a canvas ID and refocus never|body-once");
682
+ }
683
+ const page = await this.page();
684
+ const tabId = this.trackPage(page);
685
+ if (tabId !== input.tabId)
686
+ throw new BrowserAutomationError("TAB_BINDING_MISMATCH", "draft keys require the bound tab");
687
+ const documentId = this.inspectionDocumentId(page);
688
+ const url = page.url();
689
+ const signal = this.operations.current?.signal;
690
+ let dispatched = 0;
691
+ let refocused = 0;
692
+ const receipt = () => ({ tabId, dispatched, refocused, observation: "omitted" });
693
+ const stop = (code, unknownEffects = false) => ({ ...receipt(), ok: false, status: "stopped", code, ...(unknownEffects ? { unknownEffects: true } : {}) });
694
+ if (this.dialogFor(page))
695
+ return stop("BROWSER_DIALOG");
696
+ const canvas = await page.evaluateHandle((id) => document.getElementById(id), input.focusedCanvasId);
697
+ try {
698
+ // Check once more after the last key, since the page can move focus during dispatch.
699
+ for (const key of [...input.keys, undefined]) {
700
+ if (signal?.aborted)
701
+ return stop("KEY_SEQUENCE_CANCELLED");
702
+ if (this.dialogFor(page))
703
+ return stop("BROWSER_DIALOG");
704
+ if (page.isClosed() || documentId !== this.inspectionDocumentId(page) || page.url() !== url)
705
+ return stop("KEY_TARGET_CHANGED");
706
+ try {
707
+ // Recovery is only for a visible, focused page whose focus fell to BODY before any key was sent.
708
+ const refocus = input.refocus === "body-once" && dispatched === 0 && refocused === 0;
709
+ const state = await canvas.evaluate((el, recover) => {
710
+ if (!(el instanceof HTMLCanvasElement) || !el.isConnected || !document.hasFocus() || el.getClientRects().length === 0)
711
+ return "lost";
712
+ if (document.activeElement === el)
713
+ return "focused";
714
+ if (!recover || document.visibilityState !== "visible" || document.activeElement !== document.body)
715
+ return "lost";
716
+ el.focus({ preventScroll: true });
717
+ return document.activeElement === el ? "refocused" : "lost";
718
+ }, refocus);
719
+ if (state === "lost")
720
+ return stop("CANVAS_FOCUS_LOST");
721
+ if (state === "refocused")
722
+ refocused = 1;
723
+ }
724
+ catch {
725
+ return stop("KEY_TARGET_CHANGED");
726
+ }
727
+ if (signal?.aborted)
728
+ return stop("KEY_SEQUENCE_CANCELLED");
729
+ if (this.dialogFor(page))
730
+ return stop("BROWSER_DIALOG");
731
+ if (page.isClosed() || documentId !== this.inspectionDocumentId(page) || page.url() !== url)
732
+ return stop("KEY_TARGET_CHANGED");
733
+ if (key === undefined)
734
+ break;
735
+ if (dispatched === 0)
736
+ this.invalidateDocument(page);
737
+ try {
738
+ await page.keyboard.press(key);
739
+ }
740
+ catch {
741
+ return stop("KEY_DISPATCH_FAILED", true);
742
+ }
743
+ dispatched += 1;
744
+ }
745
+ return { ...receipt(), status: "dispatched" };
746
+ }
747
+ finally {
748
+ await canvas.dispose().catch(() => undefined);
749
+ }
750
+ }
645
751
  async selectTab(tabId, observe) {
646
752
  this.inspections.invalidate();
647
753
  const mode = validateBrowserObserve(observe);
@@ -728,6 +834,73 @@ export class BrowserAutomationService {
728
834
  async screenshot(options) {
729
835
  return this.snapshot({ ...options, screenshot: true });
730
836
  }
837
+ regionFingerprintKey = randomUUID();
838
+ async screenshotRegion(input) {
839
+ const { x, y, width, height } = input.region;
840
+ const region = { x, y, width, height };
841
+ const waitMs = input.waitMs ?? 0;
842
+ let ignore;
843
+ try {
844
+ ignore = checkedIgnoreRects((input.ignore ?? []).map((rect) => ({ x: rect.x, y: rect.y, width: rect.width, height: rect.height })), region);
845
+ }
846
+ catch (error) {
847
+ if (error instanceof RegionFingerprintError)
848
+ throw new BrowserAutomationError(error.code, error.message);
849
+ throw error;
850
+ }
851
+ if (![x, y, width, height, waitMs].every(Number.isSafeInteger) || x < 0 || y < 0 || width < 1 || height < 1 || width * height > 262_144 || waitMs < 0 || waitMs > 2_000 || (waitMs > 0 && !input.since)) {
852
+ throw new BrowserAutomationError("INVALID_REGION", "expected a viewport rectangle of up to 262,144 CSS pixels and a baseline for waiting up to 2 seconds");
853
+ }
854
+ const page = await this.page();
855
+ const tabId = this.trackPage(page);
856
+ if (tabId !== input.tabId)
857
+ throw new BrowserAutomationError("TAB_BINDING_MISMATCH", "region capture requires the bound tab");
858
+ const documentId = this.inspectionDocumentId(page);
859
+ const signal = this.operations.current?.signal;
860
+ const readScope = async () => {
861
+ signal?.throwIfAborted();
862
+ if (this.dialogFor(page))
863
+ throw new BrowserAutomationError("REGION_DIALOG", "dismiss or accept the browser dialog before capturing a region");
864
+ const url = page.url();
865
+ const viewport = await inspectionViewport(page);
866
+ signal?.throwIfAborted();
867
+ if (page.isClosed() || documentId !== this.inspectionDocumentId(page) || url !== page.url())
868
+ throw new BrowserAutomationError("STALE_REGION", "page changed; observe and locate the region again");
869
+ const scope = createHmac("sha256", this.regionFingerprintKey).update(JSON.stringify([documentId, url, region, viewport, ...(ignore.length > 0 ? [ignore] : [])])).digest("hex");
870
+ return { scope, viewport };
871
+ };
872
+ const { scope: baselineScope, viewport } = await readScope();
873
+ if (input.since !== undefined && (!/^[0-9a-f]{64}\.[0-9a-f]{64}$/.test(input.since) || !input.since.startsWith(`${baselineScope}.`))) {
874
+ throw new BrowserAutomationError("STALE_REGION", "baseline does not match this tab, document, viewport or region");
875
+ }
876
+ if (x + width > viewport.width || y + height > viewport.height)
877
+ throw new BrowserAutomationError("INVALID_REGION", "region must fit inside the current viewport");
878
+ const deadline = performance.now() + waitMs;
879
+ return this.performance.span("screenshot", async () => {
880
+ while (true) {
881
+ const buffer = await page.screenshot({ type: "png", clip: region, scale: "css", timeout: 3_000 });
882
+ if (baselineScope !== (await readScope()).scope)
883
+ throw new BrowserAutomationError("STALE_REGION", "viewport changed; observe and locate the region again");
884
+ let digest;
885
+ try {
886
+ digest = fingerprintRegionPng(buffer, ignore, region);
887
+ }
888
+ catch (error) {
889
+ if (error instanceof RegionFingerprintError)
890
+ throw new BrowserAutomationError(error.code, error.message);
891
+ throw error;
892
+ }
893
+ const fingerprint = `${baselineScope}.${digest}`;
894
+ const maskReceipt = ignore.length > 0 ? { ignore } : {};
895
+ if (fingerprint !== input.since)
896
+ return { tabId, region, ...maskReceipt, fingerprint, regionStatus: input.since ? "changed" : "captured", ...await this.saveScreenshot(buffer) };
897
+ const remaining = deadline - performance.now();
898
+ if (remaining <= 0)
899
+ return { tabId, region, ...maskReceipt, fingerprint, regionStatus: "unchanged" };
900
+ await delay(Math.min(150, remaining), undefined, { signal });
901
+ }
902
+ });
903
+ }
731
904
  /** True when this service runs a visible browser instead of the background default. */
732
905
  get visibleBrowser() {
733
906
  return this.options.headless === false;
@@ -893,27 +1066,225 @@ export class BrowserAutomationService {
893
1066
  return mergeBrowserStorage(await this.context(), state);
894
1067
  }
895
1068
  async evaluate(expression, options = {}) {
896
- this.inspections.invalidate();
897
1069
  if (!expression.trim() || expression.length > 100_000)
898
1070
  throw new BrowserAutomationError("INVALID_EXPRESSION", "provide a nonempty expression up to 100000 characters; use an async IIFE for statements");
899
1071
  const page = await this.page();
1072
+ const frame = options.frame ? this.childFrame(page, options.frame) : page.mainFrame();
1073
+ if (!frame) {
1074
+ return { ok: false, code: "FRAME_NOT_FOUND", error: `frame ${options.frame} was not found`, frames: page.frames().filter((item) => item !== page.mainFrame()).slice(0, 20).map((item) => ({ name: item.name(), url: item.url() })) };
1075
+ }
1076
+ this.inspections.invalidate();
900
1077
  const epoch = this.mainDocumentEpochs.get(page) ?? 0;
901
1078
  const observed = this.generations.get(page)?.get(this.snapshots.get(page) ?? "");
902
1079
  this.snapshots.delete(page);
903
1080
  this.recovering.add(page);
904
- const pending = evaluateBrowserExpression(page, expression).finally(() => {
905
- this.recovering.delete(page);
906
- this.snapshots.delete(page);
907
- });
1081
+ const pending = evaluateBrowserExpression(frame, expression).finally(() => { this.recovering.delete(page); });
908
1082
  const value = await this.performance.span("evaluation", () => waitForBrowserOperation(pending, clamp(options.timeoutMs ?? 15_000, 1, 60_000), this.operations.current?.signal));
909
1083
  this.operations.current?.signal?.throwIfAborted();
910
1084
  if (page.isClosed() || epoch !== (this.mainDocumentEpochs.get(page) ?? 0))
911
1085
  throw new BrowserAutomationError("STALE_REF", "evaluation document was replaced; observe the new document");
912
- // Child-frame navigation invalidates old observations without replacing the eval's main document.
913
1086
  const currentEpoch = this.documentEpochs.get(page) ?? 0;
914
1087
  const snapshotId = this.issueGeneration(page, observed?.epoch === currentEpoch ? observed : { refs: new Map(), epoch: currentEpoch });
1088
+ if ("spilled" in value && typeof value.spilled === "string") {
1089
+ const body = Buffer.from(value.spilled);
1090
+ const artifactPath = this.writeArtifact(`eval-${Date.now()}-${randomUUID().slice(0, 8)}.json`, body);
1091
+ return { artifact: { path: artifactPath, bytes: body.length, preview: value.spilled.slice(0, 1024) }, tabId: tabIdForValue(this.tabs, page), nextSnapshotId: snapshotId };
1092
+ }
915
1093
  return { ...value, tabId: tabIdForValue(this.tabs, page), nextSnapshotId: snapshotId };
916
1094
  }
1095
+ async cdp(input) {
1096
+ if (!this.operations.current)
1097
+ return this.run({}, () => this.cdpNow(input));
1098
+ return this.cdpNow(input);
1099
+ }
1100
+ async runCode(input, parentSignal) {
1101
+ const retain = (value) => Boolean(value && typeof value === "object" && value.unknownEffects === true);
1102
+ if (!this.operations.current)
1103
+ return this.run({ signal: parentSignal, retainAbortedResult: retain }, () => this.runCodeNow(input, parentSignal));
1104
+ this.operations.current.retainAbortedResults.add(retain);
1105
+ return this.runCodeNow(input, parentSignal);
1106
+ }
1107
+ async cdpNow(input) {
1108
+ if (!input.method && !input.events)
1109
+ return { ok: false, code: "CDP_ERROR", error: "method or events is required" };
1110
+ const page = await this.page();
1111
+ const tabId = this.trackPage(page);
1112
+ const browserTarget = input.target === "browser";
1113
+ try {
1114
+ const channel = browserTarget ? undefined : await this.pageChannel(page);
1115
+ const socket = browserTarget ? this.browserCdp() : undefined;
1116
+ for (const method of input.events?.unsubscribe ?? []) {
1117
+ if (socket)
1118
+ socket.unsubscribe([method]);
1119
+ else
1120
+ channel?.subscribed.delete(method);
1121
+ }
1122
+ for (const method of input.events?.subscribe ?? []) {
1123
+ if (socket)
1124
+ socket.subscribe([method]);
1125
+ else
1126
+ channel?.subscribed.add(method);
1127
+ }
1128
+ if (socket)
1129
+ await socket.reconcile();
1130
+ else if (channel)
1131
+ await reconcileCdpDomains(channel.subscribed, channel.enabled, (method) => sendCdp(channel.session, method));
1132
+ let result;
1133
+ let nextSnapshotId;
1134
+ if (input.method) {
1135
+ result = socket
1136
+ ? await socket.send(input.method, input.params)
1137
+ : await sendCdp(channel.session, input.method, input.params ?? {});
1138
+ nextSnapshotId = this.rotateEffectSnapshot(page);
1139
+ }
1140
+ const batch = input.events
1141
+ ? (socket ? socket.events : channel.events).read(input.events.after ?? 0, input.events.limit ?? 100)
1142
+ : undefined;
1143
+ const packed = boundJsonResult({
1144
+ ok: true,
1145
+ result,
1146
+ tabId,
1147
+ ...(input.method ? { method: input.method } : {}),
1148
+ ...(batch ?? {}),
1149
+ ...(nextSnapshotId ? { nextSnapshotId } : {}),
1150
+ }, (name, body) => this.writeArtifact(name, body));
1151
+ return recordValue(packed);
1152
+ }
1153
+ catch (error) {
1154
+ return { ok: false, code: "CDP_ERROR", error: error instanceof Error ? error.message : String(error), ...(input.method ? { method: input.method } : {}), tabId };
1155
+ }
1156
+ }
1157
+ async runCodeNow(input, parentSignal) {
1158
+ const logs = createRunLog();
1159
+ const artifacts = [];
1160
+ const images = [];
1161
+ const code = input.code ?? "";
1162
+ if (!code.trim() || code.length > BROWSER_RUN_CODE_MAX)
1163
+ return { ok: false, code: "RUN_ERROR", error: "code must be a nonempty function body up to 200000 characters", logs: logs.entries, artifacts };
1164
+ const timeoutMs = input.timeoutMs ?? BROWSER_RUN_TIMEOUT_DEFAULT_MS;
1165
+ if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > BROWSER_RUN_TIMEOUT_MAX_MS)
1166
+ return { ok: false, code: "RUN_ERROR", error: "timeoutMs is out of range", logs: logs.entries, artifacts };
1167
+ const page = await this.page();
1168
+ const channel = await this.pageChannel(page);
1169
+ const child = new AbortController();
1170
+ const userSignal = parentSignal ?? new AbortController().signal;
1171
+ const timer = setTimeout(() => child.abort(), timeoutMs);
1172
+ const onParent = () => child.abort();
1173
+ parentSignal?.addEventListener("abort", onParent, { once: true });
1174
+ if (parentSignal?.aborted)
1175
+ child.abort();
1176
+ const startedAt = Date.now();
1177
+ this.recovering.add(page);
1178
+ const write = (name, body) => {
1179
+ const file = this.writeArtifact(name, body);
1180
+ artifacts.push(file);
1181
+ return file;
1182
+ };
1183
+ const execution = invokeBrowserCode(code, {
1184
+ page,
1185
+ context: page.context(),
1186
+ cdp: {
1187
+ send: (method, params) => sendCdp(channel.session, method, params),
1188
+ browser: (method, params) => this.browserCdp().send(method, params),
1189
+ on: (method) => {
1190
+ channel.subscribed.add(method);
1191
+ const domain = method.split(".")[0];
1192
+ if (!domain || channel.enabled.has(domain))
1193
+ return;
1194
+ channel.enabled.add(domain);
1195
+ void sendCdp(channel.session, `${domain}.enable`).catch(() => undefined);
1196
+ },
1197
+ },
1198
+ la: bindRunLa(page, child.signal, logs.log, (method, params) => sendCdp(channel.session, method, params)),
1199
+ args: input.args ?? {},
1200
+ log: logs.log,
1201
+ artifact: (name, data) => write(`${Date.now()}-${randomUUID().slice(0, 8)}-${name}`, Buffer.isBuffer(data) ? data : Buffer.from(data)),
1202
+ signal: child.signal,
1203
+ }, userSignal);
1204
+ void execution.settled.finally(() => { this.recovering.delete(page); });
1205
+ try {
1206
+ const outcome = await execution.result;
1207
+ const value = outcome.ok ? materializeRunValue(outcome.value, write, images) : undefined;
1208
+ const packed = outcome.ok ? boundJsonResult(value, write) : undefined;
1209
+ const nextSnapshotId = this.rotateEffectSnapshot(page);
1210
+ return {
1211
+ ...(outcome.ok ? { ok: true, value: packed } : outcome),
1212
+ logs: logs.entries,
1213
+ artifacts,
1214
+ durationMs: Date.now() - startedAt,
1215
+ tabId: this.trackPage(page),
1216
+ ...(nextSnapshotId ? { nextSnapshotId } : {}),
1217
+ ...(images.length > 0 ? { images } : {}),
1218
+ };
1219
+ }
1220
+ finally {
1221
+ clearTimeout(timer);
1222
+ parentSignal?.removeEventListener("abort", onParent);
1223
+ }
1224
+ }
1225
+ childFrame(page, query) {
1226
+ return page.frames().filter((frame) => frame !== page.mainFrame()).find((frame) => frame.name() === query || frameGlob(query, frame.url()));
1227
+ }
1228
+ async pageChannel(page) {
1229
+ const existing = this.pageCdp.get(page);
1230
+ if (existing)
1231
+ return existing;
1232
+ const session = await page.context().newCDPSession(page);
1233
+ const channel = { session, events: new CdpEventLog(), subscribed: new Set(), enabled: new Set() };
1234
+ session.on("event", (payload) => {
1235
+ if (channel.subscribed.has(payload.method))
1236
+ channel.events.append(payload.method, payload.params);
1237
+ });
1238
+ this.pageCdp.set(page, channel);
1239
+ return channel;
1240
+ }
1241
+ browserCdp() {
1242
+ if (!this.cdpEndpoint)
1243
+ throw new Error("browser CDP endpoint is not available");
1244
+ this.browserSocket ??= new BrowserCdpSocket(this.cdpEndpoint.wsEndpoint);
1245
+ return this.browserSocket;
1246
+ }
1247
+ rotateEffectSnapshot(page) {
1248
+ if (page.isClosed())
1249
+ return undefined;
1250
+ this.inspections.invalidate();
1251
+ const observed = this.generations.get(page)?.get(this.snapshots.get(page) ?? "");
1252
+ this.snapshots.delete(page);
1253
+ const currentEpoch = this.documentEpochs.get(page) ?? 0;
1254
+ return this.issueGeneration(page, observed?.epoch === currentEpoch ? observed : { refs: new Map(), epoch: currentEpoch });
1255
+ }
1256
+ writeArtifact(name, body) {
1257
+ const safe = name.replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 80);
1258
+ const dir = path.resolve(this.options.profileDir, "..", "artifacts");
1259
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
1260
+ const file = path.join(dir, safe);
1261
+ writeFileSync(file, body, { mode: 0o600, flag: "wx" });
1262
+ this.pruneArtifacts(dir);
1263
+ return file;
1264
+ }
1265
+ pruneArtifacts(dir) {
1266
+ try {
1267
+ const now = Date.now();
1268
+ const maxAge = 7 * 24 * 60 * 60 * 1000;
1269
+ const entries = readdirSync(dir).flatMap((name) => {
1270
+ const file = path.join(dir, name);
1271
+ try {
1272
+ return [{ file, mtime: statSync(file).mtimeMs }];
1273
+ }
1274
+ catch {
1275
+ return [];
1276
+ }
1277
+ });
1278
+ for (const item of entries) {
1279
+ if (now - item.mtime > maxAge)
1280
+ unlinkSync(item.file);
1281
+ }
1282
+ const fresh = entries.filter((item) => now - item.mtime <= maxAge).sort((left, right) => right.mtime - left.mtime);
1283
+ for (const extra of fresh.slice(200))
1284
+ unlinkSync(extra.file);
1285
+ }
1286
+ catch { /* retention must not fail the write */ }
1287
+ }
917
1288
  /** Latest snapshot id for a tab, refreshed by eval or a fresh snapshot call. */
918
1289
  snapshotIdFor(tabId) {
919
1290
  const page = tabId === undefined ? this.activePage : this.tabs.get(tabId);
@@ -963,10 +1334,13 @@ export class BrowserAutomationService {
963
1334
  this.invalidateDocument(page);
964
1335
  this.tabs.clear();
965
1336
  this.activePage = undefined;
966
- if (!pending)
1337
+ if (!pending) {
1338
+ await this.clearCdpEndpoint();
967
1339
  return;
1340
+ }
968
1341
  const context = await pending.catch(() => undefined);
969
1342
  await context?.close().catch(() => undefined);
1343
+ await this.clearCdpEndpoint();
970
1344
  }
971
1345
  async prepareObservationScope(page, mode) {
972
1346
  if (mode.mode !== "scoped")
@@ -1202,6 +1576,7 @@ export class BrowserAutomationService {
1202
1576
  this.activePage = page;
1203
1577
  });
1204
1578
  context.on("close", () => {
1579
+ void this.clearCdpEndpoint();
1205
1580
  if (this.browserPromise) {
1206
1581
  void this.browserPromise.then(async (current) => {
1207
1582
  if (current === context) {
@@ -1234,16 +1609,97 @@ export class BrowserAutomationService {
1234
1609
  if (this.sandboxFallback)
1235
1610
  launchOptions.chromiumSandbox = false;
1236
1611
  try {
1237
- return await launchPersistentContextWithCandidates(this.options.profileDir, launchOptions, candidates);
1612
+ return await this.finishLaunch(await launchPersistentContextWithCandidates(this.options.profileDir, launchOptions, candidates));
1238
1613
  }
1239
1614
  catch (error) {
1240
1615
  if (launchOptions.chromiumSandbox !== false && chromiumSandboxDenied(error)) {
1241
1616
  this.sandboxFallback = true;
1242
- return await launchPersistentContextWithCandidates(this.options.profileDir, { ...launchOptions, chromiumSandbox: false }, candidates);
1617
+ return await this.finishLaunch(await launchPersistentContextWithCandidates(this.options.profileDir, { ...launchOptions, chromiumSandbox: false }, candidates));
1243
1618
  }
1244
1619
  throw error;
1245
1620
  }
1246
1621
  }
1622
+ /**
1623
+ * Registers document-start preload scripts before any page runs. A preload
1624
+ * failure aborts the launch: running without the instrumentation would look
1625
+ * like a healthy browser that silently lost its patch.
1626
+ * See docs/design/active/2026-11-20-browser-preload-injection.md.
1627
+ */
1628
+ async finishLaunch(context) {
1629
+ try {
1630
+ this.preloads = await installPreloadsFromEnv(context);
1631
+ }
1632
+ catch (error) {
1633
+ await context.close().catch(() => undefined);
1634
+ throw error;
1635
+ }
1636
+ await this.publishCdpEndpoint();
1637
+ return context;
1638
+ }
1639
+ /** Reads Chromium's ephemeral DevTools port. A missing file does not fail the launch. */
1640
+ async publishCdpEndpoint() {
1641
+ const portFile = path.join(this.options.profileDir, "DevToolsActivePort");
1642
+ const deadline = Date.now() + 3_000;
1643
+ let text = "";
1644
+ while (true) {
1645
+ text = await readFile(portFile, "utf8").catch(() => "");
1646
+ if (text.trim() || Date.now() >= deadline)
1647
+ break;
1648
+ await delay(50);
1649
+ }
1650
+ const [portLine, pathLine] = text.split(/\r?\n/);
1651
+ const port = portLine?.trim() ?? "";
1652
+ let wsPath = pathLine?.trim() ?? "";
1653
+ if (wsPath && !wsPath.startsWith("/"))
1654
+ wsPath = `/${wsPath}`;
1655
+ if (!/^\d+$/.test(port) || !wsPath.startsWith("/")) {
1656
+ this.cdpEndpoint = null;
1657
+ this.cdpEndpointError = text.trim() ? "DevToolsActivePort invalid" : "DevToolsActivePort missing";
1658
+ return;
1659
+ }
1660
+ const wsEndpoint = `ws://127.0.0.1:${port}${wsPath}`;
1661
+ const httpEndpoint = `http://127.0.0.1:${port}`;
1662
+ this.cdpEndpoint = { wsEndpoint, httpEndpoint };
1663
+ this.cdpEndpointError = undefined;
1664
+ await writeFile(path.join(this.options.profileDir, "..", "cdp-endpoint.json"), JSON.stringify({
1665
+ wsEndpoint,
1666
+ httpEndpoint,
1667
+ pid: await this.chromePid(),
1668
+ startedAt: new Date().toISOString(),
1669
+ }), { mode: 0o600 });
1670
+ }
1671
+ async chromePid() {
1672
+ try {
1673
+ const target = await readlink(path.join(this.options.profileDir, "SingletonLock"));
1674
+ const match = /-(\d+)$/.exec(target);
1675
+ return match ? Number(match[1]) : null;
1676
+ }
1677
+ catch {
1678
+ return null;
1679
+ }
1680
+ }
1681
+ clearCdpEndpoint() {
1682
+ for (const channel of this.pageCdp.values())
1683
+ void channel.session.detach().catch(() => undefined);
1684
+ this.pageCdp.clear();
1685
+ this.browserSocket?.close();
1686
+ this.browserSocket = undefined;
1687
+ const endpoint = this.cdpEndpoint;
1688
+ this.cdpEndpoint = null;
1689
+ if (!endpoint)
1690
+ return this.cdpCleanup;
1691
+ const file = path.join(this.options.profileDir, "..", "cdp-endpoint.json");
1692
+ this.cdpCleanup = (async () => {
1693
+ try {
1694
+ const parsed = JSON.parse(await readFile(file, "utf8"));
1695
+ // Sibling profiles share the parent file; only the owner removes it.
1696
+ if (parsed.wsEndpoint === endpoint.wsEndpoint)
1697
+ await rm(file, { force: true });
1698
+ }
1699
+ catch { /* already gone */ }
1700
+ })();
1701
+ return this.cdpCleanup;
1702
+ }
1247
1703
  trackPage(page) {
1248
1704
  for (const [id, existing] of this.tabs) {
1249
1705
  if (existing === page)
@@ -1264,6 +1720,11 @@ export class BrowserAutomationService {
1264
1720
  }
1265
1721
  });
1266
1722
  page.on("close", () => {
1723
+ const channel = this.pageCdp.get(page);
1724
+ if (channel) {
1725
+ void channel.session.detach().catch(() => undefined);
1726
+ this.pageCdp.delete(page);
1727
+ }
1267
1728
  this.inspections.invalidate(page);
1268
1729
  this.invalidateDocument(page);
1269
1730
  this.diagnostics.removePage(id);
@@ -1384,16 +1845,16 @@ export class BrowserAutomationService {
1384
1845
  }
1385
1846
  }
1386
1847
  async captureScreenshot(page, fullPage = false) {
1387
- return this.performance.span("screenshot", async () => {
1388
- const buffer = await page.screenshot({ type: "png", fullPage, timeout: 15_000 });
1389
- const screenshotPath = path.join(this.options.screenshotsDir, `${randomUUID()}.png`);
1390
- await writeFile(screenshotPath, buffer, { mode: 0o600, flag: "wx" });
1391
- const screenshotUrl = this.options.workspaceId ? `/api/operator/v1/chat/browser/screenshots/${path.basename(screenshotPath)}?workspaceId=${encodeURIComponent(this.options.workspaceId)}` : undefined;
1392
- if (buffer.byteLength > MAX_SCREENSHOT_BYTES) {
1393
- return { screenshotPath, screenshotUrl, screenshotError: "SCREENSHOT_TOO_LARGE: image exceeds 4 MiB; evidence saved, request a viewport screenshot" };
1394
- }
1395
- return { screenshotPath, screenshotUrl, screenshot: `data:image/png;base64,${buffer.toString("base64")}` };
1396
- });
1848
+ return this.performance.span("screenshot", async () => this.saveScreenshot(await page.screenshot({ type: "png", fullPage, timeout: 15_000 })));
1849
+ }
1850
+ async saveScreenshot(buffer) {
1851
+ const screenshotPath = path.join(this.options.screenshotsDir, `${randomUUID()}.png`);
1852
+ await writeFile(screenshotPath, buffer, { mode: 0o600, flag: "wx" });
1853
+ const screenshotUrl = this.options.workspaceId ? `/api/operator/v1/chat/browser/screenshots/${path.basename(screenshotPath)}?workspaceId=${encodeURIComponent(this.options.workspaceId)}` : undefined;
1854
+ if (buffer.byteLength > MAX_SCREENSHOT_BYTES) {
1855
+ return { screenshotPath, screenshotUrl, screenshotError: "SCREENSHOT_TOO_LARGE: image exceeds 4 MiB; evidence saved, request a viewport screenshot" };
1856
+ }
1857
+ return { screenshotPath, screenshotUrl, screenshot: `data:image/png;base64,${buffer.toString("base64")}` };
1397
1858
  }
1398
1859
  async nextDownloadResult() {
1399
1860
  const index = this.downloadQueue.findIndex((entry) => !entry.consumed);
@@ -1551,6 +2012,16 @@ function validSelectOption(option) {
1551
2012
  return typeof option.label === "string";
1552
2013
  return "index" in option && Number.isSafeInteger(option.index) && option.index >= 0;
1553
2014
  }
2015
+ function sendCdp(session, method, params) {
2016
+ return session.send(method, params);
2017
+ }
2018
+ function recordValue(value) {
2019
+ return value !== null && typeof value === "object" ? value : { value };
2020
+ }
2021
+ function frameGlob(pattern, url) {
2022
+ const escaped = pattern.split("*").map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join(".*");
2023
+ return new RegExp(`^${escaped}$`).test(url);
2024
+ }
1554
2025
  function emptyBrowserState() {
1555
2026
  return {
1556
2027
  running: false,
@@ -1559,6 +2030,7 @@ function emptyBrowserState() {
1559
2030
  tabs: [],
1560
2031
  dialog: null,
1561
2032
  ariaSnapshot: "",
2033
+ cdpEndpoint: null,
1562
2034
  };
1563
2035
  }
1564
2036
  /**
@@ -1609,6 +2081,8 @@ export function chromiumLaunchOptions(headless, env = process.env) {
1609
2081
  // the "unsupported command-line flag" infobar. CI Linux has no usable
1610
2082
  // user-namespace sandbox, so keep Playwright's --no-sandbox there.
1611
2083
  chromiumSandbox: chromiumSandboxEnabled(env),
2084
+ // Ephemeral loopback DevTools port. Chromium only listens on 127.0.0.1 and writes DevToolsActivePort.
2085
+ args: ["--remote-debugging-port=0"],
1612
2086
  // Drop --enable-automation (the "controlled by automated software" bar).
1613
2087
  // Do not pass --disable-blink-features=AutomationControlled: current Chrome
1614
2088
  // treats that switch as unsupported and shows its own infobar.