/** * ONE implementation per tool, built only on the browser-neutral Driver contract in driver.ts * (ADR-001), used by BOTH Chrome (via cdp/driver.ts's createCdpDriver()) and Firefox (via * bidi/driver.ts's createFirefoxDriver()). This file replaces the split that used to exist * between src/tools/*.ts (raw CDP, Chrome only) and src/neutral.ts (Driver-based, Firefox only) * for 20 of the 23 tools below. The other three, the list_cookies/set_cookie/delete_cookies * cookie group, landed here directly and never had a Chrome-only copy. * * THE HARD REQUIREMENT this file exists to satisfy: Chrome's return shape, timing, and quirks * stay byte-identical to what src/tools/*.ts produced before this migration: that already * shipped to npm. Where the clean Driver abstraction and that requirement conflicted, the * requirement won; every such place is called out in a comment at the call site. The most * significant ones: * - take_snapshot's uid is rendered as a bare digit for the "cdp" scheme (matching the legacy * backendDOMNodeId-as-uid contract) rather than the driver's own tagged "cdp:N" form, and its * extras (checked/expanded/disabled/url/focused) keep the legacy per-key quoting AND the * "expanded" quirk (included even when literally "false") rather than a clean uniform rule. * - navigate_page's field names (frameId, not contextId) and waitedFor vocabulary (load / * domcontentloaded / frameStoppedLoading / navigate-only) are the legacy CDP tool's, not the * Driver's own (committed / timeout). * - Every nested `target` object in a result is the legacy 3-field {id,url,title}: PageInfo's * additive `type` field is deliberately dropped there (list_pages is the one place `type` is * part of the contract). * * NOT here: list_console_messages / get_console_message / list_network_requests / * get_network_request / mock_request / list_mocks / clear_mocks. Chrome's versions of those 7 * tools are built on src/tools/recorder.ts, a disk-persisted, cross-process capture keyed by * target id (rec-.jsonl) with a materially richer shape (ConsoleEntry/NetworkRequest * correlation, per-rule hit counts, dedup-by-pattern+method). Firefox's existing implementation * (now in src/bidi-tools.ts) is a same-process, in-memory event buffer with a different shape. * Unifying them safely would mean either dropping Chrome's cross-process persistence (a real * behavior change to something that ships today) or teaching Firefox to write the same JSONL * format (new feature work, not a safety-preserving migration). Per the explicit instruction that * behavior outranks the abstraction, these 7 stay two implementations; see the migration report. */ import { focusDenied } from "./focusPolicy.ts"; import { mkdir, writeFile } from "node:fs/promises"; import { dirname, join } from "node:path"; import type { BandedCapture, BrowserCookie, BrowserDriver, Capability, DragDestination, DriverUid, ElementLocator, NavigateResult, PageDriver, PageInfo, SnapshotNode, TextInputPath, } from "./driver.ts"; import { isTiledCapture } from "./driver.ts"; import { stitchPngBandsToFile } from "./png.ts"; import type { TargetSelector } from "./types.ts"; import { assertLeaseOk, chromeLeaseBackend, claimLease, defaultLabel, leaseTtlMs, listLeases, readLease, releaseLeaseFor, requireLease, type LeaseBackend, type LeaseStaleReason, type LeaseToken, } from "./leases.ts"; import { installBeacon, probeRendererActivity, rendererProbeSupported } from "./activity.ts"; import { newTrackedPage, originIndex, readOrigin, recordOrigin, resolveLiveLabel, type PageOrigin } from "./origins.ts"; import { isWorkerSelector, WORKER_SELECTOR_PAGE_ONLY_MESSAGE, WORKER_SELECTOR_UNSUPPORTED_MESSAGE } from "./workers.ts"; import { FRAME_SELECTOR_PAGE_ONLY_MESSAGE, FRAME_SELECTOR_UNSUPPORTED_MESSAGE, isFrameSelector } from "./frames.ts"; import { reapAllowed, reapStaleAgentTabs, type ReapedTab } from "./reap.ts"; import { CONTEXT_AUTO_EVALUATE, CONTEXT_AUTO_NEEDS_SELECTOR, CONTEXT_UNSUPPORTED_MESSAGE, ContextSelectorError, parseContextSelector, type ExecutionContextInfo, type SettleOptions, } from "./contexts.ts"; import { ACCNAME_HELPERS_SOURCE, MAX_NAME_LENGTH } from "./bidi/snapshot.ts"; import { allEndpoints, currentEndpoint, isDefaultEndpoint, withEndpointScope } from "./endpoints.ts"; const ARTIFACT_DIR = process.env.CDP_ARTIFACT_DIR ?? "/tmp/cdp-toolkit"; class SharedToolError extends Error {} /** Trim a PageInfo down to the legacy 3-field {id,url,title} target shape used everywhere except list_pages. */ function target3(p: PageInfo): { id: string; url: string; title: string } { return { id: p.id, url: p.url, title: p.title }; } /** Same discriminator leases-tools.ts uses: the driver's own uid scheme tag * ("cdp" for Chrome, "bidi" for Firefox). */ function backendOf(driver: BrowserDriver): LeaseBackend { // Chrome's key carries the dispatch scope's named endpoint (chrome@); see LeaseBackend. return driver.scheme === "bidi" ? "firefox" : chromeLeaseBackend(); } /* -------------------------------- page acquisition -------------------------------- */ /** Acquire, run, always release: the Driver counterpart of client.ts's withPage. */ async function withPage(driver: BrowserDriver, target: TargetSelector | undefined, fn: (page: PageDriver) => Promise): Promise { const page = await driver.page(target); try { return await fn(page); } finally { await page.release(); } } /** Exported for leases-tools.ts's release_page{target}, which needs exactly this * gate: resolving through here is what authorizes the release. */ export async function resolvePage(driver: BrowserDriver, selector?: TargetSelector): Promise { const pages = await driver.listPages(); const hit = await pickPage(driver, pages, selector); // THE third choke point. close_page and select_page resolve here and nowhere // else, so the lease check has to be here too, not only in resolveTarget / // resolveContext. Closing someone else's leased tab is the worst version of // the collision this feature exists to stop. // // Deliberately NOT passing liveIds, matching resolveTarget and resolveContext. // For every branch but one it would be inert (hit is an element of `pages`), // and for the bare-id branch it would be actively wrong: that branch can // return a non-page target off the `all:true` listing, whose id is absent // from `pages`, so passing pages' ids would report a perfectly healthy lease // as target-gone and wave the caller straight through it. await assertLeaseOk(backendOf(driver), hit.id, { url: hit.url, title: hit.title }); return hit; } /** * Same TargetSelector grammar as client.ts's resolveTarget. Matches its one asymmetry exactly: * every branch resolves against page-type targets only EXCEPT a bare-id lookup, which (like * legacy resolveTarget's `targets.find`) searches the FULL unfiltered listing, so passing an * exact non-page targetId (a worker, an iframe) still resolves. * * THE GATE-FREE HALF of resolvePage, and exported for the one caller that needs * resolution WITHOUT authorization: claim_page{target}. Everything else must go * through resolvePage. Claiming cannot run assertLeaseOk, because under * CDP_REQUIRE_LEASE the gate AUTO-ACQUIRES a lease on an unleased tab, so a * claim routed through it would take the tab twice — once implicitly with an * auto lease, then again explicitly, and the second claim would collide with * the first. Refusing a tab another process holds is still enforced, one layer * down, by claimLease's own conflict check. */ export async function pickPage(driver: BrowserDriver, pages: PageInfo[], selector?: TargetSelector): Promise { if (selector === undefined || selector === "active") { if (!pages.length) throw new SharedToolError("no page targets open"); return pages[0]!; } if (selector.startsWith("index:")) { const p = pages[Number(selector.slice(6))]; if (!p) throw new SharedToolError(`no page target at index ${selector.slice(6)} (have ${pages.length})`); return p; } if (selector.startsWith("url:")) { const needle = selector.slice(4); const p = pages.find((x) => x.url.includes(needle)); if (!p) throw new SharedToolError(`no page url containing '${needle}'`); return p; } if (selector.startsWith("title:")) { const needle = selector.slice(6); const p = pages.find((x) => x.title.includes(needle)); if (!p) throw new SharedToolError(`no page title containing '${needle}'`); return p; } if (selector.startsWith("label:")) return pickByLabel(driver, pages, selector.slice(6)); if (isWorkerSelector(selector)) { // THE PAGE-ONLY CONTRACT, STATED OUT LOUD. Every caller of pickPage // (resolvePage -> close_page / select_page / release_page, claim_page's // takeover) acts on a TAB, and the 1.9.0 "worker:" arm is deliberately NOT // implemented here: it resolves against the page-only listing these callers // pass, which by construction never contains a worker, so the arm could // only ever miss. Refusing with the reason beats falling through to the // bare-id lookup, whose "no target with id 'worker:foo'" reads as a typo. // The arm lives in client.ts's pickTarget (Chrome's all-targets resolver), // and only evaluate_script routes to it. throw new SharedToolError( backendOf(driver) === "firefox" ? WORKER_SELECTOR_UNSUPPORTED_MESSAGE : WORKER_SELECTOR_PAGE_ONLY_MESSAGE, ); } if (isFrameSelector(selector)) { // Same contract as the worker: arm above, same reason. Every caller of // pickPage (close_page / select_page / release_page via resolvePage, and // claim_page's takeover) acts on a TAB; an out-of-process iframe has no // independent existence to close, select, release or claim. Refusing with // the reason beats the bare-id fall-through's "no target with id // 'frame:foo'", which reads as a typo. The arm itself lives in client.ts's // pickTarget and every other target-taking tool accepts it. throw new SharedToolError( backendOf(driver) === "firefox" ? FRAME_SELECTOR_UNSUPPORTED_MESSAGE : FRAME_SELECTOR_PAGE_ONLY_MESSAGE, ); } const exactPage = pages.find((x) => x.id === selector); if (exactPage) return exactPage; const all = await driver.listPages({ all: true }); const exact = all.find((x) => x.id === selector); if (exact) return exact; throw new SharedToolError(`no target with id '${selector}'`); } /** * "label:" resolution for pickPage. The lookup itself (both stores, * live-scoped) is shared with client.ts's pickTarget and bidi/driver.ts's * pickContext via origins.ts's resolveLiveLabel, so the three copies of the * selector grammar cannot drift on what counts as a hit, a miss or an * ambiguity. Only the error wording is local, matching this file's * SharedToolError idiom. * * Nothing is reaped here: this is a read, not a maintenance pass, and pickPage * stays gate-free and side-effect-free over its inputs. */ async function pickByLabel(driver: BrowserDriver, pages: PageInfo[], label: string): Promise { const { matchIds, knownLabels } = await resolveLiveLabel(backendOf(driver), label, pages.map((x) => x.id)); if (matchIds.length > 1) { throw new SharedToolError( `label 'label:${label}' matches more than one live target: ${matchIds.join(", ")}. Resolve by target id instead.`, ); } if (matchIds.length === 1) { const p = pages.find((x) => x.id === matchIds[0]); if (p) return p; } throw new SharedToolError( knownLabels.length ? `no live target with label '${label}' (labels currently in use: ${knownLabels.join(", ")})` : `no live target with label '${label}' (no labels are currently assigned to any open target)`, ); } /* ------------------------------ execution contexts (issue #12) ------------------------------ */ /** The `context` / settle params every context-aware tool shares. */ interface ContextArgs { context?: number | string; settleMs?: number; settleCapMs?: number; } function settleOf(args: ContextArgs): SettleOptions { return { ...(args.settleMs !== undefined ? { quietMs: args.settleMs } : {}), ...(args.settleCapMs !== undefined ? { capMs: args.settleCapMs } : {}) }; } function wantsContext(args: ContextArgs): boolean { return args.context !== undefined && args.context !== null; } /** Refuse a context param on a backend without "runtime.contexts", before any page is acquired. */ function assertContextSupport(driver: BrowserDriver, tool: string, used: boolean): void { if (used && !driver.capabilities.has("runtime.contexts")) throw new SharedToolError(`${tool}: ${CONTEXT_UNSUPPORTED_MESSAGE}`); } /** * Pin `page` to the requested context, if any. Returns the result field describing the pick * (`{context:{id,frameId,frameUrl}}`), or `{}` when no context was asked for, so an unchanged * call returns a byte-identical result. A bad selector string is a SharedToolError up front. */ async function applyContext(page: PageDriver, tool: string, args: ContextArgs, css?: string): Promise<{ context?: { id: number; frameId?: string; frameUrl?: string } }> { if (!wantsContext(args)) return {}; if (!page.useContext) throw new SharedToolError(`${tool}: ${CONTEXT_UNSUPPORTED_MESSAGE}`); let c: ExecutionContextInfo; try { parseContextSelector(args.context); c = await page.useContext(args.context, { css, settle: settleOf(args) }); } catch (e) { if (e instanceof ContextSelectorError) throw new SharedToolError(`${tool}: ${e.message}`); throw e; } return { context: { id: c.id, ...(c.frameId ? { frameId: c.frameId } : {}), ...(c.frameUrl ? { frameUrl: c.frameUrl } : {}) } }; } export async function listContexts( driver: BrowserDriver, args: { target?: TargetSelector; settleMs?: number; settleCapMs?: number } = {}, ): Promise<{ contexts: ExecutionContextInfo[]; count: number; target: { id: string; url: string; title: string } }> { assertContextSupport(driver, "list_contexts", true); return withPage(driver, args.target, async (page) => { if (!page.listContexts) throw new SharedToolError(`list_contexts: ${CONTEXT_UNSUPPORTED_MESSAGE}`); let contexts: ExecutionContextInfo[]; try { contexts = await page.listContexts(settleOf(args)); } catch (e) { if (e instanceof ContextSelectorError) throw new SharedToolError(`list_contexts: ${e.message}`); throw e; } return { contexts, count: contexts.length, target: target3(page.info) }; }); } /* -------------------------------- element locators -------------------------------- */ /** The css string of a css locator, for context 'auto' (which needs one to match frames with). */ function cssOf(loc: ElementLocator): string | undefined { return "css" in loc ? loc.css : undefined; } function locatorOf(args: { uid?: DriverUid; selector?: string }): ElementLocator { const hasUid = args.uid !== undefined && args.uid !== null && args.uid !== ("" as unknown); const hasSelector = typeof args.selector === "string" && args.selector.length > 0; if (hasUid === hasSelector) throw new SharedToolError("provide exactly one of { uid } or { selector }"); return hasUid ? { uid: args.uid as DriverUid } : { css: args.selector as string }; } /* -------------------------------- pages (4) -------------------------------- */ /** * A page listing entry, PageInfo plus provenance. STRICTLY ADDITIVE: {id, url, * title, type} are unchanged in name, type and value, because consumers read * them today. */ export interface ListedPage extends PageInfo { /** The named CDP endpoint this page lives on (src/endpoints.ts). Present on * every row from a NON-default endpoint, and on every row of an * allEndpoints listing, so a caller can build an `endpoint:/` * selector. Absent on a default-endpoint listing, which keeps that output * byte-identical to before named endpoints existed. */ endpoint?: string; /** "agent" when the creation ledger has a record for this target. Otherwise * "unknown", NEVER "human": the absence of a record is not proof that a * person opened the tab. See src/origins.ts. */ origin: PageOrigin; /** The creating agent's label. Present only when origin is "agent". */ label?: string; /** When this toolkit created the tab (epoch ms). Only when origin is "agent". */ createdAt?: number; /** Present only when this target HAS a ledger record that could not be read: * the errno, or "unparseable". origin stays "unknown" because provenance is * genuinely unknown, but this field is what keeps an unreadable record from * being reported as a clean "nothing was ever recorded". */ originUnreadable?: string; /** * Present only for a tab under an active, READABLE lease of THIS backend. * idleMs and expiresAt are computed fresh on every call (now-lastUsedAt and * lastUsedAt+ttlMs), never read off disk — same rule as list_leases' own * LeaseRow, and unconditional on `probe`: a lease can exist whether or not a * caller ever passes probe:true, and this costs nothing beyond a lease-dir * read this call already pays for under strict mode. */ lease?: { label: string; pid: number; idleMs: number; expiresAt: number; stale: LeaseStaleReason | false }; /** * Present only when { probe: true } was passed AND this backend can answer * it (see rendererProbeSupported in src/activity.ts) AND this entry is a * page-type target — a worker or iframe has no `window` to carry the beacon * global, so probing one would be a guaranteed false negative rather than a * genuine liveness answer. true when a bounded Runtime.evaluate answered * within budget; false on a timeout, a thrown page-side exception, or a * target the driver could not reach at all — the wedged-tab case this field * exists to surface, reported as data rather than failing the whole call. */ responsive?: boolean; /** Ms since a human last touched this tab, present only where probe:true * answered AND the same round trip found human-attributed beacon data. * Same rule as claim_page/list_leases: absence is "no answer", never "no * human". */ humanActiveMs?: number; } /** * The reap set for the origin ledger: every target the browser currently has, * INCLUDING non-page targets, regardless of what this call is listing. * * Using the filtered page list would be a bug with a plausible disguise: a * default list_pages call drops workers and iframes, so reaping against it * would delete the ledger record of any target that is alive but filtered out. * Returning undefined (which listOrigins reads as "reap nothing") when the * unfiltered listing fails is the same principle one step further: a failed * enumeration must never be able to empty the ledger. */ async function reapSet(driver: BrowserDriver, pages: PageInfo[], all?: boolean): Promise { if (all === true) return pages.map((p) => p.id); try { return (await driver.listPages({ all: true })).map((p) => p.id); } catch { return undefined; } } /** One endpoint's status in a list_pages{allEndpoints:true} result. */ export type EndpointListing = | { endpoint: string; base: string; readOnly: boolean; count: number } | { endpoint: string; base: string; readOnly: boolean; down: true; error: string }; /** * list_pages. With allEndpoints (Chrome only) every configured endpoint is * listed in its own endpoint scope, concurrently: page rows are tagged with * `endpoint`, `endpoints` reports each endpoint's count, and an endpoint that * cannot be reached is reported `{endpoint, down: true, error}` there instead * of failing the call. Each endpoint's reap runs in its own scope, so it * compares that endpoint's leases only against that endpoint's live targets, * and a down endpoint reaps nothing at all. */ export async function listPages( driver: BrowserDriver, args: { all?: boolean; probe?: boolean; allEndpoints?: boolean } = {}, ): Promise<{ pages: ListedPage[]; count: number; reaped?: Array; endpoints?: EndpointListing[] }> { const one = { all: args.all, probe: args.probe }; if (args.allEndpoints === true) { if (driver.scheme === "bidi") throw new SharedToolError("list_pages: allEndpoints needs the Chrome backend; named endpoints are CDP-only"); const results = await Promise.all( allEndpoints().map((ep) => withEndpointScope(ep, () => listPagesOne(driver, one)).then( (r) => ({ ep, r }), (e: unknown) => ({ ep, error: e instanceof Error ? e.message : String(e) }), ), ), ); const pages: ListedPage[] = []; const reaped: Array = []; const endpoints: EndpointListing[] = []; for (const res of results) { const { ep } = res; if ("error" in res) { endpoints.push({ endpoint: ep.name, base: ep.base, readOnly: ep.readOnly, down: true, error: res.error }); continue; } for (const p of res.r.pages) pages.push({ ...p, endpoint: ep.name }); for (const t of res.r.reaped ?? []) reaped.push({ ...t, endpoint: ep.name }); endpoints.push({ endpoint: ep.name, base: ep.base, readOnly: ep.readOnly, count: res.r.count }); } return { pages, count: pages.length, ...(reaped.length ? { reaped } : {}), endpoints }; } const res = await listPagesOne(driver, one); if (driver.scheme !== "bidi") { const ep = currentEndpoint(); if (!isDefaultEndpoint(ep)) { return { ...res, pages: res.pages.map((p) => ({ ...p, endpoint: ep.name })), ...(res.reaped ? { reaped: res.reaped.map((t) => ({ ...t, endpoint: ep.name })) } : {}), }; } } return res; } /** One endpoint's listing: the pre-#15 list_pages body, unchanged. */ async function listPagesOne( driver: BrowserDriver, args: { all?: boolean; probe?: boolean } = {}, ): Promise<{ pages: ListedPage[]; count: number; reaped?: ReapedTab[] }> { // Reap FIRST, so a tab this call is about to close never appears in the // listing it returns, and so the lease read just below never reports a lease // this same call is in the middle of deleting. Under strict mode only: see // requireLease. const backend = backendOf(driver); // Never on a read-only endpoint (#15): reapAllowed. const reaped = requireLease() && reapAllowed(driver) ? await reapStaleAgentTabs(driver, backend) : []; const reapedIds = new Set(reaped.map((r) => r.targetId)); const pages = (await driver.listPages({ all: args.all })).filter((p) => !reapedIds.has(p.id)); // Never let provenance break the listing: originIndex does not throw, and a // missing or unreadable ledger yields an empty map, so every page falls back // to origin "unknown" exactly as a pre-ledger consumer always saw. const ledger = await originIndex(backend, await reapSet(driver, pages, args.all)); const now = Date.now(); // Observability (1.8.0): every READABLE lease of this backend, keyed by // target. Read unconditionally, not gated on `probe`, because a lease can // exist whether or not a caller ever asks for a renderer ping. const leaseByTarget = new Map( (await listLeases({ now, liveIds: pages.map((p) => p.id), liveBackend: backend })) .filter((l) => l.backend === backend && l.unreadable === undefined) .map((l) => [l.targetId, l] as const), ); const doProbe = args.probe === true && rendererProbeSupported(driver); const annotated: ListedPage[] = await Promise.all( pages.map(async (p) => { const rec = ledger.get(p.id); const base: ListedPage = !rec ? { ...p, origin: "unknown" } : rec.unreadable !== undefined ? { ...p, origin: "unknown", originUnreadable: rec.unreadable } : { ...p, origin: "agent", label: rec.label, createdAt: rec.createdAt }; const leaseRow = leaseByTarget.get(p.id); if (leaseRow) { base.lease = { label: leaseRow.label, pid: leaseRow.pid, idleMs: now - leaseRow.lastUsedAt, expiresAt: leaseRow.lastUsedAt + leaseRow.ttlMs, stale: leaseRow.stale }; } // Page-type only: see ListedPage.responsive. Concurrent across pages // (this whole map runs inside Promise.all), so one wedged tab's 500ms // budget never serializes onto the next tab's. if (doProbe && (p.type === undefined || p.type === "page")) { const probe = await probeRendererActivity(driver, backend, p.id, now); base.responsive = probe.responsive; if (probe.humanActiveMs !== undefined) base.humanActiveMs = probe.humanActiveMs; } return base; }), ); // `reaped` is present only when it has something to say, so the common-case // shape is byte-identical to 1.4.0. Silently closing a tab is not acceptable: // if a read closed something, the read says so. return { pages: annotated, count: annotated.length, ...(reaped.length ? { reaped } : {}) }; } export async function newPage( driver: BrowserDriver, args: { url?: string; claim?: boolean; label?: string; ttlMs?: number; focus?: boolean } = {}, ): Promise<{ targetId: string; url: string; hidden?: true; focusDenied?: true; lease?: LeaseToken; label?: string; expiresAt?: number }> { const label = typeof args.label === "string" && args.label.length ? args.label : defaultLabel(); // Creates the tab AND writes its creation record. The record outlives any // lease taken below, which is the point: a released tab is still an agent's. const p = await newTrackedPage(driver, backendOf(driver), { url: args.url, label, focus: args.focus === true }); // Present only for a hidden tab (CDP_HIDDEN_TABS), so the default output is byte-identical. const hidden = { ...(p.hidden === true ? { hidden: true as const } : {}), // Present only when a focus:true was refused (CDP_DENY_FOCUS), so the default output is unchanged. ...(args.focus === true && focusDenied() ? { focusDenied: true as const } : {}), }; // Under strict mode a tab nobody holds is a tab nobody may drive, so creating // one without claiming it would hand back a target the very next call has to // auto-acquire anyway. Doing it here means the tab is never briefly unowned // AND the caller is handed a token it can release with, which matters because // an auto-acquired lease never returns one. const explicit = args.claim === true; if (!explicit && !requireLease()) return { targetId: p.id, url: p.url, ...hidden }; // Atomic in the sense that matters: the tab is claimed before this call // returns, so no other agent can see it unclaimed and take it first. const { record, token } = await claimLease(backendOf(driver), p.id, { label, ttlMs: typeof args.ttlMs === "number" && args.ttlMs > 0 ? args.ttlMs : leaseTtlMs(), // An explicit claim:true stays explicit under strict mode: the caller asked // for the strong tier and must keep getting it, or turning strict on would // silently WEAKEN every existing claim:true call site to pid-only. auto: !explicit, }); // Install the activity beacon on the same terms claim_page does: at claim // time, after the claim, best effort (installBeacon never throws). A tab // beaconed now is a tab that can ANSWER later — when this agent has released // it and a person has picked it up, which is the case the beacon exists for. // Nothing here is read back: a tab created a moment ago has no human history. await installBeacon(driver, p.id); return { targetId: p.id, url: p.url, ...hidden, lease: token, label: record.label, expiresAt: record.lastUsedAt + record.ttlMs }; } export async function closePage( driver: BrowserDriver, args: { target?: TargetSelector }, ): Promise<{ closed: string; success: boolean; leaseReleased?: boolean }> { if (args.target === undefined || args.target === "") throw new SharedToolError("close_page requires an explicit target; refusing to guess which page to close"); const p = await resolvePage(driver, args.target); const res = await driver.closePage(p.id); // A failed close (target refused to close, or was already gone) must leave // the lease intact: the caller still owns a tab that never actually closed, // and releasing it here would let another agent claim a tab this one still // thinks it holds. if (!res.success) return { closed: p.id, success: false, leaseReleased: false }; // Closing a leased tab must not leave its lease file behind waiting on the // TTL. resolvePage above already refused this call unless the caller holds // the lease, so no token is needed here. const released = await releaseLeaseFor(backendOf(driver), p.id); return { closed: p.id, success: true, ...(released.released ? { leaseReleased: true } : {}) }; } async function writeSelectedFile(id: string): Promise { // Read per call, not at import, so a test can point CDP_STATE_DIR at a temp dir. const stateDir = process.env.CDP_STATE_DIR ?? "/tmp/cdp-toolkit"; await mkdir(stateDir, { recursive: true }); await writeFile(join(stateDir, "selected"), id, "utf8"); } /** * Persist the selection; raise the tab only on an explicit focus:true. Raising * (Target.activateTarget / browsingContext.activate) switches the user's visible * tab and takes window focus, so it is never a side effect of selecting. * resolvePage already ran the lease gate, so skipping activatePage loses no check. * * focus:true on a HIDDEN tab (CDP_HIDDEN_TABS) cannot raise it in place: the driver reopens its * URL in a new visible tab and closes the hidden one (see the CDP driver's activatePage). The new * id is what gets selected and returned, with `revealedFrom` naming the closed hidden tab. The * tab's provenance label moves with it, and a lease on the hidden tab is moved to the new tab and * its NEW token returned as `lease`, since the old token names a tab that no longer exists. */ export async function selectPage( driver: BrowserDriver, args: { target?: TargetSelector; focus?: boolean }, ): Promise<{ selected: string; focused: boolean; focusDenied?: true; revealedFrom?: string; lease?: LeaseToken }> { if (args.target === undefined || args.target === "") throw new SharedToolError("select_page requires an explicit target"); const p = await resolvePage(driver, args.target); if (args.focus !== true || focusDenied()) { await writeSelectedFile(p.id); return { selected: p.id, focused: false, ...(args.focus === true ? { focusDenied: true as const } : {}) }; } const shown = await driver.activatePage(p.id); if (shown.revealedFrom === undefined || shown.id === p.id) { await writeSelectedFile(shown.id); return { selected: shown.id, focused: true }; } const moved = await moveRevealedTab(backendOf(driver), shown.revealedFrom, shown.id); await writeSelectedFile(shown.id); return { selected: shown.id, focused: true, revealedFrom: shown.revealedFrom, ...(moved.lease ? { lease: moved.lease } : {}) }; } /** Carry a revealed hidden tab's origin label and lease over to the visible tab that replaced it. */ async function moveRevealedTab(backend: LeaseBackend, fromId: string, toId: string): Promise<{ lease?: LeaseToken }> { const origin = await readOrigin(backend, fromId).catch(() => undefined); if (origin) await recordOrigin(backend, toId, { label: origin.label, now: origin.createdAt }); const lease = await readLease(backend, fromId).catch(() => undefined); if (!lease) return {}; await releaseLeaseFor(backend, fromId); const { token } = await claimLease(backend, toId, { label: lease.label, ttlMs: lease.ttlMs, auto: lease.auto === true }); return { lease: token }; } /* ------------------------------ navigation (2) ------------------------------ */ /** Legacy tools/navigation.ts vocabulary, not the Driver's own (see file header). */ function toLegacyWaitedFor(w: NavigateResult["waitedFor"]): "load" | "domcontentloaded" | "frameStoppedLoading" | "navigate-only" { if (w === "committed") return "frameStoppedLoading"; if (w === "timeout") return "navigate-only"; return w; } export interface LegacyNavigateResult { url: string; frameId: string; reloaded?: boolean; /** Present only on a history traversal, mirroring how `reloaded` is present only on a reload. */ traversed?: "back" | "forward"; waitedFor: "load" | "domcontentloaded" | "frameStoppedLoading" | "navigate-only"; } /** What a navigate_page call is actually asking for. Exactly one of the three. */ export type NavigateMode = | { mode: "url"; url: string } | { mode: "reload" } | { mode: "history"; history: "back" | "forward" }; /** * The three-way exclusivity check for navigate_page's url / reload / history, split out and * exported so every refusal is pinned by a unit test without a browser (the same reason * resolveScrollAnchor and resolveDragDestination live at this layer). * * EXCLUSIVE, NOT PRECEDENCE-ORDERED. `{url, history:"back"}` is a caller who does not know what * they want; silently honoring one of them would navigate somewhere the caller did not ask for and * report success. Refusing names both, so the mistake is visible in the error rather than in the * page that comes back. */ export function resolveNavigateMode(args: { url?: string; reload?: boolean; history?: unknown }): NavigateMode { const reload = args.reload === true; const hasUrl = typeof args.url === "string" && args.url.length > 0; const hasHistory = args.history !== undefined && args.history !== null; const given = [hasUrl ? "url" : "", reload ? "reload" : "", hasHistory ? "history" : ""].filter(Boolean); if (given.length > 1) { throw new SharedToolError(`navigate_page: 'url', 'reload' and 'history' are mutually exclusive (got ${given.join(" + ")})`); } if (hasHistory) { if (args.history !== "back" && args.history !== "forward") { throw new SharedToolError(`navigate_page: 'history' must be 'back' or 'forward' (got ${JSON.stringify(args.history)})`); } return { mode: "history", history: args.history }; } if (reload) return { mode: "reload" }; if (!hasUrl) { throw new SharedToolError( "navigate_page: 'url' is required (or pass reload:true to reload the current page, or history:'back'|'forward' to go back/forward in this tab's session history)", ); } return { mode: "url", url: args.url as string }; } export async function navigatePage( driver: BrowserDriver, args: { target?: TargetSelector; url?: string; reload?: boolean; ignoreCache?: boolean; history?: "back" | "forward"; waitUntil?: "load" | "domcontentloaded"; timeoutMs?: number; }, ): Promise { const mode = resolveNavigateMode(args); return withPage(driver, args.target, async (page) => { const r = await page.navigate(mode.mode === "history" ? { ...args, history: mode.history } : args); return { url: r.url, frameId: r.contextId, ...(r.reloaded ? { reloaded: r.reloaded } : {}), ...(r.traversed ? { traversed: r.traversed } : {}), waitedFor: toLegacyWaitedFor(r.waitedFor), }; }); } export async function waitForText(driver: BrowserDriver, args: { target?: TargetSelector; text: string; timeoutMs?: number; pollMs?: number }): Promise<{ found: true; waitedMs: number }> { if (typeof args.text !== "string" || args.text.length === 0) throw new SharedToolError("wait_for: 'text' is required"); return withPage(driver, args.target, async (page) => { const r = await page.waitForText(args.text, args.timeoutMs ?? 15_000, args.pollMs ?? 250); return { found: true, waitedMs: r.elapsedMs }; }); } /** Contract-mandated alias, matching tools/navigation.ts's exported `waitFor`. */ export const waitFor = waitForText; /* ------------------------------- evaluate (1) ------------------------------- */ /** * The `savePath` result shape. Deliberately carries NO form of the evaluated * value: not the value, not a preview, not a truncation, not a byte prefix. * The whole reason `savePath` exists is that the value may be a credential * (a JWT or session token read out of localStorage), and anything this object * carried would land in the caller's transcript, which is the exact leak the * file sink is here to prevent. `type` is the JS typeof of the value ("null" * for null), which describes the value without disclosing any of it. */ export interface EvaluateScriptSaveResult { path: string; bytes: number; type: string; target: { id: string; url: string; title: string }; } /** * Serialize an evaluated value for the file sink. `undefined` (an expression * with no result) is written as JSON null rather than left unwritten, so the * file always exists and always parses. */ function serializeForSink(value: unknown): string { const json = JSON.stringify(value === undefined ? null : value, null, 2); return json ?? "null"; } /** * THE file sink, shared by every tool that takes a `savePath`: serialize the * value as JSON, write it, and report only where it went and how big it was. * It returns no form of the value on purpose, so a caller of this helper * cannot accidentally leak one back into a response. * * Path resolution matches take_heapsnapshot: an absolute path is used as-is, a * relative one resolves under the artifact dir, and missing parent directories * are created. */ async function writeJsonSink(savePath: string, value: unknown): Promise<{ path: string; bytes: number }> { const path = savePath.startsWith("/") ? savePath : join(ARTIFACT_DIR, savePath); await mkdir(dirname(path), { recursive: true }); const json = serializeForSink(value); await writeFile(path, json, "utf8"); return { path, bytes: Buffer.byteLength(json, "utf8") }; } /** True when a savePath argument actually asks for the sink. An empty string is * treated as absent, so the caller gets the value inline. */ function sinkRequested(savePath?: string): savePath is string { return savePath !== undefined && savePath !== ""; } /** Keys a caller reaches for out of habit from other automation APIs, none of * which this tool reads: the code always goes in 'expression'. Checked in * this order so the error names one wrong key, deterministically, when a * caller happens to pass more than one. */ const EXPRESSION_ALIAS_KEYS = ["function", "code", "js", "script", "fn", "body"] as const; /** * Turn a `worker:` target into a concrete target id, waking an * idle-evicted MV3 service worker on the way when `wake` is not false. * * WHY THIS RETURNS AN ID RATHER THAN DRIVING THE WORKER ITSELF. Once resolved, * a worker is just a target with its own webSocketDebuggerUrl, and a DIRECT * connection to it evaluates exactly like a page does — `Runtime.evaluate` with * `awaitPromise` returns real awaited values there (measured on Chrome 151; * `chrome.storage.local.get(null)` comes back as an object, not undefined). So * the worker rides the ordinary page() acquisition path from here, and every * behavior around it — the args/function form, exception reporting, and above * all savePath's no-value-in-the-response secret hygiene — is the SAME CODE, * not a parallel copy that could quietly diverge on the leak-shaped edge. * * Exported for the unit tests, which need to reach the capability refusal * without a browser. */ export async function resolveWorkerSelectorFor( driver: BrowserDriver, selector: string, wake: boolean, ): Promise { if (!driver.capabilities.has("worker.targets") || typeof driver.resolveWorkerTarget !== "function") { throw new SharedToolError(`evaluateScript: ${WORKER_SELECTOR_UNSUPPORTED_MESSAGE}`); } return driver.resolveWorkerTarget(selector, { wake }); } export async function evaluateScript( driver: BrowserDriver, args: { target?: TargetSelector; expression: string; awaitPromise?: boolean; args?: unknown[]; savePath?: string; wake?: boolean; allContexts?: boolean } & ContextArgs, ): Promise { if (typeof args.expression !== "string" || args.expression.length === 0) { const wrongKey = EXPRESSION_ALIAS_KEYS.find((k) => (args as unknown as Record)[k] !== undefined); if (wrongKey !== undefined) { throw new SharedToolError( `evaluateScript: you passed '${wrongKey}'; the key is 'expression' — function literals go in 'expression', invoked with 'args'.`, ); } throw new SharedToolError("evaluateScript: 'expression' must be a non-empty string"); } if (args.wake !== undefined && typeof args.wake !== "boolean") { throw new SharedToolError("evaluateScript: 'wake' must be a boolean"); } // `wake` is REFUSED on a page selector rather than ignored. Accepting it there // would read as "this call will wake something", and the caller would never // learn that the argument did nothing at all. if (args.wake !== undefined && !isWorkerSelector(args.target)) { throw new SharedToolError( "evaluateScript: 'wake' only applies to a target of the form 'worker:'; a page target is never asleep.", ); } if (args.allContexts !== undefined && typeof args.allContexts !== "boolean") { throw new SharedToolError("evaluateScript: 'allContexts' must be a boolean"); } const allContexts = args.allContexts === true; if (allContexts && wantsContext(args)) { throw new SharedToolError("evaluateScript: pass either 'context' (one context) or 'allContexts' (every context), not both"); } if (args.context === "auto") throw new SharedToolError(`evaluateScript: ${CONTEXT_AUTO_EVALUATE}`); if ((allContexts || wantsContext(args)) && isWorkerSelector(args.target)) { throw new SharedToolError("evaluateScript: a worker has exactly one context; 'context' / 'allContexts' apply to page and iframe targets"); } assertContextSupport(driver, "evaluateScript", allContexts || wantsContext(args)); // Resolved to a bare target id BEFORE acquisition, so the page() call below is // the same one every other selector makes. const target = isWorkerSelector(args.target) ? (await resolveWorkerSelectorFor(driver, args.target, args.wake ?? true)).id : args.target; return withPage(driver, target, async (page) => { let value: unknown; if (allContexts) { if (!page.evaluateAllContexts) throw new SharedToolError(`evaluateScript: ${CONTEXT_UNSUPPORTED_MESSAGE}`); // Rows of {contextId, frameId, origin, name, isDefault, type, frameUrl, value | error}. Under // savePath the WHOLE array goes to the file and only its shape comes back, the same // no-value-in-the-response rule as a single evaluation. try { value = await page.evaluateAllContexts(args.expression, { args: args.args, awaitPromise: args.awaitPromise ?? true, settle: settleOf(args) }); } catch (e) { if (e instanceof ContextSelectorError) throw new SharedToolError(`evaluateScript: ${e.message}`); throw e; } } else { // With `context`, the value is returned raw, exactly as without it: the caller named the // context, so it already knows which one answered. await applyContext(page, "evaluateScript", args); value = await page.evaluate(args.expression, { args: args.args, awaitPromise: args.awaitPromise ?? true }); } // No savePath: byte-identical to the pre-sink behavior, the value itself. // A thrown page-side exception never reaches here, so it still surfaces as // an error rather than being written into the file. if (!sinkRequested(args.savePath)) return value; const { path, bytes } = await writeJsonSink(args.savePath, value); const result: EvaluateScriptSaveResult = { path, bytes, type: value === null ? "null" : typeof value, target: target3(page.info), }; return result; }); } /* -------------------------------- cookies (1) -------------------------------- */ /** * The `savePath` result shape for list_cookies. Same rule as * EvaluateScriptSaveResult: NO cookie value in any form, not even a prefix. A * session cookie IS the credential, so a preview of one is a leaked one. * `count` is how many cookies were written, which tells a caller the read * worked without disclosing anything about what it read. */ export interface ListCookiesSaveResult { path: string; bytes: number; count: number; target: { id: string; url: string; title: string }; } export interface ListCookiesResult { cookies: BrowserCookie[]; count: number; target: { id: string; url: string; title: string }; } /** * Cookie domain matching for the `domain` filter, deliberately small. * * A cookie's own domain carries a leading dot when it was set for subdomains * (".example.test") and none when it was host-only ("example.test"), and a * caller who types "example.test" means both. So the comparison strips a * leading dot from each side and then accepts an exact match or a subdomain of * the filter ("app.example.test" matches "example.test"). That is the whole * rule: no wildcards, no patterns, no query language. */ function cookieDomainMatches(cookieDomain: string, filter: string): boolean { const bare = (d: string) => (d.startsWith(".") ? d.slice(1) : d).toLowerCase(); const c = bare(cookieDomain); const f = bare(filter); return c === f || c.endsWith(`.${f}`); } /** Apply the optional name/domain filters. Exported for the unit tests, which * can then check the matching rule without standing up a browser. */ export function filterCookies(cookies: readonly BrowserCookie[], filter: { domain?: string; name?: string }): BrowserCookie[] { return cookies.filter((c) => { if (filter.name !== undefined && filter.name !== "" && c.name !== filter.name) return false; if (filter.domain !== undefined && filter.domain !== "" && !cookieDomainMatches(c.domain, filter.domain)) return false; return true; }); } /** * Read the cookies of the target page, httpOnly ones included. * * This is the one read that a page script cannot do: document.cookie omits * every httpOnly cookie by design, which is precisely the set a session * credential lives in. Both drivers answer over the protocol's own cookie * store, so the flags come from the browser rather than being inferred. * * With `savePath` set the cookie array is written to that file as JSON and the * response carries only {path, bytes, count, target}: no value, no preview, no * truncation. Without it, the cookies are returned inline. */ export async function listCookies( driver: BrowserDriver, args: { target?: TargetSelector; domain?: string; name?: string; savePath?: string } = {}, ): Promise { return withPage(driver, args.target, async (page) => { const all = await page.getCookies(); const cookies = filterCookies(all, { domain: args.domain, name: args.name }); if (!sinkRequested(args.savePath)) { return { cookies, count: cookies.length, target: target3(page.info) }; } const { path, bytes } = await writeJsonSink(args.savePath, cookies); return { path, bytes, count: cookies.length, target: target3(page.info) }; }); } export interface SetCookieResult { set: true; target: { id: string; url: string; title: string }; } export interface DeleteCookiesResult { deleted: true; target: { id: string; url: string; title: string }; } /** * THE site constraint both write tools share: a cookie has to be attributed to * a site, and `url` or `domain` is how a caller says which. * * Checked here, above the drivers, so the refusal is ONE message on both * backends rather than a CDP protocol error on one and a Firefox no-op on the * other. It throws rather than defaulting to the current page's origin: a * guessed domain writes a real cookie somewhere the caller did not name, and a * cookie written to the wrong site is worse than a call that failed loudly. * * Exported for the unit tests, which pin the message without a browser. */ export function assertCookieSite( args: { url?: string; domain?: string }, toolName: string, ): void { const hasUrl = args.url !== undefined && args.url !== ""; const hasDomain = args.domain !== undefined && args.domain !== ""; if (!hasUrl && !hasDomain) { throw new Error(`${toolName} requires either 'url' or 'domain': a cookie has to be attributed to a site, and neither was given.`); } } /** The shared 'name' check. A write tool with no name has nothing to write and * a delete tool with no name would match every cookie, so an empty one is * refused rather than treated as absent. */ function assertCookieName(name: string | undefined, toolName: string): asserts name is string { if (name === undefined || name === "") { throw new Error(`${toolName} requires a non-empty 'name'.`); } } /** * Write one cookie into the target page's cookie store. * * The response is deliberately tiny: `{set: true, target}`. It does NOT echo * the value back, because the value is frequently the credential and a caller * who just supplied it does not need it repeated into their transcript. The * `set: true` is earned rather than assumed: the CDP driver throws on Chrome's * `{success:false}` refusal and the BiDi driver throws when it cannot derive * the domain BiDi requires, so reaching this line means a backend confirmed * the write. */ export async function setCookie( driver: BrowserDriver, args: { target?: TargetSelector; name: string; value: string; url?: string; domain?: string; path?: string; expires?: number; httpOnly?: boolean; secure?: boolean; sameSite?: "strict" | "lax" | "none" | "default"; }, ): Promise { assertCookieName(args.name, "set_cookie"); if (typeof args.value !== "string") throw new Error("set_cookie requires a string 'value'."); assertCookieSite(args, "set_cookie"); return withPage(driver, args.target, async (page) => { await page.setCookie({ name: args.name, value: args.value, ...(args.url !== undefined ? { url: args.url } : {}), ...(args.domain !== undefined ? { domain: args.domain } : {}), ...(args.path !== undefined ? { path: args.path } : {}), ...(args.expires !== undefined ? { expires: args.expires } : {}), ...(args.httpOnly !== undefined ? { httpOnly: args.httpOnly } : {}), ...(args.secure !== undefined ? { secure: args.secure } : {}), ...(args.sameSite !== undefined ? { sameSite: args.sameSite } : {}), }); return { set: true as const, target: target3(page.info) }; }); } /** * Remove the named cookie from the target page's cookie store. * * `{deleted: true, target}` and NO count, on purpose. Neither protocol reports * how many cookies it removed, so any number here would be invented; a caller * who needs one reads list_cookies before and after. `deleted: true` means the * backend accepted and performed the deletion, not that a matching cookie * existed: deleting an absent cookie is a success on both backends. */ export async function deleteCookies( driver: BrowserDriver, args: { target?: TargetSelector; name: string; url?: string; domain?: string; path?: string }, ): Promise { assertCookieName(args.name, "delete_cookies"); assertCookieSite(args, "delete_cookies"); return withPage(driver, args.target, async (page) => { await page.deleteCookies({ name: args.name, ...(args.url !== undefined ? { url: args.url } : {}), ...(args.domain !== undefined ? { domain: args.domain } : {}), ...(args.path !== undefined ? { path: args.path } : {}), }); return { deleted: true as const, target: target3(page.info) }; }); } /* -------------------------------- snapshot (1) -------------------------------- */ /** * Legacy-faithful render, keyed by field name (see the file header's uid/extras note). The * "cdp" scheme strips its "cdp:" tag to reproduce the historical bare-backendDOMNodeId uid; * every other scheme keeps its tag (a tool must never guess at a foreign driver's uid grammar, * per driver.ts's THE UID CODEC block: this is a display choice made by the tool that already * knows its own driver's scheme, not a parse of a uid it didn't mint). */ const BARE_TOKEN_EXTRAS = new Set(["disabled", "focused"]); const UNQUOTED_EXTRAS = new Set(["checked", "expanded", "url"]); function renderSnapshotLine(n: SnapshotNode, scheme: string): string { const indent = " ".repeat(n.depth); const uidText = scheme === "cdp" && n.uid.startsWith("cdp:") ? n.uid.slice(4) : n.uid; const name = n.name !== undefined ? ` ${JSON.stringify(n.name)}` : ""; const extrasToks: string[] = []; if (n.extras) { for (const [k, v] of Object.entries(n.extras)) { if (BARE_TOKEN_EXTRAS.has(k)) extrasToks.push(k); else if (UNQUOTED_EXTRAS.has(k)) extrasToks.push(`${k}=${v}`); else extrasToks.push(`${k}=${JSON.stringify(v)}`); } } const extra = extrasToks.length ? ` [${extrasToks.join(" ")}]` : ""; return `${indent}[${uidText}] ${n.role}${name}${extra}`; } export async function takeSnapshot( driver: BrowserDriver, args: { target?: TargetSelector; interactiveOnly?: boolean } & ContextArgs = {}, ): Promise<{ snapshot: string; target: { id: string; url: string; title: string }; nodeCount: number; context?: { id: number; frameId?: string; frameUrl?: string } }> { if (args.context === "auto") throw new SharedToolError(`take_snapshot: ${CONTEXT_AUTO_NEEDS_SELECTOR}`); assertContextSupport(driver, "take_snapshot", wantsContext(args)); return withPage(driver, args.target, async (page) => { const ctx = await applyContext(page, "take_snapshot", args); const nodes = await page.snapshot({ interactiveOnly: args.interactiveOnly ?? false }); const scheme = page.browser.scheme; return { snapshot: nodes.map((n) => renderSnapshotLine(n, scheme)).join("\n"), target: target3(page.info), nodeCount: nodes.length, ...ctx }; }); } /* ------------------------------ interaction (8) ------------------------------ */ /** * In-page source that names the element `this` is, as a snapshot-style `role "name"` string * (`button "Save"`, `textbox "Email"`). It reuses the snapshot walker's role/accname heuristics; * an element with no role falls back to its tag, and one with no accessible name falls back to * its own text, so a click on a bare `
` still says what it hit. Exported for the tests. */ export function describeElementSource(): string { return `function() { var MAX_NAME_LENGTH = ${MAX_NAME_LENGTH}; ${ACCNAME_HELPERS_SOURCE} var el = this; if (!el || el.nodeType !== 1) return null; var role = implicitRole(el); var name = accessibleName(el, !!CONTENT_NAMED_ROLES[role]); if (!name) name = truncate(el.innerText || el.textContent || ""); return (role || el.tagName.toLowerCase()) + (name ? " " + JSON.stringify(name) : ""); }`; } /** How long describing may delay the action it precedes before it is given up on. */ const DESCRIBE_TIMEOUT_MS = 2_000; /** * Best-effort `role "name"` for the element an action is about to touch, read BEFORE the action * (a click can navigate or unmount its node; fill should report the label, not the new value). * Never throws and never blocks past DESCRIBE_TIMEOUT_MS: a stale or unresolvable locator is left * for the action itself to fail on with its usual error, and the result just omits `element`. */ export async function describeElement(page: PageDriver, loc: ElementLocator): Promise { let timer: ReturnType | undefined; try { const timeout = new Promise((r) => { timer = setTimeout(() => r(undefined), DESCRIBE_TIMEOUT_MS); }); const desc = await Promise.race([page.callOnElement(loc, describeElementSource()), timeout]); return typeof desc === "string" && desc.length > 0 ? desc : undefined; } catch { return undefined; } finally { clearTimeout(timer); } } /** A drag destination that names an element, as opposed to a viewport point or an offset. */ function isElementLocator(d: DragDestination): d is ElementLocator { return !("x" in d) && !("dx" in d); } /** `{ element }` when there is a description, `{}` otherwise, for spreading into a result. */ function elementField(element: string | undefined): { element?: string } { return element === undefined ? {} : { element }; } export async function click( driver: BrowserDriver, args: { target?: TargetSelector; uid?: DriverUid; selector?: string; button?: "left" | "right" | "middle"; clickCount?: number; modifiers?: string[] } & ContextArgs, ): Promise<{ clicked: true; element?: string; x: number; y: number; context?: { id: number; frameId?: string; frameUrl?: string } }> { const loc = locatorOf(args); assertContextSupport(driver, "click", wantsContext(args)); return withPage(driver, args.target, async (page) => { const ctx = await applyContext(page, "click", args, cssOf(loc)); const element = await describeElement(page, loc); const { x, y } = await page.click(loc, { button: args.button ?? "left", clickCount: args.clickCount ?? 1, modifiers: args.modifiers }); return { clicked: true, ...elementField(element), x, y, ...ctx }; }); } /** * scroll's anchor rule: exactly one of `{uid}`, `{selector}`, or `{x,y}` — or none of the three, * which means the viewport center. `x`/`y` must arrive together; one without the other is refused * rather than silently treated as "half an anchor". Exported for the unit tests, which pin the * rule without a browser. */ export function resolveScrollAnchor(args: { uid?: DriverUid; selector?: string; x?: number; y?: number }): ElementLocator | { x: number; y: number } | undefined { const hasUid = args.uid !== undefined && args.uid !== null && args.uid !== ("" as unknown); const hasSelector = typeof args.selector === "string" && args.selector.length > 0; const hasX = args.x !== undefined; const hasY = args.y !== undefined; if (hasX !== hasY) throw new SharedToolError("scroll: 'x' and 'y' must be provided together"); const hasXY = hasX && hasY; const anchorCount = [hasUid, hasSelector, hasXY].filter(Boolean).length; if (anchorCount > 1) throw new SharedToolError("scroll: provide at most one of { uid }, { selector }, or { x, y } (omit all three to scroll at the viewport center)"); if (hasUid || hasSelector) return locatorOf({ uid: args.uid, selector: args.selector }); if (hasXY) return { x: args.x as number, y: args.y as number }; return undefined; } /** scroll's delta rule: at least one of deltaX/deltaY is required (a no-op scroll is refused * rather than silently dispatched). Exported for the unit tests. */ export function resolveScrollDelta(args: { deltaX?: number; deltaY?: number }): { deltaX: number; deltaY: number } { const deltaX = args.deltaX ?? 0; const deltaY = args.deltaY ?? 0; if (deltaX === 0 && deltaY === 0) throw new SharedToolError("scroll requires at least one of { deltaX } or { deltaY }"); return { deltaX, deltaY }; } export async function scroll( driver: BrowserDriver, args: { target?: TargetSelector; uid?: DriverUid; selector?: string; x?: number; y?: number; deltaX?: number; deltaY?: number }, ): Promise<{ x: number; y: number; deltaX: number; deltaY: number; target: { id: string; url: string; title: string } }> { const anchor = resolveScrollAnchor(args); const { deltaX, deltaY } = resolveScrollDelta(args); return withPage(driver, args.target, async (page) => { const { x, y } = await page.scroll(anchor, { deltaX, deltaY }); return { x, y, deltaX, deltaY, target: target3(page.info) }; }); } export async function hover(driver: BrowserDriver, args: { target?: TargetSelector; uid?: DriverUid; selector?: string } & ContextArgs): Promise<{ hovered: true; element?: string; x: number; y: number; context?: { id: number; frameId?: string; frameUrl?: string } }> { const loc = locatorOf(args); assertContextSupport(driver, "hover", wantsContext(args)); return withPage(driver, args.target, async (page) => { const ctx = await applyContext(page, "hover", args, cssOf(loc)); const element = await describeElement(page, loc); const { x, y } = await page.hover(loc); return { hovered: true, ...elementField(element), x, y, ...ctx }; }); } /** drag's `to`: exactly one of { uid } | { selector } | { x, y }, x and y together. Exported for * the unit tests, which pin the rule without a browser. */ export function resolveDragTo(to: { uid?: DriverUid; selector?: string; x?: number; y?: number }): DragDestination { const hasUid = to.uid !== undefined && to.uid !== null && to.uid !== ("" as unknown); const hasSelector = typeof to.selector === "string" && to.selector.length > 0; const hasX = to.x !== undefined; const hasY = to.y !== undefined; if (hasX !== hasY) throw new SharedToolError("drag: 'to.x' and 'to.y' must be provided together"); const hasXY = hasX && hasY; const count = [hasUid, hasSelector, hasXY].filter(Boolean).length; if (count !== 1) throw new SharedToolError("drag: 'to' takes exactly one of { uid }, { selector }, or { x, y }"); if (hasXY) { if (!Number.isFinite(to.x) || !Number.isFinite(to.y)) throw new SharedToolError("drag: 'to.x' and 'to.y' must be finite numbers"); return { x: to.x as number, y: to.y as number }; } return locatorOf({ uid: to.uid, selector: to.selector }); } /** * drag's destination rule: EXACTLY one of `to` (where the drag ends) or `by` (how far it moves * from the source point). Both is a contradiction and neither leaves nowhere to drag to, so both * are refused rather than resolved by precedence — a caller who passed both meant one of them and * silently picking is how the wrong widget gets dragged. `by` needs at least one of dx/dy; the * other defaults to 0, so `by:{dx:40}` is a pure horizontal slider nudge. Exported for the tests. */ export function resolveDragDestination(args: { to?: { uid?: DriverUid; selector?: string; x?: number; y?: number }; by?: { dx?: number; dy?: number }; }): DragDestination { const hasTo = args.to !== undefined && args.to !== null; const hasBy = args.by !== undefined && args.by !== null; if (hasTo === hasBy) throw new SharedToolError("drag requires exactly one of { to } or { by }"); if (hasBy) { const by = args.by as { dx?: number; dy?: number }; const hasDx = by.dx !== undefined; const hasDy = by.dy !== undefined; if (!hasDx && !hasDy) throw new SharedToolError("drag: 'by' requires at least one of { dx } or { dy }"); const dx = by.dx ?? 0; const dy = by.dy ?? 0; if (!Number.isFinite(dx) || !Number.isFinite(dy)) throw new SharedToolError("drag: 'by.dx' and 'by.dy' must be finite numbers"); return { dx, dy }; } return resolveDragTo(args.to as { uid?: DriverUid; selector?: string; x?: number; y?: number }); } /** Upper bound on drag's interpolated moves. 500 already exceeds what any per-frame-sampling DnD * library needs (a 60fps drag lasting 8s), and each step is a round-tripped CDP command, so an * accidental `steps: 100000` would otherwise wedge the call for minutes. Refused, not clamped. */ const MAX_DRAG_STEPS = 500; /** drag's `steps`: an integer in [1, MAX_DRAG_STEPS], default 2 (the pre-1.8.0 midpoint + * destination sequence). Exported for the unit tests. */ export function resolveDragSteps(steps?: number): number { if (steps === undefined) return 2; if (typeof steps !== "number" || !Number.isInteger(steps) || steps < 1 || steps > MAX_DRAG_STEPS) { throw new SharedToolError(`drag: 'steps' must be an integer between 1 and ${MAX_DRAG_STEPS} (default 2)`); } return steps; } /** * drag's `mode`, plus the ONE backend gate in this file. mode:"html5" needs Capability * "input.html5Drag", which only the Chrome driver declares (Chrome's Input.setInterceptDrags / * dragIntercepted / dispatchDragEvent have no WebDriver BiDi equivalent). Per ADR-001 this is a * PARAM-level gap, not a whole-tool one: `drag` stays in tools/list on Firefox because mouse mode * works there, and asking for html5 on Firefox is a clear validation error — never a silent * downgrade to mouse mode, which would report success for a drop that never happened. * Exported for the unit tests. */ export function resolveDragMode(mode: string | undefined, capabilities: ReadonlySet): "mouse" | "html5" { if (mode === undefined || mode === "mouse") return "mouse"; if (mode !== "html5") throw new SharedToolError(`drag: unknown mode '${mode}' (use 'mouse' or 'html5')`); if (!capabilities.has("input.html5Drag")) { throw new SharedToolError( "drag: mode:'html5' is not supported by this backend (WebDriver BiDi has no drag-interception primitive). " + "Omit 'mode' for the synthetic-mouse drag, or use --browser chrome for real HTML5 drag events.", ); } return "html5"; } export async function drag( driver: BrowserDriver, args: { target?: TargetSelector; from: { uid?: DriverUid; selector?: string }; to?: { uid?: DriverUid; selector?: string; x?: number; y?: number }; by?: { dx?: number; dy?: number }; mode?: "mouse" | "html5"; steps?: number; }, ): Promise<{ dragged: true; element?: string; target_element?: string; mode: "mouse" | "html5"; steps: number; from: { x: number; y: number }; to: { x: number; y: number } }> { if (!args.from) throw new SharedToolError("drag requires { from }"); const destination = resolveDragDestination(args); const steps = resolveDragSteps(args.steps); // Capability check BEFORE withPage: an unsupported mode must not claim a lease or open a socket. const mode = resolveDragMode(args.mode, driver.capabilities); return withPage(driver, args.target, async (page) => { const fromLoc = locatorOf(args.from); const element = await describeElement(page, fromLoc); const targetElement = isElementLocator(destination) ? await describeElement(page, destination) : undefined; const { from, to } = await page.drag(fromLoc, destination, { mode, steps }); return { dragged: true, ...elementField(element), ...(targetElement === undefined ? {} : { target_element: targetElement }), mode, steps, from, to, }; }); } /** `inputPath` rides a result only when the commit did NOT go the trusted way (a background tab's * in-page fallback, or a skipped non-text element), so the common foreground shape is unchanged. */ function inputPathField(path: void | TextInputPath): { inputPath?: TextInputPath } { return path && path !== "trusted" ? { inputPath: path } : {}; } export async function fill(driver: BrowserDriver, args: { target?: TargetSelector; uid?: DriverUid; selector?: string; value: string } & ContextArgs): Promise<{ filled: true; element?: string; value: string; inputPath?: TextInputPath; context?: { id: number; frameId?: string; frameUrl?: string } }> { if (typeof args.value !== "string") throw new SharedToolError("fill requires a string { value }"); const loc = locatorOf(args); assertContextSupport(driver, "fill", wantsContext(args)); return withPage(driver, args.target, async (page) => { const ctx = await applyContext(page, "fill", args, cssOf(loc)); const element = await describeElement(page, loc); const path = await page.setValue(loc, args.value); return { filled: true, ...elementField(element), value: args.value, ...inputPathField(path), ...ctx }; }); } export async function fillForm( driver: BrowserDriver, args: { target?: TargetSelector; fields: Array<{ uid?: DriverUid; selector?: string; value: string }> } & ContextArgs, ): Promise<{ filled: number; fields: number; elements: Array; inputPaths?: TextInputPath[]; context?: { id: number; frameId?: string; frameUrl?: string } }> { if (!Array.isArray(args.fields) || args.fields.length === 0) throw new SharedToolError("fill_form requires a non-empty { fields } array"); assertContextSupport(driver, "fill_form", wantsContext(args)); return withPage(driver, args.target, async (page) => { // One context for the whole form ('auto' matches on the first field's selector). const first = args.fields[0]!; const ctx = await applyContext(page, "fill_form", args, typeof first.selector === "string" && first.selector ? first.selector : undefined); let filled = 0; const elements: Array = []; const paths: TextInputPath[] = []; for (const f of args.fields) { if (typeof f.value !== "string") throw new SharedToolError("each fill_form field requires a string value"); const loc = locatorOf(f); elements.push((await describeElement(page, loc)) ?? null); paths.push((await page.setValue(loc, f.value)) || "trusted"); filled++; } // Per field, in order, and only when some field went a non-trusted way. return { filled, fields: args.fields.length, elements, ...(paths.some((p) => p !== "trusted") ? { inputPaths: paths } : {}), ...ctx }; }); } export async function typeText(driver: BrowserDriver, args: { target?: TargetSelector; uid?: DriverUid; selector?: string; text: string } & ContextArgs): Promise<{ typed: true; element?: string; text: string; inputPath?: TextInputPath; context?: { id: number; frameId?: string; frameUrl?: string } }> { if (typeof args.text !== "string") throw new SharedToolError("type_text requires a string { text }"); const loc = locatorOf(args); assertContextSupport(driver, "type_text", wantsContext(args)); return withPage(driver, args.target, async (page) => { const ctx = await applyContext(page, "type_text", args, cssOf(loc)); const element = await describeElement(page, loc); const path = await page.typeText(loc, args.text); return { typed: true, ...elementField(element), text: args.text, ...inputPathField(path), ...ctx }; }); } export async function pressKey(driver: BrowserDriver, args: { target?: TargetSelector; key: string; modifiers?: string[] }): Promise<{ pressed: string; modifiers: string[]; delivered?: false; note?: string }> { if (typeof args.key !== "string" || !args.key.length) throw new SharedToolError("press_key requires a non-empty { key }"); const modifiers = args.modifiers ?? []; return withPage(driver, args.target, async (page) => { const res = await page.pressKey({ key: args.key, modifiers }); // Only a definite miss is reported; delivered/unknown keeps the old shape. if (res && res.delivered === false) { return { pressed: args.key, modifiers, delivered: false, note: "the page saw no keydown: a background tab gets no trusted keyboard input. A click on the tab's page (click tool) usually gives it focus so keys land; or open the tab with new_page focus:true (which raises the browser over the user's work; refused under CDP_DENY_FOCUS). A key handled inside a cross-origin iframe also reads as not delivered.", }; } return { pressed: args.key, modifiers }; }); } export async function uploadFile(driver: BrowserDriver, args: { target?: TargetSelector; uid?: DriverUid; selector?: string; files: string | string[] }): Promise<{ uploaded: string[]; element?: string }> { const files = Array.isArray(args.files) ? args.files : [args.files]; if (!files.length || files.some((f) => typeof f !== "string" || !f.length)) { throw new SharedToolError("upload_file requires { files } as a non-empty path or array of paths"); } return withPage(driver, args.target, async (page) => { const loc = locatorOf(args); const element = await describeElement(page, loc); await page.setFiles(loc, files); return { uploaded: files, ...elementField(element) }; }); } /* -------------------------- screenshot + emulation (3) -------------------------- */ function stamp(): string { return new Date(Date.now()).toISOString().replace(/[:.]/g, "-"); } /** Upper bound on take_screenshot's `scale`. 8 already gives ~11k px off a 1390 px viewport on a * ratio-2 display, past which the driver's own 16384 px encode guard is the binding limit anyway; * the point of a ceiling here is that a fat-fingered `scale: 800` is refused instantly instead of * wedging a real browser command for minutes. Refused, not clamped, like MAX_DRAG_STEPS. */ const MAX_SCREENSHOT_SCALE = 8; /** * take_screenshot's `scale`, plus the second backend gate in this file (resolveDragMode is the * first, and this follows its shape exactly). scale needs Capability "screenshot.scale", which * Chrome declares (Page.captureScreenshot takes a per-call clip.scale) and Firefox >= 160 declares * too (a one-capture devicePixelRatio override; captureScreenshot itself has no scale parameter, and * an older Firefox's driver refuses with "unsupported" from requireFirefox). Per ADR-001 * this is a PARAM-level gap, not a whole-tool one — take_screenshot stays in tools/list on Firefox * because every other argument works there, and asking for a scale on Firefox is a clear * validation error, never a silent 1x capture that would return an image the caller never asked * for and could not tell apart from the one they wanted. Exported for the unit tests. */ export function resolveScreenshotScale(scale: number | undefined, capabilities: ReadonlySet): number { if (scale === undefined) return 1; if (typeof scale !== "number" || !Number.isFinite(scale) || scale <= 0 || scale > MAX_SCREENSHOT_SCALE) { throw new SharedToolError(`take_screenshot: 'scale' must be a finite number greater than 0 and at most ${MAX_SCREENSHOT_SCALE} (default 1)`); } if (scale !== 1 && !capabilities.has("screenshot.scale")) { throw new SharedToolError( "take_screenshot: 'scale' is not supported by this backend (no per-capture scale primitive). " + `Call emulate with deviceScaleFactor:${scale} first and capture at scale 1, or use --browser chrome for a per-capture scale.`, ); } return scale; } /** Upper bound on a render-size side, in CSS px. Deliberately Chrome's own 16384 px per-side encode * ceiling: a viewport wider than the widest image the browser can encode cannot produce a * full-width capture of itself anyway, so anything past it is a typo rather than an intent. The * binding limit in practice is lower and is enforced where it can actually be computed — the * driver's assertClipEncodable, on the post-override numbers, since a 8192 css-px render is already * 16384 device px on a ratio-2 display. Refused, not clamped, like MAX_DRAG_STEPS. */ const MAX_RENDER_SIZE_PX = 16384; /** * take_screenshot's `renderWidth`/`renderHeight`, and the third backend gate in this file * (resolveDragMode is the first, resolveScreenshotScale the second, and this follows their shape). * * REQUIRED TOGETHER, mirroring the "device metrics require both width and height" rule emulate() * has always had: a viewport is two numbers, and honouring one while inventing the other would * render at a size the caller never named and never sees in the result. * * Unlike `scale` this is NOT a Chrome-only capability — both drivers ride their own viewport * emulation for it — so on today's backends the capability arm never fires. It is written anyway * because ADR-001 says availability is declared, not assumed: a future backend that cannot emulate * a viewport must refuse out loud here rather than silently capture at the tab's real size, which * would return a picture indistinguishable from the one the caller asked for. Exported for the tests. */ export function resolveRenderSize( renderWidth: number | undefined, renderHeight: number | undefined, capabilities: ReadonlySet, ): { width: number; height: number } | undefined { if (renderWidth === undefined && renderHeight === undefined) return undefined; if (renderWidth === undefined || renderHeight === undefined) { throw new SharedToolError( "take_screenshot: 'renderWidth' and 'renderHeight' are required together (a viewport is two numbers; " + `got ${renderWidth === undefined ? "only renderHeight" : "only renderWidth"})`, ); } for (const [name, value] of [["renderWidth", renderWidth], ["renderHeight", renderHeight]] as const) { if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > MAX_RENDER_SIZE_PX) { throw new SharedToolError(`take_screenshot: '${name}' must be an integer between 1 and ${MAX_RENDER_SIZE_PX} css px (got ${JSON.stringify(value)})`); } } if (!capabilities.has("screenshot.renderSize")) { throw new SharedToolError( "take_screenshot: 'renderWidth'/'renderHeight' are not supported by this backend (it cannot emulate a viewport for a capture). " + `Call emulate with width:${renderWidth}, height:${renderHeight} first, capture, then restore the viewport yourself.`, ); } return { width: renderWidth, height: renderHeight }; } /** * take_screenshot's `tile`, and the fourth backend gate in this file (resolveDragMode, * resolveScreenshotScale and resolveRenderSize are the first three, and this follows their shape). * * THREE-VALUED, AND THE DEFAULT IS AUTO — the one decision in this feature that is not a preference. * A capture past the backend's per-image encode limit does not fail politely: measured on * Chrome/151.0.7922.76, Page.captureScreenshot never answers and the tab is left resized to the * clip with every later screenshot timing out. Whole-page capture is what take_screenshot is for, so * the default has to be the one that returns the whole page: one shot when it fits, bands when it * does not. `false` is the escape hatch back to the exact pre-tiling behaviour (refuse rather than * band), `true` forces the banded path so it is directly testable. * * ONLY `true` COSTS A CAPABILITY. Auto asks a backend for nothing it cannot do — a driver without * "screenshot.tile" simply never bands, exactly as it behaved before this feature — so gating auto * would delete the default behaviour on Firefox for no gain. Exported for the unit tests. */ export function resolveTileMode( tile: boolean | undefined, capabilities: ReadonlySet, format: "png" | "jpeg", returnBase64: boolean | undefined, ): boolean | undefined { if (tile === undefined) return undefined; if (typeof tile !== "boolean") throw new SharedToolError(`take_screenshot: 'tile' must be true, false, or omitted for automatic (got ${JSON.stringify(tile)})`); if (!tile) return false; if (!capabilities.has("screenshot.tile")) { throw new SharedToolError( "take_screenshot: 'tile' is not supported by this backend (band tiling is declared only where the band arithmetic was measured against a real browser; " + "Firefox was not driven for it). Capture a smaller region or a single element, or use --browser chrome for a tiled capture.", ); } // Asked for explicitly, so refuse explicitly and BEFORE a socket is opened. The same two // combinations reached by AUTO are refused with the same words, one layer later — see // tiledCaptureRefusal's call site inside takeScreenshot. if (format !== "png") throw tiledCaptureRefusal("format"); if (returnBase64) throw tiledCaptureRefusal("base64"); return true; } /** * The two things a tiled capture cannot also be, in one place so the explicit (`tile:true`, refused * before a socket is opened) and the automatic (refused the instant the driver offers bands, before * the first one is captured) paths cannot drift into two different explanations of the same wall. * * `banded` is present only on the automatic path, where the driver has already measured what it * would take: naming the band count and the region turns "you cannot have this" into "you cannot * have this because your page is this big". */ function tiledCaptureRefusal(reason: "format" | "base64", banded?: BandedCapture): SharedToolError { const because = banded ? ` This capture needs ${banded.bandCount} bands (${banded.clip.width}x${banded.clip.height} css px is past what one image can encode).` : ""; if (reason === "format") { return new SharedToolError( "take_screenshot: a tiled capture is PNG-only — bands are stitched by concatenating PNG scanlines, and there is no lossless " + `JPEG equivalent to concatenate.${because} Pass format:"png", or lower scale / narrow the region until one JPEG fits.`, ); } return new SharedToolError( "take_screenshot: 'returnBase64' cannot be combined with a tiled capture — a tiled image runs to hundreds of megabytes and base64 " + `inflates it by a third, into the caller's response.${because} Read the file at the returned path instead, or capture a region small enough for one shot.`, ); } /** PNG: an 8-byte signature, then an IHDR chunk whose payload opens with two big-endian uint32s. */ function pngPixelSize(b: Uint8Array, view: DataView): { width: number; height: number } | undefined { if (b.length < 24) return undefined; if (view.getUint32(0) !== 0x89504e47 || view.getUint32(4) !== 0x0d0a1a0a) return undefined; if (String.fromCharCode(b[12]!, b[13]!, b[14]!, b[15]!) !== "IHDR") return undefined; return { width: view.getUint32(16), height: view.getUint32(20) }; } /** SOF markers carrying frame dimensions. SOF4 (0xc4 DHT), SOF8 (0xc8), SOF12 (0xcc DAC) are NOT frame headers. */ const JPEG_SOF = new Set([0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf]); /** JPEG: walk the marker segments to the first start-of-frame, which carries height then width. */ function jpegPixelSize(b: Uint8Array, view: DataView): { width: number; height: number } | undefined { if (b.length < 4 || b[0] !== 0xff || b[1] !== 0xd8) return undefined; let i = 2; while (i + 3 < b.length) { if (b[i] !== 0xff) { i += 1; // resync past fill bytes / padding continue; } const marker = b[i + 1]!; if (marker === 0xff) { i += 1; continue; } // Standalone markers: no length field follows. if (marker === 0xd8 || marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) { i += 2; continue; } const segLen = view.getUint16(i + 2); if (JPEG_SOF.has(marker)) { if (i + 9 > b.length) return undefined; return { width: view.getUint16(i + 7), height: view.getUint16(i + 5) }; } if (segLen < 2) return undefined; i += 2 + segLen; } return undefined; } /** * Output dimensions read from the ENCODED BYTES, never computed from the clip and the scale the * caller asked for: those two disagree the moment the device pixel ratio multiplies in (a scale-1 * capture of a 1390 px viewport is a 2780 px PNG on a ratio-2 display), and a computed number that * quietly disagrees with the file on disk is worse than no number. `undefined` when the bytes are * neither PNG nor JPEG, so take_screenshot can OMIT width/height rather than report a guess. * * A deliberate second implementation of tools/screencast.ts's imageSize, not a shared one: this * file is the browser-NEUTRAL tool layer and imports nothing from src/tools/ (that Chrome-only * layer is what it replaced), and screencast.ts's copy takes a node Buffer while a driver hands * this one a Uint8Array. The two are pinned by their own tests and must stay in agreement. * Exported for the unit tests. */ export function imagePixelSize(bytes: Uint8Array): { width: number; height: number } | undefined { if (bytes.byteLength < 4) return undefined; const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); return pngPixelSize(bytes, view) ?? jpegPixelSize(bytes, view); } /** * take_screenshot's result. Named rather than inlined now that it carries the render-size outcome: * the shape appears three times in this function (signature, literal, and the widening the optional * fields need) and a fourth divergent copy is how a field goes missing. * * `scale` is ALWAYS present; `width`/`height` only when the bytes decoded; the three render-size * fields only when a render size was applied. Absent beats invented, everywhere here. */ export interface ScreenshotToolResult { path: string; bytes: number; format: "png" | "jpeg"; target: { id: string; url: string; title: string }; scale: number; width?: number; height?: number; /** * Present, and true, ONLY when this capture was taken as bands and stitched. Auto-tiling is * silent about nothing: a caller who never asked for tiling still learns their image came from * `bands` separate captures, which is what makes the lazy-content caveat theirs to reason about * (a page that only loads content on real scroll renders blank in bands past the first viewport — * a property of the page, not of the stitch, but invisible unless the tiling is reported). */ tiled?: true; /** How many captures the image was assembled from. Present only alongside `tiled`. */ bands?: number; /** The emulated viewport the capture ran at. */ renderSize?: { width: number; height: number }; /** False means the page is STILL emulated at renderSize: the caller has to put it back. */ renderRestored?: boolean; renderRestoreError?: string; base64?: string; } export async function takeScreenshot( driver: BrowserDriver, args: { target?: TargetSelector; format?: "png" | "jpeg"; quality?: number; fullPage?: boolean; uid?: DriverUid; selector?: string; savePath?: string; returnBase64?: boolean; scale?: number; renderWidth?: number; renderHeight?: number; tile?: boolean; } = {}, ): Promise { if ((args.uid !== undefined && args.uid !== "") && args.selector) throw new SharedToolError("provide exactly one of uid or selector, not both"); const format = args.format ?? "png"; // Range + capability checks BEFORE withPage: an argument this backend cannot honour must not claim // a lease or open a socket (same reasoning as drag's resolveDragMode call site). For the render // size that is stronger than tidiness — the refusal happens before any viewport is emulated, so a // rejected call cannot be the one that leaves a page mutated. const scale = resolveScreenshotScale(args.scale, driver.capabilities); const renderSize = resolveRenderSize(args.renderWidth, args.renderHeight, driver.capabilities); const tile = resolveTileMode(args.tile, driver.capabilities, format, args.returnBase64); return withPage(driver, args.target, async (page) => { const clip = args.uid !== undefined || args.selector ? locatorOf(args) : undefined; const ext = format === "jpeg" ? "jpg" : "png"; // Named BEFORE the capture, because a banded capture writes straight to its destination as the // bands arrive — there is never a complete image in memory to name a file after. The one-shot // path names it at the same moment for the same reason a single path is easier to trust than // two; the only visible effect is that the default filename's stamp is the capture's start. const path = args.savePath ?? join(ARTIFACT_DIR, `screenshot-${page.info.id.slice(0, 8)}-${stamp()}.${ext}`); // The tool layer owns files, the driver owns the protocol: the driver decides that this capture // has to be banded and produces the bands, and this callback is the only thing that knows where // they go. It runs BEFORE the first band is captured, which is what lets the two combinations a // stitched capture cannot serve refuse without a single wasted Page.captureScreenshot. const stitch = async (banded: BandedCapture) => { if (format !== "png") throw tiledCaptureRefusal("format", banded); if (args.returnBase64) throw tiledCaptureRefusal("base64", banded); return stitchPngBandsToFile(banded.bands, path); }; const shot = await page.screenshot({ format, quality: args.quality, fullPage: args.fullPage, scale, ...(clip ? { clip } : {}), ...(renderSize ? { renderWidth: renderSize.width, renderHeight: renderSize.height } : {}), ...(tile !== undefined ? { tile } : {}), }, stitch); const result: ScreenshotToolResult = isTiledCapture(shot) ? { // width/height/bytes come from the STITCHER, which is the only thing that ever saw the // whole image: re-reading a several-hundred-MB PNG off disk to decode an IHDR this call // already computed would be slower and no more true. Still measured, never projected — // the stitcher patches the IHDR with the rows it actually wrote. path, bytes: shot.consumed.bytes, format: "png", target: target3(page.info), scale, width: shot.consumed.width, height: shot.consumed.height, tiled: true, bands: shot.consumed.bands, } : await writeOneShot(shot.data, shot.format, path, target3(page.info), scale, args.returnBase64); // What actually happened to the page, reported from the DRIVER's answer rather than from what // was asked for. renderRestored:false means the caller's tab is still emulated at renderSize // and they have to fix it — the one outcome that must never be swallowed, so it rides back on // the success result the same way a decoded width does. if (renderSize && shot.renderSize) { result.renderSize = shot.renderSize; result.renderRestored = shot.renderRestored ?? false; if (shot.renderRestoreError !== undefined) result.renderRestoreError = shot.renderRestoreError; } return result; }); } /** The one-shot half of takeScreenshot: bytes in hand, so the file is written here and the size is * DECODED from those bytes. Unchanged from before tiling existed, split out only so the tiled arm * above reads as the one difference it is. */ async function writeOneShot( data: Uint8Array, outFormat: "png" | "jpeg", path: string, target: { id: string; url: string; title: string }, scale: number, returnBase64: boolean | undefined, ): Promise { if (data.byteLength === 0) throw new SharedToolError("captureScreenshot returned empty data"); await mkdir(dirname(path), { recursive: true }); await writeFile(path, Buffer.from(data)); const size = imagePixelSize(data); const result: ScreenshotToolResult = { path, bytes: data.byteLength, format: outFormat, target, scale }; // Absent beats invented: undecodable bytes leave width/height off the result entirely. if (size) { result.width = size.width; result.height = size.height; } if (returnBase64) result.base64 = Buffer.from(data).toString("base64"); return result; } export async function emulate( driver: BrowserDriver, args: { target?: TargetSelector; width?: number; height?: number; deviceScaleFactor?: number; mobile?: boolean; userAgent?: string; cpuThrottlingRate?: number; media?: string; mediaFeatures?: Array<{ name: string; value: string }>; networkConditions?: { offline?: boolean; latency?: number; downloadThroughput?: number; uploadThroughput?: number; connectionType?: string }; clearOverrides?: boolean; } = {}, ): Promise<{ target: { id: string; url: string; title: string }; applied: string[]; cleared?: boolean }> { return withPage(driver, args.target, async (page) => { if (args.clearOverrides) { await page.emulate({ clearOverrides: true }); return { target: target3(page.info), applied: [], cleared: true }; } const { applied } = await page.emulate(args); if (applied.length === 0) throw new SharedToolError("emulate: no overrides specified (pass clearOverrides:true to reset)"); return { target: target3(page.info), applied }; }); } export async function resizePage( driver: BrowserDriver, args: { target?: TargetSelector; width: number; height: number; deviceScaleFactor?: number; mobile?: boolean }, ): Promise<{ target: { id: string; url: string; title: string }; width: number; height: number; innerWidth: number; innerHeight: number }> { if (!Number.isFinite(args.width) || !Number.isFinite(args.height) || args.width <= 0 || args.height <= 0) { throw new SharedToolError("resize_page requires positive numeric width and height"); } return withPage(driver, args.target, async (page) => { await page.emulate({ width: args.width, height: args.height, deviceScaleFactor: args.deviceScaleFactor, mobile: args.mobile }); const v = (await page.evaluate("({ w: window.innerWidth, h: window.innerHeight })")) as { w?: number; h?: number } | undefined; return { target: target3(page.info), width: args.width, height: args.height, innerWidth: v?.w ?? args.width, innerHeight: v?.h ?? args.height }; }); } /* ---------------------------------- dialogs (1) ---------------------------------- */ export async function handleDialog( driver: BrowserDriver, args: { target?: TargetSelector; accept: boolean; promptText?: string; timeoutMs?: number; autoMs?: number }, ): Promise { if (args.accept === undefined) throw new SharedToolError("handle_dialog requires { accept }"); return withPage(driver, args.target, (page) => page.handleDialog(args.accept, args.promptText, { timeoutMs: args.timeoutMs, autoMs: args.autoMs })); } /* ------------------------------------- registry ------------------------------------- */ /** The 24 tools this file unifies (23 pre-1.8.0, plus `scroll`, Track P1), importable by both * src/index.ts (Chrome) and src/firefox-tools.ts (Firefox). Each function is * (driver, args) => Promise. */ export const SHARED_TOOLS = { list_pages: listPages, new_page: newPage, close_page: closePage, select_page: selectPage, navigate_page: navigatePage, wait_for: waitForText, evaluate_script: evaluateScript, list_cookies: listCookies, set_cookie: setCookie, delete_cookies: deleteCookies, take_snapshot: takeSnapshot, list_contexts: listContexts, click, hover, drag, scroll, fill, fill_form: fillForm, type_text: typeText, press_key: pressKey, upload_file: uploadFile, take_screenshot: takeScreenshot, emulate, resize_page: resizePage, handle_dialog: handleDialog, } satisfies Record Promise>;