@open-take/runtime 0.4.4 → 0.5.1

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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cdp-capture-Bl990GzE.js","names":["sleep","ms: number","explicit?: string","candidates: string[]","buildId: string","downloaded: number","total: number","ws: WebSocket","ev: MessageEvent","wsUrl: string","resolve","method: string","params: Record<string, unknown>","fn: (params: T) => void","opts: {\n width: number;\n height: number;\n chromePath?: string;\n /** Physical pixels per CSS px (Retina density). A whole-browser launch flag,\n * NOT a per-page metrics override, so frame/viewport/event-space stay\n * consistent: events remain CSS px, the window surface (what the\n * screencast captures) is exactly `deviceScaleFactor`× that. */\n deviceScaleFactor?: number;\n /** Persistent profile dir (an authenticated capture — see `open-take auth`).\n * Kept on close, unlike the default throwaway temp profile. The SAME\n * keychain flags are used for auth and capture (mock keychain), so cookies\n * written during a headed login decrypt in the later headless capture. */\n userDataDir?: string;\n /** false ⇒ launch a visible (headed) window. Default true (headless).\n * The screencast records either way — headed is the escape hatch for\n * sites that gate on a real window. */\n headless?: boolean;\n}","proc: ChildProcess","userDir: string","pid: number","port: number","cdp: CDP","targetId: string","vw: number","vh: number","win: { windowId: number; bounds: { width: number; height: number } } | null","frames: Frame[]","n: number","dir: string","t0: number","opts: { maxWidth: number; maxHeight: number; quality?: number }","p: { data: string; sessionId: number; metadata?: { timestamp?: number } }","screencast: Pick<Screencast, \"idleForMs\">","active: () => boolean","paused: () => boolean","endMs: number","outPath: string","fps: number","ffmpegBin?: string","lines: string[]","ready: () => boolean","timeoutMs: number","sleep","ms: number","o: unknown","s: unknown","raw: string","top: unknown","text: string","selector: string","target: { text?: string; selector?: string }","resolve","pts: { x: number; y: number }[]","u: number","seg: number[]","path: string","plan: TakePlan","opts: CaptureOpts","url: string","opts: InspectOpts","expr: string","elements: InspectElement[]","target: { selector?: string; text?: string }","value: string","t: NavigateTarget","raw: string","base?: URL","message: string","issues: PrecheckIssue[]","FIELD_ORDER: Record<string, string[]>","steps: TakePlan[\"steps\"]","out: TargetSpec[]","f: string","order: string[]","field: string","kind: \"selector\" | \"text\"","revealOnly?: boolean","action: string","value: string","p: Probe","evalJson: (js: string) => Promise<unknown>","opts?: { retryMs?: number; sleep?: (ms: number) => Promise<void> }","sleep","ms: number","t: TargetSpec","lateMisses: TargetSpec[]","sleep","ms: number","cdp: CDP","heldMs: number","opts: { budgetMs?: number }","budgetMs: number","reason: SettleOutcome[\"reason\"]","ms: number","u: number","cdp: CDP","js: string","b: Box","type: \"mousePressed\" | \"mouseReleased\" | \"mouseMoved\"","x: number","y: number","MOD: Record<string, number>","NAMED: Record<string, KeyInfo>","MOD_KEY: Record<number, KeyInfo>","keys: string","info: KeyInfo","type: \"keyDown\" | \"keyUp\"","mods: number","plan: TakePlan","opts: CaptureOpts","browser: Browser | null","spec: {\n point?: Pt;\n selector?: string;\n text?: string;\n }","events: CaptureLog[\"events\"]","skipped: NonNullable<CaptureLog[\"skipped\"]>","settleWaits: NonNullable<CaptureLog[\"settleWaits\"]>","action: string","target: string | undefined","reason: string","defaultMs: number","href: string | null","label","tMs","box","pt","pathPts: Pt[]","path: Pt[]","to: Pt","from: Pt","type: \"dragEnter\" | \"dragOver\" | \"drop\"","p: Pt","carriedMs: number","dy: number","box: Box | null","url: string"],"sources":["../src/cdp.ts","../src/capture.ts","../src/nav.ts","../src/precheck.ts","../src/settle.ts","../src/cdp-capture.ts"],"sourcesContent":["// Minimal Chrome DevTools Protocol toolkit for the high-fps capture path.\n//\n// Why this exists: agent-browser's `record` wraps Playwright recordVideo,\n// hard-throttled to ~10fps (no fps flag — native binary). The fps spike\n// (spike-revideo/fps/VERDICT.md) proved a direct CDP `Page.startScreencast`\n// delivers ~60fps, and that driving the drag via CDP `Input` at ~16ms steps\n// keeps the captured ink in lockstep with the synthetic cursor. So the\n// hi-fps path drives AND captures over one CDP page session: one owner, one\n// clock, no per-step agent-browser process spawn.\n//\n// No deps — Node 22's global `WebSocket`/`fetch` carry the protocol.\n\nimport { type ChildProcess, spawn } from \"node:child_process\";\nimport {\n existsSync,\n mkdirSync,\n mkdtempSync,\n readdirSync,\n readFileSync,\n readlinkSync,\n rmSync,\n writeFileSync,\n} from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { homedir, tmpdir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport { resolveFfmpeg } from \"@open-take/compositor\";\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\nconst require = createRequire(import.meta.url);\n\n// Where we cache an auto-downloaded Chrome-for-Testing + the resolved buildId.\nconst CHROME_CACHE = join(homedir(), \".open-take\", \"browsers\");\nconst BUILDID_FILE = join(homedir(), \".open-take\", \"chrome-build.json\");\n\n// --- locate a launchable Chrome ----------------------------------------\n// Resolution order: explicit/env → a Chrome-for-Testing we downloaded → a\n// CfT an agent-browser install left behind (legacy). Returns null if none\n// (→ ensureChrome downloads CfT). We deliberately do NOT auto-pick the user's\n// *system* Chrome: launching the same binary while Chrome is already running\n// hands off to the existing instance and never opens the debug port (proven).\n// CfT is the isolated, automation-stable browser Playwright/Puppeteer use too.\n// Point OPEN_TAKE_CHROME at a system Chrome if you really want one (close it\n// first).\nexport function resolveChrome(explicit?: string): string | null {\n const candidates: string[] = [];\n if (explicit) candidates.push(explicit);\n if (process.env.OPEN_TAKE_CHROME) candidates.push(process.env.OPEN_TAKE_CHROME);\n\n // a Chrome-for-Testing we downloaded earlier (offline: derived from the\n // saved buildId, no network)\n if (existsSync(BUILDID_FILE)) {\n try {\n const exe = computeChromePathSync(JSON.parse(readFileSync(BUILDID_FILE, \"utf8\")).buildId);\n if (exe) candidates.push(exe);\n } catch {\n /* ignore a corrupt cache marker */\n }\n }\n\n // legacy: a CfT an older agent-browser install left behind (also isolated)\n const abBrowsers = join(homedir(), \".agent-browser\", \"browsers\");\n if (existsSync(abBrowsers)) {\n for (const d of readdirSync(abBrowsers)\n .filter((n) => n.startsWith(\"chrome-\"))\n .sort()\n .reverse()) {\n candidates.push(\n join(\n abBrowsers,\n d,\n \"Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing\",\n ),\n join(abBrowsers, d, \"chrome-linux64\", \"chrome\"),\n join(abBrowsers, d, \"chrome\"),\n );\n }\n }\n\n return candidates.find((c) => c && existsSync(c)) ?? null;\n}\n\n// Best-effort sync path to a cached CfT build (lazy-loads the helper; returns\n// null if @puppeteer/browsers isn't resolvable for any reason).\nfunction computeChromePathSync(buildId: string): string | null {\n try {\n // require keeps this synchronous inside the sync resolver\n const { computeExecutablePath, Browser } = require(\"@puppeteer/browsers\");\n return computeExecutablePath({ browser: Browser.CHROME, buildId, cacheDir: CHROME_CACHE });\n } catch {\n return null;\n }\n}\n\n// Resolve a Chrome, downloading Chrome-for-Testing on first use if the machine\n// has none. The download is a one-time, cached fetch via @puppeteer/browsers\n// (Chrome-team-maintained pure downloader) — this is what keeps install\n// zero-config without binding us to agent-browser.\nexport async function ensureChrome(explicit?: string): Promise<string> {\n const found = resolveChrome(explicit);\n if (found) return found;\n try {\n const { install, resolveBuildId, detectBrowserPlatform, computeExecutablePath, Browser } =\n await import(\"@puppeteer/browsers\");\n const platform = detectBrowserPlatform();\n if (!platform) throw new Error(\"unsupported platform\");\n const buildId = await resolveBuildId(Browser.CHROME, platform, \"stable\");\n const exe = computeExecutablePath({ browser: Browser.CHROME, buildId, cacheDir: CHROME_CACHE });\n if (!existsSync(exe)) {\n mkdirSync(CHROME_CACHE, { recursive: true });\n // First run on this machine: a one-time ~150MB fetch. Say so (and show\n // coarse progress) so `make` doesn't look like a silent stall.\n process.stderr.write(\n `open-take: downloading Chrome for Testing (${buildId}, one-time) → ${CHROME_CACHE}\\n`,\n );\n let lastPct = -1;\n await install({\n browser: Browser.CHROME,\n buildId,\n cacheDir: CHROME_CACHE,\n downloadProgressCallback: (downloaded: number, total: number) => {\n if (!total) return;\n const pct = Math.floor((downloaded / total) * 100);\n // throttle to whole-ten-percent steps to keep the log quiet\n if (pct >= lastPct + 10 || pct === 100) {\n lastPct = pct;\n process.stderr.write(`open-take: …Chrome download ${pct}%\\n`);\n }\n },\n });\n process.stderr.write(\"open-take: Chrome ready.\\n\");\n }\n mkdirSync(dirname(BUILDID_FILE), { recursive: true });\n writeFileSync(BUILDID_FILE, JSON.stringify({ buildId }));\n return exe;\n } catch (e) {\n throw new Error(\n `open-take: no Chrome found and auto-download failed (${(e as Error).message}). ` +\n \"Install Chrome/Chromium, or set OPEN_TAKE_CHROME to a Chrome binary.\",\n );\n }\n}\n\n// --- minimal CDP client over a page-target websocket -------------------\nexport class CDP {\n private ws: WebSocket;\n private id = 0;\n private pending = new Map<\n number,\n { resolve: (value: unknown) => void; reject: (error: Error) => void }\n >();\n private handlers = new Map<string, (params: unknown) => void>();\n\n private constructor(ws: WebSocket) {\n this.ws = ws;\n ws.addEventListener(\"message\", (ev: MessageEvent) => {\n const msg = JSON.parse(ev.data as string) as {\n id?: number;\n error?: unknown;\n result?: unknown;\n method?: string;\n params?: unknown;\n };\n if (msg.id != null && this.pending.has(msg.id)) {\n const { resolve, reject } = this.pending.get(msg.id)!;\n this.pending.delete(msg.id);\n msg.error ? reject(new Error(JSON.stringify(msg.error))) : resolve(msg.result);\n } else if (msg.method) {\n this.handlers.get(msg.method)?.(msg.params);\n }\n });\n }\n\n static connect(wsUrl: string): Promise<CDP> {\n return new Promise((resolve, reject) => {\n const ws = new WebSocket(wsUrl);\n ws.addEventListener(\"open\", () => resolve(new CDP(ws)));\n ws.addEventListener(\"error\", () => reject(new Error(`CDP connect failed: ${wsUrl}`)));\n });\n }\n\n send<T = unknown>(method: string, params: Record<string, unknown> = {}): Promise<T> {\n const id = ++this.id;\n return new Promise<T>((resolve, reject) => {\n this.pending.set(id, { resolve: (value) => resolve(value as T), reject });\n this.ws.send(JSON.stringify({ id, method, params }));\n });\n }\n\n on<T = unknown>(method: string, fn: (params: T) => void): void {\n this.handlers.set(method, (params) => fn(params as T));\n }\n\n close(): void {\n try {\n this.ws.close();\n } catch {\n /* already closed */\n }\n }\n}\n\n// --- launch + page-target discovery ------------------------------------\nexport type Browser = {\n cdp: CDP;\n /** the page target's id (for browser-level window commands) */\n targetId: string;\n /** kill the browser process and remove its temp profile */\n close: () => Promise<void>;\n};\n\n/** Launch headless Chrome, return a CDP session bound to its page target. */\nexport async function launchBrowser(opts: {\n width: number;\n height: number;\n chromePath?: string;\n /** Physical pixels per CSS px (Retina density). A whole-browser launch flag,\n * NOT a per-page metrics override, so frame/viewport/event-space stay\n * consistent: events remain CSS px, the window surface (what the\n * screencast captures) is exactly `deviceScaleFactor`× that. */\n deviceScaleFactor?: number;\n /** Persistent profile dir (an authenticated capture — see `open-take auth`).\n * Kept on close, unlike the default throwaway temp profile. The SAME\n * keychain flags are used for auth and capture (mock keychain), so cookies\n * written during a headed login decrypt in the later headless capture. */\n userDataDir?: string;\n /** false ⇒ launch a visible (headed) window. Default true (headless).\n * The screencast records either way — headed is the escape hatch for\n * sites that gate on a real window. */\n headless?: boolean;\n}): Promise<Browser> {\n const chrome = await ensureChrome(opts.chromePath);\n const ephemeral = !opts.userDataDir;\n if (opts.userDataDir) mkdirSync(opts.userDataDir, { recursive: true });\n const userDir = opts.userDataDir ?? mkdtempSync(join(tmpdir(), \"open-take-cdp-\"));\n // A REUSED profile keeps the previous session's DevToolsActivePort on disk;\n // readDevtoolsPort would trust that stale (dead) port on its first poll and\n // then time out on \"no page target appeared\". Clear it so the only port we\n // can ever read is the one THIS launch writes. (Fresh temp profiles have\n // nothing to clear.)\n if (!ephemeral) rmSync(join(userDir, \"DevToolsActivePort\"), { force: true });\n // ProcessSingleton preflight for a reused profile: if a LIVE Chrome holds it\n // (the auth window still open, or a concurrent capture), our spawn would hand\n // off to that instance and never open a debug port — fail with the real story\n // instead. A DEAD holder (SIGKILLed capture, crashed auth) leaves stale lock\n // files behind; clear them so Chrome doesn't stall on takeover.\n if (!ephemeral) {\n const holder = singletonHolderPid(userDir);\n if (holder != null && pidAlive(holder))\n throw new Error(\n `profile in use: a Chrome (pid ${holder}) is already running on ${userDir} — ` +\n `quit it first (e.g. the \\`open-take auth\\` window)`,\n );\n for (const f of [\"SingletonLock\", \"SingletonCookie\", \"SingletonSocket\"])\n rmSync(join(userDir, f), { force: true });\n }\n const dsf = opts.deviceScaleFactor ?? 1;\n const proc: ChildProcess = spawn(\n chrome,\n [\n \"--remote-debugging-port=0\", // pick a free port; read it back from DevToolsActivePort\n `--user-data-dir=${userDir}`,\n `--window-size=${opts.width},${opts.height}`,\n ...(dsf !== 1 ? [`--force-device-scale-factor=${dsf}`] : []),\n ...(opts.headless === false ? [] : [\"--headless=new\"]),\n // automation browser (throwaway profile, loads the user's own target app);\n // without this the launch hangs — never writes DevToolsActivePort — in\n // sandboxed/containerised/CI contexts where Chrome's own sandbox can't init.\n \"--no-sandbox\",\n // never touch the OS keychain (macOS would pop a \"Chrome for Testing wants\n // to use Chromium Safe Storage\" password prompt every capture); use an\n // in-process store instead. These are puppeteer/playwright defaults.\n \"--password-store=basic\",\n \"--use-mock-keychain\",\n \"--no-first-run\",\n \"--no-default-browser-check\",\n \"--hide-scrollbars\",\n \"--disable-extensions\",\n \"--disable-background-networking\",\n \"--disable-features=Translate,AcceptCHFrame,MediaRouter,OptimizationHints\",\n \"--mute-audio\",\n \"about:blank\",\n ],\n { stdio: [\"ignore\", \"ignore\", \"pipe\"] },\n );\n let stderr = \"\";\n proc.stderr?.on(\"data\", (d) => {\n stderr += d;\n });\n\n const close = async () => {\n // Throwaway profile: SIGKILL is fine (the dir is deleted anyway). A\n // PERSISTENT profile needs a graceful shutdown first — Chrome flushes\n // cookies/localStorage (session tokens refreshed DURING the capture) and\n // records a clean exit only then; a bare SIGKILL would slowly log the\n // saved profile out and leave crash-restore state behind.\n const exitWithin = (ms: number) =>\n new Promise<boolean>((res) => {\n if (proc.exitCode != null) return res(true);\n const tm = setTimeout(() => res(false), ms);\n proc.once(\"exit\", () => {\n clearTimeout(tm);\n res(true);\n });\n });\n try {\n if (!ephemeral) {\n proc.kill(\"SIGTERM\");\n if (!(await exitWithin(4000))) proc.kill(\"SIGKILL\");\n } else {\n proc.kill(\"SIGKILL\");\n }\n } catch {\n /* already gone */\n }\n await exitWithin(2000); // don't hang if exit never fires\n // Chrome may still be flushing its profile; retry the rm rather than throw.\n // A user-supplied (persistent, authenticated) profile is KEPT.\n if (ephemeral)\n rmSync(userDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });\n };\n\n try {\n const port = await readDevtoolsPort(userDir, proc);\n const target = await pageTargetWs(port);\n const cdp = await CDP.connect(target.wsUrl);\n return { cdp, targetId: target.id, close };\n } catch (e) {\n await close();\n throw new Error(\n `open-take(hi-fps): browser launch failed: ${(e as Error).message}\\n${stderr.slice(-600)}`,\n );\n }\n}\n\n// Chrome's ProcessSingleton lock is a symlink named SingletonLock pointing at\n// \"<hostname>-<pid>\". Resolve the holder's pid (null when absent/unreadable).\nfunction singletonHolderPid(userDir: string): number | null {\n try {\n const target = readlinkSync(join(userDir, \"SingletonLock\"));\n const pid = Number(target.split(\"-\").pop());\n return Number.isFinite(pid) && pid > 0 ? pid : null;\n } catch {\n return null; // no lock, or not a symlink (non-POSIX layout)\n }\n}\n\nfunction pidAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n}\n\n// Chrome writes the chosen debugging port to <user-data-dir>/DevToolsActivePort\n// (line 1) once the listener is up. Polling that file is the race-free way to\n// learn a port-0 launch's actual port.\nasync function readDevtoolsPort(userDir: string, proc: ChildProcess): Promise<number> {\n const file = join(userDir, \"DevToolsActivePort\");\n for (let i = 0; i < 100; i++) {\n if (proc.exitCode != null) throw new Error(`chrome exited early (${proc.exitCode})`);\n if (existsSync(file)) {\n const line = readFileSync(file, \"utf8\").split(\"\\n\")[0]?.trim();\n const port = Number(line);\n if (Number.isFinite(port) && port > 0) return port;\n }\n await sleep(50);\n }\n throw new Error(\"timed out waiting for DevToolsActivePort\");\n}\n\nasync function pageTargetWs(port: number): Promise<{ wsUrl: string; id: string }> {\n for (let i = 0; i < 60; i++) {\n try {\n const list = (await (await fetch(`http://localhost:${port}/json`)).json()) as Array<{\n type: string;\n id: string;\n webSocketDebuggerUrl?: string;\n }>;\n const page = list.find((t) => t.type === \"page\");\n if (page?.webSocketDebuggerUrl) return { wsUrl: page.webSocketDebuggerUrl, id: page.id };\n } catch {\n /* browser not ready yet */\n }\n await sleep(100);\n }\n throw new Error(\"no page target appeared\");\n}\n\n// Grow the window so the *natural* layout viewport matches the requested size.\n// Headless reserves window chrome (~140px), so a 1280x800 window yields a\n// ~1280x657 viewport. `Page.startScreencast` captures the window surface, NOT\n// the layout viewport — so a device-metrics override would desync the captured\n// frame from the coordinate space events are measured in. Resizing the real\n// window keeps frame == viewport == event space, exactly. Returns the achieved\n// inner size; on a browser that won't resize (remote/CDP service) it falls back\n// to whatever the natural inner is — still self-consistent, just maybe smaller.\nexport async function fitViewport(\n cdp: CDP,\n targetId: string,\n vw: number,\n vh: number,\n): Promise<[number, number]> {\n const readInner = async (): Promise<[number, number]> => {\n const r = await cdp.send<{ result?: { value?: string } }>(\"Runtime.evaluate\", {\n expression: \"JSON.stringify([window.innerWidth, window.innerHeight])\",\n returnByValue: true,\n });\n const v = JSON.parse(r.result?.value ?? \"[0,0]\");\n return [Number(v[0]), Number(v[1])];\n };\n let win: { windowId: number; bounds: { width: number; height: number } } | null = null;\n try {\n win = await cdp.send<{ windowId: number; bounds: { width: number; height: number } }>(\n \"Browser.getWindowForTarget\",\n { targetId },\n );\n } catch {\n return readInner(); // can't resize — use the natural viewport\n }\n if (!win?.windowId) return readInner();\n let { width, height } = win.bounds;\n let inner = await readInner();\n for (let i = 0; i < 4; i++) {\n const dw = vw - inner[0];\n const dh = vh - inner[1];\n if (Math.abs(dw) <= 1 && Math.abs(dh) <= 1) break;\n width += dw;\n height += dh;\n await cdp.send(\"Browser.setWindowBounds\", {\n windowId: win.windowId,\n bounds: { width, height },\n });\n await sleep(120);\n inner = await readInner();\n }\n return inner;\n}\n\n// --- screencast recorder ------------------------------------------------\n// Frames stream in only when the page surface changes; each is written to\n// disk immediately. Chrome's frame-swap time, not delayed JPEG delivery, is\n// the image's position on the action clock.\nexport type Frame = {\n file: string;\n offMs: number;\n arrivalMs?: number;\n timestampSource?: \"frame-swap\" | \"arrival\";\n};\n\nexport function captureCadence(frames: Frame[]) {\n const ordered = [...frames].sort((a, b) => a.offMs - b.offMs);\n const intervals = ordered\n .slice(1)\n .map((frame, i) => frame.offMs - ordered[i]!.offMs)\n .sort((a, b) => a - b);\n const rounded = (n: number) => Math.round(n * 1000) / 1000;\n const sources = new Set(frames.map((frame) => frame.timestampSource ?? \"arrival\"));\n return {\n frameCount: frames.length,\n timestampSource:\n sources.size > 1\n ? (\"mixed\" as const)\n : sources.has(\"frame-swap\")\n ? (\"frame-swap\" as const)\n : (\"arrival\" as const),\n frameOffsetsMs: ordered.map((frame) => rounded(frame.offMs)),\n arrivalOffsetsMs: ordered.map((frame) => rounded(frame.arrivalMs ?? frame.offMs)),\n medianIntervalMs: rounded(intervals[Math.floor(intervals.length / 2)] ?? 0),\n p95IntervalMs: rounded(intervals[Math.max(0, Math.ceil(intervals.length * 0.95) - 1)] ?? 0),\n maxIntervalMs: rounded(intervals.at(-1) ?? 0),\n maxArrivalDelayMs: rounded(\n frames.reduce(\n (max, frame) => Math.max(max, (frame.arrivalMs ?? frame.offMs) - frame.offMs),\n 0,\n ),\n ),\n outOfOrderFrames: frames.filter((frame, i) => i > 0 && frame.offMs < frames[i - 1]!.offMs)\n .length,\n note: \"Delivered-frame timing, not unique image content or a smoothness score. Static pages may send no frames; inspect image changes within active action windows. Encoded fps is separate.\",\n };\n}\n\nexport class Screencast {\n private cdp: CDP;\n private dir: string;\n private t0 = 0;\n private n = 0;\n private lastArrivalAt = 0;\n readonly frames: Frame[] = [];\n\n get idleForMs(): number {\n return Date.now() - this.lastArrivalAt;\n }\n\n constructor(cdp: CDP, dir: string) {\n this.cdp = cdp;\n this.dir = dir;\n }\n\n /** Begin capture. `t0` (Date.now) anchors every frame + event onto one clock. */\n async start(\n t0: number,\n opts: { maxWidth: number; maxHeight: number; quality?: number },\n ): Promise<void> {\n this.t0 = t0;\n this.lastArrivalAt = t0;\n this.cdp.on(\n \"Page.screencastFrame\",\n (p: { data: string; sessionId: number; metadata?: { timestamp?: number } }) => {\n const arrived = Date.now();\n this.lastArrivalAt = arrived;\n const swap = p.metadata?.timestamp;\n const hasSwap = typeof swap === \"number\" && Number.isFinite(swap);\n const off = Math.max(0, hasSwap ? swap * 1000 - this.t0 : arrived - this.t0);\n const file = join(this.dir, `f-${String(this.n++).padStart(5, \"0\")}.jpg`);\n // Release Chrome before local disk work; late delivery must not become\n // late presentation. encodeFrames orders occasional out-of-order swaps.\n this.cdp.send(\"Page.screencastFrameAck\", { sessionId: p.sessionId }).catch(() => {});\n writeFileSync(file, Buffer.from(p.data, \"base64\"));\n this.frames.push({\n file,\n offMs: off,\n arrivalMs: arrived - this.t0,\n timestampSource: hasSwap ? \"frame-swap\" : \"arrival\",\n });\n },\n );\n await this.cdp.send(\"Page.startScreencast\", {\n format: \"jpeg\",\n quality: opts.quality ?? 90,\n maxWidth: opts.maxWidth,\n maxHeight: opts.maxHeight,\n everyNthFrame: 1,\n });\n }\n\n async stop(): Promise<void> {\n await this.cdp.send(\"Page.stopScreencast\").catch(() => {});\n }\n}\n\n/** Refresh idle surfaces without interrupting pages already producing frames.\n * Never queue another expensive screenshot behind a slow/in-flight request. */\nexport async function pumpIdleRaster(\n cdp: CDP,\n screencast: Pick<Screencast, \"idleForMs\">,\n active: () => boolean,\n paused: () => boolean,\n): Promise<void> {\n let pending = false;\n while (active()) {\n if (!paused() && !pending && screencast.idleForMs >= 200) {\n pending = true;\n void cdp\n .send(\"Page.captureScreenshot\", { format: \"jpeg\", quality: 1 })\n .catch(() => {})\n .finally(() => {\n pending = false;\n });\n }\n await sleep(45);\n }\n}\n\n// --- encode timestamped frames -> video --------------------------------\n// concat demuxer with per-frame `duration` reproduces real wall-clock pacing\n// (static stretches naturally hold one frame). `-vsync cfr -r <fps>` resamples\n// onto a constant grid the web/MP4 decoders downstream read cleanly. Codec\n// follows the output extension so the file stays honest (.webm→vp9, else h264).\nexport async function encodeFrames(\n frames: Frame[],\n endMs: number,\n outPath: string,\n fps: number,\n ffmpegBin?: string,\n): Promise<void> {\n if (frames.length === 0) throw new Error(\"open-take(hi-fps): no frames captured\");\n frames = [...frames].sort((a, b) => a.offMs - b.offMs);\n const bin = ffmpegBin ?? (await resolveFfmpeg());\n const dir = dirname(frames[0]!.file);\n const listPath = join(dir, \"frames.concat\");\n\n // Each frame is shown until the next arrives; the first is held back to t0\n // so the video timeline starts where event timestamps do.\n const lines: string[] = [];\n const bounds = [\n 0,\n ...frames.slice(1).map((f) => f.offMs),\n Math.max(endMs, frames[frames.length - 1]!.offMs + 1000 / fps),\n ];\n for (let i = 0; i < frames.length; i++) {\n const dur = Math.max(0.001, (bounds[i + 1]! - bounds[i]!) / 1000);\n // Image demuxers otherwise use a 1/25s clock. Keep observed millisecond\n // timing before the final CFR resample instead of quantizing it to 40ms.\n lines.push(`file '${frames[i]!.file}'`, \"option framerate 1000\", `duration ${dur.toFixed(6)}`);\n }\n // concat demuxer ignores the final entry's duration unless the file repeats.\n lines.push(`file '${frames[frames.length - 1]!.file}'`, \"option framerate 1000\");\n writeFileSync(listPath, lines.join(\"\\n\"));\n\n const isWebm = /\\.webm$/i.test(outPath);\n const codec = isWebm\n ? [\"-c:v\", \"libvpx-vp9\", \"-b:v\", \"0\", \"-crf\", \"28\", \"-deadline\", \"good\", \"-cpu-used\", \"4\"]\n : [\"-c:v\", \"libx264\", \"-preset\", \"veryfast\", \"-crf\", \"18\"];\n\n // Color: the screencast frames are full-range JPEGs (601). For h264, convert\n // to STANDARD limited-range bt709 and label all four fields (range/matrix/\n // primaries/transfer) so every downstream decoder agrees: the revideo render,\n // end-user players, AND any browser <video>→canvas consumer.\n // Without tags ffmpeg stamped yuvj420p/pc/bt470bg, which Chrome's canvas\n // mis-decodes as limited and over-brightens (~20 levels) → washed-out colors in\n // a canvas preview, while ffmpeg/revideo honored the full-range tag and stayed\n // faithful. `scale` converts (and sets range+matrix); `setparams` adds the\n // primaries+transfer labels scale leaves unspecified, so all four are explicit.\n const colorConvert = isWebm\n ? \"\"\n : \":in_range=full:in_color_matrix=bt470bg:out_range=tv:out_color_matrix=bt709\";\n const colorLabel = isWebm\n ? \"\"\n : \",setparams=range=tv:colorspace=bt709:color_primaries=bt709:color_trc=bt709\";\n\n return new Promise((resolve, reject) => {\n const args = [\n \"-y\",\n \"-loglevel\",\n \"error\",\n \"-f\",\n \"concat\",\n \"-safe\",\n \"0\",\n \"-i\",\n listPath,\n \"-vsync\",\n \"cfr\",\n \"-r\",\n String(fps),\n // screencast frames can be odd-sized (e.g. 1280x657); yuv420p needs\n // even dims, so round down to the nearest even before pixel-format.\n \"-vf\",\n `scale=trunc(iw/2)*2:trunc(ih/2)*2${colorConvert},format=yuv420p${colorLabel}`,\n ...codec,\n outPath,\n ];\n const c = spawn(bin, args, { stdio: [\"ignore\", \"ignore\", \"pipe\"] });\n let err = \"\";\n c.stderr.on(\"data\", (d) => {\n err += d;\n });\n c.on(\"error\", reject);\n c.on(\"close\", (code) =>\n code === 0\n ? resolve()\n : reject(new Error(`ffmpeg encode exited ${code}: ${err.slice(-800)}`)),\n );\n });\n}\n\n/** A throwaway temp dir for the screencast's per-frame JPEGs. */\nexport const makeFrameDir = (): string => mkdtempSync(join(tmpdir(), \"open-take-frames-\"));\n\n/** Poll `ready` every few milliseconds until it is true or `timeoutMs` has passed.\n * Resolves true when the condition was met, false on timeout. Used to pace work\n * by something the page did (a painted frame) instead of by a blind timer. */\nexport async function waitUntil(\n ready: () => boolean,\n timeoutMs: number,\n stepMs = 4,\n): Promise<boolean> {\n const deadline = Date.now() + timeoutMs;\n while (!ready()) {\n if (Date.now() >= deadline) return false;\n await new Promise((r) => setTimeout(r, stepMs));\n }\n return true;\n}\n","// captureTake / inspectPage — drive the real app over the Chrome DevTools\n// Protocol (pure CDP — no agent-browser) and emit the ground-truth event log.\n// The exact bbox coords + measured timings are why the compositor never has\n// to *infer* zoom intent — the moat. All driving + recording lives in\n// cdp-capture.ts (captureTakeCDP); this module owns the element-locator JS\n// (shared by both paths) + the planning aid, and captureTake just delegates.\n\nimport { spawn } from \"node:child_process\";\nimport { type CaptureLog, resolveFfprobe } from \"@open-take/compositor\";\nimport { fitViewport, launchBrowser } from \"./cdp\";\nimport type { TakePlan } from \"./types\";\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\nexport type Box = { x: number; y: number; w: number; h: number };\n\n// Recursively find a {x,y,w/width,h/height} rect in a parsed value. Exported\n// so the CDP capture path can robustly extract a bbox from any eval shape.\nexport function findBox(o: unknown): Box | null {\n if (!o || typeof o !== \"object\") return null;\n const r = o as Record<string, unknown>;\n if (\n typeof r.x === \"number\" &&\n typeof r.y === \"number\" &&\n (typeof r.width === \"number\" || typeof r.w === \"number\")\n )\n return { x: r.x, y: r.y, w: (r.width ?? r.w) as number, h: (r.height ?? r.h) as number };\n for (const k of Object.keys(r)) {\n const hit = findBox(r[k]);\n if (hit) return hit;\n }\n return null;\n}\n\n// Repeatedly JSON.parse while the value is still a string (handles double-\n// encoding).\nfunction deepParse(s: unknown): unknown {\n let cur = s;\n for (let i = 0; i < 5 && typeof cur === \"string\"; i++) {\n try {\n cur = JSON.parse(cur as string);\n } catch {\n break;\n }\n }\n return cur;\n}\n\n// Extract the actual returned value from agent-browser --json output.\n// eval: {\"success\":true,\"data\":{\"result\":\"<encoded>\"},\"error\":null}\n// get box: similar wrapper around the box. Falls back to deep-parsing raw.\nexport function evalValue(raw: string): unknown {\n let top: unknown;\n try {\n top = JSON.parse(raw);\n } catch {\n return deepParse(raw);\n }\n if (top && typeof top === \"object\") {\n const o = top as Record<string, unknown>;\n const data = o.data as Record<string, unknown> | undefined;\n if (data && \"result\" in data) return deepParse(data.result);\n for (const k of [\"result\", \"output\", \"stdout\", \"value\"]) if (k in o) return deepParse(o[k]);\n }\n return deepParse(top);\n}\n\n// --- one name resolver for every text locator ---------------------------\n// Each locator below used to carry its OWN precedence chain, and they\n// disagreed: `click` matched `aria-label || textContent`, while `drag` /\n// `press` / `scroll` / `hrefFrom` put `title` FIRST, and `inspect` — the\n// planning aid whose output SKILL.md explicitly tells agents to \"target these\n// by `text`\" — used a third chain. So an element with a visible label AND a\n// tooltip was advertised by `inspect` under its label, clicked fine, and then\n// silently failed to resolve for a drag. The editor's own Compare button is a\n// live example: label \"Compare\", title \"Hold to compare against the version\n// you opened\" — `text: \"Compare\"` resolved for a click and NOTFOUND for a drag.\n// Title-only controls (icon buttons, the editor's Look swatches) were worse:\n// `inspect` skipped them entirely, so nothing advertised them at all.\n//\n// Now every locator matches against ALL of an element's names — exact before\n// substring, DOM order. This is strictly more permissive than any of the old\n// chains, so nothing that resolved before stops resolving, and an exact hit\n// anywhere in the document still beats a substring hit that comes earlier.\nexport const NAME_JS =\n `function names(e){var raw=[e.getAttribute('aria-label'),e.textContent,e.getAttribute('title'),e.getAttribute('alt'),e.getAttribute('placeholder')];var out=[];` +\n `for(var i=0;i<raw.length;i++){var s=(raw[i]||'').replace(/\\\\s+/g,' ').trim();if(s&&out.indexOf(s)===-1)out.push(s);}return out;}` +\n // The name to SHOW (inspect). Placeholder is deliberately NOT a display name:\n // inspect renders a placeholder-only field as \"[placeholder]\" so a plan\n // author can see at a glance that the control has no real label.\n `function dispName(e){var a=[e.getAttribute('aria-label'),e.textContent,e.getAttribute('title'),e.getAttribute('alt')];` +\n `for(var i=0;i<a.length;i++){var s=(a[i]||'').replace(/\\\\s+/g,' ').trim();if(s)return s;}return '';}` +\n `function pick(els,t){var i,n,j;` +\n `for(i=0;i<els.length;i++){if(names(els[i]).indexOf(t)!==-1)return els[i];}` +\n `for(i=0;i<els.length;i++){n=names(els[i]);for(j=0;j<n.length;j++){if(n[j].indexOf(t)!==-1)return els[i];}}` +\n `return null;}`;\n\n// Shared tail for both click resolvers: the element is in hand — decide HOW\n// the click gets delivered. `m.click()` fires a lone synthetic `click` event\n// with NO pointerdown/mousedown/pointerup in front of it, and a whole class\n// of real controls listens to exactly those: a Radix DropdownMenuTrigger\n// opens on pointerdown, so a programmatic click was a SILENT no-op — the\n// step \"succeeded\", nothing opened, and every later beat died with \"target\n// not found\" (a measured shoot lost 8 of 10 beats this way). So when the\n// element's centre is actually hittable — elementFromPoint lands on it or on\n// one of its descendants — do NOT click in-page: return the point (`cx`/`cy`)\n// and let the capture driver deliver a trusted CDP press/release there, the\n// full native pipeline `hover` and `drag` already use. The in-page m.click()\n// survives as the fallback for what a coordinate cannot reach: zero-size\n// targets (sr-only), a centre covered by an unrelated overlay,\n// pointer-events:none — everything that resolved before still resolves.\n//\n// Scrolling: m.click() never scrolls, and a below-fold target would advance\n// state off-screen — so scroll into view ONLY when out of frame (in-view\n// beats keep their framing) and re-read the rect so the compositor gets a\n// viewport-relative bbox. behavior:'instant' is load-bearing for the point\n// path: with CSS scroll-behavior:smooth the post-scroll rect is mid-animation\n// and the trusted click would land on yesterday's layout.\n//\n// The hittable test asks BOTH point APIs before giving up on the point path.\n// Chrome's singular elementFromPoint can return an element whose border box\n// does not even contain the point: measured on a 33px-tall heading whose\n// centre sat 16px above a sibling with 164px glyphs on a 157px line-height —\n// the sibling's ink overflow won the singular hit-test at every sample while\n// elementsFromPoint()[0] (per spec, the same answer) named the heading, and a\n// trusted click at that point reached the heading. Treating the singular miss\n// as an occluder silently downgraded the beat to m.click() — which the app\n// ignored, because its edit-mode handler resolves the anchor from the click's\n// clientX/clientY and a programmatic click carries (0,0). The beat died with\n// changeCoverage 0 and every dependent beat skipped. So: a miss from the\n// singular API alone is not occlusion — only when the layered list agrees the\n// centre belongs to someone else does the in-page fallback fire.\nconst HITTABLE_JS =\n `function hittable(m,r){var cx=Math.round(r.x+r.width/2),cy=Math.round(r.y+r.height/2);` +\n `if(!(r.width>0&&r.height>0&&document.elementFromPoint))return null;` +\n `var hit=document.elementFromPoint(cx,cy);` +\n `var ok=!!hit&&(hit===m||(m.contains&&m.contains(hit)));` +\n `if(!ok&&document.elementsFromPoint){var top=document.elementsFromPoint(cx,cy)[0];` +\n `ok=!!top&&(top===m||(m.contains&&m.contains(top)));}` +\n `return ok?{cx:cx,cy:cy}:null;}`;\n\nconst CLICK_TAIL_JS =\n `if(m.tagName==='SELECT')return 'SELECTINERT';` +\n HITTABLE_JS +\n `var r=m.getBoundingClientRect();` +\n `if(r.top<0||r.bottom>window.innerHeight){m.scrollIntoView({block:'center',behavior:'instant'});r=m.getBoundingClientRect();}` +\n `var b={x:Math.round(r.x),y:Math.round(r.y),w:Math.round(r.width),h:Math.round(r.height)};` +\n `var p=hittable(m,r);` +\n `if(p){b.cx=p.cx;b.cy=p.cy;return JSON.stringify(b);}` +\n `m.click();return JSON.stringify(b);`;\n\n// The candidate sets each by-text locator queries — exported for the\n// pre-capture check (precheck.ts), which must resolve with EXACTLY these:\n// a looser probe set would pass targets the real locator then misses, a\n// tighter one would refuse targets it finds.\nexport const CLICK_CANDIDATES =\n \"button,a,[role=button],[role=link],[role=menuitem],input[type=submit],input[type=button]\";\nexport const FIELD_CANDIDATES =\n \"input,textarea,[contenteditable],[contenteditable=true],[role=textbox],[role=searchbox]\";\nexport const BOX_CANDIDATES =\n \"button,a,[role=button],[role=link],[role=menuitem],[aria-label],[title],img[alt],li,[draggable=true]\";\nexport const SCROLL_CANDIDATES =\n \"button,a,[role=button],[role=link],[role=heading],[aria-label],[title],h1,h2,h3,li,section,p\";\n\n// Find a clickable by accessible name (aria-label or text), record its\n// rect (ground-truth bbox), and resolve the click — all in one page eval so\n// the bbox and the action refer to the same element. Robust where CSS hooks\n// are unstable. Returns the bbox, plus `cx`/`cy` when the caller should\n// deliver the click as trusted CDP input (see CLICK_TAIL_JS).\nexport function clickByTextJs(text: string): string {\n const t = JSON.stringify(text);\n return (\n `(function(){var t=${t};` +\n `var els=Array.prototype.slice.call(document.querySelectorAll('${CLICK_CANDIDATES}'));` +\n NAME_JS +\n `var m=pick(els,t);` +\n `if(!m)return 'NOTFOUND';` +\n CLICK_TAIL_JS +\n `})()`\n );\n}\n\n// Selector twin of clickByTextJs: resolve the element's rect AND the click in\n// ONE page eval, atomically. The old path made two separate agent-browser\n// round-trips (`get box <sel>` then `click <sel>`); under recording the CDP\n// `get box` call flaked (returned null ~1-in-3) and the beat was silently\n// skipped, gutting the demo. A single eval — the same mechanism the text\n// path already uses reliably — removes that race.\nexport function clickBySelectorJs(selector: string): string {\n const s = JSON.stringify(selector);\n return (\n `(function(){var m=document.querySelector(${s});` +\n `if(!m)return 'NOTFOUND';` +\n CLICK_TAIL_JS +\n `})()`\n );\n}\n\n// --- type/drag resolvers ------------------------------------------------\n// type targets are form fields (input/textarea/contenteditable), which the\n// clickable locator above does NOT match. Resolve the field by accessible\n// name OR placeholder, scroll into view, focus + click (caret), return bbox.\n//\n// Whether focus actually LANDED rides back as `f` — Input.insertText types\n// into the current selection, so when the in-page focus();click();focus()\n// bounces off (a contenteditable that only arms when the app sees a real\n// click's coordinates: measured, activeElement stayed BODY and the whole\n// string went nowhere while the step logged as a success), the driver must\n// know, not guess.\n//\n// The predicate reads the DEEP active element (piercing shadow roots — a web\n// component reports its host as document.activeElement while insertText lands\n// in the shadow's own active element) and calls it focused when it can take\n// an insertion (isContentEditable, or a string .value that is not readOnly/\n// disabled — a readOnly field swallows insertText exactly like body does)\n// AND it belongs to the target: on the composed ancestry (host chain\n// included), or as an editable host wrapping the target. document.body only\n// counts when body itself IS the target (designMode pages).\nconst FOCUS_STATE_JS =\n `function deepActive(){var a=document.activeElement;` +\n `while(a&&a.shadowRoot&&a.shadowRoot.activeElement){a=a.shadowRoot.activeElement;}return a;}` +\n `function editable(a){if(!a)return false;if(a.isContentEditable)return true;` +\n `return typeof a.value==='string'&&!a.readOnly&&!a.disabled;}` +\n `function withinTarget(a){var n=a;while(n){if(n===m||(m.contains&&m.contains(n)))return true;` +\n `var rn=n.getRootNode?n.getRootNode():null;n=n.parentElement||((rn&&rn.host)?rn.host:null);}return false;}` +\n `var ae=deepActive();` +\n `var ok=!!ae&&(ae!==document.body||m===document.body)&&editable(ae)&&` +\n `(withinTarget(ae)||(ae.isContentEditable&&ae.contains&&ae.contains(m)));`;\n\n// behavior:'instant' is load-bearing here too now: the box this returns aims\n// the driver's trusted recovery click, and a smooth scroll mid-flight would\n// hand it yesterday's layout (same reasoning as CLICK_TAIL_JS). When focus\n// bounced, `hit` says whether that recovery click can even reach the field —\n// the same hittable test the click path runs, read AFTER the in-page\n// focus/click so it sees whatever those opened. A covered centre is reported\n// rather than punched: a trusted press through an overlay would land on the\n// overlay as a real click, mutate state on camera, and the beat would still\n// skip.\nconst FOCUS_TAIL_JS =\n HITTABLE_JS +\n `var r=m.getBoundingClientRect();` +\n `if(r.top<0||r.bottom>window.innerHeight){m.scrollIntoView({block:'center',behavior:'instant'});r=m.getBoundingClientRect();}` +\n `var b={x:Math.round(r.x),y:Math.round(r.y),w:Math.round(r.width),h:Math.round(r.height)};` +\n `m.focus();m.click();m.focus();` +\n FOCUS_STATE_JS +\n `b.f=ok?1:0;` +\n `if(!ok){b.hit=hittable(m,m.getBoundingClientRect())?1:0;}` +\n `return JSON.stringify(b);`;\n\nexport function focusFieldByTextJs(text: string): string {\n const t = JSON.stringify(text);\n return (\n `(function(){var t=${t};` +\n `var els=Array.prototype.slice.call(document.querySelectorAll('${FIELD_CANDIDATES}'));` +\n NAME_JS +\n `var m=pick(els,t);` +\n `if(!m)return 'NOTFOUND';` +\n FOCUS_TAIL_JS +\n `})()`\n );\n}\n\nexport function focusSelectorJs(selector: string): string {\n const s = JSON.stringify(selector);\n return (\n `(function(){var m=document.querySelector(${s});if(!m)return 'NOTFOUND';` +\n FOCUS_TAIL_JS +\n `})()`\n );\n}\n\n// Side-effect-free re-check of the focus predicate, for after the driver has\n// delivered a trusted click at the field's centre (the recovery a real user\n// performs by hand). Resolves the target exactly like the focus builders but\n// never focuses or clicks — a second in-page click here could toggle app\n// state the first one already changed.\n//\n// After that REAL click the ownership test widens: some editors focus a\n// proxy editable OUTSIDE the clicked container (hidden textarea patterns), so\n// post-click, a deep active element that can take the insertion is accepted\n// wherever it lives — that is where a real user's click-then-type would land,\n// and the strict tier already handled the no-click case. What still skips:\n// focus parked on body or a non-editable control (the measured lie).\nexport function verifyFocusJs(target: { text?: string; selector?: string }): string {\n if (!target.text && !target.selector) return `'0'`;\n const resolve = target.text\n ? `var els=Array.prototype.slice.call(document.querySelectorAll('${FIELD_CANDIDATES}'));` +\n NAME_JS +\n `var m=pick(els,${JSON.stringify(target.text)});`\n : `var m=document.querySelector(${JSON.stringify(target.selector ?? \"\")});`;\n return (\n `(function(){${resolve}if(!m)return '0';` +\n FOCUS_STATE_JS +\n `if(ok)return '1';` +\n `return (!!ae&&ae!==document.body&&editable(ae))?'1':'0';})()`\n );\n}\n\n// Select the focused element's ENTIRE current value (input/textarea via\n// select(); contenteditable via a DOM range) so the next Input.insertText\n// REPLACES it — the `type` step's `clear: true`. Chrome's editing commands\n// don't run off dispatched key events (a \"Meta+a\" press registers nothing),\n// so the selection is made in-page instead.\nexport function selectAllInFocusedJs(): string {\n return (\n `(function(){var el=document.activeElement;if(!el)return 'NOFOCUS';` +\n `if(typeof el.select==='function'&&typeof el.value==='string'){el.select();return 'SEL';}` +\n `if(el.isContentEditable){var r=document.createRange();r.selectNodeContents(el);` +\n `var s=window.getSelection();s.removeAllRanges();s.addRange(r);return 'SEL';}` +\n `return 'NOSEL';})()`\n );\n}\n\n// bbox-only resolvers for drag endpoints — never click/focus (a drag must\n// not deselect a tool or shift the canvas before the stroke).\nexport function boxSelectorJs(selector: string): string {\n const s = JSON.stringify(selector);\n return (\n `(function(){var m=document.querySelector(${s});if(!m)return 'NOTFOUND';` +\n `var r=m.getBoundingClientRect();` +\n `if(r.top<0||r.bottom>window.innerHeight){m.scrollIntoView({block:'center'});r=m.getBoundingClientRect();}` +\n `return JSON.stringify({x:Math.round(r.x),y:Math.round(r.y),w:Math.round(r.width),h:Math.round(r.height)});})()`\n );\n}\n\nexport function boxByTextJs(text: string): string {\n const t = JSON.stringify(text);\n return (\n `(function(){var t=${t};` +\n `var els=Array.prototype.slice.call(document.querySelectorAll('${BOX_CANDIDATES}'));` +\n NAME_JS +\n `var m=pick(els,t);` +\n `if(!m)return 'NOTFOUND';var r=m.getBoundingClientRect();` +\n `if(r.top<0||r.bottom>window.innerHeight){m.scrollIntoView({block:'center'});r=m.getBoundingClientRect();}` +\n `return JSON.stringify({x:Math.round(r.x),y:Math.round(r.y),w:Math.round(r.width),h:Math.round(r.height)});})()`\n );\n}\n\n// --- href resolvers -----------------------------------------------------\n// Read a link's DESTINATION without clicking it — the late-bound half of the\n// `navigate` step. Returns the browser-resolved absolute URL (`.href`), never\n// the raw attribute, so a relative or protocol-relative link comes back usable.\n// Neither of these scrolls or clicks: nothing on screen may change, because\n// this runs mid-recording and the beat is the navigation itself.\nconst CLOSEST_ANCHOR_JS =\n // The named element may BE the link or sit inside one — closest() covers both\n // (it tests the element itself first) — or WRAP one, which it does not.\n `var a=m.closest('a[href]')||m.querySelector('a[href]');` +\n `if(!a||!a.href)return 'NOTFOUND';return a.href;`;\n\nexport function hrefSelectorJs(selector: string): string {\n const s = JSON.stringify(selector);\n return `(function(){var m=document.querySelector(${s});if(!m)return 'NOTFOUND';${CLOSEST_ANCHOR_JS}})()`;\n}\n\nexport function hrefByTextJs(text: string): string {\n const t = JSON.stringify(text);\n return (\n `(function(){var t=${t};` +\n `var els=Array.prototype.slice.call(document.querySelectorAll('a,button,[role=link],[role=button],[aria-label],[title]'));` +\n NAME_JS +\n `var m=pick(els,t);` +\n `if(!m)return 'NOTFOUND';${CLOSEST_ANCHOR_JS}})()`\n );\n}\n\n// --- scroll-to-element delta -------------------------------------------\n// How far (signed px, + = down) to scroll so the element's centre lands at\n// viewport centre. Measures the CURRENT rect WITHOUT scrollIntoView (a jump\n// would defeat the smooth wheel ramp). Returns \"NOTFOUND\" or a {dy} JSON.\nexport function scrollDeltaSelectorJs(selector: string): string {\n const s = JSON.stringify(selector);\n return (\n `(function(){var m=document.querySelector(${s});if(!m)return 'NOTFOUND';` +\n `var r=m.getBoundingClientRect();` +\n `return JSON.stringify({dy:Math.round(r.top+r.height/2-window.innerHeight/2)});})()`\n );\n}\n\nexport function scrollDeltaByTextJs(text: string): string {\n const t = JSON.stringify(text);\n return (\n `(function(){var t=${t};` +\n `var els=Array.prototype.slice.call(document.querySelectorAll('${SCROLL_CANDIDATES}'));` +\n NAME_JS +\n `var m=pick(els,t);` +\n `if(!m)return 'NOTFOUND';var r=m.getBoundingClientRect();` +\n `return JSON.stringify({dy:Math.round(r.top+r.height/2-window.innerHeight/2)});})()`\n );\n}\n\n// Sample a viewport-px point a fraction u (0..1) along a polyline by arc\n// length — used to densify a drag into smooth mouse-move steps so canvas\n// drawing libs receive continuous pointermove (and the stroke looks drawn).\nexport function sampleAlong(pts: { x: number; y: number }[], u: number): { x: number; y: number } {\n if (pts.length === 1) return pts[0]!;\n const seg: number[] = [];\n let total = 0;\n for (let i = 0; i < pts.length - 1; i++) {\n const d = Math.hypot(pts[i + 1]!.x - pts[i]!.x, pts[i + 1]!.y - pts[i]!.y);\n seg.push(d);\n total += d;\n }\n if (total === 0) return pts[0]!;\n let target = u * total;\n for (let i = 0; i < seg.length; i++) {\n if (target <= seg[i]! || i === seg.length - 1) {\n const f = seg[i]! > 0 ? target / seg[i]! : 0;\n return {\n x: pts[i]!.x + (pts[i + 1]!.x - pts[i]!.x) * f,\n y: pts[i]!.y + (pts[i + 1]!.y - pts[i]!.y) * f,\n };\n }\n target -= seg[i]!;\n }\n return pts[pts.length - 1]!;\n}\n\nexport async function ffprobe(\n path: string,\n): Promise<{ width?: number; height?: number; fps?: string; durationS?: number }> {\n // resolved binary (PATH or bundled installer); the probe itself stays\n // best-effort — a failed probe resolves {} (callers have fallbacks).\n const bin = await resolveFfprobe().catch(() => null);\n if (!bin) return {};\n return new Promise((res) => {\n const c = spawn(\n bin,\n [\n \"-v\",\n \"error\",\n \"-select_streams\",\n \"v:0\",\n \"-show_entries\",\n \"stream=width,height,r_frame_rate,duration\",\n \"-show_entries\",\n \"format=duration\",\n \"-of\",\n \"json\",\n path,\n ],\n { stdio: [\"ignore\", \"pipe\", \"ignore\"] },\n );\n let out = \"\";\n c.stdout.on(\"data\", (d) => {\n out += d;\n });\n c.on(\"close\", () => {\n try {\n const j = JSON.parse(out);\n const s = j.streams?.[0] ?? {};\n res({\n width: s.width,\n height: s.height,\n fps: s.r_frame_rate,\n durationS: Number(s.duration ?? j.format?.duration ?? 0),\n });\n } catch {\n res({});\n }\n });\n });\n}\n\nexport type CaptureOpts = {\n /** output video path (mp4) */\n videoPath: string;\n /** ms to let the page settle after capture start before the first action */\n warmupMs?: number;\n /**\n * Encode fps. Default 60; this does not guarantee 60 unique captured frames.\n * Capture is a CDP screencast at the browser's\n * native rate; this is the encode grid and the intended render fps. Drop to\n * 30 for fast-draft renders (~½ the render time + file size) while iterating.\n * See cdp-capture.ts.\n */\n fps?: number;\n /**\n * Capture pixel density (device scale factor). Default 2: record at Retina\n * density — 2 physical px per CSS px — so a camera zoom ≤2× always has\n * ≥1:1 source pixels per output pixel and stays sharp (matches how premium\n * screen recorders keep zooms crisp). Coordinates everywhere (events, log,\n * composition) stay in CSS px; only the video bitmap is denser. Drop to 1\n * if a heavy page can't hold the capture fps at 4K screencast.\n */\n captureScale?: number;\n /** Refresh idle raster surfaces with a bounded screenshot request (default\n * \"idle\"). Use \"off\" for verified self-animating pages when screenshot\n * refresh interferes with their native frame delivery. Inspect actual frames\n * and captureCadence for the chosen scale; neither mode guarantees smoothness. */\n rasterRefresh?: \"idle\" | \"off\";\n /** explicit Chrome binary (else auto-resolved system Chrome / auto-download) */\n chromePath?: string;\n /** How a `drag` stroke is paced (and thus baked into the ink): \"smooth\"\n * (accel-in / decel-out — a natural hand-draw, default) or \"linear\"\n * (constant speed). Recorded on each drag event so the compositor cursor\n * replays the same easing and stays locked to the ink. */\n dragEasing?: \"linear\" | \"smooth\";\n /** Persistent Chrome profile dir (an authenticated capture — pair with\n * `open-take auth`). Default: a throwaway temp profile, removed on close. */\n userDataDir?: string;\n /** false ⇒ drive a visible (headed) window instead of headless. The\n * screencast records either way — the escape hatch for sites that gate on\n * a real window. Default true. */\n headless?: boolean;\n /** Extra ms a beat's hold may spend waiting for the PAGE when `settleMs`\n * expires while it is still working (network in flight, DOM mutating, a\n * reveal animating). Never shortens a hold — see runtime/src/settle.ts.\n * Default `DEFAULT_SETTLE_BUDGET_MS`; 0 restores the old fixed sleeps\n * exactly. */\n settleBudgetMs?: number;\n};\n\n/** Drive `plan` against the live app over CDP, return the ground-truth log. */\nexport async function captureTake(plan: TakePlan, opts: CaptureOpts): Promise<CaptureLog> {\n const { captureTakeCDP } = await import(\"./cdp-capture\");\n return captureTakeCDP(plan, { ...opts, fps: opts.fps ?? 60 });\n}\n\n// --- inspectPage: planning aid -----------------------------------------\n\nexport type InspectElement = {\n name: string;\n tag: string;\n role: string | null;\n href: string | null;\n inView: boolean;\n x: number;\n y: number;\n w: number;\n h: number;\n};\n\nexport type InspectResult = {\n url: string;\n /** where the navigation actually landed (redirects, SPA rewrites) */\n finalUrl: string;\n /** document.title — the one-call check that this is the app you think it is\n * (a stale port number silently serves a different project's dev server) */\n title: string;\n viewport: { w: number; h: number };\n elements: InspectElement[];\n};\n\n// Exported for the locator-name tests: the bug this shares a resolver with\n// lived in the emitted page-JS, so the test evaluates this string directly.\nexport function listInteractiveJs(): string {\n return (\n `(function(){` +\n NAME_JS +\n `var sel='button,a,[role=button],[role=link],[role=menuitem],[role=tab],[role=switch],[role=checkbox],input,select,textarea';` +\n `var els=Array.prototype.slice.call(document.querySelectorAll(sel));var vw=window.innerWidth,vh=window.innerHeight;var out=[];var seen={};` +\n `for(var i=0;i<els.length;i++){var e=els[i];var n=dispName(e);var ph=e.getAttribute('placeholder');var r=e.getBoundingClientRect();` +\n `if(r.width<6||r.height<6)continue;if(!n&&!ph)continue;` +\n `var label=n||('['+(ph||e.tagName.toLowerCase())+']');var key=label+'@'+Math.round(r.x)+','+Math.round(r.y);if(seen[key])continue;seen[key]=1;` +\n `var iv=r.top<vh&&r.bottom>0&&r.left<vw&&r.right>0;` +\n `out.push({name:label,tag:e.tagName.toLowerCase(),role:e.getAttribute('role')||null,href:e.getAttribute('href')||null,inView:iv,x:Math.round(r.x),y:Math.round(r.y),w:Math.round(r.width),h:Math.round(r.height)});}` +\n `out.sort(function(a,b){return (b.inView?1:0)-(a.inView?1:0);});` +\n `return JSON.stringify(out.slice(0,60));})()`\n );\n}\n\nexport type InspectOpts = {\n viewport?: { width: number; height: number };\n warmupMs?: number;\n /** explicit Chrome binary (else auto-resolved / auto-downloaded) */\n chromePath?: string;\n /** persistent Chrome profile dir (inspect an authenticated page) */\n userDataDir?: string;\n /** false ⇒ inspect via a visible (headed) window. Default true. */\n headless?: boolean;\n};\n\n/** Open `url`, return its interactive elements (accessible name + bbox) —\n * what an agent uses to choose a demo flow. Pure CDP, same as capture, so\n * the reported coordinate space matches what capture will drive against. */\nexport async function inspectPage(url: string, opts: InspectOpts = {}): Promise<InspectResult> {\n const vw = opts.viewport?.width ?? 1920;\n const vh = opts.viewport?.height ?? 1080;\n const browser = await launchBrowser({\n width: vw,\n height: vh,\n chromePath: opts.chromePath,\n ...(opts.userDataDir ? { userDataDir: opts.userDataDir } : {}),\n ...(opts.headless === false ? { headless: false } : {}),\n });\n try {\n const { cdp } = browser;\n await cdp.send(\"Page.enable\");\n await cdp.send(\"Runtime.enable\");\n const inner = await fitViewport(cdp, browser.targetId, vw, vh);\n // errorText set ⇒ no server answered (refused/DNS/timeout) and the tab is\n // showing Chrome's own error page — inspecting ITS elements would send an\n // agent planning a demo of ERR_CONNECTION_REFUSED. An HTTP 404/500 has no\n // errorText: the app answered, inspect what it said.\n const nav = await cdp.send<{ errorText?: string }>(\"Page.navigate\", { url });\n if (nav.errorText)\n throw new Error(\n `inspectPage: ${url} did not answer (${nav.errorText}) — is the app running?`,\n );\n await sleep(opts.warmupMs ?? 1500);\n\n const evalRaw = async (expr: string): Promise<string> => {\n const r = await cdp.send<{ result?: { value?: unknown } }>(\"Runtime.evaluate\", {\n expression: expr,\n returnByValue: true,\n });\n return String(r.result?.value ?? \"\");\n };\n\n let elements: InspectElement[] = [];\n try {\n const v = evalValue(await evalRaw(listInteractiveJs()));\n if (Array.isArray(v)) elements = v as InspectElement[];\n } catch {\n /* leave empty */\n }\n const title = await evalRaw(\"document.title\").catch(() => \"\");\n const finalUrl = (await evalRaw(\"location.href\").catch(() => \"\")) || url;\n\n return { url, finalUrl, title, viewport: { w: inner[0], h: inner[1] }, elements };\n } finally {\n await browser.close();\n }\n}\n\n// --- native <select> ----------------------------------------------------\n// A native `<select>` cannot be DRIVEN by clicking it. Measured directly\n// (probe, 2026-08-09): `.click()` on a select returns in ~3ms and changes\n// NOTHING — value stays put, no popup paints, the app receives no event.\n// Headless Chrome has no browser-process popup to open, so the click is a\n// silent no-op: the beat films a cursor landing on a control that does not\n// respond, and any downstream \"the app recomputed\" payoff never happens.\n// (An earlier note here blamed a capture hang on this click; a direct probe\n// disproved that — the click is inert, not blocking.)\n//\n// So we drive it the way the PAGE experiences it: set `value` and dispatch\n// input+change. Same honesty class as `type` (synthesized keystrokes) — the\n// app really receives the event, really recomputes, and the select really\n// shows its new value on camera. Only the OS popup is missing, and that was\n// never filmable.\n//\n// The option is matched by exact value, then exact label, then a trimmed\n// substring of the label — real option text carries thin spaces, units and\n// parenthetical detail (\"Large (30 seats)\") that an author will not\n// reproduce character-perfect.\nexport function selectOptionJs(\n target: { selector?: string; text?: string },\n value: string,\n): string {\n const sel = JSON.stringify(target.selector ?? \"\");\n const name = JSON.stringify(target.text ?? \"\");\n const v = JSON.stringify(value);\n return (\n `(function(){var s=${sel},n=${name},want=${v};` +\n `var m=null;` +\n `if(s){m=document.querySelector(s);}` +\n `else if(n){var els=Array.prototype.slice.call(document.querySelectorAll('select'));` +\n // by accessible name: aria-label, the label element pointing at it, or a\n // wrapping label's text\n `m=els.find(function(e){var a=(e.getAttribute('aria-label')||'').trim();if(a===n)return true;` +\n `var id=e.id;if(id){var l=document.querySelector('label[for=\"'+id+'\"]');if(l&&(l.textContent||'').trim().indexOf(n)>=0)return true;}` +\n `var p=e.closest('label');if(p&&(p.textContent||'').trim().indexOf(n)>=0)return true;return false;})||null;}` +\n `if(!m)return 'NOTFOUND';` +\n `if(m.tagName!=='SELECT')return 'NOTASELECT';` +\n `var opts=Array.prototype.slice.call(m.options);` +\n `var norm=function(x){return (x||'').replace(/\\\\s+/g,'').trim();};` +\n `var o=opts.find(function(x){return x.value===want;})` +\n `||opts.find(function(x){return norm(x.textContent)===norm(want);})` +\n `||opts.find(function(x){return norm(x.textContent).indexOf(norm(want))>=0;});` +\n `if(!o)return 'NOOPTION';` +\n `var r=m.getBoundingClientRect();` +\n `if(r.top<0||r.bottom>window.innerHeight){m.scrollIntoView({block:'center'});r=m.getBoundingClientRect();}` +\n `m.focus();m.value=o.value;` +\n `m.dispatchEvent(new Event('input',{bubbles:true}));` +\n `m.dispatchEvent(new Event('change',{bubbles:true}));` +\n `var b={x:Math.round(r.x),y:Math.round(r.y),w:Math.round(r.width),h:Math.round(r.height)};` +\n `return JSON.stringify(b);})()`\n );\n}\n","// Destination resolution for the `navigate` step.\n//\n// A TakePlan is static JSON authored BEFORE the capture runs, which is why a\n// demo that spans two pages used to be two takes: the second page's URL often\n// does not exist yet when the plan is written (a deploy's generated domain, a\n// created record's permalink, a share link). So a navigate destination is\n// LATE-BOUND — the plan says *where to read it from*, and this resolves it\n// against what the page actually shows at that moment.\n//\n// Pure on purpose: the browser supplies `current`/`href` as strings, so every\n// precedence and merge rule below is unit-testable without launching Chrome.\n\nexport type NavigateTarget = {\n /** the page's URL right now — the base for a relative `url`, and the\n * destination itself when the step only carries `query` */\n current: string;\n /** explicit destination from the plan; absolute, or relative to `current` */\n url?: string;\n /** destination read off the page at capture time (already absolute) */\n href?: string | null;\n /** params merged onto whichever destination won. The reason this exists\n * separately from `url`: the page links to the bare thing, but the demo\n * needs it parameterised (`?speed=3` to compress a long animation into the\n * shot). Clicking the link could never produce that. */\n query?: Record<string, string>;\n};\n\n/**\n * Resolve a navigate step to one absolute URL, or null when it cannot be.\n *\n * Precedence is `href` > `url` > `current`: a destination READ FROM THE PAGE\n * beats one written in the plan, because it is the one that reflects what the\n * app just did. `current` last means `{ query }` on its own is \"reload this\n * same page with these params\" rather than an error.\n */\nexport function resolveNavigateUrl(t: NavigateTarget): string | null {\n const base = safeUrl(t.current);\n const raw = t.href || t.url || t.current;\n if (!raw) return null;\n // A relative `url` (\"/pricing\") needs the current page as its base; an\n // absolute one ignores the base. `href` is already absolute (the DOM\n // resolves it), so this is a no-op for that path.\n const dest = safeUrl(raw, base);\n if (!dest) return null;\n for (const [k, v] of Object.entries(t.query ?? {})) dest.searchParams.set(k, v);\n return dest.toString();\n}\n\nfunction safeUrl(raw: string, base?: URL): URL | undefined {\n try {\n return new URL(raw, base);\n } catch {\n return undefined;\n }\n}\n","// Pre-capture target resolution — the 2-second gate in front of the 60-second\n// shoot. Resolves every plan target against the page AS LOADED with the exact\n// locator semantics the capture will use (same candidate sets, same pick()),\n// so a plan whose opening steps can never resolve is refused BEFORE the\n// screencast exists — the same contract as the dead-URL check in cdp-capture.\n//\n// The page is stateful, so the gate is deliberately state-honest:\n// - steps up to and including the FIRST state-changing action run against\n// the initial DOM by construction — a miss there is a certainty, and an\n// error;\n// - a miss after that point is only \"not in the initial DOM\": a prior step\n// may reveal it (a toolbar that appears once editing starts), so it is a\n// warning, and the capture-time skip (plus the strict default exit) stays\n// the authority.\n// A measured motivator: 12/12 model-repaired plans of one broken take kept a\n// first click that resolves to a sidebar thumbnail instead of the headline —\n// every later beat then dies \"target not found\" after a full minute of\n// capture. The ambiguity/zero-size warnings here are how that reads BEFORE\n// the shoot.\nimport {\n BOX_CANDIDATES,\n CLICK_CANDIDATES,\n FIELD_CANDIDATES,\n NAME_JS,\n SCROLL_CANDIDATES,\n} from \"./capture\";\nimport type { TakePlan } from \"./types\";\n\nexport type PrecheckIssue = {\n severity: \"error\" | \"warn\";\n /** dotted/indexed field path, e.g. \"steps[3].selector\" */\n path: string;\n message: string;\n /** a concrete suggested correction the author can apply */\n fix?: string;\n};\n\n/** Thrown by the capture when error-severity findings refuse the shoot.\n * Carries the FULL structured findings (warns included) so the CLI can emit\n * the machine-readable defects block and exit 2 like every other gate\n * verdict — the message is only the human rendering of the same facts, and\n * flattening the findings into it is how the measured values used to get\n * lost on the way to the repair loop. */\nexport class PrecheckRefusal extends Error {\n readonly issues: PrecheckIssue[];\n constructor(message: string, issues: PrecheckIssue[]) {\n super(message);\n this.name = \"PrecheckRefusal\";\n this.issues = issues;\n }\n}\n\ntype TargetSpec = {\n step: number;\n action: string;\n field: string; // which plan field named the target (selector/text/toSelector/…)\n kind: \"selector\" | \"text\";\n value: string;\n /** true = runs against the initial DOM by construction (miss ⇒ certainty) */\n cold: boolean;\n /** press reveals are named so the ZOOM can frame them — they exist only\n * AFTER the press by definition, so a miss is never even a warning */\n revealOnly?: boolean;\n /** false = the capture will never consult this field, because the step also\n * carries the one this action resolves first (see FIELD_ORDER) */\n used: boolean;\n};\n\n// Which field the capture actually resolves when a step names more than one.\n// Read off cdp-capture / capture.ts, verb by verb: click, type, look, hover\n// and press try `text` first and do NOT fall back when it misses; `select`\n// (selectOptionJs) and `scroll` (scrollDeltaSelectorJs) try the SELECTOR\n// first; a `drag` endpoint takes a literal point, then `selector`, then\n// `text`. Grading a field the engine never reads would refuse a plan that\n// captures fine.\nconst FIELD_ORDER: Record<string, string[]> = {\n click: [\"text\", \"selector\"],\n type: [\"text\", \"selector\"],\n look: [\"text\", \"selector\"],\n hover: [\"text\", \"selector\"],\n press: [\"text\", \"selector\"],\n select: [\"selector\", \"text\"],\n scroll: [\"toSelector\", \"toText\"],\n drag: [\"selector\", \"text\"],\n};\nconst DRAG_TO_ORDER = [\"toSelector\", \"toText\"];\n\n// Any action that can change what the page shows ends the cold prefix. hover\n// and scroll are included on purpose: a hover can open a menu, a scroll can\n// mount lazy content — after either, absence from the initial DOM proves\n// nothing.\nconst MUTATING = new Set([\n \"click\",\n \"type\",\n \"press\",\n \"select\",\n \"drag\",\n \"dropFiles\",\n \"navigate\",\n \"hover\",\n \"scroll\",\n]);\n\n/** Every named target in the plan, in step order, tagged cold/late. */\nexport function planTargets(steps: TakePlan[\"steps\"]): TargetSpec[] {\n const out: TargetSpec[] = [];\n let cold = true;\n for (let i = 0; i < steps.length; i++) {\n const s = steps[i] as Record<string, unknown>;\n const action = String(s.action ?? \"\");\n const has = (f: string) => typeof s[f] === \"string\" && s[f];\n /** the first field of this group the step actually carries */\n const winner = (order: string[]) => order.find(has);\n const order = FIELD_ORDER[action];\n const dragTo = action === \"drag\" && (s.to as unknown) ? null : winner(DRAG_TO_ORDER);\n const primary = action === \"drag\" && (s.from as unknown) ? null : winner(order ?? []);\n // an action with no precedence entry gets every field checked — a new\n // verb must not silently switch the gate off for itself\n const isUsed = (field: string) => !order || field === primary || field === dragTo;\n const add = (field: string, kind: \"selector\" | \"text\", revealOnly?: boolean) => {\n const v = s[field];\n if (typeof v === \"string\" && v)\n out.push({\n step: i,\n action,\n field,\n kind,\n value: v,\n cold: cold && !revealOnly,\n used: isUsed(field),\n ...(revealOnly ? { revealOnly } : {}),\n });\n };\n switch (action) {\n case \"click\":\n case \"hover\":\n case \"look\":\n case \"type\":\n case \"select\":\n add(\"selector\", \"selector\");\n add(\"text\", \"text\");\n break;\n case \"press\":\n // the reveal target exists only after the press lands\n add(\"selector\", \"selector\", true);\n add(\"text\", \"text\", true);\n break;\n case \"scroll\":\n add(\"toSelector\", \"selector\");\n add(\"toText\", \"text\");\n break;\n case \"drag\": {\n // With a `path`, the stroke is the waypoints and each element endpoint\n // has them as a fallback (resolvePoint(...) ?? pathPts[0]) — a miss\n // costs nothing, so nothing here is load-bearing.\n const hasPath = Array.isArray(s.path) && (s.path as unknown[]).length > 0;\n if (!hasPath) {\n add(\"selector\", \"selector\");\n add(\"text\", \"text\");\n add(\"toSelector\", \"selector\");\n add(\"toText\", \"text\");\n }\n break;\n }\n case \"navigate\": {\n // navigate DOES resolve an in-page target: hrefFrom names the link\n // whose real href the demo follows — selector first, then by-text\n // over the link candidate set (capture.ts hrefSelectorJs/hrefByTextJs).\n // A cold miss here is the worst cascade in the file's header: every\n // later step is excused as \"late\", and the take shoots zero beats.\n const hf = s.hrefFrom as { selector?: string; text?: string } | undefined;\n const hfField = hf?.selector ? \"selector\" : hf?.text ? \"text\" : null;\n for (const [sub, kind] of [\n [\"selector\", \"selector\"],\n [\"text\", \"text\"],\n ] as const) {\n const v = hf?.[sub];\n if (typeof v === \"string\" && v)\n out.push({\n step: i,\n action,\n field: `hrefFrom.${sub}`,\n kind,\n value: v,\n cold,\n used: sub === hfField,\n });\n }\n break;\n }\n default:\n break; // wait names no in-page target to resolve\n }\n if (MUTATING.has(action)) cold = false;\n }\n return out;\n}\n\n/** The candidate set the ENGINE's by-text locator queries for this action —\n * imported from capture.ts so the probe and the real resolver cannot drift. */\nfunction textCandidates(action: string): string {\n switch (action) {\n case \"type\":\n return FIELD_CANDIDATES; // focusFieldByTextJs\n case \"click\":\n return CLICK_CANDIDATES; // clickByTextJs\n case \"scroll\":\n return SCROLL_CANDIDATES; // scrollDeltaByTextJs\n case \"navigate\":\n return \"a,button,[role=link],[role=button],[aria-label],[title]\"; // hrefByTextJs\n default:\n return BOX_CANDIDATES; // hover / look / drag endpoints / press reveals → boxByTextJs\n }\n}\n\n/** One page eval: resolve a target and DESCRIBE the outcome (no side effects). */\nexport function probeJs(kind: \"selector\" | \"text\", value: string, action: string): string {\n const v = JSON.stringify(value);\n const desc =\n `function desc(m){if(!m)return null;var r=m.getBoundingClientRect();` +\n `return {tag:m.tagName,w:Math.round(r.width),h:Math.round(r.height),` +\n `x:Math.round(r.x),y:Math.round(r.y),inMain:!!m.closest('main')};}`;\n if (kind === \"selector\")\n return (\n `(function(){${desc}` +\n `var all;try{all=Array.prototype.slice.call(document.querySelectorAll(${v}));}` +\n `catch(e){return JSON.stringify({err:String(e.message||e)});}` +\n `return JSON.stringify({count:all.length,first:desc(all[0]||null)});})()`\n );\n if (action === \"select\")\n // a <select> is located by its OWN semantics (selectOptionJs): aria-label\n // equal to the name, a label[for] pointing at it, or a wrapping <label> —\n // pick() over form fields would never match one.\n return (\n `(function(){${desc}var n=${v};` +\n `var els=Array.prototype.slice.call(document.querySelectorAll('select'));` +\n `var hits=els.filter(function(e){var a=(e.getAttribute('aria-label')||'').trim();if(a===n)return true;` +\n `var id=e.id;if(id){var l=document.querySelector('label[for=\"'+id+'\"]');if(l&&(l.textContent||'').trim().indexOf(n)>=0)return true;}` +\n `var p=e.closest('label');if(p&&(p.textContent||'').trim().indexOf(n)>=0)return true;return false;});` +\n `return JSON.stringify({count:hits.length?1:0,exact:hits.length,first:desc(hits[0]||null)});})()`\n );\n const set = textCandidates(action);\n // Alongside the pick itself: HOW it matched (an exact name vs a substring\n // buried in some clickable's textContent), and every element inside <main>\n // that actually carries this name — the C3.5 evidence. The intended element\n // (a headline, a paragraph) is typically NOT in the candidate set, which is\n // why a resolving target can still be the wrong node.\n return (\n `(function(){${desc}${NAME_JS}` +\n `var els=Array.prototype.slice.call(document.querySelectorAll('${set}'));` +\n `var m=pick(els,${v});` +\n `var exact=0;for(var i=0;i<els.length;i++){if(names(els[i]).indexOf(${v})!==-1)exact++;}` +\n `var how=m?(names(m).indexOf(${v})!==-1?'exact':'substring'):'none';` +\n // How much of the pick's own (shortest containing) name the value covers.\n // \"Comments\" naming a button whose name is \"Comments3\", or \"Start free\n // trial\" naming \"Start free trial →\", covers most of it — the author\n // ABBREVIATED the control's label. \"Build slides\" matched inside a\n // 200-char thumbnail blob covers a sliver — the author named something\n // else entirely. This ratio is what separates the two.\n `var share=how==='exact'?1:0,pn=null;` +\n `if(m&&how==='substring'){var mn=names(m);for(var k=0;k<mn.length;k++){` +\n `if(mn[k].indexOf(${v})!==-1&&(pn===null||mn[k].length<pn.length))pn=mn[k];}` +\n `if(pn)share=${v}.length/pn.length;}` +\n // Containment is how a plan names a fragment of a long paragraph, or a\n // headline the session has already edited — but only between names long\n // enough to be distinctive in BOTH directions: a two-letter label\n // \"contained\" in a sentence is a coincidence, not the author's intent.\n `function nm(e){var n=names(e),k;for(k=0;k<n.length;k++){if(n[k]===${v})return 'exact';}` +\n `if(${v}.length>6){for(k=0;k<n.length;k++){if(n[k].length>6&&` +\n `(n[k].indexOf(${v})!==-1||${v}.indexOf(n[k])!==-1))return 'contains';}}` +\n `return null;}` +\n `var inM=[],same=false,am=document.querySelectorAll('main *'),vwA=window.innerWidth*window.innerHeight;` +\n `for(var i=0;i<am.length;i++){var e=am[i],mk=nm(e);if(!mk)continue;` +\n // The pick wraps / sits inside the element that carries the name (a\n // clickable card around its own title, a link inside a heading): the\n // click lands on the thing the author named — no mismatch. The pick\n // MATCHING ITSELF proves nothing under substring semantics (every\n // substring pick's name contains the value by definition), so a self-hit\n // only exonerates on an exact name. Checked over EVERY match, before\n // any capping.\n `if(m&&e===m){if(mk==='exact')same=true;continue;}` +\n `if(m&&(m.contains(e)||e.contains(m))){same=true;continue;}` +\n `var d=desc(e);` +\n // display:none duplicates (responsive markup) and sr-only text measure\n // as nothing — they are not what a demo was aimed at\n `if(d.w<3||d.h<3)continue;` +\n // a containment hit the size of the stage is a container, not the element\n // the author named — every ancestor of the real target would match too\n `if(mk==='contains'&&d.w*d.h>vwA*0.25)continue;d.match=mk;inM.push(d);}` +\n // plausible intent: an exact name beats containment; among peers the\n // tightest box is the named element, its wrappers are noise\n `inM.sort(function(a,b){if(a.match!==b.match)return a.match==='exact'?-1:1;return a.w*a.h-b.w*b.h;});` +\n `return JSON.stringify({count:m?1:0,exact:exact,first:desc(m),how:how,` +\n `pickNameShare:Math.round(share*100)/100,pickName:pn?pn.slice(0,60):null,` +\n `pickIsNamed:same,mainMatches:inM.slice(0,4)});})()`\n );\n}\n\ntype Landed = {\n tag: string;\n w: number;\n h: number;\n x?: number;\n y?: number;\n inMain?: boolean;\n match?: \"exact\" | \"contains\";\n};\ntype Probe = {\n err?: string;\n count?: number;\n exact?: number;\n first?: Landed | null;\n /** how the by-text pick matched: an exact accessible name, or a substring */\n how?: \"exact\" | \"substring\" | \"none\";\n /** fraction of the pick's own (shortest containing) name the value covers:\n * 1 for an exact hit, ~0.9 for an abbreviated label (\"Comments\" naming\n * \"Comments3\"), a sliver for a match inside some blob's textContent */\n pickNameShare?: number;\n /** the pick's shortest name containing the value (substring hits only) */\n pickName?: string | null;\n /** the pick wraps/sits inside an element carrying the name, or IS one exactly */\n pickIsNamed?: boolean;\n /** elements inside <main> that carry the target's name (C3.5 evidence) */\n mainMatches?: Landed[];\n};\n\n/** C3.5 parse-intent mismatch: the pick and the same-named in-main element\n * disagree by more than a step's worth of geometry. Validated against the 36\n * plans of the X5 corpus (23 poisoned targets). A pick that covers most of\n * its own label (share >= 0.5) is the named control, abbreviated — for that\n * shape only an EXACT in-main duplicate is evidence of anything; body copy\n * merely mentioning the phrase is how landing pages talk about their own\n * buttons. */\nconst FAR_PX = 150;\nconst ABBREVIATION_SHARE = 0.5;\nfunction parseIntentMismatch(p: Probe): { pick: Landed; intended: Landed } | null {\n const pick = p.first;\n if (!pick || typeof pick.x !== \"number\" || typeof pick.y !== \"number\") return null;\n if (p.pickIsNamed) return null; // the pick is (or contains) the named element\n let matches = (p.mainMatches ?? []).filter(\n (m) => typeof m.x === \"number\" && typeof m.y === \"number\",\n );\n if ((p.pickNameShare ?? 0) >= ABBREVIATION_SHARE)\n matches = matches.filter((m) => m.match === \"exact\");\n if (!matches.length) return null;\n const cx = pick.x + pick.w / 2;\n const cy = pick.y + pick.h / 2;\n for (const m of matches) {\n // the pick IS one of the named elements — clean\n if (Math.abs(m.x! + m.w / 2 - cx) <= 5 && Math.abs(m.y! + m.h / 2 - cy) <= 5) return null;\n }\n const intended = matches[0]!; // exact-first, tightest-box-first (sorted in-page)\n const far =\n Math.abs(intended.x! + intended.w / 2 - cx) > FAR_PX ||\n Math.abs(intended.y! + intended.h / 2 - cy) > FAR_PX;\n return !pick.inMain || far ? { pick, intended } : null;\n}\n\n/** Resolve every plan target through `evalJson` (a Runtime.evaluate wrapper)\n * and grade the outcomes. Cold-prefix misses get ONE retry after `retryMs` —\n * a hydration-slow page may mount its controls a beat after load. */\nexport async function precheckPlan(\n steps: TakePlan[\"steps\"],\n evalJson: (js: string) => Promise<unknown>,\n opts?: { retryMs?: number; sleep?: (ms: number) => Promise<void> },\n): Promise<PrecheckIssue[]> {\n const sleep = opts?.sleep ?? ((ms: number) => new Promise((r) => setTimeout(r, ms)));\n // A field the capture will never read cannot break the take — probing it\n // would only produce verdicts about a resolution that never happens.\n const targets = planTargets(steps).filter((t) => t.used);\n const probes = new Map<TargetSpec, Probe>();\n const probe = async (t: TargetSpec): Promise<Probe> =>\n ((await evalJson(probeJs(t.kind, t.value, t.action))) ?? {}) as Probe;\n for (const t of targets) probes.set(t, await probe(t));\n\n // One bounded retry for every miss — a hydration-slow page mounts content a\n // beat after load, and a stale first probe would mislabel targets that ARE\n // in the initial DOM (only the cold grading below turns a miss into an\n // error; the retry just keeps both tiers honest).\n const misses = targets.filter((t) => !probes.get(t)?.err && !probes.get(t)?.count);\n if (misses.length) {\n await sleep(opts?.retryMs ?? 1500);\n for (const t of misses) probes.set(t, await probe(t));\n }\n\n const issues: PrecheckIssue[] = [];\n // Late-bound misses are EXPECTED on a healthy plan (every post-reveal step\n // has one), so they aggregate into a single advisory instead of one line\n // per step — per-step warnings on a good plan would train authors to\n // scroll past this section, which is how warnings die.\n const lateMisses: TargetSpec[] = [];\n for (const t of targets) {\n const p = probes.get(t) ?? {};\n const path = `steps[${t.step}].${t.field}`;\n const name = `${t.action} ${JSON.stringify(t.value)}`;\n if (p.err) {\n issues.push({\n severity: \"error\",\n path,\n message: `${name}: invalid selector — the page rejected it (${p.err})`,\n fix: \"fix the selector syntax; the capture would skip every use of it\",\n });\n continue;\n }\n if (!p.count) {\n if (t.revealOnly) continue; // exists only after the press, by design\n if (t.cold) {\n issues.push({\n severity: \"error\",\n path,\n message:\n `${name}: target not found in the page as loaded — this step runs before anything ` +\n `has changed the page, so it is CERTAIN to be skipped. Refusing in seconds what ` +\n `would fail after the full capture.`,\n fix:\n \"point it at an element that exists at load (`open-take inspect <url>` lists them), \" +\n \"or move it after the step that reveals it\",\n });\n } else {\n lateMisses.push(t);\n }\n continue;\n }\n // C3.5 — the target RESOLVES, so the existence check above stays quiet,\n // but it resolves to a different node than the element in <main> that\n // actually carries this name: the by-text lookup only queries the\n // action's clickable candidate set, so a headline's words match whatever\n // clickable merely CONTAINS them (measured: a sidebar page-thumbnail,\n // whose click navigates — the defect that sank a whole take). A cold\n // mismatch is a certainty by construction; a late one is graded on the\n // initial DOM, so it stays a warning. Three more conditions narrow the\n // ERROR tier to the shape that was actually measured — every one of the\n // 23 poisoned targets in the validation corpus is a SUBSTRING pick,\n // landing OUTSIDE <main>, whose value is a sliver of the picked blob's\n // name (share < 0.5) — so requiring all three costs no recall while\n // sparing the realistic look-alikes: a topbar control whose exact label\n // an in-main heading shares, an ABBREVIATED label (\"Comments\" naming the\n // header's \"Comments3\" badge button, \"Start free trial\" naming\n // \"Start free trial →\"), and two in-main elements far apart.\n // A press reveal target names what the ZOOM should frame AFTER the press,\n // so — like the miss above — the initial DOM says nothing about it.\n if (t.kind === \"text\" && !t.revealOnly) {\n const mm = parseIntentMismatch(p);\n if (mm) {\n const certain =\n t.cold &&\n p.how === \"substring\" &&\n !mm.pick.inMain &&\n (p.pickNameShare ?? 0) < ABBREVIATION_SHARE;\n issues.push({\n severity: certain ? \"error\" : \"warn\",\n path,\n message:\n `${name}: resolves to the WRONG element. The by-text lookup for ${t.action} ` +\n `searches only its candidate set and ${p.how === \"substring\" ? \"substring-\" : \"\"}matched a ` +\n `${mm.pick.w}x${mm.pick.h} ${mm.pick.tag.toLowerCase()} at (${mm.pick.x},${mm.pick.y})` +\n `${mm.pick.inMain ? \"\" : \" OUTSIDE <main>\"}` +\n `${p.pickName ? ` (its actual name: ${JSON.stringify(p.pickName)})` : \"\"}, ` +\n `while the element named ` +\n `${JSON.stringify(t.value.slice(0, 40))} is a ${mm.intended.tag.toLowerCase()} at ` +\n `(${mm.intended.x},${mm.intended.y}) inside <main>. The step would land on the impostor.`,\n fix:\n `target the in-main ${mm.intended.tag.toLowerCase()} with a CSS selector scoped to ` +\n \"`main` (`open-take inspect <url>` lists one), or name a real control instead\",\n });\n continue;\n }\n }\n if (t.kind === \"selector\" && (p.count ?? 0) > 1) {\n const z =\n p.first && (p.first.w === 0 || p.first.h === 0)\n ? \" — and the first match is ZERO-SIZE\"\n : \"\";\n issues.push({\n severity: \"warn\",\n path,\n message:\n `${name}: matches ${p.count} nodes; the engine takes the FIRST in document order${z}. ` +\n `A sidebar thumbnail or an off-screen clone outranking the real element is exactly ` +\n `how a whole take dies.`,\n fix: \"qualify the selector until it matches once (e.g. scope it to `main`)\",\n });\n continue;\n }\n if (t.kind === \"text\" && (p.exact ?? 0) > 1) {\n issues.push({\n severity: \"warn\",\n path,\n message: `${name}: ${p.exact} elements carry this exact accessible name; the engine takes the first in document order`,\n fix: \"use a more specific name, or a CSS selector scoped to the intended region\",\n });\n continue;\n }\n if (p.first && (p.first.w === 0 || p.first.h === 0)) {\n issues.push({\n severity: \"warn\",\n path,\n message: `${name}: resolves to a zero-size element — the cursor has nowhere real to land`,\n });\n }\n }\n if (lateMisses.length) {\n issues.push({\n severity: \"warn\",\n path: \"steps\",\n message:\n `${lateMisses.length} target${lateMisses.length === 1 ? \" is\" : \"s are\"} not in the initial DOM ` +\n `(${lateMisses.map((t) => `steps[${t.step}] ${JSON.stringify(t.value)}`).join(\", \")}) — ` +\n `fine if earlier steps reveal them; any that never appears is SKIPPED at capture time ` +\n `(and the run exits non-zero)`,\n });\n }\n return issues;\n}\n","// Capture-side settle: stop BETTING that the page finished inside settleMs.\n//\n// Every hold in cdp-capture.ts used to be `sleep(step.settleMs ?? N)` — a\n// fixed guess authored before the app was ever run. Two different jobs were\n// riding on that one number:\n//\n// 1. the EDITORIAL hold — how long the result stays on screen so a viewer\n// can read it. That is a taste call and belongs in the plan.\n// 2. the bet that the page had actually finished rendering by then. That is\n// not a taste call, it is a fact about the app, and guessing it wrong\n// captures the NEXT beat against a half-built page: a stale bbox, a click\n// into a button that has not mounted, a payoff frame that shows a spinner.\n//\n// This module keeps (1) exactly as it was and MEASURES (2). `settle()` runs\n// the editorial hold in full and only then, if the page is still visibly\n// working, keeps waiting — up to a budget. So a settled app pays one CDP\n// round-trip and nothing changes; a slow app gets the time it actually needs,\n// and the capture REPORTS what it needed so the next plan can stop guessing.\n//\n// It can only ever ADD time, never cut a hold short: a shortened hold would\n// silently degrade the video, which is a worse failure than waiting.\n//\n// WHAT IT SEES: DOM mutations, in-flight fetch/XHR, running finite animations,\n// pending short setTimeouts, and document.readyState. WHAT IT DOES NOT SEE:\n// repaints inside a <canvas> or <video> — no DOM signal exists for those (the\n// same blind spot that made frame-diff.ts a pixel pass).\n//\n// Timers earn their place: the commonest slow beat is not a request in flight,\n// it is \"render a skeleton now, swap in the real thing on a timer\", and DOM /\n// network / animation are all quiet across that gap. Two guards keep the\n// signal from turning into a permanent \"busy\": only timers under\n// TIMER_MAX_MS count (a 5s poll loop is the page's heartbeat, not this beat's\n// work), and infinite-iteration animations (spinners, pulses) are ignored\n// outright — they never end, so counting them would spend the whole budget on\n// every beat of any page that has one.\n\nimport type { CDP } from \"./cdp\";\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\n/** Extra time a hold may spend waiting for a busy page, per beat. Generous\n * enough for a slow round-trip, short enough that a page which NEVER goes\n * quiet (a live clock, a polling dashboard) costs a bounded, reported amount\n * rather than stretching the take without explanation. */\nexport const DEFAULT_SETTLE_BUDGET_MS = 1200;\n/** The page must have been still this long to count as settled — one paint\n * plus slack, so a mutation and the layout it triggers aren't read as two\n * separate quiet periods. */\nconst QUIET_MS = 120;\nconst POLL_MS = 60;\n/** A pending setTimeout longer than this is the page's own heartbeat (a poll\n * loop, a session timer), not this beat finishing. Counting it would make the\n * page look permanently busy. */\nconst TIMER_MAX_MS = 2000;\n/** Grace on a timer's own deadline before it stops counting as pending. Errs\n * SHORT on purpose: expiring early costs the old behaviour (a beat that may\n * be captured a touch soon), expiring late costs dead air in the cut on\n * every remaining beat — a much worse trade. */\nconst TIMER_SLACK_MS = 250;\n/** A <canvas>/<video> covering this much of the frame makes the probe\n * effectively blind for that beat: the element never changes size, position\n * or attributes no matter what is painted inside it, so \"the page is done\"\n * is unanswerable. Set low on purpose — a needless note costs a line of\n * output, a missed one costs an author trusting a quiet run that proved\n * nothing. */\nexport const PAINT_BLIND_FRAC = 0.2;\n\n/** Installed once per document; keeps `t` at the last moment anything moved. */\nconst PROBE_INSTALL_JS = `(() => {\n if (window.__openTakeActivity) return;\n const TIMER_MAX = ${TIMER_MAX_MS}, TIMER_SLACK = ${TIMER_SLACK_MS};\n const A = { t: 0, net: 0, timers: 0 };\n const touch = () => { A.t = performance.now(); };\n touch();\n try {\n new MutationObserver(touch).observe(document, {\n subtree: true, childList: true, attributes: true, characterData: true,\n });\n } catch (e) {}\n try {\n const of = window.fetch;\n if (typeof of === \"function\")\n window.fetch = function () {\n A.net++; touch();\n let p;\n try { p = of.apply(window, arguments); } catch (e) { A.net--; throw e; }\n return Promise.resolve(p).then(\n (r) => { A.net--; touch(); return r; },\n (e) => { A.net--; touch(); throw e; },\n );\n };\n } catch (e) {}\n try {\n const os = XMLHttpRequest.prototype.send;\n if (typeof os === \"function\")\n XMLHttpRequest.prototype.send = function () {\n A.net++; touch();\n // send() throws on API misuse (send before open, send after abort) and\n // then NO request exists, so loadend never fires — without this the\n // increment is permanent and the page reads busy for the rest of the\n // take. Same guard the fetch branch above already has.\n try { this.addEventListener(\"loadend\", () => { A.net--; touch(); }); } catch (e) {}\n try { return os.apply(this, arguments); } catch (e) { A.net--; touch(); throw e; }\n };\n } catch (e) {}\n try {\n const st = window.setTimeout, ct = window.clearTimeout, ci = window.clearInterval;\n // id -> the moment it must have fired by. Counting by DEADLINE rather than\n // by cancellation bookkeeping is what makes this safe: a timer we never see\n // cancelled (clearInterval on a setTimeout id, an id coerced through a\n // dataset attribute, any API we did not wrap) simply expires and stops\n // counting. Chasing every cancellation path would leave one uncounted, and\n // ONE stuck entry means every remaining beat of the take waits the whole\n // budget for nothing.\n const live = new Map();\n const forget = function (id) { live.delete(Number(id)); };\n A.pending = function () {\n const now = performance.now();\n live.forEach(function (due, id) { if (due <= now) live.delete(id); });\n A.timers = live.size;\n return live.size;\n };\n window.setTimeout = function (fn, delay) {\n const d = Number(delay) || 0;\n // a string body keeps the original semantics (wrapping would stop the\n // code ever running), and a long delay is a heartbeat, not this beat\n if (typeof fn !== \"function\" || d > TIMER_MAX) return st.apply(window, arguments);\n const rest = Array.prototype.slice.call(arguments, 2);\n let id;\n const wrapped = function () {\n forget(id); touch();\n return fn.apply(this, arguments);\n };\n id = st.apply(window, [wrapped, d].concat(rest));\n live.set(Number(id), performance.now() + d + TIMER_SLACK);\n touch();\n return id;\n };\n // Both cancellers, and both coerce their argument the way the platform\n // does — clearInterval legally cancels a setTimeout (one timer map), and\n // clearTimeout(String(id)) is what you get back out of a dataset.\n window.clearTimeout = function (id) { forget(id); return ct.apply(window, arguments); };\n window.clearInterval = function (id) { forget(id); return ci.apply(window, arguments); };\n } catch (e) {}\n window.__openTakeActivity = A;\n})()`;\n\n/** Reads the probe. Returns a JSON string so one Runtime.evaluate round-trip\n * carries the whole answer (returnByValue on a plain object also works, but\n * the rest of this package already speaks the JSON-string convention). */\nconst PROBE_READ_JS = `(() => {\n const A = window.__openTakeActivity;\n if (!A) return JSON.stringify({ ok: false });\n let anims = 0;\n try {\n for (const a of document.getAnimations()) {\n if (a.playState !== \"running\") continue;\n let it = 1;\n try { it = a.effect.getTiming().iterations; } catch (e) {}\n if (it === Infinity) continue; // ambient — never settles, never counted\n anims++;\n }\n } catch (e) {}\n // The largest <canvas>/<video> as a fraction of the viewport, clipped to it\n // (an offscreen or scrolled-away surface is not what the viewer is watching).\n let paint = 0;\n try {\n const area = innerWidth * innerHeight;\n if (area > 0)\n for (const el of document.querySelectorAll(\"canvas,video\")) {\n const r = el.getBoundingClientRect();\n const w = Math.max(0, Math.min(r.right, innerWidth) - Math.max(r.left, 0));\n const h = Math.max(0, Math.min(r.bottom, innerHeight) - Math.max(r.top, 0));\n if (w * h > paint * area) paint = (w * h) / area;\n }\n } catch (e) {}\n const timers = typeof A.pending === \"function\" ? A.pending() : (A.timers | 0);\n const busy = A.net > 0 || timers > 0 || anims > 0 || document.readyState !== \"complete\";\n return JSON.stringify({\n ok: true,\n quietMs: busy ? 0 : Math.max(0, performance.now() - A.t),\n net: A.net,\n timers,\n anims,\n paint,\n });\n})()`;\n\nexport type SettleOutcome = {\n /** the editorial hold, run in full and unchanged */\n heldMs: number;\n /** extra time spent waiting for the page AFTER the hold */\n waitedMs: number;\n /** how the wait ended: the page went quiet, the budget ran out, or no probe\n * was installed (an older page context / a navigation in flight) */\n reason: \"idle\" | \"budget\" | \"unavailable\";\n /** biggest share of the frame a <canvas>/<video> held while this beat waited.\n * Past PAINT_BLIND_FRAC the \"idle\" verdict above says nothing about what was\n * painted inside it — see the module header. */\n paintFrac: number;\n};\n\n/** Install the activity probe for the current document AND every future one\n * (a plan may navigate mid-take). Never throws — a capture must not fail\n * because a diagnostic could not be attached. */\nexport async function installActivityProbe(cdp: CDP): Promise<void> {\n await cdp\n .send(\"Page.addScriptToEvaluateOnNewDocument\", { source: PROBE_INSTALL_JS })\n .catch(() => {});\n await cdp.send(\"Runtime.evaluate\", { expression: PROBE_INSTALL_JS }).catch(() => {});\n}\n\ntype Probe = { quietMs: number; net: number; timers: number; anims: number; paint: number };\n\nasync function readProbe(cdp: CDP): Promise<Probe | null> {\n try {\n const r = await cdp.send<{ result?: { value?: unknown } }>(\"Runtime.evaluate\", {\n expression: PROBE_READ_JS,\n returnByValue: true,\n });\n const v = r.result?.value;\n if (typeof v !== \"string\") return null;\n const p = JSON.parse(v) as Partial<Probe> & { ok?: boolean };\n if (!p.ok) return null;\n return {\n quietMs: p.quietMs ?? 0,\n net: p.net ?? 0,\n timers: p.timers ?? 0,\n anims: p.anims ?? 0,\n paint: p.paint ?? 0,\n };\n } catch {\n return null;\n }\n}\n\n/**\n * Hold for `heldMs` (the editorial beat — always run in full), then keep\n * waiting while the page is still working, up to `budgetMs`.\n *\n * `budgetMs <= 0` reduces this to the old fixed sleep exactly — the escape\n * hatch for a page that never goes quiet (`CaptureOpts.settleBudgetMs: 0`),\n * and what the unit tests use to pin the legacy timing.\n */\nexport async function settle(\n cdp: CDP,\n heldMs: number,\n opts: { budgetMs?: number } = {},\n): Promise<SettleOutcome> {\n const budget = opts.budgetMs ?? DEFAULT_SETTLE_BUDGET_MS;\n await sleep(Math.max(0, heldMs));\n if (!(budget > 0)) return { heldMs, waitedMs: 0, reason: \"budget\", paintFrac: 0 };\n const t0 = Date.now();\n let paintFrac = 0;\n for (;;) {\n const p = await readProbe(cdp);\n const waitedMs = Date.now() - t0;\n if (!p) return { heldMs, waitedMs, reason: \"unavailable\", paintFrac };\n paintFrac = Math.max(paintFrac, p.paint);\n if (p.quietMs >= QUIET_MS) return { heldMs, waitedMs, reason: \"idle\", paintFrac };\n if (waitedMs >= budget) return { heldMs, waitedMs, reason: \"budget\", paintFrac };\n await sleep(POLL_MS);\n }\n}\n\n/** How many beats in a row may spend the WHOLE budget without the page ever\n * settling before the waiting is written off. */\nexport const SETTLE_GIVE_UP_STREAK = 2;\n\n/**\n * Budget policy across one take. Some pages never go quiet — a one-second\n * clock, a poll loop, a streaming widget — and no DOM signal can tell that\n * apart from real work. So do not try: once a run of beats has each spent the\n * entire budget with no result, the waiting is provably not helping, and\n * paying it on every remaining beat would add more dead air than the whole\n * demo is long. Give up once, loudly, and let the author set settleMs by eye.\n */\nexport function makeBudgetGovernor(budgetMs: number, giveUpStreak = SETTLE_GIVE_UP_STREAK) {\n let budget = budgetMs;\n let streak = 0;\n return {\n get budgetMs() {\n return budget;\n },\n get gaveUp() {\n return budget <= 0 && budgetMs > 0;\n },\n /** Feed every outcome back. Returns true on the ONE call that gives up. */\n record(reason: SettleOutcome[\"reason\"]): boolean {\n if (reason === \"idle\") {\n streak = 0;\n return false;\n }\n if (reason !== \"budget\" || budget <= 0) return false;\n if (++streak < giveUpStreak) return false;\n budget = 0;\n return true;\n },\n };\n}\n","// captureTakeCDP — the high-fps capture path (HANDOFF #5).\n//\n// Same contract as captureTake (drive `plan` against the live app, emit the\n// ground-truth CaptureLog + a video at `videoPath`), but it launches its own\n// headless Chrome and drives AND captures over one CDP page session. That\n// removes agent-browser's ~10fps recordVideo ceiling (→ ~60fps screencast)\n// and the per-step process spawn (→ drags driven at ~16ms steps, so the\n// captured ink stays in lockstep with the synthetic cursor). See\n// spike-revideo/fps/VERDICT.md. The ELEMENT-RESOLUTION logic is reused\n// verbatim from capture.ts — same locator JS, run via Runtime.evaluate —\n// so robustness is shared, not re-derived.\n\nimport { existsSync, rmSync, statSync } from \"node:fs\";\nimport { basename, resolve } from \"node:path\";\nimport type { CaptureLog } from \"@open-take/compositor\";\nimport type { CaptureOpts } from \"./capture\";\nimport {\n type Box,\n boxByTextJs,\n boxSelectorJs,\n clickBySelectorJs,\n clickByTextJs,\n evalValue,\n ffprobe,\n findBox,\n focusFieldByTextJs,\n focusSelectorJs,\n hrefByTextJs,\n hrefSelectorJs,\n sampleAlong,\n scrollDeltaByTextJs,\n scrollDeltaSelectorJs,\n selectAllInFocusedJs,\n selectOptionJs,\n verifyFocusJs,\n} from \"./capture\";\nimport {\n type Browser,\n type CDP,\n captureCadence,\n encodeFrames,\n fitViewport,\n launchBrowser,\n makeFrameDir,\n pumpIdleRaster,\n Screencast,\n waitUntil,\n} from \"./cdp\";\nimport { resolveNavigateUrl } from \"./nav\";\nimport { PrecheckRefusal, precheckPlan } from \"./precheck\";\nimport {\n DEFAULT_SETTLE_BUDGET_MS,\n installActivityProbe,\n makeBudgetGovernor,\n PAINT_BLIND_FRAC,\n settle,\n} from \"./settle\";\nimport type { TakePlan } from \"./types\";\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\n/** Report a settle wait only past this — a couple of polls is the probe\n * confirming quiet, not the page being slow, and a log full of 60ms notes\n * would bury the beat that actually needed a second. */\nconst SETTLE_NOTE_MS = 150;\n\n// smootherstep — ease-in-out. Used to ease a drag along its path (must match\n// the compositor's drag easing in math.ts exactly so the cursor stays locked\n// to the captured ink).\nconst smoother = (u: number) => {\n const clamped = Math.max(0, Math.min(1, u));\n return clamped * clamped * clamped * (clamped * (clamped * 6 - 15) + 10);\n};\n\ntype Pt = { x: number; y: number };\n\n// Run a locator JS string (the same builders capture.ts uses) and parse the\n// box it returns. `returnByValue` hands us the inner JSON string; evalValue\n// unwraps any double-encoding, then findBox extracts the rect.\nasync function evalBox(cdp: CDP, js: string): Promise<Box | null> {\n const r = await cdp.send<{ result?: { value?: unknown } }>(\"Runtime.evaluate\", {\n expression: js,\n returnByValue: true,\n awaitPromise: true,\n });\n const v = r.result?.value;\n if (v == null || v === \"NOTFOUND\") return null;\n return findBox(evalValue(typeof v === \"string\" ? v : JSON.stringify(v)));\n}\n\n// Run a locator JS string and return its parsed value (any shape), or null for\n// a NOTFOUND / empty result. Used by scroll-to-element ({dy} delta).\nasync function evalAny(cdp: CDP, js: string): Promise<unknown> {\n const r = await cdp.send<{ result?: { value?: unknown } }>(\"Runtime.evaluate\", {\n expression: js,\n returnByValue: true,\n awaitPromise: true,\n });\n const v = r.result?.value;\n if (v == null || v === \"NOTFOUND\") return null;\n return evalValue(typeof v === \"string\" ? v : JSON.stringify(v));\n}\n\n// Run a locator JS string and return its STRING result (a URL), or null for a\n// NOTFOUND/empty one. Deliberately NOT evalAny: a URL is not JSON, and the\n// deep-parse that unwraps box payloads would mangle it.\nasync function evalString(cdp: CDP, js: string): Promise<string | null> {\n const r = await cdp.send<{ result?: { value?: unknown } }>(\"Runtime.evaluate\", {\n expression: js,\n returnByValue: true,\n awaitPromise: true,\n });\n const v = r.result?.value;\n return typeof v === \"string\" && v !== \"NOTFOUND\" && v !== \"\" ? v : null;\n}\n\n// Wait (bounded) for the document's webfonts. A capture runs on a fresh temp\n// profile, so the HTTP cache is cold and third-party webfonts otherwise FOUT in\n// the first ~700ms the document is on screen. Runs before the recording clock\n// starts AND after every mid-take `navigate` — the second document is exactly\n// as cold as the first, and a FOUT mid-shot is just as visible as one at the\n// head. A page with no webfonts resolves immediately.\nasync function awaitFonts(cdp: CDP): Promise<void> {\n await Promise.race([\n cdp\n .send(\"Runtime.evaluate\", {\n expression: \"document.fonts.ready.then(() => true)\",\n awaitPromise: true,\n returnByValue: true,\n })\n .catch(() => {}),\n sleep(3000),\n ]);\n}\n\nconst center = (b: Box): Pt => ({ x: Math.round(b.x + b.w / 2), y: Math.round(b.y + b.h / 2) });\n\n// mouse via CDP Input — trusted events, near-zero per-call overhead.\n// `buttons` is the bitmask of *currently-pressed* buttons (1 = left held);\n// `button` names the one this event acts on (\"none\" for a bare move).\nconst mouse = (\n cdp: CDP,\n type: \"mousePressed\" | \"mouseReleased\" | \"mouseMoved\",\n x: number,\n y: number,\n buttons = 0,\n) =>\n cdp.send(\"Input.dispatchMouseEvent\", {\n type,\n x: Math.round(x),\n y: Math.round(y),\n button: type === \"mouseMoved\" ? \"none\" : \"left\",\n buttons,\n ...(type === \"mouseMoved\" ? {} : { clickCount: 1 }),\n });\n\n// --- keyboard ----------------------------------------------------------\n// CDP modifier bitmask: Alt=1, Ctrl=2, Meta(⌘)=4, Shift=8.\nconst MOD: Record<string, number> = {\n alt: 1,\n option: 1,\n ctrl: 2,\n control: 2,\n meta: 4,\n cmd: 4,\n command: 4,\n super: 4,\n win: 4,\n shift: 8,\n};\ntype KeyInfo = { key: string; code: string; vk: number; text?: string };\n// Named non-printable keys an editorial demo reaches for. `text` only where a\n// page expects a character (Enter submits forms via \"\\r\"; Space inserts \" \").\nconst NAMED: Record<string, KeyInfo> = {\n enter: { key: \"Enter\", code: \"Enter\", vk: 13, text: \"\\r\" },\n return: { key: \"Enter\", code: \"Enter\", vk: 13, text: \"\\r\" },\n tab: { key: \"Tab\", code: \"Tab\", vk: 9 },\n escape: { key: \"Escape\", code: \"Escape\", vk: 27 },\n esc: { key: \"Escape\", code: \"Escape\", vk: 27 },\n backspace: { key: \"Backspace\", code: \"Backspace\", vk: 8 },\n delete: { key: \"Delete\", code: \"Delete\", vk: 46 },\n space: { key: \" \", code: \"Space\", vk: 32, text: \" \" },\n arrowup: { key: \"ArrowUp\", code: \"ArrowUp\", vk: 38 },\n arrowdown: { key: \"ArrowDown\", code: \"ArrowDown\", vk: 40 },\n arrowleft: { key: \"ArrowLeft\", code: \"ArrowLeft\", vk: 37 },\n arrowright: { key: \"ArrowRight\", code: \"ArrowRight\", vk: 39 },\n up: { key: \"ArrowUp\", code: \"ArrowUp\", vk: 38 },\n down: { key: \"ArrowDown\", code: \"ArrowDown\", vk: 40 },\n left: { key: \"ArrowLeft\", code: \"ArrowLeft\", vk: 37 },\n right: { key: \"ArrowRight\", code: \"ArrowRight\", vk: 39 },\n home: { key: \"Home\", code: \"Home\", vk: 36 },\n end: { key: \"End\", code: \"End\", vk: 35 },\n pageup: { key: \"PageUp\", code: \"PageUp\", vk: 33 },\n pagedown: { key: \"PageDown\", code: \"PageDown\", vk: 34 },\n};\n\n// VK code for the Left variant of each modifier (dispatched as its own key\n// event so apps that track modifier keydown state see it pressed).\nconst MOD_KEY: Record<number, KeyInfo> = {\n 1: { key: \"Alt\", code: \"AltLeft\", vk: 18 },\n 2: { key: \"Control\", code: \"ControlLeft\", vk: 17 },\n 4: { key: \"Meta\", code: \"MetaLeft\", vk: 91 },\n 8: { key: \"Shift\", code: \"ShiftLeft\", vk: 16 },\n};\n\n// Parse \"Meta+k\" / \"Enter\" / \"Control+Shift+p\" into a modifier bitmask + the\n// main key's CDP fields. The last token is the key; the rest are modifiers.\nfunction parseChord(keys: string): { mods: number; info: KeyInfo } {\n const tokens = keys\n .split(\"+\")\n .map((t) => t.trim())\n .filter(Boolean);\n const main = tokens.pop() ?? \"\";\n let mods = 0;\n for (const t of tokens) mods |= MOD[t.toLowerCase()] ?? 0;\n const named = NAMED[main.toLowerCase()];\n let info: KeyInfo;\n if (named) {\n info = named;\n } else {\n // a single printable character\n const ch = main;\n const code = /^[a-z]$/i.test(ch)\n ? `Key${ch.toUpperCase()}`\n : /^[0-9]$/.test(ch)\n ? `Digit${ch}`\n : \"\";\n info = { key: ch, code, vk: ch.toUpperCase().charCodeAt(0) || 0 };\n // include the character ONLY for a bare key (no Ctrl/Meta/Alt) — a shortcut\n // must not also insert text.\n if (!(mods & (1 | 2 | 4))) info.text = ch;\n }\n return { mods, info };\n}\n\nasync function dispatchKey(\n cdp: CDP,\n type: \"keyDown\" | \"keyUp\",\n info: KeyInfo,\n mods: number,\n): Promise<void> {\n await cdp.send(\"Input.dispatchKeyEvent\", {\n type: info.text && type === \"keyDown\" ? \"keyDown\" : type,\n modifiers: mods,\n key: info.key,\n code: info.code,\n windowsVirtualKeyCode: info.vk,\n nativeVirtualKeyCode: info.vk,\n ...(info.text ? { text: info.text } : {}),\n });\n}\n\n// Press a chord: hold modifiers, tap the key, release in reverse — the order a\n// real keyboard produces, so apps tracking modifier state respond correctly.\nasync function pressChord(cdp: CDP, keys: string): Promise<void> {\n const { mods, info } = parseChord(keys);\n const active = [1, 2, 4, 8].filter((m) => mods & m);\n for (const m of active) await dispatchKey(cdp, \"keyDown\", MOD_KEY[m]!, mods);\n await dispatchKey(cdp, \"keyDown\", info, mods);\n await sleep(40);\n await dispatchKey(cdp, \"keyUp\", info, mods);\n for (const m of active.reverse()) await dispatchKey(cdp, \"keyUp\", MOD_KEY[m]!, 0);\n}\n\n/** High-fps twin of captureTake. Drives + records via CDP. */\nexport async function captureTakeCDP(plan: TakePlan, opts: CaptureOpts): Promise<CaptureLog> {\n const vw = plan.viewport?.width ?? 1920;\n const vh = plan.viewport?.height ?? 1080;\n const fps = Math.min(60, Math.max(24, Math.round(opts.fps ?? 60)));\n const scale = Math.max(1, opts.captureScale ?? 2);\n const out = resolve(opts.videoPath);\n\n let browser: Browser | null = null;\n const frameDir = makeFrameDir();\n try {\n browser = await launchBrowser({\n width: vw,\n height: vh,\n chromePath: opts.chromePath,\n deviceScaleFactor: scale,\n ...(opts.userDataDir ? { userDataDir: opts.userDataDir } : {}),\n ...(opts.headless === false ? { headless: false } : {}),\n });\n const { cdp } = browser;\n await cdp.send(\"Page.enable\");\n await cdp.send(\"Runtime.enable\");\n // Grow the window so the natural viewport == requested (headless reserves\n // window chrome). This — NOT a metrics override — keeps the captured frame,\n // the viewport, and the event coordinate space all the same size (the\n // frame is exactly `scale`× the CSS event space; see launchBrowser).\n let inner = await fitViewport(cdp, browser.targetId, vw, vh);\n\n // Watch the page for activity from the very first document (and every\n // one a mid-take navigation creates) so a hold can tell \"finished\" from\n // \"still working\" instead of betting on settleMs. Diagnostic only — a\n // failure to install just returns the old fixed-sleep behaviour.\n await installActivityProbe(cdp);\n if (!originAllowed(plan.url))\n throw new Error(\n `captureTakeCDP: plan.url ${plan.url} is outside OPEN_TAKE_ALLOWED_ORIGINS — an unattended run only films the app it was pointed at`,\n );\n // Fail BEFORE the screencast exists: a URL nobody is listening on used to\n // sail through here and produce a polished 4K take of Chrome's\n // ERR_CONNECTION_REFUSED page, minutes after the mistake was made.\n const navError = await navigate(cdp, plan.url);\n if (navError)\n throw new Error(\n `captureTakeCDP: ${plan.url} did not answer (${navError}) — is the app running? ` +\n `Start it (or fix the URL) and re-make; nothing was recorded.`,\n );\n await installActivityProbe(cdp);\n\n // Fonts before frames — the recording's first ~700ms is the one place a\n // viewer's eye is guaranteed to be. Every mid-take `navigate` repeats this.\n await awaitFonts(cdp);\n\n // Re-fit AFTER navigation + font wait: a window manager (cloud/Xvfb) can\n // re-apply its own bounds during those seconds, and a viewport measured\n // before that lie skews EVERY recorded coordinate the same way — a real\n // take shipped with the cursor drawn 13% below every control because the\n // window grew ~1226px tall after the first measure while the screencast\n // stayed capped at the stale 1080. Re-running the fit both retries the\n // requested size and, failing that, adopts what the window truly is.\n inner = await fitViewport(cdp, browser.targetId, vw, vh);\n\n // The 2-second gate in front of the 60-second shoot: resolve every plan\n // target with the exact locator semantics the steps below will use. A\n // cold-prefix miss is a certainty, and fails here — BEFORE the screencast\n // exists — like the dead-URL check above. Warnings ride along on the log.\n const precheck = await precheckPlan(plan.steps, (js) => evalAny(cdp, js));\n const precheckErrors = precheck.filter((p) => p.severity === \"error\");\n if (precheckErrors.length)\n throw new PrecheckRefusal(\n `captureTakeCDP: ${precheckErrors.length} plan target(s) failed the pre-capture check — nothing was recorded:\\n` +\n precheckErrors\n .map((p) => ` ${p.path}: ${p.message}${p.fix ? `\\n fix: ${p.fix}` : \"\"}`)\n .join(\"\\n\"),\n precheck,\n );\n for (const p of precheck)\n console.error(`captureTakeCDP precheck [${p.severity}] ${p.path}: ${p.message}`);\n\n const screencast = new Screencast(cdp, frameDir);\n const t0 = Date.now();\n // max dims in PHYSICAL px — at deviceScaleFactor 2 the surface is 2× the\n // CSS viewport; capping at CSS size would silently downscale back to 1×.\n await screencast.start(t0, {\n maxWidth: inner[0] * scale,\n maxHeight: inner[1] * scale,\n quality: 92,\n });\n\n // Refresh genuinely idle surfaces, not every 45ms: unconditional large\n // screenshots interrupt native animations and can queue behind each other.\n // A held mouse button still pauses the pump because screenshots can stall\n // CDP input mid-drag. The helper never waits indefinitely on a screenshot.\n let pumping = true;\n let pumpPaused = false;\n const pump =\n opts.rasterRefresh === \"off\"\n ? Promise.resolve()\n : pumpIdleRaster(\n cdp,\n screencast,\n () => pumping,\n () => pumpPaused,\n );\n\n await sleep(opts.warmupMs ?? 900);\n\n const resolvePoint = async (spec: {\n point?: Pt;\n selector?: string;\n text?: string;\n }): Promise<Pt | null> => {\n if (spec.point) return { x: Math.round(spec.point.x), y: Math.round(spec.point.y) };\n if (spec.selector) {\n const b = await evalBox(cdp, boxSelectorJs(spec.selector));\n return b ? center(b) : null;\n }\n if (spec.text) {\n const b = await evalBox(cdp, boxByTextJs(spec.text));\n return b ? center(b) : null;\n }\n return null;\n };\n\n const events: CaptureLog[\"events\"] = [];\n // Dropped steps are collected onto the log (and echoed to stderr at the\n // moment they happen) so the end-of-run summary and the strict-by-default\n // exit code can see them\n // — an early stderr line alone gets buried under render progress.\n const skipped: NonNullable<CaptureLog[\"skipped\"]> = [];\n // Beats whose hold was NOT long enough for the page — the measurement that\n // turns `settleMs` from a guess into a number the next plan can copy.\n const settleWaits: NonNullable<CaptureLog[\"settleWaits\"]> = [];\n // Bounds what a page that never goes quiet can cost the take — see\n // makeBudgetGovernor.\n const governor = makeBudgetGovernor(opts.settleBudgetMs ?? DEFAULT_SETTLE_BUDGET_MS);\n // Biggest paint surface seen. Reported ONCE — an author who sees no ⏱\n // lines would otherwise read that as \"my timings were right\", which on a\n // canvas app is exactly the wrong conclusion.\n let paintedFrac = 0;\n let paintNoted = false;\n for (let stepIdx = 0; stepIdx < plan.steps.length; stepIdx++) {\n const step = plan.steps[stepIdx]!;\n const skip = (action: string, target: string | undefined, reason: string) => {\n skipped.push({ step: stepIdx, action, ...(target ? { target } : {}), reason });\n console.error(`captureTakeCDP: ${action} ${reason}, skipped: ${JSON.stringify(target)}`);\n };\n // The editorial hold, then — only if the page is still working — the\n // time it actually needs. `defaultMs` stays the per-action default the\n // plan author never has to think about; `step.settleMs` still wins.\n const hold = async (defaultMs: number) => {\n // `step` is the un-narrowed union here (every action calls this), and\n // `wait` is the one variant with no settleMs — it IS a hold.\n const heldMs = (\"settleMs\" in step ? step.settleMs : undefined) ?? defaultMs;\n const r = await settle(cdp, heldMs, { budgetMs: governor.budgetMs });\n paintedFrac = Math.max(paintedFrac, r.paintFrac);\n if (paintedFrac >= PAINT_BLIND_FRAC && !paintNoted) {\n paintNoted = true;\n console.error(\n `captureTakeCDP: a <canvas>/<video> covers ~${Math.round(paintedFrac * 100)}% of the frame — the settle probe reads page STRUCTURE and cannot see what is painted inside one, so on beats whose payoff is drawn there, settleMs is doing the whole job. Set those by eye and check \\`frames\\`.`,\n );\n }\n if (governor.record(r.reason))\n console.error(\n \"captureTakeCDP: this page never goes quiet (consecutive beats spent the whole settle budget) — settle waiting is OFF for the rest of the take; set each beat's settleMs explicitly instead\",\n );\n if (r.waitedMs < SETTLE_NOTE_MS) return;\n const waitedMs = Math.round(r.waitedMs);\n settleWaits.push({\n step: stepIdx,\n action: step.action,\n heldMs,\n waitedMs,\n reason: r.reason,\n });\n console.error(\n `captureTakeCDP: step ${stepIdx} (${step.action}) held ${heldMs}ms, then waited ${waitedMs}ms more for the page to settle (${r.reason})`,\n );\n };\n if (step.action === \"wait\") {\n await sleep(step.ms);\n continue;\n }\n\n if (step.action === \"navigate\") {\n // Late-bind the destination FIRST — reading a link's href is the whole\n // reason this step can reach a page the plan's author could not name\n // (a deploy's generated domain, a permalink the run just created).\n const spec = step.hrefFrom;\n let href: string | null = null;\n if (spec) {\n const target = spec.text ?? spec.selector;\n if (!target) {\n skip(\"navigate\", undefined, \"hrefFrom has neither `selector` nor `text`\");\n continue;\n }\n href = spec.selector\n ? await evalString(cdp, hrefSelectorJs(spec.selector))\n : await evalString(cdp, hrefByTextJs(spec.text!));\n if (!href) {\n skip(\"navigate\", target, \"no link with an href found\");\n continue;\n }\n }\n const current = (await evalString(cdp, \"location.href\")) ?? plan.url;\n const dest = resolveNavigateUrl({ current, url: step.url, href, query: step.query });\n if (!dest) {\n skip(\"navigate\", step.url ?? href ?? current, \"destination is not a resolvable URL\");\n continue;\n }\n if (!originAllowed(dest)) {\n skip(\"navigate\", dest, \"destination is outside OPEN_TAKE_ALLOWED_ORIGINS\");\n continue;\n }\n // Same tab ⇒ same page target ⇒ the screencast never breaks. The\n // activity probe reinstalls itself on the new document (it is an\n // addScriptToEvaluateOnNewDocument), so the hold below can still tell\n // \"finished\" from \"still working\".\n const midNavError = await navigate(cdp, dest);\n if (midNavError) {\n // The failed navigation already replaced the app with Chrome's error\n // page — filming THAT for the remaining beats helps nobody. Going\n // back re-loads the app (SPA state is lost, and steps that depended\n // on it will skip in turn, each with its own reason), which is still\n // strictly more footage than an error page.\n skip(\"navigate\", dest, `destination did not answer (${midNavError})`);\n await navigate(cdp, current);\n await hold(1200);\n continue;\n }\n await awaitFonts(cdp);\n // Then the ordinary settle. A navigate with no hold cuts to a\n // half-painted screen — this is the beat where the new page arrives,\n // even though it emits no event.\n await hold(1200);\n continue;\n }\n\n if (step.action === \"type\") {\n const label = step.text ?? step.selector;\n let tMs = Date.now() - t0;\n const focusRaw = step.text\n ? await evalAny(cdp, focusFieldByTextJs(step.text))\n : step.selector\n ? await evalAny(cdp, focusSelectorJs(step.selector))\n : null;\n const box = focusRaw ? findBox(focusRaw as Record<string, unknown>) : null;\n if (!box) {\n skip(\"type\", label, \"target not found\");\n await hold(600);\n continue;\n }\n // Did focus LAND? Input.insertText types into the current selection —\n // when the in-page focus();click();focus() bounces off (a\n // contenteditable that only arms on a real click's coordinates:\n // measured, activeElement stayed BODY, the string went nowhere, and\n // the beat logged as a success with changeCoverage 0), recover the\n // way a user would: one trusted press/release at the field's centre,\n // then ask again. Still unfocused after that → the beat is a lie the\n // video would tell — skip it and let the post-shoot gate name it.\n let focused = (focusRaw as Record<string, unknown>).f === 1;\n // A covered centre is not recovered: the press would land on whatever\n // covers the field as a REAL click — state mutated on camera — and\n // the beat would skip anyway. Name it and move on.\n if (!focused && (focusRaw as Record<string, unknown>).hit !== 1) {\n skip(\n \"type\",\n label,\n \"focus never reached the target — its centre is covered, so no click could arm it\",\n );\n await hold(600);\n continue;\n }\n if (!focused) {\n const pt = center(box);\n pumpPaused = true;\n await sleep(160);\n tMs = Date.now() - t0; // the press, not the eval, is the beat (as click)\n mouse(cdp, \"mouseMoved\", pt.x, pt.y, 0).catch(() => {});\n mouse(cdp, \"mousePressed\", pt.x, pt.y, 1).catch(() => {});\n await sleep(60);\n mouse(cdp, \"mouseReleased\", pt.x, pt.y, 0).catch(() => {});\n await sleep(120);\n pumpPaused = false;\n // the app may arm the editor in a state update — a short bounded\n // poll, not one fixed probe, so a slow arm (loaded CI box) is not a\n // false skip; the failing path costs at most ~750ms extra\n for (let poll = 0; poll < 3 && !focused; poll++) {\n await sleep(250);\n focused =\n (await evalString(\n cdp,\n verifyFocusJs({ text: step.text, selector: step.selector }),\n )) === \"1\";\n }\n }\n if (!focused) {\n skip(\"type\", label, \"focus never reached the target — typing would go nowhere\");\n await hold(600);\n continue;\n }\n // Unattended runs must never film a credential being typed — the plan\n // is agent-written and the mp4 is the one artifact nobody reviews.\n // Focus is verified on the field by now, so ask the page what kind of\n // field it actually is.\n if (\n process.env.OPEN_TAKE_CI &&\n (await evalString(cdp, credentialFieldProbeJs())) === \"secret\"\n ) {\n skip(\"type\", label, \"refusing to type into a credential field (OPEN_TAKE_CI)\");\n await hold(600);\n continue;\n }\n // Replace-not-append: select the field's existing value in-page so the\n // first inserted character replaces it (dispatched \"Meta+a\" key events\n // never run Chrome's editing commands — see selectAllInFocusedJs).\n if (step.clear) await evalAny(cdp, selectAllInFocusedJs());\n // A literal zero requests one real paste-like input event. Otherwise,\n // type progressively so the recording shows the text appear; paced by\n // us (insertText fires `input` events React/inputs honour).\n const chars = [...step.value];\n // ~1.1s per beat, clamped 28–90ms/char. The cap used to be 60ms, which\n // made SHORT strings the FASTEST typing in the video (inverted feel);\n // 90 lets a short hero string read deliberate while long strings keep\n // their genre-normal pace. Mostly-CJK strings slow ~1.4× (every glyph\n // is a word — the viewer reads, not skims). perCharMs overrides.\n const cjk = chars.filter((c) =>\n /[\\u2E80-\\u9FFF\\uAC00-\\uD7AF\\uF900-\\uFAFF\\uFF66-\\uFF9F]/.test(c),\n ).length;\n const auto =\n Math.min(90, Math.max(28, Math.round(1100 / Math.max(1, chars.length)))) *\n (cjk * 2 > chars.length ? 1.4 : 1);\n if (step.perCharMs === 0) {\n await cdp.send(\"Input.insertText\", { text: step.value });\n } else {\n const perChar = Math.round(step.perCharMs ?? auto);\n for (const ch of chars) {\n const painted = screencast.frames.length,\n sentAt = Date.now();\n await cdp.send(\"Input.insertText\", { text: ch });\n // One character per painted frame. A fixed sleep after insertText let a\n // slow re-render batch several characters into one paint and then stall:\n // the recording showed 17–350 ms between visible characters for a 45 ms\n // budget, i.e. typing that stutters. Wait for the page's own swap first,\n // bounded so a surface that stops painting cannot hang the take, then\n // spend whatever is left of the per-character budget.\n await waitUntil(() => screencast.frames.length > painted, Math.max(perChar, 250));\n const rest = perChar - (Date.now() - sentAt);\n if (rest > 0) await sleep(rest);\n }\n }\n events.push({\n kind: \"type\",\n ...center(box),\n box,\n tMs,\n sel: label,\n note: step.note,\n ...(step.caption ? { caption: step.caption } : {}),\n text: step.value,\n // measured from tMs, not from the first keystroke: on the recovery\n // path the beat starts at the assist press, and the frame-diff\n // window + the compositor's dwell must span click-through-typing —\n // a typing-only duration would leave the recovery's ~700ms outside\n // the beat it belongs to\n durationMs: Date.now() - t0 - tMs,\n ...(step.zoom ? { zoom: step.zoom } : {}),\n });\n await hold(900);\n continue;\n }\n\n if (step.action === \"drag\") {\n // A freehand `path` carries its own endpoints — fall back to them so a\n // path-only drag (no addressable element) isn't dropped.\n const pathPts: Pt[] = (step.path ?? []).map((p) => ({\n x: Math.round(p.x),\n y: Math.round(p.y),\n }));\n const from =\n (await resolvePoint({ point: step.from, selector: step.selector, text: step.text })) ??\n pathPts[0] ??\n null;\n const to =\n (await resolvePoint({ point: step.to, selector: step.toSelector, text: step.toText })) ??\n pathPts[pathPts.length - 1] ??\n null;\n const label = step.note ?? step.text ?? step.selector;\n if (!from || !to) {\n skip(\"drag\", label, \"endpoint not found\");\n await hold(600);\n continue;\n }\n const path: Pt[] = pathPts.length ? pathPts : [from, to];\n const target = step.durationMs ?? 1200;\n // Stroke pacing baked into the ink. \"smooth\" (default) accelerates in /\n // decelerates out (a natural hand-draw); \"linear\" is constant speed. The\n // compositor cursor replays the SAME curve (it's recorded on the event)\n // so it stays locked to the ink. Time steps stay uniform; the EASING is\n // applied to the along-path position, so the pen moves slow-fast-slow.\n const dragEase = opts.dragEasing ?? \"smooth\";\n const easeParam = dragEase === \"smooth\" ? smoother : (u: number) => u;\n // ~16ms steps → ~60 distinct frames/sec captured (one redraw per move);\n // this is what keeps the ink from lagging the cursor (spike VERDICT).\n const n = Math.max(12, Math.round(target / 16));\n const tMs = Date.now() - t0;\n // Pause the raster pump for the held-button stroke (a stalled\n // captureScreenshot would block the drag's mouse events). Drain any\n // in-flight (button-up) screenshot first.\n pumpPaused = true;\n await sleep(160);\n const tDrag = Date.now();\n // All pointer events are fire-and-forget (see the move loop) — a\n // held-button dispatch withholds its ack ~5s in headless, so awaiting\n // press/release/moves would stall the stroke. Sends stay ordered on the\n // socket, and Chrome processes them promptly (only the ack is delayed).\n mouse(cdp, \"mouseMoved\", path[0]!.x, path[0]!.y, 0).catch(() => {});\n mouse(cdp, \"mousePressed\", path[0]!.x, path[0]!.y, 1).catch(() => {});\n for (let k = 1; k <= n; k++) {\n // Eased along-path position over UNIFORM time steps → the pen draws\n // slow-fast-slow (smooth) or constant (linear). cursorPos replays the\n // same `easeParam`, so cursor and ink stay locked (math.ts).\n const p = sampleAlong(path, easeParam(k / n));\n // FIRE-AND-FORGET the move (don't await its ack). A held-button\n // dispatchMouseEvent that paints nothing withholds its response ~5s in\n // headless (waiting for a frame commit) — awaiting each would stall the\n // whole stroke. Chrome still processes the moves in send order; we pace\n // the stroke by wall-clock below.\n mouse(cdp, \"mouseMoved\", p.x, p.y, 1).catch(() => {});\n // pace by absolute wall-clock so dispatch latency doesn't stretch the\n // stroke past its requested duration (drag stays on its editorial beat).\n const due = tDrag + (target * k) / n;\n const slack = due - Date.now();\n if (slack > 0) await sleep(slack);\n }\n const last = path[path.length - 1]!;\n mouse(cdp, \"mouseReleased\", last.x, last.y, 0).catch(() => {}); // no buttons held after release\n // durationMs is the STROKE window only (loop end ≈ target) — measured\n // before the flush/settle sleeps so the compositor cursor traces exactly\n // the ink's draw window and stays locked to it (not the longer wall time).\n const drawnMs = Date.now() - tDrag;\n await sleep(120); // let the release + last moves flush before resuming\n pumpPaused = false; // button released — safe to resume forced rasters\n events.push({\n kind: \"drag\",\n x: from.x,\n y: from.y,\n to,\n path,\n tMs,\n sel: label,\n note: step.note,\n ...(step.caption ? { caption: step.caption } : {}),\n durationMs: drawnMs,\n ease: dragEase,\n ...(step.zoom ? { zoom: step.zoom } : {}),\n });\n await hold(1100);\n continue;\n }\n\n if (step.action === \"dropFiles\") {\n // Synthesize an OS-level file drag-and-drop: CDP Input.dispatchDragEvent\n // carries REAL file paths, so the page's dragenter/dragover state fires\n // on the way in and the drop delivers actual Files (dataTransfer.files).\n // The DragData must ride EVERY dispatch (enter, each over, drop), not\n // just the drop (spiked: baseline {items:[], files, mask:1} works in\n // --headless=new with no focus requirement).\n const label = step.note ?? step.paths.map((p) => basename(p)).join(\", \");\n if (!step.paths.length) {\n skip(\"dropFiles\", label, \"no files given (empty paths)\");\n await hold(600);\n continue;\n }\n const absPaths = step.paths.map((p) => resolve(p));\n const missing = absPaths.filter((p) => !existsSync(p));\n if (missing.length) {\n skip(\"dropFiles\", label, `file not found: ${missing.join(\", \")}`);\n await hold(600);\n continue;\n }\n const files = absPaths.map((p) => {\n const st = statSync(p);\n return { name: basename(p), size: st.size };\n });\n // Drop target: locator when given (a FAILED lookup skips — dropping real\n // files \"somewhere in the middle\" would fabricate the beat, and Chrome's\n // default drop action could even navigate the tab to the file). The\n // viewport-centre default applies only when the plan names NO target.\n let to: Pt;\n if (step.to || step.toSelector || step.toText) {\n const found = await resolvePoint({\n point: step.to,\n selector: step.toSelector,\n text: step.toText,\n });\n if (!found) {\n skip(\"dropFiles\", label, \"drop target not found\");\n await hold(600);\n continue;\n }\n to = found;\n } else {\n to = { x: Math.round(inner[0] / 2), y: Math.round(inner[1] / 2) };\n }\n // default entry: swing in from the top-right edge, like a file dragged\n // in from the desktop; deterministic so re-makes reproduce the take.\n const from: Pt = step.from\n ? { x: Math.round(step.from.x), y: Math.round(step.from.y) }\n : { x: inner[0] - 28, y: Math.round(inner[1] * 0.18) };\n const pathPts: Pt[] = (step.path ?? []).map((p) => ({\n x: Math.round(p.x),\n y: Math.round(p.y),\n }));\n const path: Pt[] = pathPts.length ? pathPts : [from, to];\n const target = step.durationMs ?? 1400;\n const dragEase = opts.dragEasing ?? \"smooth\";\n const easeParam = dragEase === \"smooth\" ? smoother : (u: number) => u;\n const data = { items: [], files: absPaths, dragOperationsMask: 1 };\n const dragEvt = (type: \"dragEnter\" | \"dragOver\" | \"drop\", p: Pt) =>\n cdp.send(\"Input.dispatchDragEvent\", {\n type,\n x: Math.round(p.x),\n y: Math.round(p.y),\n data,\n });\n const n = Math.max(12, Math.round(target / 16));\n const tMs = Date.now() - t0;\n // Pause the raster pump for the carry (mirroring drag): a mid-drag\n // captureScreenshot could stall the CDP session; the page's dragover\n // reaction (dropzone morph) self-rasters, so nothing is lost.\n pumpPaused = true;\n await sleep(160);\n const tCarry = Date.now();\n const last = path[path.length - 1]!;\n let carriedMs: number;\n try {\n // dragEnter and the final drop are load-bearing (the page's drag\n // state, then the actual file delivery) — a rejection there means the\n // beat did NOT happen, so it must SKIP, not fabricate a success.\n // The mid-march dragOvers stay fire-and-forget: they only pace the\n // carry, and awaiting each ack would stall the stroke (see drag).\n await dragEvt(\"dragEnter\", path[0]!);\n for (let k = 1; k <= n; k++) {\n const p = sampleAlong(path, easeParam(k / n));\n dragEvt(\"dragOver\", p).catch(() => {});\n const due = tCarry + (target * k) / n;\n const slack = due - Date.now();\n if (slack > 0) await sleep(slack);\n }\n await dragEvt(\"dragOver\", last).catch(() => {});\n await dragEvt(\"drop\", last);\n carriedMs = Date.now() - tCarry;\n } catch (e) {\n pumpPaused = false;\n skip(\"dropFiles\", label, `drag dispatch failed: ${(e as Error).message}`);\n await hold(600);\n continue;\n }\n await sleep(120);\n pumpPaused = false;\n events.push({\n kind: \"dropFiles\",\n x: path[0]!.x,\n y: path[0]!.y,\n to: last,\n path,\n tMs,\n sel: label,\n note: step.note,\n ...(step.caption ? { caption: step.caption } : {}),\n durationMs: carriedMs,\n ease: dragEase,\n files,\n ...(step.zoom ? { zoom: step.zoom } : {}),\n });\n // dropzones usually kick off real work (parse / upload UI) — default a\n // longer settle than a click so the payoff is on screen.\n await hold(1600);\n continue;\n }\n\n if (step.action === \"scroll\") {\n // Resolve the scroll distance: to an element's centre, or a fixed dy\n // (default ~0.8 viewport down). The cursor holds; the content pans.\n const tMs = Date.now() - t0;\n let dy: number;\n if (step.toSelector || step.toText) {\n const r = (await evalAny(\n cdp,\n step.toSelector\n ? scrollDeltaSelectorJs(step.toSelector)\n : scrollDeltaByTextJs(step.toText!),\n )) as { dy?: number } | null;\n if (r && typeof r.dy === \"number\") {\n dy = r.dy;\n } else {\n skip(\"scroll\", step.toText ?? step.toSelector, \"target not found\");\n await hold(600);\n continue;\n }\n } else {\n dy = step.dy ?? Math.round(vh * 0.8);\n }\n const targetMs = step.durationMs ?? 1000;\n const cx = Math.round(inner[0] / 2),\n cy = Math.round(inner[1] / 2);\n // Programmatic window.scrollTo, eased and paced from node. The raster\n // pump (see above) forces the re-raster that makes the screencast\n // actually capture the motion — a bare scrollTo would otherwise freeze\n // the recording on stale tiles. No trusted wheel: it hangs forever in\n // headless if dispatched after an Escape keypress.\n const start = Number(await evalAny(cdp, \"window.scrollY\")) || 0;\n const n = Math.max(12, Math.round(targetMs / 16));\n const tScroll = Date.now();\n for (let k = 1; k <= n; k++) {\n const u = k / n;\n const want = Math.round(dy * (u * u * u * (u * (u * 6 - 15) + 10))); // eased cumulative\n await cdp.send(\"Runtime.evaluate\", { expression: `window.scrollTo(0, ${start + want})` });\n const due = tScroll + (targetMs * k) / n;\n const slack = due - Date.now();\n if (slack > 0) await sleep(slack);\n }\n events.push({\n kind: \"scroll\",\n x: cx,\n y: cy,\n tMs,\n dy,\n durationMs: Date.now() - tScroll,\n note: step.note,\n ...(step.caption ? { caption: step.caption } : {}),\n });\n await hold(800);\n continue;\n }\n\n if (step.action === \"hover\") {\n // Move the real pointer onto the element (triggers :hover / mouseenter)\n // and dwell so the tooltip/menu is visible. No click. The synthetic\n // cursor travels + parks at the same point (compositor).\n const label = step.text ?? step.selector;\n const tMs = Date.now() - t0;\n const box = step.text\n ? await evalBox(cdp, boxByTextJs(step.text))\n : step.selector\n ? await evalBox(cdp, boxSelectorJs(step.selector))\n : null;\n if (!box) {\n skip(\"hover\", label, \"target not found\");\n await hold(600);\n continue;\n }\n const c = center(box);\n const dwell = step.durationMs ?? 1200;\n await mouse(cdp, \"mouseMoved\", c.x, c.y, 0);\n events.push({\n kind: \"hover\",\n ...c,\n box,\n tMs,\n sel: label,\n note: step.note,\n ...(step.caption ? { caption: step.caption } : {}),\n durationMs: dwell,\n ...(step.zoom ? { zoom: step.zoom } : {}),\n });\n await sleep(dwell);\n // A hover DWELLS on its target and the cursor is parked for all of it, so\n // this settle is the ONLY room the next glide has. 300ms could not fit\n // one (travelMaxMs is 850 at the shipped pace) and the cursor darted.\n await hold(900);\n continue;\n }\n\n if (step.action === \"select\") {\n // Native <select>: set value + dispatch input/change (see\n // selectOptionJs — clicking one hangs the capture). Visually this is\n // a click beat: the cursor travels to the control and its value\n // changes under the pointer, which is exactly what a viewer sees a\n // user do, so it enters the log as `click`.\n const label = step.text ?? step.selector;\n const tMs = Date.now() - t0;\n const r = await cdp.send<{ result?: { value?: unknown } }>(\"Runtime.evaluate\", {\n expression: selectOptionJs({ selector: step.selector, text: step.text }, step.value),\n returnByValue: true,\n awaitPromise: true,\n });\n const raw = r.result?.value;\n const str = typeof raw === \"string\" ? raw : raw == null ? \"NOTFOUND\" : JSON.stringify(raw);\n if (str === \"NOTFOUND\" || str === \"NOTASELECT\" || str === \"NOOPTION\") {\n skip(\n \"select\",\n label,\n str === \"NOTASELECT\"\n ? \"target is not a <select> (use click for custom dropdowns)\"\n : str === \"NOOPTION\"\n ? `no option matching ${JSON.stringify(step.value)}`\n : \"target not found\",\n );\n await hold(600);\n continue;\n }\n const box = findBox(evalValue(str));\n if (!box) {\n skip(\"select\", label, \"target not found\");\n await hold(600);\n continue;\n }\n events.push({\n kind: \"click\",\n ...center(box),\n box,\n tMs,\n sel: label,\n note: step.note,\n ...(step.caption ? { caption: step.caption } : {}),\n ...(step.zoom ? { zoom: step.zoom } : {}),\n });\n await hold(1300);\n continue;\n }\n\n if (step.action === \"look\") {\n // CAMERA-only: resolve the target's bbox so the compositor can frame\n // it, then just WAIT out the hold. Nothing is dispatched to the page\n // and the synthetic cursor stays parked (compositor: no travel leg,\n // no ripple) — cursor movement promises an action, and a look makes\n // none. Zoom defaults to \"always\": framing IS this beat's content.\n // (Unrelated to the A/B `look=` knob, which names a backdrop preset.)\n const label = step.text ?? step.selector;\n const tMs = Date.now() - t0;\n const box = step.text\n ? await evalBox(cdp, boxByTextJs(step.text))\n : step.selector\n ? await evalBox(cdp, boxSelectorJs(step.selector))\n : null;\n if (!box) {\n skip(\"look\", label, step.text || step.selector ? \"target not found\" : \"no target given\");\n await hold(600);\n continue;\n }\n const dwell = step.durationMs ?? 1800;\n events.push({\n kind: \"look\",\n ...center(box),\n box,\n tMs,\n sel: label,\n note: step.note,\n ...(step.caption ? { caption: step.caption } : {}),\n durationMs: dwell,\n zoom: step.zoom ?? \"always\",\n });\n await sleep(dwell);\n // The cursor is parked through the hold (like hover/press), so this\n // settle is the entire window the next travel has to glide in.\n await hold(900);\n continue;\n }\n\n if (step.action === \"press\") {\n // Keyboard-driven: dispatch the chord to whatever has focus, then hold\n // while the effect plays out. The cursor does NOT move. If a reveal\n // element is named, locate its bbox AFTER the press so the zoom frames\n // what appeared.\n const tMs = Date.now() - t0;\n try {\n await pressChord(cdp, step.keys);\n } catch (e) {\n console.error(\n `captureTakeCDP: press failed for ${JSON.stringify(step.keys)}: ${(e as Error).message}`,\n );\n }\n const dwell = step.durationMs ?? 1000;\n let box: Box | null = null;\n if (step.selector || step.text) {\n await sleep(250); // let the revealed UI mount before measuring\n box = step.text\n ? await evalBox(cdp, boxByTextJs(step.text))\n : await evalBox(cdp, boxSelectorJs(step.selector!));\n }\n const anchor = box\n ? center(box)\n : { x: Math.round(inner[0] / 2), y: Math.round(inner[1] / 2) };\n events.push({\n kind: \"press\",\n ...anchor,\n ...(box ? { box } : {}),\n tMs,\n keys: step.keys,\n sel: step.text ?? step.selector,\n note: step.note,\n ...(step.caption ? { caption: step.caption } : {}),\n durationMs: dwell,\n ...(step.zoom ? { zoom: step.zoom } : {}),\n });\n await sleep(dwell);\n // Same as hover: the cursor is parked through the reveal, so this settle is\n // the entire window the next travel has to glide in. See hold() above.\n await hold(900);\n continue;\n }\n\n // click: one eval resolves the element and decides delivery. When the\n // centre is hittable the eval returns `cx`/`cy` WITHOUT clicking, and\n // the click is delivered here as trusted CDP input — press + release,\n // the full pointerdown→click pipeline. A programmatic m.click() fires a\n // lone `click` event, and pointer-listening controls (Radix dropdown\n // triggers open on pointerdown) treat that as silence: measured on a\n // real shoot, the step \"succeeded\", nothing opened, and 8 of 10 beats\n // died downstream. The eval keeps m.click() as its own fallback for\n // targets a coordinate cannot reach (zero-size / covered /\n // pointer-events:none), so `cx` missing means \"already clicked in-page\".\n const label = step.text ?? step.selector;\n let tMs = Date.now() - t0; // js-fallback mode: the eval clicks ~now\n // the locators refuse to .click() a <select> (it hangs the capture) and\n // say so with this sentinel — name the real fix instead of \"not found\"\n const clickRaw = step.text\n ? await evalString(cdp, clickByTextJs(step.text))\n : step.selector\n ? await evalString(cdp, clickBySelectorJs(step.selector))\n : null;\n if (clickRaw === \"SELECTINERT\") {\n skip(\n \"click\",\n label,\n \"clicking a native <select> does nothing headless (inert, no popup) — use the `select` action\",\n );\n await hold(600);\n continue;\n }\n const parsed = clickRaw ? (evalValue(clickRaw) as Record<string, unknown> | null) : null;\n const box = parsed ? findBox(parsed) : null;\n const pt =\n parsed && typeof parsed.cx === \"number\" && typeof parsed.cy === \"number\"\n ? { x: parsed.cx, y: parsed.cy }\n : null;\n if (box && pt) {\n // Trusted delivery, mirroring the drag block's proven pattern: pause\n // the forced-raster pump (a stalled captureScreenshot would block the\n // held-button dispatch), drain any in-flight one, then fire-and-forget\n // — a held-button dispatchMouseEvent withholds its ack ~5s in headless,\n // so awaiting press/release would stall the beat. Sends stay ordered\n // on the socket; Chrome processes them promptly.\n pumpPaused = true;\n await sleep(160);\n tMs = Date.now() - t0; // the press, not the eval, is the beat\n mouse(cdp, \"mouseMoved\", pt.x, pt.y, 0).catch(() => {});\n mouse(cdp, \"mousePressed\", pt.x, pt.y, 1).catch(() => {});\n await sleep(60); // a human-scale press→release gap\n mouse(cdp, \"mouseReleased\", pt.x, pt.y, 0).catch(() => {});\n await sleep(120); // let the release flush before resuming rasters\n pumpPaused = false;\n }\n if (box) {\n events.push({\n kind: \"click\",\n ...(pt ?? center(box)),\n box,\n tMs,\n sel: label,\n note: step.note,\n ...(step.caption ? { caption: step.caption } : {}),\n ...(step.zoom ? { zoom: step.zoom } : {}),\n });\n } else {\n skip(\"click\", label, \"target not found\");\n }\n await hold(1300);\n }\n\n const tEndMs = Date.now() - t0;\n await sleep(400);\n pumping = false;\n await pump;\n await screencast.stop();\n await encodeFrames(screencast.frames, tEndMs + 400, out, fps);\n\n const probe = await ffprobe(out);\n // Space-integrity check: the whole pipeline maps coordinates viewport →\n // stage 1:1, which is only true while the encoded frame KEEPS the\n // viewport's aspect (uniform scale cancels out downstream; a non-uniform\n // one skews every cursor/zoom point). A window resize mid-capture — after\n // the re-fit above — is the one thing that breaks it: the screencast then\n // uniform-fits a changed surface into the stale cap and the aspects drift\n // apart. Say so loudly; the take will render with visibly misplaced\n // cursors and re-running is the fix.\n if (probe.width && probe.height) {\n const videoAspect = probe.width / probe.height;\n const viewAspect = inner[0] / inner[1];\n if (Math.abs(videoAspect / viewAspect - 1) > 0.01) {\n process.stderr.write(\n `⚠ the browser window resized MID-capture: viewport ${inner[0]}×${inner[1]} but the ` +\n `recording is ${probe.width}×${probe.height} — cursor/zoom coordinates in this take ` +\n `are skewed. Re-run; in a cloud/Xvfb environment give the screen a fixed size at ` +\n `least the requested viewport.\\n`,\n );\n }\n }\n return {\n video: {\n width: probe.width ?? inner[0],\n height: probe.height ?? inner[1],\n fps: probe.fps,\n durationS: probe.durationS,\n },\n viewport: { w: inner[0], h: inner[1] },\n start: plan.startCursor ?? { x: Math.round(inner[0] * 0.25), y: Math.round(inner[1] * 0.9) },\n events,\n tEndMs,\n captureCadence: {\n ...captureCadence(screencast.frames),\n rasterRefresh: opts.rasterRefresh ?? \"idle\",\n },\n // Both of these were collected all along but never reached the caller on\n // this path, so the end-of-run summary and the strict exit saw an empty list and\n // a dropped beat lived only in an early stderr line — exactly what the\n // CaptureLog.skipped contract says must not happen.\n ...(skipped.length ? { skipped } : {}),\n ...(precheck.length ? { precheck } : {}),\n ...(settleWaits.length ? { settleWaits } : {}),\n ...(paintedFrac >= PAINT_BLIND_FRAC\n ? { paintedFrac: Math.round(paintedFrac * 100) / 100 }\n : {}),\n };\n } finally {\n await browser?.close();\n rmSync(frameDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });\n }\n}\n\n// Navigate and wait for load (bounded) so the first frame isn't a blank page.\n/** CI containment. A plan is agent-written, and the agent reads the very page\n * it films — a hostile string ON that page can talk its way into a plan step.\n * When OPEN_TAKE_ALLOWED_ORIGINS is set (comma-separated origins; `open-take\n * ci` sets it to the app's own origin), any navigation outside the list is a\n * skipped step, never a request. Unset (the interactive default), everything\n * is allowed — a human is watching. */\nfunction originAllowed(url: string): boolean {\n const raw = process.env.OPEN_TAKE_ALLOWED_ORIGINS;\n if (!raw) return true;\n try {\n const origin = new URL(url).origin;\n return raw.split(\",\").some((entry) => entry.trim() === origin);\n } catch {\n return false;\n }\n}\n\n/** Runs in-page AFTER focus landed on the type target: names the field\n * \"secret\" when it is a password input or smells like a credential field.\n * Only consulted under OPEN_TAKE_CI — locally the human sees what is typed. */\nfunction credentialFieldProbeJs(): string {\n return `(() => {\n const el = document.activeElement;\n if (!el) return \"ok\";\n const type = (el.getAttribute(\"type\") || \"\").toLowerCase();\n const smell = [el.getAttribute(\"name\"), el.getAttribute(\"id\"), el.getAttribute(\"autocomplete\"), el.getAttribute(\"placeholder\")]\n .filter(Boolean).join(\" \").toLowerCase();\n return type === \"password\" || /passw|secret|api[-_]?key|access[-_]?token/.test(smell) ? \"secret\" : \"ok\";\n })()`;\n}\n\n/** Returns Chrome's `errorText` (e.g. \"net::ERR_CONNECTION_REFUSED\") when the\n * navigation never reached a server — the tab is then showing Chrome's own\n * error page, which fires load events like any document and would otherwise\n * get filmed as if it were the app. HTTP error PAGES (404/500) carry no\n * errorText: the app answered, and what it said is what an honest take shows. */\nasync function navigate(cdp: CDP, url: string): Promise<string | undefined> {\n const loaded = new Promise<void>((res) => {\n cdp.on(\"Page.loadEventFired\", () => res());\n setTimeout(res, 8000); // don't hang on a never-firing load\n });\n const nav = await cdp.send<{ errorText?: string }>(\"Page.navigate\", { url });\n await loaded;\n return nav.errorText || undefined;\n}\n"],"mappings":";;;;;;;;AA4BA,MAAMA,UAAQ,CAACC,OAAe,IAAI,QAAQ,CAAC,MAAM,WAAW,GAAG,GAAG;AAClE,MAAM,UAAU,cAAc,OAAO,KAAK,IAAI;AAG9C,MAAM,eAAe,KAAK,SAAS,EAAE,cAAc,WAAW;AAC9D,MAAM,eAAe,KAAK,SAAS,EAAE,cAAc,oBAAoB;AAWvE,SAAgB,cAAcC,UAAkC;CAC9D,MAAMC,aAAuB,CAAE;AAC/B,KAAI,SAAU,YAAW,KAAK,SAAS;AACvC,KAAI,QAAQ,IAAI,iBAAkB,YAAW,KAAK,QAAQ,IAAI,iBAAiB;AAI/E,KAAI,WAAW,aAAa,CAC1B,KAAI;EACF,MAAM,MAAM,sBAAsB,KAAK,MAAM,aAAa,cAAc,OAAO,CAAC,CAAC,QAAQ;AACzF,MAAI,IAAK,YAAW,KAAK,IAAI;CAC9B,QAAO,CAEP;CAIH,MAAM,aAAa,KAAK,SAAS,EAAE,kBAAkB,WAAW;AAChE,KAAI,WAAW,WAAW,CACxB,MAAK,MAAM,KAAK,YAAY,WAAW,C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