@volter-ai-dev/supercode-browser-playwright 0.2.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +39 -28
- package/dist/executor.d.ts +42 -3
- package/dist/executor.mjs +397 -64
- package/dist/executor.mjs.map +4 -4
- package/dist/guard.d.ts +63 -2
- package/dist/index.d.ts +1 -1
- package/dist/index.mjs +397 -64
- package/dist/index.mjs.map +4 -4
- package/dist/script-scope.d.ts +27 -0
- package/package.json +1 -1
package/dist/index.mjs.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/executor.ts", "../src/guard.ts", "../src/protocol.ts", "../src/provider.ts", "../src/serve.ts", "../src/cli.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Supercode's `supercode/browser-operation-v1` calls over a real Playwright\n * `Page`: every locator, action and snapshot is playwright-core's own, driven\n * over CDP. No Node API is used, so the executor also runs in a browser realm\n * with a browser build of playwright-core (`@volter/almostcdp/playwright`).\n */\n\nimport { errors, type ElementHandle, type Locator, type Page } from \"playwright-core\";\nimport { BrowserSideTargets, HostElementTarget, UnidentifiedTarget, type GuardedTarget } from \"./guard.js\";\nimport {\n BROWSER_OPERATION_NAMES,\n BrowserActionRefusal,\n parseBrowserOperationCall,\n type BrowserLocator,\n type BrowserOperationCall,\n type BrowserOperationErrorCode,\n type BrowserOperationName,\n type BrowserOperationResult,\n type BrowserTarget,\n type ElementInspection,\n} from \"./protocol.js\";\n\n/** The implementation this provider reports; the pinned playwright-core. */\nexport const PLAYWRIGHT_IMPLEMENTATION = \"playwright-core 1.63.0\";\n/** The harness abandons a provider call at 12 s; a script must end before that. */\nexport const SCRIPT_TIMEOUT_CLAMP_MS = 9_000;\n/** Actionability budget for one locator action. */\nexport const ACTION_TIMEOUT_MS = 5_000;\n/** `browser.wait` accepts 30 s on the wire; the harness deadline caps what can be honoured. */\nexport const WAIT_TIMEOUT_CLAMP_MS = 9_000;\n\n/** The Playwright features `browser.status` reports. */\nexport const PLAYWRIGHT_FEATURES: readonly string[] = Object.freeze([\n \"page.ariaSnapshot\",\n \"page.keyboard\",\n \"page.navigation.history\",\n \"locator.css\",\n \"locator.ref\",\n \"locator.role\",\n \"locator.text\",\n \"locator.testId\",\n \"locator.label\",\n \"locator.placeholder\",\n \"locator.altText\",\n \"locator.title\",\n \"locator.first\",\n \"locator.nth\",\n \"locator.count\",\n \"locator.waitFor\",\n \"locator.textContent\",\n \"locator.inputValue\",\n \"locator.getAttribute\",\n \"locator.isVisible\",\n \"locator.click\",\n \"locator.fill\",\n \"locator.press\",\n \"locator.hover\",\n \"locator.focus\",\n \"locator.check\",\n \"locator.uncheck\",\n \"locator.selectOption\",\n \"locator.boundingBox\",\n \"locator.dragTo\",\n \"page.mouse\",\n \"page.mouse.wheel\",\n \"page.on.console\",\n \"page.on.pageerror\",\n \"page.consoleMessages\",\n \"page.pageErrors\",\n \"page.screenshot.png\",\n \"page.evaluate\",\n]);\n\nexport interface PlaywrightOperationExecutorOptions {\n /** True when the endpoint dispatches `isTrusted:false` input (an AlmostCDP endpoint); false for native Chrome. */\n syntheticEvents: boolean;\n /** `browser.version()` of the connected endpoint, reported by `browser.status`. */\n endpoint: string;\n /**\n * The host's policy for one action, asked before it runs: each locator\n * action, each coordinate action (`browser.mouse`, `browser.drag`,\n * `browser.wheel`), and each `browser.script` before its source is\n * compiled. An element action's target is resolved once, described from the\n * browser side (see `GuardedTarget`), and the action then runs on that same\n * element. A target that cannot be resolved or described refuses the\n * operation without asking. Throwing a `BrowserActionRefusal` refuses the\n * operation with that code.\n */\n actionGuard?: (action: PlaywrightAction) => void | Promise<void>;\n /**\n * A CSS selector for the host's own elements: `browser.snapshot` leaves out\n * every matching element's nodes (Playwright's selector, which pierces open\n * shadow roots), and a coordinate action that lands on one is refused. The\n * page itself is not changed, so what assistive technology reads stays the\n * same.\n */\n snapshotExclude?: string;\n}\n\n/** One action an operation is about to perform. */\nexport type PlaywrightAction = PlaywrightElementAction | PlaywrightScriptAction;\n\nexport type { GuardedNode, GuardedTarget } from \"./guard.js\";\n\n/** An action that lands on an element: by locator, or at a viewport point. */\nexport interface PlaywrightElementAction {\n action: \"click\" | \"fill\" | \"press\" | \"hover\" | \"focus\" | \"check\" | \"uncheck\" | \"select\" | \"drag\"\n | \"mousedown\" | \"mouseup\" | \"wheel\";\n /** What the action lands on, described from the browser side. */\n target: GuardedTarget;\n value?: unknown;\n}\n\nexport interface PlaywrightScriptAction {\n /** `browser.script`: the author's source, run with the real `page`. */\n action: \"script\";\n source: string;\n args: Record<string, unknown>;\n}\n\n/** At most this many excluded elements are looked up per snapshot. */\nconst SNAPSHOT_EXCLUDE_LIMIT = 16;\n\n/** Every aria ref in an AI-mode JSON aria snapshot. */\nfunction collectRefs(nodes: unknown, into: Set<string>): void {\n if (Array.isArray(nodes)) {\n for (const node of nodes) collectRefs(node, into);\n return;\n }\n if (!nodes || typeof nodes !== \"object\") return;\n const node = nodes as { ref?: unknown; children?: unknown };\n if (typeof node.ref === \"string\") into.add(node.ref);\n collectRefs(node.children, into);\n}\n\n/**\n * An AI-mode aria snapshot's YAML without the nodes whose `[ref=\u2026]` is in\n * `refs`, their subtrees, and any ref-less node whose children all went with\n * them. A node is a `- ` line; its subtree is the lines indented under it.\n */\nexport function snapshotWithoutRefs(text: string, refs: ReadonlySet<string>): string {\n if (refs.size === 0) return text;\n interface Line { text: string; indent: number; children: Line[]; removed: boolean }\n const root: Line = { text: \"\", indent: -1, children: [], removed: false };\n const stack: Line[] = [root];\n const lines: Line[] = [];\n for (const raw of text.split(\"\\n\")) {\n const indent = raw.length - raw.trimStart().length;\n const line: Line = { text: raw, indent, children: [], removed: false };\n while (stack.length > 1 && stack[stack.length - 1]!.indent >= indent) stack.pop();\n stack[stack.length - 1]!.children.push(line);\n stack.push(line);\n lines.push(line);\n }\n const refOf = (line: Line): string | undefined => /\\[ref=([^\\]\\s]+)\\]/.exec(line.text)?.[1];\n const remove = (line: Line): void => {\n line.removed = true;\n for (const child of line.children) remove(child);\n };\n // Post-order: a node's children are decided before the node.\n const visit = (line: Line): void => {\n const ref = refOf(line);\n if (ref !== undefined && refs.has(ref)) {\n remove(line);\n return;\n }\n const before = line.children.length;\n for (const child of line.children) visit(child);\n if (line !== root && ref === undefined && before > 0 && line.children.every((child) => child.removed))\n line.removed = true;\n };\n visit(root);\n return lines.filter((line) => !line.removed).map((line) => line.text).join(\"\\n\");\n}\n\nconst REVISION_KEY = \"__supercodeBrowserRevision\";\n\n/**\n * Keeps a document-mutation counter on the page's main world. Installed as an\n * init script (every future document) and evaluated once (the current one).\n * Self-contained: Playwright serializes it into the page.\n */\nfunction installRevisionCounter(key: string): void {\n const scope = globalThis as unknown as Record<string, unknown>;\n if (typeof scope[key] === \"number\") return;\n scope[key] = 0;\n new MutationObserver(() => { scope[key] = (scope[key] as number) + 1; })\n .observe(document, { attributes: true, childList: true, characterData: true, subtree: true });\n}\n\n/**\n * `ElementInspection`'s fields except `ref`, computed in the page.\n * Self-contained: Playwright serializes it into the page.\n */\nfunction inspectInPage({ elements, limit }: { elements: Element[]; limit: number }): Array<Omit<ElementInspection, \"ref\">> {\n const normalize = (value: string): string => value.replace(/\\s+/g, \" \").trim();\n const implied = (element: Element): string | null => {\n const tag = element.tagName.toLowerCase();\n if (tag === \"button\") return \"button\";\n if (tag === \"a\" && element.hasAttribute(\"href\")) return \"link\";\n if (/^h[1-6]$/.test(tag)) return \"heading\";\n if (tag === \"textarea\") return \"textbox\";\n if (tag === \"select\") return \"combobox\";\n if (tag === \"option\") return \"option\";\n if (tag === \"img\") return \"img\";\n if (tag === \"ul\" || tag === \"ol\") return \"list\";\n if (tag === \"li\") return \"listitem\";\n if (tag === \"nav\") return \"navigation\";\n if (tag === \"main\") return \"main\";\n if (tag === \"form\") return \"form\";\n if (tag === \"input\") {\n const type = (element.getAttribute(\"type\") ?? \"text\").toLowerCase();\n if (type === \"button\" || type === \"submit\" || type === \"reset\") return \"button\";\n if (type === \"checkbox\") return \"checkbox\";\n if (type === \"radio\") return \"radio\";\n if (type === \"range\") return \"slider\";\n return \"textbox\";\n }\n return null;\n };\n const nameOf = (element: Element): string => {\n const aria = element.getAttribute(\"aria-label\");\n if (aria?.trim()) return normalize(aria);\n const ids = element.getAttribute(\"aria-labelledby\")?.split(/\\s+/).filter(Boolean) ?? [];\n const labelled = normalize(ids.map((id) => element.ownerDocument.getElementById(id)?.textContent ?? \"\").join(\" \"));\n if (labelled) return labelled;\n if (element instanceof HTMLInputElement && element.labels?.length) {\n const label = normalize(Array.from(element.labels).map((candidate) => candidate.textContent ?? \"\").join(\" \"));\n if (label) return label;\n }\n for (const attribute of [\"alt\", \"title\", \"placeholder\"]) {\n const value = element.getAttribute(attribute);\n if (value?.trim()) return normalize(value);\n }\n return normalize(element.textContent ?? \"\");\n };\n const visible = (element: Element): boolean => {\n if (element.getAttribute(\"aria-hidden\") === \"true\") return false;\n if (!(element instanceof HTMLElement)) return true;\n if (element.hidden) return false;\n const style = getComputedStyle(element);\n return style.display !== \"none\" && style.visibility !== \"hidden\" && style.opacity !== \"0\";\n };\n return elements.slice(0, limit).map((element) => {\n const role = element.getAttribute(\"role\")?.trim() || implied(element);\n const name = nameOf(element).slice(0, 500);\n const value = element instanceof HTMLInputElement\n ? (element.type === \"password\" ? \"<redacted>\" : element.value)\n : element instanceof HTMLTextAreaElement || element instanceof HTMLSelectElement ? element.value : undefined;\n const checked = element instanceof HTMLInputElement &&\n (element.type === \"checkbox\" || element.type === \"radio\") ? element.checked : undefined;\n return {\n tag: element.tagName.toLowerCase(),\n ...(role ? { role } : {}),\n ...(name ? { name } : {}),\n ...(value !== undefined ? { value: value.slice(0, 2_000) } : {}),\n disabled: (element instanceof HTMLButtonElement || element instanceof HTMLInputElement ||\n element instanceof HTMLSelectElement) && element.disabled,\n ...(checked !== undefined ? { checked } : {}),\n visible: visible(element),\n };\n });\n}\n\nfunction scrollInPage(delta: { left: number; top: number; amount: number | null }): { x: number; y: number } {\n const amount = delta.amount ?? Math.max(240, Math.round(window.innerHeight * 0.8));\n window.scrollBy({ left: delta.left * amount, top: delta.top * amount, behavior: \"instant\" });\n return { x: window.scrollX, y: window.scrollY };\n}\n\n/** A PNG's pixel size from its IHDR chunk. */\nfunction pngSize(bytes: Uint8Array): { width: number; height: number } | null {\n const signature = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];\n if (bytes.length < 24 || !signature.every((byte, index) => bytes[index] === byte)) return null;\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n return { width: view.getUint32(16), height: view.getUint32(20) };\n}\n\n/** Base64 of bytes without Node's Buffer. */\nfunction base64(bytes: Uint8Array): string {\n let binary = \"\";\n for (let offset = 0; offset < bytes.length; offset += 0x8000)\n binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000));\n return btoa(binary);\n}\n\n/**\n * Scripts return data, not live objects: keep the wire JSON-clean. Screenshot\n * bytes become a bounded image record rather than a JSON array of numbers.\n */\nfunction serializableValue(value: unknown, syntheticEvents: boolean): unknown {\n if (value === undefined) return null;\n const replacer = (_key: string, item: unknown): unknown => {\n const bytes = item instanceof Uint8Array ? item\n : item && typeof item === \"object\" && (item as { type?: unknown }).type === \"Buffer\" &&\n Array.isArray((item as { data?: unknown }).data) ? Uint8Array.from((item as { data: number[] }).data)\n : null;\n if (!bytes) return item;\n const size = pngSize(bytes);\n const encoded = base64(bytes);\n if (!size) return encoded;\n const dataUrl = `data:image/png;base64,${encoded}`;\n if (dataUrl.length > 768 * 1024) return { error: \"Screenshot exceeds the 768 KiB image record bound.\", width: size.width, height: size.height };\n return {\n dataUrl,\n format: \"png\",\n width: size.width,\n height: size.height,\n fidelity: syntheticEvents\n ? \"Pixels rasterized by the CDP endpoint's own renderer.\"\n : \"Native Chrome pixels captured over CDP.\",\n };\n };\n try {\n return JSON.parse(JSON.stringify(value, replacer));\n } catch {\n return String(value);\n }\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/** Map a Playwright failure onto the wire's error codes. */\nexport function classifyPlaywrightError(error: unknown): BrowserOperationErrorCode {\n if (error instanceof BrowserActionRefusal) return error.code;\n if (error instanceof errors.TimeoutError) return \"TIMED_OUT\";\n const message = errorMessage(error);\n if (/has been closed|Target closed|Target page, context or browser|Browser closed|browser has disconnected|Session closed|detached/i.test(message))\n return \"NOT_AVAILABLE\";\n if (/strict mode violation|resolved to 0 elements|no element matches|matched no element/i.test(message))\n return \"NOT_FOUND\";\n if (/unavailable|not supported/i.test(message)) return \"UNSUPPORTED\";\n return \"FAILED\";\n}\n\nexport class PlaywrightOperationExecutor {\n private readonly page: Page;\n private readonly options: PlaywrightOperationExecutorOptions;\n private readonly ready: Promise<void>;\n private readonly targets: BrowserSideTargets;\n /** Where the mouse is: `page.mouse` keeps it, but does not report it. */\n private mouse = { x: 0, y: 0 };\n\n constructor(page: Page, options: PlaywrightOperationExecutorOptions) {\n this.page = page;\n this.options = options;\n this.targets = new BrowserSideTargets(page, options.snapshotExclude ?? null);\n this.ready = (async () => {\n await page.addInitScript(installRevisionCounter, REVISION_KEY);\n await page.evaluate(installRevisionCounter, REVISION_KEY).catch(() => undefined);\n })();\n }\n\n async execute(raw: unknown): Promise<BrowserOperationResult> {\n const call = parseBrowserOperationCall(raw);\n const operation = operationName(raw);\n if (!call) return this.failure(operation, \"INVALID_INPUT\", \"Invalid browser operation request.\");\n try {\n await this.ready;\n return await this.executeCall(call);\n } catch (error) {\n return this.failure(call.operation, classifyPlaywrightError(error), errorMessage(error));\n }\n }\n\n private locator(value: unknown, index?: number): Locator {\n const locator = value as BrowserLocator;\n const exact = (candidate: { exact?: boolean }) => candidate.exact !== undefined ? { exact: candidate.exact } : {};\n const page = this.page;\n const base = locator.by === \"css\" ? page.locator(locator.value)\n // Refs are the `[ref=\u2026]` marks of an AI-mode aria snapshot, resolved by\n // Playwright's built-in `aria-ref` selector engine.\n : locator.by === \"ref\" ? page.locator(`aria-ref=${locator.value}`)\n : locator.by === \"role\" ? page.getByRole(locator.role as Parameters<Page[\"getByRole\"]>[0], {\n ...(locator.name !== undefined ? { name: locator.name } : {}),\n // A role's name matches exactly unless told otherwise.\n exact: locator.exact ?? true,\n })\n : locator.by === \"text\" ? page.getByText(locator.text, exact(locator))\n : locator.by === \"label\" ? page.getByLabel(locator.text, exact(locator))\n : locator.by === \"placeholder\" ? page.getByPlaceholder(locator.text, exact(locator))\n : locator.by === \"altText\" ? page.getByAltText(locator.text, exact(locator))\n : locator.by === \"title\" ? page.getByTitle(locator.text, exact(locator))\n : page.getByTestId(locator.value);\n return index === undefined ? base : index === 0 ? base.first() : base.nth(index);\n }\n\n /**\n * Playwright's `aria-ref` engine resolves against the last AI-mode snapshot\n * the page took. Refs are stable per element, so refreshing the whole-page\n * snapshot before resolving one keeps every ref from `browser.snapshot`\n * addressable even after an element-scoped snapshot replaced the map.\n */\n private async refreshRefs(value: unknown): Promise<void> {\n if ((value as BrowserLocator | undefined)?.by === \"ref\")\n await this.page.ariaSnapshot({ mode: \"ai\", timeout: ACTION_TIMEOUT_MS });\n }\n\n private async refOf(locator: Locator): Promise<string> {\n try {\n const nodes = await locator.ariaSnapshotJSON({ mode: \"ai\", depth: 1, timeout: ACTION_TIMEOUT_MS }) as unknown;\n const first = Array.isArray(nodes) ? nodes.find((node) => node && typeof node === \"object\") as { ref?: unknown } | undefined : undefined;\n return typeof first?.ref === \"string\" ? first.ref : \"\";\n } catch {\n return \"\";\n }\n }\n\n private async inspectAll(locator: Locator, limit: number): Promise<ElementInspection[]> {\n // Element handles, not `evaluateAll`: Playwright's `evaluateAll` resolves an\n // `aria-ref` locator in the main world, where the snapshot's refs are not\n // known, and finds nothing (measured with Playwright 1.63 on Chrome).\n const handles = (await locator.elementHandles()).slice(0, limit);\n let fields: Array<Omit<ElementInspection, \"ref\">>;\n try {\n const inspect = inspectInPage as unknown as (input: { elements: unknown[]; limit: number }) => Array<Omit<ElementInspection, \"ref\">>;\n fields = await this.page.evaluate(inspect, { elements: handles as unknown[], limit });\n } finally {\n await Promise.all(handles.map((handle) => handle.dispose().catch(() => undefined)));\n }\n const refs = await Promise.all(fields.map((_, index) => this.refOf(locator.nth(index))));\n return fields.map((field, index) => ({ ref: refs[index] ?? \"\", ...field }));\n }\n\n private async inspect(locator: Locator): Promise<ElementInspection> {\n const [inspection] = await this.inspectAll(locator.first(), 1);\n if (!inspection) throw new BrowserActionRefusal(\"NOT_FOUND\", \"The locator matched no element.\");\n return inspection;\n }\n\n /** Run a locator action; a failure on a locator that matches nothing is NOT_FOUND. */\n private async act<T>(locator: Locator, action: string, run: () => Promise<T>): Promise<T> {\n try {\n return await run();\n } catch (error) {\n if (!(error instanceof BrowserActionRefusal) && await locator.count().catch(() => 1) === 0)\n throw new BrowserActionRefusal(\"NOT_FOUND\", `${action} found no element for the locator.`);\n throw error;\n }\n }\n\n /**\n * Resolves the locator's element once (waiting up to the action budget),\n * asks the host's policy about it, and returns the handle the action must\n * use, so the element guarded is the element acted on. Without a policy the\n * action runs on the locator. Resolution or description failing refuses.\n */\n private async guarded(\n locator: Locator,\n action: PlaywrightElementAction[\"action\"],\n value?: unknown,\n ): Promise<ElementHandle | null> {\n const guard = this.options.actionGuard;\n if (!guard) return null;\n let handle: ElementHandle | null;\n try {\n handle = await locator.elementHandle({ timeout: ACTION_TIMEOUT_MS });\n } catch (error) {\n if (error instanceof errors.TimeoutError)\n throw new BrowserActionRefusal(\"NOT_FOUND\", `${action} found no element for the locator in ${ACTION_TIMEOUT_MS}ms.`);\n throw error;\n }\n if (!handle) throw new BrowserActionRefusal(\"NOT_FOUND\", `${action} found no element for the locator.`);\n try {\n await guard({ action, target: await this.describe(() => this.targets.ofHandle(handle!, ACTION_TIMEOUT_MS)),\n ...(value !== undefined ? { value } : {}) });\n } catch (error) {\n await handle.dispose().catch(() => undefined);\n throw error;\n }\n return handle;\n }\n\n /** Asks the host's policy about the element at a viewport point. */\n private async guardPoint(action: PlaywrightElementAction[\"action\"], x: number, y: number): Promise<void> {\n const guard = this.options.actionGuard;\n if (!guard) return;\n await guard({ action, target: await this.describe(() => this.targets.atPoint(x, y)) });\n }\n\n /** A browser-side description, or the refusal that replaces the action. */\n private async describe(run: () => Promise<GuardedTarget>): Promise<GuardedTarget> {\n try {\n return await run();\n } catch (error) {\n if (error instanceof HostElementTarget) throw new BrowserActionRefusal(\"UNSUPPORTED\", error.message);\n if (error instanceof UnidentifiedTarget)\n throw new BrowserActionRefusal(\"UNSUPPORTED\", `${error.message} The action was refused because its target could not be checked.`);\n throw new BrowserActionRefusal(\"UNSUPPORTED\",\n `The action was refused because its target could not be checked: ${errorMessage(error)}`);\n }\n }\n\n /** The aria refs of the elements `snapshotExclude` matches, and of their contents. */\n private async excludedRefs(): Promise<Set<string>> {\n const refs = new Set<string>();\n const selector = this.options.snapshotExclude;\n if (!selector) return refs;\n const matches = this.page.locator(selector);\n const count = Math.min(await matches.count().catch(() => 0), SNAPSHOT_EXCLUDE_LIMIT);\n for (let index = 0; index < count; index += 1) {\n const nodes = await matches.nth(index).ariaSnapshotJSON({ mode: \"ai\", timeout: ACTION_TIMEOUT_MS }).catch(() => null) as unknown;\n collectRefs(nodes, refs);\n }\n return refs;\n }\n\n private async revision(): Promise<number> {\n const value = await this.page.evaluate((key) => (globalThis as unknown as Record<string, unknown>)[key], REVISION_KEY)\n .catch(() => undefined);\n return typeof value === \"number\" ? value : 0;\n }\n\n private async executeCall(call: BrowserOperationCall): Promise<BrowserOperationResult> {\n const input = call.input;\n const page = this.page;\n const expectedRevision = typeof input.expectedRevision === \"number\" ? input.expectedRevision : undefined;\n if (expectedRevision !== undefined) {\n const current = await this.revision();\n if (expectedRevision !== current)\n return this.failure(call.operation, \"STALE_PAGE\", `The page changed (expected revision ${expectedRevision}, current revision ${current}).`);\n }\n if (call.operation === \"browser.status\")\n return this.success(call.operation, {\n available: true,\n features: PLAYWRIGHT_FEATURES,\n syntheticEvents: this.options.syntheticEvents,\n implementation: PLAYWRIGHT_IMPLEMENTATION,\n endpoint: this.options.endpoint,\n });\n if (call.operation === \"browser.snapshot\") {\n await this.refreshRefs(input.locator);\n const scoped = input.locator ? this.locator(input.locator).first() : null;\n // The excluded elements' refs come first: each element-scoped snapshot\n // replaces the page's ref map, which the snapshot below then restores.\n const excluded = await this.excludedRefs();\n const text = snapshotWithoutRefs(scoped\n ? await this.act(scoped, \"ariaSnapshot\", () => scoped.ariaSnapshot({ mode: \"ai\", timeout: ACTION_TIMEOUT_MS }))\n : await page.ariaSnapshot({ mode: \"ai\", timeout: ACTION_TIMEOUT_MS }), excluded);\n const bounded = text.slice(0, 64_000);\n return this.success(call.operation, { text: bounded, truncated: bounded.length < text.length });\n }\n if (call.operation === \"browser.query\") {\n await this.refreshRefs(input.locator);\n const locator = this.locator(input.locator, typeof input.index === \"number\" ? input.index : undefined);\n const count = await locator.count();\n return this.success(call.operation, { count, matches: await this.inspectAll(locator, 50), truncated: count > 50 });\n }\n if (call.operation === \"browser.wait\") {\n await this.refreshRefs(input.locator);\n const requested = typeof input.timeout === \"number\" ? input.timeout : 5_000;\n const timeout = Math.min(requested, WAIT_TIMEOUT_CLAMP_MS);\n const locator = this.locator(input.locator, typeof input.index === \"number\" ? input.index : 0);\n try {\n await locator.waitFor({ state: input.state === \"attached\" ? \"attached\" : \"visible\", timeout });\n } catch (error) {\n if (error instanceof errors.TimeoutError)\n throw new BrowserActionRefusal(\"TIMED_OUT\", `waitFor timed out after ${timeout}ms` +\n (timeout < requested ? ` (the requested ${requested}ms is clamped to ${WAIT_TIMEOUT_CLAMP_MS}ms by the provider call deadline)` : \"\") + \".\");\n throw error;\n }\n return this.success(call.operation, { ready: true });\n }\n if (call.operation === \"browser.scroll\") {\n const direction = input.direction as \"up\" | \"down\" | \"left\" | \"right\";\n const position = await page.evaluate(scrollInPage, {\n left: direction === \"left\" ? -1 : direction === \"right\" ? 1 : 0,\n top: direction === \"up\" ? -1 : direction === \"down\" ? 1 : 0,\n amount: typeof input.amount === \"number\" ? input.amount : null,\n });\n return this.success(call.operation, position);\n }\n if (call.operation === \"browser.script\") return this.script(call);\n if (call.operation === \"browser.mouse\") {\n const action = input.action as \"move\" | \"down\" | \"up\" | \"click\";\n const at = typeof input.x === \"number\" && typeof input.y === \"number\" ? { x: input.x, y: input.y } : this.mouse;\n if (action === \"move\") await this.guardPoint(\"hover\", at.x, at.y);\n else await this.guardPoint(action === \"click\" ? \"click\" : action === \"down\" ? \"mousedown\" : \"mouseup\", at.x, at.y);\n if (action === \"move\") await page.mouse.move(at.x, at.y);\n else if (action === \"click\") await page.mouse.click(at.x, at.y);\n else if (action === \"down\") await page.mouse.down();\n else await page.mouse.up();\n if (action === \"move\" || action === \"click\") this.mouse = { x: at.x, y: at.y };\n return this.success(call.operation, { action, ...(typeof input.x === \"number\" ? { x: input.x, y: input.y } : {}) });\n }\n if (call.operation === \"browser.wheel\") {\n const deltaX = typeof input.deltaX === \"number\" ? input.deltaX : 0;\n const deltaY = typeof input.deltaY === \"number\" ? input.deltaY : 0;\n await this.guardPoint(\"wheel\", this.mouse.x, this.mouse.y);\n await page.mouse.wheel(deltaX, deltaY);\n return this.success(call.operation, { deltaX, deltaY });\n }\n if (call.operation === \"browser.drag\") {\n // Each endpoint is resolved and guarded once; the drag uses those points.\n const resolve = async (endpoint: Record<string, unknown>): Promise<{ x: number; y: number }> => {\n if (endpoint.locator === undefined) {\n const point = { x: endpoint.x as number, y: endpoint.y as number };\n await this.guardPoint(\"drag\", point.x, point.y);\n return point;\n }\n await this.refreshRefs(endpoint.locator);\n const locator = this.locator(endpoint.locator).first();\n const handle = await this.guarded(locator, \"drag\");\n try {\n const box = handle\n ? await handle.boundingBox()\n : await locator.count() === 0 ? null : await locator.boundingBox({ timeout: ACTION_TIMEOUT_MS });\n if (!box) throw new BrowserActionRefusal(\"NOT_FOUND\", \"The drag locator matched no element.\");\n return { x: box.x + box.width / 2, y: box.y + box.height / 2 };\n } finally {\n await handle?.dispose().catch(() => undefined);\n }\n };\n const from = await resolve(input.from as Record<string, unknown>);\n const to = await resolve(input.to as Record<string, unknown>);\n await page.mouse.move(from.x, from.y);\n await page.mouse.down();\n await page.mouse.move(to.x, to.y, { steps: typeof input.steps === \"number\" ? input.steps : 8 });\n await page.mouse.up();\n this.mouse = to;\n return this.success(call.operation, { from, to });\n }\n if (call.operation === \"browser.back\") {\n await page.goBack({ waitUntil: \"commit\", timeout: ACTION_TIMEOUT_MS });\n return this.success(call.operation, { requested: true });\n }\n if (call.operation === \"browser.forward\") {\n await page.goForward({ waitUntil: \"commit\", timeout: ACTION_TIMEOUT_MS });\n return this.success(call.operation, { requested: true });\n }\n if (call.operation === \"browser.reload\") {\n await page.reload({ waitUntil: \"commit\", timeout: ACTION_TIMEOUT_MS });\n return this.success(call.operation, { requested: true });\n }\n\n await this.refreshRefs(input.locator);\n const locator = input.locator\n ? this.locator(input.locator, typeof input.index === \"number\" ? input.index : 0)\n : null;\n const timeout = ACTION_TIMEOUT_MS;\n if (call.operation === \"browser.box\") {\n const box = await locator!.count() === 0 ? null : await locator!.boundingBox({ timeout });\n if (!box) return this.failure(call.operation, \"NOT_FOUND\", \"The locator matched no element.\");\n return this.success(call.operation, box);\n }\n if (call.operation === \"browser.press\" && !locator) {\n // The key goes to the focused element (the document body when none is).\n const focused = page.locator(\"*:focus\").first();\n const handle = await this.guarded(await focused.count() ? focused : page.locator(\"body\"), \"press\", input.key);\n try {\n await page.keyboard.press(input.key as string);\n } finally {\n await handle?.dispose().catch(() => undefined);\n }\n return this.success(call.operation, { key: input.key });\n }\n const target = locator!;\n const guardedAction = call.operation === \"browser.select\" ? \"select\" : call.operation.slice(\"browser.\".length) as PlaywrightElementAction[\"action\"];\n const handle = await this.guarded(target.first(), guardedAction,\n call.operation === \"browser.fill\" ? input.value : call.operation === \"browser.press\" ? input.key\n : call.operation === \"browser.select\" ? input.values : undefined);\n // The guarded element itself, when there is a policy; else the locator.\n const element: Pick<Locator, \"click\" | \"fill\" | \"press\" | \"hover\" | \"check\" | \"uncheck\" | \"selectOption\"> & { focus(): Promise<void> } =\n handle ?? { ...bind(target), focus: () => target.focus({ timeout }) };\n // The inspection is read after the action; an action that detaches or\n // navigates away from its element reports the element as it was.\n const before = await this.inspect(target).catch(() => null);\n try {\n if (call.operation === \"browser.click\") await this.act(target, \"click\", () => element.click({ timeout }));\n else if (call.operation === \"browser.fill\") await this.act(target, \"fill\", () => element.fill(input.value as string, { timeout }));\n else if (call.operation === \"browser.press\") await this.act(target, \"press\", () => element.press(input.key as string, { timeout }));\n else if (call.operation === \"browser.hover\") await this.act(target, \"hover\", () => element.hover({ timeout }));\n else if (call.operation === \"browser.focus\") await this.act(target, \"focus\", () => element.focus());\n else if (call.operation === \"browser.check\") await this.act(target, \"check\", () => element.check({ timeout }));\n else if (call.operation === \"browser.uncheck\") await this.act(target, \"uncheck\", () => element.uncheck({ timeout }));\n else if (call.operation === \"browser.select\") {\n const values = await this.act(target, \"selectOption\", () => element.selectOption(input.values as string[], { timeout }));\n return this.success(call.operation, { values });\n }\n } finally {\n await handle?.dispose().catch(() => undefined);\n }\n const after = await this.inspect(target).catch(() => null);\n const inspection = after ?? before;\n if (!inspection) throw new BrowserActionRefusal(\"NOT_FOUND\", \"The locator matched no element.\");\n return this.success(call.operation, inspection);\n }\n\n private async script(call: BrowserOperationCall): Promise<BrowserOperationResult> {\n const input = call.input;\n const source = input.source as string;\n const args = (input.args as Record<string, unknown> | undefined) ?? {};\n const requested = typeof input.timeout === \"number\" ? input.timeout : 30_000;\n const timeout = Math.min(requested, SCRIPT_TIMEOUT_CLAMP_MS);\n // Ordinary Playwright, run in this realm with the real `page`.\n const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor as\n new (...parameters: string[]) => (...values: unknown[]) => Promise<unknown>;\n if (this.options.actionGuard) await this.options.actionGuard({ action: \"script\", source, args });\n let run: (...values: unknown[]) => Promise<unknown>;\n try {\n run = new AsyncFunction(\"page\", \"args\", source);\n } catch (error) {\n return this.failure(call.operation, \"FAILED\", `The script did not parse: ${errorMessage(error)}`);\n }\n const notice = timeout < requested\n ? `The script timeout is clamped to ${SCRIPT_TIMEOUT_CLAMP_MS}ms: the harness abandons a provider call at 12 s.`\n : undefined;\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n const value = await Promise.race([\n run(this.page, args),\n new Promise((_resolve, reject) => {\n timer = setTimeout(() => reject(new BrowserActionRefusal(\"FAILED\", `The script exceeded ${timeout}ms.` + (notice ? ` ${notice}` : \"\"))), timeout);\n }),\n ]);\n return this.success(call.operation, {\n value: serializableValue(value, this.options.syntheticEvents),\n ...(notice ? { notice } : {}),\n });\n } finally {\n clearTimeout(timer);\n // Listeners a script attached do not outlive it.\n this.page.removeAllListeners();\n }\n }\n\n private async target(): Promise<BrowserTarget> {\n if (this.page.isClosed()) return { url: \"\", title: \"\", revision: 0 };\n // A page mid-navigation can hold `title()` until its next document exists;\n // the target is a description, so it never outwaits the call.\n const bounded = <T>(promise: Promise<T>, fallback: T): Promise<T> => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n return Promise.race([\n promise.catch(() => fallback),\n new Promise<T>((resolve) => { timer = setTimeout(() => resolve(fallback), 1_000); }),\n ]).finally(() => clearTimeout(timer));\n };\n const [title, revision] = await Promise.all([\n bounded(this.page.title(), \"\"),\n bounded(this.revision(), 0),\n ]);\n return { url: this.page.url(), title, revision };\n }\n\n private async success(operation: BrowserOperationName, value: unknown): Promise<BrowserOperationResult> {\n return { ok: true, operation, target: await this.target(), value };\n }\n\n private async failure(operation: BrowserOperationName, code: BrowserOperationErrorCode, message: string): Promise<BrowserOperationResult> {\n return { ok: false, operation, error: { code, message }, target: await this.target() };\n }\n}\n\nfunction operationName(raw: unknown): BrowserOperationName {\n const candidate = raw && typeof raw === \"object\" && !Array.isArray(raw) ? (raw as Record<string, unknown>).operation : undefined;\n return typeof candidate === \"string\" && (BROWSER_OPERATION_NAMES as readonly string[]).includes(candidate)\n ? candidate as BrowserOperationName\n : \"browser.status\";\n}\n\n/** A locator's action methods, bound, so it can stand where an element handle does. */\nfunction bind(locator: Locator): Pick<Locator, \"click\" | \"fill\" | \"press\" | \"hover\" | \"check\" | \"uncheck\" | \"selectOption\"> {\n return {\n click: locator.click.bind(locator),\n fill: locator.fill.bind(locator),\n press: locator.press.bind(locator),\n hover: locator.hover.bind(locator),\n check: locator.check.bind(locator),\n uncheck: locator.uncheck.bind(locator),\n selectOption: locator.selectOption.bind(locator),\n };\n}\n", "/**\n * What an action is about to land on, described from the browser side for a\n * host's `actionGuard`: the elements are found in an isolated world the page's\n * scripts cannot reach (its DOM prototypes are the browser's own), and each is\n * described over CDP from its backend node (`DOM.describeNode`,\n * `Accessibility.getPartialAXTree`), so a page cannot change what the guard\n * reads by overriding DOM functions.\n *\n * Over AlmostCDP the CDP endpoint itself runs in the page, so there the\n * description is as trustworthy as the page's world; over a native CDP\n * endpoint (Chrome, `chrome.debugger`) it is the browser's.\n */\n\nimport type { CDPSession, ElementHandle, Page } from \"playwright-core\";\n\n/** One element (or accessibility ancestor), as the browser describes it. */\nexport interface GuardedNode {\n /** The node's backend id: stable for the node's life in its document. */\n backendNodeId: number;\n /** Lower-case tag name; empty for an accessibility-only ancestor. */\n tag: string;\n /** The node's attributes, as the DOM holds them. */\n attributes: Readonly<Record<string, string>>;\n /** Computed accessibility role and name. */\n role: string;\n name: string;\n}\n\n/** Where an action lands. */\nexport interface GuardedTarget {\n /** The page URL the target was resolved on. */\n url: string;\n /**\n * The element the action lands on. For a locator, every element whose box\n * is exactly the resolved element's (a wrapper of the same size is\n * indistinguishable from outside, so a guard sees all of them); for a\n * point, the element hit there.\n */\n nodes: readonly GuardedNode[];\n /** Accessibility ancestors of those elements, nearest first. */\n ancestors: readonly GuardedNode[];\n /** The viewport point of a coordinate action. */\n point?: { x: number; y: number };\n}\n\n/** A target that could not be identified browser-side: the action is refused. */\nexport class UnidentifiedTarget extends Error {}\n\n/** A coordinate action that lands on the host's own interface: refused. */\nexport class HostElementTarget extends Error {}\n\nconst WORLD = \"supercode-guard\";\nconst GROUP = \"supercode-guard\";\nconst MAX_NODES = 8;\nconst MAX_ANCESTORS = 6;\n\ntype Query =\n | { kind: \"box\"; box: { x: number; y: number; width: number; height: number }; host: string | null; max: number }\n | { kind: \"point\"; x: number; y: number; host: string | null };\n\n/**\n * Runs in the isolated world. Returns the matching elements, or a string:\n * `host` when a point lands on the host's own elements, else why nothing was\n * found. Self-contained: it is sent as source.\n */\nfunction findInWorld(query: Query): Element[] | string {\n const onHost = (element: Element): boolean => {\n if (!query.host) return false;\n for (let node: Element | null = element; node; ) {\n if (node.matches(query.host)) return true;\n const parent: Element | null = node.parentElement;\n node = parent ?? ((node.getRootNode() as ShadowRoot).host ?? null);\n }\n return false;\n };\n if (query.kind === \"point\") {\n let element = document.elementFromPoint(query.x, query.y);\n if (!element) return \"Nothing is at that point.\";\n if (onHost(element)) return \"host\";\n while (element.shadowRoot) {\n const inner: Element | null = element.shadowRoot.elementFromPoint(query.x, query.y);\n if (!inner || inner === element) break;\n element = inner;\n if (onHost(element)) return \"host\";\n }\n if (/^(IFRAME|FRAME|OBJECT|EMBED)$/.test(element.tagName))\n return \"The point is inside an embedded frame, which the guard cannot inspect.\";\n return [element];\n }\n const { box } = query;\n const found: Element[] = [];\n const near = (a: number, b: number): boolean => Math.abs(a - b) <= 1;\n const visit = (root: Document | ShadowRoot): void => {\n for (const element of Array.from(root.querySelectorAll(\"*\"))) {\n if (found.length >= query.max) return;\n const rect = element.getBoundingClientRect();\n if (near(rect.x, box.x) && near(rect.y, box.y) && near(rect.width, box.width) && near(rect.height, box.height))\n found.push(element);\n if (element.shadowRoot) visit(element.shadowRoot);\n }\n };\n visit(document);\n return found.length ? found : \"The element could not be found in the page's top document (it may be inside an embedded frame or a closed shadow root).\";\n}\n\ninterface AXNode {\n nodeId: string;\n ignored?: boolean;\n role?: { value?: unknown };\n name?: { value?: unknown };\n parentId?: string;\n backendDOMNodeId?: number;\n}\n\nexport class BrowserSideTargets {\n private session: Promise<CDPSession> | null = null;\n\n constructor(private readonly page: Page, private readonly host: string | null) {}\n\n /** The element a resolved handle is, scrolled into view. */\n async ofHandle(handle: ElementHandle, timeout: number): Promise<GuardedTarget> {\n await handle.scrollIntoViewIfNeeded({ timeout });\n const box = await handle.boundingBox();\n if (!box || box.width === 0 || box.height === 0)\n throw new UnidentifiedTarget(\"The element has no box on the page.\");\n return await this.resolve({ kind: \"box\", box, host: this.host, max: MAX_NODES });\n }\n\n /** The element at a viewport point. */\n async atPoint(x: number, y: number): Promise<GuardedTarget> {\n return { ...await this.resolve({ kind: \"point\", x, y, host: this.host }), point: { x, y } };\n }\n\n private cdp(): Promise<CDPSession> {\n this.session ??= this.page.context().newCDPSession(this.page).catch((error: unknown) => {\n this.session = null;\n throw error;\n });\n return this.session;\n }\n\n private async resolve(query: Query): Promise<GuardedTarget> {\n const cdp = await this.cdp();\n const tree = await cdp.send(\"Page.getFrameTree\") as { frameTree: { frame: { id: string } } };\n const world = await cdp.send(\"Page.createIsolatedWorld\", { frameId: tree.frameTree.frame.id, worldName: WORLD }) as\n { executionContextId: number };\n try {\n const evaluated = await cdp.send(\"Runtime.evaluate\", {\n expression: `(${findInWorld.toString()})(${JSON.stringify(query)})`,\n contextId: world.executionContextId,\n objectGroup: GROUP,\n returnByValue: false,\n }) as { result: { type: string; value?: unknown; objectId?: string }; exceptionDetails?: { text?: string } };\n if (evaluated.exceptionDetails)\n throw new UnidentifiedTarget(`The target could not be resolved: ${evaluated.exceptionDetails.text ?? \"exception\"}.`);\n if (evaluated.result.type === \"string\") {\n if (evaluated.result.value === \"host\") throw new HostElementTarget(\"The point is on the host's own interface, which agents cannot operate.\");\n throw new UnidentifiedTarget(String(evaluated.result.value));\n }\n if (!evaluated.result.objectId) throw new UnidentifiedTarget(\"The target could not be resolved.\");\n const properties = await cdp.send(\"Runtime.getProperties\", { objectId: evaluated.result.objectId, ownProperties: true }) as\n { result: Array<{ name: string; value?: { objectId?: string } }> };\n const objects = properties.result\n .filter((property) => /^\\d+$/.test(property.name) && property.value?.objectId)\n .map((property) => property.value!.objectId!);\n if (!objects.length) throw new UnidentifiedTarget(\"The target could not be resolved.\");\n const nodes: GuardedNode[] = [];\n const ancestors: GuardedNode[] = [];\n const seen = new Set<number>();\n for (const objectId of objects) {\n const described = await cdp.send(\"DOM.describeNode\", { objectId }) as\n { node: { backendNodeId: number; nodeName: string; attributes?: string[] } };\n const attributes: Record<string, string> = {};\n const list = described.node.attributes ?? [];\n for (let index = 0; index + 1 < list.length; index += 2) attributes[list[index]!.toLowerCase()] = list[index + 1]!;\n const ax = await this.accessibility(cdp, described.node.backendNodeId);\n nodes.push({\n backendNodeId: described.node.backendNodeId,\n tag: described.node.nodeName.toLowerCase(),\n attributes,\n role: ax.self?.role ?? \"\",\n name: ax.self?.name ?? \"\",\n });\n seen.add(described.node.backendNodeId);\n for (const ancestor of ax.ancestors) {\n if (ancestors.length >= MAX_ANCESTORS || seen.has(ancestor.backendNodeId)) continue;\n seen.add(ancestor.backendNodeId);\n ancestors.push(ancestor);\n }\n }\n return { url: this.page.url(), nodes, ancestors };\n } finally {\n await cdp.send(\"Runtime.releaseObjectGroup\", { objectGroup: GROUP }).catch(() => undefined);\n }\n }\n\n private async accessibility(cdp: CDPSession, backendNodeId: number): Promise<{ self: { role: string; name: string } | null; ancestors: GuardedNode[] }> {\n const tree = await cdp.send(\"Accessibility.getPartialAXTree\", { backendNodeId, fetchRelatives: true }) as { nodes: AXNode[] };\n const byId = new Map(tree.nodes.map((node) => [node.nodeId, node]));\n const text = (value: unknown): string => typeof value === \"string\" ? value.replace(/\\s+/g, \" \").trim() : \"\";\n const self = tree.nodes.find((node) => node.backendDOMNodeId === backendNodeId) ?? null;\n const ancestors: GuardedNode[] = [];\n for (let node = self?.parentId ? byId.get(self.parentId) : undefined; node && ancestors.length < MAX_ANCESTORS;\n node = node.parentId ? byId.get(node.parentId) : undefined) {\n if (node.ignored || typeof node.backendDOMNodeId !== \"number\") continue;\n ancestors.push({ backendNodeId: node.backendDOMNodeId, tag: \"\", attributes: {}, role: text(node.role?.value), name: text(node.name?.value) });\n }\n return { self: self ? { role: text(self.role?.value), name: text(self.name?.value) } : null, ancestors };\n }\n}\n", "/**\n * The wire Supercode's browser providers answer: `supercode/browser-provider-v1`\n * envelopes carrying `supercode/browser-operation-v1` calls. Pure data and\n * parsers, with no runtime dependency, for the harness side, a host relaying\n * calls, and the executor alike.\n */\n\nexport const SUPERCODE_BROWSER_PROVIDER_PROTOCOL = \"supercode/browser-provider-v1\" as const;\nexport const SUPERCODE_BROWSER_OPERATION_PROTOCOL = \"supercode/browser-operation-v1\" as const;\n\nexport type BrowserLocator =\n | { by: \"css\"; value: string }\n | { by: \"ref\"; value: string }\n | { by: \"role\"; role: string; name?: string; exact?: boolean }\n | { by: \"text\"; text: string; exact?: boolean }\n | { by: \"testId\"; value: string }\n | { by: \"label\"; text: string; exact?: boolean }\n | { by: \"placeholder\"; text: string; exact?: boolean }\n | { by: \"altText\"; text: string; exact?: boolean }\n | { by: \"title\"; text: string; exact?: boolean };\n\nexport type BrowserOperationName =\n | \"browser.status\" | \"browser.snapshot\" | \"browser.query\" | \"browser.wait\"\n | \"browser.click\" | \"browser.fill\" | \"browser.press\" | \"browser.hover\"\n | \"browser.focus\" | \"browser.check\" | \"browser.uncheck\" | \"browser.select\"\n | \"browser.scroll\" | \"browser.back\" | \"browser.forward\" | \"browser.reload\"\n | \"browser.box\" | \"browser.mouse\" | \"browser.drag\" | \"browser.wheel\"\n | \"browser.script\";\n\nexport interface BrowserOperationCall {\n protocol: typeof SUPERCODE_BROWSER_OPERATION_PROTOCOL;\n operation: BrowserOperationName;\n input: Record<string, unknown>;\n}\n\nexport interface BrowserTarget {\n page?: string;\n url: string;\n title: string;\n revision: number;\n}\n\nexport type BrowserOperationErrorCode =\n | \"APPROVAL_REQUIRED\" | \"INVALID_INPUT\" | \"NOT_AVAILABLE\" | \"NOT_FOUND\"\n | \"STALE_PAGE\" | \"TIMED_OUT\" | \"UNSUPPORTED\" | \"FAILED\";\n\nexport type BrowserOperationResult =\n | { ok: true; operation: BrowserOperationName; target: BrowserTarget; value: unknown }\n | {\n ok: false;\n operation: BrowserOperationName;\n error: { code: BrowserOperationErrorCode; message: string };\n target?: BrowserTarget;\n };\n\nexport interface ElementInspection {\n ref: string;\n tag: string;\n role?: string;\n name?: string;\n value?: string;\n disabled: boolean;\n checked?: boolean;\n visible: boolean;\n}\n\n\n/** The 21 operations, in the registry's order. */\nexport const BROWSER_OPERATION_NAMES: readonly BrowserOperationName[] = Object.freeze([\n \"browser.status\", \"browser.snapshot\", \"browser.query\", \"browser.wait\",\n \"browser.click\", \"browser.fill\", \"browser.press\", \"browser.hover\",\n \"browser.focus\", \"browser.check\", \"browser.uncheck\", \"browser.select\",\n \"browser.scroll\", \"browser.back\", \"browser.forward\", \"browser.reload\",\n \"browser.box\", \"browser.mouse\", \"browser.drag\", \"browser.wheel\",\n \"browser.script\",\n]);\nconst OPERATION_NAMES = new Set<BrowserOperationName>(BROWSER_OPERATION_NAMES);\n\n/** A host's refusal of one action, carrying its wire error code. */\nexport class BrowserActionRefusal extends Error {\n constructor(readonly code: BrowserOperationErrorCode, message: string) {\n super(message);\n this.name = \"BrowserActionRefusal\";\n }\n}\n\nfunction record(value: unknown): Record<string, unknown> | null {\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? value as Record<string, unknown>\n : null;\n}\n\nfunction exactKeys(candidate: Record<string, unknown>, allowed: readonly string[]): boolean {\n return Object.keys(candidate).every((key) => allowed.includes(key));\n}\n\nfunction parsePage(value: unknown): string | undefined | null {\n return value === undefined\n ? undefined\n : typeof value === \"string\" && value.length > 0 && value.length <= 512\n ? value\n : null;\n}\n\nexport function parseBrowserLocator(value: unknown): BrowserLocator | null {\n const candidate = record(value);\n if (!candidate || typeof candidate.by !== \"string\") return null;\n if (candidate.by === \"label\" || candidate.by === \"placeholder\" || candidate.by === \"altText\" || candidate.by === \"title\") {\n const { by, text, exact } = candidate as Record<string, unknown>;\n return typeof text === \"string\" && (exact === undefined || typeof exact === \"boolean\") &&\n exactKeys(candidate as Record<string, unknown>, [\"by\", \"text\", \"exact\"])\n ? ({ by, text, ...(exact !== undefined ? { exact } : {}) } as BrowserLocator)\n : null;\n }\n if (candidate.by === \"css\" || candidate.by === \"ref\" || candidate.by === \"testId\") {\n return exactKeys(candidate, [\"by\", \"value\"]) && typeof candidate.value === \"string\" &&\n candidate.value.length > 0 && candidate.value.length <= 2_000\n ? { by: candidate.by, value: candidate.value }\n : null;\n }\n if (candidate.by === \"role\") {\n if (!exactKeys(candidate, [\"by\", \"role\", \"name\", \"exact\"]) ||\n typeof candidate.role !== \"string\" || !candidate.role ||\n (candidate.name !== undefined && typeof candidate.name !== \"string\") ||\n (candidate.exact !== undefined && typeof candidate.exact !== \"boolean\")) return null;\n return {\n by: \"role\",\n role: candidate.role,\n ...(typeof candidate.name === \"string\" ? { name: candidate.name } : {}),\n ...(typeof candidate.exact === \"boolean\" ? { exact: candidate.exact } : {}),\n };\n }\n if (candidate.by === \"text\") {\n if (!exactKeys(candidate, [\"by\", \"text\", \"exact\"]) ||\n typeof candidate.text !== \"string\" || !candidate.text ||\n (candidate.exact !== undefined && typeof candidate.exact !== \"boolean\")) return null;\n return {\n by: \"text\",\n text: candidate.text,\n ...(typeof candidate.exact === \"boolean\" ? { exact: candidate.exact } : {}),\n };\n }\n return null;\n}\n\nfunction parseTargetInput(\n value: unknown,\n options: { locatorRequired: boolean; value?: boolean; key?: boolean; wait?: boolean; values?: boolean },\n): Record<string, unknown> | null {\n const candidate = record(value);\n if (!candidate) return null;\n const allowed = [\"page\", \"locator\", \"index\", \"expectedRevision\"];\n if (options.value) allowed.push(\"value\");\n if (options.values) allowed.push(\"values\");\n if (options.key) allowed.push(\"key\");\n if (options.wait) allowed.push(\"state\", \"timeout\");\n if (!exactKeys(candidate, allowed)) return null;\n const page = parsePage(candidate.page);\n const locator = candidate.locator === undefined ? undefined : parseBrowserLocator(candidate.locator);\n const index = candidate.index;\n const revision = candidate.expectedRevision;\n if (page === null || (options.locatorRequired && !locator) ||\n (candidate.locator !== undefined && !locator) ||\n (index !== undefined && (!Number.isInteger(index) || (index as number) < 0)) ||\n (revision !== undefined && (!Number.isInteger(revision) || (revision as number) < 0)) ||\n (options.value && typeof candidate.value !== \"string\") ||\n (options.values && (!Array.isArray(candidate.values) ||\n !candidate.values.every((item) => typeof item === \"string\"))) ||\n (options.key && (typeof candidate.key !== \"string\" || !candidate.key || candidate.key.length > 100)) ||\n (options.wait && candidate.state !== undefined &&\n candidate.state !== \"attached\" && candidate.state !== \"visible\") ||\n (options.wait && candidate.timeout !== undefined &&\n (typeof candidate.timeout !== \"number\" || candidate.timeout < 0 || candidate.timeout > 30_000))) return null;\n return {\n ...(page ? { page } : {}),\n ...(locator ? { locator } : {}),\n ...(typeof index === \"number\" ? { index } : {}),\n ...(typeof revision === \"number\" ? { expectedRevision: revision } : {}),\n ...(options.value ? { value: candidate.value } : {}),\n ...(options.values ? { values: candidate.values } : {}),\n ...(options.key ? { key: candidate.key } : {}),\n ...(options.wait && candidate.state ? { state: candidate.state } : {}),\n ...(options.wait && typeof candidate.timeout === \"number\" ? { timeout: candidate.timeout } : {}),\n };\n}\n\nfunction parseBrowserOperationInput(operation: BrowserOperationName, value: unknown): Record<string, unknown> | null {\n const candidate = record(value);\n if (!candidate) return null;\n if (operation === \"browser.status\") return exactKeys(candidate, []) ? {} : null;\n if (operation === \"browser.snapshot\") {\n const page = parsePage(candidate.page);\n const locator = candidate.locator === undefined ? undefined : parseBrowserLocator(candidate.locator);\n return exactKeys(candidate, [\"page\", \"locator\"]) && page !== null &&\n (candidate.locator === undefined || locator !== null)\n ? { ...(page ? { page } : {}), ...(locator ? { locator } : {}) }\n : null;\n }\n if (operation === \"browser.query\" || operation === \"browser.click\" ||\n operation === \"browser.hover\" || operation === \"browser.focus\" ||\n operation === \"browser.check\" || operation === \"browser.uncheck\") {\n return parseTargetInput(candidate, { locatorRequired: true });\n }\n if (operation === \"browser.wait\")\n return parseTargetInput(candidate, { locatorRequired: true, wait: true });\n if (operation === \"browser.fill\")\n return parseTargetInput(candidate, { locatorRequired: true, value: true });\n if (operation === \"browser.select\")\n return parseTargetInput(candidate, { locatorRequired: true, values: true });\n if (operation === \"browser.press\")\n return parseTargetInput(candidate, { locatorRequired: false, key: true });\n if (operation === \"browser.script\") {\n const page = parsePage(candidate.page);\n const { source, args, timeout } = candidate;\n return exactKeys(candidate, [\"page\", \"source\", \"args\", \"timeout\"]) && page !== null &&\n typeof source === \"string\" && source.length > 0 && source.length <= 100_000 &&\n (args === undefined || (typeof args === \"object\" && args !== null && !Array.isArray(args))) &&\n (timeout === undefined || (typeof timeout === \"number\" && timeout >= 0 && timeout <= 120_000))\n ? {\n ...(page ? { page } : {}),\n source,\n ...(args !== undefined ? { args } : {}),\n ...(typeof timeout === \"number\" ? { timeout } : {}),\n }\n : null;\n }\n if (operation === \"browser.box\") return parseTargetInput(candidate, { locatorRequired: true });\n if (operation === \"browser.mouse\") {\n const page = parsePage(candidate.page);\n const { action, x, y, deltaX, deltaY } = candidate;\n const point = (value: unknown): boolean => typeof value === \"number\" && Number.isFinite(value);\n const needsPoint = action === \"move\" || action === \"click\";\n return exactKeys(candidate, [\"page\", \"action\", \"x\", \"y\", \"deltaX\", \"deltaY\"]) && page !== null &&\n (action === \"move\" || action === \"down\" || action === \"up\" || action === \"click\") &&\n (!needsPoint || (point(x) && point(y))) &&\n deltaX === undefined && deltaY === undefined\n ? { ...(page ? { page } : {}), action, ...(point(x) ? { x } : {}), ...(point(y) ? { y } : {}) }\n : null;\n }\n if (operation === \"browser.wheel\") {\n const page = parsePage(candidate.page);\n const { deltaX, deltaY } = candidate;\n return exactKeys(candidate, [\"page\", \"deltaX\", \"deltaY\"]) && page !== null &&\n (deltaX === undefined || typeof deltaX === \"number\") &&\n (deltaY === undefined || typeof deltaY === \"number\")\n ? {\n ...(page ? { page } : {}),\n ...(typeof deltaX === \"number\" ? { deltaX } : {}),\n ...(typeof deltaY === \"number\" ? { deltaY } : {}),\n }\n : null;\n }\n if (operation === \"browser.drag\") {\n const page = parsePage(candidate.page);\n const { from, to, steps } = candidate;\n const endpoint = (value: unknown): boolean => {\n if (!value || typeof value !== \"object\") return false;\n const record = value as Record<string, unknown>;\n if (record.locator !== undefined) return parseBrowserLocator(record.locator) !== null && exactKeys(record, [\"locator\"]);\n return typeof record.x === \"number\" && typeof record.y === \"number\" && exactKeys(record, [\"x\", \"y\"]);\n };\n return exactKeys(candidate, [\"page\", \"from\", \"to\", \"steps\"]) && page !== null &&\n endpoint(from) && endpoint(to) &&\n (steps === undefined || (Number.isInteger(steps) && (steps as number) >= 1 && (steps as number) <= 100))\n ? { ...(page ? { page } : {}), from, to, ...(typeof steps === \"number\" ? { steps } : {}) }\n : null;\n }\n if (operation === \"browser.scroll\") {\n const page = parsePage(candidate.page);\n const { direction, amount, expectedRevision } = candidate;\n return exactKeys(candidate, [\"page\", \"direction\", \"amount\", \"expectedRevision\"]) && page !== null &&\n (direction === \"up\" || direction === \"down\" || direction === \"left\" || direction === \"right\") &&\n (amount === undefined || (typeof amount === \"number\" && amount >= 1 && amount <= 10_000)) &&\n (expectedRevision === undefined || (Number.isInteger(expectedRevision) && (expectedRevision as number) >= 0))\n ? {\n ...(page ? { page } : {}), direction,\n ...(typeof amount === \"number\" ? { amount } : {}),\n ...(typeof expectedRevision === \"number\" ? { expectedRevision } : {}),\n }\n : null;\n }\n return parseTargetInput(candidate, { locatorRequired: false });\n}\n\nexport function parseBrowserOperationCall(value: unknown): BrowserOperationCall | null {\n const candidate = record(value);\n if (!candidate || candidate.protocol !== SUPERCODE_BROWSER_OPERATION_PROTOCOL ||\n typeof candidate.operation !== \"string\" || !OPERATION_NAMES.has(candidate.operation as BrowserOperationName)) return null;\n const operation = candidate.operation as BrowserOperationName;\n const input = parseBrowserOperationInput(operation, candidate.input);\n return input === null ? null : { protocol: SUPERCODE_BROWSER_OPERATION_PROTOCOL, operation, input };\n}\n\nexport function parseBrowserOperationResult(value: unknown): BrowserOperationResult | null {\n const candidate = record(value);\n if (!candidate || typeof candidate.ok !== \"boolean\" ||\n typeof candidate.operation !== \"string\" || !OPERATION_NAMES.has(candidate.operation as BrowserOperationName)) return null;\n const operation = candidate.operation as BrowserOperationName;\n const targetCandidate = record(candidate.target);\n const target = targetCandidate &&\n (targetCandidate.page === undefined || typeof targetCandidate.page === \"string\") &&\n typeof targetCandidate.url === \"string\" && typeof targetCandidate.title === \"string\" &&\n Number.isInteger(targetCandidate.revision)\n ? {\n ...(typeof targetCandidate.page === \"string\" ? { page: targetCandidate.page } : {}),\n url: targetCandidate.url,\n title: targetCandidate.title,\n revision: targetCandidate.revision as number,\n }\n : null;\n if (candidate.ok) return target ? { ok: true, operation, target, value: candidate.value } : null;\n const error = record(candidate.error);\n const codes = new Set<BrowserOperationErrorCode>([\n \"APPROVAL_REQUIRED\", \"INVALID_INPUT\", \"NOT_AVAILABLE\", \"NOT_FOUND\",\n \"STALE_PAGE\", \"TIMED_OUT\", \"UNSUPPORTED\", \"FAILED\",\n ]);\n if (!error || typeof error.code !== \"string\" || !codes.has(error.code as BrowserOperationErrorCode) ||\n typeof error.message !== \"string\") return null;\n return {\n ok: false,\n operation,\n error: { code: error.code as BrowserOperationErrorCode, message: error.message },\n ...(target ? { target } : {}),\n };\n}\n", "/**\n * The provider: one Playwright connection over CDP, one page, and the\n * `supercode/browser-provider-v1` envelope around each operation call.\n */\n\nimport { timingSafeEqual } from \"node:crypto\";\nimport { chromium, type Browser, type Page } from \"playwright-core\";\nimport {\n SUPERCODE_BROWSER_OPERATION_PROTOCOL,\n SUPERCODE_BROWSER_PROVIDER_PROTOCOL,\n type BrowserOperationName,\n type BrowserOperationResult,\n} from \"./protocol.js\";\nimport { PlaywrightOperationExecutor } from \"./executor.js\";\n\n/** Bound for one provider request (`BROWSER_PROVIDER_MAX_REQUEST_BYTES`). */\nexport const MAX_REQUEST_BYTES = 256 * 1024;\n/** Bound for one provider response (`BROWSER_PROVIDER_MAX_RESPONSE_BYTES`). */\nexport const MAX_RESPONSE_BYTES = 1024 * 1024;\n\nexport interface PlaywrightBrowserProviderOptions {\n /** CDP endpoint: `http://\u2026` (resolved through `/json/version`) or `ws://\u2026`. */\n cdpUrl: string;\n /** Hex token every request must carry. */\n token: string;\n /** True when the endpoint dispatches `isTrusted:false` input (an AlmostCDP endpoint). */\n syntheticEvents: boolean;\n}\n\n/** The provider-v1 response envelope the harness reads. */\nexport interface ProviderResponse {\n protocol: typeof SUPERCODE_BROWSER_PROVIDER_PROTOCOL;\n id: string | null;\n result: BrowserOperationResult;\n}\n\nexport interface PlaywrightBrowserProvider {\n readonly token: string;\n /** Validate one provider-v1 request and answer it with a provider-v1 response. */\n handle(request: unknown): Promise<ProviderResponse>;\n /** Disconnect from the endpoint. The browser itself is left running. */\n close(): Promise<void>;\n}\n\ninterface Connection {\n browser: Browser;\n page: Page;\n executor: PlaywrightOperationExecutor;\n}\n\nfunction record(value: unknown): Record<string, unknown> | null {\n return typeof value === \"object\" && value !== null && !Array.isArray(value) ? value as Record<string, unknown> : null;\n}\n\nfunction tokenMatches(expected: string, actual: unknown): boolean {\n if (typeof actual !== \"string\") return false;\n const left = Buffer.from(expected);\n const right = Buffer.from(actual);\n return left.length === right.length && timingSafeEqual(left, right);\n}\n\nfunction callOperation(call: unknown): BrowserOperationName {\n const operation = record(call)?.operation;\n return typeof operation === \"string\" && operation.startsWith(\"browser.\") ? operation as BrowserOperationName : \"browser.status\";\n}\n\nexport function createPlaywrightBrowserProvider(options: PlaywrightBrowserProviderOptions): PlaywrightBrowserProvider {\n if (!/^[0-9a-f]{32,}$/i.test(options.token))\n throw new Error(\"The provider token must be at least 32 hexadecimal characters.\");\n let connection: Connection | null = null;\n let queue: Promise<unknown> = Promise.resolve();\n\n const usable = (candidate: Connection | null): candidate is Connection =>\n candidate !== null && candidate.browser.isConnected() && !candidate.page.isClosed();\n\n const connect = async (): Promise<Connection> => {\n const previous = connection;\n connection = null;\n // The provider is attached to a browser it does not own: it changes none\n // of that browser's defaults (download policy, focus emulation, media).\n const browser = previous?.browser.isConnected() ? previous.browser : await chromium.connectOverCDP(options.cdpUrl, { noDefaults: true });\n const page = browser.contexts()[0]?.pages()[0];\n if (!page) {\n if (browser !== previous?.browser) await browser.close().catch(() => undefined);\n throw new Error(\"The browser has no open page.\");\n }\n const executor = new PlaywrightOperationExecutor(page, {\n syntheticEvents: options.syntheticEvents,\n endpoint: browser.version(),\n });\n connection = { browser, page, executor };\n return connection;\n };\n\n const failure = (operation: BrowserOperationName, code: \"INVALID_INPUT\" | \"NOT_AVAILABLE\", message: string): BrowserOperationResult =>\n ({ ok: false, operation, error: { code, message } });\n\n const run = async (call: unknown): Promise<BrowserOperationResult> => {\n let current = connection;\n if (!usable(current)) {\n // One reconnect per call; a second failure is the answer.\n try {\n current = await connect();\n } catch (error) {\n return failure(callOperation(call), \"NOT_AVAILABLE\",\n `The CDP endpoint is not available: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n return current.executor.execute(call);\n };\n\n return {\n token: options.token,\n async handle(request: unknown): Promise<ProviderResponse> {\n const envelope = record(request);\n const id = typeof envelope?.id === \"string\" && envelope.id.length > 0 && envelope.id.length <= 256 ? envelope.id : null;\n const respond = (result: BrowserOperationResult): ProviderResponse =>\n ({ protocol: SUPERCODE_BROWSER_PROVIDER_PROTOCOL, id, result });\n const call = envelope?.call;\n const operation = callOperation(call);\n if (!envelope || envelope.protocol !== SUPERCODE_BROWSER_PROVIDER_PROTOCOL || id === null ||\n record(call)?.protocol !== SUPERCODE_BROWSER_OPERATION_PROTOCOL)\n return respond(failure(operation, \"INVALID_INPUT\", \"Invalid browser provider request envelope.\"));\n if (!tokenMatches(options.token, envelope.token))\n return respond(failure(operation, \"INVALID_INPUT\", \"Invalid browser provider token.\"));\n // One page, one caller at a time: operations never interleave on it.\n const result = queue.then(() => run(call));\n queue = result.catch(() => undefined);\n return respond(await result);\n },\n async close(): Promise<void> {\n const current = connection;\n connection = null;\n // For a CDP connection `close()` closes the websocket, not the browser.\n await current?.browser.close().catch(() => undefined);\n },\n };\n}\n", "/**\n * Two framings of the same provider-v1 envelope.\n *\n * - TCP (the harness's wire, `crates/harness/src/browser.rs`): one\n * newline-terminated JSON request per connection, one JSON response, close.\n * Discovery is an owner-only record under `<providers dir>/browser/<id>.json`.\n * - HTTP: `POST /` with the request JSON as the body, the response JSON as the\n * body, for a host that can reach the provider only by HTTP.\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport * as fs from \"node:fs\";\nimport * as http from \"node:http\";\nimport * as net from \"node:net\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport { SUPERCODE_BROWSER_PROVIDER_PROTOCOL } from \"./protocol.js\";\nimport { PLAYWRIGHT_IMPLEMENTATION } from \"./executor.js\";\nimport {\n MAX_REQUEST_BYTES,\n MAX_RESPONSE_BYTES,\n type PlaywrightBrowserProvider,\n type ProviderResponse,\n} from \"./provider.js\";\n\nconst HOST = \"127.0.0.1\";\n\nexport interface ServeHandle {\n framing: \"tcp\" | \"http\";\n port: number;\n /** The discovery record written for the TCP framing. */\n discoveryPath?: string;\n stop(): Promise<void>;\n}\n\n/** Supercode's providers directory, resolved as `browser_provider_directory()` resolves its parent. */\nexport function defaultProvidersDirectory(): string {\n const env = process.env;\n const root = env.SUPERCODE_HOME ? env.SUPERCODE_HOME\n : env.XDG_CONFIG_HOME ? path.join(env.XDG_CONFIG_HOME, \"supercode\")\n : env.HOME ? path.join(env.HOME, \".config\", \"supercode\")\n : path.join(os.tmpdir(), \"supercode\");\n return path.join(root, \"providers\");\n}\n\nfunction invalid(id: string | null, message: string): ProviderResponse {\n return {\n protocol: SUPERCODE_BROWSER_PROVIDER_PROTOCOL,\n id,\n result: { ok: false, operation: \"browser.status\", error: { code: \"INVALID_INPUT\", message } },\n };\n}\n\n/** Serialize a response inside the 1 MiB bound, replacing an oversized result with a bounded failure. */\nfunction encode(response: ProviderResponse): string {\n const text = JSON.stringify(response);\n if (Buffer.byteLength(text) <= MAX_RESPONSE_BYTES) return text;\n return JSON.stringify({\n ...response,\n result: {\n ok: false,\n operation: response.result.operation,\n error: { code: \"FAILED\", message: \"The operation result exceeds the provider's 1 MiB response bound.\" },\n },\n });\n}\n\nasync function answer(provider: PlaywrightBrowserProvider, body: string): Promise<ProviderResponse> {\n let request: unknown;\n try {\n request = JSON.parse(body);\n } catch {\n return invalid(null, \"The request is not JSON.\");\n }\n return provider.handle(request);\n}\n\nexport interface TcpServeOptions {\n port: number;\n /** Parent of `browser/`; defaults to Supercode's providers directory. */\n providersDirectory?: string;\n /** Workspace the discovery record is scoped to; defaults to the working directory. */\n workspace?: string;\n syntheticEvents: boolean;\n}\n\nexport async function serveTcp(provider: PlaywrightBrowserProvider, options: TcpServeOptions): Promise<ServeHandle> {\n const server = net.createServer((socket) => {\n const chunks: Buffer[] = [];\n let size = 0;\n let done = false;\n const finish = (response: ProviderResponse): void => {\n if (socket.destroyed) return;\n socket.end(`${encode(response)}\\n`);\n };\n socket.setTimeout(15_000, () => socket.destroy());\n socket.on(\"error\", () => socket.destroy());\n socket.on(\"data\", (chunk: Buffer) => {\n if (done) return;\n const newline = chunk.indexOf(0x0a);\n const part = newline === -1 ? chunk : chunk.subarray(0, newline);\n size += part.length + (newline === -1 ? 0 : 1);\n if (size > MAX_REQUEST_BYTES) {\n done = true;\n finish(invalid(null, \"The request exceeds 256 KiB.\"));\n return;\n }\n chunks.push(part);\n if (newline === -1) return;\n done = true;\n void answer(provider, Buffer.concat(chunks).toString(\"utf8\")).then(finish, (error: unknown) =>\n finish(invalid(null, error instanceof Error ? error.message : String(error))));\n });\n socket.on(\"end\", () => {\n if (done) return;\n done = true;\n // A request without its newline is still one request.\n void answer(provider, Buffer.concat(chunks).toString(\"utf8\")).then(finish, () => socket.destroy());\n });\n });\n await new Promise<void>((resolve, reject) => {\n server.once(\"error\", reject);\n server.listen(options.port, HOST, () => { server.off(\"error\", reject); resolve(); });\n });\n const port = (server.address() as net.AddressInfo).port;\n\n const directory = path.join(options.providersDirectory ?? defaultProvidersDirectory(), \"browser\");\n fs.mkdirSync(directory, { recursive: true, mode: 0o700 });\n fs.chmodSync(directory, 0o700);\n const id = `playwright.cdp.${port}`;\n const discoveryPath = path.join(directory, `${id}.json`);\n const workspace = fs.realpathSync(options.workspace ?? process.cwd());\n const discovery = {\n protocol: SUPERCODE_BROWSER_PROVIDER_PROTOCOL,\n workspace,\n host: HOST,\n port,\n token: provider.token,\n provider: {\n id,\n name: \"Playwright over CDP\",\n fidelity: {\n implementation: PLAYWRIGHT_IMPLEMENTATION,\n transport: \"cdp\",\n accessibility: \"playwright-aria-snapshot\",\n syntheticEvents: options.syntheticEvents,\n trustedInput: !options.syntheticEvents,\n script: \"node-playwright-page\",\n },\n },\n };\n const temporary = `${discoveryPath}.${randomBytes(6).toString(\"hex\")}.tmp`;\n fs.writeFileSync(temporary, `${JSON.stringify(discovery, null, 2)}\\n`, { mode: 0o600, flag: \"wx\" });\n fs.renameSync(temporary, discoveryPath);\n\n return {\n framing: \"tcp\",\n port,\n discoveryPath,\n async stop(): Promise<void> {\n fs.rmSync(discoveryPath, { force: true });\n await new Promise<void>((resolve) => server.close(() => resolve()));\n },\n };\n}\n\nexport interface HttpServeOptions {\n port: number;\n}\n\nexport async function serveHttp(provider: PlaywrightBrowserProvider, options: HttpServeOptions): Promise<ServeHandle> {\n const server = http.createServer((request, response) => {\n const send = (status: number, body?: string): void => {\n response.writeHead(status, body === undefined ? {} : { \"content-type\": \"application/json\" });\n response.end(body);\n };\n const pathname = (request.url ?? \"/\").split(\"?\", 1)[0];\n if (pathname !== \"/\") { request.resume(); send(404); return; }\n if (request.method !== \"POST\") { request.resume(); response.setHeader(\"allow\", \"POST\"); send(405); return; }\n const chunks: Buffer[] = [];\n let size = 0;\n let rejected = false;\n request.on(\"data\", (chunk: Buffer) => {\n if (rejected) return;\n size += chunk.length;\n if (size > MAX_REQUEST_BYTES) {\n rejected = true;\n send(413, encode(invalid(null, \"The request exceeds 256 KiB.\")));\n request.destroy();\n return;\n }\n chunks.push(chunk);\n });\n request.on(\"end\", () => {\n if (rejected) return;\n let body: unknown;\n try {\n body = JSON.parse(Buffer.concat(chunks).toString(\"utf8\"));\n } catch {\n send(400, encode(invalid(null, \"The request is not JSON.\")));\n return;\n }\n void provider.handle(body).then(\n (result) => send(200, encode(result)),\n (error: unknown) => send(500, encode(invalid(null, error instanceof Error ? error.message : String(error)))),\n );\n });\n });\n await new Promise<void>((resolve, reject) => {\n server.once(\"error\", reject);\n server.listen(options.port, HOST, () => { server.off(\"error\", reject); resolve(); });\n });\n const port = (server.address() as net.AddressInfo).port;\n return {\n framing: \"http\",\n port,\n async stop(): Promise<void> {\n await new Promise<void>((resolve) => server.close(() => resolve()));\n },\n };\n}\n", "/**\n * `supercode-browser-playwright --cdp-url <url>\n * (--tcp <port> [--providers-dir <dir>] [--workspace <path>] | --http <port>)\n * [--token <hex>] [--synthetic-events]`\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport { parseArgs } from \"node:util\";\nimport { createPlaywrightBrowserProvider } from \"./provider.js\";\nimport { serveHttp, serveTcp, type ServeHandle } from \"./serve.js\";\n\nconst USAGE = \"usage: supercode-browser-playwright --cdp-url <url> \" +\n \"(--tcp <port> [--providers-dir <dir>] [--workspace <path>] | --http <port>) \" +\n \"[--token <hex>] [--synthetic-events]\";\n\nfunction port(value: string, flag: string): number {\n const parsed = Number(value);\n if (!/^\\d+$/.test(value) || parsed > 65_535) throw new Error(`${flag} must be a port number (0 picks a free one).`);\n return parsed;\n}\n\nexport async function main(argv: readonly string[]): Promise<ServeHandle> {\n const { values } = parseArgs({\n args: [...argv],\n strict: true,\n allowPositionals: false,\n options: {\n \"cdp-url\": { type: \"string\" },\n tcp: { type: \"string\" },\n http: { type: \"string\" },\n \"providers-dir\": { type: \"string\" },\n workspace: { type: \"string\" },\n token: { type: \"string\" },\n \"synthetic-events\": { type: \"boolean\", default: false },\n },\n });\n const cdpUrl = values[\"cdp-url\"];\n if (!cdpUrl) throw new Error(`--cdp-url is required.\\n${USAGE}`);\n if ((values.tcp === undefined) === (values.http === undefined))\n throw new Error(`Exactly one of --tcp and --http is required.\\n${USAGE}`);\n if (values.http !== undefined && (values[\"providers-dir\"] !== undefined || values.workspace !== undefined))\n throw new Error(`--providers-dir and --workspace belong to the TCP framing.\\n${USAGE}`);\n if (values.http !== undefined && values.token === undefined)\n throw new Error(\"--http requires --token: the host that calls the provider passes it.\");\n const token = values.token ?? randomBytes(32).toString(\"hex\");\n const syntheticEvents = values[\"synthetic-events\"] ?? false;\n const provider = createPlaywrightBrowserProvider({ cdpUrl, token, syntheticEvents });\n const handle = values.tcp !== undefined\n ? await serveTcp(provider, {\n port: port(values.tcp, \"--tcp\"),\n syntheticEvents,\n ...(values[\"providers-dir\"] !== undefined ? { providersDirectory: values[\"providers-dir\"] } : {}),\n ...(values.workspace !== undefined ? { workspace: values.workspace } : {}),\n })\n : await serveHttp(provider, { port: port(values.http!, \"--http\") });\n process.stdout.write(`${JSON.stringify({ listening: { framing: handle.framing, port: handle.port } })}\\n`);\n let stopping = false;\n const stop = (): void => {\n if (stopping) return;\n stopping = true;\n void Promise.allSettled([handle.stop(), provider.close()]).then(() => process.exit(0));\n };\n process.once(\"SIGINT\", stop);\n process.once(\"SIGTERM\", stop);\n process.once(\"SIGHUP\", stop);\n return handle;\n}\n"],
|
|
5
|
-
"mappings": ";AAOA,SAAS,cAA2D;;;ACuC7D,IAAM,qBAAN,cAAiC,MAAM;AAAC;AAGxC,IAAM,oBAAN,cAAgC,MAAM;AAAC;AAE9C,IAAM,QAAQ;AACd,IAAM,QAAQ;AACd,IAAM,YAAY;AAClB,IAAM,gBAAgB;AAWtB,SAAS,YAAY,OAAkC;AACrD,QAAM,SAAS,CAAC,YAA8B;AAC5C,QAAI,CAAC,MAAM,KAAM,QAAO;AACxB,aAAS,OAAuB,SAAS,QAAQ;AAC/C,UAAI,KAAK,QAAQ,MAAM,IAAI,EAAG,QAAO;AAC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GAAG,KAAK,UAAU,EAAE,WAAW,EAAE,SAAS,OAAO,SAAS,MAAM,OAAO,KAAK,EAAE,CAAC,CAAC;AAAA,CAAI;AACzG,MAAI,WAAW;AACf,QAAM,OAAO,MAAY;AACvB,QAAI,SAAU;AACd,eAAW;AACX,SAAK,QAAQ,WAAW,CAAC,OAAO,KAAK,GAAG,SAAS,MAAM,CAAC,CAAC,EAAE,KAAK,MAAM,QAAQ,KAAK,CAAC,CAAC;AAAA,EACvF;AACA,UAAQ,KAAK,UAAU,IAAI;AAC3B,UAAQ,KAAK,WAAW,IAAI;AAC5B,UAAQ,KAAK,UAAU,IAAI;AAC3B,SAAO;AACT;",
|
|
6
|
-
"names": ["value", "record", "node", "locator", "timeout", "
|
|
3
|
+
"sources": ["../src/executor.ts", "../src/guard.ts", "../src/script-scope.ts", "../src/protocol.ts", "../src/provider.ts", "../src/serve.ts", "../src/cli.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * Supercode's `supercode/browser-operation-v1` calls over a real Playwright\n * `Page`: every locator, action and snapshot is playwright-core's own, driven\n * over CDP. No Node API is used, so the executor also runs in a browser realm\n * with a browser build of playwright-core (`@volter/almostcdp/playwright`).\n */\n\nimport { errors, type ElementHandle, type Locator, type Page } from \"playwright-core\";\nimport {\n BrowserSideTargets,\n DocumentChanged,\n HostElementTarget,\n UnidentifiedTarget,\n type DocumentState,\n type GuardedTarget,\n} from \"./guard.js\";\nimport { ScriptScope } from \"./script-scope.js\";\nimport {\n BROWSER_OPERATION_NAMES,\n BrowserActionRefusal,\n parseBrowserOperationCall,\n type BrowserLocator,\n type BrowserOperationCall,\n type BrowserOperationErrorCode,\n type BrowserOperationName,\n type BrowserOperationResult,\n type BrowserTarget,\n type ElementInspection,\n} from \"./protocol.js\";\n\n/** The implementation this provider reports; the pinned playwright-core. */\nexport const PLAYWRIGHT_IMPLEMENTATION = \"playwright-core 1.63.0\";\n/** The harness abandons a provider call at 12 s; a script must end before that. */\nexport const SCRIPT_TIMEOUT_CLAMP_MS = 9_000;\n/** Actionability budget for one locator action. */\nexport const ACTION_TIMEOUT_MS = 5_000;\n/** `browser.wait` accepts 30 s on the wire; the harness deadline caps what can be honoured. */\nexport const WAIT_TIMEOUT_CLAMP_MS = 9_000;\n\n/** The Playwright features `browser.status` reports. */\nexport const PLAYWRIGHT_FEATURES: readonly string[] = Object.freeze([\n \"page.ariaSnapshot\",\n \"page.keyboard\",\n \"page.navigation.history\",\n \"locator.css\",\n \"locator.ref\",\n \"locator.role\",\n \"locator.text\",\n \"locator.testId\",\n \"locator.label\",\n \"locator.placeholder\",\n \"locator.altText\",\n \"locator.title\",\n \"locator.first\",\n \"locator.nth\",\n \"locator.count\",\n \"locator.waitFor\",\n \"locator.textContent\",\n \"locator.inputValue\",\n \"locator.getAttribute\",\n \"locator.isVisible\",\n \"locator.click\",\n \"locator.fill\",\n \"locator.press\",\n \"locator.hover\",\n \"locator.focus\",\n \"locator.check\",\n \"locator.uncheck\",\n \"locator.selectOption\",\n \"locator.boundingBox\",\n \"locator.dragTo\",\n \"page.mouse\",\n \"page.mouse.wheel\",\n \"page.on.console\",\n \"page.on.pageerror\",\n \"page.consoleMessages\",\n \"page.pageErrors\",\n \"page.screenshot.png\",\n \"page.evaluate\",\n]);\n\nexport interface PlaywrightOperationExecutorOptions {\n /** True when the endpoint dispatches `isTrusted:false` input (an AlmostCDP endpoint); false for native Chrome. */\n syntheticEvents: boolean;\n /** `browser.version()` of the connected endpoint, reported by `browser.status`. */\n endpoint: string;\n /**\n * The host's policy for one action, asked before it runs: each locator\n * action, each coordinate action (`browser.mouse`, `browser.drag`,\n * `browser.wheel`), and each `browser.script` before its source is\n * compiled. An element action's target is resolved once, described from the\n * browser side (see `GuardedTarget`), and the action then runs on that same\n * element. A target that cannot be resolved or described refuses the\n * operation without asking. Throwing a `BrowserActionRefusal` refuses the\n * operation with that code.\n */\n actionGuard?: (action: PlaywrightAction) => void | Promise<void>;\n /**\n * A CSS selector for the host's own elements: `browser.snapshot` leaves out\n * every matching element's nodes (Playwright's selector, which pierces open\n * shadow roots), and a coordinate action that lands on one is refused. The\n * page itself is not changed, so what assistive technology reads stays the\n * same.\n */\n snapshotExclude?: string;\n /**\n * The host's last check just before input is dispatched to the page, after\n * the executor has confirmed the main frame still holds the checked\n * document with no navigation in flight. `url` is the page URL the action\n * was checked on. Throwing a `BrowserActionRefusal` refuses the action; no\n * input has been sent.\n */\n beforeInput?: (checked: { url: string }) => void | Promise<void>;\n}\n\n/** One action an operation is about to perform. */\nexport type PlaywrightAction = PlaywrightElementAction | PlaywrightPageAction | PlaywrightScriptAction;\n\n/** An action on the page as a whole: history navigation, reload, scrolling. */\nexport interface PlaywrightPageAction {\n action: \"back\" | \"forward\" | \"reload\" | \"scroll\";\n /** The page's URL when the action was asked about. */\n url: string;\n value?: unknown;\n}\n\nexport type { GuardedNode, GuardedTarget } from \"./guard.js\";\n\n/** An action that lands on an element: by locator, or at a viewport point. */\nexport interface PlaywrightElementAction {\n action: \"click\" | \"fill\" | \"press\" | \"hover\" | \"focus\" | \"check\" | \"uncheck\" | \"select\" | \"drag\"\n | \"mousedown\" | \"mouseup\" | \"wheel\";\n /** What the action lands on, described from the browser side. */\n target: GuardedTarget;\n value?: unknown;\n /**\n * Raw pointer input (`browser.mouse` down/up/click, `browser.wheel`,\n * `browser.drag`): the target is the element at `target.point` as best\n * known, which a page can change between the look and the press.\n */\n pointer?: boolean;\n}\n\nexport interface PlaywrightScriptAction {\n /** `browser.script`: the author's source, run with the real `page`. */\n action: \"script\";\n source: string;\n args: Record<string, unknown>;\n}\n\n/** At most this many excluded elements are looked up per snapshot. */\nconst SNAPSHOT_EXCLUDE_LIMIT = 16;\n\n/** Every aria ref in an AI-mode JSON aria snapshot. */\nfunction collectRefs(nodes: unknown, into: Set<string>): void {\n if (Array.isArray(nodes)) {\n for (const node of nodes) collectRefs(node, into);\n return;\n }\n if (!nodes || typeof nodes !== \"object\") return;\n const node = nodes as { ref?: unknown; children?: unknown };\n if (typeof node.ref === \"string\") into.add(node.ref);\n collectRefs(node.children, into);\n}\n\n/**\n * An AI-mode aria snapshot's YAML without the nodes whose `[ref=\u2026]` is in\n * `refs`, their subtrees, and any ref-less node whose children all went with\n * them. A node is a `- ` line; its subtree is the lines indented under it.\n */\nexport function snapshotWithoutRefs(text: string, refs: ReadonlySet<string>): string {\n if (refs.size === 0) return text;\n interface Line { text: string; indent: number; children: Line[]; removed: boolean }\n const root: Line = { text: \"\", indent: -1, children: [], removed: false };\n const stack: Line[] = [root];\n const lines: Line[] = [];\n for (const raw of text.split(\"\\n\")) {\n const indent = raw.length - raw.trimStart().length;\n const line: Line = { text: raw, indent, children: [], removed: false };\n while (stack.length > 1 && stack[stack.length - 1]!.indent >= indent) stack.pop();\n stack[stack.length - 1]!.children.push(line);\n stack.push(line);\n lines.push(line);\n }\n const refOf = (line: Line): string | undefined => /\\[ref=([^\\]\\s]+)\\]/.exec(line.text)?.[1];\n const remove = (line: Line): void => {\n line.removed = true;\n for (const child of line.children) remove(child);\n };\n // Post-order: a node's children are decided before the node.\n const visit = (line: Line): void => {\n const ref = refOf(line);\n if (ref !== undefined && refs.has(ref)) {\n remove(line);\n return;\n }\n const before = line.children.length;\n for (const child of line.children) visit(child);\n if (line !== root && ref === undefined && before > 0 && line.children.every((child) => child.removed))\n line.removed = true;\n };\n visit(root);\n return lines.filter((line) => !line.removed).map((line) => line.text).join(\"\\n\");\n}\n\nconst REVISION_KEY = \"__supercodeBrowserRevision\";\n\n/**\n * Keeps a document-mutation counter on the page's main world. Installed as an\n * init script (every future document) and evaluated once (the current one).\n * Self-contained: Playwright serializes it into the page.\n */\nfunction installRevisionCounter(key: string): void {\n const scope = globalThis as unknown as Record<string, unknown>;\n if (typeof scope[key] === \"number\") return;\n scope[key] = 0;\n new MutationObserver(() => { scope[key] = (scope[key] as number) + 1; })\n .observe(document, { attributes: true, childList: true, characterData: true, subtree: true });\n}\n\n/**\n * `ElementInspection`'s fields except `ref`, computed in the page.\n * Self-contained: Playwright serializes it into the page.\n */\nfunction inspectInPage({ elements, limit }: { elements: Element[]; limit: number }): Array<Omit<ElementInspection, \"ref\">> {\n const normalize = (value: string): string => value.replace(/\\s+/g, \" \").trim();\n const implied = (element: Element): string | null => {\n const tag = element.tagName.toLowerCase();\n if (tag === \"button\") return \"button\";\n if (tag === \"a\" && element.hasAttribute(\"href\")) return \"link\";\n if (/^h[1-6]$/.test(tag)) return \"heading\";\n if (tag === \"textarea\") return \"textbox\";\n if (tag === \"select\") return \"combobox\";\n if (tag === \"option\") return \"option\";\n if (tag === \"img\") return \"img\";\n if (tag === \"ul\" || tag === \"ol\") return \"list\";\n if (tag === \"li\") return \"listitem\";\n if (tag === \"nav\") return \"navigation\";\n if (tag === \"main\") return \"main\";\n if (tag === \"form\") return \"form\";\n if (tag === \"input\") {\n const type = (element.getAttribute(\"type\") ?? \"text\").toLowerCase();\n if (type === \"button\" || type === \"submit\" || type === \"reset\") return \"button\";\n if (type === \"checkbox\") return \"checkbox\";\n if (type === \"radio\") return \"radio\";\n if (type === \"range\") return \"slider\";\n return \"textbox\";\n }\n return null;\n };\n const nameOf = (element: Element): string => {\n const aria = element.getAttribute(\"aria-label\");\n if (aria?.trim()) return normalize(aria);\n const ids = element.getAttribute(\"aria-labelledby\")?.split(/\\s+/).filter(Boolean) ?? [];\n const labelled = normalize(ids.map((id) => element.ownerDocument.getElementById(id)?.textContent ?? \"\").join(\" \"));\n if (labelled) return labelled;\n if (element instanceof HTMLInputElement && element.labels?.length) {\n const label = normalize(Array.from(element.labels).map((candidate) => candidate.textContent ?? \"\").join(\" \"));\n if (label) return label;\n }\n for (const attribute of [\"alt\", \"title\", \"placeholder\"]) {\n const value = element.getAttribute(attribute);\n if (value?.trim()) return normalize(value);\n }\n return normalize(element.textContent ?? \"\");\n };\n const visible = (element: Element): boolean => {\n if (element.getAttribute(\"aria-hidden\") === \"true\") return false;\n if (!(element instanceof HTMLElement)) return true;\n if (element.hidden) return false;\n const style = getComputedStyle(element);\n return style.display !== \"none\" && style.visibility !== \"hidden\" && style.opacity !== \"0\";\n };\n return elements.slice(0, limit).map((element) => {\n const role = element.getAttribute(\"role\")?.trim() || implied(element);\n const name = nameOf(element).slice(0, 500);\n const value = element instanceof HTMLInputElement\n ? (element.type === \"password\" ? \"<redacted>\" : element.value)\n : element instanceof HTMLTextAreaElement || element instanceof HTMLSelectElement ? element.value : undefined;\n const checked = element instanceof HTMLInputElement &&\n (element.type === \"checkbox\" || element.type === \"radio\") ? element.checked : undefined;\n return {\n tag: element.tagName.toLowerCase(),\n ...(role ? { role } : {}),\n ...(name ? { name } : {}),\n ...(value !== undefined ? { value: value.slice(0, 2_000) } : {}),\n disabled: (element instanceof HTMLButtonElement || element instanceof HTMLInputElement ||\n element instanceof HTMLSelectElement) && element.disabled,\n ...(checked !== undefined ? { checked } : {}),\n visible: visible(element),\n };\n });\n}\n\nfunction scrollInPage(delta: { left: number; top: number; amount: number | null }): { x: number; y: number } {\n const amount = delta.amount ?? Math.max(240, Math.round(window.innerHeight * 0.8));\n window.scrollBy({ left: delta.left * amount, top: delta.top * amount, behavior: \"instant\" });\n return { x: window.scrollX, y: window.scrollY };\n}\n\n/** A PNG's pixel size from its IHDR chunk. */\nfunction pngSize(bytes: Uint8Array): { width: number; height: number } | null {\n const signature = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];\n if (bytes.length < 24 || !signature.every((byte, index) => bytes[index] === byte)) return null;\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n return { width: view.getUint32(16), height: view.getUint32(20) };\n}\n\n/** Base64 of bytes without Node's Buffer. */\nfunction base64(bytes: Uint8Array): string {\n let binary = \"\";\n for (let offset = 0; offset < bytes.length; offset += 0x8000)\n binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000));\n return btoa(binary);\n}\n\n/**\n * Scripts return data, not live objects: keep the wire JSON-clean. Screenshot\n * bytes become a bounded image record rather than a JSON array of numbers.\n */\nfunction serializableValue(value: unknown, syntheticEvents: boolean): unknown {\n if (value === undefined) return null;\n const replacer = (_key: string, item: unknown): unknown => {\n const bytes = item instanceof Uint8Array ? item\n : item && typeof item === \"object\" && (item as { type?: unknown }).type === \"Buffer\" &&\n Array.isArray((item as { data?: unknown }).data) ? Uint8Array.from((item as { data: number[] }).data)\n : null;\n if (!bytes) return item;\n const size = pngSize(bytes);\n const encoded = base64(bytes);\n if (!size) return encoded;\n const dataUrl = `data:image/png;base64,${encoded}`;\n if (dataUrl.length > 768 * 1024) return { error: \"Screenshot exceeds the 768 KiB image record bound.\", width: size.width, height: size.height };\n return {\n dataUrl,\n format: \"png\",\n width: size.width,\n height: size.height,\n fidelity: syntheticEvents\n ? \"Pixels rasterized by the CDP endpoint's own renderer.\"\n : \"Native Chrome pixels captured over CDP.\",\n };\n };\n try {\n return JSON.parse(JSON.stringify(value, replacer));\n } catch {\n return String(value);\n }\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/** Map a Playwright failure onto the wire's error codes. */\nexport function classifyPlaywrightError(error: unknown): BrowserOperationErrorCode {\n if (error instanceof BrowserActionRefusal) return error.code;\n if (error instanceof errors.TimeoutError) return \"TIMED_OUT\";\n const message = errorMessage(error);\n if (/has been closed|Target closed|Target page, context or browser|Browser closed|browser has disconnected|Session closed|detached/i.test(message))\n return \"NOT_AVAILABLE\";\n if (/strict mode violation|resolved to 0 elements|no element matches|matched no element/i.test(message))\n return \"NOT_FOUND\";\n if (/unavailable|not supported/i.test(message)) return \"UNSUPPORTED\";\n return \"FAILED\";\n}\n\nexport class PlaywrightOperationExecutor {\n private readonly page: Page;\n private readonly options: PlaywrightOperationExecutorOptions;\n private readonly ready: Promise<void>;\n private readonly targets: BrowserSideTargets;\n /**\n * Where the mouse is: `page.mouse` keeps it, but does not report it. A\n * locator action moves it to the element's clickable point; it is then the\n * centre of that element's box as measured after the action, or unknown\n * (null) when that cannot be measured, and a press needs coordinates.\n */\n private mouse: { x: number; y: number } | null = { x: 0, y: 0 };\n\n constructor(page: Page, options: PlaywrightOperationExecutorOptions) {\n this.page = page;\n this.options = options;\n this.targets = new BrowserSideTargets(page, options.snapshotExclude ?? null);\n this.ready = (async () => {\n await page.addInitScript(installRevisionCounter, REVISION_KEY);\n await page.evaluate(installRevisionCounter, REVISION_KEY).catch(() => undefined);\n })();\n }\n\n async execute(raw: unknown): Promise<BrowserOperationResult> {\n const call = parseBrowserOperationCall(raw);\n const operation = operationName(raw);\n if (!call) return this.failure(operation, \"INVALID_INPUT\", \"Invalid browser operation request.\");\n try {\n await this.ready;\n return await this.executeCall(call);\n } catch (error) {\n return this.failure(call.operation, classifyPlaywrightError(error), errorMessage(error));\n }\n }\n\n private locator(value: unknown, index?: number): Locator {\n const locator = value as BrowserLocator;\n const exact = (candidate: { exact?: boolean }) => candidate.exact !== undefined ? { exact: candidate.exact } : {};\n const page = this.page;\n const base = locator.by === \"css\" ? page.locator(locator.value)\n // Refs are the `[ref=\u2026]` marks of an AI-mode aria snapshot, resolved by\n // Playwright's built-in `aria-ref` selector engine.\n : locator.by === \"ref\" ? page.locator(`aria-ref=${locator.value}`)\n : locator.by === \"role\" ? page.getByRole(locator.role as Parameters<Page[\"getByRole\"]>[0], {\n ...(locator.name !== undefined ? { name: locator.name } : {}),\n // A role's name matches exactly unless told otherwise.\n exact: locator.exact ?? true,\n })\n : locator.by === \"text\" ? page.getByText(locator.text, exact(locator))\n : locator.by === \"label\" ? page.getByLabel(locator.text, exact(locator))\n : locator.by === \"placeholder\" ? page.getByPlaceholder(locator.text, exact(locator))\n : locator.by === \"altText\" ? page.getByAltText(locator.text, exact(locator))\n : locator.by === \"title\" ? page.getByTitle(locator.text, exact(locator))\n : page.getByTestId(locator.value);\n return index === undefined ? base : index === 0 ? base.first() : base.nth(index);\n }\n\n /**\n * Playwright's `aria-ref` engine resolves against the last AI-mode snapshot\n * the page took. Refs are stable per element, so refreshing the whole-page\n * snapshot before resolving one keeps every ref from `browser.snapshot`\n * addressable even after an element-scoped snapshot replaced the map.\n */\n private async refreshRefs(value: unknown): Promise<void> {\n if ((value as BrowserLocator | undefined)?.by === \"ref\")\n await this.page.ariaSnapshot({ mode: \"ai\", timeout: ACTION_TIMEOUT_MS });\n }\n\n private async refOf(locator: Locator): Promise<string> {\n try {\n const nodes = await locator.ariaSnapshotJSON({ mode: \"ai\", depth: 1, timeout: ACTION_TIMEOUT_MS }) as unknown;\n const first = Array.isArray(nodes) ? nodes.find((node) => node && typeof node === \"object\") as { ref?: unknown } | undefined : undefined;\n return typeof first?.ref === \"string\" ? first.ref : \"\";\n } catch {\n return \"\";\n }\n }\n\n private async inspectAll(locator: Locator, limit: number): Promise<ElementInspection[]> {\n // Element handles, not `evaluateAll`: Playwright's `evaluateAll` resolves an\n // `aria-ref` locator in the main world, where the snapshot's refs are not\n // known, and finds nothing (measured with Playwright 1.63 on Chrome).\n const handles = (await locator.elementHandles()).slice(0, limit);\n let fields: Array<Omit<ElementInspection, \"ref\">>;\n try {\n const inspect = inspectInPage as unknown as (input: { elements: unknown[]; limit: number }) => Array<Omit<ElementInspection, \"ref\">>;\n fields = await this.page.evaluate(inspect, { elements: handles as unknown[], limit });\n } finally {\n await Promise.all(handles.map((handle) => handle.dispose().catch(() => undefined)));\n }\n const refs = await Promise.all(fields.map((_, index) => this.refOf(locator.nth(index))));\n return fields.map((field, index) => ({ ref: refs[index] ?? \"\", ...field }));\n }\n\n private async inspect(locator: Locator): Promise<ElementInspection> {\n const [inspection] = await this.inspectAll(locator.first(), 1);\n if (!inspection) throw new BrowserActionRefusal(\"NOT_FOUND\", \"The locator matched no element.\");\n return inspection;\n }\n\n /** Run a locator action; a failure on a locator that matches nothing is NOT_FOUND. */\n private async act<T>(locator: Locator, action: string, run: () => Promise<T>): Promise<T> {\n try {\n return await run();\n } catch (error) {\n if (!(error instanceof BrowserActionRefusal) && await locator.count().catch(() => 1) === 0)\n throw new BrowserActionRefusal(\"NOT_FOUND\", `${action} found no element for the locator.`);\n throw error;\n }\n }\n\n /**\n * Resolves the locator's element once (waiting up to the action budget),\n * asks the host's policy about it, and returns the handle the action must\n * use, so the element guarded is the element acted on. Without a policy the\n * action runs on the locator. Resolution or description failing refuses.\n */\n private async guarded(\n locator: Locator,\n action: PlaywrightElementAction[\"action\"],\n value?: unknown | ((target: GuardedTarget) => Promise<unknown>),\n ): Promise<{ handle: ElementHandle; target: GuardedTarget } | null> {\n const guard = this.options.actionGuard;\n if (!guard) return null;\n let handle: ElementHandle | null;\n try {\n handle = await locator.elementHandle({ timeout: ACTION_TIMEOUT_MS });\n } catch (error) {\n if (error instanceof errors.TimeoutError)\n throw new BrowserActionRefusal(\"NOT_FOUND\", `${action} found no element for the locator in ${ACTION_TIMEOUT_MS}ms.`);\n throw error;\n }\n if (!handle) throw new BrowserActionRefusal(\"NOT_FOUND\", `${action} found no element for the locator.`);\n try {\n const target = await this.describe(() => this.targets.ofHandle(handle!, ACTION_TIMEOUT_MS));\n const described = typeof value === \"function\" ? await (value as (target: GuardedTarget) => Promise<unknown>)(target) : value;\n await guard({ action, target, ...(described !== undefined ? { value: described } : {}) });\n return { handle, target };\n } catch (error) {\n await handle.dispose().catch(() => undefined);\n throw error;\n }\n }\n\n /** The document an action is checked on; input later goes only to it. */\n private async checkpoint(): Promise<DocumentState | null> {\n if (!this.options.actionGuard) return null;\n try {\n return await this.targets.documentState();\n } catch (error) {\n throw new BrowserActionRefusal(\"UNSUPPORTED\", `The page's document could not be identified, so nothing was sent: ${errorMessage(error)}`);\n }\n }\n\n /** Just before input: the same document, no navigation in flight, and the host's own last check. */\n private async dispatching(state: DocumentState | null): Promise<void> {\n if (!state) return;\n try {\n await this.targets.sameDocument(state);\n } catch (error) {\n if (error instanceof DocumentChanged) throw new BrowserActionRefusal(\"STALE_PAGE\", error.message);\n throw new BrowserActionRefusal(\"UNSUPPORTED\", `The page's document could not be confirmed, so nothing was sent: ${errorMessage(error)}`);\n }\n await this.options.beforeInput?.({ url: state.url });\n }\n\n /** The page-level action's guard. */\n private async guardPage(action: PlaywrightPageAction[\"action\"], value?: unknown): Promise<void> {\n if (this.options.actionGuard)\n await this.options.actionGuard({ action, url: this.page.url(), ...(value !== undefined ? { value } : {}) });\n }\n\n /** The pointer's position for a press that names none; unknown after a locator action. */\n private pointer(input: Record<string, unknown>): { x: number; y: number } {\n if (typeof input.x === \"number\" && typeof input.y === \"number\") return { x: input.x, y: input.y };\n if (!this.mouse)\n throw new BrowserActionRefusal(\"INVALID_INPUT\",\n \"Where the mouse is after a locator action is not known exactly; give x and y, or move the mouse first.\");\n return this.mouse;\n }\n\n /**\n * Asks the host's policy about raw pointer input at a viewport point; the\n * target is the element there as best known (`unidentified` when not).\n */\n private async guardPoint(action: PlaywrightElementAction[\"action\"], x: number, y: number, value?: unknown): Promise<void> {\n const guard = this.options.actionGuard;\n if (!guard) return;\n await guard({ action, target: await this.describe(() => this.targets.atPoint(x, y)), pointer: true,\n ...(value !== undefined ? { value } : {}) });\n }\n\n /** A browser-side description, or the refusal that replaces the action. */\n private async describe(run: () => Promise<GuardedTarget>): Promise<GuardedTarget> {\n try {\n return await run();\n } catch (error) {\n if (error instanceof HostElementTarget) throw new BrowserActionRefusal(\"UNSUPPORTED\", error.message);\n if (error instanceof UnidentifiedTarget)\n throw new BrowserActionRefusal(\"UNSUPPORTED\", `${error.message} The action was refused because its target could not be checked.`);\n throw new BrowserActionRefusal(\"UNSUPPORTED\",\n `The action was refused because its target could not be checked: ${errorMessage(error)}`);\n }\n }\n\n /** The aria refs of the elements `snapshotExclude` matches, and of their contents. */\n private async excludedRefs(): Promise<Set<string>> {\n const refs = new Set<string>();\n const selector = this.options.snapshotExclude;\n if (!selector) return refs;\n const matches = this.page.locator(selector);\n const count = Math.min(await matches.count().catch(() => 0), SNAPSHOT_EXCLUDE_LIMIT);\n for (let index = 0; index < count; index += 1) {\n const nodes = await matches.nth(index).ariaSnapshotJSON({ mode: \"ai\", timeout: ACTION_TIMEOUT_MS }).catch(() => null) as unknown;\n collectRefs(nodes, refs);\n }\n return refs;\n }\n\n private async revision(): Promise<number> {\n const value = await this.page.evaluate((key) => (globalThis as unknown as Record<string, unknown>)[key], REVISION_KEY)\n .catch(() => undefined);\n return typeof value === \"number\" ? value : 0;\n }\n\n private async executeCall(call: BrowserOperationCall): Promise<BrowserOperationResult> {\n const input = call.input;\n const page = this.page;\n const expectedRevision = typeof input.expectedRevision === \"number\" ? input.expectedRevision : undefined;\n if (expectedRevision !== undefined) {\n const current = await this.revision();\n if (expectedRevision !== current)\n return this.failure(call.operation, \"STALE_PAGE\", `The page changed (expected revision ${expectedRevision}, current revision ${current}).`);\n }\n if (call.operation === \"browser.status\")\n return this.success(call.operation, {\n available: true,\n features: PLAYWRIGHT_FEATURES,\n syntheticEvents: this.options.syntheticEvents,\n implementation: PLAYWRIGHT_IMPLEMENTATION,\n endpoint: this.options.endpoint,\n });\n if (call.operation === \"browser.snapshot\") {\n await this.refreshRefs(input.locator);\n const scoped = input.locator ? this.locator(input.locator).first() : null;\n // The excluded elements' refs come first: each element-scoped snapshot\n // replaces the page's ref map, which the snapshot below then restores.\n const excluded = await this.excludedRefs();\n const text = snapshotWithoutRefs(scoped\n ? await this.act(scoped, \"ariaSnapshot\", () => scoped.ariaSnapshot({ mode: \"ai\", timeout: ACTION_TIMEOUT_MS }))\n : await page.ariaSnapshot({ mode: \"ai\", timeout: ACTION_TIMEOUT_MS }), excluded);\n const bounded = text.slice(0, 64_000);\n return this.success(call.operation, { text: bounded, truncated: bounded.length < text.length });\n }\n if (call.operation === \"browser.query\") {\n await this.refreshRefs(input.locator);\n const locator = this.locator(input.locator, typeof input.index === \"number\" ? input.index : undefined);\n const count = await locator.count();\n return this.success(call.operation, { count, matches: await this.inspectAll(locator, 50), truncated: count > 50 });\n }\n if (call.operation === \"browser.wait\") {\n await this.refreshRefs(input.locator);\n const requested = typeof input.timeout === \"number\" ? input.timeout : 5_000;\n const timeout = Math.min(requested, WAIT_TIMEOUT_CLAMP_MS);\n const locator = this.locator(input.locator, typeof input.index === \"number\" ? input.index : 0);\n try {\n await locator.waitFor({ state: input.state === \"attached\" ? \"attached\" : \"visible\", timeout });\n } catch (error) {\n if (error instanceof errors.TimeoutError)\n throw new BrowserActionRefusal(\"TIMED_OUT\", `waitFor timed out after ${timeout}ms` +\n (timeout < requested ? ` (the requested ${requested}ms is clamped to ${WAIT_TIMEOUT_CLAMP_MS}ms by the provider call deadline)` : \"\") + \".\");\n throw error;\n }\n return this.success(call.operation, { ready: true });\n }\n if (call.operation === \"browser.scroll\") {\n const direction = input.direction as \"up\" | \"down\" | \"left\" | \"right\";\n const state = await this.checkpoint();\n await this.guardPage(\"scroll\", { direction, ...(typeof input.amount === \"number\" ? { amount: input.amount } : {}) });\n await this.dispatching(state);\n const position = await page.evaluate(scrollInPage, {\n left: direction === \"left\" ? -1 : direction === \"right\" ? 1 : 0,\n top: direction === \"up\" ? -1 : direction === \"down\" ? 1 : 0,\n amount: typeof input.amount === \"number\" ? input.amount : null,\n });\n return this.success(call.operation, position);\n }\n if (call.operation === \"browser.script\") return this.script(call);\n if (call.operation === \"browser.mouse\") {\n // Raw pointer input: the guard is asked about the point the press\n // happens at. A down or up given coordinates moves there first, so the\n // press lands where the guard looked.\n const action = input.action as \"move\" | \"down\" | \"up\" | \"click\";\n if (action === \"move\") {\n const at = { x: input.x as number, y: input.y as number };\n await page.mouse.move(at.x, at.y);\n this.mouse = at;\n return this.success(call.operation, { action, x: at.x, y: at.y });\n }\n const at = this.pointer(input);\n const state = await this.checkpoint();\n await this.guardPoint(action === \"click\" ? \"click\" : action === \"down\" ? \"mousedown\" : \"mouseup\", at.x, at.y);\n await this.dispatching(state);\n // The press always happens where the guard looked.\n await page.mouse.move(at.x, at.y);\n if (action === \"click\") await page.mouse.click(at.x, at.y);\n else if (action === \"down\") await page.mouse.down();\n else await page.mouse.up();\n this.mouse = at;\n return this.success(call.operation, { action, x: at.x, y: at.y });\n }\n if (call.operation === \"browser.wheel\") {\n const deltaX = typeof input.deltaX === \"number\" ? input.deltaX : 0;\n const deltaY = typeof input.deltaY === \"number\" ? input.deltaY : 0;\n const at = this.pointer(input);\n const state = await this.checkpoint();\n await this.guardPoint(\"wheel\", at.x, at.y, { deltaX, deltaY });\n await this.dispatching(state);\n await page.mouse.move(at.x, at.y);\n await page.mouse.wheel(deltaX, deltaY);\n this.mouse = at;\n return this.success(call.operation, { deltaX, deltaY });\n }\n if (call.operation === \"browser.drag\") {\n // A drag is raw pointer input from start to end: the guard is asked once,\n // about the element at the start, with both points.\n const resolve = async (endpoint: Record<string, unknown>): Promise<{ x: number; y: number }> => {\n if (endpoint.locator === undefined) return { x: endpoint.x as number, y: endpoint.y as number };\n await this.refreshRefs(endpoint.locator);\n const locator = this.locator(endpoint.locator).first();\n const box = await locator.boundingBox({ timeout: ACTION_TIMEOUT_MS }).catch(() => null);\n if (!box) throw new BrowserActionRefusal(\"NOT_FOUND\", \"The drag locator matched no element.\");\n return { x: box.x + box.width / 2, y: box.y + box.height / 2 };\n };\n const from = await resolve(input.from as Record<string, unknown>);\n const to = await resolve(input.to as Record<string, unknown>);\n // The card names what is at the drop point as well as the start.\n const drop = await this.describe(() => this.targets.atPoint(to.x, to.y));\n const state = await this.checkpoint();\n await this.guardPoint(\"drag\", from.x, from.y, { from, to, drop });\n await this.dispatching(state);\n await page.mouse.move(from.x, from.y);\n await page.mouse.down();\n await page.mouse.move(to.x, to.y, { steps: typeof input.steps === \"number\" ? input.steps : 8 });\n await page.mouse.up();\n this.mouse = to;\n return this.success(call.operation, { from, to });\n }\n if (call.operation === \"browser.back\") {\n const state = await this.checkpoint();\n await this.guardPage(\"back\");\n await this.dispatching(state);\n await page.goBack({ waitUntil: \"commit\", timeout: ACTION_TIMEOUT_MS });\n return this.success(call.operation, { requested: true });\n }\n if (call.operation === \"browser.forward\") {\n const state = await this.checkpoint();\n await this.guardPage(\"forward\");\n await this.dispatching(state);\n await page.goForward({ waitUntil: \"commit\", timeout: ACTION_TIMEOUT_MS });\n return this.success(call.operation, { requested: true });\n }\n if (call.operation === \"browser.reload\") {\n const state = await this.checkpoint();\n await this.guardPage(\"reload\");\n await this.dispatching(state);\n await page.reload({ waitUntil: \"commit\", timeout: ACTION_TIMEOUT_MS });\n return this.success(call.operation, { requested: true });\n }\n\n await this.refreshRefs(input.locator);\n const locator = input.locator\n ? this.locator(input.locator, typeof input.index === \"number\" ? input.index : 0)\n : null;\n const timeout = ACTION_TIMEOUT_MS;\n if (call.operation === \"browser.box\") {\n const box = await locator!.count() === 0 ? null : await locator!.boundingBox({ timeout });\n if (!box) return this.failure(call.operation, \"NOT_FOUND\", \"The locator matched no element.\");\n return this.success(call.operation, box);\n }\n if (call.operation === \"browser.press\" && !locator) {\n // The key goes to the focused element (the body when none is); focus\n // inside an embedded frame is refused.\n const state = await this.checkpoint();\n if (this.options.actionGuard)\n await this.options.actionGuard({ action: \"press\", target: await this.describe(() => this.targets.focused()), value: input.key });\n await this.dispatching(state);\n await page.keyboard.press(input.key as string);\n return this.success(call.operation, { key: input.key });\n }\n const target = locator!;\n const guardedAction = call.operation === \"browser.select\" ? \"select\" : call.operation.slice(\"browser.\".length) as PlaywrightElementAction[\"action\"];\n const state = await this.checkpoint();\n const guarded = await this.guarded(target.first(), guardedAction,\n call.operation === \"browser.fill\" ? input.value : call.operation === \"browser.press\" ? input.key\n : call.operation === \"browser.select\"\n // The options the select will choose, as the browser reads them.\n ? async (described: GuardedTarget) => ({ values: input.values, options: await this.targets.selectOptions(described, input.values as string[]) })\n : undefined);\n const handle = guarded?.handle ?? null;\n // The guarded element itself, when there is a policy; else the locator.\n const element: Pick<Locator, \"click\" | \"fill\" | \"press\" | \"hover\" | \"check\" | \"uncheck\" | \"selectOption\"> & { focus(): Promise<void> } =\n handle ?? { ...bind(target), focus: () => target.focus({ timeout }) };\n // A key press goes to whatever holds focus: the guarded element must\n // hold it after being focused, or the key would land somewhere else.\n const press = async (): Promise<void> => {\n if (!guarded) {\n await element.press(input.key as string, { timeout });\n return;\n }\n await guarded.handle.focus();\n if (!await this.targets.focusWithin(guarded.target))\n throw new BrowserActionRefusal(\"UNSUPPORTED\",\n \"Focusing the element left focus elsewhere, so the key would go to another element; the press was refused.\");\n await this.dispatching(state);\n await page.keyboard.press(input.key as string);\n };\n // The inspection is read after the action; an action that detaches or\n // navigates away from its element reports the element as it was.\n const before = await this.inspect(target).catch(() => null);\n try {\n // A pointer action waits for its element (a trial run) before the last\n // document check, so input follows the check as closely as it can.\n const pointer = (run: (options: { timeout: number; trial?: boolean }) => Promise<void>) => async (): Promise<void> => {\n if (guarded) await run({ timeout, trial: true });\n await this.dispatching(state);\n await run({ timeout });\n };\n const direct = <T>(run: () => Promise<T>) => async (): Promise<T> => {\n await this.dispatching(state);\n return await run();\n };\n if (call.operation === \"browser.click\") await this.act(target, \"click\", pointer((options) => element.click(options)));\n else if (call.operation === \"browser.fill\") await this.act(target, \"fill\", direct(() => element.fill(input.value as string, { timeout })));\n else if (call.operation === \"browser.press\") await this.act(target, \"press\", press);\n else if (call.operation === \"browser.hover\") await this.act(target, \"hover\", pointer((options) => element.hover(options)));\n else if (call.operation === \"browser.focus\") await this.act(target, \"focus\", direct(() => element.focus()));\n else if (call.operation === \"browser.check\") await this.act(target, \"check\", pointer((options) => element.check(options)));\n else if (call.operation === \"browser.uncheck\") await this.act(target, \"uncheck\", pointer((options) => element.uncheck(options)));\n else if (call.operation === \"browser.select\") {\n const values = await this.act(target, \"selectOption\", direct(() => element.selectOption(input.values as string[], { timeout })));\n return this.success(call.operation, { values });\n }\n } finally {\n // Playwright moved the mouse to the element's clickable point (its box\n // centre); anything else leaves the position unknown.\n if ([\"browser.click\", \"browser.hover\", \"browser.check\", \"browser.uncheck\"].includes(call.operation)) {\n const box = await (handle ?? target).boundingBox().catch(() => null);\n this.mouse = box ? { x: box.x + box.width / 2, y: box.y + box.height / 2 } : null;\n }\n await handle?.dispose().catch(() => undefined);\n }\n const after = await this.inspect(target).catch(() => null);\n const inspection = after ?? before;\n if (!inspection) throw new BrowserActionRefusal(\"NOT_FOUND\", \"The locator matched no element.\");\n return this.success(call.operation, inspection);\n }\n\n private async script(call: BrowserOperationCall): Promise<BrowserOperationResult> {\n const input = call.input;\n const source = input.source as string;\n const args = (input.args as Record<string, unknown> | undefined) ?? {};\n const requested = typeof input.timeout === \"number\" ? input.timeout : 30_000;\n const timeout = Math.min(requested, SCRIPT_TIMEOUT_CLAMP_MS);\n // Ordinary Playwright, run in this realm with the real `page`.\n const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor as\n new (...parameters: string[]) => (...values: unknown[]) => Promise<unknown>;\n if (this.options.actionGuard) await this.options.actionGuard({ action: \"script\", source, args });\n let run: (...values: unknown[]) => Promise<unknown>;\n try {\n run = new AsyncFunction(\"page\", \"args\", source);\n } catch (error) {\n return this.failure(call.operation, \"FAILED\", `The script did not parse: ${errorMessage(error)}`);\n }\n const notice = timeout < requested\n ? `The script timeout is clamped to ${SCRIPT_TIMEOUT_CLAMP_MS}ms: the harness abandons a provider call at 12 s.`\n : undefined;\n let timer: ReturnType<typeof setTimeout> | undefined;\n // The script holds the page through a membrane that closes when it ends or\n // times out: it is cancelled, not left running with the page.\n const scope = new ScriptScope();\n try {\n const value = await Promise.race([\n run(scope.wrap(this.page), args),\n new Promise((_resolve, reject) => {\n timer = setTimeout(() => reject(new BrowserActionRefusal(\"FAILED\", `The script exceeded ${timeout}ms.` + (notice ? ` ${notice}` : \"\"))), timeout);\n }),\n ]);\n return this.success(call.operation, {\n value: serializableValue(value, this.options.syntheticEvents),\n ...(notice ? { notice } : {}),\n });\n } finally {\n clearTimeout(timer);\n // Routes, bindings, init scripts and listeners the script installed do not outlive it.\n await scope.close(this.page);\n }\n }\n\n private async target(): Promise<BrowserTarget> {\n if (this.page.isClosed()) return { url: \"\", title: \"\", revision: 0 };\n // A page mid-navigation can hold `title()` until its next document exists;\n // the target is a description, so it never outwaits the call.\n const bounded = <T>(promise: Promise<T>, fallback: T): Promise<T> => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n return Promise.race([\n promise.catch(() => fallback),\n new Promise<T>((resolve) => { timer = setTimeout(() => resolve(fallback), 1_000); }),\n ]).finally(() => clearTimeout(timer));\n };\n const [title, revision] = await Promise.all([\n bounded(this.page.title(), \"\"),\n bounded(this.revision(), 0),\n ]);\n return { url: this.page.url(), title, revision };\n }\n\n private async success(operation: BrowserOperationName, value: unknown): Promise<BrowserOperationResult> {\n return { ok: true, operation, target: await this.target(), value };\n }\n\n private async failure(operation: BrowserOperationName, code: BrowserOperationErrorCode, message: string): Promise<BrowserOperationResult> {\n return { ok: false, operation, error: { code, message }, target: await this.target() };\n }\n}\n\nfunction operationName(raw: unknown): BrowserOperationName {\n const candidate = raw && typeof raw === \"object\" && !Array.isArray(raw) ? (raw as Record<string, unknown>).operation : undefined;\n return typeof candidate === \"string\" && (BROWSER_OPERATION_NAMES as readonly string[]).includes(candidate)\n ? candidate as BrowserOperationName\n : \"browser.status\";\n}\n\n/** A locator's action methods, bound, so it can stand where an element handle does. */\nfunction bind(locator: Locator): Pick<Locator, \"click\" | \"fill\" | \"press\" | \"hover\" | \"check\" | \"uncheck\" | \"selectOption\"> {\n return {\n click: locator.click.bind(locator),\n fill: locator.fill.bind(locator),\n press: locator.press.bind(locator),\n hover: locator.hover.bind(locator),\n check: locator.check.bind(locator),\n uncheck: locator.uncheck.bind(locator),\n selectOption: locator.selectOption.bind(locator),\n };\n}\n", "/**\n * What an action is about to land on, described from the browser side for a\n * host's `actionGuard`: the elements are found in an isolated world the page's\n * scripts cannot reach (its DOM prototypes are the browser's own), and each is\n * described over CDP from its backend node (`DOM.describeNode`,\n * `Accessibility.getPartialAXTree`), so a page cannot change what the guard\n * reads by overriding DOM functions.\n *\n * Over AlmostCDP the CDP endpoint itself runs in the page, so there the\n * description is as trustworthy as the page's world; over a native CDP\n * endpoint (Chrome, `chrome.debugger`) it is the browser's.\n */\n\nimport type { CDPSession, ElementHandle, Page } from \"playwright-core\";\n\n/** One element (or accessibility ancestor), as the browser describes it. */\nexport interface GuardedNode {\n /** The node's backend id: stable for the node's life in its document. */\n backendNodeId: number;\n /** Lower-case tag name; empty for an accessibility-only ancestor. */\n tag: string;\n /** The node's attributes, as the DOM holds them. */\n attributes: Readonly<Record<string, string>>;\n /** Computed accessibility role and name. */\n role: string;\n name: string;\n /** The element belongs to a form (its `form` owner, or a form around it): Enter in a text field may submit it. */\n inForm?: boolean;\n /** The element's own text, when its accessible name is empty (a generic element), up to 80 characters. */\n text?: string;\n}\n\n/** Where an action lands. */\nexport interface GuardedTarget {\n /** The page URL the target was resolved on. */\n url: string;\n /**\n * The element the action lands on. For a locator, every element whose box\n * is exactly the resolved element's (a wrapper of the same size is\n * indistinguishable from outside, so a guard sees all of them); for a\n * point, the element hit there.\n */\n nodes: readonly GuardedNode[];\n /** Accessibility ancestors of those elements, nearest first. */\n ancestors: readonly GuardedNode[];\n /** The viewport point of a coordinate action. */\n point?: { x: number; y: number };\n /**\n * Set when the element at a coordinate action's point could not be\n * identified (an embedded frame, nothing there): `nodes` is then empty and\n * this says why. A locator or key target that cannot be identified is\n * refused instead.\n */\n unidentified?: string;\n}\n\n/** A target that could not be identified browser-side: the action is refused. */\nexport class UnidentifiedTarget extends Error {}\n\n/** A coordinate action that lands on the host's own interface: refused. */\nexport class HostElementTarget extends Error {}\n\n/** The main frame's document when a target was checked: input may only go to that document. */\nexport interface DocumentState {\n loaderId: string;\n url: string;\n}\n\n/** The page changed documents, or is navigating, since the target was checked. */\nexport class DocumentChanged extends Error {}\n\nconst WORLD = \"supercode-guard\";\nconst GROUP = \"supercode-guard\";\nconst MAX_NODES = 8;\nconst MAX_ANCESTORS = 6;\n\ntype Query =\n | { kind: \"box\"; box: { x: number; y: number; width: number; height: number }; host: string | null; max: number; marker: string }\n | { kind: \"point\"; x: number; y: number; host: string | null }\n | { kind: \"focus\"; host: string | null };\n\n/**\n * Runs in the isolated world. Returns the matching elements, or a string:\n * `host` when a point lands on the host's own elements, else why nothing was\n * found. Self-contained: it is sent as source.\n */\nfunction findInWorld(query: Query): Element[] | string {\n const onHost = (element: Element): boolean => {\n if (!query.host) return false;\n for (let node: Element | null = element; node; ) {\n if (node.matches(query.host)) return true;\n const parent: Element | null = node.parentElement;\n node = parent ?? ((node.getRootNode() as ShadowRoot).host ?? null);\n }\n return false;\n };\n const frame = (element: Element): boolean => /^(IFRAME|FRAME|OBJECT|EMBED)$/.test(element.tagName);\n if (query.kind === \"focus\") {\n // Where a key press goes: the focused element, through open shadow roots.\n let element: Element | null = document.activeElement ?? document.body;\n while (element?.shadowRoot?.activeElement) element = element.shadowRoot.activeElement;\n if (!element) return \"Nothing has focus.\";\n if (frame(element)) return \"Focus is inside an embedded frame, which the guard cannot inspect.\";\n if (onHost(element)) return \"host\";\n return [element];\n }\n if (query.kind === \"point\") {\n let element = document.elementFromPoint(query.x, query.y);\n if (!element) return \"Nothing is at that point.\";\n if (onHost(element)) return \"host\";\n while (element.shadowRoot) {\n const inner: Element | null = element.shadowRoot.elementFromPoint(query.x, query.y);\n if (!inner || inner === element) break;\n element = inner;\n if (onHost(element)) return \"host\";\n }\n if (frame(element)) return \"The point is inside an embedded frame, which the guard cannot inspect.\";\n return [element];\n }\n const { box } = query;\n // The element the action's handle is carries a one-off marker attribute;\n // it must be one of the elements found at the handle's box.\n const marked: Element[] = [];\n const found: Element[] = [];\n const near = (a: number, b: number): boolean => Math.abs(a - b) <= 1;\n const visit = (root: Document | ShadowRoot): void => {\n for (const element of Array.from(root.querySelectorAll(\"*\"))) {\n if (found.length > query.max - 1) return;\n const rect = element.getBoundingClientRect();\n if (element.hasAttribute(query.marker)) {\n marked.push(element);\n element.removeAttribute(query.marker);\n }\n if (near(rect.x, box.x) && near(rect.y, box.y) && near(rect.width, box.width) && near(rect.height, box.height))\n found.push(element);\n if (element.shadowRoot) visit(element.shadowRoot);\n }\n };\n // Every element is visited, so a marker is always found and removed.\n const cap = query.max;\n query.max = Number.MAX_SAFE_INTEGER;\n visit(document);\n query.max = cap;\n if (marked.length !== 1 || !found.includes(marked[0]!))\n return \"The element the action targets could not be confirmed at its place on the page.\";\n if (!found.length)\n return \"The element could not be found in the page's top document (it may be inside an embedded frame or a closed shadow root).\";\n if (found.length >= query.max)\n return `More than ${query.max - 1} elements share the target's box, so which one the action lands on cannot be told.`;\n if (found.some(frame)) return \"The target is an embedded frame, whose content the guard cannot inspect.\";\n // Playwright acts on the control a label forwards to (a fill or click on a\n // <label>, or on text inside one, reaches its control).\n for (const element of [...found]) {\n const label = element.closest(\"label\");\n const control = label ? (label as HTMLLabelElement).control : null;\n if (control && !found.includes(control)) found.push(control);\n }\n return found;\n}\n\ninterface AXNode {\n nodeId: string;\n ignored?: boolean;\n role?: { value?: unknown };\n name?: { value?: unknown };\n parentId?: string;\n backendDOMNodeId?: number;\n}\n\nexport class BrowserSideTargets {\n private session: Promise<CDPSession> | null = null;\n /** A main-frame navigation has been requested or is loading and has not finished. */\n private navigating = false;\n private mainFrame = \"\";\n\n constructor(private readonly page: Page, private readonly host: string | null) {}\n\n /**\n * The element a resolved handle is, scrolled into view. It must be in the\n * page's main frame, and it must be one of the elements found browser-side\n * at its box (the handle is marked with a one-off attribute the isolated\n * world looks for, then removes).\n */\n async ofHandle(handle: ElementHandle, timeout: number): Promise<GuardedTarget> {\n if (await handle.ownerFrame() !== this.page.mainFrame())\n throw new UnidentifiedTarget(\"The element is inside an embedded frame, which the guard cannot inspect.\");\n await handle.scrollIntoViewIfNeeded({ timeout });\n const box = await handle.boundingBox();\n if (!box || box.width === 0 || box.height === 0)\n throw new UnidentifiedTarget(\"The element has no box on the page.\");\n const marker = `data-supercode-guard-${Array.from(crypto.getRandomValues(new Uint8Array(8)), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\")}`;\n await handle.evaluate((element, name) => (element as Element).setAttribute(name, \"\"), marker);\n try {\n // One over the cap: reaching it means the candidates were cut short.\n return await this.resolve({ kind: \"box\", box, host: this.host, max: MAX_NODES + 1, marker });\n } finally {\n await handle.evaluate((element, name) => (element as Element).removeAttribute(name), marker).catch(() => undefined);\n }\n }\n\n /**\n * Where a key press goes: the focused element. Focus inside an embedded\n * frame or a closed shadow root is refused.\n */\n async focused(): Promise<GuardedTarget> {\n return await this.resolve({ kind: \"focus\", host: this.host });\n }\n\n /**\n * Whether focus is now on one of the target's elements or inside one (open\n * shadow roots included), judged in the isolated world: a locator press is\n * refused when focusing its element left focus elsewhere.\n */\n async focusWithin(target: GuardedTarget): Promise<boolean> {\n return await this.inWorld(target, `function (...nodes) {\n let active = document.activeElement;\n while (active && active.shadowRoot && active.shadowRoot.activeElement) active = active.shadowRoot.activeElement;\n for (let node = active; node; node = node.parentNode || node.host) if (nodes.includes(node)) return true;\n return false;\n }`) === true;\n }\n\n /** The options a select action will choose, by value or label, read browser-side. */\n async selectOptions(target: GuardedTarget, wanted: readonly string[]): Promise<Array<{ label: string; value: string }>> {\n const select = { ...target, nodes: target.nodes.filter((node) => node.tag === \"select\") };\n if (!select.nodes.length) return [];\n const options = await this.inWorld(select, `function (wanted) {\n return Array.from(this.options).filter((option) => wanted.includes(option.value) || wanted.includes(option.label))\n .map((option) => ({ label: option.label, value: option.value }));\n }`, [wanted]);\n return Array.isArray(options) ? options as Array<{ label: string; value: string }> : [];\n }\n\n /**\n * Calls `source` in the isolated world with the target's first node as\n * `this`, and its nodes (or `extra` values) as arguments.\n */\n private async inWorld(target: GuardedTarget, source: string, extra?: unknown[]): Promise<unknown> {\n const cdp = await this.cdp();\n const contextId = await this.world(cdp);\n try {\n const objects: string[] = [];\n for (const node of target.nodes) {\n const resolved = await cdp.send(\"DOM.resolveNode\", { backendNodeId: node.backendNodeId, executionContextId: contextId, objectGroup: GROUP }) as\n { object: { objectId?: string } };\n if (resolved.object.objectId) objects.push(resolved.object.objectId);\n }\n if (!objects.length) return undefined;\n const called = await cdp.send(\"Runtime.callFunctionOn\", {\n objectId: objects[0],\n functionDeclaration: source,\n arguments: extra ? extra.map((value) => ({ value })) : objects.map((objectId) => ({ objectId })),\n returnByValue: true,\n }) as { result: { value?: unknown }; exceptionDetails?: unknown };\n return called.exceptionDetails ? undefined : called.result.value;\n } finally {\n await cdp.send(\"Runtime.releaseObjectGroup\", { objectGroup: GROUP }).catch(() => undefined);\n }\n }\n\n private async world(cdp: CDPSession): Promise<number> {\n const tree = await cdp.send(\"Page.getFrameTree\") as { frameTree: { frame: { id: string } } };\n const world = await cdp.send(\"Page.createIsolatedWorld\", { frameId: tree.frameTree.frame.id, worldName: WORLD }) as\n { executionContextId: number };\n return world.executionContextId;\n }\n\n /**\n * The element at a viewport point, as best known. A point on the host's own\n * interface is refused; a point whose element cannot be identified is\n * returned with no nodes and the reason, for a guard that decides on raw\n * pointer input regardless.\n */\n async atPoint(x: number, y: number): Promise<GuardedTarget> {\n try {\n return { ...await this.resolve({ kind: \"point\", x, y, host: this.host }), point: { x, y } };\n } catch (error) {\n if (error instanceof HostElementTarget) throw error;\n return {\n url: this.page.url(),\n nodes: [],\n ancestors: [],\n point: { x, y },\n unidentified: error instanceof Error ? error.message : String(error),\n };\n }\n }\n\n /** The main frame's document now. */\n async documentState(): Promise<DocumentState> {\n const cdp = await this.cdp();\n const tree = await cdp.send(\"Page.getFrameTree\") as { frameTree: { frame: { id: string; loaderId: string; url: string } } };\n this.mainFrame = tree.frameTree.frame.id;\n return { loaderId: tree.frameTree.frame.loaderId, url: tree.frameTree.frame.url };\n }\n\n /**\n * Just before input is dispatched: the main frame must still hold the\n * document the target was checked on, with no navigation in flight.\n */\n async sameDocument(checked: DocumentState): Promise<void> {\n const now = await this.documentState();\n if (this.navigating) throw new DocumentChanged(\"The page is navigating, so nothing was sent; ask again once it has loaded.\");\n if (now.loaderId !== checked.loaderId || now.url !== checked.url)\n throw new DocumentChanged(\"The page changed since the action was checked, so nothing was sent; ask again.\");\n }\n\n private cdp(): Promise<CDPSession> {\n this.session ??= this.page.context().newCDPSession(this.page).then(async (session) => {\n // Navigations of the main frame: requested or loading until it stops.\n const main = (frameId: unknown): boolean => !this.mainFrame || frameId === this.mainFrame;\n session.on(\"Page.frameRequestedNavigation\", (event: { frameId?: string }) => { if (main(event.frameId)) this.navigating = true; });\n session.on(\"Page.frameStartedNavigating\", (event: { frameId?: string }) => { if (main(event.frameId)) this.navigating = true; });\n session.on(\"Page.frameStartedLoading\", (event: { frameId?: string }) => { if (main(event.frameId)) this.navigating = true; });\n // A navigation ends when a document commits, a same-document move\n // happens, loading stops (a 204 answer, a cancelled or failed load), or\n // it turns into a download.\n const settled = (event: { frameId?: string; frame?: { id?: string; parentId?: string } }): void => {\n const frameId = event.frameId ?? event.frame?.id;\n if (main(frameId) && !event.frame?.parentId) this.navigating = false;\n };\n session.on(\"Page.frameStoppedLoading\", settled);\n session.on(\"Page.frameNavigated\", settled);\n session.on(\"Page.navigatedWithinDocument\", settled);\n session.on(\"Page.downloadWillBegin\", settled);\n await session.send(\"Page.enable\").catch(() => undefined);\n return session;\n }, (error: unknown) => {\n this.session = null;\n throw error;\n });\n return this.session;\n }\n\n private async resolve(query: Query): Promise<GuardedTarget> {\n const cdp = await this.cdp();\n const contextId = await this.world(cdp);\n try {\n const evaluated = await cdp.send(\"Runtime.evaluate\", {\n expression: `(${findInWorld.toString()})(${JSON.stringify(query)})`,\n contextId,\n objectGroup: GROUP,\n returnByValue: false,\n }) as { result: { type: string; value?: unknown; objectId?: string }; exceptionDetails?: { text?: string } };\n if (evaluated.exceptionDetails)\n throw new UnidentifiedTarget(`The target could not be resolved: ${evaluated.exceptionDetails.text ?? \"exception\"}.`);\n if (evaluated.result.type === \"string\") {\n if (evaluated.result.value === \"host\") throw new HostElementTarget(\"The point is on the host's own interface, which agents cannot operate.\");\n throw new UnidentifiedTarget(String(evaluated.result.value));\n }\n if (!evaluated.result.objectId) throw new UnidentifiedTarget(\"The target could not be resolved.\");\n const properties = await cdp.send(\"Runtime.getProperties\", { objectId: evaluated.result.objectId, ownProperties: true }) as\n { result: Array<{ name: string; value?: { objectId?: string } }> };\n const objects = properties.result\n .filter((property) => /^\\d+$/.test(property.name) && property.value?.objectId)\n .map((property) => property.value!.objectId!);\n if (!objects.length) throw new UnidentifiedTarget(\"The target could not be resolved.\");\n const nodes: GuardedNode[] = [];\n const ancestors: GuardedNode[] = [];\n const seen = new Set<number>();\n for (const objectId of objects) {\n const described = await cdp.send(\"DOM.describeNode\", { objectId, depth: 1, pierce: true }) as\n { node: { backendNodeId: number; nodeName: string; attributes?: string[]; shadowRoots?: Array<{ shadowRootType?: string }> } };\n // Focus that ends at a closed shadow root's host is somewhere inside it.\n if (query.kind === \"focus\" && described.node.shadowRoots?.some((root) => root.shadowRootType === \"closed\"))\n throw new UnidentifiedTarget(\"Focus is inside a closed shadow root, which the guard cannot inspect.\");\n const facts = await cdp.send(\"Runtime.callFunctionOn\", {\n objectId,\n functionDeclaration: \"function () { return { form: !!(this.form || (this.closest && this.closest('form'))), text: (this.textContent || '').replace(/\\\\s+/g, ' ').trim().slice(0, 80) }; }\",\n returnByValue: true,\n }) as { result: { value?: { form?: unknown; text?: unknown } } };\n const attributes: Record<string, string> = {};\n const list = described.node.attributes ?? [];\n for (let index = 0; index + 1 < list.length; index += 2) attributes[list[index]!.toLowerCase()] = list[index + 1]!;\n const ax = await this.accessibility(cdp, described.node.backendNodeId);\n nodes.push({\n backendNodeId: described.node.backendNodeId,\n tag: described.node.nodeName.toLowerCase(),\n attributes,\n role: ax.self?.role ?? \"\",\n name: ax.self?.name ?? \"\",\n inForm: facts.result.value?.form === true,\n ...(typeof facts.result.value?.text === \"string\" && facts.result.value.text ? { text: facts.result.value.text } : {}),\n });\n seen.add(described.node.backendNodeId);\n for (const ancestor of ax.ancestors) {\n if (ancestors.length >= MAX_ANCESTORS || seen.has(ancestor.backendNodeId)) continue;\n seen.add(ancestor.backendNodeId);\n ancestors.push(ancestor);\n }\n }\n return { url: this.page.url(), nodes, ancestors };\n } finally {\n await cdp.send(\"Runtime.releaseObjectGroup\", { objectGroup: GROUP }).catch(() => undefined);\n }\n }\n\n private async accessibility(cdp: CDPSession, backendNodeId: number): Promise<{ self: { role: string; name: string } | null; ancestors: GuardedNode[] }> {\n const tree = await cdp.send(\"Accessibility.getPartialAXTree\", { backendNodeId, fetchRelatives: true }) as { nodes: AXNode[] };\n const byId = new Map(tree.nodes.map((node) => [node.nodeId, node]));\n const text = (value: unknown): string => typeof value === \"string\" ? value.replace(/\\s+/g, \" \").trim() : \"\";\n const self = tree.nodes.find((node) => node.backendDOMNodeId === backendNodeId) ?? null;\n const ancestors: GuardedNode[] = [];\n for (let node = self?.parentId ? byId.get(self.parentId) : undefined; node && ancestors.length < MAX_ANCESTORS;\n node = node.parentId ? byId.get(node.parentId) : undefined) {\n if (node.ignored || typeof node.backendDOMNodeId !== \"number\") continue;\n ancestors.push({ backendNodeId: node.backendDOMNodeId, tag: \"\", attributes: {}, role: text(node.role?.value), name: text(node.name?.value) });\n }\n return { self: self ? { role: text(self.role?.value), name: text(self.name?.value) } : null, ancestors };\n }\n}\n", "/**\n * What a `browser.script` holds while it runs: the real Playwright `page`\n * behind a membrane. Every Playwright object the script reaches through it\n * (locators, frames, the keyboard, the context) is wrapped the same way, and\n * everything a call returns with a `dispose()` (routes, exposed bindings and\n * functions, init scripts) is recorded. When the script ends, or its time runs\n * out, the membrane closes: every later call through it throws, the recorded\n * disposables are disposed, routes are removed and listeners dropped, so\n * nothing the script installed outlives it.\n */\n\nimport type { Page } from \"playwright-core\";\n\n/** A value the membrane passes through untouched: data, not a Playwright object. */\nfunction isData(value: object): boolean {\n if (Array.isArray(value) || ArrayBuffer.isView(value) || value instanceof ArrayBuffer ||\n value instanceof Date || value instanceof RegExp || value instanceof Map || value instanceof Set ||\n value instanceof Promise || value instanceof Error) return true;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nexport class ScriptScope {\n private closed = false;\n private readonly proxies = new WeakMap<object, object>();\n private readonly targets = new WeakMap<object, object>();\n private readonly disposables: Array<{ dispose(): unknown }> = [];\n\n /** The membrane's view of `value`. */\n wrap<T>(value: T): T {\n if (value === null || (typeof value !== \"object\" && typeof value !== \"function\")) return value;\n const object = value as unknown as object;\n if (typeof value === \"object\" && isData(object)) return value;\n const existing = this.proxies.get(object);\n if (existing) return existing as T;\n const scope = this;\n const proxy = new Proxy(object, {\n get(target, property) {\n scope.check();\n const member = Reflect.get(target, property, target) as unknown;\n if (typeof member !== \"function\") return scope.wrap(member);\n return function (this: unknown, ...args: unknown[]) {\n scope.check();\n return scope.returned(Reflect.apply(member as (...values: unknown[]) => unknown, target, args.map((arg) => scope.unwrap(arg))));\n };\n },\n set() {\n throw new Error(\"A script cannot change Playwright's objects.\");\n },\n apply(target, _self, args) {\n scope.check();\n return scope.returned(Reflect.apply(target as (...values: unknown[]) => unknown, undefined, args.map((arg) => scope.unwrap(arg))));\n },\n });\n this.proxies.set(object, proxy);\n this.targets.set(proxy, object);\n return proxy as T;\n }\n\n /**\n * Ends the script's hold on the page: later calls through the membrane\n * throw, and what it installed is removed.\n */\n async close(page: Page): Promise<void> {\n this.closed = true;\n for (const disposable of this.disposables.splice(0)) {\n try {\n await disposable.dispose();\n } catch { /* Already gone with its page. */ }\n }\n await page.unrouteAll({ behavior: \"ignoreErrors\" }).catch(() => undefined);\n await page.context().unrouteAll({ behavior: \"ignoreErrors\" }).catch(() => undefined);\n page.removeAllListeners();\n page.context().removeAllListeners();\n }\n\n private check(): void {\n if (this.closed) throw new Error(\"The script has ended or was cancelled; it can no longer use the page.\");\n }\n\n private unwrap(value: unknown): unknown {\n return value !== null && (typeof value === \"object\" || typeof value === \"function\")\n ? this.targets.get(value as object) ?? value\n : value;\n }\n\n private returned(value: unknown): unknown {\n if (value instanceof Promise) return value.then((resolved) => this.returned(resolved));\n if (value !== null && typeof value === \"object\" && typeof (value as { dispose?: unknown }).dispose === \"function\")\n this.disposables.push(value as { dispose(): unknown });\n return this.wrap(value);\n }\n}\n", "/**\n * The wire Supercode's browser providers answer: `supercode/browser-provider-v1`\n * envelopes carrying `supercode/browser-operation-v1` calls. Pure data and\n * parsers, with no runtime dependency, for the harness side, a host relaying\n * calls, and the executor alike.\n */\n\nexport const SUPERCODE_BROWSER_PROVIDER_PROTOCOL = \"supercode/browser-provider-v1\" as const;\nexport const SUPERCODE_BROWSER_OPERATION_PROTOCOL = \"supercode/browser-operation-v1\" as const;\n\nexport type BrowserLocator =\n | { by: \"css\"; value: string }\n | { by: \"ref\"; value: string }\n | { by: \"role\"; role: string; name?: string; exact?: boolean }\n | { by: \"text\"; text: string; exact?: boolean }\n | { by: \"testId\"; value: string }\n | { by: \"label\"; text: string; exact?: boolean }\n | { by: \"placeholder\"; text: string; exact?: boolean }\n | { by: \"altText\"; text: string; exact?: boolean }\n | { by: \"title\"; text: string; exact?: boolean };\n\nexport type BrowserOperationName =\n | \"browser.status\" | \"browser.snapshot\" | \"browser.query\" | \"browser.wait\"\n | \"browser.click\" | \"browser.fill\" | \"browser.press\" | \"browser.hover\"\n | \"browser.focus\" | \"browser.check\" | \"browser.uncheck\" | \"browser.select\"\n | \"browser.scroll\" | \"browser.back\" | \"browser.forward\" | \"browser.reload\"\n | \"browser.box\" | \"browser.mouse\" | \"browser.drag\" | \"browser.wheel\"\n | \"browser.script\";\n\nexport interface BrowserOperationCall {\n protocol: typeof SUPERCODE_BROWSER_OPERATION_PROTOCOL;\n operation: BrowserOperationName;\n input: Record<string, unknown>;\n}\n\nexport interface BrowserTarget {\n page?: string;\n url: string;\n title: string;\n revision: number;\n}\n\nexport type BrowserOperationErrorCode =\n | \"APPROVAL_REQUIRED\" | \"INVALID_INPUT\" | \"NOT_AVAILABLE\" | \"NOT_FOUND\"\n | \"STALE_PAGE\" | \"TIMED_OUT\" | \"UNSUPPORTED\" | \"FAILED\";\n\nexport type BrowserOperationResult =\n | { ok: true; operation: BrowserOperationName; target: BrowserTarget; value: unknown }\n | {\n ok: false;\n operation: BrowserOperationName;\n error: { code: BrowserOperationErrorCode; message: string };\n target?: BrowserTarget;\n };\n\nexport interface ElementInspection {\n ref: string;\n tag: string;\n role?: string;\n name?: string;\n value?: string;\n disabled: boolean;\n checked?: boolean;\n visible: boolean;\n}\n\n\n/** The 21 operations, in the registry's order. */\nexport const BROWSER_OPERATION_NAMES: readonly BrowserOperationName[] = Object.freeze([\n \"browser.status\", \"browser.snapshot\", \"browser.query\", \"browser.wait\",\n \"browser.click\", \"browser.fill\", \"browser.press\", \"browser.hover\",\n \"browser.focus\", \"browser.check\", \"browser.uncheck\", \"browser.select\",\n \"browser.scroll\", \"browser.back\", \"browser.forward\", \"browser.reload\",\n \"browser.box\", \"browser.mouse\", \"browser.drag\", \"browser.wheel\",\n \"browser.script\",\n]);\nconst OPERATION_NAMES = new Set<BrowserOperationName>(BROWSER_OPERATION_NAMES);\n\n/** A host's refusal of one action, carrying its wire error code. */\nexport class BrowserActionRefusal extends Error {\n constructor(readonly code: BrowserOperationErrorCode, message: string) {\n super(message);\n this.name = \"BrowserActionRefusal\";\n }\n}\n\nfunction record(value: unknown): Record<string, unknown> | null {\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? value as Record<string, unknown>\n : null;\n}\n\nfunction exactKeys(candidate: Record<string, unknown>, allowed: readonly string[]): boolean {\n return Object.keys(candidate).every((key) => allowed.includes(key));\n}\n\nfunction parsePage(value: unknown): string | undefined | null {\n return value === undefined\n ? undefined\n : typeof value === \"string\" && value.length > 0 && value.length <= 512\n ? value\n : null;\n}\n\nexport function parseBrowserLocator(value: unknown): BrowserLocator | null {\n const candidate = record(value);\n if (!candidate || typeof candidate.by !== \"string\") return null;\n if (candidate.by === \"label\" || candidate.by === \"placeholder\" || candidate.by === \"altText\" || candidate.by === \"title\") {\n const { by, text, exact } = candidate as Record<string, unknown>;\n return typeof text === \"string\" && (exact === undefined || typeof exact === \"boolean\") &&\n exactKeys(candidate as Record<string, unknown>, [\"by\", \"text\", \"exact\"])\n ? ({ by, text, ...(exact !== undefined ? { exact } : {}) } as BrowserLocator)\n : null;\n }\n if (candidate.by === \"css\" || candidate.by === \"ref\" || candidate.by === \"testId\") {\n return exactKeys(candidate, [\"by\", \"value\"]) && typeof candidate.value === \"string\" &&\n candidate.value.length > 0 && candidate.value.length <= 2_000\n ? { by: candidate.by, value: candidate.value }\n : null;\n }\n if (candidate.by === \"role\") {\n if (!exactKeys(candidate, [\"by\", \"role\", \"name\", \"exact\"]) ||\n typeof candidate.role !== \"string\" || !candidate.role ||\n (candidate.name !== undefined && typeof candidate.name !== \"string\") ||\n (candidate.exact !== undefined && typeof candidate.exact !== \"boolean\")) return null;\n return {\n by: \"role\",\n role: candidate.role,\n ...(typeof candidate.name === \"string\" ? { name: candidate.name } : {}),\n ...(typeof candidate.exact === \"boolean\" ? { exact: candidate.exact } : {}),\n };\n }\n if (candidate.by === \"text\") {\n if (!exactKeys(candidate, [\"by\", \"text\", \"exact\"]) ||\n typeof candidate.text !== \"string\" || !candidate.text ||\n (candidate.exact !== undefined && typeof candidate.exact !== \"boolean\")) return null;\n return {\n by: \"text\",\n text: candidate.text,\n ...(typeof candidate.exact === \"boolean\" ? { exact: candidate.exact } : {}),\n };\n }\n return null;\n}\n\nfunction parseTargetInput(\n value: unknown,\n options: { locatorRequired: boolean; value?: boolean; key?: boolean; wait?: boolean; values?: boolean },\n): Record<string, unknown> | null {\n const candidate = record(value);\n if (!candidate) return null;\n const allowed = [\"page\", \"locator\", \"index\", \"expectedRevision\"];\n if (options.value) allowed.push(\"value\");\n if (options.values) allowed.push(\"values\");\n if (options.key) allowed.push(\"key\");\n if (options.wait) allowed.push(\"state\", \"timeout\");\n if (!exactKeys(candidate, allowed)) return null;\n const page = parsePage(candidate.page);\n const locator = candidate.locator === undefined ? undefined : parseBrowserLocator(candidate.locator);\n const index = candidate.index;\n const revision = candidate.expectedRevision;\n if (page === null || (options.locatorRequired && !locator) ||\n (candidate.locator !== undefined && !locator) ||\n (index !== undefined && (!Number.isInteger(index) || (index as number) < 0)) ||\n (revision !== undefined && (!Number.isInteger(revision) || (revision as number) < 0)) ||\n (options.value && typeof candidate.value !== \"string\") ||\n (options.values && (!Array.isArray(candidate.values) ||\n !candidate.values.every((item) => typeof item === \"string\"))) ||\n (options.key && (typeof candidate.key !== \"string\" || !candidate.key || candidate.key.length > 100)) ||\n (options.wait && candidate.state !== undefined &&\n candidate.state !== \"attached\" && candidate.state !== \"visible\") ||\n (options.wait && candidate.timeout !== undefined &&\n (typeof candidate.timeout !== \"number\" || candidate.timeout < 0 || candidate.timeout > 30_000))) return null;\n return {\n ...(page ? { page } : {}),\n ...(locator ? { locator } : {}),\n ...(typeof index === \"number\" ? { index } : {}),\n ...(typeof revision === \"number\" ? { expectedRevision: revision } : {}),\n ...(options.value ? { value: candidate.value } : {}),\n ...(options.values ? { values: candidate.values } : {}),\n ...(options.key ? { key: candidate.key } : {}),\n ...(options.wait && candidate.state ? { state: candidate.state } : {}),\n ...(options.wait && typeof candidate.timeout === \"number\" ? { timeout: candidate.timeout } : {}),\n };\n}\n\nfunction parseBrowserOperationInput(operation: BrowserOperationName, value: unknown): Record<string, unknown> | null {\n const candidate = record(value);\n if (!candidate) return null;\n if (operation === \"browser.status\") return exactKeys(candidate, []) ? {} : null;\n if (operation === \"browser.snapshot\") {\n const page = parsePage(candidate.page);\n const locator = candidate.locator === undefined ? undefined : parseBrowserLocator(candidate.locator);\n return exactKeys(candidate, [\"page\", \"locator\"]) && page !== null &&\n (candidate.locator === undefined || locator !== null)\n ? { ...(page ? { page } : {}), ...(locator ? { locator } : {}) }\n : null;\n }\n if (operation === \"browser.query\" || operation === \"browser.click\" ||\n operation === \"browser.hover\" || operation === \"browser.focus\" ||\n operation === \"browser.check\" || operation === \"browser.uncheck\") {\n return parseTargetInput(candidate, { locatorRequired: true });\n }\n if (operation === \"browser.wait\")\n return parseTargetInput(candidate, { locatorRequired: true, wait: true });\n if (operation === \"browser.fill\")\n return parseTargetInput(candidate, { locatorRequired: true, value: true });\n if (operation === \"browser.select\")\n return parseTargetInput(candidate, { locatorRequired: true, values: true });\n if (operation === \"browser.press\")\n return parseTargetInput(candidate, { locatorRequired: false, key: true });\n if (operation === \"browser.script\") {\n const page = parsePage(candidate.page);\n const { source, args, timeout } = candidate;\n return exactKeys(candidate, [\"page\", \"source\", \"args\", \"timeout\"]) && page !== null &&\n typeof source === \"string\" && source.length > 0 && source.length <= 100_000 &&\n (args === undefined || (typeof args === \"object\" && args !== null && !Array.isArray(args))) &&\n (timeout === undefined || (typeof timeout === \"number\" && timeout >= 0 && timeout <= 120_000))\n ? {\n ...(page ? { page } : {}),\n source,\n ...(args !== undefined ? { args } : {}),\n ...(typeof timeout === \"number\" ? { timeout } : {}),\n }\n : null;\n }\n if (operation === \"browser.box\") return parseTargetInput(candidate, { locatorRequired: true });\n if (operation === \"browser.mouse\") {\n const page = parsePage(candidate.page);\n const { action, x, y, deltaX, deltaY } = candidate;\n const point = (value: unknown): boolean => typeof value === \"number\" && Number.isFinite(value);\n const needsPoint = action === \"move\" || action === \"click\";\n return exactKeys(candidate, [\"page\", \"action\", \"x\", \"y\", \"deltaX\", \"deltaY\"]) && page !== null &&\n (action === \"move\" || action === \"down\" || action === \"up\" || action === \"click\") &&\n (!needsPoint || (point(x) && point(y))) &&\n deltaX === undefined && deltaY === undefined\n ? { ...(page ? { page } : {}), action, ...(point(x) ? { x } : {}), ...(point(y) ? { y } : {}) }\n : null;\n }\n if (operation === \"browser.wheel\") {\n const page = parsePage(candidate.page);\n const { deltaX, deltaY } = candidate;\n return exactKeys(candidate, [\"page\", \"deltaX\", \"deltaY\"]) && page !== null &&\n (deltaX === undefined || typeof deltaX === \"number\") &&\n (deltaY === undefined || typeof deltaY === \"number\")\n ? {\n ...(page ? { page } : {}),\n ...(typeof deltaX === \"number\" ? { deltaX } : {}),\n ...(typeof deltaY === \"number\" ? { deltaY } : {}),\n }\n : null;\n }\n if (operation === \"browser.drag\") {\n const page = parsePage(candidate.page);\n const { from, to, steps } = candidate;\n const endpoint = (value: unknown): boolean => {\n if (!value || typeof value !== \"object\") return false;\n const record = value as Record<string, unknown>;\n if (record.locator !== undefined) return parseBrowserLocator(record.locator) !== null && exactKeys(record, [\"locator\"]);\n return typeof record.x === \"number\" && typeof record.y === \"number\" && exactKeys(record, [\"x\", \"y\"]);\n };\n return exactKeys(candidate, [\"page\", \"from\", \"to\", \"steps\"]) && page !== null &&\n endpoint(from) && endpoint(to) &&\n (steps === undefined || (Number.isInteger(steps) && (steps as number) >= 1 && (steps as number) <= 100))\n ? { ...(page ? { page } : {}), from, to, ...(typeof steps === \"number\" ? { steps } : {}) }\n : null;\n }\n if (operation === \"browser.scroll\") {\n const page = parsePage(candidate.page);\n const { direction, amount, expectedRevision } = candidate;\n return exactKeys(candidate, [\"page\", \"direction\", \"amount\", \"expectedRevision\"]) && page !== null &&\n (direction === \"up\" || direction === \"down\" || direction === \"left\" || direction === \"right\") &&\n (amount === undefined || (typeof amount === \"number\" && amount >= 1 && amount <= 10_000)) &&\n (expectedRevision === undefined || (Number.isInteger(expectedRevision) && (expectedRevision as number) >= 0))\n ? {\n ...(page ? { page } : {}), direction,\n ...(typeof amount === \"number\" ? { amount } : {}),\n ...(typeof expectedRevision === \"number\" ? { expectedRevision } : {}),\n }\n : null;\n }\n return parseTargetInput(candidate, { locatorRequired: false });\n}\n\nexport function parseBrowserOperationCall(value: unknown): BrowserOperationCall | null {\n const candidate = record(value);\n if (!candidate || candidate.protocol !== SUPERCODE_BROWSER_OPERATION_PROTOCOL ||\n typeof candidate.operation !== \"string\" || !OPERATION_NAMES.has(candidate.operation as BrowserOperationName)) return null;\n const operation = candidate.operation as BrowserOperationName;\n const input = parseBrowserOperationInput(operation, candidate.input);\n return input === null ? null : { protocol: SUPERCODE_BROWSER_OPERATION_PROTOCOL, operation, input };\n}\n\nexport function parseBrowserOperationResult(value: unknown): BrowserOperationResult | null {\n const candidate = record(value);\n if (!candidate || typeof candidate.ok !== \"boolean\" ||\n typeof candidate.operation !== \"string\" || !OPERATION_NAMES.has(candidate.operation as BrowserOperationName)) return null;\n const operation = candidate.operation as BrowserOperationName;\n const targetCandidate = record(candidate.target);\n const target = targetCandidate &&\n (targetCandidate.page === undefined || typeof targetCandidate.page === \"string\") &&\n typeof targetCandidate.url === \"string\" && typeof targetCandidate.title === \"string\" &&\n Number.isInteger(targetCandidate.revision)\n ? {\n ...(typeof targetCandidate.page === \"string\" ? { page: targetCandidate.page } : {}),\n url: targetCandidate.url,\n title: targetCandidate.title,\n revision: targetCandidate.revision as number,\n }\n : null;\n if (candidate.ok) return target ? { ok: true, operation, target, value: candidate.value } : null;\n const error = record(candidate.error);\n const codes = new Set<BrowserOperationErrorCode>([\n \"APPROVAL_REQUIRED\", \"INVALID_INPUT\", \"NOT_AVAILABLE\", \"NOT_FOUND\",\n \"STALE_PAGE\", \"TIMED_OUT\", \"UNSUPPORTED\", \"FAILED\",\n ]);\n if (!error || typeof error.code !== \"string\" || !codes.has(error.code as BrowserOperationErrorCode) ||\n typeof error.message !== \"string\") return null;\n return {\n ok: false,\n operation,\n error: { code: error.code as BrowserOperationErrorCode, message: error.message },\n ...(target ? { target } : {}),\n };\n}\n", "/**\n * The provider: one Playwright connection over CDP, one page, and the\n * `supercode/browser-provider-v1` envelope around each operation call.\n */\n\nimport { timingSafeEqual } from \"node:crypto\";\nimport { chromium, type Browser, type Page } from \"playwright-core\";\nimport {\n SUPERCODE_BROWSER_OPERATION_PROTOCOL,\n SUPERCODE_BROWSER_PROVIDER_PROTOCOL,\n type BrowserOperationName,\n type BrowserOperationResult,\n} from \"./protocol.js\";\nimport { PlaywrightOperationExecutor } from \"./executor.js\";\n\n/** Bound for one provider request (`BROWSER_PROVIDER_MAX_REQUEST_BYTES`). */\nexport const MAX_REQUEST_BYTES = 256 * 1024;\n/** Bound for one provider response (`BROWSER_PROVIDER_MAX_RESPONSE_BYTES`). */\nexport const MAX_RESPONSE_BYTES = 1024 * 1024;\n\nexport interface PlaywrightBrowserProviderOptions {\n /** CDP endpoint: `http://\u2026` (resolved through `/json/version`) or `ws://\u2026`. */\n cdpUrl: string;\n /** Hex token every request must carry. */\n token: string;\n /** True when the endpoint dispatches `isTrusted:false` input (an AlmostCDP endpoint). */\n syntheticEvents: boolean;\n}\n\n/** The provider-v1 response envelope the harness reads. */\nexport interface ProviderResponse {\n protocol: typeof SUPERCODE_BROWSER_PROVIDER_PROTOCOL;\n id: string | null;\n result: BrowserOperationResult;\n}\n\nexport interface PlaywrightBrowserProvider {\n readonly token: string;\n /** Validate one provider-v1 request and answer it with a provider-v1 response. */\n handle(request: unknown): Promise<ProviderResponse>;\n /** Disconnect from the endpoint. The browser itself is left running. */\n close(): Promise<void>;\n}\n\ninterface Connection {\n browser: Browser;\n page: Page;\n executor: PlaywrightOperationExecutor;\n}\n\nfunction record(value: unknown): Record<string, unknown> | null {\n return typeof value === \"object\" && value !== null && !Array.isArray(value) ? value as Record<string, unknown> : null;\n}\n\nfunction tokenMatches(expected: string, actual: unknown): boolean {\n if (typeof actual !== \"string\") return false;\n const left = Buffer.from(expected);\n const right = Buffer.from(actual);\n return left.length === right.length && timingSafeEqual(left, right);\n}\n\nfunction callOperation(call: unknown): BrowserOperationName {\n const operation = record(call)?.operation;\n return typeof operation === \"string\" && operation.startsWith(\"browser.\") ? operation as BrowserOperationName : \"browser.status\";\n}\n\nexport function createPlaywrightBrowserProvider(options: PlaywrightBrowserProviderOptions): PlaywrightBrowserProvider {\n if (!/^[0-9a-f]{32,}$/i.test(options.token))\n throw new Error(\"The provider token must be at least 32 hexadecimal characters.\");\n let connection: Connection | null = null;\n let queue: Promise<unknown> = Promise.resolve();\n\n const usable = (candidate: Connection | null): candidate is Connection =>\n candidate !== null && candidate.browser.isConnected() && !candidate.page.isClosed();\n\n const connect = async (): Promise<Connection> => {\n const previous = connection;\n connection = null;\n // The provider is attached to a browser it does not own: it changes none\n // of that browser's defaults (download policy, focus emulation, media).\n const browser = previous?.browser.isConnected() ? previous.browser : await chromium.connectOverCDP(options.cdpUrl, { noDefaults: true });\n const page = browser.contexts()[0]?.pages()[0];\n if (!page) {\n if (browser !== previous?.browser) await browser.close().catch(() => undefined);\n throw new Error(\"The browser has no open page.\");\n }\n const executor = new PlaywrightOperationExecutor(page, {\n syntheticEvents: options.syntheticEvents,\n endpoint: browser.version(),\n });\n connection = { browser, page, executor };\n return connection;\n };\n\n const failure = (operation: BrowserOperationName, code: \"INVALID_INPUT\" | \"NOT_AVAILABLE\", message: string): BrowserOperationResult =>\n ({ ok: false, operation, error: { code, message } });\n\n const run = async (call: unknown): Promise<BrowserOperationResult> => {\n let current = connection;\n if (!usable(current)) {\n // One reconnect per call; a second failure is the answer.\n try {\n current = await connect();\n } catch (error) {\n return failure(callOperation(call), \"NOT_AVAILABLE\",\n `The CDP endpoint is not available: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n return current.executor.execute(call);\n };\n\n return {\n token: options.token,\n async handle(request: unknown): Promise<ProviderResponse> {\n const envelope = record(request);\n const id = typeof envelope?.id === \"string\" && envelope.id.length > 0 && envelope.id.length <= 256 ? envelope.id : null;\n const respond = (result: BrowserOperationResult): ProviderResponse =>\n ({ protocol: SUPERCODE_BROWSER_PROVIDER_PROTOCOL, id, result });\n const call = envelope?.call;\n const operation = callOperation(call);\n if (!envelope || envelope.protocol !== SUPERCODE_BROWSER_PROVIDER_PROTOCOL || id === null ||\n record(call)?.protocol !== SUPERCODE_BROWSER_OPERATION_PROTOCOL)\n return respond(failure(operation, \"INVALID_INPUT\", \"Invalid browser provider request envelope.\"));\n if (!tokenMatches(options.token, envelope.token))\n return respond(failure(operation, \"INVALID_INPUT\", \"Invalid browser provider token.\"));\n // One page, one caller at a time: operations never interleave on it.\n const result = queue.then(() => run(call));\n queue = result.catch(() => undefined);\n return respond(await result);\n },\n async close(): Promise<void> {\n const current = connection;\n connection = null;\n // For a CDP connection `close()` closes the websocket, not the browser.\n await current?.browser.close().catch(() => undefined);\n },\n };\n}\n", "/**\n * Two framings of the same provider-v1 envelope.\n *\n * - TCP (the harness's wire, `crates/harness/src/browser.rs`): one\n * newline-terminated JSON request per connection, one JSON response, close.\n * Discovery is an owner-only record under `<providers dir>/browser/<id>.json`.\n * - HTTP: `POST /` with the request JSON as the body, the response JSON as the\n * body, for a host that can reach the provider only by HTTP.\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport * as fs from \"node:fs\";\nimport * as http from \"node:http\";\nimport * as net from \"node:net\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport { SUPERCODE_BROWSER_PROVIDER_PROTOCOL } from \"./protocol.js\";\nimport { PLAYWRIGHT_IMPLEMENTATION } from \"./executor.js\";\nimport {\n MAX_REQUEST_BYTES,\n MAX_RESPONSE_BYTES,\n type PlaywrightBrowserProvider,\n type ProviderResponse,\n} from \"./provider.js\";\n\nconst HOST = \"127.0.0.1\";\n\nexport interface ServeHandle {\n framing: \"tcp\" | \"http\";\n port: number;\n /** The discovery record written for the TCP framing. */\n discoveryPath?: string;\n stop(): Promise<void>;\n}\n\n/** Supercode's providers directory, resolved as `browser_provider_directory()` resolves its parent. */\nexport function defaultProvidersDirectory(): string {\n const env = process.env;\n const root = env.SUPERCODE_HOME ? env.SUPERCODE_HOME\n : env.XDG_CONFIG_HOME ? path.join(env.XDG_CONFIG_HOME, \"supercode\")\n : env.HOME ? path.join(env.HOME, \".config\", \"supercode\")\n : path.join(os.tmpdir(), \"supercode\");\n return path.join(root, \"providers\");\n}\n\nfunction invalid(id: string | null, message: string): ProviderResponse {\n return {\n protocol: SUPERCODE_BROWSER_PROVIDER_PROTOCOL,\n id,\n result: { ok: false, operation: \"browser.status\", error: { code: \"INVALID_INPUT\", message } },\n };\n}\n\n/** Serialize a response inside the 1 MiB bound, replacing an oversized result with a bounded failure. */\nfunction encode(response: ProviderResponse): string {\n const text = JSON.stringify(response);\n if (Buffer.byteLength(text) <= MAX_RESPONSE_BYTES) return text;\n return JSON.stringify({\n ...response,\n result: {\n ok: false,\n operation: response.result.operation,\n error: { code: \"FAILED\", message: \"The operation result exceeds the provider's 1 MiB response bound.\" },\n },\n });\n}\n\nasync function answer(provider: PlaywrightBrowserProvider, body: string): Promise<ProviderResponse> {\n let request: unknown;\n try {\n request = JSON.parse(body);\n } catch {\n return invalid(null, \"The request is not JSON.\");\n }\n return provider.handle(request);\n}\n\nexport interface TcpServeOptions {\n port: number;\n /** Parent of `browser/`; defaults to Supercode's providers directory. */\n providersDirectory?: string;\n /** Workspace the discovery record is scoped to; defaults to the working directory. */\n workspace?: string;\n syntheticEvents: boolean;\n}\n\nexport async function serveTcp(provider: PlaywrightBrowserProvider, options: TcpServeOptions): Promise<ServeHandle> {\n const server = net.createServer((socket) => {\n const chunks: Buffer[] = [];\n let size = 0;\n let done = false;\n const finish = (response: ProviderResponse): void => {\n if (socket.destroyed) return;\n socket.end(`${encode(response)}\\n`);\n };\n socket.setTimeout(15_000, () => socket.destroy());\n socket.on(\"error\", () => socket.destroy());\n socket.on(\"data\", (chunk: Buffer) => {\n if (done) return;\n const newline = chunk.indexOf(0x0a);\n const part = newline === -1 ? chunk : chunk.subarray(0, newline);\n size += part.length + (newline === -1 ? 0 : 1);\n if (size > MAX_REQUEST_BYTES) {\n done = true;\n finish(invalid(null, \"The request exceeds 256 KiB.\"));\n return;\n }\n chunks.push(part);\n if (newline === -1) return;\n done = true;\n void answer(provider, Buffer.concat(chunks).toString(\"utf8\")).then(finish, (error: unknown) =>\n finish(invalid(null, error instanceof Error ? error.message : String(error))));\n });\n socket.on(\"end\", () => {\n if (done) return;\n done = true;\n // A request without its newline is still one request.\n void answer(provider, Buffer.concat(chunks).toString(\"utf8\")).then(finish, () => socket.destroy());\n });\n });\n await new Promise<void>((resolve, reject) => {\n server.once(\"error\", reject);\n server.listen(options.port, HOST, () => { server.off(\"error\", reject); resolve(); });\n });\n const port = (server.address() as net.AddressInfo).port;\n\n const directory = path.join(options.providersDirectory ?? defaultProvidersDirectory(), \"browser\");\n fs.mkdirSync(directory, { recursive: true, mode: 0o700 });\n fs.chmodSync(directory, 0o700);\n const id = `playwright.cdp.${port}`;\n const discoveryPath = path.join(directory, `${id}.json`);\n const workspace = fs.realpathSync(options.workspace ?? process.cwd());\n const discovery = {\n protocol: SUPERCODE_BROWSER_PROVIDER_PROTOCOL,\n workspace,\n host: HOST,\n port,\n token: provider.token,\n provider: {\n id,\n name: \"Playwright over CDP\",\n fidelity: {\n implementation: PLAYWRIGHT_IMPLEMENTATION,\n transport: \"cdp\",\n accessibility: \"playwright-aria-snapshot\",\n syntheticEvents: options.syntheticEvents,\n trustedInput: !options.syntheticEvents,\n script: \"node-playwright-page\",\n },\n },\n };\n const temporary = `${discoveryPath}.${randomBytes(6).toString(\"hex\")}.tmp`;\n fs.writeFileSync(temporary, `${JSON.stringify(discovery, null, 2)}\\n`, { mode: 0o600, flag: \"wx\" });\n fs.renameSync(temporary, discoveryPath);\n\n return {\n framing: \"tcp\",\n port,\n discoveryPath,\n async stop(): Promise<void> {\n fs.rmSync(discoveryPath, { force: true });\n await new Promise<void>((resolve) => server.close(() => resolve()));\n },\n };\n}\n\nexport interface HttpServeOptions {\n port: number;\n}\n\nexport async function serveHttp(provider: PlaywrightBrowserProvider, options: HttpServeOptions): Promise<ServeHandle> {\n const server = http.createServer((request, response) => {\n const send = (status: number, body?: string): void => {\n response.writeHead(status, body === undefined ? {} : { \"content-type\": \"application/json\" });\n response.end(body);\n };\n const pathname = (request.url ?? \"/\").split(\"?\", 1)[0];\n if (pathname !== \"/\") { request.resume(); send(404); return; }\n if (request.method !== \"POST\") { request.resume(); response.setHeader(\"allow\", \"POST\"); send(405); return; }\n const chunks: Buffer[] = [];\n let size = 0;\n let rejected = false;\n request.on(\"data\", (chunk: Buffer) => {\n if (rejected) return;\n size += chunk.length;\n if (size > MAX_REQUEST_BYTES) {\n rejected = true;\n send(413, encode(invalid(null, \"The request exceeds 256 KiB.\")));\n request.destroy();\n return;\n }\n chunks.push(chunk);\n });\n request.on(\"end\", () => {\n if (rejected) return;\n let body: unknown;\n try {\n body = JSON.parse(Buffer.concat(chunks).toString(\"utf8\"));\n } catch {\n send(400, encode(invalid(null, \"The request is not JSON.\")));\n return;\n }\n void provider.handle(body).then(\n (result) => send(200, encode(result)),\n (error: unknown) => send(500, encode(invalid(null, error instanceof Error ? error.message : String(error)))),\n );\n });\n });\n await new Promise<void>((resolve, reject) => {\n server.once(\"error\", reject);\n server.listen(options.port, HOST, () => { server.off(\"error\", reject); resolve(); });\n });\n const port = (server.address() as net.AddressInfo).port;\n return {\n framing: \"http\",\n port,\n async stop(): Promise<void> {\n await new Promise<void>((resolve) => server.close(() => resolve()));\n },\n };\n}\n", "/**\n * `supercode-browser-playwright --cdp-url <url>\n * (--tcp <port> [--providers-dir <dir>] [--workspace <path>] | --http <port>)\n * [--token <hex>] [--synthetic-events]`\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport { parseArgs } from \"node:util\";\nimport { createPlaywrightBrowserProvider } from \"./provider.js\";\nimport { serveHttp, serveTcp, type ServeHandle } from \"./serve.js\";\n\nconst USAGE = \"usage: supercode-browser-playwright --cdp-url <url> \" +\n \"(--tcp <port> [--providers-dir <dir>] [--workspace <path>] | --http <port>) \" +\n \"[--token <hex>] [--synthetic-events]\";\n\nfunction port(value: string, flag: string): number {\n const parsed = Number(value);\n if (!/^\\d+$/.test(value) || parsed > 65_535) throw new Error(`${flag} must be a port number (0 picks a free one).`);\n return parsed;\n}\n\nexport async function main(argv: readonly string[]): Promise<ServeHandle> {\n const { values } = parseArgs({\n args: [...argv],\n strict: true,\n allowPositionals: false,\n options: {\n \"cdp-url\": { type: \"string\" },\n tcp: { type: \"string\" },\n http: { type: \"string\" },\n \"providers-dir\": { type: \"string\" },\n workspace: { type: \"string\" },\n token: { type: \"string\" },\n \"synthetic-events\": { type: \"boolean\", default: false },\n },\n });\n const cdpUrl = values[\"cdp-url\"];\n if (!cdpUrl) throw new Error(`--cdp-url is required.\\n${USAGE}`);\n if ((values.tcp === undefined) === (values.http === undefined))\n throw new Error(`Exactly one of --tcp and --http is required.\\n${USAGE}`);\n if (values.http !== undefined && (values[\"providers-dir\"] !== undefined || values.workspace !== undefined))\n throw new Error(`--providers-dir and --workspace belong to the TCP framing.\\n${USAGE}`);\n if (values.http !== undefined && values.token === undefined)\n throw new Error(\"--http requires --token: the host that calls the provider passes it.\");\n const token = values.token ?? randomBytes(32).toString(\"hex\");\n const syntheticEvents = values[\"synthetic-events\"] ?? false;\n const provider = createPlaywrightBrowserProvider({ cdpUrl, token, syntheticEvents });\n const handle = values.tcp !== undefined\n ? await serveTcp(provider, {\n port: port(values.tcp, \"--tcp\"),\n syntheticEvents,\n ...(values[\"providers-dir\"] !== undefined ? { providersDirectory: values[\"providers-dir\"] } : {}),\n ...(values.workspace !== undefined ? { workspace: values.workspace } : {}),\n })\n : await serveHttp(provider, { port: port(values.http!, \"--http\") });\n process.stdout.write(`${JSON.stringify({ listening: { framing: handle.framing, port: handle.port } })}\\n`);\n let stopping = false;\n const stop = (): void => {\n if (stopping) return;\n stopping = true;\n void Promise.allSettled([handle.stop(), provider.close()]).then(() => process.exit(0));\n };\n process.once(\"SIGINT\", stop);\n process.once(\"SIGTERM\", stop);\n process.once(\"SIGHUP\", stop);\n return handle;\n}\n"],
|
|
5
|
+
"mappings": ";AAOA,SAAS,cAA2D;;;ACkD7D,IAAM,qBAAN,cAAiC,MAAM;AAAC;AAGxC,IAAM,oBAAN,cAAgC,MAAM;AAAC;AASvC,IAAM,kBAAN,cAA8B,MAAM;AAAC;AAE5C,IAAM,QAAQ;AACd,IAAM,QAAQ;AACd,IAAM,YAAY;AAClB,IAAM,gBAAgB;AAYtB,SAAS,YAAY,OAAkC;AACrD,QAAM,SAAS,CAAC,YAA8B;AAC5C,QAAI,CAAC,MAAM,KAAM,QAAO;AACxB,aAAS,OAAuB,SAAS,QAAQ;AAC/C,UAAI,KAAK,QAAQ,MAAM,IAAI,EAAG,QAAO;AACrC,YAAM,SAAyB,KAAK;AACpC,aAAO,WAAY,KAAK,YAAY,EAAiB,QAAQ;AAAA,IAC/D;AACA,WAAO;AAAA,EACT;AACA,QAAM,QAAQ,CAAC,YAA8B,gCAAgC,KAAK,QAAQ,OAAO;AACjG,MAAI,MAAM,SAAS,SAAS;AAE1B,QAAI,UAA0B,SAAS,iB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