@open-take/runtime 0.2.9 → 0.3.0

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.
@@ -1 +1 @@
1
- {"version":3,"file":"cdp-capture-BA3qT1Tg.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","dir: string","t0: number","opts: { maxWidth: number; maxHeight: number; quality?: number }","p: { data: string; sessionId: number }","frames: Frame[]","endMs: number","outPath: string","fps: number","ffmpegBin?: string","lines: string[]","sleep","ms: number","o: unknown","s: unknown","raw: string","top: unknown","text: string","selector: string","pts: { x: number; y: number }[]","u: number","seg: number[]","path: string","plan: TakePlan","opts: CaptureOpts","url: string","opts: InspectOpts","expr: string","elements: InspectElement[]","t: NavigateTarget","raw: string","base?: URL","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","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/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 readFileSync,\n readdirSync,\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 (don't buffer ~1500 JPEGs in RAM) with its arrival offset\n// from t0, so the encoder can reconstruct true wall-clock timing.\nexport type Frame = { file: string; offMs: number };\n\nexport class Screencast {\n private cdp: CDP;\n private dir: string;\n private t0 = 0;\n private n = 0;\n readonly frames: Frame[] = [];\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.cdp.on(\"Page.screencastFrame\", (p: { data: string; sessionId: number }) => {\n const off = Date.now() - this.t0;\n const file = join(this.dir, `f-${String(this.n++).padStart(5, \"0\")}.jpg`);\n writeFileSync(file, Buffer.from(p.data, \"base64\"));\n this.frames.push({ file, offMs: off });\n // ack so Chrome keeps sending (un-acked frames stall the stream)\n this.cdp.send(\"Page.screencastFrameAck\", { sessionId: p.sessionId }).catch(() => {});\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// --- 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 const bin = ffmpegBin ?? (await resolveFfmpeg());\n const dir = frames[0]!.file.slice(0, frames[0]!.file.lastIndexOf(\"/\"));\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 + 33),\n ];\n for (let i = 0; i < frames.length; i++) {\n const dur = Math.max(0.001, (bounds[i + 1]! - bounds[i]!) / 1000);\n lines.push(`file '${frames[i]!.file}'`, `duration ${dur.toFixed(4)}`);\n }\n // concat demuxer ignores the final entry's duration unless the file repeats.\n lines.push(`file '${frames[frames.length - 1]!.file}'`);\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","// 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.\nconst 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// Find a clickable by accessible name (aria-label or text), record its\n// rect (ground-truth bbox), and click it — all in one page eval so the\n// bbox and the action refer to the same element. Robust where CSS hooks\n// are unstable.\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('button,a,[role=button],[role=link],[role=menuitem],input[type=submit],input[type=button]'));` +\n NAME_JS +\n `var m=pick(els,t);` +\n `if(!m)return 'NOTFOUND';` +\n // m.click() fires programmatically and never scrolls; below-fold targets\n // would advance state off-screen. Scroll into view ONLY when out of frame\n // so in-view beats keep their framing; re-read the rect post-scroll so the\n // compositor gets a viewport-relative (in-frame) bbox.\n `var r=m.getBoundingClientRect();` +\n `if(r.top<0||r.bottom>window.innerHeight){m.scrollIntoView({block:'center'});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.click();return JSON.stringify(b);})()`\n );\n}\n\n// Selector twin of clickByTextJs: resolve the element's rect AND click it 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 `var r=m.getBoundingClientRect();` +\n `if(r.top<0||r.bottom>window.innerHeight){m.scrollIntoView({block:'center'});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.click();return JSON.stringify(b);})()`\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.\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('input,textarea,[contenteditable],[contenteditable=true],[role=textbox],[role=searchbox]'));` +\n NAME_JS +\n `var m=pick(els,t);` +\n `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 `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();return JSON.stringify(b);})()`\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 `var r=m.getBoundingClientRect();` +\n `if(r.top<0||r.bottom>window.innerHeight){m.scrollIntoView({block:'center'});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();return JSON.stringify(b);})()`\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('button,a,[role=button],[role=link],[role=menuitem],[aria-label],[title],img[alt],li,[draggable=true]'));` +\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('button,a,[role=button],[role=link],[role=heading],[aria-label],[title],h1,h2,h3,li,section,p'));` +\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 * Capture + encode fps. Default 60 (the polished, premium 60fps feel).\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 /** 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 await cdp.send(\"Page.navigate\", { url });\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","// 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","// 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} from \"./capture\";\nimport {\n type Browser,\n type CDP,\n Screencast,\n encodeFrames,\n fitViewport,\n launchBrowser,\n makeFrameDir,\n} from \"./cdp\";\nimport { resolveNavigateUrl } from \"./nav\";\nimport {\n DEFAULT_SETTLE_BUDGET_MS,\n PAINT_BLIND_FRAC,\n installActivityProbe,\n makeBudgetGovernor,\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 const 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 await navigate(cdp, plan.url);\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 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 // Raster pump. Page.startScreencast only emits a frame when the renderer\n // produces one, and in headless a state change that isn't driven by trusted\n // input — a CSS :hover reveal, a keyboard-opened modal, window.scrollTo —\n // updates the DOM/scroll offset but does NOT re-raster, so the screencast\n // composites STALE tiles and the recording freezes on the old frame.\n // Page.captureScreenshot forces a fresh raster; running it on a steady tick\n // keeps the screencast current for the whole capture, so every action is\n // recorded regardless of how it's driven. (quality:1 → cheap; the result is\n // discarded — only the re-raster side effect matters.)\n // captureScreenshot STALLS while a mouse button is held (mid-drag), and a\n // stalled screenshot BLOCKS the whole CDP session — Chrome won't process the\n // drag's mouseMoved events until it resolves, wedging the capture. So the\n // pump PAUSES around a drag (a drag draws real ink, so it self-rasters and\n // needs no pump). The timeout race is a second belt: it keeps a stall during\n // any other beat from wedging the final `await pump`.\n let pumping = true;\n let pumpPaused = false;\n const pump = (async () => {\n while (pumping) {\n if (!pumpPaused)\n await Promise.race([\n cdp.send(\"Page.captureScreenshot\", { format: \"jpeg\", quality: 1 }).catch(() => {}),\n sleep(150),\n ]);\n await sleep(45);\n }\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 --strict 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 // 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 await navigate(cdp, dest);\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 const tMs = Date.now() - t0;\n const box = step.text\n ? await evalBox(cdp, focusFieldByTextJs(step.text))\n : step.selector\n ? await evalBox(cdp, focusSelectorJs(step.selector))\n : null;\n if (!box) {\n skip(\"type\", label, \"target not found\");\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 // progressive char-by-char so the recording shows text appear; paced\n // by 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 const perChar = Math.round(step.perCharMs ?? auto);\n const tType = Date.now();\n for (const ch of chars) {\n await cdp.send(\"Input.insertText\", { text: ch });\n await sleep(perChar);\n }\n events.push({\n kind: \"type\",\n ...center(box),\n box,\n tMs,\n sel: label,\n note: step.note,\n text: step.value,\n durationMs: Date.now() - tType,\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 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 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 });\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 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 === \"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 const tPress = Date.now();\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 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: timestamp, resolve bbox + programmatic click in one eval\n const label = step.text ?? step.selector;\n const tMs = Date.now() - t0;\n const box = step.text\n ? await evalBox(cdp, clickByTextJs(step.text))\n : step.selector\n ? await evalBox(cdp, clickBySelectorJs(step.selector))\n : null;\n if (box) {\n events.push({\n kind: \"click\",\n ...center(box),\n box,\n tMs,\n sel: label,\n note: step.note,\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 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 // Both of these were collected all along but never reached the caller on\n // this path, so the end-of-run summary and --strict 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 ...(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.\nasync function navigate(cdp: CDP, url: string): Promise<void> {\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 await cdp.send(\"Page.navigate\", { url });\n await loaded;\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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AAO,mBAAmB;AAE1C,SAAM,KAAK,KAAK;EACjB;EAED,MAAM,SAAS,KAAK,KAAK,GAAG;AAC5B,QAAM,MAAM,IAAI;AAChB,YAAU;AACV,QAAM;AACN,QAAM,WAAW,MAAM;AACvB,QAAM,aAAa,WAAW,QAAQ,SAAS,KAAK,KAAK,IAAI;EAE7D,MAAM,QAAQ,MAAM,QAAQ,IAAI;AAChC,SAAO;GACL,OAAO;IACL,OAAO,MAAM,SAAS,MAAM;IAC5B,QAAQ,MAAM,UAAU,MAAM;IAC9B,KAAK,MAAM;IACX,WAAW,MAAM;GAClB;GACD,UAAU;IAAE,GAAG,MAAM;IAAI,GAAG,MAAM;GAAI;GACtC,OAAO,KAAK,eAAe;IAAE,GAAG,KAAK,MAAM,MAAM,KAAK,IAAK;IAAE,GAAG,KAAK,MAAM,MAAM,KAAK,GAAI;GAAE;GAC5F;GACA;GAKA,GAAI,QAAQ,SAAS,EAAE,QAAS,IAAG,CAAE;GACrC,GAAI,YAAY,SAAS,EAAE,YAAa,IAAG,CAAE;GAC7C,GAAI,eAAe,mBACf,EAAE,aAAa,KAAK,MAAM,cAAc,IAAI,GAAG,IAAK,IACpD,CAAE;EACP;CACF,UAAS;AACR,QAAM,SAAS,OAAO;AACtB,SAAO,UAAU;GAAE,WAAW;GAAM,OAAO;GAAM,YAAY;GAAG,YAAY;EAAK,EAAC;CACnF;AACF;AAGD,eAAe,SAAS3B,KAAUqC,KAA4B;CAC5D,MAAM,SAAS,IAAI,QAAc,CAAC,QAAQ;AACxC,MAAI,GAAG,uBAAuB,MAAM,KAAK,CAAC;AAC1C,aAAW,KAAK,IAAK;CACtB;AACD,OAAM,IAAI,KAAK,iBAAiB,EAAE,IAAK,EAAC;AACxC,OAAM;AACP"}
1
+ {"version":3,"file":"cdp-capture-CWNroQPQ.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","dir: string","t0: number","opts: { maxWidth: number; maxHeight: number; quality?: number }","p: { data: string; sessionId: number }","frames: Frame[]","endMs: number","outPath: string","fps: number","ffmpegBin?: string","lines: string[]","sleep","ms: number","o: unknown","s: unknown","raw: string","top: unknown","text: string","selector: string","pts: { x: number; y: number }[]","u: number","seg: number[]","path: string","plan: TakePlan","opts: CaptureOpts","url: string","opts: InspectOpts","expr: string","elements: InspectElement[]","t: NavigateTarget","raw: string","base?: URL","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","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/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 readFileSync,\n readdirSync,\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 (don't buffer ~1500 JPEGs in RAM) with its arrival offset\n// from t0, so the encoder can reconstruct true wall-clock timing.\nexport type Frame = { file: string; offMs: number };\n\nexport class Screencast {\n private cdp: CDP;\n private dir: string;\n private t0 = 0;\n private n = 0;\n readonly frames: Frame[] = [];\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.cdp.on(\"Page.screencastFrame\", (p: { data: string; sessionId: number }) => {\n const off = Date.now() - this.t0;\n const file = join(this.dir, `f-${String(this.n++).padStart(5, \"0\")}.jpg`);\n writeFileSync(file, Buffer.from(p.data, \"base64\"));\n this.frames.push({ file, offMs: off });\n // ack so Chrome keeps sending (un-acked frames stall the stream)\n this.cdp.send(\"Page.screencastFrameAck\", { sessionId: p.sessionId }).catch(() => {});\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// --- 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 const bin = ffmpegBin ?? (await resolveFfmpeg());\n const dir = frames[0]!.file.slice(0, frames[0]!.file.lastIndexOf(\"/\"));\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 + 33),\n ];\n for (let i = 0; i < frames.length; i++) {\n const dur = Math.max(0.001, (bounds[i + 1]! - bounds[i]!) / 1000);\n lines.push(`file '${frames[i]!.file}'`, `duration ${dur.toFixed(4)}`);\n }\n // concat demuxer ignores the final entry's duration unless the file repeats.\n lines.push(`file '${frames[frames.length - 1]!.file}'`);\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","// 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.\nconst 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// Find a clickable by accessible name (aria-label or text), record its\n// rect (ground-truth bbox), and click it — all in one page eval so the\n// bbox and the action refer to the same element. Robust where CSS hooks\n// are unstable.\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('button,a,[role=button],[role=link],[role=menuitem],input[type=submit],input[type=button]'));` +\n NAME_JS +\n `var m=pick(els,t);` +\n `if(!m)return 'NOTFOUND';` +\n // m.click() fires programmatically and never scrolls; below-fold targets\n // would advance state off-screen. Scroll into view ONLY when out of frame\n // so in-view beats keep their framing; re-read the rect post-scroll so the\n // compositor gets a viewport-relative (in-frame) bbox.\n `var r=m.getBoundingClientRect();` +\n `if(r.top<0||r.bottom>window.innerHeight){m.scrollIntoView({block:'center'});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.click();return JSON.stringify(b);})()`\n );\n}\n\n// Selector twin of clickByTextJs: resolve the element's rect AND click it 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 `var r=m.getBoundingClientRect();` +\n `if(r.top<0||r.bottom>window.innerHeight){m.scrollIntoView({block:'center'});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.click();return JSON.stringify(b);})()`\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.\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('input,textarea,[contenteditable],[contenteditable=true],[role=textbox],[role=searchbox]'));` +\n NAME_JS +\n `var m=pick(els,t);` +\n `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 `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();return JSON.stringify(b);})()`\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 `var r=m.getBoundingClientRect();` +\n `if(r.top<0||r.bottom>window.innerHeight){m.scrollIntoView({block:'center'});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();return JSON.stringify(b);})()`\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('button,a,[role=button],[role=link],[role=menuitem],[aria-label],[title],img[alt],li,[draggable=true]'));` +\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('button,a,[role=button],[role=link],[role=heading],[aria-label],[title],h1,h2,h3,li,section,p'));` +\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 * Capture + encode fps. Default 60 (the polished, premium 60fps feel).\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 /** 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 await cdp.send(\"Page.navigate\", { url });\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","// 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","// 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} from \"./capture\";\nimport {\n type Browser,\n type CDP,\n Screencast,\n encodeFrames,\n fitViewport,\n launchBrowser,\n makeFrameDir,\n} from \"./cdp\";\nimport { resolveNavigateUrl } from \"./nav\";\nimport {\n DEFAULT_SETTLE_BUDGET_MS,\n PAINT_BLIND_FRAC,\n installActivityProbe,\n makeBudgetGovernor,\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 const 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 await navigate(cdp, plan.url);\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 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 // Raster pump. Page.startScreencast only emits a frame when the renderer\n // produces one, and in headless a state change that isn't driven by trusted\n // input — a CSS :hover reveal, a keyboard-opened modal, window.scrollTo —\n // updates the DOM/scroll offset but does NOT re-raster, so the screencast\n // composites STALE tiles and the recording freezes on the old frame.\n // Page.captureScreenshot forces a fresh raster; running it on a steady tick\n // keeps the screencast current for the whole capture, so every action is\n // recorded regardless of how it's driven. (quality:1 → cheap; the result is\n // discarded — only the re-raster side effect matters.)\n // captureScreenshot STALLS while a mouse button is held (mid-drag), and a\n // stalled screenshot BLOCKS the whole CDP session — Chrome won't process the\n // drag's mouseMoved events until it resolves, wedging the capture. So the\n // pump PAUSES around a drag (a drag draws real ink, so it self-rasters and\n // needs no pump). The timeout race is a second belt: it keeps a stall during\n // any other beat from wedging the final `await pump`.\n let pumping = true;\n let pumpPaused = false;\n const pump = (async () => {\n while (pumping) {\n if (!pumpPaused)\n await Promise.race([\n cdp.send(\"Page.captureScreenshot\", { format: \"jpeg\", quality: 1 }).catch(() => {}),\n sleep(150),\n ]);\n await sleep(45);\n }\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 --strict 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 await navigate(cdp, dest);\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 const tMs = Date.now() - t0;\n const box = step.text\n ? await evalBox(cdp, focusFieldByTextJs(step.text))\n : step.selector\n ? await evalBox(cdp, focusSelectorJs(step.selector))\n : null;\n if (!box) {\n skip(\"type\", label, \"target not found\");\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 // The focus JS above already parked focus on the field, so ask the\n // page what kind of 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 // progressive char-by-char so the recording shows text appear; paced\n // by 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 const perChar = Math.round(step.perCharMs ?? auto);\n const tType = Date.now();\n for (const ch of chars) {\n await cdp.send(\"Input.insertText\", { text: ch });\n await sleep(perChar);\n }\n events.push({\n kind: \"type\",\n ...center(box),\n box,\n tMs,\n sel: label,\n note: step.note,\n text: step.value,\n durationMs: Date.now() - tType,\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 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 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 });\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 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 === \"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 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: timestamp, resolve bbox + programmatic click in one eval\n const label = step.text ?? step.selector;\n const tMs = Date.now() - t0;\n const box = step.text\n ? await evalBox(cdp, clickByTextJs(step.text))\n : step.selector\n ? await evalBox(cdp, clickBySelectorJs(step.selector))\n : null;\n if (box) {\n events.push({\n kind: \"click\",\n ...center(box),\n box,\n tMs,\n sel: label,\n note: step.note,\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 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 // Both of these were collected all along but never reached the caller on\n // this path, so the end-of-run summary and --strict 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 ...(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\nasync function navigate(cdp: CDP, url: string): Promise<void> {\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 await cdp.send(\"Page.navigate\", { url });\n await loaded;\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,cAA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