@tea-agent/loop-agent 0.55.0-next.3 → 0.55.0-next.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +11 -1
- package/README.md +1 -0
- package/dist/build-stamp.json +3 -3
- package/dist/worker/cli.js +16 -4
- package/dist/worker/console/chat/browser-automation.js +530 -26
- package/dist/worker/console/chat/browser-cdp.js +145 -0
- package/dist/worker/console/chat/browser-evaluation.js +26 -25
- package/dist/worker/console/chat/browser-exposure.js +8 -26
- package/dist/worker/console/chat/browser-la.js +266 -0
- package/dist/worker/console/chat/browser-policy.js +5 -4
- package/dist/worker/console/chat/browser-preload.js +119 -0
- package/dist/worker/console/chat/browser-preloads/vcp.js +417 -0
- package/dist/worker/console/chat/browser-region-fingerprint.js +36 -0
- package/dist/worker/console/chat/browser-run.js +97 -0
- package/dist/worker/console/chat/browser-screenshot-result.js +2 -2
- package/dist/worker/console/chat/browser-scripts.js +42 -4
- package/dist/worker/console/chat/browser-timeline.js +4 -0
- package/dist/worker/console/chat/pi-runtime/custom-tools/browser-tools.js +73 -16
- package/dist/worker/console/chat/pi-runtime/sdk-bindings.js +70 -0
- package/dist/worker/console/chat/pi-runtime.js +53 -35
- package/dist/worker/console/chat/png-fingerprint.js +189 -0
- package/dist/worker/console/chat/routes.js +47 -38
- package/dist/worker/console/chat/session-store.js +7 -21
- package/dist/worker/console/chat/terminal-sessions.js +1 -1
- package/dist/worker/console/chat/terminal-tools.js +1 -0
- package/dist/worker/console/chat/tool-exposure-catalog.js +2 -2
- package/dist/worker/console/chat/tools.js +2 -0
- package/dist/worker/console/chat/workspace-landing.js +9 -0
- package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-C29lbS0T.js → abnfDiagram-N423BO3Z-mcArn3xd.js} +1 -1
- package/dist/worker/console/static/assets/{arc--Vi-BzUR.js → arc-D22Gr5Kh.js} +1 -1
- package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-DwdFPJd-.js → architectureDiagram-T3A2C74G-5P-xaSwS.js} +1 -1
- package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-BFuPq4yu.js → blockDiagram-VBNYF7ZC-ClYqZUog.js} +1 -1
- package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-oKn9EfQa.js → c4Diagram-5PPSVZJV-B5615n-w.js} +1 -1
- package/dist/worker/console/static/assets/channel-BcPrK1uQ.js +1 -0
- package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-TwXtrEhU.js → chunk-2GRJ4B5K-DaXOOg2S.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-Cc3zFHjT.js → chunk-2Q5K7J3B-DewgVpWS.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-5RXB4S5H-xJfu4YKo.js → chunk-5RXB4S5H-C6dIPMGB.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-5VM5RSS4-VBNdtRqb.js → chunk-5VM5RSS4-CIxapjAj.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-DxhJidW7.js → chunk-6Q2QTUOP-dYOgBsXL.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-GF5L2VYU-P6N3qPX5.js → chunk-GF5L2VYU-NOEzJIgx.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-JWPE2WC7-LE21hHhq.js → chunk-JWPE2WC7-BYibgnxd.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-KBJHAD2P-CZmtvzKZ.js → chunk-KBJHAD2P-CbxJFJr1.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-RYQCIY6F-BQrw57-q.js → chunk-RYQCIY6F-MaH52RLP.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-XXDRQBXY-DSNQHlxO.js → chunk-XXDRQBXY-D3YLa2yq.js} +1 -1
- package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-DdqL4uaJ.js +1 -0
- package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-DdqL4uaJ.js +1 -0
- package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-Ckm2oC4s.js → cose-bilkent-JH36ORCC-lsxffBWh.js} +1 -1
- package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-B7ecDXon.js → cynefinDiagram-MW4NZA55-FlNQHEbD.js} +1 -1
- package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-Cx_kCtwr.js → dagre-VZM6K2ZE-ChG_TvEA.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-7IWD3JNH-DTqfz-9k.js → diagram-7IWD3JNH-BL-8sI-U.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-BH8nNNYl.js → diagram-B4RE2ZJO-DRuUXlYn.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-LBJQPF4R-mwUmtiIR.js → diagram-LBJQPF4R-BNWH241c.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-Q27KOJAE-B6_cW-cc.js → diagram-Q27KOJAE-DM4OKpX4.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-UB23O5K3-D1sGiHf5.js → diagram-UB23O5K3-DngjP8qb.js} +1 -1
- package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR-C07tYieV.js → ebnfDiagram-BXEA7PRR-jVdtkqdM.js} +1 -1
- package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-eHwocxI1.js → erDiagram-JOGREHBK-BTc9JI_e.js} +1 -1
- package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-B1B-mb0t.js → flowDiagram-UKHOOZJN-48TF2hOm.js} +1 -1
- package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-B2fpno6f.js → ganttDiagram-PKOTCBZU-Dk-BQhyz.js} +1 -1
- package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-DcM98HR9.js → gitGraphDiagram-DS77QQ5N-Cq8vG_LR.js} +1 -1
- package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-edHmAaaC.js → infoDiagram-6WML65LV-YL-Nd82t.js} +1 -1
- package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-Df_rsjoZ.js → ishikawaDiagram-WSZJBQD7-FWxeUP4G.js} +1 -1
- package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-BqK30536.js → journeyDiagram-NVQOT4AX-B9joXO0y.js} +1 -1
- package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-DCvcYw-F.js → kanban-definition-27J2QSJJ-DUr3LGth.js} +1 -1
- package/dist/worker/console/static/assets/{linear-4rMK0UAe.js → linear-Cs-mfq2-.js} +1 -1
- package/dist/worker/console/static/assets/main-DKX9JQ3f.css +1 -0
- package/dist/worker/console/static/assets/main-ashAmyih.js +655 -0
- package/dist/worker/console/static/assets/{mermaid.core-CIeuqFlz.js → mermaid.core-DXXCdcu4.js} +4 -4
- package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-isklXv_u.js → mindmap-definition-FAOFIHXS--vtGc5sI.js} +1 -1
- package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-DufJ3B32.js → pegDiagram-VL7TDLO6-fiXBc-id.js} +1 -1
- package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-e-dscJOX.js → pieDiagram-7S7Q4E2Y-Cx5Lr1-Y.js} +1 -1
- package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-BMXdwlfZ.js → quadrantDiagram-CIZ2JOQS-BlNemfDx.js} +1 -1
- package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-BkLHnA2m.js → railroadDiagram-AXF67PYL-BsuFyiqc.js} +1 -1
- package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-BzXmvm6l.js → requirementDiagram-LRYGKXZP-CKEYRC2J.js} +1 -1
- package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-BZuur-BM.js → sankeyDiagram-W5VNT64P-vrMh2hZZ.js} +1 -1
- package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-DbZxmtRn.js → sequenceDiagram-SI44F4Z6-BeA4ln2I.js} +1 -1
- package/dist/worker/console/static/assets/{sheet-workbook-D_6Enbgn.js → sheet-workbook-P_0sJUSC.js} +1 -1
- package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-BHbP5ADt.js → sizeCapture-X5ZJPWSS-BdgLOvid.js} +1 -1
- package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-CGNrvQQV.js → stateDiagram-OKZ733FA-CcI28rqU.js} +1 -1
- package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-B0DPdHTy.js +1 -0
- package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-BWNaMfHj.js → swimlanes-SLNWSIFB-DGNDAHUl.js} +2 -2
- package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-Ctgvnx6w.js +8 -0
- package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-BhI167N4.js → timeline-definition-Z64GVDOM-DBzInzT7.js} +1 -1
- package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-BFHqLPNk.js → vennDiagram-T6HMQDX7-C97pu5Ae.js} +1 -1
- package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-D-ThxcCm.js → wardleyDiagram-T6FBY63Y-D3tT-Oxo.js} +1 -1
- package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-CeUzoGed.js → xychartDiagram-ELKLHX3M-1_u6WRbI.js} +1 -1
- package/dist/worker/console/static/index.html +2 -2
- package/dist/worker/console/static-src/operator-chat/controlled-request-status.js +28 -0
- package/dist/worker/console/static-src/operator-chat/turn-submission.js +3 -0
- package/dist/worker/console/static-src/operator-chat/useChatSessions.js +140 -34
- package/dist/worker/console/static-src/operator-chat/useChatStream.js +12 -2
- package/dist/worker/console/static-src/operator-chat/useChatThread.js +5 -0
- package/dist/worker/console/static-src/operator-chat/useComposer.js +10 -17
- package/dist/worker/console/static-src/operator-chat/useControlledHandoff.js +33 -0
- package/dist/worker/console/static-src/operator-chat/useControlledReceipt.js +206 -0
- package/dist/worker/console/static-src/shell/workspace-route.js +17 -1
- package/dist/worker/observe/static/operator-chrome.css +49 -0
- package/dist/worker/observe/static/operator-chrome.d.ts +7 -0
- package/dist/worker/observe/static/operator-chrome.js +31 -0
- package/docs/architecture/runtime-boundaries.md +5 -0
- package/package.json +3 -3
- package/dist/worker/console/static/assets/channel-o_uspxIc.js +0 -1
- package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-BAMhQfS-.js +0 -1
- package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-BAMhQfS-.js +0 -1
- package/dist/worker/console/static/assets/main-CBjwyx0a.js +0 -654
- package/dist/worker/console/static/assets/main-CGnkpKqw.css +0 -1
- package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-Oa0mw2RA.js +0 -1
- 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 {
|
|
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,13 +19,38 @@ 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";
|
|
22
28
|
import { BrowserDiagnostics } from "./browser-diagnostics.js";
|
|
23
|
-
|
|
24
|
-
|
|
29
|
+
const VIEWPORT_PAIR_RE = /^\s*(\d{2,5})\s*[xX*]\s*(\d{2,5})\s*$/;
|
|
30
|
+
/** Parse a single positive dimension (3~5 digits, >=100), undefined when invalid. */
|
|
31
|
+
function parseViewportDimension(raw) {
|
|
32
|
+
if (!raw)
|
|
33
|
+
return undefined;
|
|
34
|
+
const value = Number.parseInt(raw, 10);
|
|
35
|
+
return Number.isFinite(value) && value >= 100 && value <= 99999 ? value : undefined;
|
|
36
|
+
}
|
|
37
|
+
/** Screencast cap and explicit viewport width. Headed windows follow the screen unless overridden. */
|
|
38
|
+
export function resolveBrowserViewportWidth(env = process.env) {
|
|
39
|
+
const fromPair = VIEWPORT_PAIR_RE.exec(env.LOOP_BROWSER_VIEWPORT ?? "")?.[1];
|
|
40
|
+
return parseViewportDimension(env.LOOP_BROWSER_VIEWPORT_WIDTH) ?? parseViewportDimension(fromPair) ?? 1280;
|
|
41
|
+
}
|
|
42
|
+
/** Screencast cap and explicit viewport height. Headed windows follow the screen unless overridden. */
|
|
43
|
+
export function resolveBrowserViewportHeight(env = process.env) {
|
|
44
|
+
const fromPair = VIEWPORT_PAIR_RE.exec(env.LOOP_BROWSER_VIEWPORT ?? "")?.[2];
|
|
45
|
+
return parseViewportDimension(env.LOOP_BROWSER_VIEWPORT_HEIGHT) ?? parseViewportDimension(fromPair) ?? 900;
|
|
46
|
+
}
|
|
47
|
+
function hasBrowserViewportOverride(env) {
|
|
48
|
+
return parseViewportDimension(env.LOOP_BROWSER_VIEWPORT_WIDTH) !== undefined
|
|
49
|
+
|| parseViewportDimension(env.LOOP_BROWSER_VIEWPORT_HEIGHT) !== undefined
|
|
50
|
+
|| VIEWPORT_PAIR_RE.test(env.LOOP_BROWSER_VIEWPORT ?? "");
|
|
51
|
+
}
|
|
52
|
+
export const BROWSER_VIEWPORT_WIDTH = resolveBrowserViewportWidth(process.env);
|
|
53
|
+
export const BROWSER_VIEWPORT_HEIGHT = resolveBrowserViewportHeight(process.env);
|
|
25
54
|
const SEARCH_INPUT_SELECTORS = [
|
|
26
55
|
"input[name='wd']",
|
|
27
56
|
"input[name='q']",
|
|
@@ -48,6 +77,13 @@ const NAVIGATION_SETTLE_CAP_MS = 2_000;
|
|
|
48
77
|
const SEARCH_RESULT_TIMEOUT_MS = 15_000;
|
|
49
78
|
const MAX_SNAPSHOT_CHARS = 24_000;
|
|
50
79
|
const MAX_SCREENSHOT_BYTES = 4 * 1024 * 1024;
|
|
80
|
+
/** Draft punctuation shared by the tool schema and runtime preflight; Enter/Tab/newlines stay excluded. */
|
|
81
|
+
export const BROWSER_DRAFT_KEY_PATTERN = "^(?:[a-zA-Z0-9]|Space|Backspace|[.\\-/=:,_])$";
|
|
82
|
+
export const BROWSER_CANVAS_ID_PATTERN = "^[a-zA-Z0-9_-]{1,80}$";
|
|
83
|
+
export const MAX_BROWSER_DRAFT_KEYS = 64;
|
|
84
|
+
export const BROWSER_DRAFT_REFOCUS_MODES = ["never", "body-once"];
|
|
85
|
+
/** Caret-sized rectangles, relative to the region, excluded from the fingerprint only. */
|
|
86
|
+
export { MAX_BROWSER_IGNORE_RECTS, MAX_BROWSER_IGNORE_WIDTH, MAX_BROWSER_IGNORE_HEIGHT } from "./browser-region-fingerprint.js";
|
|
51
87
|
export class BrowserAutomationService {
|
|
52
88
|
options;
|
|
53
89
|
performance;
|
|
@@ -82,6 +118,14 @@ export class BrowserAutomationService {
|
|
|
82
118
|
mirrorStarting;
|
|
83
119
|
/** Remember a seatbelt failure so later launches skip the sandbox without another crash. */
|
|
84
120
|
sandboxFallback = false;
|
|
121
|
+
/** Document-start scripts registered on the launched context (empty by default). */
|
|
122
|
+
preloads = [];
|
|
123
|
+
cdpEndpoint = null;
|
|
124
|
+
cdpEndpointError;
|
|
125
|
+
/** In-flight endpoint-file removal so dispose waits for the context-close cleanup. */
|
|
126
|
+
cdpCleanup = Promise.resolve();
|
|
127
|
+
pageCdp = new Map();
|
|
128
|
+
browserSocket;
|
|
85
129
|
constructor(options) {
|
|
86
130
|
this.options = options;
|
|
87
131
|
this.performance = new BrowserPerformance(options.performance);
|
|
@@ -271,12 +315,13 @@ export class BrowserAutomationService {
|
|
|
271
315
|
* encoding on every panel poll.
|
|
272
316
|
*/
|
|
273
317
|
async state() {
|
|
318
|
+
const cdp = this.cdpEndpointState();
|
|
274
319
|
if (!this.browserPromise && !this.disposed)
|
|
275
|
-
return { ...emptyBrowserState(), headless: this.options.headless === true, sandboxFallback: this.sandboxFallback || undefined };
|
|
320
|
+
return { ...emptyBrowserState(), headless: this.options.headless === true, sandboxFallback: this.sandboxFallback || undefined, ...cdp };
|
|
276
321
|
// Polling never starts a context, changes selection, or waits on a quarantined page.
|
|
277
322
|
const page = this.operations.current?.target.page ?? this.activePage;
|
|
278
323
|
if (!page || page.isClosed())
|
|
279
|
-
return { ...emptyBrowserState(), running: !!this.browserPromise, headless: this.options.headless === true, sandboxFallback: this.sandboxFallback || undefined, tabs: await this.tabSummaries() };
|
|
324
|
+
return { ...emptyBrowserState(), running: !!this.browserPromise, headless: this.options.headless === true, sandboxFallback: this.sandboxFallback || undefined, tabs: await this.tabSummaries(), ...cdp };
|
|
280
325
|
const state = {
|
|
281
326
|
running: true,
|
|
282
327
|
headless: this.options.headless === true,
|
|
@@ -287,9 +332,19 @@ export class BrowserAutomationService {
|
|
|
287
332
|
tabs: await this.tabSummaries(),
|
|
288
333
|
dialog: this.dialogFor(page),
|
|
289
334
|
ariaSnapshot: "",
|
|
335
|
+
...cdp,
|
|
290
336
|
};
|
|
291
337
|
return state;
|
|
292
338
|
}
|
|
339
|
+
cdpEndpointState() {
|
|
340
|
+
if (this.cdpEndpoint)
|
|
341
|
+
return { cdpEndpoint: this.cdpEndpoint };
|
|
342
|
+
return { cdpEndpoint: null, ...(this.cdpEndpointError ? { cdpEndpointError: this.cdpEndpointError } : {}) };
|
|
343
|
+
}
|
|
344
|
+
/** Env for a shell of this workspace. Never written onto process.env. */
|
|
345
|
+
shellEnvironment() {
|
|
346
|
+
return this.cdpEndpoint ? { LOOP_BROWSER_CDP_ENDPOINT: this.cdpEndpoint.wsEndpoint } : {};
|
|
347
|
+
}
|
|
293
348
|
/**
|
|
294
349
|
* Passive screencast frame of the active page for the panel mirror view.
|
|
295
350
|
* Like state(), polling never launches the browser and never touches the
|
|
@@ -642,6 +697,80 @@ export class BrowserAutomationService {
|
|
|
642
697
|
await page.waitForLoadState("domcontentloaded", { timeout: 3_000 }).catch(() => undefined);
|
|
643
698
|
return this.completeObservation(page, mode);
|
|
644
699
|
}
|
|
700
|
+
/** Only draft keys are accepted; submission remains a separate action. */
|
|
701
|
+
async pressDraftKeys(input) {
|
|
702
|
+
const keyPattern = new RegExp(BROWSER_DRAFT_KEY_PATTERN);
|
|
703
|
+
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))) {
|
|
704
|
+
throw new BrowserAutomationError("INVALID_KEY_SEQUENCE", "expected 1–64 draft keys (ASCII letters, digits, Space, Backspace, . - / = : , _), a canvas ID and refocus never|body-once");
|
|
705
|
+
}
|
|
706
|
+
const page = await this.page();
|
|
707
|
+
const tabId = this.trackPage(page);
|
|
708
|
+
if (tabId !== input.tabId)
|
|
709
|
+
throw new BrowserAutomationError("TAB_BINDING_MISMATCH", "draft keys require the bound tab");
|
|
710
|
+
const documentId = this.inspectionDocumentId(page);
|
|
711
|
+
const url = page.url();
|
|
712
|
+
const signal = this.operations.current?.signal;
|
|
713
|
+
let dispatched = 0;
|
|
714
|
+
let refocused = 0;
|
|
715
|
+
const receipt = () => ({ tabId, dispatched, refocused, observation: "omitted" });
|
|
716
|
+
const stop = (code, unknownEffects = false) => ({ ...receipt(), ok: false, status: "stopped", code, ...(unknownEffects ? { unknownEffects: true } : {}) });
|
|
717
|
+
if (this.dialogFor(page))
|
|
718
|
+
return stop("BROWSER_DIALOG");
|
|
719
|
+
const canvas = await page.evaluateHandle((id) => document.getElementById(id), input.focusedCanvasId);
|
|
720
|
+
try {
|
|
721
|
+
// Check once more after the last key, since the page can move focus during dispatch.
|
|
722
|
+
for (const key of [...input.keys, undefined]) {
|
|
723
|
+
if (signal?.aborted)
|
|
724
|
+
return stop("KEY_SEQUENCE_CANCELLED");
|
|
725
|
+
if (this.dialogFor(page))
|
|
726
|
+
return stop("BROWSER_DIALOG");
|
|
727
|
+
if (page.isClosed() || documentId !== this.inspectionDocumentId(page) || page.url() !== url)
|
|
728
|
+
return stop("KEY_TARGET_CHANGED");
|
|
729
|
+
try {
|
|
730
|
+
// Recovery is only for a visible, focused page whose focus fell to BODY before any key was sent.
|
|
731
|
+
const refocus = input.refocus === "body-once" && dispatched === 0 && refocused === 0;
|
|
732
|
+
const state = await canvas.evaluate((el, recover) => {
|
|
733
|
+
if (!(el instanceof HTMLCanvasElement) || !el.isConnected || !document.hasFocus() || el.getClientRects().length === 0)
|
|
734
|
+
return "lost";
|
|
735
|
+
if (document.activeElement === el)
|
|
736
|
+
return "focused";
|
|
737
|
+
if (!recover || document.visibilityState !== "visible" || document.activeElement !== document.body)
|
|
738
|
+
return "lost";
|
|
739
|
+
el.focus({ preventScroll: true });
|
|
740
|
+
return document.activeElement === el ? "refocused" : "lost";
|
|
741
|
+
}, refocus);
|
|
742
|
+
if (state === "lost")
|
|
743
|
+
return stop("CANVAS_FOCUS_LOST");
|
|
744
|
+
if (state === "refocused")
|
|
745
|
+
refocused = 1;
|
|
746
|
+
}
|
|
747
|
+
catch {
|
|
748
|
+
return stop("KEY_TARGET_CHANGED");
|
|
749
|
+
}
|
|
750
|
+
if (signal?.aborted)
|
|
751
|
+
return stop("KEY_SEQUENCE_CANCELLED");
|
|
752
|
+
if (this.dialogFor(page))
|
|
753
|
+
return stop("BROWSER_DIALOG");
|
|
754
|
+
if (page.isClosed() || documentId !== this.inspectionDocumentId(page) || page.url() !== url)
|
|
755
|
+
return stop("KEY_TARGET_CHANGED");
|
|
756
|
+
if (key === undefined)
|
|
757
|
+
break;
|
|
758
|
+
if (dispatched === 0)
|
|
759
|
+
this.invalidateDocument(page);
|
|
760
|
+
try {
|
|
761
|
+
await page.keyboard.press(key);
|
|
762
|
+
}
|
|
763
|
+
catch {
|
|
764
|
+
return stop("KEY_DISPATCH_FAILED", true);
|
|
765
|
+
}
|
|
766
|
+
dispatched += 1;
|
|
767
|
+
}
|
|
768
|
+
return { ...receipt(), status: "dispatched" };
|
|
769
|
+
}
|
|
770
|
+
finally {
|
|
771
|
+
await canvas.dispose().catch(() => undefined);
|
|
772
|
+
}
|
|
773
|
+
}
|
|
645
774
|
async selectTab(tabId, observe) {
|
|
646
775
|
this.inspections.invalidate();
|
|
647
776
|
const mode = validateBrowserObserve(observe);
|
|
@@ -728,6 +857,73 @@ export class BrowserAutomationService {
|
|
|
728
857
|
async screenshot(options) {
|
|
729
858
|
return this.snapshot({ ...options, screenshot: true });
|
|
730
859
|
}
|
|
860
|
+
regionFingerprintKey = randomUUID();
|
|
861
|
+
async screenshotRegion(input) {
|
|
862
|
+
const { x, y, width, height } = input.region;
|
|
863
|
+
const region = { x, y, width, height };
|
|
864
|
+
const waitMs = input.waitMs ?? 0;
|
|
865
|
+
let ignore;
|
|
866
|
+
try {
|
|
867
|
+
ignore = checkedIgnoreRects((input.ignore ?? []).map((rect) => ({ x: rect.x, y: rect.y, width: rect.width, height: rect.height })), region);
|
|
868
|
+
}
|
|
869
|
+
catch (error) {
|
|
870
|
+
if (error instanceof RegionFingerprintError)
|
|
871
|
+
throw new BrowserAutomationError(error.code, error.message);
|
|
872
|
+
throw error;
|
|
873
|
+
}
|
|
874
|
+
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)) {
|
|
875
|
+
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");
|
|
876
|
+
}
|
|
877
|
+
const page = await this.page();
|
|
878
|
+
const tabId = this.trackPage(page);
|
|
879
|
+
if (tabId !== input.tabId)
|
|
880
|
+
throw new BrowserAutomationError("TAB_BINDING_MISMATCH", "region capture requires the bound tab");
|
|
881
|
+
const documentId = this.inspectionDocumentId(page);
|
|
882
|
+
const signal = this.operations.current?.signal;
|
|
883
|
+
const readScope = async () => {
|
|
884
|
+
signal?.throwIfAborted();
|
|
885
|
+
if (this.dialogFor(page))
|
|
886
|
+
throw new BrowserAutomationError("REGION_DIALOG", "dismiss or accept the browser dialog before capturing a region");
|
|
887
|
+
const url = page.url();
|
|
888
|
+
const viewport = await inspectionViewport(page);
|
|
889
|
+
signal?.throwIfAborted();
|
|
890
|
+
if (page.isClosed() || documentId !== this.inspectionDocumentId(page) || url !== page.url())
|
|
891
|
+
throw new BrowserAutomationError("STALE_REGION", "page changed; observe and locate the region again");
|
|
892
|
+
const scope = createHmac("sha256", this.regionFingerprintKey).update(JSON.stringify([documentId, url, region, viewport, ...(ignore.length > 0 ? [ignore] : [])])).digest("hex");
|
|
893
|
+
return { scope, viewport };
|
|
894
|
+
};
|
|
895
|
+
const { scope: baselineScope, viewport } = await readScope();
|
|
896
|
+
if (input.since !== undefined && (!/^[0-9a-f]{64}\.[0-9a-f]{64}$/.test(input.since) || !input.since.startsWith(`${baselineScope}.`))) {
|
|
897
|
+
throw new BrowserAutomationError("STALE_REGION", "baseline does not match this tab, document, viewport or region");
|
|
898
|
+
}
|
|
899
|
+
if (x + width > viewport.width || y + height > viewport.height)
|
|
900
|
+
throw new BrowserAutomationError("INVALID_REGION", "region must fit inside the current viewport");
|
|
901
|
+
const deadline = performance.now() + waitMs;
|
|
902
|
+
return this.performance.span("screenshot", async () => {
|
|
903
|
+
while (true) {
|
|
904
|
+
const buffer = await page.screenshot({ type: "png", clip: region, scale: "css", timeout: 3_000 });
|
|
905
|
+
if (baselineScope !== (await readScope()).scope)
|
|
906
|
+
throw new BrowserAutomationError("STALE_REGION", "viewport changed; observe and locate the region again");
|
|
907
|
+
let digest;
|
|
908
|
+
try {
|
|
909
|
+
digest = fingerprintRegionPng(buffer, ignore, region);
|
|
910
|
+
}
|
|
911
|
+
catch (error) {
|
|
912
|
+
if (error instanceof RegionFingerprintError)
|
|
913
|
+
throw new BrowserAutomationError(error.code, error.message);
|
|
914
|
+
throw error;
|
|
915
|
+
}
|
|
916
|
+
const fingerprint = `${baselineScope}.${digest}`;
|
|
917
|
+
const maskReceipt = ignore.length > 0 ? { ignore } : {};
|
|
918
|
+
if (fingerprint !== input.since)
|
|
919
|
+
return { tabId, region, ...maskReceipt, fingerprint, regionStatus: input.since ? "changed" : "captured", ...await this.saveScreenshot(buffer) };
|
|
920
|
+
const remaining = deadline - performance.now();
|
|
921
|
+
if (remaining <= 0)
|
|
922
|
+
return { tabId, region, ...maskReceipt, fingerprint, regionStatus: "unchanged" };
|
|
923
|
+
await delay(Math.min(150, remaining), undefined, { signal });
|
|
924
|
+
}
|
|
925
|
+
});
|
|
926
|
+
}
|
|
731
927
|
/** True when this service runs a visible browser instead of the background default. */
|
|
732
928
|
get visibleBrowser() {
|
|
733
929
|
return this.options.headless === false;
|
|
@@ -893,27 +1089,225 @@ export class BrowserAutomationService {
|
|
|
893
1089
|
return mergeBrowserStorage(await this.context(), state);
|
|
894
1090
|
}
|
|
895
1091
|
async evaluate(expression, options = {}) {
|
|
896
|
-
this.inspections.invalidate();
|
|
897
1092
|
if (!expression.trim() || expression.length > 100_000)
|
|
898
1093
|
throw new BrowserAutomationError("INVALID_EXPRESSION", "provide a nonempty expression up to 100000 characters; use an async IIFE for statements");
|
|
899
1094
|
const page = await this.page();
|
|
1095
|
+
const frame = options.frame ? this.childFrame(page, options.frame) : page.mainFrame();
|
|
1096
|
+
if (!frame) {
|
|
1097
|
+
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() })) };
|
|
1098
|
+
}
|
|
1099
|
+
this.inspections.invalidate();
|
|
900
1100
|
const epoch = this.mainDocumentEpochs.get(page) ?? 0;
|
|
901
1101
|
const observed = this.generations.get(page)?.get(this.snapshots.get(page) ?? "");
|
|
902
1102
|
this.snapshots.delete(page);
|
|
903
1103
|
this.recovering.add(page);
|
|
904
|
-
const pending = evaluateBrowserExpression(
|
|
905
|
-
this.recovering.delete(page);
|
|
906
|
-
this.snapshots.delete(page);
|
|
907
|
-
});
|
|
1104
|
+
const pending = evaluateBrowserExpression(frame, expression).finally(() => { this.recovering.delete(page); });
|
|
908
1105
|
const value = await this.performance.span("evaluation", () => waitForBrowserOperation(pending, clamp(options.timeoutMs ?? 15_000, 1, 60_000), this.operations.current?.signal));
|
|
909
1106
|
this.operations.current?.signal?.throwIfAborted();
|
|
910
1107
|
if (page.isClosed() || epoch !== (this.mainDocumentEpochs.get(page) ?? 0))
|
|
911
1108
|
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
1109
|
const currentEpoch = this.documentEpochs.get(page) ?? 0;
|
|
914
1110
|
const snapshotId = this.issueGeneration(page, observed?.epoch === currentEpoch ? observed : { refs: new Map(), epoch: currentEpoch });
|
|
1111
|
+
if ("spilled" in value && typeof value.spilled === "string") {
|
|
1112
|
+
const body = Buffer.from(value.spilled);
|
|
1113
|
+
const artifactPath = this.writeArtifact(`eval-${Date.now()}-${randomUUID().slice(0, 8)}.json`, body);
|
|
1114
|
+
return { artifact: { path: artifactPath, bytes: body.length, preview: value.spilled.slice(0, 1024) }, tabId: tabIdForValue(this.tabs, page), nextSnapshotId: snapshotId };
|
|
1115
|
+
}
|
|
915
1116
|
return { ...value, tabId: tabIdForValue(this.tabs, page), nextSnapshotId: snapshotId };
|
|
916
1117
|
}
|
|
1118
|
+
async cdp(input) {
|
|
1119
|
+
if (!this.operations.current)
|
|
1120
|
+
return this.run({}, () => this.cdpNow(input));
|
|
1121
|
+
return this.cdpNow(input);
|
|
1122
|
+
}
|
|
1123
|
+
async runCode(input, parentSignal) {
|
|
1124
|
+
const retain = (value) => Boolean(value && typeof value === "object" && value.unknownEffects === true);
|
|
1125
|
+
if (!this.operations.current)
|
|
1126
|
+
return this.run({ signal: parentSignal, retainAbortedResult: retain }, () => this.runCodeNow(input, parentSignal));
|
|
1127
|
+
this.operations.current.retainAbortedResults.add(retain);
|
|
1128
|
+
return this.runCodeNow(input, parentSignal);
|
|
1129
|
+
}
|
|
1130
|
+
async cdpNow(input) {
|
|
1131
|
+
if (!input.method && !input.events)
|
|
1132
|
+
return { ok: false, code: "CDP_ERROR", error: "method or events is required" };
|
|
1133
|
+
const page = await this.page();
|
|
1134
|
+
const tabId = this.trackPage(page);
|
|
1135
|
+
const browserTarget = input.target === "browser";
|
|
1136
|
+
try {
|
|
1137
|
+
const channel = browserTarget ? undefined : await this.pageChannel(page);
|
|
1138
|
+
const socket = browserTarget ? this.browserCdp() : undefined;
|
|
1139
|
+
for (const method of input.events?.unsubscribe ?? []) {
|
|
1140
|
+
if (socket)
|
|
1141
|
+
socket.unsubscribe([method]);
|
|
1142
|
+
else
|
|
1143
|
+
channel?.subscribed.delete(method);
|
|
1144
|
+
}
|
|
1145
|
+
for (const method of input.events?.subscribe ?? []) {
|
|
1146
|
+
if (socket)
|
|
1147
|
+
socket.subscribe([method]);
|
|
1148
|
+
else
|
|
1149
|
+
channel?.subscribed.add(method);
|
|
1150
|
+
}
|
|
1151
|
+
if (socket)
|
|
1152
|
+
await socket.reconcile();
|
|
1153
|
+
else if (channel)
|
|
1154
|
+
await reconcileCdpDomains(channel.subscribed, channel.enabled, (method) => sendCdp(channel.session, method));
|
|
1155
|
+
let result;
|
|
1156
|
+
let nextSnapshotId;
|
|
1157
|
+
if (input.method) {
|
|
1158
|
+
result = socket
|
|
1159
|
+
? await socket.send(input.method, input.params)
|
|
1160
|
+
: await sendCdp(channel.session, input.method, input.params ?? {});
|
|
1161
|
+
nextSnapshotId = this.rotateEffectSnapshot(page);
|
|
1162
|
+
}
|
|
1163
|
+
const batch = input.events
|
|
1164
|
+
? (socket ? socket.events : channel.events).read(input.events.after ?? 0, input.events.limit ?? 100)
|
|
1165
|
+
: undefined;
|
|
1166
|
+
const packed = boundJsonResult({
|
|
1167
|
+
ok: true,
|
|
1168
|
+
result,
|
|
1169
|
+
tabId,
|
|
1170
|
+
...(input.method ? { method: input.method } : {}),
|
|
1171
|
+
...(batch ?? {}),
|
|
1172
|
+
...(nextSnapshotId ? { nextSnapshotId } : {}),
|
|
1173
|
+
}, (name, body) => this.writeArtifact(name, body));
|
|
1174
|
+
return recordValue(packed);
|
|
1175
|
+
}
|
|
1176
|
+
catch (error) {
|
|
1177
|
+
return { ok: false, code: "CDP_ERROR", error: error instanceof Error ? error.message : String(error), ...(input.method ? { method: input.method } : {}), tabId };
|
|
1178
|
+
}
|
|
1179
|
+
}
|
|
1180
|
+
async runCodeNow(input, parentSignal) {
|
|
1181
|
+
const logs = createRunLog();
|
|
1182
|
+
const artifacts = [];
|
|
1183
|
+
const images = [];
|
|
1184
|
+
const code = input.code ?? "";
|
|
1185
|
+
if (!code.trim() || code.length > BROWSER_RUN_CODE_MAX)
|
|
1186
|
+
return { ok: false, code: "RUN_ERROR", error: "code must be a nonempty function body up to 200000 characters", logs: logs.entries, artifacts };
|
|
1187
|
+
const timeoutMs = input.timeoutMs ?? BROWSER_RUN_TIMEOUT_DEFAULT_MS;
|
|
1188
|
+
if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > BROWSER_RUN_TIMEOUT_MAX_MS)
|
|
1189
|
+
return { ok: false, code: "RUN_ERROR", error: "timeoutMs is out of range", logs: logs.entries, artifacts };
|
|
1190
|
+
const page = await this.page();
|
|
1191
|
+
const channel = await this.pageChannel(page);
|
|
1192
|
+
const child = new AbortController();
|
|
1193
|
+
const userSignal = parentSignal ?? new AbortController().signal;
|
|
1194
|
+
const timer = setTimeout(() => child.abort(), timeoutMs);
|
|
1195
|
+
const onParent = () => child.abort();
|
|
1196
|
+
parentSignal?.addEventListener("abort", onParent, { once: true });
|
|
1197
|
+
if (parentSignal?.aborted)
|
|
1198
|
+
child.abort();
|
|
1199
|
+
const startedAt = Date.now();
|
|
1200
|
+
this.recovering.add(page);
|
|
1201
|
+
const write = (name, body) => {
|
|
1202
|
+
const file = this.writeArtifact(name, body);
|
|
1203
|
+
artifacts.push(file);
|
|
1204
|
+
return file;
|
|
1205
|
+
};
|
|
1206
|
+
const execution = invokeBrowserCode(code, {
|
|
1207
|
+
page,
|
|
1208
|
+
context: page.context(),
|
|
1209
|
+
cdp: {
|
|
1210
|
+
send: (method, params) => sendCdp(channel.session, method, params),
|
|
1211
|
+
browser: (method, params) => this.browserCdp().send(method, params),
|
|
1212
|
+
on: (method) => {
|
|
1213
|
+
channel.subscribed.add(method);
|
|
1214
|
+
const domain = method.split(".")[0];
|
|
1215
|
+
if (!domain || channel.enabled.has(domain))
|
|
1216
|
+
return;
|
|
1217
|
+
channel.enabled.add(domain);
|
|
1218
|
+
void sendCdp(channel.session, `${domain}.enable`).catch(() => undefined);
|
|
1219
|
+
},
|
|
1220
|
+
},
|
|
1221
|
+
la: bindRunLa(page, child.signal, logs.log, (method, params) => sendCdp(channel.session, method, params)),
|
|
1222
|
+
args: input.args ?? {},
|
|
1223
|
+
log: logs.log,
|
|
1224
|
+
artifact: (name, data) => write(`${Date.now()}-${randomUUID().slice(0, 8)}-${name}`, Buffer.isBuffer(data) ? data : Buffer.from(data)),
|
|
1225
|
+
signal: child.signal,
|
|
1226
|
+
}, userSignal);
|
|
1227
|
+
void execution.settled.finally(() => { this.recovering.delete(page); });
|
|
1228
|
+
try {
|
|
1229
|
+
const outcome = await execution.result;
|
|
1230
|
+
const value = outcome.ok ? materializeRunValue(outcome.value, write, images) : undefined;
|
|
1231
|
+
const packed = outcome.ok ? boundJsonResult(value, write) : undefined;
|
|
1232
|
+
const nextSnapshotId = this.rotateEffectSnapshot(page);
|
|
1233
|
+
return {
|
|
1234
|
+
...(outcome.ok ? { ok: true, value: packed } : outcome),
|
|
1235
|
+
logs: logs.entries,
|
|
1236
|
+
artifacts,
|
|
1237
|
+
durationMs: Date.now() - startedAt,
|
|
1238
|
+
tabId: this.trackPage(page),
|
|
1239
|
+
...(nextSnapshotId ? { nextSnapshotId } : {}),
|
|
1240
|
+
...(images.length > 0 ? { images } : {}),
|
|
1241
|
+
};
|
|
1242
|
+
}
|
|
1243
|
+
finally {
|
|
1244
|
+
clearTimeout(timer);
|
|
1245
|
+
parentSignal?.removeEventListener("abort", onParent);
|
|
1246
|
+
}
|
|
1247
|
+
}
|
|
1248
|
+
childFrame(page, query) {
|
|
1249
|
+
return page.frames().filter((frame) => frame !== page.mainFrame()).find((frame) => frame.name() === query || frameGlob(query, frame.url()));
|
|
1250
|
+
}
|
|
1251
|
+
async pageChannel(page) {
|
|
1252
|
+
const existing = this.pageCdp.get(page);
|
|
1253
|
+
if (existing)
|
|
1254
|
+
return existing;
|
|
1255
|
+
const session = await page.context().newCDPSession(page);
|
|
1256
|
+
const channel = { session, events: new CdpEventLog(), subscribed: new Set(), enabled: new Set() };
|
|
1257
|
+
session.on("event", (payload) => {
|
|
1258
|
+
if (channel.subscribed.has(payload.method))
|
|
1259
|
+
channel.events.append(payload.method, payload.params);
|
|
1260
|
+
});
|
|
1261
|
+
this.pageCdp.set(page, channel);
|
|
1262
|
+
return channel;
|
|
1263
|
+
}
|
|
1264
|
+
browserCdp() {
|
|
1265
|
+
if (!this.cdpEndpoint)
|
|
1266
|
+
throw new Error("browser CDP endpoint is not available");
|
|
1267
|
+
this.browserSocket ??= new BrowserCdpSocket(this.cdpEndpoint.wsEndpoint);
|
|
1268
|
+
return this.browserSocket;
|
|
1269
|
+
}
|
|
1270
|
+
rotateEffectSnapshot(page) {
|
|
1271
|
+
if (page.isClosed())
|
|
1272
|
+
return undefined;
|
|
1273
|
+
this.inspections.invalidate();
|
|
1274
|
+
const observed = this.generations.get(page)?.get(this.snapshots.get(page) ?? "");
|
|
1275
|
+
this.snapshots.delete(page);
|
|
1276
|
+
const currentEpoch = this.documentEpochs.get(page) ?? 0;
|
|
1277
|
+
return this.issueGeneration(page, observed?.epoch === currentEpoch ? observed : { refs: new Map(), epoch: currentEpoch });
|
|
1278
|
+
}
|
|
1279
|
+
writeArtifact(name, body) {
|
|
1280
|
+
const safe = name.replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 80);
|
|
1281
|
+
const dir = path.resolve(this.options.profileDir, "..", "artifacts");
|
|
1282
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
1283
|
+
const file = path.join(dir, safe);
|
|
1284
|
+
writeFileSync(file, body, { mode: 0o600, flag: "wx" });
|
|
1285
|
+
this.pruneArtifacts(dir);
|
|
1286
|
+
return file;
|
|
1287
|
+
}
|
|
1288
|
+
pruneArtifacts(dir) {
|
|
1289
|
+
try {
|
|
1290
|
+
const now = Date.now();
|
|
1291
|
+
const maxAge = 7 * 24 * 60 * 60 * 1000;
|
|
1292
|
+
const entries = readdirSync(dir).flatMap((name) => {
|
|
1293
|
+
const file = path.join(dir, name);
|
|
1294
|
+
try {
|
|
1295
|
+
return [{ file, mtime: statSync(file).mtimeMs }];
|
|
1296
|
+
}
|
|
1297
|
+
catch {
|
|
1298
|
+
return [];
|
|
1299
|
+
}
|
|
1300
|
+
});
|
|
1301
|
+
for (const item of entries) {
|
|
1302
|
+
if (now - item.mtime > maxAge)
|
|
1303
|
+
unlinkSync(item.file);
|
|
1304
|
+
}
|
|
1305
|
+
const fresh = entries.filter((item) => now - item.mtime <= maxAge).sort((left, right) => right.mtime - left.mtime);
|
|
1306
|
+
for (const extra of fresh.slice(200))
|
|
1307
|
+
unlinkSync(extra.file);
|
|
1308
|
+
}
|
|
1309
|
+
catch { /* retention must not fail the write */ }
|
|
1310
|
+
}
|
|
917
1311
|
/** Latest snapshot id for a tab, refreshed by eval or a fresh snapshot call. */
|
|
918
1312
|
snapshotIdFor(tabId) {
|
|
919
1313
|
const page = tabId === undefined ? this.activePage : this.tabs.get(tabId);
|
|
@@ -963,10 +1357,13 @@ export class BrowserAutomationService {
|
|
|
963
1357
|
this.invalidateDocument(page);
|
|
964
1358
|
this.tabs.clear();
|
|
965
1359
|
this.activePage = undefined;
|
|
966
|
-
if (!pending)
|
|
1360
|
+
if (!pending) {
|
|
1361
|
+
await this.clearCdpEndpoint();
|
|
967
1362
|
return;
|
|
1363
|
+
}
|
|
968
1364
|
const context = await pending.catch(() => undefined);
|
|
969
1365
|
await context?.close().catch(() => undefined);
|
|
1366
|
+
await this.clearCdpEndpoint();
|
|
970
1367
|
}
|
|
971
1368
|
async prepareObservationScope(page, mode) {
|
|
972
1369
|
if (mode.mode !== "scoped")
|
|
@@ -1202,6 +1599,7 @@ export class BrowserAutomationService {
|
|
|
1202
1599
|
this.activePage = page;
|
|
1203
1600
|
});
|
|
1204
1601
|
context.on("close", () => {
|
|
1602
|
+
void this.clearCdpEndpoint();
|
|
1205
1603
|
if (this.browserPromise) {
|
|
1206
1604
|
void this.browserPromise.then(async (current) => {
|
|
1207
1605
|
if (current === context) {
|
|
@@ -1234,16 +1632,97 @@ export class BrowserAutomationService {
|
|
|
1234
1632
|
if (this.sandboxFallback)
|
|
1235
1633
|
launchOptions.chromiumSandbox = false;
|
|
1236
1634
|
try {
|
|
1237
|
-
return await launchPersistentContextWithCandidates(this.options.profileDir, launchOptions, candidates);
|
|
1635
|
+
return await this.finishLaunch(await launchPersistentContextWithCandidates(this.options.profileDir, launchOptions, candidates));
|
|
1238
1636
|
}
|
|
1239
1637
|
catch (error) {
|
|
1240
1638
|
if (launchOptions.chromiumSandbox !== false && chromiumSandboxDenied(error)) {
|
|
1241
1639
|
this.sandboxFallback = true;
|
|
1242
|
-
return await launchPersistentContextWithCandidates(this.options.profileDir, { ...launchOptions, chromiumSandbox: false }, candidates);
|
|
1640
|
+
return await this.finishLaunch(await launchPersistentContextWithCandidates(this.options.profileDir, { ...launchOptions, chromiumSandbox: false }, candidates));
|
|
1243
1641
|
}
|
|
1244
1642
|
throw error;
|
|
1245
1643
|
}
|
|
1246
1644
|
}
|
|
1645
|
+
/**
|
|
1646
|
+
* Registers document-start preload scripts before any page runs. A preload
|
|
1647
|
+
* failure aborts the launch: running without the instrumentation would look
|
|
1648
|
+
* like a healthy browser that silently lost its patch.
|
|
1649
|
+
* See docs/design/active/2026-11-20-browser-preload-injection.md.
|
|
1650
|
+
*/
|
|
1651
|
+
async finishLaunch(context) {
|
|
1652
|
+
try {
|
|
1653
|
+
this.preloads = await installPreloadsFromEnv(context);
|
|
1654
|
+
}
|
|
1655
|
+
catch (error) {
|
|
1656
|
+
await context.close().catch(() => undefined);
|
|
1657
|
+
throw error;
|
|
1658
|
+
}
|
|
1659
|
+
await this.publishCdpEndpoint();
|
|
1660
|
+
return context;
|
|
1661
|
+
}
|
|
1662
|
+
/** Reads Chromium's ephemeral DevTools port. A missing file does not fail the launch. */
|
|
1663
|
+
async publishCdpEndpoint() {
|
|
1664
|
+
const portFile = path.join(this.options.profileDir, "DevToolsActivePort");
|
|
1665
|
+
const deadline = Date.now() + 3_000;
|
|
1666
|
+
let text = "";
|
|
1667
|
+
while (true) {
|
|
1668
|
+
text = await readFile(portFile, "utf8").catch(() => "");
|
|
1669
|
+
if (text.trim() || Date.now() >= deadline)
|
|
1670
|
+
break;
|
|
1671
|
+
await delay(50);
|
|
1672
|
+
}
|
|
1673
|
+
const [portLine, pathLine] = text.split(/\r?\n/);
|
|
1674
|
+
const port = portLine?.trim() ?? "";
|
|
1675
|
+
let wsPath = pathLine?.trim() ?? "";
|
|
1676
|
+
if (wsPath && !wsPath.startsWith("/"))
|
|
1677
|
+
wsPath = `/${wsPath}`;
|
|
1678
|
+
if (!/^\d+$/.test(port) || !wsPath.startsWith("/")) {
|
|
1679
|
+
this.cdpEndpoint = null;
|
|
1680
|
+
this.cdpEndpointError = text.trim() ? "DevToolsActivePort invalid" : "DevToolsActivePort missing";
|
|
1681
|
+
return;
|
|
1682
|
+
}
|
|
1683
|
+
const wsEndpoint = `ws://127.0.0.1:${port}${wsPath}`;
|
|
1684
|
+
const httpEndpoint = `http://127.0.0.1:${port}`;
|
|
1685
|
+
this.cdpEndpoint = { wsEndpoint, httpEndpoint };
|
|
1686
|
+
this.cdpEndpointError = undefined;
|
|
1687
|
+
await writeFile(path.join(this.options.profileDir, "..", "cdp-endpoint.json"), JSON.stringify({
|
|
1688
|
+
wsEndpoint,
|
|
1689
|
+
httpEndpoint,
|
|
1690
|
+
pid: await this.chromePid(),
|
|
1691
|
+
startedAt: new Date().toISOString(),
|
|
1692
|
+
}), { mode: 0o600 });
|
|
1693
|
+
}
|
|
1694
|
+
async chromePid() {
|
|
1695
|
+
try {
|
|
1696
|
+
const target = await readlink(path.join(this.options.profileDir, "SingletonLock"));
|
|
1697
|
+
const match = /-(\d+)$/.exec(target);
|
|
1698
|
+
return match ? Number(match[1]) : null;
|
|
1699
|
+
}
|
|
1700
|
+
catch {
|
|
1701
|
+
return null;
|
|
1702
|
+
}
|
|
1703
|
+
}
|
|
1704
|
+
clearCdpEndpoint() {
|
|
1705
|
+
for (const channel of this.pageCdp.values())
|
|
1706
|
+
void channel.session.detach().catch(() => undefined);
|
|
1707
|
+
this.pageCdp.clear();
|
|
1708
|
+
this.browserSocket?.close();
|
|
1709
|
+
this.browserSocket = undefined;
|
|
1710
|
+
const endpoint = this.cdpEndpoint;
|
|
1711
|
+
this.cdpEndpoint = null;
|
|
1712
|
+
if (!endpoint)
|
|
1713
|
+
return this.cdpCleanup;
|
|
1714
|
+
const file = path.join(this.options.profileDir, "..", "cdp-endpoint.json");
|
|
1715
|
+
this.cdpCleanup = (async () => {
|
|
1716
|
+
try {
|
|
1717
|
+
const parsed = JSON.parse(await readFile(file, "utf8"));
|
|
1718
|
+
// Sibling profiles share the parent file; only the owner removes it.
|
|
1719
|
+
if (parsed.wsEndpoint === endpoint.wsEndpoint)
|
|
1720
|
+
await rm(file, { force: true });
|
|
1721
|
+
}
|
|
1722
|
+
catch { /* already gone */ }
|
|
1723
|
+
})();
|
|
1724
|
+
return this.cdpCleanup;
|
|
1725
|
+
}
|
|
1247
1726
|
trackPage(page) {
|
|
1248
1727
|
for (const [id, existing] of this.tabs) {
|
|
1249
1728
|
if (existing === page)
|
|
@@ -1264,6 +1743,11 @@ export class BrowserAutomationService {
|
|
|
1264
1743
|
}
|
|
1265
1744
|
});
|
|
1266
1745
|
page.on("close", () => {
|
|
1746
|
+
const channel = this.pageCdp.get(page);
|
|
1747
|
+
if (channel) {
|
|
1748
|
+
void channel.session.detach().catch(() => undefined);
|
|
1749
|
+
this.pageCdp.delete(page);
|
|
1750
|
+
}
|
|
1267
1751
|
this.inspections.invalidate(page);
|
|
1268
1752
|
this.invalidateDocument(page);
|
|
1269
1753
|
this.diagnostics.removePage(id);
|
|
@@ -1384,16 +1868,16 @@ export class BrowserAutomationService {
|
|
|
1384
1868
|
}
|
|
1385
1869
|
}
|
|
1386
1870
|
async captureScreenshot(page, fullPage = false) {
|
|
1387
|
-
return this.performance.span("screenshot", async () => {
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
}
|
|
1395
|
-
|
|
1396
|
-
}
|
|
1871
|
+
return this.performance.span("screenshot", async () => this.saveScreenshot(await page.screenshot({ type: "png", fullPage, timeout: 15_000 })));
|
|
1872
|
+
}
|
|
1873
|
+
async saveScreenshot(buffer) {
|
|
1874
|
+
const screenshotPath = path.join(this.options.screenshotsDir, `${randomUUID()}.png`);
|
|
1875
|
+
await writeFile(screenshotPath, buffer, { mode: 0o600, flag: "wx" });
|
|
1876
|
+
const screenshotUrl = this.options.workspaceId ? `/api/operator/v1/chat/browser/screenshots/${path.basename(screenshotPath)}?workspaceId=${encodeURIComponent(this.options.workspaceId)}` : undefined;
|
|
1877
|
+
if (buffer.byteLength > MAX_SCREENSHOT_BYTES) {
|
|
1878
|
+
return { screenshotPath, screenshotUrl, screenshotError: "SCREENSHOT_TOO_LARGE: image exceeds 4 MiB; evidence saved, request a viewport screenshot" };
|
|
1879
|
+
}
|
|
1880
|
+
return { screenshotPath, screenshotUrl, screenshot: `data:image/png;base64,${buffer.toString("base64")}` };
|
|
1397
1881
|
}
|
|
1398
1882
|
async nextDownloadResult() {
|
|
1399
1883
|
const index = this.downloadQueue.findIndex((entry) => !entry.consumed);
|
|
@@ -1551,6 +2035,16 @@ function validSelectOption(option) {
|
|
|
1551
2035
|
return typeof option.label === "string";
|
|
1552
2036
|
return "index" in option && Number.isSafeInteger(option.index) && option.index >= 0;
|
|
1553
2037
|
}
|
|
2038
|
+
function sendCdp(session, method, params) {
|
|
2039
|
+
return session.send(method, params);
|
|
2040
|
+
}
|
|
2041
|
+
function recordValue(value) {
|
|
2042
|
+
return value !== null && typeof value === "object" ? value : { value };
|
|
2043
|
+
}
|
|
2044
|
+
function frameGlob(pattern, url) {
|
|
2045
|
+
const escaped = pattern.split("*").map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join(".*");
|
|
2046
|
+
return new RegExp(`^${escaped}$`).test(url);
|
|
2047
|
+
}
|
|
1554
2048
|
function emptyBrowserState() {
|
|
1555
2049
|
return {
|
|
1556
2050
|
running: false,
|
|
@@ -1559,6 +2053,7 @@ function emptyBrowserState() {
|
|
|
1559
2053
|
tabs: [],
|
|
1560
2054
|
dialog: null,
|
|
1561
2055
|
ariaSnapshot: "",
|
|
2056
|
+
cdpEndpoint: null,
|
|
1562
2057
|
};
|
|
1563
2058
|
}
|
|
1564
2059
|
/**
|
|
@@ -1599,9 +2094,16 @@ async function launchPersistentContextWithCandidates(profileDir, launchOptions,
|
|
|
1599
2094
|
throw lastError instanceof Error ? lastError : new Error("no Chromium executable was available");
|
|
1600
2095
|
}
|
|
1601
2096
|
export function chromiumLaunchOptions(headless, env = process.env) {
|
|
2097
|
+
const headed = !(headless ?? false);
|
|
2098
|
+
// A fixed viewport taller than the real window is laid out but not painted:
|
|
2099
|
+
// fullscreen on a short screen leaves the bottom off the mirror and off the scrollbar.
|
|
2100
|
+
// Headed mode follows the window. Headless and LOOP_BROWSER_VIEWPORT* still pin a size.
|
|
2101
|
+
const viewport = headed && !hasBrowserViewportOverride(env)
|
|
2102
|
+
? null
|
|
2103
|
+
: { width: resolveBrowserViewportWidth(env), height: resolveBrowserViewportHeight(env) };
|
|
1602
2104
|
return {
|
|
1603
2105
|
headless: headless ?? false,
|
|
1604
|
-
viewport
|
|
2106
|
+
viewport,
|
|
1605
2107
|
acceptDownloads: true,
|
|
1606
2108
|
locale: "zh-CN",
|
|
1607
2109
|
timezoneId: "Asia/Shanghai",
|
|
@@ -1609,6 +2111,8 @@ export function chromiumLaunchOptions(headless, env = process.env) {
|
|
|
1609
2111
|
// the "unsupported command-line flag" infobar. CI Linux has no usable
|
|
1610
2112
|
// user-namespace sandbox, so keep Playwright's --no-sandbox there.
|
|
1611
2113
|
chromiumSandbox: chromiumSandboxEnabled(env),
|
|
2114
|
+
// Ephemeral loopback DevTools port. Chromium only listens on 127.0.0.1 and writes DevToolsActivePort.
|
|
2115
|
+
args: ["--remote-debugging-port=0"],
|
|
1612
2116
|
// Drop --enable-automation (the "controlled by automated software" bar).
|
|
1613
2117
|
// Do not pass --disable-blink-features=AutomationControlled: current Chrome
|
|
1614
2118
|
// treats that switch as unsupported and shows its own infobar.
|