From 982d17cdb8ad7b7402fe3bd5d72fd4e0efc9ae2a Mon Sep 17 00:00:00 2001 From: Ryan Vogel <89211796+R44VC0RP@users.noreply.github.com> Date: Sun, 18 Oct 2026 14:10:01 -0400 Subject: [PATCH] feat(browser-extension): add opencode-browser-cli with the relay and browse MCP server packages/browser-extension/cli is the npm package `opencode-browser-cli`, with its own package.json and lockfile so its dependencies stay out of the monorepo's. It is Browser Control (anomalyco/browser-control 8c80ac2, MIT) ported into OpenCode Browser: renamed, on its own port (19988), accepting only OpenCode Browser's extension IDs, with files under ~/.local/share/opencode-browser. - The relay: a local CDP endpoint backed by the extension's chrome.debugger, shared by several clients, with named sessions that survive relay restarts and extension reloads, handoffs, recordings (CDP and tab capture), a flight recorder, network capture with a redacted HAR, secrets, and a journal. relay.log records lifecycle, connects (with the extension's build and origin), every HTTP request with its duration, and faults. - The `browse` MCP server (stdio) and the `opencode-browser` CLI: execute (Playwright API through patchright-core, which never enables CDP's Runtime domain, so pages can't detect the debugger that way; pageConsole.start() opts one page into console capture), session_* (session_adopt also takes a Chrome tab id), network_*, recording_*, flight_recorder_*, secrets_*, tabs_cleanup, status, skill. The agent guide is skills/browse/SKILL.md. - Human-like input (human-input.ts): curved, eased mouse paths, off-center clicks with a settle and hold, paced keys, gliding wheel scrolls. OPENCODE_BROWSER_HUMAN_INPUT=0 turns it off. - Setup (setup.ts): `install` installs a pinned runtime, adds the `browse` MCP server to opencode's global config (with a fingerprint so opencode restarts it on updates), restarts an outdated relay, copies the unpacked extension and reloads a connected unpacked build only when it is older (checking the reload took effect), then reports which browsers and profiles have the extension and opens its Web Store listing when none does (unless headless, --no-open, or a browser couldn't be read). It removes leftovers of earlier versions (native messaging host, opencode plugin, `opencode-browser` MCP entry). `extension` and `uninstall` round it out. Verified: cli typecheck and build; install on the user's machine (detected Helium/Ryan as default with the unpacked build, Chrome unreadable under macOS privacy protection, Arc without it; a second install neither restarts the relay nor reloads the extension); through the browse MCP tools in Helium: session_new, execute (goto, title, locators), screenshot, session_list, a CDP recording, session_delete. --- packages/browser-extension/cli/.gitignore | 2 + packages/browser-extension/cli/build.ts | 57 + packages/browser-extension/cli/bun.lock | 92 + packages/browser-extension/cli/package.json | 47 + .../cli/skills/browse/SKILL.md | 686 ++++++ .../cli/src/aria-snapshot.ts | 224 ++ .../browser-extension/cli/src/auth-profile.ts | 373 +++ .../cli/src/authenticated-origin.ts | 254 ++ .../cli/src/cdp-client-pool.ts | 212 ++ .../cli/src/cdp-guardrails.ts | 44 + .../browser-extension/cli/src/cdp-router.ts | 166 ++ .../browser-extension/cli/src/cdp-runtime.ts | 299 +++ .../browser-extension/cli/src/cdp-shims.ts | 133 + .../cli/src/cdp-visibility.ts | 36 + .../cli/src/child-process.ts | 35 + packages/browser-extension/cli/src/cli.ts | 1094 +++++++++ .../cli/src/demonstration.ts | 246 ++ packages/browser-extension/cli/src/doctor.ts | 615 +++++ packages/browser-extension/cli/src/execute.ts | 2176 +++++++++++++++++ .../cli/src/extension-rpc.ts | 218 ++ .../cli/src/flight-recorder.ts | 293 +++ .../cli/src/fs-durability.ts | 41 + .../browser-extension/cli/src/ghost-cursor.ts | 1309 ++++++++++ packages/browser-extension/cli/src/handoff.ts | 278 +++ .../browser-extension/cli/src/http-api.ts | 669 +++++ .../browser-extension/cli/src/human-input.ts | 251 ++ packages/browser-extension/cli/src/index.ts | 3 + packages/browser-extension/cli/src/main.ts | 37 + .../browser-extension/cli/src/mcp-main.ts | 5 + packages/browser-extension/cli/src/mcp.ts | 727 ++++++ .../cli/src/mjpeg-matroska.ts | 118 + .../cli/src/network-capture.ts | 864 +++++++ .../cli/src/network-redaction.ts | 378 +++ .../cli/src/opencode-browser-client.ts | 442 ++++ .../browser-extension/cli/src/page-console.ts | 72 + .../cli/src/page-read-timeout.ts | 43 + .../cli/src/patchright-tuning.ts | 59 + packages/browser-extension/cli/src/paths.ts | 16 + .../cli/src/protected-frames.ts | 109 + .../browser-extension/cli/src/protocol.ts | 193 ++ .../cli/src/recording-protocol.ts | 62 + .../cli/src/recording-relay.ts | 1199 +++++++++ .../browser-extension/cli/src/relay-client.ts | 312 +++ .../cli/src/relay-helpers.ts | 483 ++++ .../cli/src/relay-lifecycle-log.ts | 52 + .../cli/src/relay-lifecycle.ts | 337 +++ .../browser-extension/cli/src/relay-log.ts | 41 + .../browser-extension/cli/src/relay-schema.ts | 569 +++++ .../cli/src/relay-shutdown.ts | 152 ++ .../browser-extension/cli/src/relay-types.ts | 94 + packages/browser-extension/cli/src/relay.ts | 1627 ++++++++++++ .../cli/src/root-target-lifecycle.ts | 341 +++ .../cli/src/runtime-diagnostics.ts | 112 + .../cli/src/screenshot-diff.ts | 104 + .../cli/src/secret-profile.ts | 17 + .../cli/src/session-catalog.ts | 88 + .../cli/src/session-journal.ts | 149 ++ .../cli/src/session-manager.ts | 990 ++++++++ .../cli/src/session-store.ts | 129 + packages/browser-extension/cli/src/setup.ts | 575 +++++ .../browser-extension/cli/src/snapshot.ts | 1717 +++++++++++++ .../cli/src/target-registry.ts | 489 ++++ packages/browser-extension/cli/src/version.ts | 37 + packages/browser-extension/cli/src/webmcp.ts | 210 ++ packages/browser-extension/cli/tsconfig.json | 22 + 65 files changed, 22824 insertions(+) create mode 100644 packages/browser-extension/cli/.gitignore create mode 100644 packages/browser-extension/cli/build.ts create mode 100644 packages/browser-extension/cli/bun.lock create mode 100644 packages/browser-extension/cli/package.json create mode 100644 packages/browser-extension/cli/skills/browse/SKILL.md create mode 100644 packages/browser-extension/cli/src/aria-snapshot.ts create mode 100644 packages/browser-extension/cli/src/auth-profile.ts create mode 100644 packages/browser-extension/cli/src/authenticated-origin.ts create mode 100644 packages/browser-extension/cli/src/cdp-client-pool.ts create mode 100644 packages/browser-extension/cli/src/cdp-guardrails.ts create mode 100644 packages/browser-extension/cli/src/cdp-router.ts create mode 100644 packages/browser-extension/cli/src/cdp-runtime.ts create mode 100644 packages/browser-extension/cli/src/cdp-shims.ts create mode 100644 packages/browser-extension/cli/src/cdp-visibility.ts create mode 100644 packages/browser-extension/cli/src/child-process.ts create mode 100644 packages/browser-extension/cli/src/cli.ts create mode 100644 packages/browser-extension/cli/src/demonstration.ts create mode 100644 packages/browser-extension/cli/src/doctor.ts create mode 100644 packages/browser-extension/cli/src/execute.ts create mode 100644 packages/browser-extension/cli/src/extension-rpc.ts create mode 100644 packages/browser-extension/cli/src/flight-recorder.ts create mode 100644 packages/browser-extension/cli/src/fs-durability.ts create mode 100644 packages/browser-extension/cli/src/ghost-cursor.ts create mode 100644 packages/browser-extension/cli/src/handoff.ts create mode 100644 packages/browser-extension/cli/src/http-api.ts create mode 100644 packages/browser-extension/cli/src/human-input.ts create mode 100644 packages/browser-extension/cli/src/index.ts create mode 100644 packages/browser-extension/cli/src/main.ts create mode 100644 packages/browser-extension/cli/src/mcp-main.ts create mode 100644 packages/browser-extension/cli/src/mcp.ts create mode 100644 packages/browser-extension/cli/src/mjpeg-matroska.ts create mode 100644 packages/browser-extension/cli/src/network-capture.ts create mode 100644 packages/browser-extension/cli/src/network-redaction.ts create mode 100644 packages/browser-extension/cli/src/opencode-browser-client.ts create mode 100644 packages/browser-extension/cli/src/page-console.ts create mode 100644 packages/browser-extension/cli/src/page-read-timeout.ts create mode 100644 packages/browser-extension/cli/src/patchright-tuning.ts create mode 100644 packages/browser-extension/cli/src/paths.ts create mode 100644 packages/browser-extension/cli/src/protected-frames.ts create mode 100644 packages/browser-extension/cli/src/protocol.ts create mode 100644 packages/browser-extension/cli/src/recording-protocol.ts create mode 100644 packages/browser-extension/cli/src/recording-relay.ts create mode 100644 packages/browser-extension/cli/src/relay-client.ts create mode 100644 packages/browser-extension/cli/src/relay-helpers.ts create mode 100644 packages/browser-extension/cli/src/relay-lifecycle-log.ts create mode 100644 packages/browser-extension/cli/src/relay-lifecycle.ts create mode 100644 packages/browser-extension/cli/src/relay-log.ts create mode 100644 packages/browser-extension/cli/src/relay-schema.ts create mode 100644 packages/browser-extension/cli/src/relay-shutdown.ts create mode 100644 packages/browser-extension/cli/src/relay-types.ts create mode 100644 packages/browser-extension/cli/src/relay.ts create mode 100644 packages/browser-extension/cli/src/root-target-lifecycle.ts create mode 100644 packages/browser-extension/cli/src/runtime-diagnostics.ts create mode 100644 packages/browser-extension/cli/src/screenshot-diff.ts create mode 100644 packages/browser-extension/cli/src/secret-profile.ts create mode 100644 packages/browser-extension/cli/src/session-catalog.ts create mode 100644 packages/browser-extension/cli/src/session-journal.ts create mode 100644 packages/browser-extension/cli/src/session-manager.ts create mode 100644 packages/browser-extension/cli/src/session-store.ts create mode 100644 packages/browser-extension/cli/src/setup.ts create mode 100644 packages/browser-extension/cli/src/snapshot.ts create mode 100644 packages/browser-extension/cli/src/target-registry.ts create mode 100644 packages/browser-extension/cli/src/version.ts create mode 100644 packages/browser-extension/cli/src/webmcp.ts create mode 100644 packages/browser-extension/cli/tsconfig.json diff --git a/packages/browser-extension/cli/.gitignore b/packages/browser-extension/cli/.gitignore new file mode 100644 index 00000000000..012f34b379a --- /dev/null +++ b/packages/browser-extension/cli/.gitignore @@ -0,0 +1,2 @@ +dist/ +extension/ diff --git a/packages/browser-extension/cli/build.ts b/packages/browser-extension/cli/build.ts new file mode 100644 index 00000000000..ee7e1f8d36b --- /dev/null +++ b/packages/browser-extension/cli/build.ts @@ -0,0 +1,57 @@ +// Builds the published package: dist/cli.mjs (main.ts and everything it loads, with npm dependencies left +// external and installed by npm) and extension/ (the built unpacked extension, keeping its manifest key so the +// unpacked ID matches the host's allowed origins). Both carry this package's version. +import { $ } from "bun" +import { chmod, cp, rm } from "node:fs/promises" +import path from "node:path" + +const here = import.meta.dir +const extension = path.resolve(here, "..") +const pkg = await Bun.file(path.join(here, "package.json")).json() + +const build = new Date().toISOString() +await $`bun run build`.cwd(extension).env({ ...process.env, OPENCODE_BROWSER_BUILD: build }).quiet() +await rm(path.join(here, "dist"), { recursive: true, force: true }) +await rm(path.join(here, "extension"), { recursive: true, force: true }) + +const result = await Bun.build({ + entrypoints: [path.join(here, "src/main.ts")], + outdir: path.join(here, "dist"), + naming: "cli.mjs", + target: "node", + format: "esm", + // Runtime dependencies stay external; jsonc-parser (a dev dependency) is bundled. + external: Object.keys(pkg.dependencies ?? {}), + plugins: [ + { + // jsonc-parser's default entry is UMD with runtime requires; its ESM build bundles cleanly. + name: "jsonc-parser-esm", + setup(build) { + build.onResolve({ filter: /^jsonc-parser$/ }, () => ({ + path: path.join(path.dirname(Bun.resolveSync("jsonc-parser/package.json", here)), "lib/esm/main.js"), + })) + }, + }, + ], + define: { + "globalThis.__OPENCODE_BROWSER_VERSION__": JSON.stringify(pkg.version), + "globalThis.__OPENCODE_BROWSER_BUILD_ID__": JSON.stringify(new Date().toISOString()), + }, +}) +if (!result.success) throw new AggregateError(result.logs, "build failed") +const cli = path.join(here, "dist", "cli.mjs") +const source = await Bun.file(cli).text() +await Bun.write(cli, source.startsWith("#!") ? source : `#!/usr/bin/env node\n${source}`) +await chmod(cli, 0o755) + +await cp(path.join(extension, "dist"), path.join(here, "extension"), { + recursive: true, + filter: (file) => !file.endsWith(".map"), +}) +const manifestFile = path.join(here, "extension", "manifest.json") +const manifest = await Bun.file(manifestFile).json() +manifest.version = pkg.version +await Bun.write(manifestFile, JSON.stringify(manifest, null, 2) + "\n") +// install compares this with the build a connected extension reports, to skip a reload that changes nothing. +await Bun.write(path.join(here, "extension", "build.json"), JSON.stringify({ build }) + "\n") +console.log(`built dist/cli.mjs and extension/ (${pkg.version})`) diff --git a/packages/browser-extension/cli/bun.lock b/packages/browser-extension/cli/bun.lock new file mode 100644 index 00000000000..880aeb31936 --- /dev/null +++ b/packages/browser-extension/cli/bun.lock @@ -0,0 +1,92 @@ +{ + "lockfileVersion": 2, + "configVersion": 1, + "workspaces": { + "": { + "name": "opencode-browser-cli", + "dependencies": { + "@effect/platform-node": "4.0.1", + "@effect/platform-node-shared": "4.0.1", + "acorn": "8.18.0", + "effect": "4.0.1", + "patchright-core": "1.63.0", + "pixelmatch": "7.2.0", + "pngjs": "7.0.0", + "ws": "8.22.0", + }, + "devDependencies": { + "@types/chrome": "0.3.4", + "@types/node": "26.6.4", + "@types/pngjs": "6.0.5", + "@types/ws": "8.18.2", + "@typescript/native-preview": "7.0.0-dev.20260707.2", + "jsonc-parser": "3.3.1", + }, + }, + }, + "packages": { + "@effect/platform-node": ["@effect/platform-node@4.0.1", "", { "dependencies": { "@effect/platform-node-shared": "^4.0.1", "undici": "^8.11.2" }, "peerDependencies": { "effect": "^4.0.1", "redis": ">=5.0.0 <7.0.0" } }, "sha512-FT0Fu5LO0/XP9zBpj0HqrtJNLluK4StNKqf6TSulUsjp8FPBsDVXGJiDuyoN5J2yVMT7tgvhxSwaDcObWVRIaQ=="], + + "@effect/platform-node-shared": ["@effect/platform-node-shared@4.0.1", "", { "dependencies": { "@types/ws": "^8.18.1", "ws": "^8.22.0" }, "peerDependencies": { "effect": "^4.0.1" } }, "sha512-VanaejudEhKJ4mpmqnEzdncVUhN6sGSO9ZDND54mRxAlZxj+4dYAWjDTYAy9o4tJo9aALeP2U8cVcOFzEdSeLg=="], + + "@redis/bloom": ["@redis/bloom@6.3.0", "", { "peerDependencies": { "@redis/client": "^6.3.0" } }, "sha512-NQ5poYpZr0jv6zazN1cy6JY5kIipKFZ3R9GTL4kOUTX3a9YAfY29U8bsE4lWhVQEM+G4V0BXVC57mubIdDijeA=="], + + "@redis/client": ["@redis/client@6.3.0", "", { "peerDependencies": { "@node-rs/xxhash": "^1.1.0", "@opentelemetry/api": ">=1 <2" }, "optionalPeers": ["@node-rs/xxhash", "@opentelemetry/api"] }, "sha512-fHrjwGCBvAANGi+TuRuwKi83sIOzgHr8eh+Uf48w3fSX7Hhrz174NrWqfJhAC2vnN0d/tfaZpdr6+o6JC3QHwg=="], + + "@redis/json": ["@redis/json@6.3.0", "", { "peerDependencies": { "@redis/client": "^6.3.0" } }, "sha512-yt6vRfPBXtW/3qm53cF81TSQpLMjWdW4/2E9WQ2GgbvsKkuCKCFQIcMiKlil1ZMnezK+IQuS795xKU5psbaegw=="], + + "@redis/search": ["@redis/search@6.3.0", "", { "peerDependencies": { "@redis/client": "^6.3.0" } }, "sha512-RPXAZmKjZZG7Tm7m1w9keFdXzbL91PiSHQBfQRe9xwW40jNsTRbG0FwhIz4QlHPU4gKDAsCy8IQHj4yZl4H9rw=="], + + "@redis/time-series": ["@redis/time-series@6.3.0", "", { "peerDependencies": { "@redis/client": "^6.3.0" } }, "sha512-+fJOB8mN1z5WRakCJNh5lVdz1KqvHGSOistsKeitD24QsCtPwyRQXWC0iq6T/i/ubLE/YcguZqPm8F598MKk4A=="], + + "@types/chrome": ["@types/chrome@0.3.4", "", { "dependencies": { "@types/filesystem": "*", "@types/har-format": "*" } }, "sha512-dcySM5R3WAUVYFjylu6tvI4D03hPKjgAqk+tKZ/tm/vxL4mLgbnSsOEQ3J7V99qP/U3Oo9IORstJLmX2hPaDlA=="], + + "@types/filesystem": ["@types/filesystem@0.0.36", "", { "dependencies": { "@types/filewriter": "*" } }, "sha512-vPDXOZuannb9FZdxgHnqSwAG/jvdGM8Wq+6N4D/d80z+D4HWH+bItqsZaVRQykAn6WEVeEkLm2oQigyHtgb0RA=="], + + "@types/filewriter": ["@types/filewriter@0.0.33", "", {}, "sha512-xFU8ZXTw4gd358lb2jw25nxY9QAgqn2+bKKjKOYfNCzN4DKCFetK7sPtrlpg66Ywe3vWY9FNxprZawAh9wfJ3g=="], + + "@types/har-format": ["@types/har-format@1.2.16", "", {}, "sha512-fluxdy7ryD3MV6h8pTfTYpy/xQzCFC7m89nOH9y94cNqJ1mDIDPut7MnRHI3F6qRmh/cT2fUjG1MLdCNb4hE9A=="], + + "@types/node": ["@types/node@26.6.4", "", { "dependencies": { "undici-types": "~8.9.0" } }, "sha512-ldVPDCzj7fsaGZrLB0NuHuTvJcsNasysBAqMolr/cgxrLd1xbqxIr3XJiPnHHJUCxj5sNF1vnRj9aWnrVh5Jcg=="], + + "@types/pngjs": ["@types/pngjs@6.0.5", "", { "dependencies": { "@types/node": "*" } }, "sha512-0k5eKfrA83JOZPppLtS2C7OUtyNAl2wKNxfyYl9Q5g9lPkgBl/9hNyAu6HuEH2J4XmIv2znEpkDd0SaZVxW6iQ=="], + + "@types/ws": ["@types/ws@8.18.2", "", { "dependencies": { "@types/node": "*" } }, "sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w=="], + + "@typescript/native-preview": ["@typescript/native-preview@7.0.0-dev.20260707.2", "", { "optionalDependencies": { "@typescript/native-preview-darwin-arm64": "7.0.0-dev.20260707.2", "@typescript/native-preview-darwin-x64": "7.0.0-dev.20260707.2", "@typescript/native-preview-linux-arm": "7.0.0-dev.20260707.2", "@typescript/native-preview-linux-arm64": "7.0.0-dev.20260707.2", "@typescript/native-preview-linux-x64": "7.0.0-dev.20260707.2", "@typescript/native-preview-win32-arm64": "7.0.0-dev.20260707.2", "@typescript/native-preview-win32-x64": "7.0.0-dev.20260707.2" }, "bin": { "tsgo": "bin/tsgo" } }, "sha512-oUGp+Rep/hqMhPunyinsALUwSlzHINSxitifPiSaeqoKOKD2OlR9NE3TaPqwsl4NlGslsOSUXI1JotWQzpYCPg=="], + + "@typescript/native-preview-darwin-arm64": ["@typescript/native-preview-darwin-arm64@7.0.0-dev.20260707.2", "", { "os": "darwin", "cpu": "arm64" }, "sha512-wny2pgKjGbiZtnOIHVa3tXC1UfDqxNEFzyPGmiqybedG8hipG2Nfp0l5UxbaKCjkLacUpH/W5bP2hBOMVhCOzg=="], + + "@typescript/native-preview-darwin-x64": ["@typescript/native-preview-darwin-x64@7.0.0-dev.20260707.2", "", { "os": "darwin", "cpu": "x64" }, "sha512-Afc7M5zOwo+GpfcYwz5Z8HMB2tPVsui7nNIqEuuFB73MPdVqNn/Wmpe4tP4MRri0AtJnJknoHBaTJ/VDAp/Jhw=="], + + "@typescript/native-preview-linux-arm": ["@typescript/native-preview-linux-arm@7.0.0-dev.20260707.2", "", { "os": "linux", "cpu": "arm" }, "sha512-hJm/UOqZTr9FHmR7uNm8VGX4oKtfWk0Jem0zPeJFNC8ckGUfSBueyiEYMZB+XmRc1aG4x1E46y3CplP4CLHvGQ=="], + + "@typescript/native-preview-linux-arm64": ["@typescript/native-preview-linux-arm64@7.0.0-dev.20260707.2", "", { "os": "linux", "cpu": "arm64" }, "sha512-iITBa2WjjTI5N9t5l7Z4KoOSI+2zBlhbvFzsD/f8qX8QoKjz/Y4DPyBDgezYi8nkqjjksbgSOJ3/ykzhwrB9cg=="], + + "@typescript/native-preview-linux-x64": ["@typescript/native-preview-linux-x64@7.0.0-dev.20260707.2", "", { "os": "linux", "cpu": "x64" }, "sha512-du0dzi6y97Po5vDNdPJTyyijHCpaS22JLRnKZEJXBDaO9gCIymOv/5QQokFRuOlQm0bWl3i9PF4OVdGP6uAOQA=="], + + "@typescript/native-preview-win32-arm64": ["@typescript/native-preview-win32-arm64@7.0.0-dev.20260707.2", "", { "os": "win32", "cpu": "arm64" }, "sha512-SsAwfhyHJ1akgBc+99z4+hwdbHsdWaKB8EwCNIMA6JfSLMeUjffrYvxu+vfMyxVtOVOz7RrRXRoiDiu4a2sCtg=="], + + "@typescript/native-preview-win32-x64": ["@typescript/native-preview-win32-x64@7.0.0-dev.20260707.2", "", { "os": "win32", "cpu": "x64" }, "sha512-DL4u27stv0fo71sVhOzHSwE+YMZsbBijVI+kg5dLDLilSH79WFTJ8RSQ46vJrCMt+Gjlv/JOZP1PuLJDfioYeQ=="], + + "acorn": ["acorn@8.18.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ=="], + + "effect": ["effect@4.0.1", "", {}, "sha512-b1VlQG9g8fwxE5QnIZuPoOP/0MsqHJSRKxUijjoM80E5q95FXrX5yWtY5XI8G+GJsBQAVSDbLS458z9a++uVvw=="], + + "jsonc-parser": ["jsonc-parser@3.3.1", "", {}, "sha512-HUgH65KyejrUFPvHFPbqOY0rsFip3Bo5wb4ngvdi1EpCYWUQDC5V+Y7mZws+DLkr4M//zQJoanu1SP+87Dv1oQ=="], + + "patchright-core": ["patchright-core@1.63.0", "", { "bin": { "patchright-core": "cli.js" } }, "sha512-nuRJVTMVKoOFzY8vmwFqJZR3F0trUCKiPzDSgCOPq/yHHTefm9czILV23dXJsi5mvS7sCy7U1CqG7edA/21DtQ=="], + + "pixelmatch": ["pixelmatch@7.2.0", "", { "dependencies": { "pngjs": "^7.0.0" }, "bin": { "pixelmatch": "bin/pixelmatch" } }, "sha512-xhcb4yHu9sM/G7foGzoLtXYcC0zHEaOXXjRKhGup0fw78Nf2Tkiapv4EQyMzrbcmQPsllAI7DbFY2UT7PlI9Pg=="], + + "pngjs": ["pngjs@7.0.0", "", {}, "sha512-LKWqWJRhstyYo9pGvgor/ivk2w94eSjE3RGVuzLGlr3NmD8bf7RcYGze1mNdEHRP6TRP6rMuDHk5t44hnTRyow=="], + + "redis": ["redis@6.3.0", "", { "dependencies": { "@redis/bloom": "6.3.0", "@redis/client": "6.3.0", "@redis/json": "6.3.0", "@redis/search": "6.3.0", "@redis/time-series": "6.3.0" } }, "sha512-XFQbPie1lGpKeUZ8ySYY43yLnQy/iIQtHNvIr/1XdaABpb96rUSdm3Mfl+98FEVbv9ZJIzINMno5s0Nh8E5LEw=="], + + "undici": ["undici@8.11.2", "", {}, "sha512-u4UB2/IrKdU6lFxumHmmo1a3fCQO5tzQllRorfoRS63txhrB7xTpSn1PftwC4qEHkOaqP95fCWW4lJzwErwzhQ=="], + + "undici-types": ["undici-types@8.9.0", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="], + + "ws": ["ws@8.22.0", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg=="], + } +} diff --git a/packages/browser-extension/cli/package.json b/packages/browser-extension/cli/package.json new file mode 100644 index 00000000000..ac638ce7b4a --- /dev/null +++ b/packages/browser-extension/cli/package.json @@ -0,0 +1,47 @@ +{ + "name": "opencode-browser-cli", + "version": "0.0.2", + "description": "OpenCode Browser: connect the extension to opencode, and drive your browser from any agent (CLI, MCP, Playwright).", + "type": "module", + "license": "MIT", + "bin": { + "opencode-browser": "dist/cli.mjs", + "opencode-browser-cli": "dist/cli.mjs" + }, + "files": [ + "dist", + "extension", + "skills" + ], + "engines": { + "node": ">=22.19.0" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/anomalyco/opencode.git", + "directory": "packages/browser-extension/cli" + }, + "scripts": { + "build": "bun build.ts", + "typecheck": "tsgo --noEmit -p tsconfig.json", + "prepublishOnly": "bun build.ts" + }, + "dependencies": { + "@effect/platform-node": "4.0.1", + "@effect/platform-node-shared": "4.0.1", + "acorn": "8.18.0", + "effect": "4.0.1", + "pixelmatch": "7.2.0", + "patchright-core": "1.63.0", + "pngjs": "7.0.0", + "ws": "8.22.0" + }, + "devDependencies": { + "@types/chrome": "0.3.4", + "@types/node": "26.6.4", + "@types/pngjs": "6.0.5", + "@types/ws": "8.18.2", + "@typescript/native-preview": "7.0.0-dev.20260707.2", + "jsonc-parser": "3.3.1" + } +} diff --git a/packages/browser-extension/cli/skills/browse/SKILL.md b/packages/browser-extension/cli/skills/browse/SKILL.md new file mode 100644 index 00000000000..061e8966775 --- /dev/null +++ b/packages/browser-extension/cli/skills/browse/SKILL.md @@ -0,0 +1,686 @@ +--- +name: browse +description: Browse with the user's existing Chromium-family browser (OpenCode Browser) using deterministic Playwright. Use when asked to inspect, automate, test, or interact with a visible browser tab; continue an authenticated browser workflow; handle 2FA, passkeys, CAPTCHAs, or payment confirmation; record browser behavior; or capture an authenticated network flow. +--- + +# browse (OpenCode Browser) + +The `browse` tools (MCP server `browse`; the same commands as the `opencode-browser` +CLI) drive the user's browser through the OpenCode Browser extension. +OpenCode Browser is a **driver**, not an agent. The calling agent decides what to +do; OpenCode Browser runs deterministic Playwright code in the user's visible +browser. + +Use one loop throughout: **inspect, act, verify**. Inspect the real page before +choosing locators, act through the narrowest stable control, then verify the +result through a URL or fresh page read. Never treat a successful click or human +acknowledgment as proof that the task succeeded. + +## Core Workflow + +### 1. Run The Task Directly + +Start with the requested browser work. Relay-backed commands start the detached +relay and wait for the extension; do not start `opencode-browser serve` first. + +```bash +opencode-browser execute 'return { url: page.url(), title: await page.title() }' +``` + +Use `opencode-browser doctor` only when setup or runtime behavior is unclear. +`status` and `doctor` are observational and never start the relay. + +MCP startup, tool discovery, `skill`, and `session_current` do not contact the +relay. The first operational tool call starts it if needed; relay-backed +observational tools report unavailability instead of starting it. + +For an externally supervised relay, set `OPENCODE_BROWSER_AUTOSTART=false` to +make ordinary calls fail when that relay is absent instead of launching another +process. Existing relay connections and explicit `relay restart` still work. + +Ordinary CLI/MCP/SDK calls never replace a running relay. On a build mismatch, +coordinate with other agents before running `opencode-browser relay restart`. +It preserves browser tabs and durable sessions but resets JavaScript state and +snapshot refs. A busy or timed-out drain leaves the old relay running; finish +recordings/captures and disconnect raw CDP clients rather than forcing a stop. + +```bash +opencode-browser doctor +opencode-browser status --json +``` + +Completion: one execute returns a page result and a readable session id, or +`doctor` identifies the concrete setup failure. + +### 2. Choose The Page Deliberately + +DevTools-attached tabs +are excluded from OpenCode Browser's inventory. `page.title()` reads time out +after five seconds if the page execution context remains unavailable; the read +timeout does not close or replace the tab. + +A bare CLI execute creates a fresh session-owned page and prints the exact +`--session ` continuation command, or you can pass a descriptive session +name (including an optional emoji, which appears directly on the browser tab +group and in-page status pill). Every later CLI call must pass that id or set +`OPENCODE_BROWSER_SESSION`; bare execute never guesses from human-shell current +state. + +```bash +opencode-browser session new "๐ŸŽ™๏ธ elevenlabs" +opencode-browser execute --session "๐ŸŽ™๏ธ elevenlabs" 'return page.url()' +opencode-browser execute 'return page.url()' +``` + +MCP keeps one implicit process session. Omit `session` for that normal path, or +call `session_new` and pass an explicit id when one MCP process needs multiple +sessions. + +To work in a tab the user already has open, ask them to click the OpenCode +Browser toolbar button on it (the badge shows ON; another click takes it back). +`status` then lists it with `owner=user` and its `tab=` id. Select it for one +execute, or adopt it for sticky reuse with `session_adopt({ tabId })` (omit the +selector when only one user tab is attached): + +```bash +opencode-browser session adopt --tab-id 123 --session github +opencode-browser session adopt --target-url github.com --session github +opencode-browser execute --target-url github.com 'return page.url()' +``` + +`execute --target-url` selects a page for that call only. Continuing with just +`--session` uses the session's default page, which may still be `about:blank`. +For a multi-step task in an existing user tab, adopt it first. Always include +`page.url()` when diagnosing an empty snapshot. Snapshot labels are compact +descriptions; use `ref()` for actions rather than assuming their text is an +exact Playwright accessible name. + +`targetUrl` and `targetIndex` select existing attached pages; they never +navigate. A URL selector must match exactly one page, and URL and index selectors +cannot be combined. Adoption makes that tab the session default, closes the +session's previous relay-created page, and is exclusive to one OpenCode Browser +session. Reset or delete releases an adopted user tab without closing it. + +Adoption binds ownership and exact target identity before initializing automation. +Until the first execute resolves the page, session status reports `connected: +false` and `pageUrl: null`; `adoptedUrl` is the registry-selected URL, not a fresh +page read. A busy page can produce `session-page/adopted-initialization-timeout` +on execute: user code did not run, and the exact adopted target is retained. +Retry after the page settles; do not reset or adopt a different tab to recover. + +Prefer adoption for authenticated browser state rather than reproducing login +in a fresh page. + +Each relay controls one browser/profile at a time. A second extension connection +cannot replace a healthy active connection. If `status` or `doctor` reports +rejected competing connections, keep the extension enabled only in the intended +browser/profile. To switch browsers, disconnect the incumbent extension first; +creating a new execute session does not switch browsers. + +Completion: the selected page URL is the intended page, and later work either +retains the returned session id or intentionally uses the MCP process session. + +### 3. Inspect, Act, Verify + +Inspect before guessing roles or selectors: + +```js +return await snapshot() +``` + +Then act from the returned structure and verify the destination: + +```js +await ref("e12").click() +await page.getByRole("heading", { name: "Settings" }).waitFor() +if (!page.url().includes("/settings")) { + throw new Error(`Unexpected destination: ${page.url()}`) +} +return { url: page.url(), heading: await page.getByRole("heading").first().innerText() } +``` + +Use normal Playwright first. Keep dependent interactions in one execute when +they rely on transient UI such as an open menu, selected rows, hover state, or +an in-progress form. + +Clicks, hovers and key presses already move and pace like a person (curved +mouse paths, a short settle before pressing, human key gaps), so don't add your +own `steps` or delays. `fill()` pastes text in one go; on sites that watch +typing (sign-ups, logins behind bot protection), type with +`locator.pressSequentially(text)` instead. + +If native `locator.fill()` hangs because a browser extension interferes with +focus, use the explicit input, textarea, or contenteditable fallback: + +```js +await fillInput(page.getByPlaceholder("Username"), "standard_user") +``` + +Completion: the final return value contains evidence of the requested outcome, +not merely evidence that an action was attempted. + +### 4. Continue Or Finish Cleanly + +Named sessions preserve their default page across short-lived CLI and MCP +processes. They also survive relay restarts: OpenCode Browser restores the id, +read-only mode, and exact default target. JavaScript `state` and snapshot refs +are process-local and reset after a relay restart with an explicit warning. + +```bash +opencode-browser session list +opencode-browser session reset github +opencode-browser session delete github +``` + +Deletion is idempotent for an explicit session id, so cleanup can be safely +retried when that session is already absent. + +Give a session a short, meaningful id (`github`, `checkout-test`): the tabs it +opens are grouped in the browser under that name. Unnamed sessions are grouped as +"Agent ยท ". + +Tabs agents open close by themselves after about 10 minutes without use (no +command and not visited by the user); tabs the user shared, pinned, or is +looking at stay open. When a task is done, tidy up right away: + +```bash +opencode-browser tabs cleanup --idle-minutes 0 # MCP: tabs_cleanup { idleMinutes: 0 } +``` + +Every execute is journaled under +`/sessions//journal.jsonl` (`~/.local/share/opencode-browser` on +macOS and Linux). The journal records code, +status, duration, URL movement, warnings, handoffs, and bounded diagnostics. +Never place credentials directly in execute source. + +```bash +opencode-browser journal --session github --limit 50 +``` + +Completion: retain the session only when follow-up work is expected; otherwise +reset or delete session-owned pages and report any warnings that affect later +work. + +## Canonical Authenticated Flow + +The distinguishing OpenCode Browser workflow is an authenticated tab plus a +human-only prompt: + +Attach and adopt the existing tab, inspect its real UI, fill ordinary fields, +then register `handoff` before triggering WebAuthn, 2FA, CAPTCHA, or payment UI. +After the user completes it, verify the authenticated destination. The same +session can continue after an MCP process or relay restart. + +When the prompt-triggering action may itself block, put only that action in +`start`. OpenCode Browser presents and acknowledges WAIT before invoking it: + +```js +await handoff("Complete the security-key prompt, then continue", { + timeoutMs: 600_000, + start: () => page + .getByRole("button", { name: /passkey|security key|sign in/i }) + .click({ timeout: 600_000 }), +}) + +await page.waitForURL((url) => !url.pathname.startsWith("/login")) +await page.getByRole("heading", { name: /account|dashboard/i }).waitFor() +return { authenticatedUrl: page.url(), title: await page.title() } +``` + +After a resolved handoff, OpenCode Browser waits through transient destination +context replacement before returning, so this verification can remain in the +same execute. + +With `start`, the handoff deadline and target cancellation remain active until +the action settles, even if the user has already pressed Continue. An early +acknowledgment does not authorize an indefinitely pending action. + +For a handoff on another page, pass `{ page: otherPage }`. Readiness checks that +page, not the session default. If a non-default page was replaced or closed, +inspect the remaining pages rather than assuming an old Playwright reference +now identifies its replacement. + +Tell the user what action is waiting. Human acknowledgment is not verification: +always assert the expected URL or stable element after `handoff`. If the action +was already completed and only the human step remains, call `handoff(message)` +without `start`. The default timeout is ten minutes. + +Completion: the prompt was presented only after WAIT was registered, the action +settled, and the authenticated result was independently verified. + +To turn a user-demonstrated flow into reusable Playwright, use `demonstrate()`. +It uses the same exact-tab handoff, records clicks, edits, checkbox/select +changes, and same-tab navigations, then returns editable code: + +```ts +return await demonstrate("Perform the workflow once, then continue") +``` + +Password fields become explicit secret-source comments rather than copied +values. Review selectors and add outcome assertions before reusing generated +code; a demonstration records actions, not proof that the workflow succeeded. + +### Password Manager Prompts + +Ordinary webpage fields and accessible open-shadow-root controls remain usable. +1Password's inline menus are extension-owned iframes, not ordinary webpage DOM. +Chromium blocks one extension from debugging another extension's pages; toolbar +popups and native unlock, Touch ID, and Windows Hello prompts are not supported +Playwright control surfaces. + +Focusing or filling a card-number or credential field can open the inline menu +by itself, even inside a third-party payment iframe. While it is open, Chrome +rejects every automation command for that tab; Playwright shows this as +"Execution context was destroyed" or a locator timeout, so the execute result +carries the `target/cross-extension-page` diagnostic and warning, and +`opencode-browser status` marks the tab `protected-ui=true`. + +`target/cross-extension-page` means a permission boundary. Ask the user to finish +or dismiss the prompt and retry; do not reset the page, read vault contents, or +weaken browser security to get around it. The page itself is healthy: do not +treat the failure as an unresponsive tab or create a new page. Register `handoff` on the originating +webpage before triggering a human-only prompt when possible. If the prompt +already prevents attachment, give the user the required action directly rather +than assuming an in-page handoff can be displayed. Verify the intended webpage +state after the prompt is completed. + +## Inspection Tools + +Use the least expensive view that answers the question: + +- `snapshot()` is the compact read-before-act default. It prioritizes semantic + groups, alerts, lists, tables, headings, links, and controls. Text input and + textarea values are omitted. +- The default snapshot scopes to a single visible modal when present; portal + dialogs outside `main` remain discoverable. Use an explicit `within` scope + when you intentionally need background content. Repeated list wrappers have + a bounded reservation so product links can still fit in a dense page. +- Native number/search inputs are `spinbutton`/`searchbox`. Native disclosure + controls are labeled `summary`, which is an element kind rather than an ARIA + role; use the returned `ref()` to operate them. +- `ref("e12")` resolves a control from the latest snapshot. Refs fail closed + after navigation or incompatible DOM drift. Compatible refs keep the same id + across repeated same-document captures. +- `snapshot({ diff: true })` reports semantic changes from the compatible prior + baseline. `snapshot({ delta: true })` returns a full first baseline and compact + deltas afterward. Existing compatible refs remain usable. +- `snapshot({ find: "checkout", context: 2 })` searches the bounded semantic + snapshot and returns matching lines with nearby context and actionable refs. +- `ariaSnapshot(target?, { timeout })` returns Playwright's detailed YAML aria + tree when the compact snapshot omits needed structure. Native text-control + values, custom ARIA range values, and editable content are omitted so they do + not enter tool output. Await it separately; do not run other operations on + the same page concurrently. +- `screenshotWithLabels({ page?, path? })` adds visual labels and metadata when + layout matters, and registers its `e1..eN` labels for `ref()`. +- `screenshotDiff({ baseline, path?, threshold?, fullPage? })` compares a saved + PNG (absolute path or Buffer) with the current session page at CSS-pixel scale. + It returns `matches`, `changedPixels`, `changedRatio` (0..1), dimensions, and a + red-highlighted PNG. Omit `path` to return the image as execute media; otherwise + supply a fresh absolute `.png` path. Existing output files are never overwritten. + +```js +return await snapshot({ within: "main", maxItems: 200 }) +return await snapshot({ find: /checkout|payment/i, context: 2 }) +return await snapshot({ delta: true }) +// When layout matters, return the image through MCP so it can be inspected. +return await screenshotWithLabels({ page }) +``` + +Saving an image and returning only `"ok"` proves file creation, not visual +correctness. Return screenshot buffers through MCP when visual evidence matters. + +For visual regression checks, save a baseline before changing the UI: + +```ts +await page.screenshot({ path: "/absolute/before.png", scale: "css" }) +// After the intended UI change, in the same viewport: +return await screenshotDiff({ baseline: "/absolute/before.png" }) +``` + +The threshold defaults to 0.1 and controls per-pixel color tolerance, not the +allowed changed area. Set it to 0 for exact pixels. Antialiasing changes count. +Settle animations yourself and use the same viewport and `fullPage` setting for +both captures. Dimension mismatches fail explicitly; images are never resized. +Comparisons are limited to PNGs of 32 MiB / 16 megapixels each. Screenshots and +diffs include visible page content: inspect for private information before sharing. + +## Execute Interface + +Execute code can use `page`, `context`, `browser`, persistent `state`, selected +Node modules through `modules` and aliases such as `fs` and `path`, plus the +OpenCode Browser helpers documented here. Execute code runs in Node. Use +`page.evaluate` for `window`, `document`, storage, and same-origin `fetch` +with page cookies. Single expressions auto-return; +multi-statement scripts need `return`. Use `--file` for longer scripts: + +```bash +opencode-browser execute --session github --file ./perform-flow.js +``` + +Human CLI output includes logs, warnings, and a concise aftermath. Logs hold your +own `console.log` output; the page's console messages and uncaught errors are +off by default, because capturing them lets the page detect a debugger (bot +checks look for it). When you need them, for example to debug a broken page, +turn them on for that page; they then appear in each execute's logs: + +```js +await pageConsole.start() // or pageConsole.start(otherPage) +await pageConsole.stop() // when done, so the page looks undebugged again +``` + + Use `--json` +when another command needs to branch on `ok`, `value`, `error`, `warnings`, or +`aftermath`: + +```bash +opencode-browser execute --json --session github '({ url: page.url() })' | jq .value.url +``` + +Playwright downloads are unavailable through extension-backed tabs because +Chromium blocks download artifact control through `chrome.debugger`. If the +page exposes the payload through fetch or an API response, read the bytes in the +page and write them with `fs`. Do not retry `page.waitForEvent("download")`. + +Pages with WebMCP enabled can expose structured page tools. Discover and call +them through the execute helper; names, descriptions, schemas, and results come +from the page: + +```ts +const tools = await webmcp.list() +const result = await webmcp.call("search_catalog", { query: "adapter" }) +return { tools, result } +``` + +Discovery covers all frames. If the same name appears in multiple frames, pass +the exact reported frame label as `{ frame }`. OpenCode Browser re-discovers the +tool immediately before invoking it, so stale registrations fail directly. + +## Safety + +OpenCode Browser blocks CDP commands that would destroy shared browser state, +including browser close and cookie/cache clearing. Never work around those +guardrails. + +For inspect-only work, use a read-only session: + +```bash +opencode-browser session new inspect-prod --read-only +opencode-browser execute --session inspect-prod 'await page.goto("https://example.com"); return page.title()' +``` + +Read-only sessions reject `Input.*`, so they cannot click or type through +Playwright. `page.evaluate` can still mutate the DOM; read-only prevents trusted +mistakes, not malicious code. + +For destructive UI work, use a two-phase **read, confirm, verify** flow: + +1. Read candidates and return exact stable identifiers or row text. +2. Obtain user approval for those exact items. +3. Re-select only approved items and assert the selected count. +4. Read the confirmation dialog and throw unless it matches the approved action. +5. Confirm, then verify through a fresh page read or independent CLI/API path. + +Do not discover and confirm destructive candidates in one script unless the +user already approved exact stable identifiers. Never globally auto-accept +native dialogs; wait for the expected dialog and assert its type and message +before accepting it. + +## TypeScript Client + +Applications and CLI tools can use `OpenCodeBrowserClient.origin()` for direct +same-origin JSON requests authenticated by a session page (with optional default +headers and automatic in-page `handoff` recovery when a session expires or +redirects to login): + +```ts +import { OpenCodeBrowserClient } from "opencode-browser-cli" + +const ubereats = OpenCodeBrowserClient.origin("https://www.ubereats.com", { + session: "๐Ÿฅค karma-cafe", + startUrl: "/feed", + headers: { "x-csrf-token": "x" }, + handoffOnAuthFailure: true, +}) + +const store = await ubereats.post("/_p/api/getStoreV1", { + storeUuid: "78cb1602-9f58-57bb-ad08-f6b8f80bb788", + diningMode: "DELIVERY", +}) +``` + +For Effect-native applications with schema decoding or `sensitive: true` +`Redacted` responses, use `OpenCodeBrowserClient.Service`: + +```ts +import { OpenCodeBrowserClient } from "opencode-browser-cli" + +const sensitive = yield* origin.json({ + path: "/api/session", + method: "POST", + body: {}, + response: SessionResponse, + sensitive: true, +}) +const session = OpenCodeBrowserClient.reveal(sensitive) +``` + +## Authenticated Network Capture + +Use network capture when the browser is needed to authenticate or discover a +workflow, but repeated direct HTTP calls would be faster and more reliable. +Capture each flow at least twice with different inputs so constants and +parameters can be distinguished. + +```bash +opencode-browser network start --session github --url /api/ \ + --resource-type fetch --resource-type xhr +opencode-browser execute --session github --file ./perform-flow.js +opencode-browser network status --session github +opencode-browser network stop --session github \ + --output ./github.har --secrets github +``` + +Written artifacts replace credential-bearing headers, cookies, query fields, +OAuth fragment fields, and structured body fields with stable references such as `${BC_SECRET_1}`. +`--secrets github` stores lossless values separately in a mode-`0600` Secret +Profile. Never copy profile values into source, output, diagnostics, or journals, +and never deliberately return or log credentials. + +Inspect the redacted artifact offline, generate one typed function per observed +flow, then verify each function with a harmless live request. Run generated +clients without exposing values: + +```bash +opencode-browser secrets status github +opencode-browser secrets run github -- ./github-cli repositories +``` + +Generated TypeScript applications can own that wrapper internally through the +public SDK: + +```ts +import { SecretProfile } from "opencode-browser-cli" +import { Effect } from "effect" + +const result = await Effect.runPromise(SecretProfile.run({ + name: "github", + command: process.execPath, + args: ["./github-cli.js", "repositories"], +})) +``` + +The trusted worker receives `BC_SECRET_N` variables and its bounded output is +redacted. The public SDK exposes profile metadata but never raw profile values. + +Refresh credentials normally renewed by a page reload with: + +```bash +opencode-browser secrets refresh github --session github --url /api/ +``` + +If refresh requires login or a human prompt, reauthenticate in the adopted tab +and repeat capture with the same profile. MCP exposes equivalent `network_*` +and `secrets_*` tools. + +Completion: the artifact contains references rather than credential values, the +generated operation passes a harmless live check, and no secret value appears +in source or output. + +## Recording + +Record an attached or session-owned tab with: + +```bash +opencode-browser recording start ./tmp/demo.mp4 --session github --mode cdp +opencode-browser recording status --session github +opencode-browser recording stop --session github +``` + +Start, stop, and status accept `--json`. CDP stop/status results include a +`quality` receipt: output dimensions/rate, source and retained-image counts/rates, +coalesced/dropped frames, and `screenshotFallback`. The fallback means no +compositor frames arrived and the video holds one stop-time screenshot; do not +present that as recorded motion. Source counters count compositor events, not +visually distinct frames. Low rates can be normal on a static page. Tab capture +and older relays omit quality telemetry rather than inventing measurements. + +Explicit frame rates must be integers from 1 through 60 in either mode; invalid +values fail instead of silently clamping. The start result reports the chosen rate. + +`--mode auto` uses tab capture for user-owned tabs and CDP for relay-owned tabs. +Tab capture can include audio; CDP requires `ffmpeg` and has no audio. Use the +command's `--help` for format and cursor options. + +Playwright mouse actions automatically reveal the on-page Ghost Cursor +(`distance-glide` motion + `tactile-bloom` click shockwave). When recording a +user-facing proof or PR walkthrough video, opt into the `ghostCursor` helpers +inside `execute` to focus attention on key steps and verified postconditions: + +```ts +await showGhostCursor() +await ghostCursor.caption("Verify cluster & promote release", { step: "01", tone: "neutral" }) +await ghostCursor.zoom("#release-card", { scale: 1.45 }) +await page.locator("#promote-btn").click() +await ghostCursor.keys("โŒ˜+โ‡ง+P", "Promote Release") +await ghostCursor.resetZoom() +await ghostCursor.spotlight("#status-badge", { label: "Verified", detail: "200 OK", tone: "success" }) +``` + +CDP recordings preserve the starting CSS viewport (not a fixed 720p canvas), +use high-quality source frames, and default to 60 fps. Use `--frame-rate 30` +for smaller files. Actual motion still depends on Chrome delivering new frames; +60 fps output does not guarantee 60 distinct frames. Larger viewports cost more +CPU, transport bandwidth, and storage. Set the viewport before recording and do +not change viewport/emulation mid-recording. Odd dimensions round down to even. + +For failures that are hard to reproduce, keep a rolling CDP frame buffer and +save recent history after the problem occurs: + +```bash +opencode-browser flight-recorder start --session github --retention-ms 60000 +opencode-browser flight-recorder status --session github +opencode-browser flight-recorder save-last ./tmp/failure.mp4 --session github --duration-ms 30000 +opencode-browser flight-recorder cancel --session github +``` + +Saving does not stop buffering. The recorder is memory-bounded, reports retained +duration/frame/byte/drop counters, writes a JSON receipt beside each clip, and is +mutually exclusive with ordinary recording on the same tab. CLI recording and +flight-recorder lifecycle operations are also available as MCP tools. + +Inspect an encoded frame at native size before sharing: the whole viewport must +fill the frame, small text must be readable, and motion must not be a repeated +still image. Do not crop and upscale a low-resolution capture to call it HD. +On an older installed relay that shrinks the page into a padded corner, record +the defect and coordinate a recorder update; changing the file's resolution is +not a repair. + +Completion: stop the recorder, inspect the resulting media rather than only its +existence, and report the viewport, state, and interaction path actually tested. + +## Troubleshooting + +1. Run `opencode-browser doctor`; it checks package metadata, CLI/relay build + identity, extension protocol compatibility, sessions, targets, and artifacts. +2. Use `status --json` to inspect exact sessions and target ownership. +3. Reproduce once with the smallest execute before changing code. + +Common diagnoses: + +- `session-page/context-read-timeout; operation=page.title; timeoutMs=5000`: + the title read did not finish within its budget. The execution context may be + unavailable or busy; this does not prove a frozen renderer. The watchdog does + not cancel the underlying read or trigger page replacement. A cached + `page.url()` read can still work; retry the page read after the page settles. + Ordinary missing-locator timeouts do not receive this diagnostic. +- `connected:false`: run a relay-backed command and allow the extension startup + or alarm wake-up to reconnect. A sleeping extension wakes on a 30-second + alarm, so the command waits up to 35 seconds. Reload the unpacked extension + only if that loop does not recover. +- Incompatible extension protocol: update either the extension or npm package; + exact extension and relay release versions do not need to match. +- Competing browser/profile connections: the active browser is preserved and + additional connections are rejected. Use one browser/profile per relay; + repeatedly creating sessions or resetting tabs does not switch browsers. +- Stale relay build: inspect `doctor`, then coordinate an explicit + `opencode-browser relay restart`. It requires an exact managed instance and + safe shutdown protocol 2. Legacy relays need a one-time coordinated manual + stop; foreground/source or newer relays are never force-killed or downgraded. + MCP observational tools remain available on a mismatch. +- Unexpected restart: inspect private endpoint-scoped + `~/.opencode-browser/relays//lifecycle.jsonl` for requester/build/instance + metadata. Preparing or selecting a development candidate must not restart the + daemon. Use isolated `runtime:prepare` / `runtime:select`, not a live checkout + link, when developing OpenCode Browser itself. +- `Target not found`: attach the intended tab, then select or adopt it using a + unique URL substring or explicit index. +- All targets disappeared: dismissing Chromium's debugging banner detaches every + tab. Ask the user to click the toolbar button on it again. +- Relay restarted: named sessions reclaim exact targets, but JavaScript `state` + and snapshot refs reset. Continue after the warning. +- Reset/delete after an extension update may wait briefly for target + re-announcement; if the old relay-owned target is absent from the completed + inventory, OpenCode Browser forgets the dead identity without closing a + guessed tab. +- Repeated execution-context errors: run one short follow-up so OpenCode Browser + can health-check the page. A live page is kept: OpenCode Browser reconnects and + re-resolves the same tab once, then fails with a `session-page/*-unresponsive` + diagnosis if the page still does not answer. Blank or unknown URLs are preserved: + they can contain unsaved content. Only a crashed or + `chrome-error://` relay-owned page is closed and recreated. It never replaces + an adopted user tab. Main-frame navigation clears an earlier crash diagnosis; + child-frame navigation does not. When a page stays unresponsive (bot-protected sites can + stall the main world for automation while rendering normally for the human), + open a fresh tab with `context.newPage()` or hand the tab to the user. +- Handoff ends with "page execution context did not become available": the user + finished; only OpenCode Browser's view of the tab is stale. Run a short + follow-up execute so the page is re-checked instead of assuming it was lost. +- Fill timeout on login fields: inspect first, then try `fillInput` after + confirming the selector or locator resolves. String selectors search open + shadow roots recursively; closed shadow roots remain unavailable. +- Click blocked by a verified dialog backdrop: inspect the exact target and + blocker first. If the target is the approved action and Playwright actionability + alone is stale, dispatch `await locator.evaluate((element) => element.click())`, + then verify the result. Do not make dispatched clicks the default. +- Hidden checkbox/radio input: click its visible associated label or wrapper, + then verify `isChecked()`. Do not force-click an invisible input or infer an + arbitrary ancestor. +- Download wait fails: use fetch plus `fs`; extension-backed Playwright cannot + retain a native download artifact. +- Hover on an infinitely animated target: Playwright may never consider the + element stable. Read its current `getBoundingClientRect()` and use + `page.mouse.move()` when coordinate input is appropriate. +- Chromium-protected pages such as the Chrome Web Store developer dashboard may + detach `chrome.debugger`. Do not retry or bypass that boundary; open the page + for manual operation. + +For deeper relay diagnosis, restart with `OPENCODE_BROWSER_DEBUG=1`. Debug traces +must never include expressions, arguments, results, headers, cookies, or form +values. + +Whenever OpenCode Browser fails, wedges, replaces a page/session, or behaves +unexpectedly, create or update a `opencode-browser` project todo with the Browser +Control version, safe session/page context, exact error, deterministic +reproduction, expected versus actual behavior, and recovery attempted. Never +include credentials, form values, or private account data. diff --git a/packages/browser-extension/cli/src/aria-snapshot.ts b/packages/browser-extension/cli/src/aria-snapshot.ts new file mode 100644 index 00000000000..d4d89c962ca --- /dev/null +++ b/packages/browser-extension/cli/src/aria-snapshot.ts @@ -0,0 +1,224 @@ +import { selectors, type BrowserContext, type Frame, type Locator, type Page } from "patchright-core" +import { runtimeFailureKind } from "./runtime-diagnostics.ts" + +const redactionCleanupErrorMessage = "OpenCode Browser could not confirm ARIA snapshot value-redaction cleanup" +// Keep the engine as source text so bundlers cannot inject Node-only helpers into the browser function. +const redactionSelectorSource = `({ + query(root, body) { + const separator = body.indexOf("_") + const action = body.slice(0, separator) + const token = body.slice(separator + 1) + const stateKey = "__opencodeBrowserAriaRedactionState__" + let state = globalThis[stateKey] + + if (action === "on") { + if (!state) { + state = { + tokens: new Set(), + editableNameAttributes: new Set(["alt", "aria-description", "aria-describedby", "aria-label", "aria-labelledby", "aria-placeholder", "placeholder", "title"]), + nonTextInputTypes: new Set(["button", "checkbox", "file", "hidden", "image", "radio", "reset", "submit"]), + valueAttributes: new Set(["aria-valuenow", "aria-valuetext", "value"]), + valueRoles: new Set(["meter", "progressbar", "scrollbar", "separator", "slider", "spinbutton"]), + inputValue: Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value"), + textareaValue: Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value"), + nodeValue: Object.getOwnPropertyDescriptor(Node.prototype, "nodeValue"), + textContent: Object.getOwnPropertyDescriptor(Node.prototype, "textContent"), + innerText: Object.getOwnPropertyDescriptor(HTMLElement.prototype, "innerText"), + getAttribute: Object.getOwnPropertyDescriptor(Element.prototype, "getAttribute"), + } + globalThis[stateKey] = state + const getAttribute = (element, name) => state.getAttribute.value.call(element, name) + const explicitEditableState = (element) => { + const value = getAttribute(element, "contenteditable") + if (value === null) return undefined + const normalized = value.trim().toLowerCase() + if (normalized === "false") return false + return normalized === "" || normalized === "true" || normalized === "plaintext-only" ? true : undefined + } + const composedParent = (node) => { + if (node.parentNode) return node.parentNode + const treeRoot = node.getRootNode?.() + return treeRoot instanceof ShadowRoot ? treeRoot.host : null + } + const isInEditableSubtree = (node) => { + let current = node.nodeType === Node.TEXT_NODE ? node.parentNode : node + while (current) { + if (current instanceof Element) { + const explicit = explicitEditableState(current) + if (explicit !== undefined) return explicit + if (current instanceof HTMLElement && current.isContentEditable) return true + } + current = composedParent(current) + } + return false + } + const isEditableDescendant = (element) => explicitEditableState(element) !== true && isInEditableSubtree(element) + const isNativeTextControl = (element) => element instanceof HTMLTextAreaElement + || (element instanceof HTMLInputElement && !state.nonTextInputTypes.has(element.type)) + const isValueRole = (element) => { + const role = getAttribute(element, "role") + return role !== null && role.trim().toLowerCase().split(/\\s+/).some((candidate) => state.valueRoles.has(candidate)) + } + const hasRedactedText = (node) => isInEditableSubtree(node) + || (node.nodeType === Node.TEXT_NODE && node.parentElement && isNativeTextControl(node.parentElement)) + Object.defineProperty(HTMLInputElement.prototype, "value", { + ...state.inputValue, + get() { + return isNativeTextControl(this) ? "" : state.inputValue.get.call(this) + }, + }) + Object.defineProperty(HTMLTextAreaElement.prototype, "value", { ...state.textareaValue, get() { return "" } }) + Object.defineProperty(Node.prototype, "nodeValue", { + ...state.nodeValue, + get() { + return this.nodeType === Node.TEXT_NODE && hasRedactedText(this) + ? "" + : state.nodeValue.get.call(this) + }, + }) + Object.defineProperty(Node.prototype, "textContent", { + ...state.textContent, + get() { + return (this instanceof Element && isNativeTextControl(this)) || hasRedactedText(this) + ? "" + : state.textContent.get.call(this) + }, + }) + Object.defineProperty(HTMLElement.prototype, "innerText", { + ...state.innerText, + get() { + return isNativeTextControl(this) || isInEditableSubtree(this) ? "" : state.innerText.get.call(this) + }, + }) + Object.defineProperty(Element.prototype, "getAttribute", { + ...state.getAttribute, + value(name) { + const attribute = String(name).toLowerCase() + if (state.valueAttributes.has(attribute) + && (isNativeTextControl(this) || isValueRole(this) || isInEditableSubtree(this))) return null + if (state.editableNameAttributes.has(attribute) && isEditableDescendant(this)) return null + return state.getAttribute.value.call(this, name) + }, + }) + } + state.tokens.add(token) + } else if (action === "off" && state) { + state.tokens.delete(token) + if (state.tokens.size === 0) { + Object.defineProperty(HTMLInputElement.prototype, "value", state.inputValue) + Object.defineProperty(HTMLTextAreaElement.prototype, "value", state.textareaValue) + Object.defineProperty(Node.prototype, "nodeValue", state.nodeValue) + Object.defineProperty(Node.prototype, "textContent", state.textContent) + Object.defineProperty(HTMLElement.prototype, "innerText", state.innerText) + Object.defineProperty(Element.prototype, "getAttribute", state.getAttribute) + delete globalThis[stateKey] + } + } + + return root instanceof Element ? root : document.documentElement + }, + queryAll(root, body) { + return [this.query(root, body)] + }, +})` + +const redactionModuleId = globalThis.crypto.randomUUID().replaceAll("-", "") +let nextRedactionSelector = 0 +let nextRedactionToken = 0 +const contextSelectors = new WeakMap>() +const pageCleanup = new WeakMap + queue: Promise +}>() + +export async function ariaSnapshotWithoutTextControlValues( + locator: Locator, + options: { readonly timeout: number }, +): Promise { + const page = locator.page() + const redactionSelectorName = await selectorForContext(page.context()) + const token = `${redactionModuleId}${++nextRedactionToken}` + const handle = await locator.elementHandle({ timeout: options.timeout }) + if (!handle) throw new Error("ARIA snapshot target did not resolve to an element") + const frame = await handle.ownerFrame().finally(() => handle.dispose()) + if (!frame) throw new Error("ARIA snapshot target is not attached to a frame") + let snapshot: string | undefined + let captureFailed = false + let captureError: unknown + try { + snapshot = await locator + .locator(`${redactionSelectorName}=on_${token}`) + .ariaSnapshot(options) + } catch (error) { + captureFailed = true + captureError = error + } + + try { + await cleanupRedaction(page, frame, redactionSelectorName, token) + } catch (cleanupError) { + if (captureFailed) { + const cleanupReasons = cleanupError instanceof AggregateError ? cleanupError.errors : [cleanupError] + throw new AggregateError([captureError, ...cleanupReasons], redactionCleanupErrorMessage) + } + throw cleanupError + } + + if (captureFailed) throw captureError + return snapshot! +} + +export async function registerAriaSnapshotSelector(context: BrowserContext): Promise { + await selectorForContext(context) +} + +async function selectorForContext(context: BrowserContext): Promise { + const existing = contextSelectors.get(context) + if (existing) return existing + + const name = `bcariaredact${redactionModuleId}${++nextRedactionSelector}` + const registration = selectors.register( + name, + { content: redactionSelectorSource }, + { contentScript: true }, + ).then(() => name, (error) => { + contextSelectors.delete(context) + throw error + }) + contextSelectors.set(context, registration) + return registration +} + +async function cleanupRedaction(page: Page, frame: Frame, redactionSelectorName: string, token: string): Promise { + let state = pageCleanup.get(page) + if (!state) { + state = { pendingTokens: new Map(), queue: Promise.resolve() } + pageCleanup.set(page, state) + } + state.pendingTokens.set(token, { frame, selectorName: redactionSelectorName }) + + const cleanup = state.queue.then(async () => { + const pending = [...state.pendingTokens] + const results = await Promise.allSettled(pending.map(async ([pendingToken, target]) => { + await target.frame.locator(`${target.selectorName}=off_${pendingToken}`).waitFor({ state: "attached", timeout: 1_000 }) + })) + const failures: unknown[] = [] + for (let index = 0; index < results.length; index++) { + const result = results[index]! + const pendingToken = pending[index]![0] + if (result.status === "fulfilled" || redactionContextIsGone(result.reason)) { + state.pendingTokens.delete(pendingToken) + } else { + failures.push(result.reason) + } + } + if (failures.length > 0) throw new AggregateError(failures, redactionCleanupErrorMessage) + }) + state.queue = cleanup.catch(() => {}) + await cleanup +} + +function redactionContextIsGone(cause: unknown): boolean { + const kind = runtimeFailureKind(cause) + return kind === "context-destroyed" || kind === "context-missing" || kind === "target-closed" +} diff --git a/packages/browser-extension/cli/src/auth-profile.ts b/packages/browser-extension/cli/src/auth-profile.ts new file mode 100644 index 00000000000..c7b0bd5b80a --- /dev/null +++ b/packages/browser-extension/cli/src/auth-profile.ts @@ -0,0 +1,373 @@ +import { dataRoot } from "./paths.ts" +import { Effect, Schema, Semaphore } from "effect" +import { spawn } from "node:child_process" +import fs from "node:fs/promises" +import os from "node:os" +import path from "node:path" +import { terminateChildProcess } from "./child-process.ts" +import { isNodeError, writeJsonFileAtomically } from "./fs-durability.ts" +import { redactKnownValues, type CredentialSlot } from "./network-redaction.ts" + +const StoredCredentialSlot = Schema.Struct({ + ref: Schema.String.check(Schema.isPattern(/^BC_SECRET_[1-9][0-9]*$/)), + value: Schema.String, + sources: Schema.Array(Schema.String), + expiresAt: Schema.optionalKey(Schema.String), +}) + +const StoredAuthProfile = Schema.Struct({ + version: Schema.Literal(1), + name: Schema.String, + createdAt: Schema.String, + updatedAt: Schema.String, + slots: Schema.Array(StoredCredentialSlot), +}).check(Schema.makeFilter((profile) => { + const refs = profile.slots.map((slot) => slot.ref) + if (new Set(refs).size !== refs.length) return "Auth profile refs must be unique" + const sources = profile.slots.flatMap((slot) => slot.sources) + return new Set(sources).size === sources.length ? undefined : "Auth profile sources must be unique" +})) + +interface AuthProfile extends Schema.Schema.Type {} + +export type AuthProfileSummary = { + readonly name: string + readonly createdAt: string + readonly updatedAt: string + readonly slotCount: number + readonly slots: readonly { + readonly ref: string + readonly sources: readonly string[] + readonly expiresAt?: string + readonly expired: boolean + }[] +} + +export type AuthRunResult = { + readonly exitCode: number + readonly signal: NodeJS.Signals | null + readonly stdout: string + readonly stderr: string + readonly stdoutTruncated: boolean + readonly stderrTruncated: boolean + readonly durationMs: number +} + +export interface AuthProfileOptions { + readonly baseDir?: string +} + +export interface AuthRunOptions extends AuthProfileOptions { + readonly name: string + readonly command: string + readonly args?: readonly string[] + readonly cwd?: string + readonly timeoutMs?: number + readonly maxOutputBytes?: number +} + +export class AuthProfileError extends Schema.TaggedError()( + "AuthProfile.Error", + { + message: Schema.String, + operation: Schema.String, + reason: Schema.Literals(["invalid-name", "not-found", "read-failed", "invalid-json", "invalid-profile", "write-failed", "run-failed"]), + cause: Schema.optionalKey(Schema.Defect()), + }, +) {} + +const defaultBaseDir = (): string => path.join(dataRoot(), "secrets") +const writeLock = Semaphore.makeUnsafe(1) +const profileLockTimeoutMs = 30_000 +const staleProfileLockMs = 60_000 +const maximumRunOutputBytes = 10_000_000 +const maximumTimeoutMs = 2_147_483_647 + +export const read = Effect.fn("AuthProfile.read")(function* (name: string, options: { readonly baseDir?: string } = {}) { + const filePath = yield* profilePath(options.baseDir ?? defaultBaseDir(), name) + const text = yield* Effect.tryPromise({ + try: () => fs.readFile(filePath, "utf8"), + catch: (cause) => isNodeError(cause) && cause.code === "ENOENT" + ? new AuthProfileError({ message: `Auth profile not found: ${name}`, operation: "read", reason: "not-found", cause }) + : new AuthProfileError({ message: `Could not read auth profile: ${name}`, operation: "read", reason: "read-failed", cause }), + }) + return yield* Schema.decodeUnknownEffect(StoredAuthProfile)(yield* Effect.try({ + try: () => JSON.parse(text), + catch: (cause) => new AuthProfileError({ message: `Auth profile is not valid JSON: ${name}`, operation: "read", reason: "invalid-json", cause }), + })).pipe( + Effect.mapError((cause) => cause instanceof AuthProfileError + ? cause + : new AuthProfileError({ message: `Auth profile has an invalid shape: ${name}`, operation: "read", reason: "invalid-profile", cause })), + ) +}) + +export const readOptional = Effect.fn("AuthProfile.readOptional")(function* (name: string, options: { readonly baseDir?: string } = {}) { + return yield* read(name, options).pipe( + Effect.catchIf((error) => error.reason === "not-found", () => Effect.succeed(undefined)), + ) +}) + +export function withLock( + name: string, + options: { readonly baseDir?: string }, + effect: Effect.Effect, +): Effect.Effect { + const baseDir = options.baseDir ?? defaultBaseDir() + const acquire = Effect.gen(function* () { + const filePath = yield* profilePath(baseDir, name) + const lockPath = `${filePath}.lock` + yield* Effect.tryPromise({ + try: async () => { + await fs.mkdir(baseDir, { recursive: true, mode: 0o700 }) + await fs.chmod(baseDir, 0o700) + const deadline = Date.now() + profileLockTimeoutMs + while (true) { + try { + const handle = await fs.open(lockPath, "wx", 0o600) + let written = false + try { + await handle.writeFile(`${process.pid}\n`) + written = true + } finally { + await handle.close() + if (!written) await fs.unlink(lockPath).catch(() => {}) + } + return + } catch (cause) { + if (!isNodeError(cause) || cause.code !== "EEXIST") throw cause + const stat = await fs.stat(lockPath).catch(() => undefined) + if (stat && Date.now() - stat.mtimeMs > staleProfileLockMs) { + await fs.unlink(lockPath).catch(() => {}) + continue + } + if (Date.now() >= deadline) throw new Error(`Timed out waiting for auth profile lock: ${name}`) + await new Promise((resolve) => setTimeout(resolve, 25)) + } + } + }, + catch: (cause) => new AuthProfileError({ message: `Could not lock auth profile: ${name}`, operation: "lock", reason: "write-failed", cause }), + }) + return lockPath + }) + return Effect.acquireUseRelease( + acquire, + () => effect, + (lockPath) => Effect.tryPromise({ + try: () => fs.unlink(lockPath).catch(() => {}).then(() => {}), + catch: (cause) => new AuthProfileError({ message: `Could not release auth profile lock: ${name}`, operation: "lock", reason: "write-failed", cause }), + }), + ) +} + +const writeProfile = Effect.fnUntraced(function* (options: { + readonly name: string + readonly slots: readonly CredentialSlot[] + readonly baseDir?: string +}) { + const baseDir = options.baseDir ?? defaultBaseDir() + const filePath = yield* profilePath(baseDir, options.name) + const existing = yield* readOptional(options.name, { baseDir }) + const now = new Date().toISOString() + const profile: AuthProfile = { + version: 1, + name: options.name, + createdAt: existing?.createdAt ?? now, + updatedAt: now, + slots: options.slots.map((slot) => ({ + ref: slot.ref, + value: slot.value, + sources: [...slot.sources], + ...(slot.expiresAt ? { expiresAt: slot.expiresAt } : {}), + })), + } + yield* Schema.decodeUnknownEffect(StoredAuthProfile)(profile).pipe( + Effect.mapError((cause) => new AuthProfileError({ message: `Auth profile has an invalid shape: ${options.name}`, operation: "write", reason: "invalid-profile", cause })), + ) + if (existing && sameSlots(existing.slots, profile.slots)) return summary(existing) + yield* Effect.tryPromise({ + try: () => writeJsonFileAtomically(filePath, profile, { dirMode: 0o700 }), + catch: (cause) => new AuthProfileError({ message: `Could not write auth profile: ${options.name}`, operation: "write", reason: "write-failed", cause }), + }) + return summary(profile) +}) + +export const write = Effect.fn("AuthProfile.write")(function* (options: { + readonly name: string + readonly slots: readonly CredentialSlot[] + readonly baseDir?: string +}) { + return yield* writeLock.withPermit(writeProfile(options)) +}) + +export const status = Effect.fn("AuthProfile.status")(function* (name: string, options: AuthProfileOptions = {}) { + return summary(yield* read(name, options)) +}) + +export const run = Effect.fn("AuthProfile.run")(function* (options: AuthRunOptions) { + if (!options.command.trim()) { + return yield* new AuthProfileError({ message: "Auth command must not be empty", operation: "run", reason: "run-failed" }) + } + const timeoutMs = options.timeoutMs ?? 120_000 + if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > maximumTimeoutMs) { + return yield* new AuthProfileError({ message: `Auth command timeout must be an integer between 1 and ${maximumTimeoutMs} milliseconds`, operation: "run", reason: "run-failed" }) + } + const maxOutputBytes = options.maxOutputBytes ?? 1_000_000 + if (!Number.isSafeInteger(maxOutputBytes) || maxOutputBytes < 0 || maxOutputBytes > maximumRunOutputBytes) { + return yield* new AuthProfileError({ message: `Auth command output limit must be an integer between 0 and ${maximumRunOutputBytes} bytes`, operation: "run", reason: "run-failed" }) + } + const profile = yield* read(options.name, { ...(options.baseDir ? { baseDir: options.baseDir } : {}) }) + const startedAt = Date.now() + const maxSecretBytes = profile.slots.reduce((max, slot) => Math.max(max, Buffer.byteLength(slot.value)), 0) + const result = yield* runChild({ + command: options.command, + args: options.args ?? [], + ...(options.cwd ? { cwd: options.cwd } : {}), + timeoutMs, + maxOutputBytes: maxOutputBytes + maxSecretBytes, + env: Object.fromEntries(profile.slots.map((slot) => [slot.ref, slot.value])), + }).pipe( + Effect.mapError((cause) => new AuthProfileError({ message: `Could not run command with auth profile ${options.name}`, operation: "run", reason: "run-failed", cause })), + ) + const stdout = redactOutput(result.stdout, profile.slots, maxOutputBytes) + const stderr = redactOutput(result.stderr, profile.slots, maxOutputBytes) + return { + ...result, + stdout: stdout.text, + stderr: stderr.text, + stdoutTruncated: result.stdoutTruncated || stdout.truncated, + stderrTruncated: result.stderrTruncated || stderr.truncated, + durationMs: Date.now() - startedAt, + } satisfies AuthRunResult +}) + +function summary(profile: AuthProfile): AuthProfileSummary { + const now = Date.now() + return { + name: profile.name, + createdAt: profile.createdAt, + updatedAt: profile.updatedAt, + slotCount: profile.slots.length, + slots: profile.slots.map((slot) => ({ + ref: slot.ref, + sources: [...slot.sources], + ...(slot.expiresAt ? { expiresAt: slot.expiresAt } : {}), + expired: slot.expiresAt ? Date.parse(slot.expiresAt) <= now : false, + })), + } +} + +function profilePath(baseDir: string, name: string): Effect.Effect { + return /^[a-z0-9][a-z0-9._-]{0,63}$/i.test(name) + ? Effect.succeed(path.join(baseDir, `${name}.json`)) + : Effect.fail(new AuthProfileError({ message: `Invalid auth profile name: ${name}`, operation: "path", reason: "invalid-name" })) +} + +function sameSlots(left: readonly CredentialSlot[], right: readonly CredentialSlot[]): boolean { + return JSON.stringify(left) === JSON.stringify(right) +} + +function redactOutput(text: string, slots: readonly CredentialSlot[], maxBytes: number): { readonly text: string; readonly truncated: boolean } { + const bytes = Buffer.from(text) + let cutoff = Math.min(bytes.length, maxBytes) + let changed = true + while (changed) { + changed = false + for (const slot of slots) { + if (!slot.value) continue + const secret = Buffer.from(slot.value) + let start = bytes.indexOf(secret) + while (start >= 0 && start < cutoff) { + if (start + secret.length > cutoff) { + cutoff = start + changed = true + break + } + start = bytes.indexOf(secret, start + secret.length) + } + } + } + return { + text: redactKnownValues(bytes.subarray(0, cutoff).toString("utf8"), slots), + truncated: cutoff < bytes.length, + } +} + +function runChild(options: { + readonly command: string + readonly args: readonly string[] + readonly cwd?: string + readonly timeoutMs: number + readonly maxOutputBytes: number + readonly env: Readonly> +}): Effect.Effect, Error> { + return Effect.callback((resume) => { + const child = spawn(options.command, [...options.args], { + ...(options.cwd ? { cwd: options.cwd } : {}), + env: childEnvironment(options.env), + detached: process.platform !== "win32", + stdio: ["ignore", "pipe", "pipe"], + }) + const stdout: Buffer[] = [] + const stderr: Buffer[] = [] + let stdoutBytes = 0 + let stderrBytes = 0 + let stdoutTruncated = false + let stderrTruncated = false + const append = (chunks: Buffer[], chunk: Buffer, currentBytes: number): number => { + const remaining = options.maxOutputBytes - currentBytes + if (remaining <= 0) return currentBytes + chunks.push(chunk.subarray(0, remaining)) + return currentBytes + Math.min(chunk.length, remaining) + } + child.stdout.on("data", (chunk: Buffer) => { + const next = append(stdout, chunk, stdoutBytes) + stdoutTruncated ||= next - stdoutBytes < chunk.length + stdoutBytes = next + }) + child.stderr.on("data", (chunk: Buffer) => { + const next = append(stderr, chunk, stderrBytes) + stderrTruncated ||= next - stderrBytes < chunk.length + stderrBytes = next + }) + let closed = false + let settled = false + let closePromiseResolve: (() => void) | undefined + const closePromise = new Promise((resolve) => { + closePromiseResolve = resolve + }) + const timeout = setTimeout(() => { + void terminateChildProcess({ child, exit: closePromise, graceMs: 1_000, isExited: () => closed }) + }, options.timeoutMs) + child.once("error", (cause) => { + clearTimeout(timeout) + closed = true + closePromiseResolve?.() + if (settled) return + settled = true + resume(Effect.fail(cause)) + }) + child.once("close", (code, signal) => { + clearTimeout(timeout) + closed = true + closePromiseResolve?.() + if (settled) return + settled = true + resume(Effect.succeed({ + exitCode: code ?? 1, + signal, + stdout: Buffer.concat(stdout).toString("utf8"), + stderr: Buffer.concat(stderr).toString("utf8"), + stdoutTruncated, + stderrTruncated, + })) + }) + return Effect.promise(() => terminateChildProcess({ child, exit: closePromise, graceMs: 1_000, isExited: () => closed })) + }) +} + +function childEnvironment(profile: Readonly>): NodeJS.ProcessEnv { + const inherited = Object.fromEntries( + Object.entries(process.env).filter(([name]) => !/^BC_SECRET_[1-9][0-9]*$/.test(name)), + ) + return { ...inherited, ...profile } +} diff --git a/packages/browser-extension/cli/src/authenticated-origin.ts b/packages/browser-extension/cli/src/authenticated-origin.ts new file mode 100644 index 00000000000..ef7fba6941d --- /dev/null +++ b/packages/browser-extension/cli/src/authenticated-origin.ts @@ -0,0 +1,254 @@ +import { Effect, Match, Schema } from "effect" +import type { Page } from "patchright-core" +import { + AuthenticatedJsonOutcome, + type AuthenticatedJsonMethod, + type AuthenticatedJsonRequest, +} from "./relay-schema.ts" + +const defaultTimeoutMs = 30_000 +const defaultMaxResponseBytes = 2_000_000 + +export class AuthenticatedOriginError extends Schema.TaggedError()( + "AuthenticatedOrigin.Error", + { + message: Schema.String, + reason: Schema.Literals(["invalid-request", "page-failed"]), + cause: Schema.optionalKey(Schema.Defect()), + }, +) {} + +type RequestOptions = Omit + +type PageRequestInput = { + readonly origin: string + readonly method: AuthenticatedJsonMethod + readonly url: string + readonly headers?: Readonly> + readonly body?: unknown + readonly timeoutMs: number + readonly maxResponseBytes: number +} + +export const requestJson = Effect.fn("AuthenticatedOrigin.requestJson")(function* ( + page: Page, + request: RequestOptions, +) { + const target = yield* Effect.try({ + try: () => { + const origin = normalizeOrigin(request.origin) + return { + origin, + requestUrl: resolveRequestUrl(origin, request.path), + startUrl: request.startUrl === undefined ? undefined : resolveStartUrl(origin, request.startUrl), + } + }, + catch: (cause) => cause instanceof AuthenticatedOriginError + ? cause + : new AuthenticatedOriginError({ + message: "Invalid authenticated origin request", + reason: "invalid-request", + cause, + }), + }) + const { origin, requestUrl, startUrl } = target + + if (pageOrigin(page.url()) !== origin && startUrl !== undefined) { + yield* Effect.tryPromise({ + try: () => page.goto(startUrl, { waitUntil: "domcontentloaded", timeout: request.timeoutMs ?? defaultTimeoutMs }), + catch: (cause) => new AuthenticatedOriginError({ + message: cause instanceof Error ? cause.message : "Navigate to authenticated origin", + reason: "page-failed", + cause, + }), + }) + } + + const actualOrigin = pageOrigin(page.url()) + if (actualOrigin !== origin) { + return AuthenticatedJsonOutcome.cases.OriginMismatch.make({ + expectedOrigin: origin, + actualOrigin, + }) + } + + const input: PageRequestInput = { + origin, + method: request.method, + url: requestUrl, + ...(request.headers === undefined ? {} : { headers: request.headers }), + ...(request.body === undefined ? {} : { body: request.body }), + timeoutMs: request.timeoutMs ?? defaultTimeoutMs, + maxResponseBytes: request.maxResponseBytes ?? defaultMaxResponseBytes, + } + + const pageResult = yield* Effect.tryPromise({ + try: () => page.evaluate(runPageRequest, input), + catch: (cause) => new AuthenticatedOriginError({ + message: cause instanceof Error ? cause.message : "Run authenticated page request", + reason: "page-failed", + cause, + }), + }).pipe(Effect.uninterruptible) + + return Match.value(pageResult).pipe( + Match.when({ kind: "OriginMismatch" }, ({ expectedOrigin, actualOrigin }) => + AuthenticatedJsonOutcome.cases.OriginMismatch.make({ expectedOrigin, actualOrigin })), + Match.when({ kind: "HttpError" }, ({ status }) => + AuthenticatedJsonOutcome.cases.HttpError.make({ status })), + Match.when({ kind: "ResponseTooLarge" }, ({ status, maxResponseBytes }) => + AuthenticatedJsonOutcome.cases.ResponseTooLarge.make({ status, maxResponseBytes })), + Match.when({ kind: "Success" }, ({ status, value }) => + AuthenticatedJsonOutcome.cases.Success.make({ status, value })), + Match.when({ kind: "InvalidJson" }, ({ status }) => + AuthenticatedJsonOutcome.cases.InvalidJson.make({ status })), + Match.when({ kind: "RequestFailed" }, ({ outcome }) => + AuthenticatedJsonOutcome.cases.RequestFailed.make({ outcome })), + Match.exhaustive, + ) +}) + +export function normalizeOrigin(value: string): string { + let url: URL + try { + url = new URL(value) + } catch (cause) { + throw new AuthenticatedOriginError({ + message: `Invalid authenticated origin: ${value}`, + reason: "invalid-request", + cause, + }) + } + if ((url.protocol !== "https:" && url.protocol !== "http:") || url.username || url.password) { + throw new AuthenticatedOriginError({ + message: `Authenticated origin must be an HTTP(S) origin without credentials: ${value}`, + reason: "invalid-request", + }) + } + if (url.pathname !== "/" || url.search || url.hash) { + throw new AuthenticatedOriginError({ + message: `Authenticated origin must not include a path, query, or fragment: ${value}`, + reason: "invalid-request", + }) + } + return url.origin +} + +function resolveRequestUrl(origin: string, path: string): string { + if (!path.startsWith("/") || path.startsWith("//")) { + throw new AuthenticatedOriginError({ + message: "Authenticated request path must start with one slash", + reason: "invalid-request", + }) + } + const url = new URL(path, origin) + if (url.origin !== origin) { + throw new AuthenticatedOriginError({ + message: `Authenticated request escaped its declared origin: ${path}`, + reason: "invalid-request", + }) + } + return url.toString() +} + +export function resolveStartUrl(origin: string, value: string): string { + const url = new URL(value, origin) + if (url.origin !== origin) { + throw new AuthenticatedOriginError({ + message: `Authenticated origin startUrl must stay on ${origin}`, + reason: "invalid-request", + }) + } + return url.toString() +} + +function pageOrigin(value: string): string { + try { + return new URL(value).origin + } catch { + return "null" + } +} + +type PageRequestResult = + | { readonly kind: "OriginMismatch"; readonly expectedOrigin: string; readonly actualOrigin: string } + | { readonly kind: "HttpError"; readonly status: number } + | { readonly kind: "ResponseTooLarge"; readonly status: number; readonly maxResponseBytes: number } + | { readonly kind: "Success"; readonly status: number; readonly value: Schema.Schema.Type } + | { readonly kind: "InvalidJson"; readonly status: number } + | { readonly kind: "RequestFailed"; readonly outcome: "not-sent" | "unknown" } + +async function runPageRequest(input: PageRequestInput): Promise { + if (window.location.origin !== input.origin) { + return { + kind: "OriginMismatch", + expectedOrigin: input.origin, + actualOrigin: window.location.origin, + } + } + + const controller = new AbortController() + const timeout = window.setTimeout(() => controller.abort(), input.timeoutMs) + let requestStarted = false + try { + const body = input.body === undefined ? undefined : JSON.stringify(input.body) + const headers: Record = { + ...(body === undefined ? {} : { "content-type": "application/json" }), + ...(input.headers ?? {}), + } + requestStarted = true + const response = await window.fetch(input.url, { + method: input.method, + credentials: "same-origin", + mode: "same-origin", + redirect: "error", + signal: controller.signal, + ...(Object.keys(headers).length > 0 ? { headers } : {}), + ...(body === undefined ? {} : { body }), + }) + + if (!response.ok) { + await response.body?.cancel().catch(() => undefined) + return { kind: "HttpError", status: response.status } + } + + const reader = response.body?.getReader() + const decoder = new TextDecoder() + let byteCount = 0 + let text = "" + if (reader) { + while (true) { + const chunk = await reader.read() + if (chunk.done) break + byteCount += chunk.value.byteLength + if (byteCount > input.maxResponseBytes) { + await reader.cancel().catch(() => undefined) + return { + kind: "ResponseTooLarge", + status: response.status, + maxResponseBytes: input.maxResponseBytes, + } + } + text += decoder.decode(chunk.value, { stream: true }) + } + text += decoder.decode() + } + + try { + return { + kind: "Success", + status: response.status, + value: text ? JSON.parse(text) : null, + } + } catch { + return { kind: "InvalidJson", status: response.status } + } + } catch { + return { + kind: "RequestFailed", + outcome: requestStarted ? "unknown" : "not-sent", + } + } finally { + window.clearTimeout(timeout) + } +} diff --git a/packages/browser-extension/cli/src/cdp-client-pool.ts b/packages/browser-extension/cli/src/cdp-client-pool.ts new file mode 100644 index 00000000000..47cbf66410e --- /dev/null +++ b/packages/browser-extension/cli/src/cdp-client-pool.ts @@ -0,0 +1,212 @@ +import { Data } from "effect" +import type { CdpEvent, JsonObject } from "./protocol.ts" +import type { ChildTarget, ConnectedTarget } from "./relay-types.ts" + +type ClientCdpSessionAlias = Data.TaggedEnum<{ + Browser: {} + Target: { readonly tabId: number; readonly targetId: string; readonly chromeSessionId?: string } +}> +export const ClientCdpSessionAlias = Data.taggedEnum() + +type AnnouncedTarget = { + readonly tabId: number + readonly targetId: string + readonly sessionId: string + readonly parentSessionId?: string +} + +type CdpClientState = { + readonly aliases: Map + readonly announcements: Map + readonly opencodeBrowserSessionId?: string + readonly kind: "raw" | "sandbox" + autoAttachParams?: JsonObject +} + +export class CdpClientPool implements Iterable { + private readonly states = new Map() + private nextAliasId = 1 + private connectionGeneration = 0 + + constructor( + private readonly send: (client: Client, event: CdpEvent) => void, + /** Observe every canonical session this client stops seeing, announced or silent. */ + private readonly retired: (client: Client, sessionId: string) => void, + ) {} + + register(client: Client, opencodeBrowserSessionId?: string, kind: "raw" | "sandbox" = "raw"): void { + if (this.states.has(client)) throw new Error("CDP client is already registered") + this.states.set(client, { + aliases: new Map(), + announcements: new Map(), + kind: opencodeBrowserSessionId ? kind : "raw", + ...(opencodeBrowserSessionId ? { opencodeBrowserSessionId } : {}), + }) + this.connectionGeneration += 1 + } + + unregister(client: Client): number | undefined { + if (!this.states.delete(client) || this.states.size !== 0) return undefined + return ++this.connectionGeneration + } + + get size(): number { + return this.states.size + } + + has(client: Client): boolean { + return this.states.has(client) + } + + [Symbol.iterator](): IterableIterator { + return this.states.keys() + } + + sessionId(client: Client): string | undefined { + return this.states.get(client)?.opencodeBrowserSessionId + } + + isSandbox(client: Client): boolean { + return this.states.get(client)?.kind === "sandbox" + } + + hasSession(client: Client, sessionId: string): boolean { + return this.states.get(client)?.announcements.has(sessionId) ?? false + } + + announce(client: Client, target: ConnectedTarget | ChildTarget): void { + const state = this.requireState(client) + const targetId = target.targetInfo.targetId + const existing = Array.from(state.announcements.values()).find((entry) => entry.targetId === targetId) + if (existing?.sessionId === target.sessionId) return + if (existing) this.detachSession(client, state, existing.sessionId) + this.detachSession(client, state, target.sessionId) + const parent = "parentSessionId" in target ? { parentSessionId: target.parentSessionId } : {} + state.announcements.set(target.sessionId, { tabId: target.tabId, targetId, sessionId: target.sessionId, ...parent }) + this.send(client, { + ...(parent.parentSessionId === undefined ? {} : { sessionId: parent.parentSessionId }), + method: "Target.attachedToTarget", + params: { + sessionId: target.sessionId, + targetInfo: { ...target.targetInfo, attached: true }, + waitingForDebugger: "waitingForDebugger" in target ? target.waitingForDebugger : false, + }, + }) + } + + detach(client: Client, sessionId: string): void { + const state = this.requireState(client) + if (state.aliases.delete(sessionId)) return + this.detachSession(client, state, sessionId, { notify: false }) + } + + detachTab(tabId: number, options: { readonly destroyed?: boolean } = {}): void { + for (const [client, state] of this.states) { + this.removeTargetAliases(state, (alias) => alias.tabId === tabId) + for (const announced of state.announcements.values()) { + if (announced.tabId === tabId) this.detachSession(client, state, announced.sessionId, options) + } + } + } + + detachTarget(target: ChildTarget, options: { readonly notify?: boolean } = {}): void { + for (const [client, state] of this.states) { + this.removeTargetAliases(state, (alias) => alias.targetId === target.targetInfo.targetId) + this.detachSession(client, state, target.sessionId, options) + } + } + + pruneInvisible(client: Client, canSeeTab: (tabId: number) => boolean): void { + const state = this.requireState(client) + this.removeTargetAliases(state, (alias) => !canSeeTab(alias.tabId)) + for (const announced of state.announcements.values()) { + if (!canSeeTab(announced.tabId)) this.detachSession(client, state, announced.sessionId) + } + } + + sendToViewers(rootSessionId: string, event: CdpEvent, canSeeTab: (client: Client, tabId: number) => boolean): void { + for (const [client, state] of this.states) { + const announced = state.announcements.get(rootSessionId) + if (!announced) continue + if (!canSeeTab(client, announced.tabId)) { + this.pruneInvisible(client, (tabId) => canSeeTab(client, tabId)) + continue + } + this.send(client, event) + } + } + + setAutoAttachParams(client: Client, params: JsonObject | undefined): void { + const state = this.requireState(client) + if (params === undefined) delete state.autoAttachParams + else state.autoAttachParams = params + } + + autoAttachParams(client: Client): JsonObject | undefined { + return this.states.get(client)?.autoAttachParams + } + + isCurrentIdleGeneration(generation: number): boolean { + return this.states.size === 0 && this.connectionGeneration === generation + } + + createBrowserAlias(client: Client): string { + const aliasId = this.nextAlias("browser") + this.requireState(client).aliases.set(aliasId, ClientCdpSessionAlias.Browser()) + return aliasId + } + + createTargetAlias(client: Client, target: ConnectedTarget | ChildTarget): string { + const aliasId = this.nextAlias("session") + this.requireState(client).aliases.set(aliasId, ClientCdpSessionAlias.Target({ + tabId: target.tabId, + targetId: target.targetInfo.targetId, + ...("parentSessionId" in target ? { chromeSessionId: target.sessionId } : {}), + })) + return aliasId + } + + alias(client: Client, aliasId: string): ClientCdpSessionAlias | undefined { + return this.states.get(client)?.aliases.get(aliasId) + } + + private detachSession(client: Client, state: CdpClientState, sessionId: string, options: { + readonly notify?: boolean + readonly destroyed?: boolean + } = {}): void { + const announced = state.announcements.get(sessionId) + if (!announced) return + state.announcements.delete(sessionId) + this.removeTargetAliases(state, (alias) => alias.targetId === announced.targetId) + // Descendants must disappear before their parent, including on replacement. + for (const child of state.announcements.values()) { + if (child.parentSessionId === sessionId) this.detachSession(client, state, child.sessionId, options) + } + this.retired(client, sessionId) + if (options.notify === false) return + if (options.destroyed && announced.parentSessionId === undefined) { + this.send(client, { method: "Target.targetDestroyed", params: { targetId: announced.targetId } }) + } + this.send(client, { + ...(announced.parentSessionId === undefined ? {} : { sessionId: announced.parentSessionId }), + method: "Target.detachedFromTarget", + params: { sessionId, targetId: announced.targetId }, + }) + } + + private removeTargetAliases(state: CdpClientState, matches: (alias: Data.TaggedEnum.Value) => boolean): void { + for (const [aliasId, alias] of state.aliases) { + if (ClientCdpSessionAlias.$is("Target")(alias) && matches(alias)) state.aliases.delete(aliasId) + } + } + + private nextAlias(kind: "browser" | "session"): string { + return `bc-client-${kind}-${this.nextAliasId++}` + } + + private requireState(client: Client): CdpClientState { + const state = this.states.get(client) + if (!state) throw new Error("CDP client is not registered") + return state + } +} diff --git a/packages/browser-extension/cli/src/cdp-guardrails.ts b/packages/browser-extension/cli/src/cdp-guardrails.ts new file mode 100644 index 00000000000..3055f99c3d9 --- /dev/null +++ b/packages/browser-extension/cli/src/cdp-guardrails.ts @@ -0,0 +1,44 @@ +/** + * Relay-level CDP guardrails. + * + * The relay refuses a small set of CDP methods that would destroy the user's + * real browser state (OpenCode Browser drives the user's own browser, with + * their real logins). Read-only sessions additionally refuse input-dispatching + * methods so "go look at X" tasks cannot click or type. + * + * Pure module: given a method and session context, return a rejection message + * or null. The relay turns a rejection into a normal CDP error response for + * that command id, so the calling script fails loudly without breaking the + * connection. + */ + +const alwaysBlocked = new Map([ + ["Network.clearBrowserCookies", "it would log the user out of every site in their browser"], + ["Network.clearBrowserCache", "it would clear the user's entire browser cache"], + ["Storage.clearCookies", "it would log the user out of every site in their browser"], + ["Browser.close", "it would close the user's browser"], +]) + +const readOnlyBlockedPrefixes = ["Input."] as const + +export type GuardContext = { + readonly method: string + readonly readOnly: boolean + readonly sessionId?: string | undefined +} + +/** + * Returns a human-readable rejection message when the method must be blocked, + * or null when the command may be forwarded to the browser. + */ +export function guardCdpMethod(context: GuardContext): string | null { + const reason = alwaysBlocked.get(context.method) + if (reason) { + return `OpenCode Browser blocked ${context.method}: ${reason}. This command is always blocked by the relay.` + } + if (context.readOnly && readOnlyBlockedPrefixes.some((prefix) => context.method.startsWith(prefix))) { + const session = context.sessionId ? `Session ${context.sessionId}` : "This session" + return `${session} is read-only: ${context.method} is blocked. Use a session created without --read-only to interact with pages.` + } + return null +} diff --git a/packages/browser-extension/cli/src/cdp-router.ts b/packages/browser-extension/cli/src/cdp-router.ts new file mode 100644 index 00000000000..1e652dfe6d3 --- /dev/null +++ b/packages/browser-extension/cli/src/cdp-router.ts @@ -0,0 +1,166 @@ +import { ClientCdpSessionAlias, type CdpClientPool } from "./cdp-client-pool.ts" +import { canClientSeeTarget } from "./cdp-visibility.ts" +import type { CdpRequest, TargetInfo } from "./protocol.ts" +import { getString, isRestrictedTarget } from "./relay-helpers.ts" +import type { ChildTarget, ConnectedTarget } from "./relay-types.ts" +import { shouldExposeChildTarget, type TargetRegistry } from "./target-registry.ts" + +const rootRoutableBrowserContextMethods = new Set([ + "Browser.grantPermissions", + "Browser.resetPermissions", + "Storage.getCookies", + "Storage.setCookies", + "Storage.clearCookies", +]) + +export function isRootRoutableBrowserContextMethod(method: string): boolean { + return rootRoutableBrowserContextMethods.has(method) +} + +export type CdpRoutedSession = { + readonly tabId: number + readonly rootSessionId: string + readonly chromeSessionId?: string +} + +export class CdpRouter { + constructor( + private readonly clients: CdpClientPool, + private readonly registry: TargetRegistry, + ) {} + + canSeeTarget(client: Client, target: ConnectedTarget): boolean { + return this.clients.has(client) && this.canSessionSeeTarget(this.clients.sessionId(client), target) + } + + canSessionSeeTarget(clientSessionId: string | undefined, target: ConnectedTarget): boolean { + return canClientSeeTarget({ + clientSessionId, + targetOwnerSessionId: target.opencodeBrowserSessionId, + targetOwner: target.owner, + clientHasOwnedTarget: clientSessionId !== undefined && this.registry + .listRootTargets() + .some((candidate) => candidate.opencodeBrowserSessionId === clientSessionId), + }) + } + + canSeeTab(client: Client, tabId: number): boolean { + const rootTarget = this.registry.tabTargets.get(tabId) + return rootTarget ? this.canSeeTarget(client, rootTarget) : false + } + + preferredRoot(client: Client, browserContextId?: string): ConnectedTarget | undefined { + const clientSessionId = this.clients.sessionId(client) + const candidates = this.registry.listRootTargets().filter((target) => { + if (target.crashed) return false + if (browserContextId !== undefined && target.targetInfo.browserContextId !== browserContextId) return false + return clientSessionId !== undefined + ? target.opencodeBrowserSessionId === clientSessionId + : this.canSeeTarget(client, target) + }) + if (candidates.length === 0) return undefined + if (clientSessionId !== undefined || candidates.length === 1) return candidates[0] + const contexts = new Set(candidates.map((target) => target.targetInfo.browserContextId)) + // CDP omits browserContextId for the singleton default context. Matching + // absence is therefore a validated default-context identity, not a guess. + if (contexts.size === 1) { + return candidates[0] + } + return undefined + } + + isBrowserAlias(client: Client, sessionId: string): boolean { + return ClientCdpSessionAlias.$is("Browser")(this.clients.alias(client, sessionId)) + } + + visibleRoots(client: Client): ConnectedTarget[] { + return this.registry.listRootTargets().filter((target) => this.canSeeTarget(client, target)) + } + + rootForSession(client: Client, sessionId: string): ConnectedTarget | undefined { + const target = this.registry.targets.get(sessionId) + return target && this.canSeeTarget(client, target) ? target : undefined + } + + targetForAttach(client: Client, targetId: string): ConnectedTarget | ChildTarget | undefined { + const root = this.registry.targetsByTargetId.get(targetId) + if (root) return this.canSeeTarget(client, root) ? root : undefined + const child = this.registry.childTargetsByTargetId.get(targetId) + return child && this.canSeeTab(client, child.tabId) ? child : undefined + } + + targetInfo(client: Client, options: { + readonly targetId?: string + readonly sessionId?: string + }): ConnectedTarget | ChildTarget | undefined { + const alias = options.sessionId ? this.clients.alias(client, options.sessionId) : undefined + const aliasedTargetId = ClientCdpSessionAlias.$is("Target")(alias) ? alias.targetId : undefined + const target = (options.targetId + ? this.registry.targetsByTargetId.get(options.targetId) ?? this.registry.childTargetsByTargetId.get(options.targetId) + : undefined) ?? + (aliasedTargetId + ? this.registry.targetsByTargetId.get(aliasedTargetId) ?? this.registry.childTargetsByTargetId.get(aliasedTargetId) + : undefined) ?? + (options.sessionId + ? this.registry.targets.get(options.sessionId) ?? this.registry.childTargets.get(options.sessionId) + : undefined) + if (!target) return undefined + return "owner" in target + ? this.canSeeTarget(client, target) ? target : undefined + : this.canSeeTab(client, target.tabId) ? target : undefined + } + + session(client: Client, requestedSessionId: string): CdpRoutedSession | undefined { + const sessionAlias = this.clients.alias(client, requestedSessionId) + if (ClientCdpSessionAlias.$is("Browser")(sessionAlias)) return undefined + const alias = ClientCdpSessionAlias.$is("Target")(sessionAlias) ? sessionAlias : undefined + const target = alias + ? this.registry.targetsByTargetId.get(alias.targetId) ?? this.registry.childTargetsByTargetId.get(alias.targetId) + : this.registry.targets.get(requestedSessionId) ?? this.registry.childTargets.get(requestedSessionId) + if (!target || !this.canSeeTab(client, target.tabId)) return undefined + const rootSessionId = this.registry.tabTargets.get(target.tabId)?.sessionId + if (!rootSessionId) return undefined + const expectedChromeSessionId = "owner" in target ? undefined : target.sessionId + if (alias && (alias.tabId !== target.tabId || alias.chromeSessionId !== expectedChromeSessionId)) return undefined + return { + tabId: target.tabId, + rootSessionId, + ...(expectedChromeSessionId ? { chromeSessionId: expectedChromeSessionId } : {}), + } + } + + resolveCommandRoute(client: Client, message: CdpRequest): CdpRoutedSession { + const browserAlias = message.sessionId !== undefined && this.isBrowserAlias(client, message.sessionId) + const rootRoutable = isRootRoutableBrowserContextMethod(message.method) && (!message.sessionId || browserAlias) + const requestedBrowserContextId = getString(message.params, "browserContextId") + const preferredRoot = rootRoutable ? this.preferredRoot(client, requestedBrowserContextId) : undefined + const route = rootRoutable && preferredRoot + ? { tabId: preferredRoot.tabId, rootSessionId: preferredRoot.sessionId } + : message.sessionId + ? this.session(client, message.sessionId) + : undefined + if (route) return route + throw new Error(rootRoutable + ? requestedBrowserContextId !== undefined + ? `A healthy visible root target in browser context ${requestedBrowserContextId} is required for ${message.method}` + : this.clients.sessionId(client) === undefined + ? `Exactly one visible browser context is required for ${message.method}` + : `A healthy session-owned root target is required for ${message.method}` + : message.sessionId + ? `Unknown CDP session ${message.sessionId} for ${message.method}` + : `CDP sessionId is required for ${message.method}`) + } + + reconcileClient(client: Client): void { + this.clients.pruneInvisible(client, (tabId) => this.canSeeTab(client, tabId)) + } + + visibleTargetInfos(client: Client): TargetInfo[] { + return this.registry.allTargetInfos({ + isRestrictedTarget, + isVisibleTarget: (target) => { + return this.canSeeTab(client, target.tabId) && ("owner" in target || shouldExposeChildTarget(target)) + }, + }) + } +} diff --git a/packages/browser-extension/cli/src/cdp-runtime.ts b/packages/browser-extension/cli/src/cdp-runtime.ts new file mode 100644 index 00000000000..0677cd5f6f2 --- /dev/null +++ b/packages/browser-extension/cli/src/cdp-runtime.ts @@ -0,0 +1,299 @@ +import { Deferred, Effect, Fiber, Predicate } from "effect" +import type { CdpRoutedSession } from "./cdp-router.ts" +import type { CdpEvent, JsonObject } from "./protocol.ts" +import { getNumber, getObject, getString } from "./relay-helpers.ts" +import { boundedToken, runtimeFailureKind } from "./runtime-diagnostics.ts" +import type { TargetRegistry } from "./target-registry.ts" + +const maxCachedContexts = 512 + +type Waiter = { + readonly sessionId: string + readonly ready: Deferred.Deferred + readonly nativeReady: (event: CdpEvent) => boolean + /** Installed once the enable command succeeds. */ + replay?: () => boolean +} + +type Contexts = Map +/** `contexts` is undefined once the cache overflowed and can no longer prove completeness. */ +type ContextCache = { readonly current: () => boolean; contexts: Contexts | undefined } +type Requester = { + readonly current: () => boolean + readonly delivered: Map + frameId?: string +} + +const routeSessionId = (route: CdpRoutedSession) => route.chromeSessionId ?? route.rootSessionId +const disableKey = (tabId: number, chromeSessionId?: string) => `${tabId}:${chromeSessionId ?? "root"}` +const contextAux = (event: CdpEvent) => getObject(getObject(event.params?.context)?.auxData) + +export class CdpRuntime { + private readonly waiters = new Set() + private readonly contexts = new Map() + private readonly requesters = new WeakMap>() + private readonly disabling = new Map() + + constructor(private readonly options: { + readonly registry: TargetRegistry + readonly generation: () => number + readonly send: (command: { readonly tabId: number; readonly sessionId?: string; readonly method: string; readonly params: JsonObject }) => Effect.Effect + readonly sendEvent: (client: Client, event: CdpEvent) => void + readonly trace?: (message: string) => void + }) {} + + notify(event: CdpEvent): void { + if (event.sessionId) this.recordContextEvent(event.sessionId, event) + if (event.method !== "Runtime.executionContextCreated" || contextAux(event)?.isDefault !== true) return + // Replay missing sibling contexts before waking the native waiter: resolving + // its Deferred can synchronously retire the waiter's pending replay. + for (const waiter of this.waiters) this.settle(waiter) + for (const waiter of this.waiters) { + if (waiter.sessionId === event.sessionId && waiter.nativeReady(event)) Deferred.doneUnsafe(waiter.ready, Effect.succeed(true)) + } + } + + /** Observe the exact events actually sent to this canonical client. Aliases never enter here. */ + deliver(client: Client, event: CdpEvent): void { + const requester = event.sessionId ? this.requesters.get(client)?.get(event.sessionId) : undefined + const active = requester?.current() ? requester : undefined + const context = getObject(event.params?.context) + const id = getNumber(context, "id") + const destroyedId = getNumber(event.params, "executionContextId") + if (event.method === "Runtime.executionContextsCleared") active?.delivered.clear() + if (event.method === "Runtime.executionContextDestroyed" && destroyedId !== undefined) { + active?.delivered.delete(destroyedId) + } + if (event.method === "Runtime.executionContextCreated" && active?.frameId !== undefined && id !== undefined) { + const unique = getString(context, "uniqueId") + if (active.delivered.has(id) && active.delivered.get(id) === unique) return + active.delivered.set(id, unique) + } + this.options.sendEvent(client, event) + } + + /** Construct at request admission; invoke with the result only after its successful response is sent. */ + frameTreeResponse(client: Client, route: CdpRoutedSession, canContinue: () => boolean): (result: unknown) => void { + const requester = this.requester(client, route, canContinue) + return (result) => { + const frameId = getString(getObject(getObject(getObject(result)?.frameTree)?.frame), "id") + if (!Predicate.isString(frameId) || !requester.current()) return + requester.frameId = frameId + for (const waiter of this.waiters) this.settle(waiter) + } + } + + disconnect(client: Client): void { + this.requesters.delete(client) + } + + detach(client: Client, sessionId: string): void { + this.requesters.get(client)?.delete(sessionId) + } + + beginDisable(tabId: number, chromeSessionId?: string): () => void { + const key = disableKey(tabId, chromeSessionId) + this.disabling.set(key, (this.disabling.get(key) ?? 0) + 1) + this.invalidate(tabId, chromeSessionId) + return () => { + const count = (this.disabling.get(key) ?? 1) - 1 + if (count === 0) this.disabling.delete(key) + else this.disabling.set(key, count) + } + } + + private recordContextEvent(sessionId: string, event: CdpEvent): void { + if (!event.method.startsWith("Runtime.executionContext") && event.method !== "Page.frameDetached") return + const cache = this.cacheFor(sessionId) + if (!cache) return + switch (event.method) { + case "Runtime.executionContextsCleared": + cache.contexts = new Map() + return + case "Runtime.executionContextDestroyed": { + const id = getNumber(event.params, "executionContextId") + if (id !== undefined) cache.contexts?.delete(id) + return + } + case "Page.frameDetached": + for (const [id, created] of cache.contexts ?? []) { + if (contextAux(created)?.frameId === event.params?.frameId) cache.contexts?.delete(id) + } + return + case "Runtime.executionContextCreated": { + const id = getNumber(getObject(event.params?.context), "id") + if (!cache.contexts || id === undefined) return + cache.contexts.set(id, event) + if (cache.contexts.size > maxCachedContexts) cache.contexts = undefined + } + } + } + + private invalidate(tabId: number, chromeSessionId?: string): void { + for (const [sessionId] of this.contexts) { + const target = this.options.registry.targets.get(sessionId) ?? this.options.registry.childTargets.get(sessionId) + if (target?.tabId === tabId && (chromeSessionId === undefined || sessionId === chromeSessionId)) this.contexts.delete(sessionId) + } + } + + private cacheFor(sessionId: string): ContextCache | undefined { + for (const [key, value] of this.contexts) if (!value.current()) this.contexts.delete(key) + const root = this.options.registry.targets.get(sessionId) + const child = this.options.registry.childTargets.get(sessionId) + const parent = child ? this.options.registry.tabTargets.get(child.tabId) : undefined + const route = root ? { tabId: root.tabId, rootSessionId: root.sessionId } + : child && parent ? { tabId: child.tabId, rootSessionId: parent.sessionId, chromeSessionId: child.sessionId } : undefined + if (!route) return undefined + if (this.disabling.has(disableKey(route.tabId)) || this.disabling.has(disableKey(route.tabId, route.chromeSessionId))) return undefined + let cache = this.contexts.get(sessionId) + if (!cache) { + cache = { current: this.capture(route), contexts: new Map() } + this.contexts.set(sessionId, cache) + } + return cache + } + + private requester(client: Client, route: CdpRoutedSession, canContinue: () => boolean): Requester { + const sessions = this.requesters.get(client) ?? new Map() + this.requesters.set(client, sessions) + const sessionId = routeSessionId(route) + const existing = sessions.get(sessionId) + if (existing?.current()) return existing + const captured = this.capture(route) + const next: Requester = { + current: () => captured() && canContinue() && this.requesters.get(client) === sessions && sessions.get(sessionId) === next, + delivered: new Map(), + } + sessions.set(sessionId, next) + return next + } + + readonly enable = Effect.fn("CdpRuntime.enable")(function* ( + this: CdpRuntime, + route: CdpRoutedSession, + params: JsonObject, + canContinue: () => boolean, + client?: Client, + ) { + const current = this.capture(route) + const permitted = () => current() && canContinue() + // Raw CDP clients need not request a frame tree. Preserve their ordinary + // native-event path; cached replay requires a frame-tree request already admitted. + const requester = client ? this.requesters.get(client)?.get(routeSessionId(route)) : undefined + const rootFrame = () => requester && permitted() && requester.current() ? requester.frameId : undefined + const first = yield* this.observe(route, Effect.suspend(() => permitted() + ? this.options.send({ + tabId: route.tabId, method: "Runtime.enable", params, + ...(route.chromeSessionId === undefined ? {} : { sessionId: route.chromeSessionId }), + }) + : Effect.fail(new Error("CDP target changed before Runtime.enable"))), client && requester ? { + replay: () => { + const frameId = rootFrame() + return frameId !== undefined && this.replayCached(client, route, frameId) + }, + nativeReady: (event) => { + const frameId = rootFrame() + return frameId !== undefined && contextAux(event)?.frameId === frameId + }, + } : {}) + this.trace(route, `runtime-enable defaultContextSeen=${first.seen}`) + if (!first.seen && permitted()) { + // The shared debugger may acknowledge enable without replaying its context. + // Never run the recovery cycle against a successor generation or new owner. + const retry = yield* this.observe(route, this.reset(route, "Runtime.disable", {}, permitted).pipe( + Effect.andThen(() => this.reset(route, "Runtime.enable", params, permitted)), + )) + this.trace(route, `runtime-reset phase=missing-default-context defaultContextSeen=${retry.seen}`) + } + return first.result + }) + + readonly disableIdle = Effect.fn("CdpRuntime.disableIdle")(function* (this: CdpRuntime, stillIdle: () => boolean) { + const { registry } = this.options + const routes: CdpRoutedSession[] = registry.listRootTargets().map((target) => ({ tabId: target.tabId, rootSessionId: target.sessionId })) + for (const target of registry.childTargets.values()) { + const root = registry.tabTargets.get(target.tabId) + if (root) routes.push({ tabId: target.tabId, rootSessionId: root.sessionId, chromeSessionId: target.sessionId }) + } + const targets = routes.map((route) => ({ route, current: this.capture(route) })) + for (const { route, current } of targets) { + if (!stillIdle()) break + yield* this.reset(route, "Runtime.disable", {}, () => stillIdle() && current()) + } + }) + + /** Replay a complete cache only when it already holds the requester's root-frame default context. */ + private replayCached(client: Client, route: CdpRoutedSession, frameId: string): boolean { + const cache = this.contexts.get(routeSessionId(route)) + const contexts = cache?.current() ? cache.contexts : undefined + if (!contexts || ![...contexts.values()].some((event) => { + const aux = contextAux(event) + return aux?.isDefault === true && aux.frameId === frameId + })) return false + for (const event of contexts.values()) this.deliver(client, event) + this.trace(route, "runtime-replay defaultContextSeen=true") + return true + } + + private settle(waiter: Waiter): void { + if (waiter.replay?.()) Deferred.doneUnsafe(waiter.ready, Effect.succeed(true)) + } + + private observe(route: CdpRoutedSession, command: Effect.Effect, options: { + readonly replay?: () => boolean + readonly nativeReady?: (event: CdpEvent) => boolean + } = {}): Effect.Effect<{ readonly result: A; readonly seen: boolean }, Error> { + const runtime = this + return Effect.acquireUseRelease( + Effect.sync(() => { + const waiter: Waiter = { sessionId: routeSessionId(route), ready: Deferred.makeUnsafe(), nativeReady: options.nativeReady ?? (() => true) } + runtime.waiters.add(waiter) + return waiter + }), + (waiter) => Effect.gen(function* () { + // Start the window before sending: context events may precede the reply. + const seen = yield* Effect.forkScoped(Deferred.await(waiter.ready).pipe(Effect.timeoutOrElse({ + duration: "3 seconds", + orElse: () => Effect.succeed(false), + })), { startImmediately: true }) + const result = yield* command + if (options.replay) waiter.replay = options.replay + runtime.settle(waiter) + return { result, seen: yield* Fiber.join(seen) } + }).pipe(Effect.scoped), + (waiter) => Effect.sync(() => { runtime.waiters.delete(waiter) }), + ) + } + + private reset(route: CdpRoutedSession, method: "Runtime.enable" | "Runtime.disable", params: JsonObject, current: () => boolean): Effect.Effect { + return Effect.suspend(() => { + if (!current()) return Effect.void + this.trace(route, `runtime-reset command=${method}`) + return this.options.send({ tabId: route.tabId, method, params, ...(route.chromeSessionId === undefined ? {} : { sessionId: route.chromeSessionId }) }).pipe( + Effect.match({ + onFailure: (error) => this.trace(route, `runtime-reset command=${method} outcome=failed failure=${runtimeFailureKind(error)}`), + onSuccess: () => this.trace(route, `runtime-reset command=${method} outcome=ok`), + }), + ) + }) + } + + private capture(route: CdpRoutedSession): () => boolean { + const { registry } = this.options + const generation = this.options.generation() + const root = registry.targets.get(route.rootSessionId) + const owner = root?.opencodeBrowserSessionId + const child = route.chromeSessionId === undefined ? undefined : registry.childTargets.get(route.chromeSessionId) + return () => { + const currentRoot = registry.routingRootTarget(route.tabId) + if (!root || generation !== this.options.generation() || currentRoot?.sessionId !== root.sessionId || currentRoot.targetInfo.targetId !== root.targetInfo.targetId || currentRoot.opencodeBrowserSessionId !== owner) return false + if (route.chromeSessionId === undefined) return true + const currentChild = registry.childTargets.get(route.chromeSessionId) + return child !== undefined && currentChild?.tabId === route.tabId && currentChild.targetInfo.targetId === child.targetInfo.targetId && currentChild.parentSessionId === child.parentSessionId + } + } + + private trace(route: CdpRoutedSession, message: string): void { + this.options.trace?.(`${message} tab=${route.tabId} rootSession=${boundedToken(route.rootSessionId)} chromeSession=${boundedToken(route.chromeSessionId)}`) + } +} diff --git a/packages/browser-extension/cli/src/cdp-shims.ts b/packages/browser-extension/cli/src/cdp-shims.ts new file mode 100644 index 00000000000..9de44f703f8 --- /dev/null +++ b/packages/browser-extension/cli/src/cdp-shims.ts @@ -0,0 +1,133 @@ +import type { WebSocket } from "ws" +import type { CdpRequest, JsonObject, TargetInfo } from "./protocol.ts" +import { getObject, getString, sendCdpEvent } from "./relay-helpers.ts" +import type { ChildTarget } from "./relay-types.ts" +import { shouldExposeChildTarget, type TargetRegistry } from "./target-registry.ts" +import type { CdpClientPool } from "./cdp-client-pool.ts" + +export function removeDefaultLightColorSchemeEmulation(message: CdpRequest): CdpRequest { + if (message.method !== "Emulation.setEmulatedMedia") { + return message + } + const features = Array.isArray(message.params?.features) ? message.params.features : [] + const isExplicit = features.some((feature) => { + const object = getObject(feature) + return object?.name === "__bc_explicit__" + }) + if (isExplicit) { + return { + ...message, + params: { + ...message.params, + features: features.filter((feature) => { + const object = getObject(feature) + return object?.name !== "__bc_explicit__" + }), + }, + } + } + const hasDefaultLightColorScheme = features.some((feature) => { + const object = getObject(feature) + return object?.name === "prefers-color-scheme" && object.value === "light" + }) + if (!hasDefaultLightColorScheme) { + return message + } + return { + ...message, + params: { + ...message.params, + features: features.filter((feature) => { + const object = getObject(feature) + return object?.name !== "prefers-color-scheme" + }), + }, + } +} + +export function replayChildTargetsForParent>(options: { + readonly socket: Client + readonly parentSessionId: string + readonly registry: TargetRegistry + readonly clients: CdpClientPool +}): void { + for (const target of options.registry.childTargets.values()) { + if (target.parentSessionId === options.parentSessionId && shouldExposeChildTarget(target)) { + replayFrameEventsForChild({ socket: options.socket, registry: options.registry, target }) + options.clients.announce(options.socket, target) + replayChildFrameNavigation({ socket: options.socket, registry: options.registry, target }) + } + } +} + +function replayFrameEventsForChild(options: { readonly socket: Pick; readonly registry: TargetRegistry; readonly target: ChildTarget }): void { + if (options.target.targetInfo.type !== "iframe") { + return + } + const frameEvents = options.registry.tabFrameEvents.get(options.target.tabId)?.get(options.target.targetInfo.targetId) + if (!frameEvents) { + return + } + if (frameEvents.attached) { + sendCdpEvent(options.socket, { sessionId: options.target.parentSessionId, method: "Page.frameAttached", params: frameEvents.attached }) + } + if (frameEvents.navigated) { + sendCdpEvent(options.socket, { sessionId: options.target.parentSessionId, method: "Page.frameNavigated", params: frameEvents.navigated }) + } +} + +export function replayChildFrameNavigation(options: { readonly socket: Pick; readonly registry: TargetRegistry; readonly target: ChildTarget }): void { + const navigationParams = childFrameNavigationParams({ registry: options.registry, target: options.target }) + if (!navigationParams) { + return + } + // Stock Playwright does not apply Page.getFrameTree to child iframe sessions; + // replay the current navigation on the child session so reconnects do not + // leave OOPIF frames with an empty URL. + sendCdpEvent(options.socket, { sessionId: options.target.sessionId, method: "Page.frameNavigated", params: navigationParams }) +} + +function childFrameNavigationParams(options: { readonly registry: TargetRegistry; readonly target: ChildTarget }): JsonObject | undefined { + if (options.target.targetInfo.type !== "iframe") { + return undefined + } + const frameEvents = options.registry.findFrameEventsForChild(options.target) + const navigated = frameEvents?.navigated + const frame = getObject(navigated?.frame) + if (navigated && frame) { + return { + ...navigated, + frame: { + ...frame, + id: options.target.targetInfo.targetId, + url: options.target.targetInfo.url || (getString(frame, "url") ?? ""), + ...(options.target.targetInfo.parentFrameId ? { parentId: options.target.targetInfo.parentFrameId } : {}), + }, + } + } + if (!options.target.targetInfo.url) { + return undefined + } + const gatedAPIFeatures: string[] = [] + return { + frame: { + id: options.target.targetInfo.targetId, + loaderId: options.target.targetInfo.targetId, + url: options.target.targetInfo.url, + domainAndRegistry: "", + securityOrigin: new URL(options.target.targetInfo.url).origin, + mimeType: "text/html", + adFrameStatus: { adFrameType: "none" }, + secureContextType: "Secure", + crossOriginIsolatedContextType: "NotIsolated", + gatedAPIFeatures, + ...(options.target.targetInfo.parentFrameId ? { parentId: options.target.targetInfo.parentFrameId } : {}), + }, + } +} + +export function replayTargetCreated(options: { readonly socket: Pick; readonly targetInfos: readonly TargetInfo[] }): void { + for (const targetInfo of options.targetInfos) { + sendCdpEvent(options.socket, { method: "Target.targetCreated", params: { targetInfo } }) + } +} diff --git a/packages/browser-extension/cli/src/cdp-visibility.ts b/packages/browser-extension/cli/src/cdp-visibility.ts new file mode 100644 index 00000000000..896891c26cc --- /dev/null +++ b/packages/browser-extension/cli/src/cdp-visibility.ts @@ -0,0 +1,36 @@ +/** + * Per-client CDP target visibility. + * + * Each OpenCode Browser session's sandbox connects as its own CDP client and + * identifies itself with a OpenCode Browser session id. Tabs created for a + * session are owned by that session. Without scoping, every client is told + * about every tab, so concurrently connected clients attach to and + * double-initialize each other's pages, which makes + * `newPage`/`setContent`/`evaluate` hang non-deterministically. + * + * Visibility rule: + * - Session-owned targets are visible only to that session's clients. + * - User toolbar-attached targets stay visible to every client, so + * `--target-url` recovery keeps working. + * - Relay-created targets without a OpenCode Browser session id belong to raw + * `connectOverCDP` clients. They are visible to raw clients and to a session + * client that does not already own a target, so explicit `--target-url` + * adoption can still find existing attached pages. Once a session has its own + * sandbox target, it must not attach to raw-client pages, or Playwright + * double-initializes the page on Chrome's single debugger attachment and + * `locator.evaluate` can wedge. + * + * Two simultaneous raw clients can still interfere with each other's tabs; + * OpenCode Browser sessions are the isolated, supported path. + */ +export function canClientSeeTarget(options: { + readonly clientSessionId: string | undefined + readonly targetOwnerSessionId: string | undefined + readonly targetOwner: "relay" | "user" + readonly clientHasOwnedTarget: boolean +}): boolean { + if (options.targetOwnerSessionId === undefined) { + return options.targetOwner === "user" || options.clientSessionId === undefined || !options.clientHasOwnedTarget + } + return options.clientSessionId === options.targetOwnerSessionId +} diff --git a/packages/browser-extension/cli/src/child-process.ts b/packages/browser-extension/cli/src/child-process.ts new file mode 100644 index 00000000000..a7e416b93a8 --- /dev/null +++ b/packages/browser-extension/cli/src/child-process.ts @@ -0,0 +1,35 @@ +import type { ChildProcess } from "node:child_process" + +export async function terminateChildProcess(options: { + readonly child: ChildProcess + readonly exit: Promise + readonly graceMs: number + readonly isExited?: () => boolean +}): Promise { + const isExited = options.isExited ?? (() => options.child.exitCode !== null || options.child.signalCode !== null) + if (isExited()) return + signalChildProcess(options.child, "SIGTERM") + let timeout: ReturnType | undefined + await Promise.race([ + options.exit, + new Promise((resolve) => { + timeout = setTimeout(resolve, options.graceMs) + }), + ]) + if (timeout) clearTimeout(timeout) + if (isExited()) return + signalChildProcess(options.child, "SIGKILL") + await options.exit +} + +function signalChildProcess(child: ChildProcess, signal: NodeJS.Signals): void { + if (process.platform !== "win32" && child.pid !== undefined) { + try { + process.kill(-child.pid, signal) + return + } catch { + // The child may have exited between the state check and the signal. + } + } + child.kill(signal) +} diff --git a/packages/browser-extension/cli/src/cli.ts b/packages/browser-extension/cli/src/cli.ts new file mode 100644 index 00000000000..f2c5ddccdbe --- /dev/null +++ b/packages/browser-extension/cli/src/cli.ts @@ -0,0 +1,1094 @@ +#!/usr/bin/env node +import { NodeRuntime, NodeServices } from "@effect/platform-node" +import { Config, Console, Effect, FileSystem, Layer, Option, Predicate, Result, Schema } from "effect" +import { Argument, Command, Flag } from "effect/cli" +import path from "node:path" +import process from "node:process" +import { fileURLToPath } from "node:url" +import { createDoctorReport, formatDoctorReport, formatTargetSummary } from "./doctor.ts" +import { runMcpServer } from "./mcp.ts" +import * as RelayClient from "./relay-client.ts" +import { parseAdditionalExtensionOrigins } from "./relay-helpers.ts" +import * as RelayLifecycle from "./relay-lifecycle.ts" +import type { ExecuteAftermath, ExecuteLogEntry, ExecuteResponse, NetworkStatusResponse, NetworkStopResponse, RecordingQuality } from "./relay-schema.ts" +import { startRelay } from "./relay.ts" +import { defaultJournalBaseDir, formatJournalEntry, readJournalEntries } from "./session-journal.ts" +import * as SessionStore from "./session-store.ts" +import { opencodeBrowserVersion } from "./version.ts" + +const packageRoot = path.dirname(path.dirname(fileURLToPath(import.meta.url))) +const sessionIdConfig = Config.option(Config.String("OPENCODE_BROWSER_SESSION")) +const targetUrlConfig = Config.option(Config.String("OPENCODE_BROWSER_TARGET_URL")) +const targetIndexConfig = Config.option(Config.Int("OPENCODE_BROWSER_TARGET_INDEX")) +const encodedCliOperandsMarker = "bc-cli-operands:v1" +const encodedCliOperandPrefix = "bc-cli-operand:" +const jsonFlag = Flag.Boolean("json").pipe(Flag.withDefault(false), Flag.withDescription("Print machine-readable JSON")) +const sessionFlag = (description?: string) => { + const flag = Flag.String("session").pipe(Flag.optional, Flag.withAlias("s")) + return description ? flag.pipe(Flag.withDescription(description)) : flag +} +const tabIdFlag = (description?: string) => { + const flag = Flag.Int("tab-id").pipe(Flag.optional) + return description ? flag.pipe(Flag.withDescription(description)) : flag +} +const failExit = Effect.sync(() => { + process.exitCode = 1 +}) + +export function resolveExplicitSessionSelector(options: { + readonly positional: string | undefined + readonly flag: string | undefined + readonly environment: string | undefined +}): string | undefined { + if (options.positional && options.flag) { + throw new Error("Use either a positional session id or --session, not both") + } + return options.flag ?? options.positional ?? options.environment +} + +export function formatRecordingQuality(quality: RecordingQuality | undefined): string { + if (!quality) return "Capture quality: unavailable (tab capture or older relay)." + return [ + `Capture: ${quality.width}ร—${quality.height}, output ${quality.frameRate} fps; source surface ${quality.sourceWidth ?? "?"}ร—${quality.sourceHeight ?? "?"} CSS px`, + `Source frames: ${quality.sourceFrameCount} received (${quality.achievedSourceFrameRate.toFixed(1)}/s), ${quality.encodedSourceFrameCount} retained (${quality.achievedEncodedSourceFrameRate.toFixed(1)}/s), ${quality.coalescedFrameCount} coalesced, ${quality.droppedFrameCount} dropped`, + quality.screenshotFallback + ? "WARNING: no compositor frames arrived; this video holds a single stop-time screenshot." + : "Source counts are compositor events, not a measurement of distinct motion. Inspect the video before sharing.", + ].join("\n") +} + +export function normalizeCliArguments(args: ReadonlyArray): ReadonlyArray { + const delimiter = args.indexOf("--") + const secretsRun = args.findIndex((argument, index) => argument === "secrets" && args[index + 1] === "run") + if (delimiter === -1 || secretsRun === -1 || secretsRun > delimiter) return args + return [ + ...args.slice(0, delimiter), + encodedCliOperandsMarker, + ...args.slice(delimiter + 1).map((operand) => `${encodedCliOperandPrefix}${encodeURIComponent(operand)}`), + ] +} + +function decodeCliOperands(operands: ReadonlyArray): ReadonlyArray { + if (operands[0] !== encodedCliOperandsMarker) return operands + return operands.slice(1).map((operand) => { + if (!operand.startsWith(encodedCliOperandPrefix)) throw new Error("Invalid encoded secrets run operand") + return decodeURIComponent(operand.slice(encodedCliOperandPrefix.length)) + }) +} + +const readExecuteFile = Effect.fnUntraced(function* (filePath: string) { + const fs = yield* FileSystem.FileSystem + return yield* fs.readFileString(path.resolve(filePath)).pipe( + Effect.mapError((cause) => new Error(`read execute file ${filePath}: ${cause.reason.message}`, { cause })), + ) +}) + +const ensureCliRelay = Effect.fnUntraced(function* () { + const relay = yield* RelayClient.Service + const readiness = yield* RelayLifecycle.ensureRelay({ relay }) + if (readiness.started) { + yield* Console.error(`Started OpenCode Browser relay at ${relay.endpoint}`) + } + if (readiness.buildProblem) { + return yield* Effect.fail(new Error(readiness.buildProblem)) + } + return readiness +}) + +const ensureCliRelayAndExtension = Effect.fnUntraced(function* () { + const relay = yield* RelayClient.Service + const readiness = yield* ensureCliRelay() + yield* RelayLifecycle.ensureExtensionConnected({ + relay, + waitForReconnect: RelayLifecycle.shouldWaitForExtensionReconnect(readiness), + onWait: Console.error(`Waiting up to ${RelayLifecycle.extensionReconnectWaitMs / 1_000}s for the OpenCode Browser extension to reconnect`), + }) +}) + +const resolveSelectedSessionId = Effect.fnUntraced(function* (explicitSessionId: string | undefined) { + const store = yield* SessionStore.Service + const sessionId = explicitSessionId ?? (yield* store.read) + if (!sessionId) { + return yield* Effect.fail(new Error("No session provided and no current OpenCode Browser session exists")) + } + return sessionId +}) + +const resolvePositionalOrFlagSessionId = Effect.fnUntraced(function* ( + id: Option.Option, + session: Option.Option, +) { + return yield* resolveSelectedSessionId(resolveExplicitSessionSelector({ + positional: Option.getOrUndefined(id), + flag: Option.getOrUndefined(session), + environment: Option.getOrUndefined(yield* sessionIdConfig), + })) +}) + +const ensureSessionExists = Effect.fnUntraced(function* (id: string) { + const relay = yield* RelayClient.Service + yield* ensureCliRelay() + const sessions = yield* relay.sessions + const exists = sessions.some((session) => { + return session.id === id + }) + if (!exists) { + return yield* Effect.fail(new Error(`Session not found: ${id}`)) + } +}) + +const recordingTarget = Effect.fnUntraced(function* (options: { + readonly session: Option.Option + readonly tabId: Option.Option +}) { + const sessionId = Option.getOrUndefined(options.session) + const tabId = Option.getOrUndefined(options.tabId) + if (sessionId && tabId !== undefined) { + return yield* Effect.fail(new Error("Use only one recording target selector: --session or --tab-id")) + } + return { + ...(sessionId ? { sessionId } : {}), + ...(tabId === undefined ? {} : { tabId }), + } +}) + +const parseRecordingModeOption = Effect.fnUntraced(function* (value: string | undefined) { + if (value === undefined) { + return undefined + } + if (value === "auto" || value === "tab-capture" || value === "cdp") { + return value + } + return yield* Effect.fail(new Error("Recording mode must be auto, tab-capture, or cdp")) +}) + +function formatExecuteLogs(logs: readonly ExecuteLogEntry[]): string { + return [ + "Console logs:", + ...logs.map((log) => { + const location = log.location?.url ? ` ${log.location.url}:${log.location.lineNumber}:${log.location.columnNumber}` : "" + return `[${log.source}:${log.type}]${location} ${log.text}` + }), + ].join("\n") +} + +/** One-line aftermath summary, or null when nothing interesting happened. */ +function formatAftermath(aftermath: ExecuteAftermath): string | null { + const parts: string[] = [] + if (aftermath.startUrl !== aftermath.endUrl) { + parts.push(`Page: ${aftermath.startUrl ?? "none"} -> ${aftermath.endUrl ?? "none"}`) + } + if (aftermath.navigations.length > 1) { + parts.push(`navigations=${aftermath.navigations.length}`) + } + if (aftermath.pageErrorCount > 0) { + parts.push(`pageErrors=${aftermath.pageErrorCount}`) + } + if (aftermath.handoffs > 0) { + parts.push(`handoffs=${aftermath.handoffs}`) + } + return parts.length > 0 ? parts.join(" ") : null +} + +type ExecuteJsonEnvelope = { + readonly ok: boolean + readonly isError: boolean + readonly text: string + readonly value: unknown | null + readonly valueUnavailable: boolean + readonly error?: { readonly _tag: string; readonly message: string } + readonly logs: readonly ExecuteLogEntry[] + readonly warnings: readonly string[] + readonly diagnostic?: string + readonly aftermath?: ExecuteAftermath + readonly session?: ExecuteResponse["session"] +} + +const ScriptErrorEnvelope = Schema.TaggedStruct("ScriptError", { + message: Schema.String, +}) + +export function executeJsonEnvelope(result: ExecuteResponse): ExecuteJsonEnvelope { + const hasStructuredValue = Object.hasOwn(result, "value") && result.value !== undefined + return { + ok: !result.isError, + isError: result.isError, + text: result.text, + value: hasStructuredValue ? result.value : null, + valueUnavailable: !hasStructuredValue, + ...(result.isError ? { error: ScriptErrorEnvelope.make({ message: result.text }) } : {}), + logs: result.logs, + warnings: result.warnings ?? [], + ...(result.diagnostic ? { diagnostic: result.diagnostic } : {}), + ...(result.aftermath ? { aftermath: result.aftermath } : {}), + session: result.session, + } +} + +export function formatSessionContinuation(sessionId: string): string { + return `Session: ${sessionId}. Continue with --session ${sessionId}.` +} + +function errorJsonEnvelope(error: unknown): ExecuteJsonEnvelope { + const tag = Predicate.isObject(error) && Predicate.hasProperty(error, "_tag") && Predicate.isString(error._tag) ? error._tag : "Error" + const message = error instanceof Error ? error.message : String(error) + const errorValue: { readonly _tag: string; readonly message: string } = Object.assign({ message }, { _tag: tag }) + return { ok: false, isError: true, text: message, value: null, valueUnavailable: true, error: errorValue, logs: [], warnings: [] } +} + +const serve = Command.make( + "serve", + {}, + Effect.fn("Cli.serve")(function* () { + const port = yield* RelayClient.portConfig + const additionalExtensionOrigins = parseAdditionalExtensionOrigins(yield* RelayClient.extensionOriginsConfig) + yield* Effect.scoped( + Effect.gen(function* () { + const relay = yield* startRelay({ port, additionalExtensionOrigins }) + yield* Console.log(`opencode-browser relay listening at ${relay.url}`) + yield* Console.log("OpenCode Browser connects automatically while the browser runs. Run `opencode-browser status` to check.") + yield* Effect.never + }), + ) + }), +).pipe(Command.withDescription("Start the local OpenCode Browser relay")) + +const relayRestart = Command.make( + "restart", + {}, + Effect.fn("Cli.relayRestart")(function* () { + const relay = yield* RelayClient.Service + yield* Console.error("Restarting the relay leaves browser tabs open but resets in-memory JavaScript state.") + const readiness = yield* RelayLifecycle.restartRelay({ relay, clientKind: "cli" }) + yield* Console.log(`${readiness.started ? "Started" : "Reused concurrent replacement"} OpenCode Browser relay at ${relay.endpoint} (${readiness.version.buildId})`) + }), +).pipe(Command.withDescription("Explicitly drain and restart the managed relay using this installation")) + +const relay = Command.make("relay").pipe( + Command.withDescription("Manage the local relay lifecycle"), + Command.withSubcommands([relayRestart]), +) + +const execute = Command.make( + "execute", + { + code: Argument.String("code").pipe(Argument.variadic({ min: 0 })), + file: Flag.String("file").pipe(Flag.optional, Flag.withDescription("Read execute code from a file")), + session: sessionFlag("Continue an existing OpenCode Browser session; omit to create a fresh one"), + targetUrl: Flag.String("target-url").pipe(Flag.optional, Flag.withDescription("Use the attached page whose URL contains this text")), + targetIndex: Flag.Int("target-index").pipe(Flag.optional, Flag.withDescription("Use the attached page at this zero-based index")), + json: Flag.Boolean("json").pipe(Flag.withDefault(false), Flag.withDescription("Print a machine-readable result envelope: { ok, isError, text, value, valueUnavailable, error?, logs, warnings, diagnostic?, aftermath, session }")), + }, + Effect.fn("Cli.execute")(function* ({ code, file, session, targetUrl, targetIndex, json }) { + const run = Effect.gen(function* () { + const relay = yield* RelayClient.Service + const filePath = Option.getOrUndefined(file) + if (code.length > 0 && filePath) { + return yield* Effect.fail(new Error("Use either positional code or --file, not both")) + } + if (code.length === 0 && !filePath) { + return yield* Effect.fail(new Error("Execute requires positional code or --file ")) + } + const executeCode = filePath ? yield* readExecuteFile(filePath) : code.join(" ") + yield* ensureCliRelayAndExtension() + const explicitSessionId = Option.getOrUndefined(session) ?? Option.getOrUndefined(yield* sessionIdConfig) + const targetUrlValue = Option.getOrUndefined(targetUrl) ?? Option.getOrUndefined(yield* targetUrlConfig) + const targetIndexValue = Option.getOrUndefined(targetIndex) ?? Option.getOrUndefined(yield* targetIndexConfig) + if (targetIndexValue !== undefined && targetIndexValue < 0) { + return yield* Effect.fail(new Error("Target index must be a non-negative integer")) + } + if (targetUrlValue && targetIndexValue !== undefined) { + return yield* Effect.fail(new Error("Use only one target selector: --target-url/OPENCODE_BROWSER_TARGET_URL or --target-index/OPENCODE_BROWSER_TARGET_INDEX")) + } + const result = yield* relay.execute({ + ...(explicitSessionId ? { sessionId: explicitSessionId } : {}), + code: executeCode, + createIfMissing: !explicitSessionId, + ...(targetUrlValue || targetIndexValue !== undefined + ? { + targetSelection: { + ...(targetUrlValue ? { urlIncludes: targetUrlValue } : {}), + ...(targetIndexValue !== undefined ? { index: targetIndexValue } : {}), + }, + } + : {}), + }) + if (!explicitSessionId) { + yield* Console.error(formatSessionContinuation(result.session.id)) + } + return result + }) + if (json) { + const envelope = yield* run.pipe( + Effect.map(executeJsonEnvelope), + Effect.catch((error) => Effect.succeed(errorJsonEnvelope(error))), + ) + yield* Console.log(JSON.stringify(envelope, null, 2)) + if (!envelope.ok) { + yield* failExit + } + return + } + const outcome = yield* Effect.result(run) + if (Result.isFailure(outcome)) { + yield* Console.error(outcome.failure.message) + yield* failExit + return + } + const result = outcome.success + const print = result.isError ? Console.error : Console.log + yield* print(result.text) + if (result.logs.length > 0) { + yield* print(formatExecuteLogs(result.logs)) + } + yield* Effect.forEach(result.warnings ?? [], (warning) => print(`Warning: ${warning}`)) + if (result.diagnostic) { + yield* print(`Diagnostic: ${result.diagnostic}`) + } + const aftermath = result.aftermath ? formatAftermath(result.aftermath) : null + if (aftermath) { + yield* print(aftermath) + } + if (result.isError) { + yield* failExit + } + }), +).pipe(Command.withDescription("Execute Playwright code against the attached browser")) + +const sessionNew = Command.make( + "new", + { + name: Argument.String("name").pipe(Argument.optional, Argument.withDescription("Optional lowercase session id")), + readOnly: Flag.Boolean("read-only").pipe(Flag.withDefault(false), Flag.withDescription("Create a read-only session: the relay rejects input-dispatching CDP so scripts can inspect but not click or type")), + }, + Effect.fn("Cli.sessionNew")(function* ({ name, readOnly }) { + const relay = yield* RelayClient.Service + yield* ensureCliRelay() + const store = yield* SessionStore.Service + const result = yield* relay.sessionNew(Option.getOrUndefined(name), readOnly ? { readOnly: true } : {}) + yield* store.write(result.id) + yield* Console.log(result.id) + }), +).pipe(Command.withDescription("Create a OpenCode Browser session and make it current")) + +const sessionList = Command.make( + "list", + { + json: jsonFlag, + }, + Effect.fn("Cli.sessionList")(function* ({ json }) { + const relay = yield* RelayClient.Service + yield* ensureCliRelay() + const store = yield* SessionStore.Service + const sessions = yield* relay.sessions + const current = yield* store.read + if (json) { + yield* Console.log(JSON.stringify({ current: current ?? undefined, sessions }, null, 2)) + return + } + if (sessions.length === 0) { + yield* Console.log("No sessions") + return + } + yield* Effect.forEach(sessions, (item) => { + const marker = item.id === current ? "*" : " " + const page = item.pageUrl ?? "no page yet" + const keys = item.stateKeys.length ? ` state=${item.stateKeys.join(",")}` : "" + const readOnly = item.readOnly ? " read-only" : "" + return Console.log(`${marker} ${item.id} ${page}${keys}${readOnly}`) + }) + }), +).pipe(Command.withDescription("List OpenCode Browser sessions")) + +const sessionCurrent = Command.make( + "current", + {}, + Effect.fn("Cli.sessionCurrent")(function* () { + const store = yield* SessionStore.Service + const current = yield* store.read + yield* Console.log(current ?? "none") + }), +).pipe(Command.withDescription("Print the current default session")) + +const sessionUse = Command.make( + "use", + { + id: Argument.String("id"), + }, + Effect.fn("Cli.sessionUse")(function* ({ id }) { + const store = yield* SessionStore.Service + yield* ensureSessionExists(id) + yield* store.write(id) + yield* Console.log(id) + }), +).pipe(Command.withDescription("Set the current default session")) + +const sessionReset = Command.make( + "reset", + { + id: Argument.String("id").pipe(Argument.optional), + session: sessionFlag("Reset this OpenCode Browser session id"), + }, + Effect.fn("Cli.sessionReset")(function* ({ id, session }) { + const relay = yield* RelayClient.Service + const sessionId = yield* resolvePositionalOrFlagSessionId(id, session) + yield* ensureCliRelay() + const resetSession = yield* relay.sessionReset(sessionId) + yield* Console.log(resetSession.id) + }), +).pipe(Command.withDescription("Reset a OpenCode Browser session state and page")) + +const sessionAdopt = Command.make( + "adopt", + { + session: sessionFlag("Adopt into this OpenCode Browser session, creating it when it does not exist yet; omit to create a fresh readable id"), + targetUrl: Flag.String("target-url").pipe(Flag.optional, Flag.withDescription("Adopt the attached page whose URL contains this text")), + targetIndex: Flag.Int("target-index").pipe(Flag.optional, Flag.withDescription("Adopt the attached page at this zero-based target index")), + tabId: tabIdFlag("Adopt the user's shared tab with this Chrome tab id (the tab= value in status)"), + }, + Effect.fn("Cli.sessionAdopt")(function* ({ session, targetUrl, targetIndex, tabId }) { + const relay = yield* RelayClient.Service + yield* ensureCliRelayAndExtension() + const explicitSessionId = Option.getOrUndefined(session) ?? Option.getOrUndefined(yield* sessionIdConfig) + const targetUrlValue = Option.getOrUndefined(targetUrl) + const targetIndexValue = Option.getOrUndefined(targetIndex) + if (targetIndexValue !== undefined && targetIndexValue < 0) { + return yield* Effect.fail(new Error("Target index must be a non-negative integer")) + } + const tabIdValue = Option.getOrUndefined(tabId) + if ([targetUrlValue, targetIndexValue, tabIdValue].filter((value) => value !== undefined).length > 1) { + return yield* Effect.fail(new Error("Use only one target selector: --target-url, --target-index, or --tab-id")) + } + const targetSelection = targetUrlValue + ? { urlIncludes: targetUrlValue } + : targetIndexValue !== undefined + ? { index: targetIndexValue } + : undefined + // An explicit id names the session the agent wants to continue with; creating it here + // mirrors `session new ` and never infers identity from shared current-session state. + const result = yield* relay.sessionAdopt({ + ...(explicitSessionId ? { sessionId: explicitSessionId } : {}), + createIfMissing: true, + ...(targetSelection ? { targetSelection } : {}), + ...(tabIdValue === undefined ? {} : { tabId: tabIdValue }), + }) + yield* Console.log(`${result.session.created ? "Created and adopted" : "Adopted"} session '${result.session.id}' default page: ${result.adoptedUrl}`) + if (result.session.created) { + yield* Console.error(formatSessionContinuation(result.session.id)) + } + }), +).pipe(Command.withDescription("Make an attached tab the session's default page")) + +const sessionDelete = Command.make( + "delete", + { + id: Argument.String("id").pipe(Argument.optional), + session: sessionFlag("Delete this OpenCode Browser session id"), + }, + Effect.fn("Cli.sessionDelete")(function* ({ id, session }) { + const relay = yield* RelayClient.Service + const store = yield* SessionStore.Service + const sessionId = yield* resolvePositionalOrFlagSessionId(id, session) + yield* ensureCliRelay() + yield* relay.sessionDelete(sessionId) + const current = yield* store.read + if (current === sessionId) { + yield* store.clear + } + yield* Console.log(sessionId) + }), +).pipe(Command.withDescription("Delete a OpenCode Browser session")) + +const session = Command.make("session").pipe( + Command.withDescription("Manage OpenCode Browser sessions"), + Command.withSubcommands([sessionNew, sessionList, sessionCurrent, sessionUse, sessionReset, sessionAdopt, sessionDelete]), +) + +const status = Command.make( + "status", + { + json: jsonFlag, + }, + Effect.fn("Cli.status")(function* ({ json }) { + const relay = yield* RelayClient.Service + const store = yield* SessionStore.Service + const relayResult = yield* Effect.result(relay.version) + if (Result.isFailure(relayResult)) { + if (!(relayResult.failure instanceof RelayClient.RelayUnreachable)) { + if (json) { + yield* Console.log(JSON.stringify({ + endpoint: relay.endpoint, + relay: { running: false, error: relayResult.failure.message }, + extension: null, + sessions: [], + targets: [], + }, null, 2)) + } else { + yield* Console.error(`Relay status failed: ${relayResult.failure.message}`) + } + yield* failExit + return + } + const stopped = RelayLifecycle.stoppedRelayStatus(relay.endpoint) + if (json) { + yield* Console.log(JSON.stringify(stopped, null, 2)) + } else { + yield* Console.log(`Relay: stopped (${relay.endpoint})`) + yield* Console.log("Run opencode-browser execute to start it automatically.") + } + yield* failExit + return + } + const version = relayResult.success + const buildProblem = RelayLifecycle.relayBuildProblem(version) + const [extensionStatus, current] = yield* Effect.all([relay.extensionStatus, store.read]) + const collections = RelayLifecycle.statusCollections(extensionStatus) + const [sessions, targets] = collections + ? [collections.sessions, collections.targets] + : yield* Effect.all([relay.sessions, relay.targets]) + if (json) { + yield* Console.log(JSON.stringify({ + endpoint: relay.endpoint, + relay: { running: true, version: version.version, buildId: version.buildId ?? null, stale: buildProblem !== undefined }, + extension: extensionStatus, + currentSession: current ?? null, + sessions, + targets, + }, null, 2)) + if (buildProblem) { + yield* failExit + } + return + } + yield* Console.log(`Relay: ${relay.endpoint} (${version.version})`) + if (buildProblem) { + yield* Console.log(`Warning: ${buildProblem}`) + } + yield* Console.log(`Extension: ${extensionStatus.connected ? "connected" : "disconnected"}${extensionStatus.version ? ` (${extensionStatus.version})` : ""}`) + if ((extensionStatus.rejectedConnections ?? 0) > 0) { + yield* Console.log(`Warning: ${extensionStatus.rejectedConnections} competing browser/profile connection attempt(s) rejected; the active connection was preserved. Use OpenCode Browser in one browser/profile at a time.`) + } + if (extensionStatus.protocolVersion !== undefined && extensionStatus.protocolVersion !== null) { + const compatibility = extensionStatus.protocolCompatible === false ? "incompatible" : "compatible" + const legacy = extensionStatus.protocolLegacy === true ? ", inferred from legacy hello" : "" + yield* Console.log(`Extension protocol: ${extensionStatus.protocolVersion} (${compatibility}${legacy})`) + } + yield* Console.log(`Active targets: ${extensionStatus.activeTargets}`) + if (extensionStatus.childTargets !== undefined) { + yield* Console.log(`Child targets: ${extensionStatus.childTargets}`) + } + if (extensionStatus.cdpClients !== undefined) { + yield* Console.log(`CDP clients: ${extensionStatus.cdpClients}`) + } + yield* Console.log(`Current session: ${current ?? "none"}`) + if (sessions.length === 0) { + yield* Console.log("Sessions: none") + } else { + yield* Console.log("Sessions:") + const activeSessions = sessions.filter((item) => item.id === current || item.connected || item.pageUrl !== null || item.stateKeys.length > 0 || item.readOnly) + const idleSessions = sessions.filter((item) => !activeSessions.includes(item)) + const shownSessions = activeSessions.length > 0 ? activeSessions : idleSessions.slice(0, 5) + const omittedIdleCount = activeSessions.length > 0 ? idleSessions.length : Math.max(0, idleSessions.length - shownSessions.length) + yield* Effect.forEach(shownSessions, (item) => { + const marker = item.id === current ? "*" : " " + return Console.log(`${marker} ${item.id} ${item.pageUrl ?? "no page yet"}`) + }) + if (omittedIdleCount > 0) { + yield* Console.log(` (${omittedIdleCount} idle session(s) with no page omitted; run opencode-browser session list to view all)`) + } + } + if (targets.length === 0) { + yield* Console.log("Targets: none") + } else { + yield* Console.log("Targets:") + yield* Effect.forEach(targets, (target, index) => { + return Console.log(`- [${index}] ${formatTargetSummary(target, { includeSession: true })}`) + }) + } + if (buildProblem) { + yield* failExit + } + }), +).pipe(Command.withDescription("Show relay, extension, and target status")) + +const recordingStart = Command.make( + "start", + { + outputPath: Argument.String("output-path").pipe(Argument.withDescription("Path to write the recording artifact; tabCapture requires .webm, CDP accepts .webm or .mp4")), + session: sessionFlag("Record the page for this OpenCode Browser or CDP session id"), + tabId: tabIdFlag("Record this attached Chrome tab id"), + mode: Flag.String("mode").pipe(Flag.optional, Flag.withDescription("Recording mode: auto, tab-capture, or cdp. auto uses CDP for relay-owned tabs and tabCapture for user-owned tabs")), + audio: Flag.Boolean("audio").pipe(Flag.withDefault(false), Flag.withDescription("Include tab audio")), + frameRate: Flag.Int("frame-rate").pipe(Flag.optional, Flag.withDescription("Output frame rate, integer 1..60; defaults to 30 for tab-capture and 60 for CDP")), + maxDurationMs: Flag.Int("max-duration-ms").pipe(Flag.optional, Flag.withDescription("Auto-stop guard in milliseconds, defaults to 900000")), + json: jsonFlag, + }, + Effect.fn("Cli.recordingStart")(function* ({ outputPath, session, tabId, mode, audio, frameRate, maxDurationMs, json }) { + if (Option.isSome(frameRate) && (frameRate.value < 1 || frameRate.value > 60)) { + return yield* Effect.fail(new Error("Recording frameRate must be an integer from 1 to 60")) + } + const relay = yield* RelayClient.Service + yield* ensureCliRelayAndExtension() + const target = yield* recordingTarget({ session, tabId }) + const modeValue = yield* parseRecordingModeOption(Option.getOrUndefined(mode)) + const resolvedOutputPath = path.resolve(outputPath) + const result = yield* relay.recordingStart({ + ...target, + outputPath: resolvedOutputPath, + ...(modeValue === undefined ? {} : { mode: modeValue }), + audio, + ...(Option.isSome(frameRate) ? { frameRate: frameRate.value } : {}), + ...(Option.isSome(maxDurationMs) ? { maxDurationMs: maxDurationMs.value } : {}), + }) + if (!result.success) { + return yield* Effect.fail(new Error(result.error ?? "Failed to start recording")) + } + yield* Console.log(json ? JSON.stringify(result, null, 2) : `Recording started: ${result.path ?? resolvedOutputPath} tab=${result.tabId ?? "unknown"} mode=${result.mode ?? "tab-capture"} artifact=${result.artifactType ?? "webm"} mime=${result.mimeType ?? "video/webm"} fps=${result.frameRate ?? "unknown"}`) + }), +).pipe(Command.withDescription("Start recording an attached tab")) + +const recordingStop = Command.make( + "stop", + { + session: sessionFlag("Stop recording for this CDP session id"), + tabId: tabIdFlag("Stop recording for this Chrome tab id"), + json: jsonFlag, + }, + Effect.fn("Cli.recordingStop")(function* ({ session, tabId, json }) { + const relay = yield* RelayClient.Service + yield* ensureCliRelay() + const target = yield* recordingTarget({ session, tabId }) + const result = yield* relay.recordingStop(target) + if (!result.success) { + return yield* Effect.fail(new Error(result.error ?? "Failed to stop recording")) + } + if (json) return yield* Console.log(JSON.stringify(result, null, 2)) + const frames = result.frameCount === undefined ? "" : `, frames=${result.frameCount}` + yield* Console.log(`Recording saved: ${result.path ?? "unknown"} (${result.size ?? 0} bytes, ${result.duration ?? 0}ms, mode=${result.mode ?? "tab-capture"}, artifact=${result.artifactType ?? "webm"}${frames})`) + yield* Console.log(formatRecordingQuality(result.quality)) + }), +).pipe(Command.withDescription("Stop recording and write the artifact")) + +const recordingStatus = Command.make( + "status", + { + session: sessionFlag("Check recording for this CDP session id"), + tabId: tabIdFlag("Check recording for this Chrome tab id"), + json: jsonFlag, + }, + Effect.fn("Cli.recordingStatus")(function* ({ session, tabId, json }) { + const relay = yield* RelayClient.Service + yield* ensureCliRelay() + const target = yield* recordingTarget({ session, tabId }) + const result = yield* relay.recordingStatus(target) + if (json) { + yield* Console.log(JSON.stringify(result, null, 2)) + return + } + if (!result.isRecording) { + yield* Console.log("Recording: inactive") + return + } + const frames = result.frameCount === undefined ? "" : ` frameCount=${result.frameCount}` + yield* Console.log(`Recording: active tab=${result.tabId ?? "unknown"} mode=${result.mode ?? "tab-capture"} artifact=${result.artifactType ?? "webm"} path=${result.path ?? "unknown"} size=${result.size ?? 0}${frames} startedAt=${result.startedAt ?? "unknown"}`) + yield* Console.log(formatRecordingQuality(result.quality)) + }), +).pipe(Command.withDescription("Check current recording status")) + +const recordingCancel = Command.make( + "cancel", + { + session: sessionFlag("Cancel recording for this CDP session id"), + tabId: tabIdFlag("Cancel recording for this Chrome tab id"), + }, + Effect.fn("Cli.recordingCancel")(function* ({ session, tabId }) { + const relay = yield* RelayClient.Service + yield* ensureCliRelay() + const target = yield* recordingTarget({ session, tabId }) + const result = yield* relay.recordingCancel(target) + if (!result.success) { + return yield* Effect.fail(new Error(result.error ?? "Failed to cancel recording")) + } + yield* Console.log("Recording cancelled") + }), +).pipe(Command.withDescription("Cancel recording without writing a file")) + +const recording = Command.make("recording").pipe( + Command.withDescription("Record an attached tab to WebM or MP4"), + Command.withSubcommands([recordingStart, recordingStop, recordingStatus, recordingCancel]), +) + +const flightRecorderStart = Command.make( + "start", + { + session: sessionFlag("Buffer the tab owned by this session"), + tabId: tabIdFlag("Buffer this attached Chrome tab id"), + retentionMs: Flag.Int("retention-ms").pipe(Flag.optional, Flag.withDescription("Ring-buffer duration in milliseconds (1000..120000; default 60000)")), + frameRate: Flag.Int("frame-rate").pipe(Flag.optional, Flag.withDescription("Output frame rate from 1 to 60")), + json: jsonFlag, + }, + Effect.fn("Cli.flightRecorderStart")(function* ({ session, tabId, retentionMs, frameRate, json }) { + const relay = yield* RelayClient.Service + yield* ensureCliRelayAndExtension() + const target = yield* recordingTarget({ session, tabId }) + const result = yield* relay.flightRecorderStart({ + ...target, + ...(Option.isSome(retentionMs) ? { retentionMs: retentionMs.value } : {}), + ...(Option.isSome(frameRate) ? { frameRate: frameRate.value } : {}), + }) + yield* Console.log(json ? JSON.stringify(result) : `Flight recorder buffering tab ${result.tabId}; retention=${result.retentionMs}ms`) + }), +).pipe(Command.withDescription("Start a rolling in-memory video buffer")) + +const flightRecorderStatus = Command.make( + "status", + { + session: sessionFlag(), + tabId: tabIdFlag(), + json: jsonFlag, + }, + Effect.fn("Cli.flightRecorderStatus")(function* ({ session, tabId, json }) { + const relay = yield* RelayClient.Service + yield* ensureCliRelay() + const result = yield* relay.flightRecorderStatus(yield* recordingTarget({ session, tabId })) + if (json) return yield* Console.log(JSON.stringify(result)) + if (!result.active) return yield* Console.log("Flight recorder inactive") + yield* Console.log(`Flight recorder tab=${result.tabId} frames=${result.bufferedFrames} retained=${result.retainedDurationMs}ms bytes=${result.bufferedBytes}`) + }), +).pipe(Command.withDescription("Show rolling flight-recorder status")) + +const flightRecorderSaveLast = Command.make( + "save-last", + { + outputPath: Argument.String("output-path").pipe(Argument.withDescription("Fresh .webm or .mp4 artifact path")), + session: sessionFlag(), + tabId: tabIdFlag(), + durationMs: Flag.Int("duration-ms").pipe(Flag.optional, Flag.withDescription("How much recent history to save; defaults to 30 seconds")), + json: jsonFlag, + }, + Effect.fn("Cli.flightRecorderSaveLast")(function* ({ outputPath, session, tabId, durationMs, json }) { + const relay = yield* RelayClient.Service + yield* ensureCliRelay() + const result = yield* relay.flightRecorderSaveLast({ + ...(yield* recordingTarget({ session, tabId })), + outputPath: path.resolve(outputPath), + ...(Option.isSome(durationMs) ? { durationMs: durationMs.value } : {}), + }) + yield* Console.log(json ? JSON.stringify(result) : `Saved ${result.durationMs}ms flight recorder clip (${result.frameCount} frames) to ${result.path}`) + }), +).pipe(Command.withDescription("Save the most recent buffered video without stopping the recorder")) + +const flightRecorderCancel = Command.make( + "cancel", + { + session: sessionFlag(), + tabId: tabIdFlag(), + }, + Effect.fn("Cli.flightRecorderCancel")(function* ({ session, tabId }) { + const relay = yield* RelayClient.Service + yield* ensureCliRelay() + const result = yield* relay.flightRecorderCancel(yield* recordingTarget({ session, tabId })) + yield* Console.log(result.cancelled ? "Flight recorder stopped" : "No active flight recorder") + }), +).pipe(Command.withDescription("Stop and discard the rolling video buffer")) + +const flightRecorder = Command.make("flight-recorder").pipe( + Command.withDescription("Keep and save a rolling buffer of recent browser video"), + Command.withSubcommands([flightRecorderStart, flightRecorderStatus, flightRecorderSaveLast, flightRecorderCancel]), +) + +const networkSession = Effect.fnUntraced(function* (session: Option.Option) { + return yield* resolveSelectedSessionId(Option.getOrUndefined(session) ?? Option.getOrUndefined(yield* sessionIdConfig)) +}) + +const parseNetworkContent = Effect.fnUntraced(function* (content: Option.Option) { + const value = Option.getOrUndefined(content) + if (value === undefined || value === "embed" || value === "omit") return value + return yield* Effect.fail(new Error("Network content must be embed or omit")) +}) + +function formatNetworkStatus(status: NetworkStatusResponse): string { + if (!status.active) return "Network capture: inactive" + return `Network capture: active entries=${status.entryCount} responses=${status.responseCount} failures=${status.failureCount} bodyBytes=${status.capturedBodyBytes} truncated=${status.truncatedBodyCount} dropped=${status.droppedEntryCount} startedAt=${status.startedAt ?? "unknown"}` +} + +function formatNetworkResult(result: NetworkStopResponse): string { + const output = result.outputPath ? ` output=${result.outputPath}` : "" + const profile = result.authProfile ? ` secrets=${result.authProfile.name}(${result.authProfile.slotCount})` : "" + return `Network capture stopped: entries=${result.entryCount} responses=${result.responseCount} failures=${result.failureCount} bodyBytes=${result.capturedBodyBytes} truncated=${result.truncatedBodyCount} dropped=${result.droppedEntryCount}${output}${profile}` +} + +const networkStart = Command.make( + "start", + { + session: sessionFlag("Capture the default page for this OpenCode Browser session"), + urlFilter: Flag.String("url").pipe(Flag.optional, Flag.withDescription("Capture only requests whose URL contains this text")), + resourceTypes: Flag.String("resource-type").pipe(Flag.atMost(50), Flag.withDescription("Capture this Playwright resource type; repeat for multiple types")), + content: Flag.String("content").pipe(Flag.optional, Flag.withDescription("Response and request body mode: embed (default) or omit")), + maxBodyBytes: Flag.Int("max-body-bytes").pipe(Flag.optional, Flag.withDescription("Maximum captured bytes per body, defaults to 1000000")), + maxTotalBodyBytes: Flag.Int("max-total-body-bytes").pipe(Flag.optional, Flag.withDescription("Maximum captured body bytes for the whole capture, defaults to 25000000")), + maxEntries: Flag.Int("max-entries").pipe(Flag.optional, Flag.withDescription("Maximum request entries, defaults to 1000")), + json: jsonFlag, + }, + Effect.fn("Cli.networkStart")(function* ({ session, urlFilter, resourceTypes, content, maxBodyBytes, maxTotalBodyBytes, maxEntries, json }) { + const relay = yield* RelayClient.Service + yield* ensureCliRelayAndExtension() + const sessionId = yield* networkSession(session) + const contentValue = yield* parseNetworkContent(content) + const result = yield* relay.networkStart({ + sessionId, + ...(Option.isSome(urlFilter) ? { urlFilter: urlFilter.value } : {}), + ...(resourceTypes.length === 0 ? {} : { resourceTypes }), + ...(contentValue === undefined ? {} : { content: contentValue }), + ...(Option.isSome(maxBodyBytes) ? { maxBodyBytes: maxBodyBytes.value } : {}), + ...(Option.isSome(maxTotalBodyBytes) ? { maxTotalBodyBytes: maxTotalBodyBytes.value } : {}), + ...(Option.isSome(maxEntries) ? { maxEntries: maxEntries.value } : {}), + }) + yield* Console.log(json ? JSON.stringify(result, null, 2) : formatNetworkStatus(result)) + }), +).pipe(Command.withDescription("Start session-scoped network capture")) + +const networkStatus = Command.make( + "status", + { + session: sessionFlag(), + json: jsonFlag, + }, + Effect.fn("Cli.networkStatus")(function* ({ session, json }) { + const relay = yield* RelayClient.Service + const sessionId = yield* networkSession(session) + yield* ensureCliRelay() + const result = yield* relay.networkStatus({ sessionId }) + yield* Console.log(json ? JSON.stringify(result, null, 2) : formatNetworkStatus(result)) + }), +).pipe(Command.withDescription("Show session-scoped network capture status")) + +const networkStop = Command.make( + "stop", + { + session: sessionFlag(), + output: Flag.String("output").pipe(Flag.optional, Flag.withAlias("o"), Flag.withDescription("Write a credential-redacted HAR artifact to this path")), + secrets: Flag.String("secrets").pipe(Flag.optional, Flag.withDescription("Store captured credentials under this reusable profile name")), + json: jsonFlag, + }, + Effect.fn("Cli.networkStop")(function* ({ session, output, secrets, json }) { + const relay = yield* RelayClient.Service + const outputValue = Option.getOrUndefined(output) + const secretsValue = Option.getOrUndefined(secrets) + if (!outputValue && !secretsValue) { + return yield* Effect.fail(new Error("network stop requires --output, --secrets, or both")) + } + const sessionId = yield* networkSession(session) + yield* ensureCliRelay() + const result = yield* relay.networkStop({ + sessionId, + ...(outputValue ? { outputPath: path.resolve(outputValue) } : {}), + ...(secretsValue ? { secrets: secretsValue } : {}), + }) + yield* Console.log(json ? JSON.stringify(result, null, 2) : formatNetworkResult(result)) + }), +).pipe(Command.withDescription("Stop capture and write a redacted artifact or reusable secret profile")) + +const networkCancel = Command.make( + "cancel", + { session: sessionFlag() }, + Effect.fn("Cli.networkCancel")(function* ({ session }) { + const relay = yield* RelayClient.Service + const sessionId = yield* networkSession(session) + yield* ensureCliRelay() + const result = yield* relay.networkCancel({ sessionId }) + yield* Console.log(result.cancelled ? "Network capture cancelled" : "Network capture was not active") + }), +).pipe(Command.withDescription("Cancel capture without writing an artifact")) + +const network = Command.make("network").pipe( + Command.withDescription("Capture authenticated network exchanges for direct client derivation"), + Command.withSubcommands([networkStart, networkStatus, networkStop, networkCancel]), +) + +const secretsStatus = Command.make( + "status", + { + name: Argument.String("name"), + json: jsonFlag, + }, + Effect.fn("Cli.secretsStatus")(function* ({ name, json }) { + const relay = yield* RelayClient.Service + yield* ensureCliRelay() + const result = yield* relay.authStatus({ name }) + if (json) { + yield* Console.log(JSON.stringify(result, null, 2)) + return + } + yield* Console.log(`Secrets profile ${result.name}: slots=${result.slotCount} updatedAt=${result.updatedAt}`) + yield* Effect.forEach(result.slots, (slot) => Console.log(`- ${slot.ref} sources=${slot.sources.join(",")} expired=${slot.expired}${slot.expiresAt ? ` expiresAt=${slot.expiresAt}` : ""}`)) + }), +).pipe(Command.withDescription("Show secret profile metadata without revealing values")) + +const secretsRefresh = Command.make( + "refresh", + { + name: Argument.String("name"), + session: sessionFlag(), + urlFilter: Flag.String("url").pipe(Flag.optional, Flag.withDescription("Observe credentials only on matching request URLs")), + timeoutMs: Flag.Int("timeout-ms").pipe(Flag.optional, Flag.withDescription("Page reload timeout, defaults to 30000")), + json: jsonFlag, + }, + Effect.fn("Cli.secretsRefresh")(function* ({ name, session, urlFilter, timeoutMs, json }) { + const relay = yield* RelayClient.Service + yield* ensureCliRelayAndExtension() + const sessionId = yield* networkSession(session) + const result = yield* relay.authRefresh({ + sessionId, + name, + ...(Option.isSome(urlFilter) ? { urlFilter: urlFilter.value } : {}), + ...(Option.isSome(timeoutMs) ? { timeoutMs: timeoutMs.value } : {}), + }) + yield* Console.log(json ? JSON.stringify(result, null, 2) : `Secrets profile ${name} refreshed: observed=${result.observedSecretRefs.length} changed=${result.updatedSecretRefs.length}`) + }), +).pipe(Command.withDescription("Reload a session page and refresh a profile while preserving stable references")) + +const secretsRun = Command.make( + "run", + { + name: Argument.String("name"), + command: Argument.String("command").pipe(Argument.variadic({ min: 1 })), + cwd: Flag.String("cwd").pipe(Flag.optional, Flag.withDescription("Child process working directory")), + timeoutMs: Flag.Int("timeout-ms").pipe(Flag.optional, Flag.withDescription("Child timeout in milliseconds, defaults to 120000")), + }, + Effect.fn("Cli.secretsRun")(function* ({ name, command, cwd, timeoutMs }) { + const relay = yield* RelayClient.Service + yield* ensureCliRelay() + const [executable, ...args] = decodeCliOperands(command) + if (!executable) return yield* Effect.fail(new Error("secrets run requires a command after --")) + const result = yield* relay.authRun({ + name, + command: executable, + args, + cwd: path.resolve(Option.getOrElse(cwd, () => process.cwd())), + ...(Option.isSome(timeoutMs) ? { timeoutMs: timeoutMs.value } : {}), + }) + yield* Effect.sync(() => { + if (result.stdout) process.stdout.write(result.stdout) + if (result.stderr) process.stderr.write(result.stderr) + if (result.stdoutTruncated || result.stderrTruncated) process.stderr.write("\nOpenCode Browser truncated child output.\n") + if (result.exitCode !== 0) process.exitCode = result.exitCode + }) + }), +).pipe(Command.withDescription("Run a command with profile values injected as BC_SECRET_* environment variables")) + +const secrets = Command.make("secrets").pipe( + Command.withDescription("Inspect, refresh, and use captured credentials without revealing their values"), + Command.withSubcommands([secretsStatus, secretsRefresh, secretsRun]), +) + +const journal = Command.make( + "journal", + { + session: sessionFlag("Show the journal for this OpenCode Browser session id"), + limit: Flag.Int("limit").pipe(Flag.optional, Flag.withDescription("Number of most recent entries to show, defaults to 20")), + json: jsonFlag, + }, + Effect.fn("Cli.journal")(function* ({ session, limit, json }) { + const sessionId = yield* networkSession(session) + const entries = yield* Effect.tryPromise({ + try: () => readJournalEntries({ baseDir: defaultJournalBaseDir(), sessionId, limit: Option.getOrUndefined(limit) ?? 20 }), + catch: (cause) => new Error(`read session journal for ${sessionId}`, { cause }), + }) + if (json) { + yield* Console.log(JSON.stringify({ session: sessionId, entries }, null, 2)) + return + } + if (entries.length === 0) { + yield* Console.log(`No journal entries for session ${sessionId}`) + return + } + yield* Console.log(`Journal for ${sessionId} (last ${entries.length}):`) + yield* Effect.forEach(entries, (entry) => { + return Console.log(formatJournalEntry(entry)) + }) + }), +).pipe(Command.withDescription("Show what agents did in a OpenCode Browser session")) + +const doctor = Command.make( + "doctor", + { + json: jsonFlag, + }, + Effect.fn("Cli.doctor")(function* ({ json }) { + const report = yield* createDoctorReport({ packageRoot }) + if (json) { + yield* Console.log(JSON.stringify(report, null, 2)) + } else { + yield* Console.log(formatDoctorReport(report)) + } + if (report.status === "fail") { + yield* failExit + } + }), +).pipe(Command.withDescription("Diagnose the local OpenCode Browser install and runtime")) + +const skill = Command.make( + "skill", + {}, + Effect.fn("Cli.skill")(function* () { + const fs = yield* FileSystem.FileSystem + const text = yield* fs.readFileString(path.join(packageRoot, "skills", "browse", "SKILL.md")).pipe( + Effect.mapError((cause) => new Error("read opencode-browser skill", { cause })), + ) + yield* Console.log(text.trimEnd()) + }), +).pipe(Command.withDescription("Print the OpenCode Browser agent skill text")) + +const tabsCleanup = Command.make( + "cleanup", + { + idleMinutes: Flag.Int("idle-minutes").pipe( + Flag.optional, + Flag.withDescription("Close agent tabs idle at least this long; 0 closes every eligible agent tab (default: the extension's setting, 10)"), + ), + json: jsonFlag, + }, + Effect.fn("Cli.tabsCleanup")(function* ({ idleMinutes, json }) { + const relay = yield* RelayClient.Service + yield* ensureCliRelay() + const result = yield* relay.tabsCleanup(Option.getOrUndefined(idleMinutes)) + if (json) return yield* Console.log(JSON.stringify(result, null, 2)) + if (!result.closed.length) return yield* Console.log("No idle agent tabs to close.") + for (const tab of result.closed) yield* Console.log(`Closed ${tab.title} (idle ${tab.idleMinutes}m)`) + }), +).pipe(Command.withDescription("Close tabs agents opened that nobody has used for a while")) + +const tabs = Command.make("tabs").pipe( + Command.withDescription("Manage the tabs agents open"), + Command.withSubcommands([tabsCleanup]), +) + +const mcp = Command.make( + "mcp", + {}, + Effect.fn("Cli.mcp")(function* () { + yield* runMcpServer + }), +).pipe(Command.withDescription("Run the OpenCode Browser MCP server over stdio")) + +export const opencodeBrowser = Command.make("opencode-browser").pipe( + Command.withDescription("Control the user's existing browser through the OpenCode Browser extension"), + Command.withSubcommands([serve, relay, execute, session, tabs, status, network, secrets, recording, flightRecorder, journal, doctor, skill, mcp]), +) + +const mainLayer = Layer.mergeAll(RelayClient.layerFetch, SessionStore.layer).pipe( + // CLI commands consume FileSystem directly in addition to SessionStore, so + // Node services intentionally remain exposed downstream. + Layer.provideMerge(NodeServices.layer), +) + +Command.runWith(opencodeBrowser, { version: opencodeBrowserVersion })(normalizeCliArguments(process.argv.slice(2))).pipe( + Effect.catchTags({ + "RelayClient.RelayRejected": (error) => Console.error(error.message).pipe(Effect.andThen(failExit)), + "RelayClient.RelayUnreachable": (error) => Console.error(error.message).pipe(Effect.andThen(failExit)), + "RelayClient.RelayDecodeFailed": (error) => Console.error(error.message).pipe(Effect.andThen(failExit)), + }), + Effect.provide(mainLayer), + NodeRuntime.runMain, +) diff --git a/packages/browser-extension/cli/src/demonstration.ts b/packages/browser-extension/cli/src/demonstration.ts new file mode 100644 index 00000000000..f8573cb7c0d --- /dev/null +++ b/packages/browser-extension/cli/src/demonstration.ts @@ -0,0 +1,246 @@ +import { Match, Schema } from "effect" +import type { Frame, Page } from "patchright-core" + +const DemonstrationStep = Schema.Union([ + Schema.Struct({ + kind: Schema.Literal("click"), + selector: Schema.String, + role: Schema.optionalKey(Schema.String), + name: Schema.optionalKey(Schema.String), + }), + Schema.Struct({ + kind: Schema.Literal("fill"), + selector: Schema.String, + value: Schema.String, + redacted: Schema.optionalKey(Schema.Boolean), + }), + Schema.Struct({ + kind: Schema.Literal("check"), + selector: Schema.String, + checked: Schema.Boolean, + }), + Schema.Struct({ + kind: Schema.Literal("select"), + selector: Schema.String, + value: Schema.String, + }), + Schema.Struct({ + kind: Schema.Literal("navigation"), + url: Schema.String, + }), +]) + +export type DemonstrationStep = typeof DemonstrationStep.Type + +export type DemonstrationResult = { + readonly startedUrl: string + readonly endedUrl: string + readonly steps: readonly DemonstrationStep[] + readonly code: string +} + +type PageRecorderState = { + active?: { readonly id: string; readonly startedUrl: string; readonly steps: DemonstrationStep[] } +} + +const demonstrationBindingName = "__opencodeBrowserDemonstration__" +const pageRecorders = new WeakMap() +let nextRecorder = 0 + +export async function startDemonstrationRecorder(page: Page): Promise<{ readonly stop: () => Promise }> { + const state = await recorderState(page) + if (state.active) throw new Error("A human demonstration is already being recorded on this page") + const id = `demo-${++nextRecorder}` + const active = { id, startedUrl: page.url(), steps: [] as DemonstrationStep[] } + state.active = active + const pendingInstalls = new Set>() + const install = (frame: Frame): Promise => { + const pending = frame.evaluate(installDemonstrationListeners, { recorderId: id }) + .then(() => {}, () => {}) + .finally(() => pendingInstalls.delete(pending)) + pendingInstalls.add(pending) + return pending + } + const onFrameNavigated = (frame: Frame) => { + if (frame === page.mainFrame()) appendStep(active.steps, { kind: "navigation", url: frame.url() }) + void install(frame) + } + page.on("framenavigated", onFrameNavigated) + await Promise.all(page.frames().map(install)) + let stopped = false + return { + stop: async () => { + if (stopped) throw new Error("Human demonstration recording has already stopped") + stopped = true + page.off("framenavigated", onFrameNavigated) + await Promise.all([...pendingInstalls]) + await Promise.all(page.frames().map((frame) => frame.evaluate(removeDemonstrationListeners, { recorderId: id }).catch(() => {}))) + if (state.active?.id === id) delete state.active + const steps = [...active.steps] + const endedUrl = page.isClosed() ? active.startedUrl : page.url() + return { + startedUrl: active.startedUrl, + endedUrl, + steps, + code: formatDemonstrationCode({ startedUrl: active.startedUrl, steps }), + } + }, + } +} + +export function formatDemonstrationCode(options: { + readonly startedUrl: string + readonly steps: readonly DemonstrationStep[] +}): string { + const lines = [ + `// Recorded from ${options.startedUrl}`, + ...options.steps.map((step) => + Match.value(step).pipe( + Match.when({ kind: "navigation" }, ({ url }) => `// Navigated to ${url}`), + Match.when({ kind: "click" }, ({ selector, role, name }) => { + const description = role && name ? ` // ${role} ${JSON.stringify(name)}` : "" + return `await page.locator(${JSON.stringify(selector)}).click()${description}` + }), + Match.when({ kind: "fill" }, ({ selector, value, redacted }) => + redacted + ? `// Fill ${JSON.stringify(selector)} from an approved secret source.` + : `await page.locator(${JSON.stringify(selector)}).fill(${JSON.stringify(value)})`), + Match.when({ kind: "check" }, ({ selector, checked }) => + `await page.locator(${JSON.stringify(selector)}).${checked ? "check" : "uncheck"}()`), + Match.when({ kind: "select" }, ({ selector, value }) => + `await page.locator(${JSON.stringify(selector)}).selectOption(${JSON.stringify(value)})`), + Match.exhaustive, + ), + ), + "return { url: page.url(), title: await page.title() }", + ] + return lines.join("\n") +} + +async function recorderState(page: Page): Promise { + const existing = pageRecorders.get(page) + if (existing) return existing + const state: PageRecorderState = {} + pageRecorders.set(page, state) + await page.exposeBinding(demonstrationBindingName, (_source, value: unknown) => { + const active = state.active + if (!active || !isDemonstrationStep(value)) return + appendStep(active.steps, value) + }) + return state +} + +function appendStep(steps: DemonstrationStep[], next: DemonstrationStep): void { + const previous = steps.at(-1) + if (next.kind === "fill" && previous?.kind === "fill" && previous.selector === next.selector) { + steps[steps.length - 1] = next + return + } + if (next.kind === "navigation" && previous?.kind === "navigation" && previous.url === next.url) return + steps.push(next) +} + +const isDemonstrationStep = Schema.is(DemonstrationStep) + +function installDemonstrationListeners(options: { readonly recorderId: string }): void { + type BrowserState = { readonly id: string; readonly cleanup: () => void } + const browserWindow = window as Window & { + __opencodeBrowserDemonstration__?: (step: DemonstrationStep) => unknown + __opencodeBrowserDemonstrationListeners__?: BrowserState + } + browserWindow.__opencodeBrowserDemonstrationListeners__?.cleanup() + const send = (step: DemonstrationStep) => { + const binding = browserWindow.__opencodeBrowserDemonstration__ + if (binding instanceof Function) void Promise.resolve(binding(step)).catch(() => {}) + } + const cssPath = (element: Element): string => { + const id = element.getAttribute("id") + if (id) return `#${CSS.escape(id)}` + for (const attribute of ["data-testid", "data-test", "name", "aria-label"]) { + const value = element.getAttribute(attribute) + if (!value) continue + const candidate = `[${attribute}="${CSS.escape(value)}"]` + if (document.querySelectorAll(candidate).length === 1) return candidate + } + const parent = element.parentElement + const tag = element.tagName.toLowerCase() + if (!parent) return tag + const siblings = Array.from(parent.children).filter((candidate) => candidate.tagName === element.tagName) + return `${cssPath(parent)} > ${tag}:nth-of-type(${siblings.indexOf(element) + 1})` + } + const nameFor = (element: Element): string | undefined => { + const ariaLabel = element.getAttribute("aria-label")?.trim() + if (ariaLabel) return ariaLabel + const labelledBy = element.getAttribute("aria-labelledby") + if (labelledBy) { + const text = labelledBy.split(/\s+/).map((id) => document.getElementById(id)?.textContent ?? "").join(" ").replace(/\s+/g, " ").trim() + if (text) return text + } + const text = element.textContent?.replace(/\s+/g, " ").trim() + return text ? text.slice(0, 120) : undefined + } + const roleFor = (element: Element): string | undefined => { + const explicit = element.getAttribute("role") + if (explicit) return explicit + if (element instanceof HTMLButtonElement) return "button" + if (element instanceof HTMLAnchorElement) return "link" + if (element instanceof HTMLInputElement) { + if (element.type === "checkbox") return "checkbox" + if (element.type === "radio") return "radio" + return "textbox" + } + if (element instanceof HTMLSelectElement) return "combobox" + if (element instanceof HTMLTextAreaElement || (element instanceof HTMLElement && element.isContentEditable)) return "textbox" + return undefined + } + const onClick = (event: Event) => { + const target = event.composedPath().find((candidate) => candidate instanceof Element) as Element | undefined + const actionable = target?.closest("button, a[href], summary, [role='button'], [role='link'], [role='tab'], [role='menuitem']") + if (!actionable) return + const role = roleFor(actionable) + const name = nameFor(actionable) + send({ kind: "click", selector: cssPath(actionable), ...(role === undefined ? {} : { role }), ...(name === undefined ? {} : { name }) }) + } + const onInput = (event: Event) => { + const element = event.target + if (element instanceof HTMLInputElement) { + if (["checkbox", "radio", "file", "button", "submit", "reset"].includes(element.type)) return + send({ kind: "fill", selector: cssPath(element), value: element.type === "password" ? "" : element.value, ...(element.type === "password" ? { redacted: true } : {}) }) + } else if (element instanceof HTMLTextAreaElement) { + send({ kind: "fill", selector: cssPath(element), value: element.value }) + } else if (element instanceof HTMLElement && element.isContentEditable) { + send({ kind: "fill", selector: cssPath(element), value: element.innerText }) + } + } + const onChange = (event: Event) => { + const element = event.target + if (element instanceof HTMLInputElement && (element.type === "checkbox" || element.type === "radio")) { + send({ kind: "check", selector: cssPath(element), checked: element.checked }) + } else if (element instanceof HTMLSelectElement) { + send({ kind: "select", selector: cssPath(element), value: element.value }) + } else { + onInput(event) + } + } + document.addEventListener("click", onClick, true) + document.addEventListener("input", onInput, true) + document.addEventListener("change", onChange, true) + const cleanup = () => { + document.removeEventListener("click", onClick, true) + document.removeEventListener("input", onInput, true) + document.removeEventListener("change", onChange, true) + if (browserWindow.__opencodeBrowserDemonstrationListeners__?.id === options.recorderId) { + delete browserWindow.__opencodeBrowserDemonstrationListeners__ + } + } + browserWindow.__opencodeBrowserDemonstrationListeners__ = { id: options.recorderId, cleanup } +} + +function removeDemonstrationListeners(options: { readonly recorderId: string }): void { + const browserWindow = window as Window & { + __opencodeBrowserDemonstrationListeners__?: { readonly id: string; readonly cleanup: () => void } + } + if (browserWindow.__opencodeBrowserDemonstrationListeners__?.id === options.recorderId) { + browserWindow.__opencodeBrowserDemonstrationListeners__.cleanup() + } +} diff --git a/packages/browser-extension/cli/src/doctor.ts b/packages/browser-extension/cli/src/doctor.ts new file mode 100644 index 00000000000..ffac754ffe1 --- /dev/null +++ b/packages/browser-extension/cli/src/doctor.ts @@ -0,0 +1,615 @@ +import { Effect, FileSystem, Path, Schema } from "effect" +import * as RelayClient from "./relay-client.ts" +import { relayBuildProblem } from "./relay-lifecycle.ts" +import type { ExtensionStatus, RelayVersion, SessionSummary, TargetSummary } from "./relay-schema.ts" +import { extensionProtocolVersion } from "./protocol.ts" +import * as SessionStore from "./session-store.ts" +import { opencodeBrowserBuildId, opencodeBrowserVersion } from "./version.ts" + +/** + * Read-only local install and runtime diagnostics. Pure report construction + * over RelayClient/SessionStore/FileSystem probes; never fails, degrades to + * warn/fail checks instead. + */ + +export type ProbeResult = + | { readonly ok: true; readonly value: T } + | { readonly ok: false; readonly error: string } + +const PackageMetadata = Schema.Struct({ + name: Schema.String, + version: Schema.String, + bin: Schema.optionalKey(Schema.Record(Schema.String, Schema.String)), +}) + +const ManifestVersion = Schema.Struct({ + version: Schema.String, +}) +const bundledExtensionManifestPath = "extension/manifest.json" + +type PackageInfo = { + readonly name: string + readonly version: string + readonly bin: { + readonly opencodeBrowser: string | null + readonly opencodeBrowserMcp: string | null + } +} + +type DoctorArtifact = { + readonly path: string + readonly exists: boolean + readonly version?: string +} + +export type DoctorCheckStatus = "ok" | "warn" | "fail" + +export type DoctorCheck = { + readonly id: string + readonly label: string + readonly status: DoctorCheckStatus + readonly message: string +} + +export type DoctorReport = { + readonly status: DoctorCheckStatus + readonly endpoint: string + readonly cli: { + readonly version: string + readonly buildId: string + } + readonly package: { + readonly path: string + readonly name: string | null + readonly version: string | null + readonly bin: { + readonly opencodeBrowser: boolean + readonly opencodeBrowserMcp: boolean + } + readonly error: string | null + } + readonly relay: { + readonly reachable: boolean + readonly version: string | null + readonly buildId: string | null + readonly buildMatches: boolean | null + readonly error: string | null + } + readonly extension: { + readonly connected: boolean | null + readonly version: string | null + readonly expectedVersion: string | null + readonly versionMatches: boolean | null + readonly protocolVersion: number | null + readonly expectedProtocolVersion: number + readonly protocolCompatible: boolean | null + readonly protocolLegacy: boolean | null + readonly rejectedConnections: number | null + readonly error: string | null + } + readonly targets: { + readonly active: number | null + readonly child: number | null + readonly relayOwned: readonly TargetSummary[] + readonly unhealthy: readonly TargetSummary[] + readonly all: readonly TargetSummary[] + readonly error: string | null + } + readonly sessions: { + readonly current: string | null + readonly staleCurrent: boolean + readonly possibleLeaked: readonly SessionSummary[] + readonly all: readonly SessionSummary[] + readonly error: string | null + } + readonly artifacts: readonly DoctorArtifact[] + readonly checks: readonly DoctorCheck[] + readonly recommendations: readonly string[] +} + +const probe = (effect: Effect.Effect): Effect.Effect> => + effect.pipe( + Effect.match({ + onFailure: (error) => ({ ok: false, error: errorMessage(error) } as const), + onSuccess: (value) => ({ ok: true, value } as const), + }), + ) + +const errorMessage = (error: unknown): string => { + if (error instanceof Error) { + return error.message + } + return String(error) +} + +export const createDoctorReport = Effect.fn("Doctor.createReport")(function* (options: { + readonly packageRoot: string +}) { + const relay = yield* RelayClient.Service + const store = yield* SessionStore.Service + const fs = yield* FileSystem.FileSystem + const path = yield* Path.Path + + const readJsonFile = (relativePath: string, schema: Schema.ConstraintDecoder): Effect.Effect => + fs.readFileString(path.join(options.packageRoot, relativePath)).pipe( + Effect.mapError((cause) => new Error(`read ${relativePath}: ${cause.reason.message}`)), + Effect.flatMap((text) => + Effect.try({ + try: () => JSON.parse(text) as unknown, + catch: () => new Error(`parse ${relativePath}: invalid JSON`), + }) + ), + Effect.flatMap((value) => + Schema.decodeUnknownEffect(schema)(value).pipe( + Effect.mapError((cause) => new Error(`decode ${relativePath}: ${cause.message}`)), + ) + ), + ) + + const readPackageInfo: Effect.Effect = readJsonFile("package.json", PackageMetadata).pipe( + Effect.map((metadata) => ({ + name: metadata.name, + version: metadata.version, + bin: { + opencodeBrowser: metadata.bin?.["opencode-browser"] ?? null, + opencodeBrowserMcp: metadata.bin?.["opencode-browser-mcp"] ?? null, + }, + })), + ) + + const readManifestVersion = (relativePath: string): Effect.Effect => + readJsonFile(relativePath, ManifestVersion).pipe(Effect.map((manifest) => manifest.version)) + + const fileExists = (relativePath: string): Effect.Effect => + fs.exists(path.join(options.packageRoot, relativePath)).pipe( + Effect.orElseSucceed(() => false), + ) + + const [packageResult, bundledManifestVersion, distCliExists, distMcpExists, extensionDistManifestExists, currentResult] = yield* Effect.all([ + probe(readPackageInfo), + probe(readManifestVersion(bundledExtensionManifestPath)), + fileExists("dist/cli.mjs"), + fileExists("dist/cli.mjs"), + fileExists(bundledExtensionManifestPath), + probe(store.read), + ]) + const relayResult = yield* probe(relay.version) + const relayBuildMatches = relayResult.ok + ? relayResult.value.buildId + ? relayBuildProblem(relayResult.value, opencodeBrowserBuildId) === undefined + : null + : null + const [extensionResult, targetsResult, sessionsResult] = relayResult.ok + ? yield* Effect.all([ + probe(relay.extensionStatus), + probe(relay.targets), + probe(relay.sessions), + ]) + : [ + { ok: false, error: relayResult.error } satisfies ProbeResult, + { ok: false, error: relayResult.error } satisfies ProbeResult, + { ok: false, error: relayResult.error } satisfies ProbeResult, + ] + const expectedVersion = bundledManifestVersion.ok ? bundledManifestVersion.value : null + const extensionVersion = extensionResult.ok ? extensionResult.value.version : null + const extensionVersionMatches = extensionResult.ok && extensionVersion && expectedVersion ? extensionVersion === expectedVersion : null + const current = currentResult.ok ? currentResult.value ?? null : null + const targets = targetsResult.ok ? targetsResult.value : [] + const sessions = sessionsResult.ok ? sessionsResult.value : [] + const staleCurrent = Boolean(current && sessionsResult.ok && !sessions.some((session) => { + return session.id === current + })) + const relayOwnedTargets = targets.filter((target) => { + return target.owner === "relay" + }) + const unhealthyTargets = targets.filter((target) => { + return target.crashed === true || target.url.startsWith("chrome-error://") + }) + const possibleLeakedSessions = sessions.filter((session) => { + return session.connected && session.id !== current + }) + const artifacts: readonly DoctorArtifact[] = [ + { path: "dist/cli.mjs", exists: distCliExists && distMcpExists }, + { + path: bundledExtensionManifestPath, + exists: extensionDistManifestExists, + ...(bundledManifestVersion.ok ? { version: bundledManifestVersion.value } : {}), + }, + ] + const checks = buildDoctorChecks({ + packageResult, + relayResult, + extensionResult, + bundledManifestVersion, + artifacts, + currentResult, + staleCurrent, + relayOwnedTargets, + unhealthyTargets, + possibleLeakedSessions, + targetsResult, + sessionsResult, + }) + const report: DoctorReport = { + status: summarizeCheckStatus(checks), + endpoint: relay.endpoint, + cli: { version: opencodeBrowserVersion, buildId: opencodeBrowserBuildId }, + package: { + path: path.join(options.packageRoot, "package.json"), + name: packageResult.ok ? packageResult.value.name : null, + version: packageResult.ok ? packageResult.value.version : null, + bin: { + opencodeBrowser: packageResult.ok ? Boolean(packageResult.value.bin.opencodeBrowser) : false, + opencodeBrowserMcp: packageResult.ok ? Boolean(packageResult.value.bin.opencodeBrowserMcp) : false, + }, + error: packageResult.ok ? null : packageResult.error, + }, + relay: { + reachable: relayResult.ok, + version: relayResult.ok ? relayResult.value.version : null, + buildId: relayResult.ok ? relayResult.value.buildId ?? null : null, + buildMatches: relayBuildMatches, + error: relayResult.ok ? null : relayResult.error, + }, + extension: { + connected: extensionResult.ok ? extensionResult.value.connected : null, + version: extensionVersion, + expectedVersion, + versionMatches: extensionVersionMatches, + protocolVersion: extensionResult.ok ? extensionResult.value.protocolVersion ?? null : null, + expectedProtocolVersion: extensionProtocolVersion, + protocolCompatible: extensionResult.ok ? extensionResult.value.protocolCompatible ?? null : null, + protocolLegacy: extensionResult.ok ? extensionResult.value.protocolLegacy ?? null : null, + rejectedConnections: extensionResult.ok ? extensionResult.value.rejectedConnections ?? null : null, + error: extensionResult.ok ? null : extensionResult.error, + }, + targets: { + active: extensionResult.ok ? extensionResult.value.activeTargets : null, + child: extensionResult.ok ? extensionResult.value.childTargets ?? null : null, + relayOwned: relayOwnedTargets, + unhealthy: unhealthyTargets, + all: targets, + error: targetsResult.ok ? null : targetsResult.error, + }, + sessions: { + current, + staleCurrent, + possibleLeaked: possibleLeakedSessions, + all: sessions, + error: sessionsResult.ok ? currentResult.ok ? null : currentResult.error : sessionsResult.error, + }, + artifacts, + checks, + recommendations: buildDoctorRecommendations({ + relayResult, + extensionResult, + artifacts, + staleCurrent, + current, + unhealthyTargets, + }), + } + return report +}) + +function buildDoctorChecks(options: { + readonly packageResult: ProbeResult + readonly relayResult: ProbeResult + readonly extensionResult: ProbeResult + readonly bundledManifestVersion: ProbeResult + readonly artifacts: readonly DoctorArtifact[] + readonly currentResult: ProbeResult + readonly staleCurrent: boolean + readonly relayOwnedTargets: readonly TargetSummary[] + readonly unhealthyTargets: readonly TargetSummary[] + readonly possibleLeakedSessions: readonly SessionSummary[] + readonly targetsResult: ProbeResult + readonly sessionsResult: ProbeResult +}): readonly DoctorCheck[] { + const packageBinChecks: readonly DoctorCheck[] = options.packageResult.ok + ? [ + { + id: "bin-opencode-browser", + label: "opencode-browser bin", + status: options.packageResult.value.bin.opencodeBrowser ? "ok" : "fail", + message: options.packageResult.value.bin.opencodeBrowser ?? "missing from package.json bin", + }, + { + id: "bin-opencode-browser-mcp", + label: "opencode-browser-mcp bin", + status: options.packageResult.value.bin.opencodeBrowserMcp ? "ok" : "warn", + message: options.packageResult.value.bin.opencodeBrowserMcp ?? "missing from package.json bin", + }, + ] + : [] + const artifactChecks = options.artifacts.map((artifact): DoctorCheck => { + return { + id: `artifact-${artifact.path}`, + label: artifact.path, + status: artifact.exists ? "ok" : "warn", + message: artifact.exists ? artifact.version ? `exists (${artifact.version})` : "exists" : "missing; prepare a fresh runtime", + } + }) + return [ + { + id: "package-metadata", + label: "package metadata", + status: options.packageResult.ok ? "ok" : "fail", + message: options.packageResult.ok ? `${options.packageResult.value.name} ${options.packageResult.value.version}` : options.packageResult.error, + }, + ...packageBinChecks, + { + id: "relay-http", + label: "relay HTTP endpoint", + status: options.relayResult.ok ? "ok" : "fail", + message: options.relayResult.ok ? `reachable (${options.relayResult.value.version})` : options.relayResult.error, + }, + relayBuildCheck({ relayResult: options.relayResult, cliBuildId: opencodeBrowserBuildId }), + { + id: "extension-connected", + label: "extension connection", + status: options.extensionResult.ok && options.extensionResult.value.connected ? "ok" : "fail", + message: options.extensionResult.ok ? options.extensionResult.value.connected ? `connected${options.extensionResult.value.version ? ` (${options.extensionResult.value.version})` : ""}` : "disconnected" : options.extensionResult.error, + }, + extensionVersionCheck({ + extensionResult: options.extensionResult, + bundledManifestVersion: options.bundledManifestVersion, + }), + extensionProtocolCheck(options.extensionResult), + ...(options.extensionResult.ok && options.extensionResult.value.rejectedConnections !== undefined ? [{ + id: "extension-connection-conflicts", + label: "competing browser connections", + status: options.extensionResult.value.rejectedConnections > 0 ? "warn" as const : "ok" as const, + message: options.extensionResult.value.rejectedConnections > 0 + ? `${options.extensionResult.value.rejectedConnections} connection attempt(s) rejected; the active browser connection was preserved` + : "none observed on this connection", + }] : []), + { + id: "targets-readable", + label: "targets readable", + status: options.targetsResult.ok ? "ok" : "fail", + message: options.targetsResult.ok ? `${options.targetsResult.value.length} active root target(s)` : options.targetsResult.error, + }, + unhealthyTargetsCheck({ + targetsResult: options.targetsResult, + unhealthyTargets: options.unhealthyTargets, + }), + { + id: "sessions-readable", + label: "sessions readable", + status: options.sessionsResult.ok ? "ok" : "fail", + message: options.sessionsResult.ok ? `${options.sessionsResult.value.length} session(s)` : options.sessionsResult.error, + }, + { + id: "current-session-file", + label: "current session file", + status: options.currentResult.ok ? "ok" : "warn", + message: options.currentResult.ok ? options.currentResult.value ?? "none" : options.currentResult.error, + }, + { + id: "current-session-stale", + label: "current session membership", + status: options.staleCurrent ? "warn" : "ok", + message: options.staleCurrent ? "current session is not present in relay sessions" : "current session is valid or unset", + }, + { + id: "relay-owned-targets", + label: "relay-owned active targets", + status: "ok", + message: options.relayOwnedTargets.length ? `${options.relayOwnedTargets.length} persistent relay-owned target(s)` : "none", + }, + { + id: "possible-leaked-sessions", + label: "connected non-current sessions", + status: "ok", + message: options.possibleLeakedSessions.length ? `${options.possibleLeakedSessions.length} connected non-current session(s)` : "none", + }, + ...artifactChecks, + ] +} + +const makeDoctorCheck = (id: string, label: string) => (status: DoctorCheckStatus, message: string): DoctorCheck => ({ + id, + label, + status, + message, +}) + +export function unhealthyTargetsCheck(options: { + readonly targetsResult: ProbeResult + readonly unhealthyTargets: readonly TargetSummary[] +}): DoctorCheck { + const check = makeDoctorCheck("unhealthy-targets", "crashed or browser-error targets") + if (!options.targetsResult.ok) { + return check("warn", `target health unknown: ${options.targetsResult.error}`) + } + return check( + options.unhealthyTargets.length ? "warn" : "ok", + options.unhealthyTargets.length ? `${options.unhealthyTargets.length} unhealthy target(s)` : "none", + ) +} + +export function relayBuildCheck(options: { + readonly relayResult: ProbeResult + readonly cliBuildId: string +}): DoctorCheck { + const check = makeDoctorCheck("relay-build", "relay build") + if (!options.relayResult.ok) { + return check("warn", "relay unreachable; cannot compare builds") + } + const relayBuildId = options.relayResult.value.buildId + if (!relayBuildId) { + return check("warn", "running relay does not report a build id") + } + const matches = relayBuildId === options.cliBuildId + return check( + matches ? "ok" : "warn", + matches + ? `matches CLI build (${options.cliBuildId})` + : `runtime ${relayBuildId} does not match CLI ${options.cliBuildId}`, + ) +} + +function extensionVersionCheck(options: { + readonly extensionResult: ProbeResult + readonly bundledManifestVersion: ProbeResult +}): DoctorCheck { + const check = makeDoctorCheck("extension-version", "extension version") + if (!options.extensionResult.ok) { + return check("warn", options.extensionResult.error) + } + if (!options.extensionResult.value.connected) { + return check("warn", "extension disconnected; cannot compare runtime version") + } + if (!options.bundledManifestVersion.ok) { + return check("warn", `could not read ${bundledExtensionManifestPath}: ${options.bundledManifestVersion.error}`) + } + const runtimeVersion = options.extensionResult.value.version + if (!runtimeVersion) { + return check("warn", "extension did not report a version") + } + return check( + "ok", + runtimeVersion === options.bundledManifestVersion.value + ? `matches bundled extension (${options.bundledManifestVersion.value})` + : `runtime ${runtimeVersion} differs from bundled ${options.bundledManifestVersion.value}; protocol compatibility determines support`, + ) +} + +export function extensionProtocolCheck(extensionResult: ProbeResult): DoctorCheck { + const check = makeDoctorCheck("extension-protocol", "extension protocol") + if (!extensionResult.ok) { + return check("warn", extensionResult.error) + } + const protocolVersion = extensionResult.value.protocolVersion + const protocolCompatible = extensionResult.value.protocolCompatible + if (protocolCompatible === false) { + return check("fail", `runtime ${protocolVersion ?? "unknown"} is incompatible with relay ${extensionProtocolVersion}`) + } + if (extensionResult.value.protocolLegacy === true) { + return check("warn", `legacy extension does not report its protocol; relay infers ${protocolVersion ?? "unknown"}`) + } + if (protocolVersion === undefined || protocolVersion === null) { + return check("warn", "extension protocol is unknown") + } + return check("ok", `runtime ${protocolVersion} is compatible with relay ${extensionProtocolVersion}`) +} + +function buildDoctorRecommendations(options: { + readonly relayResult: ProbeResult + readonly extensionResult: ProbeResult + readonly artifacts: readonly DoctorArtifact[] + readonly staleCurrent: boolean + readonly current: string | null + readonly unhealthyTargets: readonly TargetSummary[] +}): readonly string[] { + const relayRecommendations = options.relayResult.ok ? [] : [ + "Run a relay-backed command to start the detached relay automatically; use `opencode-browser serve` only for foreground debugging.", + ] + const relayBuildRecommendations = options.relayResult.ok + ? [relayBuildProblem(options.relayResult.value)].filter((message) => message !== undefined) + : [] + const extensionRecommendations = options.relayResult.ok && options.extensionResult.ok && !options.extensionResult.value.connected + ? options.extensionResult.value.protocolCompatible === false + ? ["Update the OpenCode Browser extension or npm package so their extension protocols are compatible."] + : ["Run `npx opencode-browser-cli install`, and install OpenCode Browser from the Chrome Web Store (or load the unpacked extension it copies)."] + : [] + const artifactRecommendations = options.artifacts.some((artifact) => { + return !artifact.exists + }) ? ["Prepare and select a fresh validated runtime with `pnpm runtime:prepare` / `pnpm runtime:select`; do not rebuild the active installation."] : [] + const connectionConflictRecommendations = options.extensionResult.ok && (options.extensionResult.value.rejectedConnections ?? 0) > 0 + ? ["Keep OpenCode Browser enabled in one browser/profile. To switch, disable it in the current browser before connecting the other; new sessions do not change the active browser."] + : [] + const staleSessionRecommendations = options.staleCurrent && options.current ? [ + `Current session ${options.current} is stale; run \`opencode-browser session new\` or \`opencode-browser session use \` after the relay is running.`, + ] : [] + const unhealthyTargetRecommendations = options.unhealthyTargets.length ? [ + "A target is crashed or showing a browser error page. Run the owning session once to trigger relay-owned recovery, or reset/re-adopt a user-owned tab.", + ] : [] + return [ + ...relayRecommendations, + ...relayBuildRecommendations, + ...extensionRecommendations, + ...connectionConflictRecommendations, + ...artifactRecommendations, + ...staleSessionRecommendations, + ...unhealthyTargetRecommendations, + ] +} + +function summarizeCheckStatus(checks: readonly DoctorCheck[]): DoctorCheckStatus { + if (checks.some((check) => { + return check.status === "fail" + })) { + return "fail" + } + if (checks.some((check) => { + return check.status === "warn" + })) { + return "warn" + } + return "ok" +} + +export function formatDoctorReport(report: DoctorReport): string { + const lines: string[] = [ + "OpenCode Browser doctor", + `Status: ${report.status}`, + `Endpoint: ${report.endpoint}`, + `CLI: ${report.cli.version} (${report.cli.buildId})`, + `Package: ${report.package.name && report.package.version ? `${report.package.name} ${report.package.version}` : report.package.error ?? "unknown"}`, + `Relay: ${report.relay.reachable ? `reachable (${report.relay.version ?? "unknown"}, ${report.relay.buildId ?? "unknown build"})` : `unreachable (${report.relay.error ?? "unknown error"})`}`, + `Extension: ${formatExtensionSummary(report)}`, + `Targets: active=${formatNullableNumber(report.targets.active)} child=${formatNullableNumber(report.targets.child)} relay-owned=${report.targets.relayOwned.length} unhealthy=${report.targets.unhealthy.length}`, + `Sessions: current=${report.sessions.current ?? "none"} total=${report.sessions.all.length} connected=${report.sessions.all.filter((session) => { + return session.connected + }).length}`, + "", + "Checks:", + ...report.checks.map((check) => { + return `[${check.status}] ${check.label}: ${check.message}` + }), + ] + const targetLines = report.targets.relayOwned.map((target) => { + return `- ${formatTargetSummary(target)}` + }) + const unhealthyTargetLines = report.targets.unhealthy.map((target) => { + return `- ${formatTargetSummary(target)}` + }) + const sessionLines = report.sessions.possibleLeaked.map((session) => { + return `- ${session.id} ${session.pageUrl ?? "no page yet"}` + }) + const details = [ + ...(targetLines.length ? ["", "Relay-owned targets:", ...targetLines] : []), + ...(unhealthyTargetLines.length ? ["", "Unhealthy targets:", ...unhealthyTargetLines] : []), + ...(sessionLines.length ? ["", "Connected non-current sessions:", ...sessionLines] : []), + ...(report.recommendations.length ? ["", "Next steps:", ...report.recommendations.map((item) => { + return `- ${item}` + })] : []), + ] + return [...lines, ...details].join("\n") +} + +function formatExtensionSummary(report: DoctorReport): string { + if (report.extension.connected === null) { + return `unknown (${report.extension.error ?? "relay unreachable"})` + } + const version = report.extension.version ? ` (${report.extension.version})` : "" + const protocol = report.extension.protocolVersion === null + ? "" + : `, protocol ${report.extension.protocolVersion} ${report.extension.protocolCompatible === false ? "incompatible" : "compatible"}` + const match = report.extension.versionMatches === null ? "" : report.extension.versionMatches ? ", matches bundled version" : ", differs from bundled version" + return `${report.extension.connected ? "connected" : "disconnected"}${version}${protocol}${match}` +} + +function formatNullableNumber(value: number | null): string { + return value === null ? "unknown" : String(value) +} + +export function formatTargetSummary(target: TargetSummary, options: { readonly includeSession?: boolean } = {}): string { + const tab = target.tabId === undefined ? "" : ` tab=${target.tabId}` + const session = options.includeSession && target.opencodeBrowserSessionId ? ` session=${target.opencodeBrowserSessionId}` : "" + const owner = target.owner ? ` owner=${target.owner}` : "" + const health = `${target.crashed ? " crashed=true" : ""}${target.protectedUi ? " protected-ui=true" : ""}` + return `${target.type} ${target.id}${tab}${session}${owner}${health} ${target.url || "about:blank"}` +} diff --git a/packages/browser-extension/cli/src/execute.ts b/packages/browser-extension/cli/src/execute.ts new file mode 100644 index 00000000000..f2fc2da9924 --- /dev/null +++ b/packages/browser-extension/cli/src/execute.ts @@ -0,0 +1,2176 @@ +import { Effect, Predicate, Schema } from "effect" +import { installPageReadTimeout } from "./page-read-timeout.ts" +import { chromium, errors, type Browser, type BrowserContext, type ConsoleMessage, type Frame, type Locator, type Page } from "patchright-core" +import * as acorn from "acorn" +import fs from "node:fs" +import path from "node:path" +import os from "node:os" +import crypto from "node:crypto" +import url from "node:url" +import util from "node:util" +import events from "node:events" +import stream from "node:stream" +import buffer from "node:buffer" +import http from "node:http" +import https from "node:https" +import zlib from "node:zlib" +import { + clearGhostCursorCallouts, + hideGhostCursor as hideGhostCursorOnPage, + setGhostCursorCaption, + setGhostCursorSpotlight, + showGhostCursor as showGhostCursorOnPage, + showGhostCursorCallout, + showGhostCursorKeys, + zoomGhostCursorCamera, + type GhostCursorCalloutOptions, + type GhostCursorCaptionOptions, + type GhostCursorClientOptions, + type GhostCursorSpotlightOptions, + type GhostCursorZoomOptions, +} from "./ghost-cursor.ts" +import type { HandoffOutcome } from "./handoff.ts" +import * as AuthProfile from "./auth-profile.ts" +import * as AuthenticatedOrigin from "./authenticated-origin.ts" +import * as NetworkCapture from "./network-capture.ts" +import { PageConsole } from "./page-console.ts" +import { tunePatchright } from "./patchright-tuning.ts" +import { AuthenticatedJsonOutcome, type AuthenticatedJsonRequest, type ExecuteAftermath, type ExecuteLogEntry, type ExecuteLogSummary, type ExecuteMedia } from "./relay-schema.ts" +import type { SessionTarget } from "./relay-types.ts" +import { executionContextFailureDiagnostic, runtimeFailureKind } from "./runtime-diagnostics.ts" +import { registerAriaSnapshotSelector } from "./aria-snapshot.ts" +import { + createAriaSnapshotHelper, + createSnapshotHelpers, + defaultAriaSnapshotTimeoutMs, + fillInput, + fillInputs, + invalidateSnapshotDocument, + screenshotWithLabels, + type AriaSnapshotHelper, + type InputField, + type InputTarget, + type ScreenshotWithLabelsOptions, + type ScreenshotWithLabelsResult, + type SnapshotHelper, + type SnapshotRefHelper, + type SnapshotRefRegistry, +} from "./snapshot.ts" +import { createScreenshotDiff, type ScreenshotDiffOptions, type ScreenshotDiffResult } from "./screenshot-diff.ts" +import { createWebMcpHelper, type WebMcpHelper } from "./webmcp.ts" +import { startDemonstrationRecorder, type DemonstrationResult } from "./demonstration.ts" + +export { createAriaSnapshotHelper, createSnapshotHelpers, defaultAriaSnapshotTimeoutMs, fillInputs } + +tunePatchright() + +const nodeModules = { fs, path, os, crypto, url, util, events, stream, buffer, http, https, zlib } +const nodeModuleAliases = Object.keys(nodeModules).join(", ") + +const playwrightCloseTimeoutMs = 2_000 +const playwrightConnectTimeoutMs = 15_000 +// CdpRuntime can spend two 3s observation windows replaying shared contexts. +// Leave room for that healthy reconnect path while bounding adopted setup. +const adoptedPageConnectTimeoutMs = 8_000 +const sessionPageHealthCheckTimeoutMs = 3_000 +const sessionPageHealthRetryDelayMs = 100 +const handoffPageContextTimeoutMs = 15_000 +const timedOut = Symbol("timed-out") +export const downloadCapabilityErrorMessage = "Downloads are unavailable in OpenCode Browser extension-backed tabs: Chromium blocks Browser.setDownloadBehavior and Page.setDownloadBehavior through chrome.debugger, so Playwright cannot retain an artifact for download.saveAs(). Fetch the response in the page and write the returned bytes with fs when the site exposes them." +const downloadGuardedPages = new WeakSet() +const downloadGuardedContexts = new WeakSet() +const viewportZoomGuardedPages = new WeakSet() + +class PlaywrightOperationError extends Schema.TaggedError()( + "Execute.PlaywrightOperationError", + { + message: Schema.String, + operation: Schema.String, + reason: Schema.Literals(["failed", "timeout"]), + cause: Schema.optionalKey(Schema.Defect()), + }, +) {} + +class SessionPageRecoveryError extends Schema.TaggedError()( + "Execute.SessionPageRecoveryError", + { + message: Schema.String, + reason: Schema.Literals(["adopted-unresponsive", "adopted-initialization-timeout", "owned-unresponsive", "close-failed", "target-unavailable"]), + cause: Schema.Defect(), + }, +) {} + +/** Internal signal: the relay-owned page is alive but Playwright's view of it is stale; reconnect before retrying. */ +class SessionPageRepairRequired extends Error { + constructor() { + super("Session page repair required") + } +} + +const unresponsivePageDiagnosis = (options: { readonly ownsPage: boolean; readonly repaired: boolean }): string => [ + `The ${options.ownsPage ? "relay-owned" : "adopted"} session page is unresponsive: the tab is open but its execution context did not answer automation within the health-check budget`, + options.repaired ? " even after reconnecting to the relay" : "", + ". The tab was kept and was not replaced. This usually means the page is mid-navigation or its main world is stalled for automation (for example, bot protection). ", + "Retry after the page settles, navigate the tab with page.goto(), open a fresh tab with context.newPage(), or release it with `opencode-browser session reset`.", +].join("") + +export class TargetSelectionError extends Schema.TaggedError()( + "Execute.TargetSelectionError", + { + message: Schema.String, + reason: Schema.Literals(["invalid", "not-found", "ambiguous"]), + }, +) {} + +export const runPlaywrightOperation = Effect.fn("Execute.playwrightOperation")((options: { + readonly label: string + readonly timeoutMs: number + readonly run: () => Promise +}): Effect.Effect => Effect.tryPromise({ + try: options.run, + catch: (cause) => new PlaywrightOperationError({ + message: cause instanceof Error ? cause.message : options.label, + operation: options.label, + reason: "failed", + cause, + }), + }).pipe( + Effect.timeoutOrElse({ + duration: options.timeoutMs, + orElse: () => Effect.fail(new PlaywrightOperationError({ + message: `${options.label} timed out after ${options.timeoutMs}ms`, + operation: options.label, + reason: "timeout", + })), + }), + ) +) + +const runSettledPlaywrightOperation = Effect.fn("Execute.settledPlaywrightOperation")((options: { + readonly label: string + readonly run: () => Promise +}): Effect.Effect => Effect.tryPromise({ + try: options.run, + catch: (cause) => new PlaywrightOperationError({ + message: cause instanceof Error ? cause.message : options.label, + operation: options.label, + reason: "failed", + cause, + }), +})) + +/** + * Decide what to do with a default page that failed or needs a health check. + * + * Only a relay-owned page with nothing left to lose (a crashed renderer, + * `about:blank`, or a `chrome-error://` document) is closed and recreated. Any + * other live page is kept: an unresponsive execution context is a symptom of + * Playwright's stale view of the tab or of the page itself, not proof that the + * tab is gone, and the tab may hold login or form state the user produced. + */ +export const recoverSessionPage = Effect.fn("Execute.recoverSessionPage")(function* (options: { + readonly ownsPage: boolean + readonly url: string + readonly timeoutMs: number + readonly healthCheck: () => Promise + readonly close: () => Promise + readonly crashed?: boolean + readonly repaired?: boolean +}) { + const healthFailure = yield* runPlaywrightOperation({ + label: "Session page health check", + timeoutMs: options.timeoutMs, + run: options.healthCheck, + }).pipe( + Effect.match({ + onFailure: (error) => error, + onSuccess: () => undefined, + }), + ) + if (!healthFailure) { + return "use" as const + } + if (!options.ownsPage) { + return yield* new SessionPageRecoveryError({ + message: unresponsivePageDiagnosis({ ownsPage: false, repaired: options.repaired === true }), + reason: "adopted-unresponsive", + cause: healthFailure, + }) + } + if (!isDisposableSessionPage(options)) { + if (options.repaired) { + return yield* new SessionPageRecoveryError({ + message: unresponsivePageDiagnosis({ ownsPage: true, repaired: true }), + reason: "owned-unresponsive", + cause: healthFailure, + }) + } + return "repair" as const + } + const closeFailure = yield* runPlaywrightOperation({ + label: "Close unhealthy session page", + timeoutMs: options.timeoutMs, + run: options.close, + }).pipe( + Effect.match({ + onFailure: (error) => error, + onSuccess: () => undefined, + }), + ) + if (closeFailure) { + return yield* new SessionPageRecoveryError({ + message: "The unhealthy relay-owned session page could not be closed. Run `opencode-browser session reset` before continuing.", + reason: "close-failed", + cause: closeFailure, + }) + } + return "recreate" as const +}) + +/** A relay-owned page whose document holds no user-produced state worth preserving. */ +export function isDisposableSessionPage(options: { readonly url: string; readonly crashed?: boolean }): boolean { + // Blank documents can hold setContent output, forms, and opener-written state. + // An unknown URL is not evidence that the document is safe to discard either. + return options.crashed === true || options.url.startsWith("chrome-error://") +} + +export async function waitForPageContext(options: { + readonly evaluate: () => Promise + readonly timeoutMs: number + readonly retryDelayMs?: number + readonly delay?: (milliseconds: number) => Promise +}): Promise { + const retryDelayMs = options.retryDelayMs ?? sessionPageHealthRetryDelayMs + const deadline = Date.now() + options.timeoutMs + let lastError: unknown + while (true) { + const remainingMs = deadline - Date.now() + if (remainingMs <= 0) break + try { + const result = await withTimeout(options.evaluate(), remainingMs) + if (result === timedOut) break + return + } catch (error) { + lastError = error + const kind = runtimeFailureKind(error) + if (kind !== "context-destroyed" && kind !== "context-missing") throw error + const retryInMs = Math.min(retryDelayMs, Math.max(0, deadline - Date.now())) + if (retryInMs > 0) await (options.delay ?? delay)(retryInMs) + } + } + throw lastError ?? new Error(`Execution context not available: it did not become available within ${options.timeoutMs}ms`) +} + +export async function finishHandoff(options: { + readonly outcome: HandoffOutcome + readonly message: string + readonly timeoutMs: number + readonly evaluate: () => Promise + readonly contextTimeoutMs?: number + readonly retryDelayMs?: number + readonly delay?: (milliseconds: number) => Promise +}): Promise { + if (options.outcome === "timeout") { + throw new Error(`Handoff timed out after ${options.timeoutMs}ms waiting for the user: ${options.message}`) + } + if (options.outcome !== "resolved") { + const targetEvent = options.outcome.reason === "target-crashed" ? "crashed" : "detached" + throw new Error(`Handoff cancelled because its target ${targetEvent}: ${options.message}`) + } + const contextTimeoutMs = options.contextTimeoutMs ?? sessionPageHealthCheckTimeoutMs + try { + await waitForPageContext({ + evaluate: options.evaluate, + timeoutMs: contextTimeoutMs, + ...(options.retryDelayMs === undefined ? {} : { retryDelayMs: options.retryDelayMs }), + ...(options.delay === undefined ? {} : { delay: options.delay }), + }) + } catch (error) { + const kind = runtimeFailureKind(error) + if (kind !== "context-destroyed" && kind !== "context-missing") throw error + // The user finished the handoff; only OpenCode Browser's view of the page is stale. Keep that + // distinction visible and let the next execute health-check and repair the same tab. + throw new Error( + `Handoff resolved (${options.message}), but the page execution context did not become available within ${contextTimeoutMs}ms: ${error instanceof Error ? error.message : String(error)}. The tab was kept; run a short follow-up execute so OpenCode Browser can re-check it.`, + { cause: error }, + ) + } +} + +export function isSessionPageConnected(options: { + readonly browserConnected: boolean + readonly pageUrl: string | null + readonly healthCheckRequired: boolean +}): boolean { + return options.browserConnected && options.pageUrl !== null && !options.healthCheckRequired +} + +function delay(milliseconds: number): Promise { + return new Promise((resolve) => setTimeout(resolve, milliseconds)) +} + +function withTimeout(promise: Promise, timeoutMs: number): Promise { + return new Promise((resolve, reject) => { + const timeout = setTimeout(() => resolve(timedOut), timeoutMs) + promise.then( + (value) => { + clearTimeout(timeout) + resolve(value) + }, + (error: unknown) => { + clearTimeout(timeout) + reject(error) + }, + ) + }) +} + +type SandboxGlobals = { + readonly browser: Browser + readonly context: BrowserContext + readonly page: Page + readonly state: Record + readonly modules: typeof nodeModules + readonly fillInput: (target: InputTarget, value: string) => Promise + readonly fillInputs: (page: Page, fields: ReadonlyArray) => Promise + readonly screenshotWithLabels: (options?: ScreenshotWithLabelsOptions) => Promise + readonly screenshotDiff: (options: ScreenshotDiffOptions) => Promise + readonly ariaSnapshot: AriaSnapshotHelper + readonly snapshot: SnapshotHelper + readonly ref: SnapshotRefHelper + readonly webmcp: WebMcpHelper + readonly showGhostCursor: (options?: ShowGhostCursorOptions) => Promise + readonly hideGhostCursor: (options?: HideGhostCursorOptions) => Promise + readonly ghostCursor: { + readonly show: (options?: ShowGhostCursorOptions) => Promise + readonly hide: (options?: HideGhostCursorOptions) => Promise + readonly caption: (title: string | null, options?: GhostCursorCaptionOptions & { readonly page?: Page }) => Promise + readonly clearCaption: (options?: { readonly page?: Page }) => Promise + readonly callout: (target: Locator | string, label: string, options?: GhostCursorCalloutOptions & { readonly page?: Page }) => Promise + readonly clearCallouts: (options?: { readonly page?: Page }) => Promise + readonly zoom: (target: Locator | string | { readonly x: number; readonly y: number } | null, options?: GhostCursorZoomOptions & { readonly page?: Page }) => Promise + readonly resetZoom: (options?: { readonly durationMs?: number; readonly page?: Page }) => Promise + readonly spotlight: (target: Locator | string | null, options?: GhostCursorSpotlightOptions & { readonly page?: Page }) => Promise + readonly clearSpotlight: (options?: { readonly page?: Page }) => Promise + readonly keys: (keys: string | readonly string[], label?: string, options?: { readonly page?: Page }) => Promise + } + readonly handoff: (message?: string, options?: HandoffCallOptions) => Promise + readonly demonstrate: (message?: string, options?: HandoffCallOptions) => Promise + readonly network: { + readonly start: (options?: NetworkCapture.NetworkCaptureOptions) => Promise + readonly status: () => NetworkCapture.NetworkCaptureStatus + readonly stop: (options?: NetworkCapture.NetworkCaptureStopOptions) => Promise + readonly cancel: () => Promise<{ readonly cancelled: boolean }> + } + readonly pageConsole: { + readonly start: (page?: Page) => Promise<{ readonly capturing: boolean }> + readonly stop: (page?: Page) => Promise<{ readonly capturing: boolean }> + } + readonly handoffTracker: { count: number } +} + +type HandoffCallOptions = { + readonly timeoutMs?: number + readonly page?: Page + readonly start?: () => unknown | Promise +} + +export type HandoffPageTarget = { + readonly targetId: string +} + +export type RequestHandoff = (options: { + readonly message: string + readonly timeoutMs: number + readonly target: HandoffPageTarget + readonly start?: () => unknown | Promise + readonly cancelStart?: () => Promise +}) => Promise + +const defaultHandoffTimeoutMs = 10 * 60 * 1_000 + +const defaultHandoffMessage = "Complete the requested task, then use the in-page continue control." + +type ShowGhostCursorOptions = GhostCursorClientOptions & { + readonly page?: Page +} + +type HideGhostCursorOptions = { + readonly page?: Page +} + +export type ExecuteTargetSelection = { + readonly urlIncludes?: string + readonly index?: number +} + +export const defaultPageClosedWarning = "The session default page was closed; created a new page. References to the old page in state are stale." +const defaultPageRecoveredWarning = "The session default page was unresponsive; created a new page. References to the old page in state are stale." +const defaultPageCrashedWarning = "The session default page target crashed; checking it before the next execute." +export const defaultPageRepairedWarning = "The session default page stopped answering automation; OpenCode Browser reconnected and re-resolved the same tab. References to the old page in state are stale." +const protectedExtensionUiWarning = "Chromium blocked protected extension UI, possibly a password manager. Ask the user to finish or dismiss it in the browser, then retry." +const protectedExtensionUiDiagnostic = "target/cross-extension-page" + +/** + * Playwright rewrites Chrome's "Cannot access a chrome-extension:// URL of + * different extension" rejection into a generic destroyed-context error and + * retries locators until they time out. When the relay reports that the tab is + * blocked by protected extension UI, those masked failures are the block. + */ +function isMaskedProtectedUiFailure(cause: unknown): boolean { + const kind = runtimeFailureKind(cause) + return kind === "context-destroyed" || kind === "context-missing" || kind === "timeout" +} +export const defaultPageReplacedWarning = "The session default page target was replaced; rebound to the same browser tab. References to the old page in state are stale." + +export const shouldCloseCurrentPageOnAdopt = (options: { + readonly hasCurrentPage: boolean + readonly ownsCurrentPage: boolean + readonly currentPageIsSelected: boolean + readonly currentPageIsClosed: boolean +}): boolean => { + return options.hasCurrentPage && options.ownsCurrentPage && !options.currentPageIsSelected && !options.currentPageIsClosed +} + +type ExecuteSandboxOptions = { + readonly endpointUrl: string + readonly sessionId?: string + readonly requestHandoff?: RequestHandoff + readonly onDefaultTargetChange?: (target: SessionTarget | undefined) => void + /** Health-check budget per attempt for a page that failed with an execution-context error. */ + readonly pageHealthCheckTimeoutMs?: number +} + +export type ExecuteResult = { + readonly text: string + readonly value?: unknown + readonly media?: readonly ExecuteMedia[] + readonly isError: boolean + readonly logs: readonly ExecuteLogEntry[] + readonly logSummary: ExecuteLogSummary + readonly warnings: readonly string[] + readonly diagnostic?: string + readonly aftermath?: ExecuteAftermath + readonly setupFailed?: true +} + +class ExecuteCodeError extends Error { + constructor( + readonly originalError: Error, + readonly logs: readonly ExecuteLogEntry[], + readonly logSummary: ExecuteLogSummary, + readonly aftermath?: ExecuteAftermath, + ) { + super(originalError.message, { cause: originalError }) + this.name = originalError.name + if (originalError.stack) { + this.stack = originalError.stack + } + } +} + +export type ExecuteOptions = { + readonly targetSelection?: ExecuteTargetSelection +} + +export class ExecuteSandbox { + private browser: Browser | undefined + private page: Page | undefined + private defaultPageTargetId: string | undefined + private ownsPage = false + private pageHealthCheckRequired = false + private pageCrashed = false + private pageProtectedUi = false + private pendingTargetRebind: "replaced" | "repaired" | undefined + private lastKnownNonBlankUrl: string | undefined + private recreatedFromClosedUrl: string | undefined + private explicitLightColorScheme = false + private readonly state: Record = {} + private readonly snapshotRefs: SnapshotRefRegistry = { selectors: new Map() } + private readonly networkCapture = new NetworkCapture.Recorder() + private pendingWarnings: string[] = [] + private boundPageListeners: { + readonly page: Page + readonly close: () => void + readonly navigate: (frame: Frame) => void + } | undefined + + constructor(readonly options: ExecuteSandboxOptions) {} + + execute(code: string, options: ExecuteOptions = {}): Effect.Effect { + return Effect.tryPromise({ + try: async () => { + const globals = await this.getGlobals(options) + const { result, logs, logSummary, aftermath } = await runUserCode({ code, globals }) + await this.networkCapture.settleForOutput() + const extracted = extractExecuteMedia(result) + const redactedValue = this.networkCapture.redactValue(extracted.value) + const jsonSafeResult = toJsonSafeValue(redactedValue) + const warnings = this.finalizeWarnings( + logSummary, + jsonSafeResult.serializable ? undefined : `Execute result could not be represented as JSON value: ${jsonSafeResult.reason}`, + ) + return { + text: stringifyResult(redactedValue), + ...(jsonSafeResult.serializable ? { value: jsonSafeResult.value } : {}), + ...(extracted.media.length > 0 ? { media: extracted.media } : {}), + isError: false, + logs: this.redactCaptureLogs(logs), + logSummary, + warnings, + aftermath: this.redactCaptureAftermath(aftermath), + } + }, + catch: (cause) => { + if (cause instanceof ExecuteCodeError) { + return cause + } + return cause instanceof Error ? cause : new Error("execute sandbox code", { cause }) + }, + }).pipe( + Effect.uninterruptible, + Effect.tapError(() => Effect.promise(() => this.networkCapture.settleForOutput())), + Effect.match({ + onFailure: (error): ExecuteResult => { + const logSummary = error instanceof ExecuteCodeError ? error.logSummary : emptyExecuteLogSummary() + const aftermath = error instanceof ExecuteCodeError ? error.aftermath : undefined + const diagnostic = error instanceof SessionPageRecoveryError + ? `session-page/${error.reason}` + : this.pageProtectedUi && isMaskedProtectedUiFailure(error) + ? protectedExtensionUiDiagnostic + : executionContextFailureDiagnostic(error, aftermath) + if (diagnostic?.startsWith("execution-context/")) { + this.pageHealthCheckRequired = true + } + const warnings = this.finalizeWarnings( + logSummary, + diagnostic === protectedExtensionUiDiagnostic ? protectedExtensionUiWarning : undefined, + error instanceof ExecuteCodeError ? formatNodeContextWarning(error.originalError) : undefined, + error instanceof ExecuteCodeError ? formatPointerInterceptionWarning(error.originalError) : formatPointerInterceptionWarning(error), + diagnostic === protectedExtensionUiDiagnostic + ? undefined + : formatLocatorFailurePageWarning(error instanceof ExecuteCodeError ? error.originalError : error, aftermath, this.recreatedFromClosedUrl), + ) + return { + text: this.networkCapture.redactText(error instanceof ExecuteCodeError ? error.stack ?? error.message : error.message), + isError: true, + logs: this.redactCaptureLogs(error instanceof ExecuteCodeError ? error.logs : []), + logSummary, + warnings, + ...(diagnostic ? { diagnostic: this.networkCapture.redactText(diagnostic) } : {}), + ...(aftermath ? { aftermath: this.redactCaptureAftermath(aftermath) } : {}), + ...(error instanceof ExecuteCodeError ? {} : { setupFailed: true as const }), + } + }, + onSuccess: (result) => { + return result + }, + }), + ) + } + + authenticatedJson( + request: Omit, + ): Effect.Effect { + const sandbox = this + return Effect.gen(function* () { + if (request.sensitive === true && sandbox.networkCapture.status().active) { + return AuthenticatedJsonOutcome.cases.SensitiveCaptureActive.make({}) + } + const page = yield* sandbox.ensureSessionPage("Set up authenticated origin page") + const firstOutcome = yield* AuthenticatedOrigin.requestJson(page, request) + const isAuthFailure = + firstOutcome._tag === "OriginMismatch" || + (firstOutcome._tag === "HttpError" && (firstOutcome.status === 401 || firstOutcome.status === 403)) || + (firstOutcome._tag !== "Success" && /\/(?:login|signin|sign-in|auth)\b/i.test(safePageUrl(page) ?? "")) + if ( + request.handoffOnAuthFailure === true && + sandbox.options.requestHandoff !== undefined && + isAuthFailure + ) { + const requestHandoff = sandbox.options.requestHandoff + const targetId = yield* Effect.tryPromise(() => pageTargetId(page)) + const message = request.handoffMessage?.trim() || `Sign in to ${request.origin}, then click Continue` + const outcome = yield* Effect.tryPromise(() => + requestHandoff({ + message, + timeoutMs: defaultHandoffTimeoutMs, + target: { targetId }, + }), + ) + yield* Effect.tryPromise(() => + finishHandoff({ + outcome, + message, + timeoutMs: defaultHandoffTimeoutMs, + contextTimeoutMs: handoffPageContextTimeoutMs, + evaluate: async () => { + await page.evaluate(() => true) + }, + }), + ) + const retryPage = yield* sandbox.ensureSessionPage("Re-verify authenticated origin page after handoff") + return yield* AuthenticatedOrigin.requestJson(retryPage, { + ...request, + startUrl: request.startUrl ?? "/", + }) + } + return firstOutcome + }).pipe(Effect.uninterruptible) + } + + private drainWarnings(): string[] { + const warnings = this.pendingWarnings + this.pendingWarnings = [] + return warnings + } + + private finalizeWarnings(logSummary: ExecuteLogSummary, ...extraWarnings: Array): string[] { + const warnings = this.drainWarnings() + for (const warning of extraWarnings) { + if (warning) warnings.push(warning) + } + const logCompactionWarning = formatLogCompactionWarning(logSummary) + if (logCompactionWarning) { + warnings.push(logCompactionWarning) + } + return warnings.map((warning) => this.networkCapture.redactText(warning)) + } + + redactNetworkCaptureText(text: string): string { + return this.networkCapture.redactText(text) + } + + private redactCaptureLogs(logs: readonly ExecuteLogEntry[]): readonly ExecuteLogEntry[] { + return logs.map((log) => ({ + ...log, + text: this.networkCapture.redactText(log.text), + ...(log.location ? { + location: { ...log.location, url: this.networkCapture.redactUrl(log.location.url) }, + } : {}), + })) + } + + private redactCaptureAftermath(aftermath: ExecuteAftermath): ExecuteAftermath { + return { + ...aftermath, + startUrl: aftermath.startUrl ? this.networkCapture.redactUrl(aftermath.startUrl) : aftermath.startUrl, + endUrl: aftermath.endUrl ? this.networkCapture.redactUrl(aftermath.endUrl) : aftermath.endUrl, + navigations: aftermath.navigations.map((url) => this.networkCapture.redactUrl(url)), + } + } + + disconnectSettled(): Effect.Effect { + const sandbox = this + return Effect.gen(function* () { + const browser = sandbox.browser + sandbox.browser = undefined + sandbox.unbindDefaultPage(sandbox.defaultPageTargetId, { + ownsPage: sandbox.ownsPage, + pageCrashed: sandbox.pageCrashed, + pageProtectedUi: sandbox.pageProtectedUi, + }) + yield* sandbox.networkCapture.cancel() + if (browser) { + yield* runSettledPlaywrightOperation({ + label: "Disconnect sandbox browser after handoff cancellation", + run: () => browser.close(), + }).pipe(Effect.ignore) + } + }) + } + + closeSettled(): Effect.Effect { + const sandbox = this + return Effect.gen(function* () { + const page = sandbox.page + const browser = sandbox.browser + const ownsOpenPage = page !== undefined && sandbox.ownsPage && !page.isClosed() + sandbox.browser = undefined + sandbox.unbindDefaultPage(undefined, { notify: true }) + yield* sandbox.networkCapture.cancel() + + if (ownsOpenPage) { + yield* runSettledPlaywrightOperation({ + label: "Close sandbox page after adoption", + run: () => page.close(), + }).pipe(Effect.ignore) + } + if (browser) { + yield* runSettledPlaywrightOperation({ + label: "Close sandbox browser connection after adoption", + run: () => browser.close(), + }).pipe(Effect.ignore) + } + }) + } + + adoptPage(targetId: string): Effect.Effect { + const sandbox = this + return Effect.gen(function* () { + // The manager reserves and validates the exact registry generation. Adoption + // binds that identity, not renderer readiness: a cold CDP connection waits + // for every announced page to initialize, which a busy user tab cannot do. + const currentPage = sandbox.page + const sameTarget = sandbox.defaultPageTargetId === targetId + yield* sandbox.networkCapture.cancel() + if (shouldCloseCurrentPageOnAdopt({ + hasCurrentPage: currentPage !== undefined, + ownsCurrentPage: sandbox.ownsPage, + currentPageIsSelected: sameTarget, + currentPageIsClosed: currentPage?.isClosed() ?? true, + }) && currentPage) { + // Keep the old binding until close settles. A failed close must not + // publish the new identity or orphan an open relay-owned page. + yield* runSettledPlaywrightOperation({ + label: "Close the previous session page during adoption", + run: () => currentPage.close(), + }) + } + sandbox.unbindDefaultPage(targetId) + }).pipe(Effect.uninterruptible) + } + + /** Forget the bound page; a target id is re-resolved exactly on the next execute. */ + private unbindDefaultPage( + targetId: string | undefined, + options: { + readonly ownsPage?: boolean + readonly pageCrashed?: boolean + readonly pageProtectedUi?: boolean + readonly rebind?: "replaced" | "repaired" + readonly notify?: boolean + } = {}, + ): void { + this.clearPageListeners() + this.page = undefined + this.defaultPageTargetId = targetId + this.ownsPage = options.ownsPage ?? false + this.pageHealthCheckRequired = false + this.pageCrashed = options.pageCrashed ?? false + this.pageProtectedUi = options.pageProtectedUi ?? false + this.pendingTargetRebind = targetId ? options.rebind : undefined + this.networkCapture.bindPage(undefined) + if (options.notify) this.notifyDefaultTargetChange() + } + + private async connectContext(): Promise<{ readonly browser: Browser; readonly context: BrowserContext }> { + if (!this.browser?.isConnected()) { + const hadBrowser = this.browser !== undefined + const staleBrowser = this.browser + if (staleBrowser) { + await Effect.runPromise(runPlaywrightOperation({ + label: "Close stale browser connection before reconnecting", + timeoutMs: playwrightCloseTimeoutMs, + run: () => staleBrowser.close(), + }).pipe(Effect.ignore)) + } + const adoptedDefaultTarget = this.defaultPageTargetId !== undefined && !this.ownsPage + try { + // Let Playwright own timeout/transport cleanup; never race and abandon + // a connect promise that could bind a page after reporting failure. + this.browser = await chromium.connectOverCDP(this.options.endpointUrl, { + timeout: adoptedDefaultTarget ? adoptedPageConnectTimeoutMs : playwrightConnectTimeoutMs, + ...(this.options.sessionId ? { headers: { "OpenCode-Browser-Session-Id": encodeURIComponent(this.options.sessionId), "OpenCode-Browser-Client-Kind": "sandbox" } } : {}), + }) + } catch (cause) { + if (adoptedDefaultTarget && cause instanceof errors.TimeoutError) { + throw new SessionPageRecoveryError({ + message: `Automation connection initialization for the adopted tab did not finish within ${adoptedPageConnectTimeoutMs}ms. The tab and exact target were kept; user code did not run. Retry after the browser or page becomes responsive.`, + reason: "adopted-initialization-timeout", + cause, + }) + } + throw cause + } + this.unbindDefaultPage(this.defaultPageTargetId, { + ownsPage: this.ownsPage, + pageCrashed: this.pageCrashed, + pageProtectedUi: this.pageProtectedUi, + ...(this.pendingTargetRebind ? { rebind: this.pendingTargetRebind } : {}), + }) + if (hadBrowser) { + this.pendingWarnings.push("Relay connection was lost and re-established; the session default page was re-resolved.") + } + } + const browser = this.browser + const context = browser.contexts()[0] ?? (await browser.newContext()) + await registerAriaSnapshotSelector(context) + installDownloadCapabilityGuards(context) + return { browser, context } + } + + /** + * Drop the Playwright connection but remember the default page target so the + * next connect re-resolves the same tab with fresh frame and context state. + * The relay re-enables Runtime for the tab on the new connection, which is the + * designed recovery for a page whose context events stopped reaching Playwright. + */ + private async repairSessionPage(): Promise { + const browser = this.browser + this.browser = undefined + this.unbindDefaultPage(this.defaultPageTargetId, { + ownsPage: this.ownsPage, + pageCrashed: this.pageCrashed, + pageProtectedUi: this.pageProtectedUi, + rebind: "repaired", + }) + if (browser) { + await Effect.runPromise(runPlaywrightOperation({ + label: "Close browser connection to repair the session page", + timeoutMs: playwrightCloseTimeoutMs, + run: () => browser.close(), + }).pipe(Effect.ignore)) + } + } + + private async acquireSessionPage(targetSelection?: ExecuteTargetSelection): Promise<{ + readonly browser: Browser + readonly context: BrowserContext + readonly page: Page + }> { + let { browser, context } = await this.connectContext() + let page: Page + try { + page = await this.getSessionPage({ context, ...(targetSelection ? { targetSelection } : {}) }) + } catch (error) { + if (!(error instanceof SessionPageRepairRequired)) throw error + await this.repairSessionPage() + ;({ browser, context } = await this.connectContext()) + page = await this.getSessionPage({ context, ...(targetSelection ? { targetSelection } : {}) }) + } + installPageReadTimeout(page) + this.installViewportZoomGuard(page) + this.networkCapture.bindPage(this.page) + return { browser, context, page } + } + + private ensureSessionPage(label: string): Effect.Effect { + return Effect.tryPromise({ + try: async () => (await this.acquireSessionPage()).page, + catch: (cause) => cause instanceof Error ? cause : new Error(label, { cause }), + }) + } + + private async getGlobals(options: ExecuteOptions): Promise { + const { browser, context, page } = await this.acquireSessionPage(options.targetSelection) + const showGhostCursor = async (options?: ShowGhostCursorOptions) => { + const { page: targetPage = page, ...cursorOptions } = options ?? {} + await showGhostCursorOnPage({ page: targetPage, cursorOptions }) + } + const hideGhostCursor = async (options?: HideGhostCursorOptions) => { + await hideGhostCursorOnPage({ page: options?.page ?? page }) + } + const ariaSnapshot = createAriaSnapshotHelper(page) + const { snapshot, ref } = createSnapshotHelpers(page, this.snapshotRefs) + const handoffTracker = { count: 0 } + const requestHandoff = this.options.requestHandoff + const handoff = async (message?: string, options?: HandoffCallOptions) => { + if (!requestHandoff) { + throw new Error("handoff is not available in this sandbox; it requires a relay-backed OpenCode Browser session") + } + const handoffMessage = message?.trim() || defaultHandoffMessage + const timeoutMs = options?.timeoutMs ?? defaultHandoffTimeoutMs + const handoffPage = options?.page ?? page + if (handoffPage.isClosed() || handoffPage.context() !== context) { + throw new Error("handoff requires an open page in the current browser context") + } + const followsDefaultPage = handoffPage === this.page + const targetId = await pageTargetId(handoffPage) + const outcome = await requestHandoff({ + message: handoffMessage, + timeoutMs, + target: { targetId }, + ...(options?.start ? { start: options.start } : {}), + ...(options?.start ? { cancelStart: () => Effect.runPromise(this.disconnectSettled()) } : {}), + }) + await finishHandoff({ + outcome, + message: handoffMessage, + timeoutMs, + contextTimeoutMs: handoffPageContextTimeoutMs, + evaluate: async () => { + try { + const currentPage = followsDefaultPage ? await this.getSessionPage({ context }) : handoffPage + await currentPage.evaluate(() => true) + } catch (error) { + if ((error instanceof SessionPageRecoveryError && error.reason === "target-unavailable") || error instanceof SessionPageRepairRequired) { + throw new Error("Execution context is not available while the handoff destination settles", { cause: error }) + } + throw error + } + }, + }) + handoffTracker.count += 1 + } + const demonstrate = async (message?: string, options?: HandoffCallOptions) => { + const demonstrationPage = options?.page ?? page + if (demonstrationPage.isClosed() || demonstrationPage.context() !== context) { + throw new Error("demonstrate requires an open page in the current browser context") + } + const recorder = await startDemonstrationRecorder(demonstrationPage) + try { + await handoff(message ?? "Demonstrate the browser flow, then continue", { ...options, page: demonstrationPage }) + } catch (error) { + await recorder.stop().catch(() => {}) + throw error + } + return await recorder.stop() + } + return { + browser, + context, + page, + state: this.state, + modules: nodeModules, + fillInput: (target, value) => fillInput({ page, target, value }), + fillInputs, + screenshotWithLabels: (screenshotOptions = {}) => screenshotWithLabels({ + ...screenshotOptions, + page: screenshotOptions.page ?? page, + registry: this.snapshotRefs, + }), + screenshotDiff: createScreenshotDiff(page), + ariaSnapshot, + snapshot, + ref, + webmcp: createWebMcpHelper(page), + showGhostCursor, + hideGhostCursor, + ghostCursor: { + show: showGhostCursor, + hide: hideGhostCursor, + caption: async (title, captionOptions) => { + const { page: targetPage = page, ...rest } = captionOptions ?? {} + await setGhostCursorCaption({ page: targetPage, title, captionOptions: rest }) + }, + clearCaption: async (clearOptions) => { + await setGhostCursorCaption({ page: clearOptions?.page ?? page, title: null }) + }, + callout: async (target, label, calloutOptions) => { + const { page: targetPage = page, ...rest } = calloutOptions ?? {} + await showGhostCursorCallout({ page: targetPage, target, label, calloutOptions: rest }) + }, + clearCallouts: async (clearOptions) => { + await clearGhostCursorCallouts({ page: clearOptions?.page ?? page }) + }, + zoom: async (target, zoomOptions) => { + const { page: targetPage = page, ...rest } = zoomOptions ?? {} + await zoomGhostCursorCamera({ page: targetPage, target, zoomOptions: rest }) + }, + resetZoom: async (resetOptions) => { + const { page: targetPage = page, ...rest } = resetOptions ?? {} + await zoomGhostCursorCamera({ page: targetPage, target: null, zoomOptions: rest }) + }, + spotlight: async (target, spotlightOptions) => { + const { page: targetPage = page, ...rest } = spotlightOptions ?? {} + await setGhostCursorSpotlight({ page: targetPage, target, spotlightOptions: rest }) + }, + clearSpotlight: async (clearOptions) => { + await setGhostCursorSpotlight({ page: clearOptions?.page ?? page, target: null }) + }, + keys: async (keys, label, keyOptions) => { + await showGhostCursorKeys({ page: keyOptions?.page ?? page, keys, ...(label ? { label } : {}) }) + }, + }, + handoff, + demonstrate, + network: { + start: (options) => Effect.runPromise(this.networkCapture.start(page, options)), + status: () => this.networkCapture.status(), + stop: (options) => Effect.runPromise(this.networkCapture.stop(options)), + cancel: () => Effect.runPromise(this.networkCapture.cancel()), + }, + pageConsole: { + start: (target) => PageConsole.start(target ?? page), + stop: (target) => PageConsole.stop(target ?? page), + }, + handoffTracker, + } + } + + markTargetCrashed(targetId: string): boolean { + if (this.defaultPageTargetId !== targetId) { + return false + } + this.pageHealthCheckRequired = true + this.pageCrashed = true + if (!this.pendingWarnings.includes(defaultPageCrashedWarning)) { + this.pendingWarnings.push(defaultPageCrashedWarning) + } + return true + } + + /** Relay report that protected extension UI started or stopped blocking the default page's tab. */ + markTargetProtectedUi(targetId: string, protectedUi: boolean): boolean { + if (this.defaultPageTargetId !== targetId) { + return false + } + this.pageProtectedUi = protectedUi + return true + } + + markTargetDetached(targetId: string): boolean { + if (this.defaultPageTargetId !== targetId) { + return false + } + if (this.lastKnownNonBlankUrl) { + this.recreatedFromClosedUrl = this.lastKnownNonBlankUrl + } + this.unbindDefaultPage(undefined) + if (!this.pendingWarnings.includes(defaultPageClosedWarning)) { + this.pendingWarnings.push(defaultPageClosedWarning) + } + return true + } + + markTargetReplaced(previousTargetId: string, targetId: string): boolean { + if (this.defaultPageTargetId !== previousTargetId) return false + this.unbindDefaultPage(targetId, { + ownsPage: this.ownsPage, + rebind: "replaced", + }) + return true + } + + restore(target: SessionTarget | undefined): void { + if (target) { + this.unbindDefaultPage(target.id, { ownsPage: target.owner === "relay" }) + } + this.pendingWarnings.push("The relay restarted; session JavaScript state and snapshot refs were reset.") + } + + private notifyDefaultTargetChange(): void { + this.options.onDefaultTargetChange?.(this.defaultPageTargetId + ? { id: this.defaultPageTargetId, owner: this.ownsPage ? "relay" : "user" } + : undefined) + } + + private recordNonBlankUrl(url: string | null | undefined): void { + if (url && url !== "about:blank" && !url.startsWith("chrome-error://")) { + this.lastKnownNonBlankUrl = url + this.recreatedFromClosedUrl = undefined + } + } + + private bindDefaultPage(page: Page, targetId: string | undefined, ownsPage: boolean, notify: boolean): void { + this.clearPageListeners() + this.page = page + if (targetId === undefined || targetId !== this.defaultPageTargetId) { + this.pageCrashed = false + this.pageProtectedUi = false + } + this.defaultPageTargetId = targetId + this.ownsPage = ownsPage + this.pendingTargetRebind = undefined + this.recordNonBlankUrl(safePageUrl(page)) + const close = () => { + if (this.page !== page) return + if (this.lastKnownNonBlankUrl) { + this.recreatedFromClosedUrl = this.lastKnownNonBlankUrl + } + this.unbindDefaultPage(undefined, { + pageCrashed: this.pageCrashed, + pageProtectedUi: this.pageProtectedUi, + notify: true, + }) + } + const navigate = (frame: Frame) => { + if (this.page === page && frame === page.mainFrame()) { + this.pageCrashed = false + this.recordNonBlankUrl(frame.url()) + page.setDefaultTimeout?.(30_000) + if (this.explicitLightColorScheme) { + void this.applyExplicitLightColorScheme(page) + } + } + } + this.boundPageListeners = { page, close, navigate } + page.once("close", close) + page.on("framenavigated", navigate) + if (notify) this.notifyDefaultTargetChange() + } + + private clearBoundPageListeners(): void { + const bound = this.boundPageListeners + if (!bound) return + bound.page.off("close", bound.close) + bound.page.off("framenavigated", bound.navigate) + this.boundPageListeners = undefined + } + + private clearSnapshotRefs(): void { + this.snapshotRefs.removeNavigationListener?.() + delete this.snapshotRefs.removeNavigationListener + invalidateSnapshotDocument(this.snapshotRefs) + } + + private clearPageListeners(): void { + this.clearBoundPageListeners() + this.clearSnapshotRefs() + } + + getStatus(): { readonly sessionId?: string; readonly connected: boolean; readonly pageUrl: string | null; readonly stateKeys: string[] } { + const pageUrl = this.page && !this.page.isClosed() ? this.page.url() : null + return { + ...(this.options.sessionId ? { sessionId: this.options.sessionId } : {}), + connected: isSessionPageConnected({ + browserConnected: Boolean(this.browser?.isConnected()), + pageUrl, + healthCheckRequired: this.pageHealthCheckRequired, + }), + pageUrl, + stateKeys: Object.keys(this.state), + } + } + + networkStart(options: NetworkCapture.NetworkCaptureOptions = {}): Effect.Effect { + const sandbox = this + return Effect.gen(function* () { + const page = yield* sandbox.ensureSessionPage("Set up page for network capture") + return yield* sandbox.networkCapture.start(page, options) + }).pipe(Effect.uninterruptible) + } + + networkStatus(): NetworkCapture.NetworkCaptureStatus { + return this.networkCapture.status() + } + + networkStop(options: NetworkCapture.NetworkCaptureStopOptions = {}): Effect.Effect { + return this.networkCapture.stop(options) + } + + networkCancel(): Effect.Effect<{ readonly cancelled: boolean }> { + return this.networkCapture.cancel() + } + + authRefresh(options: { + readonly name: string + readonly urlFilter?: string + readonly timeoutMs?: number + }): Effect.Effect { + const sandbox = this + return Effect.gen(function* () { + const page = yield* sandbox.ensureSessionPage("Set up page for auth refresh") + yield* AuthProfile.read(options.name).pipe(Effect.asVoid) + yield* sandbox.networkCapture.start(page, { + ...(options.urlFilter ? { urlFilter: options.urlFilter } : {}), + }) + return yield* Effect.gen(function* () { + yield* Effect.tryPromise({ + try: () => page.reload({ waitUntil: "domcontentloaded", timeout: options.timeoutMs ?? 30_000 }), + catch: (cause) => cause instanceof Error ? cause : new Error("Refresh auth profile", { cause }), + }) + yield* Effect.tryPromise({ + try: () => page.waitForLoadState("networkidle", { timeout: Math.min(options.timeoutMs ?? 30_000, 5_000) }).catch(() => {}), + catch: (cause) => cause instanceof Error ? cause : new Error("Wait for auth refresh network", { cause }), + }) + return yield* sandbox.networkCapture.stop({ secrets: options.name, requireObservedSecrets: true }) + }).pipe(Effect.ensuring(sandbox.networkCapture.cancel())) + }).pipe(Effect.uninterruptible) + } + + private async getSessionPage({ context, targetSelection }: { readonly context: BrowserContext; readonly targetSelection?: ExecuteTargetSelection }): Promise { + const selection = targetSelection ?? {} + if (hasExplicitTargetSelection(selection)) { + const selected = selectPage({ pages: context.pages(), selection }) + if (!selected) { + throw new Error("No page matched target selection") + } + return selected + } + if (!this.page && this.defaultPageTargetId) { + const targetId = this.defaultPageTargetId + const rebind = this.pendingTargetRebind + const replacement = await waitForPageTarget({ context, targetId, timeoutMs: sessionPageHealthCheckTimeoutMs }) + if (!replacement) { + throw new SessionPageRecoveryError({ + message: `Playwright did not expose session page target ${targetId} after the browser connection or target changed. Retry after the browser transition settles.`, + reason: "target-unavailable", + cause: new Error(`Session page target unavailable: ${targetId}`), + }) + } + this.bindDefaultPage(replacement, targetId, this.ownsPage, false) + if (rebind === "replaced") this.pendingWarnings.push(defaultPageReplacedWarning) + if (rebind !== "repaired") return replacement + this.pageHealthCheckRequired = true + const checked = await this.checkSessionPage(replacement, { repaired: true }) + if (checked) { + this.pendingWarnings.push(defaultPageRepairedWarning) + return checked + } + } + if (this.page && !this.page.isClosed()) { + // A tab blocked by protected extension UI cannot answer a probe; the + // block is named on the next failure instead of treated as a dead page. + if ((this.pageHealthCheckRequired && !this.pageProtectedUi) || this.page.url().startsWith("chrome-error://")) { + const page = await this.checkSessionPage(this.page, { repaired: false }) + if (page) return page + } else { + return this.page + } + } + if (this.page?.isClosed()) { + if (this.lastKnownNonBlankUrl) { + this.recreatedFromClosedUrl = this.lastKnownNonBlankUrl + } + this.unbindDefaultPage(undefined, { + pageCrashed: this.pageCrashed, + pageProtectedUi: this.pageProtectedUi, + notify: true, + }) + this.pendingWarnings.push(defaultPageClosedWarning) + } + const page = await context.newPage() + const targetId = await resolvePageTargetId(page) + this.bindDefaultPage(page, targetId, true, true) + if (this.recreatedFromClosedUrl) { + this.installClosedPageReplacementGuard(page) + } + return page + } + + private installClosedPageReplacementGuard(page: Page): void { + page.setDefaultTimeout?.(2_500) + const restoreTimeout = () => { + this.recreatedFromClosedUrl = undefined + page.setDefaultTimeout?.(30_000) + } + if (typeof page.goto === "function") { + const originalGoto = page.goto.bind(page) + Object.defineProperty(page, "goto", { + configurable: true, + value: async (...args: Parameters) => { + restoreTimeout() + return await originalGoto(...args) + }, + }) + } + if (typeof page.setContent === "function") { + const originalSetContent = page.setContent.bind(page) + Object.defineProperty(page, "setContent", { + configurable: true, + value: async (...args: Parameters) => { + restoreTimeout() + return await originalSetContent(...args) + }, + }) + } + } + + private async applyExplicitLightColorScheme(page: Page): Promise { + try { + const cdp = await page.context().newCDPSession(page) + try { + await cdp.send("Emulation.setEmulatedMedia", { + features: [ + { name: "prefers-color-scheme", value: "light" }, + { name: "__bc_explicit__", value: "1" }, + ], + }) + } finally { + await cdp.detach().catch(() => {}) + } + } catch {} + } + + private installViewportZoomGuard(page: Page): void { + if (viewportZoomGuardedPages.has(page)) return + if (typeof page.emulateMedia === "function") { + const originalEmulateMedia = page.emulateMedia.bind(page) + Object.defineProperty(page, "emulateMedia", { + configurable: true, + value: async (options?: Parameters[0]) => { + if (options && "colorScheme" in options) { + this.explicitLightColorScheme = options.colorScheme === "light" + } + await originalEmulateMedia(options) + if (this.explicitLightColorScheme) { + await this.applyExplicitLightColorScheme(page) + } + }, + }) + } + if (typeof page.setViewportSize === "function") { + const originalSetViewportSize = page.setViewportSize.bind(page) + Object.defineProperty(page, "setViewportSize", { + configurable: true, + value: async (size: { width: number; height: number }) => { + await originalSetViewportSize(size) + try { + const measured = await withTimeout( + page.evaluate(() => ({ + innerWidth: window.innerWidth, + innerHeight: window.innerHeight, + dpr: window.devicePixelRatio, + })), + 1_000, + ) + if ( + measured !== timedOut + && (Math.abs(measured.innerWidth - size.width) > 2 || Math.abs(measured.innerHeight - size.height) > 2) + ) { + const warning = `Viewport size ${size.width}x${size.height} resulted in CSS viewport ${measured.innerWidth}x${measured.innerHeight} (devicePixelRatio=${Number(measured.dpr.toFixed(3))}) due to browser zoom on this origin.` + if (!this.pendingWarnings.includes(warning)) { + this.pendingWarnings.push(warning) + } + } + } catch {} + }, + }) + } + viewportZoomGuardedPages.add(page) + } + + /** + * Health-check the current default page. Returns the page when it is usable, + * `undefined` after a disposable relay-owned page was closed so the caller + * recreates it, throws `SessionPageRepairRequired` when a live relay-owned + * page should be re-resolved over a fresh connection, and otherwise fails + * with a `SessionPageRecoveryError` diagnosis while keeping the tab. + */ + private async checkSessionPage(page: Page, options: { readonly repaired: boolean }): Promise { + const timeoutMs = this.options.pageHealthCheckTimeoutMs ?? sessionPageHealthCheckTimeoutMs + const sandbox = this + const recovery = await Effect.runPromise(recoverSessionPage({ + ownsPage: this.ownsPage, + // Read these after the asynchronous probe: navigation may have recovered + // an error document or cleared the crash while its old context failed. + get url() { return page.url() }, + timeoutMs, + get crashed() { return sandbox.pageCrashed }, + repaired: options.repaired, + healthCheck: () => waitForPageContext({ + timeoutMs, + evaluate: async () => { + await page.evaluate(() => true) + }, + }), + close: () => page.close(), + })) + if (recovery === "use") { + this.pageHealthCheckRequired = false + this.pageCrashed = false + return page + } + if (recovery === "repair") { + throw new SessionPageRepairRequired() + } + this.unbindDefaultPage(undefined, { notify: true }) + this.pendingWarnings.push(defaultPageRecoveredWarning) + return undefined + } +} + +async function waitForPageTarget(options: { + readonly context: BrowserContext + readonly targetId: string + readonly timeoutMs: number +}): Promise { + return await waitForExactTarget({ + targetId: options.targetId, + timeoutMs: options.timeoutMs, + candidates: () => options.context.pages(), + getTargetId: resolvePageTargetId, + }) +} + +export async function waitForExactTarget(options: { + readonly targetId: string + readonly timeoutMs: number + readonly candidates: () => readonly T[] + readonly getTargetId: (candidate: T) => Promise + readonly delay?: (milliseconds: number) => Promise +}): Promise { + const deadline = Date.now() + options.timeoutMs + const cachedTargetIds = new Map() + const inFlightTargetIds = new Map>() + while (true) { + const remainingMs = deadline - Date.now() + if (remainingMs <= 0) return undefined + const candidates = options.candidates() + for (const candidate of candidates) { + const cached = cachedTargetIds.get(candidate) + if (cached === options.targetId) return candidate + if (cached !== undefined || inFlightTargetIds.has(candidate)) continue + inFlightTargetIds.set(candidate, options.getTargetId(candidate).then( + (targetId) => ({ candidate, targetId }), + () => ({ candidate, targetId: undefined }), + )) + } + const retryInMs = Math.min(sessionPageHealthRetryDelayMs, Math.max(0, deadline - Date.now())) + if (retryInMs <= 0) return undefined + if (inFlightTargetIds.size > 0) { + const resolved = await withTimeout(Promise.race(inFlightTargetIds.values()), retryInMs) + if (resolved !== timedOut) { + inFlightTargetIds.delete(resolved.candidate) + if (resolved.targetId !== undefined) cachedTargetIds.set(resolved.candidate, resolved.targetId) + if (resolved.targetId === options.targetId) return resolved.candidate + } + continue + } + await (options.delay ?? delay)(retryInMs) + } +} + +export function installDownloadCapabilityGuard(page: Page): void { + if (downloadGuardedPages.has(page)) { + return + } + const waitForEvent = page.waitForEvent.bind(page) as (event: string, ...args: unknown[]) => Promise + Object.defineProperty(page, "waitForEvent", { + configurable: true, + value: (event: string, ...args: unknown[]) => { + if (event === "download") { + return Promise.reject(new Error(downloadCapabilityErrorMessage)) + } + return waitForEvent(event, ...args) + }, + }) + downloadGuardedPages.add(page) +} + +export function installDownloadCapabilityGuards(context: BrowserContext): void { + if (downloadGuardedContexts.has(context)) { + return + } + for (const page of context.pages()) { + installDownloadCapabilityGuard(page) + } + context.on("page", installDownloadCapabilityGuard) + downloadGuardedContexts.add(context) +} + +export function hasExplicitTargetSelection(selection: ExecuteTargetSelection | undefined): boolean { + return Boolean(selection?.urlIncludes) || selection?.index !== undefined +} + +export function selectTarget({ + targets, + selection, + getUrl, + getIndex, +}: { + readonly targets: readonly T[] + readonly selection: ExecuteTargetSelection + readonly getUrl: (target: T) => string + readonly getIndex?: (target: T, fallbackIndex: number) => number +}): T | undefined { + if (selection.urlIncludes && selection.index !== undefined) { + throw new TargetSelectionError({ reason: "invalid", message: "Use only one target selector: --target-url or --target-index" }) + } + if (selection.urlIncludes) { + const matches = targets.filter((candidate) => { + return getUrl(candidate).includes(selection.urlIncludes ?? "") + }) + if (matches.length === 0) { + throw new TargetSelectionError({ + reason: "not-found", + message: `No existing attached page URL includes ${selection.urlIncludes}. Target selectors do not navigate or open pages: use page.goto() in the session page, or attach the intended user tab with the OpenCode Browser toolbar first.`, + }) + } + if (matches.length > 1) { + const candidates = targets.flatMap((candidate, index) => matches.includes(candidate) ? [`[${getIndex ? getIndex(candidate, index) : index}] ${getUrl(candidate)}`] : []) + throw new TargetSelectionError({ + reason: "ambiguous", + message: `Multiple attached pages (${matches.length}) match URL ${selection.urlIncludes}; use a more specific --target-url or --target-index. Matches: ${candidates.join(", ")}`, + }) + } + return matches[0] + } + if (selection.index !== undefined) { + if (selection.index < 0) { + throw new TargetSelectionError({ reason: "invalid", message: "Target index must be a non-negative integer" }) + } + const target = targets[selection.index] + if (!target) { + throw new TargetSelectionError({ + reason: "not-found", + message: `No existing attached page at index ${selection.index}; ${targets.length} page(s) available. Target selectors do not create pages.`, + }) + } + return target + } + if (targets.length === 0) { + throw new TargetSelectionError({ + reason: "not-found", + message: "No attached pages available. Attach the intended user tab with the OpenCode Browser toolbar first.", + }) + } + if (targets.length > 1) { + const candidates = targets.map((candidate, index) => `[${getIndex ? getIndex(candidate, index) : index}] ${getUrl(candidate)}`) + throw new TargetSelectionError({ + reason: "ambiguous", + message: `Multiple attached pages (${targets.length}); use --target-url or --target-index to choose one. Matches: ${candidates.join(", ")}`, + }) + } + return targets[0] +} + +function selectPage({ pages, selection }: { readonly pages: readonly Page[]; readonly selection: ExecuteTargetSelection }): Page | undefined { + return selectTarget({ targets: pages, selection, getUrl: (page) => page.url() }) +} + +async function resolvePageTargetId(page: Page): Promise { + return await Effect.runPromise( + runPlaywrightOperation({ + label: "Resolve session page target id", + timeoutMs: playwrightCloseTimeoutMs, + run: () => pageTargetId(page), + }).pipe( + Effect.match({ + onFailure: () => undefined, + onSuccess: (targetId) => targetId, + }), + ), + ) +} + +export async function pageTargetId(page: Page): Promise { + if (page.isClosed()) { + throw new Error("Cannot identify the CDP target for a closed page") + } + const session = await page.context().newCDPSession(page) + try { + const result = await session.send("Target.getTargetInfo") + const targetId = result.targetInfo?.targetId + if (!targetId) { + throw new Error("Target.getTargetInfo did not return a target id for the handoff page") + } + return targetId + } finally { + await session.detach() + } +} + + +const maxTrackedNavigations = 25 +const maxCapturedPageLogs = 50 +const maxCapturedScriptLogs = 100 + +type ExecuteLogCaptureSnapshot = { + readonly logs: readonly ExecuteLogEntry[] + readonly summary: ExecuteLogSummary + readonly consoleErrorCount: number + readonly pageErrorCount: number +} + +export function createExecuteLogCapture(limits: { + readonly page?: number + readonly script?: number +} = {}): { + readonly add: (entry: ExecuteLogEntry) => void + readonly snapshot: () => ExecuteLogCaptureSnapshot +} { + const pageLimit = limits.page ?? maxCapturedPageLogs + const scriptLimit = limits.script ?? maxCapturedScriptLogs + const logs: ExecuteLogEntry[] = [] + const pageEntryIndexes = new Map() + let pageEntries = 0 + let scriptEntries = 0 + let totalCount = 0 + let repeatedCount = 0 + let omittedCount = 0 + let consoleErrorCount = 0 + let pageErrorCount = 0 + + const add = (entry: ExecuteLogEntry): void => { + totalCount += 1 + if (entry.type === "error") { + consoleErrorCount += 1 + } else if (entry.type === "pageerror") { + pageErrorCount += 1 + } + + if (entry.source === "page") { + const key = pageLogKey(entry) + const existingIndex = pageEntryIndexes.get(key) + if (existingIndex !== undefined) { + const existing = logs[existingIndex] + if (existing) { + logs[existingIndex] = { ...existing, repeatCount: (existing.repeatCount ?? 0) + 1 } + repeatedCount += 1 + return + } + } + if (pageEntries >= pageLimit) { + omittedCount += 1 + return + } + pageEntryIndexes.set(key, logs.length) + pageEntries += 1 + logs.push(entry) + return + } + + if (scriptEntries >= scriptLimit) { + omittedCount += 1 + return + } + scriptEntries += 1 + logs.push(entry) + } + + return { + add, + snapshot: () => ({ + logs: [...logs], + summary: { + totalCount, + returnedCount: logs.length, + repeatedCount, + omittedCount, + }, + consoleErrorCount, + pageErrorCount, + }), + } +} + +function pageLogKey(entry: ExecuteLogEntry): string { + const routineCategory = routinePageLogCategory(entry) + if (routineCategory) { + return JSON.stringify([entry.type, routineCategory]) + } + return JSON.stringify([ + entry.type, + entry.text, + entry.location?.url ?? null, + entry.location?.lineNumber ?? null, + entry.location?.columnNumber ?? null, + ]) +} + +function routinePageLogCategory(entry: ExecuteLogEntry): string | undefined { + if (entry.source !== "page") return undefined + const text = entry.text.toLowerCase() + if (/^(?:error with permissions-policy header|permissions-policy header warning|permissions policy violation|\[violation\] potential permissions policy violation)/.test(text)) { + return "browser-permissions-policy" + } + if (!text.includes("err_blocked_by_client")) return undefined + const resource = entry.location?.url.toLowerCase() ?? "" + const analyticsMarkers = [ + "google-analytics.com", + "googletagmanager.com", + "doubleclick.net", + "connect.facebook.net", + "/analytics", + "analytics.", + ] + return analyticsMarkers.some((marker) => resource.includes(marker)) ? "blocked-analytics-resource" : undefined +} + +function emptyExecuteLogSummary(): ExecuteLogSummary { + return { + totalCount: 0, + returnedCount: 0, + repeatedCount: 0, + omittedCount: 0, + } +} + +function formatLogCompactionWarning(summary: ExecuteLogSummary): string | undefined { + if (summary.repeatedCount === 0 && summary.omittedCount === 0) { + return undefined + } + return `Captured ${summary.totalCount} console/page events: returned ${summary.returnedCount}, folded ${summary.repeatedCount} repeated page entries, and omitted ${summary.omittedCount} after limits (page=${maxCapturedPageLogs}, script=${maxCapturedScriptLogs}). Aftermath error counts include all events.` +} + +const pageOnlyGlobalPattern = /^(window|document|localStorage|sessionStorage|location|navigator|getComputedStyle) is not defined$/ + +/** Explain failures caused by treating Node-side execute code as page code. */ +export function formatNodeContextWarning(error: Error): string | undefined { + const pageGlobal = error.name === "ReferenceError" ? pageOnlyGlobalPattern.exec(error.message)?.[1] : undefined + if (pageGlobal) { + return `Execute code runs in Node, where \`${pageGlobal}\` is undefined. Read page globals inside page.evaluate(() => ...).` + } + if (error.name === "TypeError" && error.message.startsWith("Failed to parse URL from ")) { + return "Execute code runs in Node, so fetch has no page origin or cookies. Use page.evaluate(() => fetch(...)) for same-origin requests." + } + if (error.name === "TypeError" && /The "cb" argument must be of type function/i.test(error.message)) { + return "The execute `fs` alias is callback-style `node:fs`; use `await fs.promises.writeFile(...)` / `await fs.promises.readFile(...)` or `fs.writeFileSync(...)`." + } + return undefined +} + +const pointerInterceptionPattern = /(<[a-zA-Z][^>\n]*>[^\n]*?)\s+intercepts pointer events/ +const locatorFailurePattern = /waiting for locator\(|waiting for getBy|strict mode violation:/i + +/** Extract the covering element when Playwright times out because another element intercepts pointer events. */ +export function formatPointerInterceptionWarning(error: unknown): string | undefined { + if (!(error instanceof Error)) return undefined + const blocker = pointerInterceptionPattern.exec(error.message)?.[1] + if (!blocker) return undefined + return `Pointer action was blocked because ${blocker} intercepts pointer events. Dismiss the covering dialog/banner or scroll the target clear of sticky chrome instead of retrying the same click.` +} + +function formatBoundedPageUrl(rawUrl: string): string { + try { + const parsed = new URL(rawUrl) + return parsed.origin === "null" ? rawUrl.slice(0, 96) : `${parsed.origin}${parsed.pathname}`.slice(0, 120) + } catch { + return rawUrl.slice(0, 96) + } +} + +function formatLocatorFailurePageWarning( + error: unknown, + aftermath: ExecuteAftermath | undefined, + recreatedFromClosedUrl?: string, +): string | undefined { + if (!(error instanceof Error) || !locatorFailurePattern.test(error.message)) return undefined + const rawUrl = aftermath?.endUrl ?? aftermath?.startUrl + if (rawUrl !== "about:blank") return undefined + if (recreatedFromClosedUrl) { + return `Locator failed on about:blank because the previous session page (${formatBoundedPageUrl(recreatedFromClosedUrl)}) was closed. Call page.goto(...) to reopen it before querying controls.` + } + return "Locator failed on page about:blank. Navigate with page.goto(...) or adopt an attached tab before querying controls." +} + +export async function runUserCode({ code, globals }: { readonly code: string; readonly globals: SandboxGlobals }): Promise<{ + readonly result: unknown + readonly logs: readonly ExecuteLogEntry[] + readonly logSummary: ExecuteLogSummary + readonly aftermath: ExecuteAftermath +}> { + const logCapture = createExecuteLogCapture() + const navigations: string[] = [] + const onConsole = (message: ConsoleMessage) => { + logCapture.add({ + source: "page", + type: message.type(), + text: message.text(), + location: message.location(), + }) + } + const onPageError = (error: Error) => { + logCapture.add({ + source: "page", + type: "pageerror", + text: error.stack ?? error.message, + }) + } + const onFrameNavigated = (frame: Frame) => { + if (frame !== globals.page.mainFrame() || navigations.length >= maxTrackedNavigations) { + return + } + navigations.push(frame.url()) + } + const sandboxConsole = createSandboxConsole({ addLog: logCapture.add }) + const startUrl = safePageUrl(globals.page) + globals.page.on("console", onConsole) + globals.page.on("pageerror", onPageError) + const stopListening = PageConsole.listen(globals.page, logCapture.add) + globals.page.on("framenavigated", onFrameNavigated) + const buildResultMetadata = () => { + const captured = logCapture.snapshot() + return { + logs: captured.logs, + logSummary: captured.summary, + aftermath: { + startUrl, + endUrl: safePageUrl(globals.page), + navigations, + consoleErrorCount: captured.consoleErrorCount, + pageErrorCount: captured.pageErrorCount, + handoffs: globals.handoffTracker.count, + }, + } satisfies { readonly logs: readonly ExecuteLogEntry[]; readonly logSummary: ExecuteLogSummary; readonly aftermath: ExecuteAftermath } + } + try { + const AsyncFunction = async function () {}.constructor as new (...args: string[]) => (...args: unknown[]) => Promise + const fn = new AsyncFunction("console", ...sandboxGlobalKeys, wrapCodeWithModuleAliases(code)) + const result = await fn(sandboxConsole, ...sandboxGlobalKeys.map((key) => globals[key])) + return { result, ...buildResultMetadata() } + } catch (cause) { + const error = cause instanceof Error ? cause : new Error("execute sandbox code", { cause }) + const metadata = buildResultMetadata() + throw new ExecuteCodeError(error, metadata.logs, metadata.logSummary, metadata.aftermath) + } finally { + globals.page.off("console", onConsole) + globals.page.off("pageerror", onPageError) + globals.page.off("framenavigated", onFrameNavigated) + stopListening() + } +} + +const sandboxGlobalKeys = [ + "browser", + "context", + "page", + "state", + "modules", + "fillInput", + "fillInputs", + "screenshotWithLabels", + "screenshotDiff", + "ariaSnapshot", + "snapshot", + "ref", + "webmcp", + "showGhostCursor", + "hideGhostCursor", + "ghostCursor", + "handoff", + "demonstrate", + "network", + "pageConsole", +] as const satisfies readonly (keyof Omit)[] + +function safePageUrl(page: Page): string | null { + try { + return page.isClosed() ? null : page.url() + } catch { + return null + } +} + +function createSandboxConsole(options: { readonly addLog: (entry: ExecuteLogEntry) => void }): Pick { + const capture = (type: ExecuteLogEntry["type"], values: readonly unknown[]) => { + options.addLog({ + source: "script", + type, + text: values.map(formatLogValue).join(" "), + }) + } + return { + debug: (...values: readonly unknown[]) => { + capture("debug", values) + }, + error: (...values: readonly unknown[]) => { + capture("error", values) + }, + info: (...values: readonly unknown[]) => { + capture("info", values) + }, + log: (...values: readonly unknown[]) => { + capture("log", values) + }, + warn: (...values: readonly unknown[]) => { + capture("warn", values) + }, + } +} + +function formatLogValue(value: unknown): string { + if (Predicate.isString(value)) { + return value + } + return util.inspect(value, { depth: 4, colors: false, maxArrayLength: 100, maxStringLength: 1000 }) +} + +export function getAutoReturnExpression(code: string): string | null { + try { + const ast = acorn.parse(code, { + ecmaVersion: "latest", + allowAwaitOutsideFunction: true, + allowReturnOutsideFunction: true, + sourceType: "script", + }) + if (ast.body.length !== 1) { + return null + } + const statement = ast.body[0] + if (statement?.type !== "ExpressionStatement") { + return null + } + const expression = statement.expression + if (expression.type === "AssignmentExpression" || expression.type === "UpdateExpression") { + return null + } + if (expression.type === "UnaryExpression" && expression.operator === "delete") { + return null + } + if (expression.type === "SequenceExpression" && expression.expressions.some((item) => { + return item.type === "AssignmentExpression" + })) { + return null + } + return code.slice(expression.start, expression.end) + } catch { + return null + } +} + +export function wrapCode(code: string): string { + const expression = getAutoReturnExpression(code) + if (expression) { + return `return await (${expression})` + } + return code +} + +function wrapCodeWithModuleAliases(code: string): string { + return `const { ${nodeModuleAliases} } = modules;\n{\n${wrapCode(code)}\n}` +} + +function stringifyResult(result: unknown): string { + if (Predicate.isString(result)) { + return result + } + if (result === undefined) { + return "undefined" + } + return util.inspect(result, { depth: 3, colors: false, maxArrayLength: 50, maxStringLength: 4000 }) +} + +type JsonSafeResult = + | { readonly serializable: true; readonly value: unknown } + | { readonly serializable: false; readonly reason: string } + +const maxJsonSafeDepth = 8 +const maxJsonSafeBytes = 32 * 1024 + +export function extractExecuteMedia(value: unknown): { readonly value: unknown; readonly media: readonly ExecuteMedia[] } { + const media: ExecuteMedia[] = [] + const seen = new WeakMap() + + const replace = (item: unknown): unknown => { + if (Buffer.isBuffer(item)) { + const mimeType = imageMimeType(item) + if (!mimeType) return item + const image = { + type: "image" as const, + mimeType, + data: item.toString("base64"), + size: item.byteLength, + } + media.push(image) + return { type: image.type, mimeType: image.mimeType, size: image.size } + } + if (!Predicate.isObjectOrArray(item)) return item + const previous = seen.get(item) + if (previous !== undefined) return previous + if (Array.isArray(item)) { + const output: unknown[] = [] + seen.set(item, output) + for (const value of item) output.push(replace(value)) + return output + } + if (item instanceof Map) { + const output = new Map() + seen.set(item, output) + for (const [key, value] of item) output.set(replace(key), replace(value)) + return output + } + if (item instanceof Set) { + const output = new Set() + seen.set(item, output) + for (const value of item) output.add(replace(value)) + return output + } + if (!isPlainJsonContainer(item)) return item + const output: Record = {} + seen.set(item, output) + for (const key of safeObjectKeys(item) ?? []) { + try { + output[key] = replace(item[key as keyof typeof item]) + } catch { + // Match structured-result conversion: skip inaccessible properties. + } + } + return output + } + + return { value: replace(value), media } +} + +function imageMimeType(value: Buffer): string | undefined { + if (value.length >= 8 && value.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) { + return "image/png" + } + if (value.length >= 3 && value[0] === 0xff && value[1] === 0xd8 && value[2] === 0xff) { + return "image/jpeg" + } + if (value.length >= 12 && value.subarray(0, 4).toString("ascii") === "RIFF" && value.subarray(8, 12).toString("ascii") === "WEBP") { + return "image/webp" + } + return undefined +} + +/** + * Best-effort structured execute value for machine consumers. + * + * Only plain JSON-ish data is preserved, with Map converted to a plain object + * when all keys are strings and Set converted to an array. Class instances (for + * example Playwright Page/Locator/Response objects) are not serialized: a + * top-level instance omits `value` entirely, while nested instances are omitted + * from object branches and become `null` in array branches. Throwing proxies or + * other unexpected conversion failures also omit `value`; throwing getters on + * otherwise plain objects are skipped property-by-property. Oversized values are + * also omitted so `value` stays compact for agents; `text` remains the human + * fallback for every result. + */ +export function toJsonSafeValue(value: unknown): JsonSafeResult { + try { + const seen = new WeakSet() + const converted = convertJsonSafe(value, { seen, depth: 0 }) + if (converted.omit) { + return { serializable: false, reason: converted.reason } + } + const jsonText = safeJsonStringify(converted.value) + if (jsonText === undefined) { + return { serializable: false, reason: "JSON serialization failed" } + } + if (Buffer.byteLength(jsonText, "utf8") > maxJsonSafeBytes) { + return { serializable: false, reason: `JSON value exceeds ${maxJsonSafeBytes} bytes` } + } + return { serializable: true, value: converted.value } + } catch (cause) { + return { serializable: false, reason: cause instanceof Error && cause.message ? cause.message : "JSON conversion failed" } + } +} + +type JsonSafeConversion = + | { readonly omit: false; readonly value: unknown } + | { readonly omit: true; readonly reason: string } + +function convertJsonSafe(value: unknown, options: { readonly seen: WeakSet; readonly depth: number }): JsonSafeConversion { + if (value === null || Predicate.isString(value) || Predicate.isBoolean(value)) { + return { omit: false, value } + } + if (Predicate.isNumber(value)) { + return { omit: false, value: Number.isFinite(value) ? value : null } + } + if (Predicate.isBigInt(value)) { + return { omit: false, value: value.toString() } + } + if (value === undefined) { + return { omit: true, reason: "undefined" } + } + if (Predicate.isFunction(value)) { + return { omit: true, reason: "function value" } + } + if (Predicate.isSymbol(value)) { + return { omit: true, reason: "symbol value" } + } + if (!Predicate.isObjectOrArray(value)) { + return { omit: true, reason: "unsupported value" } + } + const isMap = value instanceof Map + const isSet = !isMap && value instanceof Set + if (!isMap && !isSet && !isPlainJsonContainer(value)) { + return { omit: true, reason: "class instance" } + } + if (options.seen.has(value)) { + return { omit: true, reason: "circular reference" } + } + if (options.depth >= maxJsonSafeDepth) { + return { omit: true, reason: "maximum object depth exceeded" } + } + options.seen.add(value) + try { + if (isMap) { + try { + const output: Record = {} + let entries: IterableIterator<[unknown, unknown]> + try { + entries = value.entries() + } catch { + return { omit: true, reason: "map entries unavailable" } + } + for (const [key, item] of entries) { + if (!Predicate.isString(key)) { + return { omit: true, reason: "map contains non-string key" } + } + const converted = convertJsonSafe(item, { seen: options.seen, depth: options.depth + 1 }) + if (!converted.omit) output[key] = converted.value + } + return { omit: false, value: output } + } catch { + return { omit: true, reason: "map iteration failed" } + } + } + if (isSet) { + try { + const output: unknown[] = [] + let values: IterableIterator + try { + values = value.values() + } catch { + return { omit: true, reason: "set values unavailable" } + } + for (const item of values) { + const converted = convertJsonSafe(item, { seen: options.seen, depth: options.depth + 1 }) + output.push(converted.omit ? null : converted.value) + } + return { omit: false, value: output } + } catch { + return { omit: true, reason: "set iteration failed" } + } + } + if (Array.isArray(value)) { + let length: number + try { + length = value.length + } catch { + return { omit: true, reason: "array length unavailable" } + } + const items: unknown[] = [] + for (let index = 0; index < length; index++) { + let item: unknown + try { + item = value[index] + } catch { + items.push(null) + continue + } + const converted = convertJsonSafe(item, { seen: options.seen, depth: options.depth + 1 }) + items.push(converted.omit ? null : converted.value) + } + return { + omit: false, + value: items, + } + } + const output: Record = {} + const keys = safeObjectKeys(value) + if (!keys) { + return { omit: true, reason: "object keys unavailable" } + } + for (const key of keys) { + let item: unknown + try { + item = value[key as keyof typeof value] + } catch { + continue + } + const converted = convertJsonSafe(item, { seen: options.seen, depth: options.depth + 1 }) + if (!converted.omit) { + output[key] = converted.value + } + } + return { omit: false, value: output } + } finally { + options.seen.delete(value) + } +} + +function isPlainJsonContainer(value: T): boolean { + if (Array.isArray(value)) { + return true + } + let prototype: unknown + try { + prototype = Object.getPrototypeOf(value) + } catch { + return false + } + return prototype === Object.prototype || prototype === null +} + +function safeObjectKeys(value: T): string[] | undefined { + try { + return Object.keys(value) + } catch { + return undefined + } +} + +function safeJsonStringify(value: unknown): string | undefined { + try { + return JSON.stringify(value) + } catch { + return undefined + } +} diff --git a/packages/browser-extension/cli/src/extension-rpc.ts b/packages/browser-extension/cli/src/extension-rpc.ts new file mode 100644 index 00000000000..18bff9e1497 --- /dev/null +++ b/packages/browser-extension/cli/src/extension-rpc.ts @@ -0,0 +1,218 @@ +import { Effect, Predicate } from "effect" +import { WebSocket } from "ws" +import { + extensionProtocolCompatibility, + type ExtensionCommand, + type ExtensionProtocolCompatibility, + type ExtensionResponse, + type JsonObject, + type JsonValue, +} from "./protocol.ts" +import type { PendingExtensionRequest } from "./relay-types.ts" + +export type ExtensionRpcTimeouts = { + readonly commandTimeoutMs?: number + readonly debuggerCommandTimeoutMs?: number + readonly livenessProbeTimeoutMs?: number +} + +/** + * Request/response correlator for the single extension websocket. + * + * A timed-out command fails only that command. Connection teardown is reserved + * for a failed websocket-level liveness probe, so one hung debugger command + * (for example a dialog-blocked tab) cannot destroy every attached tab's relay + * state. + */ +export class ExtensionRpc { + private socket: WebSocket | undefined + private ready = false + private nextRequestId = 1 + private readonly pendingRequests = new Map() + private livenessProbe: { readonly timeout: NodeJS.Timeout; readonly socket: WebSocket; readonly onPong: () => void } | undefined + version: string | undefined + protocolVersion: number | null | undefined + protocolCompatible: boolean | undefined + protocolLegacy: boolean | undefined + + constructor(private readonly timeouts: ExtensionRpcTimeouts = {}) {} + + get connected(): boolean { + return this.socket?.readyState === WebSocket.OPEN && this.ready && this.protocolCompatible !== false + } + + get acceptsEvents(): boolean { + return this.socket?.readyState === WebSocket.OPEN && this.protocolCompatible === true + } + + isCurrent(socket: WebSocket): boolean { + return this.socket === socket + } + + replaceSocket(socket: WebSocket): void { + this.rejectPending(new Error("Extension replaced")) + this.socket?.close(4001, "Extension replaced") + this.resetConnectionState(socket) + } + + markHandshake(version: string | undefined, reportedProtocolVersion: JsonValue | undefined): ExtensionProtocolCompatibility { + const protocol = extensionProtocolCompatibility(reportedProtocolVersion) + this.version = version + this.protocolVersion = protocol.version + this.protocolCompatible = protocol.compatible + this.protocolLegacy = protocol.legacy + return protocol + } + + markReady(): void { + if (this.protocolCompatible === true) { + this.ready = true + } + } + + disconnectIfCurrent(socket: WebSocket): boolean { + if (this.socket !== socket) { + return false + } + this.resetConnectionState(undefined) + this.rejectPending(new Error("Extension disconnected")) + return true + } + + private resetConnectionState(socket: WebSocket | undefined): void { + this.cancelLivenessProbe() + this.socket = socket + this.ready = false + this.version = undefined + this.protocolVersion = undefined + this.protocolCompatible = undefined + this.protocolLegacy = undefined + } + + close(): void { + this.cancelLivenessProbe() + this.socket?.close() + } + + rejectPending(error: Error): void { + for (const pending of this.pendingRequests.values()) { + pending.reject(error) + } + } + + rejectDebuggerCommandsForTab(tabId: number, error: Error): void { + for (const pending of this.pendingRequests.values()) { + if (pending.debuggerTabId !== tabId) { + continue + } + pending.reject(error) + } + } + + handleResponse(response: ExtensionResponse): boolean { + const pending = this.pendingRequests.get(response.id) + if (!pending) { + return false + } + if (response.error) { + pending.reject(new Error(response.error)) + return true + } + pending.resolve(response.result ?? {}) + return true + } + + send(command: Omit): Effect.Effect { + return Effect.callback((resume) => { + const socket = this.socket + if (this.protocolCompatible === false) { + resume(Effect.fail(new Error(`OpenCode Browser extension protocol ${this.protocolVersion ?? "unknown"} is incompatible`))) + return Effect.void + } + if (!socket || socket.readyState !== WebSocket.OPEN || !this.acceptsEvents) { + resume(Effect.fail(new Error("OpenCode Browser extension is not connected"))) + return Effect.void + } + + const id = this.nextRequestId++ + const message: ExtensionCommand = { ...command, id } + let completed = false + const timeoutMs = command.method === "debugger.sendCommand" + ? this.timeouts.debuggerCommandTimeoutMs ?? 60_000 + : this.timeouts.commandTimeoutMs ?? 15_000 + const finish = (effect: Effect.Effect) => { + if (completed) { + return + } + completed = true + clearTimeout(timeout) + this.pendingRequests.delete(id) + resume(effect) + } + const timeout = setTimeout(() => { + // Fail only this command. Close the socket only if the websocket + // itself is unresponsive to a protocol-level ping. + this.probeLiveness(socket) + finish(Effect.fail(new Error(`Extension command timed out after ${timeoutMs}ms: ${command.method}`))) + }, timeoutMs) + const debuggerTabId = command.method === "debugger.sendCommand" && Predicate.isNumber(command.params?.tabId) + ? command.params.tabId + : undefined + this.pendingRequests.set(id, { + resolve: (value) => { + finish(Effect.succeed(value)) + }, + reject: (error) => { + finish(Effect.fail(error)) + }, + ...(debuggerTabId === undefined ? {} : { debuggerTabId }), + }) + try { + socket.send(JSON.stringify(message), (error) => { + if (error) { + finish(Effect.fail(new Error(`send extension command: ${command.method}`, { cause: error }))) + } + }) + } catch (error) { + finish(Effect.fail(new Error(`send extension command: ${command.method}`, { cause: error }))) + } + return Effect.sync(() => { + completed = true + clearTimeout(timeout) + this.pendingRequests.delete(id) + }) + }) + } + + probeLiveness(socket = this.socket): void { + if (!socket || this.socket !== socket || this.livenessProbe || socket.readyState !== WebSocket.OPEN) { + return + } + const probeTimeoutMs = this.timeouts.livenessProbeTimeoutMs ?? 10_000 + const onPong = () => { + if (this.livenessProbe?.socket !== socket) return + this.cancelLivenessProbe() + } + const timeout = setTimeout(() => { + if (this.livenessProbe?.socket !== socket) return + this.cancelLivenessProbe() + socket.close(4002, "Extension websocket did not answer liveness probe") + }, probeTimeoutMs) + this.livenessProbe = { timeout, socket, onPong } + socket.on("pong", onPong) + try { + socket.ping() + } catch { + // If ping cannot be sent the socket is already failing; let the probe + // timeout close it. + } + } + + private cancelLivenessProbe(): void { + if (this.livenessProbe) { + clearTimeout(this.livenessProbe.timeout) + this.livenessProbe.socket.off("pong", this.livenessProbe.onPong) + this.livenessProbe = undefined + } + } +} diff --git a/packages/browser-extension/cli/src/flight-recorder.ts b/packages/browser-extension/cli/src/flight-recorder.ts new file mode 100644 index 00000000000..eb7f31bd951 --- /dev/null +++ b/packages/browser-extension/cli/src/flight-recorder.ts @@ -0,0 +1,293 @@ +import fs from "node:fs/promises" +import path from "node:path" +import { performance } from "node:perf_hooks" +import type { JsonObject } from "./protocol.ts" +import { getNumber, getObject, getString } from "./relay-helpers.ts" +import type { FlightRecorderSaveResponse, FlightRecorderStatusResponse } from "./relay-schema.ts" +import { + cdpArtifactType, + findByRecordingTarget, + prepareCdpScreencastViewport, + startFfmpegVideoEncoder, + type RecordingTargetOptions, + type SendDebuggerCommand, + type StartVideoEncoder, +} from "./recording-relay.ts" + +const defaultRetentionMs = 60_000 +const defaultFrameRate = 60 +const maxRetentionMs = 120_000 +const maxBufferedBytes = 128 * 1024 * 1024 +const maxBufferedFrames = 7_200 + +type BufferedFrame = { + readonly data: Buffer + readonly receivedAt: number + readonly surfaceWidth?: number +} + +type ActiveFlightRecorder = { + readonly tabId: number + readonly sessionId?: string + readonly retentionMs: number + readonly frameRate: number + readonly startedAt: number + readonly width: number + readonly height: number + readonly frames: BufferedFrame[] + bufferedBytes: number + sourceFrameCount: number + droppedFrameCount: number + savePromise?: Promise +} + +export type FlightRecorderTarget = RecordingTargetOptions + +export type FlightRecorderStartOptions = { + readonly tabId: number + readonly sessionId?: string + readonly retentionMs?: number + readonly frameRate?: number +} + +export type FlightRecorderStatus = FlightRecorderStatusResponse + +export type FlightRecorderSaveReceipt = FlightRecorderSaveResponse + +export class FlightRecorderRelay { + private readonly active = new Map() + private readonly starting = new Set() + + constructor(readonly options: { + readonly sendDebuggerCommand: SendDebuggerCommand + readonly isExtensionConnected: () => boolean + readonly isTabRecording?: (tabId: number) => boolean + readonly startVideoEncoder?: StartVideoEncoder + readonly now?: () => number + readonly monotonicNow?: () => number + }) {} + + hasActiveRecorders(): boolean { + return this.active.size > 0 || this.starting.size > 0 + } + + isActiveTab(tabId: number): boolean { + return this.active.has(tabId) || this.starting.has(tabId) + } + + async start(options: FlightRecorderStartOptions): Promise { + if (!this.options.isExtensionConnected()) throw new Error("OpenCode Browser extension is not connected") + if (this.isActiveTab(options.tabId)) throw new Error("Flight recorder already active for this tab") + if (this.options.isTabRecording?.(options.tabId)) throw new Error("Stop the active recording before starting the flight recorder") + const retentionMs = options.retentionMs ?? defaultRetentionMs + if (!Number.isInteger(retentionMs) || retentionMs < 1_000 || retentionMs > maxRetentionMs) { + throw new Error("Flight recorder retentionMs must be an integer from 1000 to 120000") + } + const frameRate = options.frameRate ?? defaultFrameRate + if (!Number.isInteger(frameRate) || frameRate < 1 || frameRate > 60) { + throw new Error("Flight recorder frameRate must be an integer from 1 to 60") + } + this.starting.add(options.tabId) + try { + const { width, height } = await prepareCdpScreencastViewport(this.options.sendDebuggerCommand, options.tabId) + const recorder: ActiveFlightRecorder = { + tabId: options.tabId, + ...(options.sessionId ? { sessionId: options.sessionId } : {}), + retentionMs, + frameRate, + startedAt: this.now(), + width, + height, + frames: [], + bufferedBytes: 0, + sourceFrameCount: 0, + droppedFrameCount: 0, + } + this.active.set(options.tabId, recorder) + await this.options.sendDebuggerCommand({ + tabId: options.tabId, + method: "Page.startScreencast", + params: { format: "jpeg", quality: 90, everyNthFrame: 1 }, + }) + return this.statusFor(recorder) + } catch (error) { + this.active.delete(options.tabId) + throw error + } finally { + this.starting.delete(options.tabId) + } + } + + status(target: FlightRecorderTarget): FlightRecorderStatus { + const recorder = this.find(target) + return recorder ? this.statusFor(recorder) : { active: false } + } + + async saveLast(target: FlightRecorderTarget & { readonly outputPath: string; readonly durationMs?: number }): Promise { + const recorder = this.find(target) + if (!recorder) throw new Error("No active flight recorder found") + if (recorder.savePromise) throw new Error("Flight recorder save already in progress") + const savePromise = this.saveLastForRecorder(recorder, target) + recorder.savePromise = savePromise + try { + return await savePromise + } finally { + if (recorder.savePromise === savePromise) delete recorder.savePromise + } + } + + private async saveLastForRecorder( + recorder: ActiveFlightRecorder, + target: FlightRecorderTarget & { readonly outputPath: string; readonly durationMs?: number }, + ): Promise { + const artifactType = cdpArtifactType(target.outputPath) + if (!artifactType) throw new Error("Flight recorder output path must end in .webm or .mp4") + const requestedDuration = target.durationMs ?? Math.min(30_000, recorder.retentionMs) + if (!Number.isInteger(requestedDuration) || requestedDuration < 1 || requestedDuration > recorder.retentionMs) { + throw new Error(`Flight recorder durationMs must be an integer from 1 to ${recorder.retentionMs}`) + } + if (recorder.frames.length === 0) throw new Error("Flight recorder has not captured any frames yet") + await assertOutputAvailable(target.outputPath) + await assertOutputAvailable(`${target.outputPath}.json`) + const newestAt = recorder.frames.at(-1)!.receivedAt + const frames = recorder.frames.filter((frame) => frame.receivedAt >= newestAt - requestedDuration) + const startAt = frames[0]!.receivedAt + const endAt = frames.at(-1)!.receivedAt + const durationMs = Math.max(1, endAt - startAt) + await fs.mkdir(path.dirname(target.outputPath), { recursive: true }) + let encoder: Awaited> | undefined + try { + encoder = await (this.options.startVideoEncoder ?? startFfmpegVideoEncoder)({ + outputPath: target.outputPath, + artifactType, + frameRate: recorder.frameRate, + width: recorder.width, + height: recorder.height, + }) + for (const [index, frame] of frames.entries()) { + const next = frames[index + 1] + const timestampMs = frame.receivedAt - startAt + const frameDurationMs = Math.max(1, (next?.receivedAt ?? endAt + Math.round(1_000 / recorder.frameRate)) - frame.receivedAt) + await encoder.write(frame.data, timestampMs, frameDurationMs, frame.surfaceWidth) + } + await encoder.finish() + const receipt = { + path: target.outputPath, + durationMs, + frameCount: frames.length, + sourceFrameCount: recorder.sourceFrameCount, + droppedFrameCount: recorder.droppedFrameCount, + } + await fs.writeFile(`${target.outputPath}.json`, `${JSON.stringify({ ...receipt, savedAt: new Date(this.now()).toISOString(), retainedDurationMs: this.retainedDuration(recorder) }, null, 2)}\n`, "utf8") + return receipt + } catch (error) { + await encoder?.cancel().catch(() => {}) + throw error + } + } + + async cancel(target: FlightRecorderTarget): Promise<{ readonly cancelled: boolean }> { + const recorder = this.find(target) + if (!recorder) return { cancelled: false } + await recorder.savePromise?.catch(() => {}) + this.active.delete(recorder.tabId) + await this.options.sendDebuggerCommand({ tabId: recorder.tabId, method: "Page.stopScreencast", params: {} }).catch(() => {}) + return { cancelled: true } + } + + async cleanupAll(): Promise { + await Promise.all([...this.active.values()].map((recorder) => this.cancel({ tabId: recorder.tabId }))) + } + + handleDebuggerEvent(options: { readonly tabId: number; readonly method: string; readonly params: JsonObject | undefined }): boolean { + if (options.method !== "Page.screencastFrame") return false + const recorder = this.active.get(options.tabId) + if (!recorder) return false + const frameSessionId = getNumber(options.params, "sessionId") + if (frameSessionId !== undefined) { + void this.options.sendDebuggerCommand({ + tabId: recorder.tabId, + method: "Page.screencastFrameAck", + params: { sessionId: frameSessionId }, + }).catch(() => {}) + } + const frameData = getString(options.params, "data") + if (frameData === undefined) return true + recorder.sourceFrameCount += 1 + if (frameData.length > Math.ceil(maxBufferedBytes * 4 / 3) + 4) { + recorder.droppedFrameCount += 1 + return true + } + const data = Buffer.from(frameData, "base64") + if (data.byteLength > maxBufferedBytes) { + recorder.droppedFrameCount += 1 + return true + } + const surfaceWidth = getNumber(getObject(options.params?.metadata), "deviceWidth") + const frame: BufferedFrame = { + data, + receivedAt: this.monotonicNow(), + ...(surfaceWidth !== undefined ? { surfaceWidth } : {}), + } + recorder.frames.push(frame) + recorder.bufferedBytes += data.byteLength + this.trim(recorder, frame.receivedAt) + return true + } + + private trim(recorder: ActiveFlightRecorder, now: number): void { + while (recorder.frames.length > 0 && ( + now - recorder.frames[0]!.receivedAt > recorder.retentionMs || + recorder.frames.length > maxBufferedFrames || + recorder.bufferedBytes > maxBufferedBytes + )) { + const removed = recorder.frames.shift()! + recorder.bufferedBytes -= removed.data.byteLength + recorder.droppedFrameCount += 1 + } + } + + private retainedDuration(recorder: ActiveFlightRecorder): number { + if (recorder.frames.length < 2) return 0 + return Math.max(0, recorder.frames.at(-1)!.receivedAt - recorder.frames[0]!.receivedAt) + } + + private statusFor(recorder: ActiveFlightRecorder): FlightRecorderStatus { + return { + active: true, + tabId: recorder.tabId, + ...(recorder.sessionId ? { sessionId: recorder.sessionId } : {}), + startedAt: recorder.startedAt, + retentionMs: recorder.retentionMs, + retainedDurationMs: this.retainedDuration(recorder), + frameRate: recorder.frameRate, + bufferedFrames: recorder.frames.length, + bufferedBytes: recorder.bufferedBytes, + sourceFrameCount: recorder.sourceFrameCount, + droppedFrameCount: recorder.droppedFrameCount, + saving: recorder.savePromise !== undefined, + } + } + + private find(target: FlightRecorderTarget): ActiveFlightRecorder | undefined { + return findByRecordingTarget(this.active, target, "Multiple flight recorders are active; provide sessionId or tabId") + } + + private now(): number { + return this.options.now?.() ?? Date.now() + } + + private monotonicNow(): number { + return this.options.monotonicNow?.() ?? performance.now() + } +} + +async function assertOutputAvailable(filePath: string): Promise { + try { + await fs.stat(filePath) + } catch (error) { + if (error instanceof Error && "code" in error && error.code === "ENOENT") return + throw error + } + throw new Error(`Flight recorder output already exists: ${filePath}`) +} diff --git a/packages/browser-extension/cli/src/fs-durability.ts b/packages/browser-extension/cli/src/fs-durability.ts new file mode 100644 index 00000000000..ae5a7d3e135 --- /dev/null +++ b/packages/browser-extension/cli/src/fs-durability.ts @@ -0,0 +1,41 @@ +import { Predicate } from "effect" +import crypto from "node:crypto" +import fs from "node:fs/promises" +import path from "node:path" + +const unsupportedDirectorySyncCodes = new Set(["EPERM", "EINVAL", "ENOTSUP"]) + +export function isNodeError(error: unknown): error is NodeJS.ErrnoException { + return error instanceof Error && "code" in error +} + +export function isUnsupportedDirectorySyncError(error: unknown): boolean { + return isNodeError(error) && + Predicate.isString(error.code) && + unsupportedDirectorySyncCodes.has(error.code) +} + +export async function writeJsonFileAtomically( + filePath: string, + value: unknown, + options: { readonly dirMode?: number } = {}, +): Promise { + const directory = path.dirname(filePath) + await fs.mkdir(directory, { + recursive: true, + ...(options.dirMode === undefined ? {} : { mode: options.dirMode }), + }) + if (options.dirMode !== undefined) { + await fs.chmod(directory, options.dirMode) + } + const temporaryPath = `${filePath}.${process.pid}.${crypto.randomUUID()}.tmp` + let renamed = false + try { + await fs.writeFile(temporaryPath, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 }) + await fs.rename(temporaryPath, filePath) + renamed = true + await fs.chmod(filePath, 0o600) + } finally { + if (!renamed) await fs.rm(temporaryPath, { force: true }).catch(() => {}) + } +} diff --git a/packages/browser-extension/cli/src/ghost-cursor.ts b/packages/browser-extension/cli/src/ghost-cursor.ts new file mode 100644 index 00000000000..aa4faa92ab0 --- /dev/null +++ b/packages/browser-extension/cli/src/ghost-cursor.ts @@ -0,0 +1,1309 @@ +import { Match, Predicate } from "effect" +import type { Locator, Page } from "patchright-core" +import type { JsonObject } from "./protocol.ts" + +type GhostCursorStyle = "distance-glide" | "spring-inertia" + +export type GhostCursorClientOptions = { + readonly color?: string + readonly size?: number + readonly zIndex?: number + readonly style?: GhostCursorStyle +} + +type GhostCursorTone = "neutral" | "accent" | "success" | "warn" + +export type GhostCursorCaptionOptions = { + readonly subtitle?: string + readonly step?: string + readonly tone?: GhostCursorTone +} + +export type GhostCursorCalloutOptions = { + readonly detail?: string + readonly tone?: GhostCursorTone +} + +export type GhostCursorZoomOptions = { + readonly scale?: number + readonly durationMs?: number +} + +export type GhostCursorSpotlightOptions = { + readonly label?: string + readonly detail?: string + readonly tone?: GhostCursorTone + readonly padding?: number + readonly dim?: number +} + +export type GhostCursorMouseAction = { + readonly type: "move" | "down" | "up" + readonly x: number + readonly y: number + readonly button: "left" | "right" | "middle" | "none" +} + +type GhostCursorEvaluatePayload = { + readonly cursorOptions?: GhostCursorClientOptions +} + +type GhostCursorCaptionPayload = { + readonly title: string + readonly options?: GhostCursorCaptionOptions +} + +type GhostCursorRect = { + readonly x: number + readonly y: number + readonly width: number + readonly height: number +} + +type GhostCursorCalloutPayload = { + readonly rect: GhostCursorRect + readonly label: string + readonly options?: GhostCursorCalloutOptions +} + +type GhostCursorZoomPayload = { + readonly rect: GhostCursorRect | null + readonly scale: number + readonly durationMs: number +} + +type GhostCursorSpotlightPayload = { + readonly rect: GhostCursorRect | null + readonly options?: GhostCursorSpotlightOptions +} + +type GhostCursorKeysPayload = { + readonly keys: readonly string[] + readonly label?: string +} + +type GhostCursorBrowserApi = { + readonly show: (options?: GhostCursorClientOptions) => void + readonly hide: () => void + readonly restore: (position: { readonly x: number; readonly y: number }) => void + readonly applyMouseEvent: (action: GhostCursorMouseAction) => Promise + readonly setCaption: (payload: GhostCursorCaptionPayload | null) => void + readonly showCallout: (payload: GhostCursorCalloutPayload) => void + readonly clearCallouts: () => void + readonly zoomTo: (payload: GhostCursorZoomPayload) => Promise + readonly setSpotlight: (payload: GhostCursorSpotlightPayload) => Promise + readonly showKeys: (payload: GhostCursorKeysPayload) => void + readonly isVisible: () => boolean +} + +const ghostCursorElementId = "__opencode_browser_ghost_cursor__" + +export const ghostCursorClientSource = `(() => { + if (window !== window.top) { + return; + } + if (globalThis.__opencodeBrowserGhostCursor?.version === 12) { + return; + } + globalThis.__opencodeBrowserGhostCursor?.hide?.(); + const cursorId = "${ghostCursorElementId}"; + const stageId = "__opencode_browser_ghost_stage__"; + const captionId = "__opencode_browser_ghost_caption__"; + const spotlightId = "__opencode_browser_ghost_spotlight__"; + const keysId = "__opencode_browser_ghost_keys__"; + const positionStorageKey = "__opencode_browser_ghost_cursor_position__"; + const captionStorageKey = "__opencode_browser_ghost_cursor_caption__"; + const defaults = { + color: "#1c1c1f", + size: 23, + zIndex: 2147483646, + style: "distance-glide", + }; + const svgNamespace = "http://www.w3.org/2000/svg"; + const cursorPathData = + "M0.92 2.18C0.61 1.37 1.42 0.58 2.23 0.9L14.39 5.68C15.23 6.01 15.23 7.2 14.39 7.54L9.86 9.37C9.61 9.47 9.41 9.67 9.31 9.92L7.44 14.42C7.09 15.25 5.9 15.23 5.58 14.39L0.92 2.18Z"; + + const PI = Math.PI; + const FRAME_MS = 1000 / 60; + const tones = { + neutral: "#e0b35a", + accent: "#93c5fd", + success: "#a8ba96", + warn: "#f59e0b", + }; + const initialX = Math.round(window.innerWidth / 2); + const initialY = Math.round(window.innerHeight / 2); + + const state = { + element: null, + arrow: null, + stage: null, + targetX: initialX, + targetY: initialY, + renderedX: initialX, + renderedY: initialY, + vx: 0, + vy: 0, + deg: 0, + vDeg: 0, + scale: 1, + vScale: 0, + arcSign: 1, + lastMoveDist: 0, + flight: null, + camera: { scale: 1, tx: 0, ty: 0 }, + cameraAnim: null, + spotlight: null, + spotlightAnim: null, + keysTimer: undefined, + effects: [], + flightResolvers: [], + activeUntil: 0, + actionQueue: Promise.resolve(), + tickTimer: undefined, + previousFrameTime: undefined, + nextTickDue: 0, + mode: "auto", + options: defaults, + fadeTimer: undefined, + removeTimer: undefined, + }; + const clamp = (value, min, max) => Math.max(min, Math.min(max, value)); + const smoothstep = (e0, e1, x) => { + const t = clamp((x - e0) / Math.max(1e-5, e1 - e0), 0, 1); + return t * t * (3 - 2 * t); + }; + const smootherstep = (t) => { + const u = clamp(t, 0, 1); + return u * u * u * (u * (u * 6 - 15) + 10); + }; + const easeOutExpo = (t) => { + const u = clamp(t, 0, 1); + return u === 1 ? 1 : 1 - Math.pow(2, -10 * u); + }; + const easeOutQuart = (t) => 1 - Math.pow(1 - clamp(t, 0, 1), 4); + const mergeOptions = (options) => ({ + color: typeof options?.color === "string" ? options.color : defaults.color, + size: typeof options?.size === "number" && Number.isFinite(options.size) ? options.size : defaults.size, + zIndex: typeof options?.zIndex === "number" && Number.isFinite(options.zIndex) ? options.zIndex : defaults.zIndex, + style: typeof options?.style === "string" ? options.style : state.options.style || defaults.style, + }); + const formatCoord = (value) => String(Number(value.toFixed(2))); + const applyCamera = () => { + const body = document.body; + if (!body) return; + const { scale, tx, ty } = state.camera; + if (Math.abs(scale - 1) < 0.001 && Math.abs(tx) < 0.25 && Math.abs(ty) < 0.25) { + body.style.transform = ""; + body.style.transformOrigin = ""; + return; + } + body.style.transformOrigin = "0 0"; + body.style.transform = "translate3d(" + formatCoord(tx) + "px, " + formatCoord(ty) + "px, 0) scale(" + formatCoord(scale) + ")"; + }; + const applyPosition = () => { + if (!state.element) return; + state.element.style.transform = "translate3d(" + formatCoord(state.renderedX) + "px, " + formatCoord(state.renderedY) + "px, 0)"; + if (state.arrow) { + const pressed = state.element.dataset.pressed === "true"; + const cameraBoost = Math.pow(Math.max(1, state.camera.scale), 0.32); + state.arrow.style.transform = "rotate(" + formatCoord(state.deg) + "deg) scale(" + formatCoord(state.scale * cameraBoost) + ")"; + state.arrow.style.filter = pressed + ? "drop-shadow(0 1px 2px rgba(0,0,0,0.52))" + : "drop-shadow(0 2.5px 5px rgba(0,0,0,0.34)) drop-shadow(0 0.5px 1.5px rgba(0,0,0,0.22))"; + } + }; + + const sampleBezier = (b, u) => { + const inv = 1 - u; + const x = inv * inv * inv * b.x0 + 3 * inv * inv * u * b.cx1 + 3 * inv * u * u * b.cx2 + u * u * u * b.x1; + const y = inv * inv * inv * b.y0 + 3 * inv * inv * u * b.cy1 + 3 * inv * u * u * b.cy2 + u * u * u * b.y1; + const tx = 3 * inv * inv * (b.cx1 - b.x0) + 6 * inv * u * (b.cx2 - b.cx1) + 3 * u * u * (b.x1 - b.cx2); + const ty = 3 * inv * inv * (b.cy1 - b.y0) + 6 * inv * u * (b.cy2 - b.cy1) + 3 * u * u * (b.y1 - b.cy2); + return { x, y, heading: Math.atan2(ty, tx) }; + }; + + const ensureStage = () => { + const existing = document.getElementById(stageId); + if (existing instanceof HTMLDivElement) { + state.stage = existing; + return existing; + } + const stage = document.createElement("div"); + stage.id = stageId; + stage.setAttribute("aria-hidden", "true"); + stage.style.cssText = "position:fixed;inset:0;pointer-events:none;z-index:" + (state.options.zIndex - 1) + ";overflow:hidden;font-family:-apple-system,BlinkMacSystemFont,'Inter','SF Pro Text',sans-serif;"; + document.documentElement.appendChild(stage); + state.stage = stage; + return stage; + }; + const createSvgOverlay = (x, y, boxSize) => { + const stage = ensureStage(); + const svg = document.createElementNS(svgNamespace, "svg"); + const half = boxSize / 2; + svg.setAttribute("viewBox", (-half) + " " + (-half) + " " + boxSize + " " + boxSize); + svg.style.cssText = "position:fixed;left:" + formatCoord(x - half) + "px;top:" + formatCoord(y - half) + "px;width:" + boxSize + "px;height:" + boxSize + "px;pointer-events:none;overflow:visible;"; + stage.appendChild(svg); + return svg; + }; + const populateChip = (chip, toneColor, label, detail) => { + chip.replaceChildren(); + if (!label) { + chip.style.display = "none"; + return; + } + const dot = document.createElement("span"); + dot.style.cssText = "width:7px;height:7px;border-radius:999px;background:" + toneColor + ";flex-shrink:0;"; + const txt = document.createElement("span"); + txt.textContent = label; + chip.append(dot, txt); + if (detail) { + const det = document.createElement("span"); + det.textContent = detail; + det.style.cssText = "font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:11px;font-weight:500;color:#9ca3af;"; + chip.appendChild(det); + } + }; + const styleChipAtRect = (chip, x, y, h, alpha = 1) => { + const placeAbove = y > 64; + const chipTop = placeAbove ? Math.max(12, y - 40) : Math.min(window.innerHeight - 48, y + h + 12); + const chipLeft = clamp(x, 16, Math.max(16, window.innerWidth - 320)); + chip.style.cssText = [ + "position:fixed", + "left:" + formatCoord(chipLeft) + "px", + "top:" + formatCoord(chipTop) + "px", + "display:inline-flex", + "align-items:center", + "gap:8px", + "padding:5px 12px", + "background:rgba(14, 14, 13, 0.94)", + "backdrop-filter:blur(12px)", + "border:1px solid rgba(255,255,255,0.16)", + "border-radius:999px", + "box-shadow:0 10px 24px rgba(0,0,0,0.42)", + "font-size:12px", + "font-weight:600", + "color:#f4f3ef", + "white-space:nowrap", + "opacity:" + formatCoord(alpha), + ].join(";"); + }; + + // Tactile specular bloom + SVG variable-stroke shockwave ring + const spawnClickPulse = (x, y, phase) => { + const now = performance.now(); + const R = 24 * Math.pow(Math.max(1, state.camera.scale), 0.25); + + if (phase === "down") { + const svg = createSvgOverlay(x, y, 64); + const halo = document.createElementNS(svgNamespace, "circle"); + halo.setAttribute("r", "4"); + halo.setAttribute("fill", "rgba(250, 250, 249, 0.28)"); + const dot = document.createElementNS(svgNamespace, "circle"); + dot.setAttribute("r", "3.2"); + dot.setAttribute("fill", "#fafaf9"); + dot.setAttribute("stroke", "rgba(24, 24, 27, 0.65)"); + dot.setAttribute("stroke-width", "1.2"); + svg.append(halo, dot); + state.effects.push({ + el: svg, + startTime: now, + durationMs: 130, + step: (u) => { + const e = easeOutQuart(u); + halo.setAttribute("r", formatCoord(3 + 8 * e)); + halo.setAttribute("opacity", formatCoord(0.55 * (1 - e))); + dot.setAttribute("r", formatCoord(2.2 + 2.6 * Math.sin(u * PI))); + dot.setAttribute("opacity", formatCoord(1 - u * 0.6)); + }, + }); + return; + } + + const svg = createSvgOverlay(x, y, 100); + const bloom = document.createElementNS(svgNamespace, "circle"); + bloom.setAttribute("fill", "rgba(250, 250, 249, 0.16)"); + const contrastRing = document.createElementNS(svgNamespace, "circle"); + contrastRing.setAttribute("fill", "none"); + contrastRing.setAttribute("stroke", "rgba(18, 18, 20, 0.55)"); + const mainRing = document.createElementNS(svgNamespace, "circle"); + mainRing.setAttribute("fill", "none"); + mainRing.setAttribute("stroke", "#fafaf9"); + svg.append(bloom, contrastRing, mainRing); + state.effects.push({ + el: svg, + startTime: now, + durationMs: 300, + step: (u) => { + const e = easeOutExpo(u); + const r = 4 + (R - 4) * e; + const sw = 2.8 * (1 - 0.84 * e); + const alpha = (1 - u) * (1 - u * 0.35); + bloom.setAttribute("r", formatCoord(r * 0.82)); + bloom.setAttribute("opacity", formatCoord(Math.pow(1 - u, 2.2) * 0.85)); + contrastRing.setAttribute("r", formatCoord(r)); + contrastRing.setAttribute("stroke-width", formatCoord(sw + 1.6)); + contrastRing.setAttribute("opacity", formatCoord(alpha * 0.65)); + mainRing.setAttribute("r", formatCoord(r)); + mainRing.setAttribute("stroke-width", formatCoord(sw)); + mainRing.setAttribute("opacity", formatCoord(alpha)); + }, + }); + }; + const stepEffects = (timestamp) => { + for (let i = state.effects.length - 1; i >= 0; i--) { + const fx = state.effects[i]; + const u = (timestamp - fx.startTime) / fx.durationMs; + if (u >= 1) { + fx.el.remove(); + state.effects.splice(i, 1); + continue; + } + fx.step(u); + } + }; + const flushFlightResolvers = () => { + const resolvers = state.flightResolvers.splice(0); + for (const resolve of resolvers) { + try { resolve(); } catch {} + } + }; + + const stepCameraAndSpotlight = (timestamp) => { + let active = false; + if (state.cameraAnim) { + const ca = state.cameraAnim; + const u = clamp((timestamp - ca.startTime) / ca.durationMs, 0, 1); + const s = smootherstep(u); + const vw = window.innerWidth; + const vh = window.innerHeight; + const scale = Math.exp(ca.logS0 + (ca.logS1 - ca.logS0) * s); + const fx = ca.fx0 + (ca.fx1 - ca.fx0) * s; + const fy = ca.fy0 + (ca.fy1 - ca.fy0) * s; + state.camera.scale = scale; + state.camera.tx = clamp(vw / 2 - fx * scale, vw * (1 - scale), 0); + state.camera.ty = clamp(vh / 2 - fy * scale, vh * (1 - scale), 0); + applyCamera(); + if (!state.flight && ca.cursorPageX !== undefined) { + state.renderedX = ca.cursorPageX * state.camera.scale + state.camera.tx; + state.renderedY = ca.cursorPageY * state.camera.scale + state.camera.ty; + state.targetX = state.renderedX; + state.targetY = state.renderedY; + state.vx = 0; + state.vy = 0; + } + if (u >= 1) { + const resolve = ca.resolve; + state.cameraAnim = null; + try { resolve?.(); } catch {} + } else { + active = true; + } + } + if (state.spotlightAnim && state.spotlight) { + const sa = state.spotlightAnim; + const u = clamp((timestamp - sa.startTime) / sa.durationMs, 0, 1); + const s = smootherstep(u); + const sp = state.spotlight; + sp.x = sa.x0 + (sa.x1 - sa.x0) * s; + sp.y = sa.y0 + (sa.y1 - sa.y0) * s; + sp.w = sa.w0 + (sa.w1 - sa.w0) * s; + sp.h = sa.h0 + (sa.h1 - sa.h0) * s; + sp.alpha = sa.a0 + (sa.a1 - sa.a0) * s; + sp.render(); + if (u >= 1) { + const resolve = sa.resolve; + state.spotlightAnim = null; + if (sp.alpha <= 0.01) { + sp.el.remove(); + state.spotlight = null; + } + try { resolve?.(); } catch {} + } else { + active = true; + } + } + return active; + }; + + const stepMotion = (timestamp, dt) => { + stepEffects(timestamp); + const camActive = stepCameraAndSpotlight(timestamp); + const pressed = state.element?.dataset.pressed === "true"; + const pressDip = pressed ? -4.5 : 0; + + if (state.flight) { + const f = state.flight; + const u = clamp((timestamp - f.startTime) / f.durationMs, 0, 1); + const s = smootherstep(u); + const sample = sampleBezier(f.bezier, s); + const prevX = state.renderedX; + const prevY = state.renderedY; + state.renderedX = sample.x; + state.renderedY = sample.y; + state.vx = (state.renderedX - prevX) / dt; + state.vy = (state.renderedY - prevY) / dt; + + const bell = Math.pow(Math.sin(PI * Math.pow(u, 0.82)), 1.15); + const bankDir = clamp((f.bezier.x1 - f.bezier.x0) / Math.max(40, f.dist), -1, 1) * 0.72 + state.arcSign * 0.28; + const targetDeg = bankDir * 28 * f.farFactor * bell; + state.deg += (targetDeg + pressDip - state.deg) * Math.min(1, dt * 30); + + if (u >= 1) { + const endSample = sampleBezier(f.bezier, 1); + const overshootSpeed = clamp(f.dist * 0.14, 0, 85); + state.vx = Math.cos(endSample.heading) * overshootSpeed; + state.vy = Math.sin(endSample.heading) * overshootSpeed; + state.flight = null; + flushFlightResolvers(); + } + } else { + const omega = 26; + const zeta = 0.88; + const k = omega * omega; + const c = 2 * zeta * omega; + const substeps = 4; + const sdt = dt / substeps; + for (let i = 0; i < substeps; i++) { + const ax = -k * (state.renderedX - state.targetX) - c * state.vx; + const ay = -k * (state.renderedY - state.targetY) - c * state.vy; + state.vx += ax * sdt; + state.vy += ay * sdt; + state.renderedX += state.vx * sdt; + state.renderedY += state.vy * sdt; + } + + const distToTarget = Math.hypot(state.targetX - state.renderedX, state.targetY - state.renderedY); + const speed = Math.hypot(state.vx, state.vy); + if (distToTarget < 1.2 && speed < 18) { + state.renderedX = state.targetX; + state.renderedY = state.targetY; + state.vx = 0; + state.vy = 0; + flushFlightResolvers(); + } + + const distScale = smoothstep(35, 190, state.lastMoveDist); + const velTilt = clamp((state.vx * 0.015 - state.vy * 0.005) * (0.3 + 0.7 * distScale), -16, 16); + const targetDeg = velTilt + pressDip; + const rotAcc = -380 * (state.deg - targetDeg) - 35 * state.vDeg; + state.vDeg += rotAcc * dt; + state.deg += state.vDeg * dt; + if (Math.abs(state.deg - pressDip) < 0.15 && Math.abs(state.vDeg) < 1) { + state.deg = pressDip; + state.vDeg = 0; + } + } + + const targetScale = pressed ? 0.80 : 1; + const scAcc = -680 * (state.scale - targetScale) - 32 * state.vScale; + state.vScale += scAcc * dt; + state.scale += state.vScale * dt; + if (Math.abs(state.scale - targetScale) < 0.005 && Math.abs(state.vScale) < 0.05) { + state.scale = targetScale; + state.vScale = 0; + } + + const moving = Boolean(state.flight) + || camActive + || Math.hypot(state.targetX - state.renderedX, state.targetY - state.renderedY) > 0.25 + || Math.hypot(state.vx, state.vy) > 2 + || Math.abs(state.deg - pressDip) > 0.2 + || Math.abs(state.scale - targetScale) > 0.01; + return moving || state.effects.length > 0 || timestamp < state.activeUntil; + }; + + const onTick = () => { + state.tickTimer = undefined; + if (!state.element && !state.cameraAnim && !state.spotlightAnim) { + state.previousFrameTime = undefined; + flushFlightResolvers(); + state.flight = null; + return; + } + const timestamp = performance.now(); + const dt = state.previousFrameTime === undefined + ? FRAME_MS / 1000 + : clamp((timestamp - state.previousFrameTime) / 1000, 1 / 240, 0.05); + state.previousFrameTime = timestamp; + const active = stepMotion(timestamp, dt); + applyPosition(); + if (active) { + state.nextTickDue = Math.max(timestamp + 4, (state.nextTickDue || timestamp) + FRAME_MS); + state.tickTimer = window.setTimeout(onTick, Math.max(4, Math.round(state.nextTickDue - performance.now()))); + } else { + state.previousFrameTime = undefined; + state.nextTickDue = 0; + } + }; + const startLoop = () => { + if (state.tickTimer === undefined) { + state.nextTickDue = performance.now(); + state.tickTimer = window.setTimeout(onTick, 0); + } + }; + const applyVisualOptions = () => { + if (!state.element) return; + state.element.style.width = state.options.size + "px"; + state.element.style.height = state.options.size + "px"; + state.element.style.zIndex = String(state.options.zIndex); + const arrow = state.arrow; + if (arrow instanceof SVGSVGElement && arrow.firstElementChild) { + arrow.firstElementChild.setAttribute("fill", state.options.color); + } + }; + const ensureElement = () => { + const existing = document.getElementById(cursorId); + if (existing instanceof HTMLDivElement) { + state.element = existing; + state.arrow = existing.querySelector("svg"); + return existing; + } + const element = document.createElement("div"); + element.id = cursorId; + element.setAttribute("aria-hidden", "true"); + element.style.position = "fixed"; + element.style.left = "0"; + element.style.top = "0"; + element.style.pointerEvents = "none"; + element.style.boxSizing = "border-box"; + element.style.transition = "opacity 160ms ease-out"; + element.style.transformOrigin = "0 0"; + element.style.willChange = "transform, opacity"; + element.style.opacity = "0"; + element.dataset.motion = "spring"; + const arrow = document.createElementNS(svgNamespace, "svg"); + arrow.setAttribute("viewBox", "0 0 16 16"); + arrow.style.display = "block"; + arrow.style.width = "100%"; + arrow.style.height = "100%"; + arrow.style.overflow = "visible"; + arrow.style.transformOrigin = "8.75% 8.75%"; + arrow.style.filter = "drop-shadow(0 2.5px 5px rgba(0,0,0,0.34)) drop-shadow(0 0.5px 1.5px rgba(0,0,0,0.22))"; + const arrowPath = document.createElementNS(svgNamespace, "path"); + arrowPath.setAttribute("d", cursorPathData); + arrowPath.setAttribute("fill", state.options.color); + arrowPath.setAttribute("stroke", "#fafafa"); + arrowPath.setAttribute("stroke-width", "1.5"); + arrowPath.setAttribute("stroke-linejoin", "round"); + arrowPath.setAttribute("paint-order", "stroke"); + arrow.appendChild(arrowPath); + element.appendChild(arrow); + document.documentElement.appendChild(element); + state.element = element; + state.arrow = arrow; + return element; + }; + const clearIdleTimers = () => { + if (state.fadeTimer !== undefined) window.clearTimeout(state.fadeTimer); + if (state.removeTimer !== undefined) window.clearTimeout(state.removeTimer); + state.fadeTimer = undefined; + state.removeTimer = undefined; + }; + const scheduleIdleFade = () => { + if (state.mode !== "auto") return; + clearIdleTimers(); + state.fadeTimer = window.setTimeout(() => { + if (state.element) state.element.style.opacity = "0"; + state.removeTimer = window.setTimeout(() => { + state.element?.remove(); + state.element = null; + state.arrow = null; + state.removeTimer = undefined; + }, 160); + state.fadeTimer = undefined; + }, 620); + }; + const show = (options) => { + clearIdleTimers(); + state.options = mergeOptions(options); + state.mode = "persistent"; + const element = ensureElement(); + applyVisualOptions(); + applyPosition(); + element.style.opacity = "1"; + element.dataset.pressed = "false"; + }; + const hide = () => { + clearIdleTimers(); + if (state.tickTimer !== undefined) window.clearTimeout(state.tickTimer); + state.tickTimer = undefined; + state.previousFrameTime = undefined; + flushFlightResolvers(); + state.flight = null; + state.camera = { scale: 1, tx: 0, ty: 0 }; + state.cameraAnim = null; + state.spotlightAnim = null; + state.spotlight = null; + applyCamera(); + state.effects.splice(0); + state.mode = "disabled"; + state.element?.remove(); + state.element = null; + state.arrow = null; + document.getElementById(stageId)?.remove(); + state.stage = null; + }; + const restore = (position) => { + if (typeof position?.x !== "number" || typeof position?.y !== "number") return; + clearIdleTimers(); + state.mode = "persistent"; + state.targetX = position.x; + state.targetY = position.y; + state.renderedX = position.x; + state.renderedY = position.y; + state.vx = 0; + state.vy = 0; + state.deg = 0; + state.vDeg = 0; + state.scale = 1; + state.vScale = 0; + state.flight = null; + const element = ensureElement(); + applyVisualOptions(); + element.dataset.targetX = String(position.x); + element.dataset.targetY = String(position.y); + element.dataset.pressed = "false"; + element.style.opacity = "1"; + applyPosition(); + }; + const waitMs = (ms) => new Promise((resolve) => window.setTimeout(resolve, ms)); + const runSingleMouseAction = (action) => { + if (state.mode === "disabled" || typeof action?.x !== "number" || typeof action?.y !== "number") { + return Promise.resolve(); + } + const element = ensureElement(); + applyVisualOptions(); + state.targetX = action.x; + state.targetY = action.y; + try { + window.sessionStorage.setItem(positionStorageKey, JSON.stringify({ x: action.x, y: action.y })); + } catch {} + element.dataset.targetX = String(action.x); + element.dataset.targetY = String(action.y); + element.style.opacity = "1"; + + if (action.type === "down") { + element.dataset.pressed = "true"; + state.activeUntil = performance.now() + 140; + applyPosition(); + spawnClickPulse(action.x, action.y, "down"); + startLoop(); + scheduleIdleFade(); + return waitMs(35); + } + if (action.type === "up") { + element.dataset.pressed = "false"; + state.vScale = 2.6; + state.activeUntil = performance.now() + 360; + applyPosition(); + spawnClickPulse(action.x, action.y, "up"); + startLoop(); + scheduleIdleFade(); + return waitMs(45); + } + + const dx = action.x - state.renderedX; + const dy = action.y - state.renderedY; + const dist = Math.hypot(dx, dy); + state.lastMoveDist = dist; + if (dist < 4) { + state.renderedX = action.x; + state.renderedY = action.y; + state.vx = 0; + state.vy = 0; + state.deg = 0; + applyPosition(); + scheduleIdleFade(); + return Promise.resolve(); + } + + const style = state.options.style || "distance-glide"; + state.arcSign *= -1; + const nx = -dy / dist; + const ny = dx / dist; + flushFlightResolvers(); + + if (style === "spring-inertia") { + const distGate = smoothstep(38, 190, dist); + const kick = dist * 0.13 * distGate * state.arcSign * 5.2; + state.vx += nx * kick; + state.vy += ny * kick; + state.flight = null; + const expectedMs = clamp(120 + Math.sqrt(dist) * 6.2, 120, 310); + state.activeUntil = performance.now() + expectedMs + 140; + startLoop(); + scheduleIdleFade(); + return new Promise((resolve) => { + const safetyTimer = window.setTimeout(() => { + state.renderedX = action.x; + state.renderedY = action.y; + state.vx = 0; + state.vy = 0; + state.deg = 0; + applyPosition(); + resolve(); + }, expectedMs + 140); + state.flightResolvers.push(() => { + window.clearTimeout(safetyTimer); + resolve(); + }); + }); + } + + const farFactor = smoothstep(50, 220, dist); + const arcOffset = dist * 0.16 * farFactor * state.arcSign; + const durationMs = clamp(125 + Math.sqrt(dist) * 6.2, 125, 315); + state.flight = { + startTime: performance.now(), + durationMs, + dist, + farFactor, + bezier: { + x0: state.renderedX, + y0: state.renderedY, + cx1: state.renderedX + dx * 0.3 + nx * arcOffset, + cy1: state.renderedY + dy * 0.3 + ny * arcOffset, + cx2: state.renderedX + dx * 0.72 + nx * arcOffset * 0.55, + cy2: state.renderedY + dy * 0.72 + ny * arcOffset * 0.55, + x1: action.x, + y1: action.y, + }, + }; + state.activeUntil = performance.now() + durationMs + 150; + startLoop(); + scheduleIdleFade(); + + return new Promise((resolve) => { + const safetyTimer = window.setTimeout(() => { + state.flight = null; + state.renderedX = action.x; + state.renderedY = action.y; + state.deg = 0; + applyPosition(); + resolve(); + }, durationMs + 160); + state.flightResolvers.push(() => { + window.clearTimeout(safetyTimer); + resolve(); + }); + }); + }; + const applyMouseEvent = (action) => { + const next = state.actionQueue.then(() => runSingleMouseAction(action), () => runSingleMouseAction(action)); + state.actionQueue = next; + return next; + }; + + const zoomTo = (payload) => { + const vw = window.innerWidth; + const vh = window.innerHeight; + const S = clamp(typeof payload?.scale === "number" ? payload.scale : 1, 1, 3.2); + const durationMs = clamp(typeof payload?.durationMs === "number" ? payload.durationMs : 360, 80, 1200); + const fx0 = (vw / 2 - state.camera.tx) / state.camera.scale; + const fy0 = (vh / 2 - state.camera.ty) / state.camera.scale; + let fx1 = vw / 2; + let fy1 = vh / 2; + if (payload?.rect && S > 1.001) { + const cx = payload.rect.x + payload.rect.width / 2; + const cy = payload.rect.y + payload.rect.height / 2; + const ux = (cx - state.camera.tx) / state.camera.scale; + const uy = (cy - state.camera.ty) / state.camera.scale; + const halfVisW = (vw * 0.5) / S; + const halfVisH = (vh * 0.5) / S; + fx1 = clamp(ux, halfVisW, vw - halfVisW); + fy1 = clamp(uy, halfVisH, vh - halfVisH); + } + const cursorPageX = (state.renderedX - state.camera.tx) / state.camera.scale; + const cursorPageY = (state.renderedY - state.camera.ty) / state.camera.scale; + return new Promise((resolve) => { + state.cameraAnim = { + startTime: performance.now(), + durationMs, + logS0: Math.log(Math.max(1, state.camera.scale)), + logS1: Math.log(S), + fx0, + fy0, + fx1, + fy1, + cursorPageX, + cursorPageY, + resolve, + }; + state.activeUntil = performance.now() + durationMs + 60; + startLoop(); + }); + }; + + const setSpotlight = (payload) => { + const stage = ensureStage(); + if (!payload?.rect) { + if (!state.spotlight) return Promise.resolve(); + const sp = state.spotlight; + return new Promise((resolve) => { + state.spotlightAnim = { + startTime: performance.now(), + durationMs: 200, + x0: sp.x, y0: sp.y, w0: sp.w, h0: sp.h, a0: sp.alpha, + x1: sp.x, y1: sp.y, w1: sp.w, h1: sp.h, a1: 0, + resolve, + }; + state.activeUntil = performance.now() + 240; + startLoop(); + }); + } + const pad = typeof payload.options?.padding === "number" ? payload.options.padding : 10; + const dim = typeof payload.options?.dim === "number" ? payload.options.dim : 0.56; + const toneColor = tones[payload.options?.tone] || tones.neutral; + const x1 = payload.rect.x - pad; + const y1 = payload.rect.y - pad; + const w1 = payload.rect.width + pad * 2; + const h1 = payload.rect.height + pad * 2; + + if (!state.spotlight) { + const container = document.createElement("div"); + container.id = spotlightId; + container.style.cssText = "position:fixed;inset:0;pointer-events:none;"; + const hole = document.createElement("div"); + const chip = document.createElement("div"); + container.append(hole, chip); + stage.appendChild(container); + state.spotlight = { + el: container, + hole, + chip, + x: x1, y: y1, w: w1, h: h1, + alpha: 0, + dim, + toneColor, + label: "", + render() { + const sp = this; + sp.hole.style.cssText = [ + "position:fixed", + "left:" + formatCoord(sp.x) + "px", + "top:" + formatCoord(sp.y) + "px", + "width:" + formatCoord(sp.w) + "px", + "height:" + formatCoord(sp.h) + "px", + "border-radius:10px", + "border:2px solid " + sp.toneColor, + "box-shadow:0 0 0 9999px rgba(8, 8, 10, " + formatCoord(sp.dim * sp.alpha) + "), 0 0 28px rgba(224,179,90," + formatCoord(0.26 * sp.alpha) + ")", + "opacity:" + formatCoord(sp.alpha), + "box-sizing:border-box", + ].join(";"); + if (sp.label) { + styleChipAtRect(sp.chip, sp.x, sp.y, sp.h, sp.alpha); + } + }, + }; + } + const sp = state.spotlight; + sp.dim = dim; + sp.toneColor = toneColor; + sp.label = payload.options?.label || ""; + populateChip(sp.chip, toneColor, sp.label, payload.options?.detail); + + return new Promise((resolve) => { + state.spotlightAnim = { + startTime: performance.now(), + durationMs: 240, + x0: sp.x, y0: sp.y, w0: sp.w, h0: sp.h, a0: sp.alpha, + x1, y1, w1, h1, a1: 1, + resolve, + }; + state.activeUntil = performance.now() + 270; + startLoop(); + }); + }; + + const showKeys = (payload) => { + if (!payload?.keys?.length) return; + const stage = ensureStage(); + document.getElementById(keysId)?.remove(); + if (state.keysTimer !== undefined) window.clearTimeout(state.keysTimer); + const badge = document.createElement("div"); + badge.id = keysId; + badge.style.cssText = [ + "position:fixed", + "right:28px", + "bottom:24px", + "display:inline-flex", + "align-items:center", + "gap:6px", + "padding:7px 11px", + "background:rgba(16, 16, 15, 0.92)", + "backdrop-filter:blur(14px)", + "-webkit-backdrop-filter:blur(14px)", + "border:1px solid rgba(255,255,255,0.14)", + "border-radius:10px", + "box-shadow:0 12px 28px rgba(0,0,0,0.38)", + "color:#f4f3ef", + ].join(";"); + for (const k of payload.keys) { + const kbd = document.createElement("kbd"); + kbd.textContent = k; + kbd.style.cssText = [ + "display:inline-flex", + "align-items:center", + "justify-content:center", + "min-width:22px", + "height:22px", + "padding:0 6px", + "font-family:ui-monospace,SFMono-Regular,Menlo,monospace", + "font-size:12px", + "font-weight:600", + "color:#fafafa", + "background:rgba(255,255,255,0.11)", + "border:1px solid rgba(255,255,255,0.2)", + "border-bottom-width:2px", + "border-radius:5px", + ].join(";"); + badge.appendChild(kbd); + } + if (payload.label) { + const lbl = document.createElement("span"); + lbl.textContent = payload.label; + lbl.style.cssText = "font-size:12px;font-weight:500;color:#a1a1aa;margin-left:4px;"; + badge.appendChild(lbl); + } + stage.appendChild(badge); + state.keysTimer = window.setTimeout(() => { + badge.remove(); + state.keysTimer = undefined; + }, 1500); + }; + + const setCaption = (payload) => { + const stage = ensureStage(); + const existing = document.getElementById(captionId); + if (!payload || !payload.title) { + try { window.sessionStorage.removeItem(captionStorageKey); } catch {} + if (existing) existing.remove(); + return; + } + try { window.sessionStorage.setItem(captionStorageKey, JSON.stringify(payload)); } catch {} + if (existing) existing.remove(); + const wrap = document.createElement("div"); + wrap.id = captionId; + wrap.style.cssText = [ + "position:fixed", + "left:50%", + "bottom:24px", + "transform:translate3d(-50%, 0, 0)", + "display:flex", + "align-items:stretch", + "gap:12px", + "padding:10px 16px 10px 12px", + "background:rgba(14, 14, 13, 0.88)", + "backdrop-filter:blur(14px)", + "-webkit-backdrop-filter:blur(14px)", + "border:1px solid rgba(255, 255, 255, 0.12)", + "border-radius:10px", + "box-shadow:0 12px 32px rgba(0, 0, 0, 0.35)", + "color:#e2dfd9", + "pointer-events:none", + "max-width:min(680px, 88vw)", + ].join(";"); + const barColor = tones[payload.options?.tone] || tones.neutral; + const bar = document.createElement("div"); + bar.style.cssText = "width:3.5px;border-radius:999px;background:" + barColor + ";"; + const textCol = document.createElement("div"); + textCol.style.cssText = "display:flex;flex-direction:column;justify-content:center;gap:2px;overflow:hidden;"; + const titleRow = document.createElement("div"); + titleRow.style.cssText = "display:flex;align-items:center;gap:8px;font-size:13.5px;font-weight:600;letter-spacing:-0.01em;color:#f4f3ef;white-space:nowrap;"; + if (payload.options?.step) { + const stepBadge = document.createElement("span"); + stepBadge.textContent = payload.options.step; + stepBadge.style.cssText = "font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:11px;font-weight:600;padding:1px 6px;border-radius:4px;background:rgba(255,255,255,0.09);color:" + barColor + ";"; + titleRow.appendChild(stepBadge); + } + const titleSpan = document.createElement("span"); + titleSpan.textContent = payload.title; + titleRow.appendChild(titleSpan); + textCol.appendChild(titleRow); + if (payload.options?.subtitle) { + const sub = document.createElement("div"); + sub.textContent = payload.options.subtitle; + sub.style.cssText = "font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:11.5px;color:#9ca3af;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;"; + textCol.appendChild(sub); + } + wrap.append(bar, textCol); + stage.appendChild(wrap); + }; + const clearCallouts = () => { + const stage = document.getElementById(stageId); + if (!stage) return; + for (const node of Array.from(stage.querySelectorAll("[data-bc-callout='true']"))) { + node.remove(); + } + }; + const showCallout = (payload) => { + if (!payload?.rect) return; + clearCallouts(); + const stage = ensureStage(); + const toneColor = tones[payload.options?.tone] || tones.neutral; + const { x, y, width, height } = payload.rect; + const container = document.createElement("div"); + container.dataset.bcCallout = "true"; + container.style.cssText = "position:fixed;inset:0;pointer-events:none;"; + + const ring = document.createElement("div"); + ring.style.cssText = [ + "position:fixed", + "left:" + formatCoord(x - 4) + "px", + "top:" + formatCoord(y - 4) + "px", + "width:" + formatCoord(width + 8) + "px", + "height:" + formatCoord(height + 8) + "px", + "border-radius:8px", + "border:1.75px solid " + toneColor, + "box-shadow:0 0 0 1px rgba(14,14,13,0.5), 0 0 20px rgba(224,179,90,0.22)", + "box-sizing:border-box", + ].join(";"); + + const chip = document.createElement("div"); + populateChip(chip, toneColor, payload.label, payload.options?.detail); + styleChipAtRect(chip, x, y, height, 1); + container.append(ring, chip); + stage.appendChild(container); + }; + globalThis.__opencodeBrowserGhostCursor = { + version: 12, + show, + hide, + restore, + applyMouseEvent, + setCaption, + showCallout, + clearCallouts, + zoomTo, + setSpotlight, + showKeys, + isVisible: () => state.mode !== "disabled" && Boolean(state.element), + }; + const restoreSavedState = () => { + try { + const savedPosition = JSON.parse(window.sessionStorage.getItem(positionStorageKey) || "null"); + if (typeof savedPosition?.x === "number" && typeof savedPosition?.y === "number") { + restore(savedPosition); + } + const savedCaption = JSON.parse(window.sessionStorage.getItem(captionStorageKey) || "null"); + if (savedCaption?.title) { + setCaption(savedCaption); + } + } catch {} + }; + const isForeignExtensionNode = (node) => { + if (!(node instanceof Element)) return false; + const tag = node.tagName ? node.tagName.toLowerCase() : ""; + if (tag.startsWith("com-1password-") || node.hasAttribute("data-onepassword-extension") || node.hasAttribute("data-lastpass-root")) { + return true; + } + if (tag === "iframe" || tag === "frame" || tag === "object" || tag === "embed") { + const src = node.getAttribute("src") || node.src || ""; + if (typeof src === "string" && src.startsWith("chrome-extension://")) return true; + } + return false; + }; + const sweepForeignExtensionNodes = (root) => { + if (document.getElementById("__opencode_browser_page_status__")?.getAttribute("data-waiting") === "true") return; + if (isForeignExtensionNode(root)) { + root.remove(); + return; + } + if (!root || typeof root.querySelectorAll !== "function") return; + for (const el of root.querySelectorAll("com-1password-notification, com-1password-menu, com-1password-button, [data-onepassword-extension], [data-lastpass-root], iframe[src^='chrome-extension://'], frame[src^='chrome-extension://']")) { + el.remove(); + } + }; + const guardExtensionFrames = () => { + sweepForeignExtensionNodes(document.documentElement); + const extObserver = new MutationObserver((records) => { + if (document.getElementById("__opencode_browser_page_status__")?.getAttribute("data-waiting") === "true") return; + for (const record of records) { + for (const added of record.addedNodes) { + sweepForeignExtensionNodes(added); + } + } + }); + extObserver.observe(document.documentElement, { childList: true, subtree: true }); + }; + if (document.documentElement) { + restoreSavedState(); + guardExtensionFrames(); + } else { + const observer = new MutationObserver(() => { + if (!document.documentElement) return; + observer.disconnect(); + restoreSavedState(); + guardExtensionFrames(); + }); + observer.observe(document, { childList: true }); + } +})();` + +export function inputDispatchMouseEventToGhostCursorAction(params: JsonObject | undefined): GhostCursorMouseAction | undefined { + if (!params) { + return undefined + } + const type = params.type + if (type !== "mouseMoved" && type !== "mousePressed" && type !== "mouseReleased") { + return undefined + } + if (!Predicate.isNumber(params.x) || !Predicate.isNumber(params.y)) { + return undefined + } + const button = parseButton(params.button) + return { + type: Match.value(type).pipe( + Match.when("mousePressed", () => "down" as const), + Match.when("mouseReleased", () => "up" as const), + Match.when("mouseMoved", () => "move" as const), + Match.exhaustive, + ), + x: params.x, + y: params.y, + button, + } +} + +export function ghostCursorMouseActionExpression(action: GhostCursorMouseAction): string { + return `globalThis.__opencodeBrowserGhostCursor?.applyMouseEvent(${JSON.stringify(action)})` +} + +export function ghostCursorRestoreExpression(position: { readonly x: number; readonly y: number }): string { + return `globalThis.__opencodeBrowserGhostCursor?.restore(${JSON.stringify(position)})` +} + +async function ensureGhostCursor(page: Page): Promise { + await page.evaluate(ghostCursorClientSource) +} + +async function resolveTargetBox(page: Page, target: Locator | string): Promise { + const locator = Predicate.isString(target) ? page.locator(target) : target + return await locator.first().boundingBox() +} + +export async function showGhostCursor(options: { readonly page: Page; readonly cursorOptions?: GhostCursorClientOptions }): Promise { + await ensureGhostCursor(options.page) + const payload: GhostCursorEvaluatePayload = options.cursorOptions ? { cursorOptions: options.cursorOptions } : {} + await options.page.evaluate( + (payload: GhostCursorEvaluatePayload) => { + const api = (globalThis as { __opencodeBrowserGhostCursor?: GhostCursorBrowserApi }).__opencodeBrowserGhostCursor + api?.show(payload.cursorOptions) + }, + payload, + ) +} + +export async function hideGhostCursor(options: { readonly page: Page }): Promise { + await options.page.evaluate(() => { + const api = (globalThis as { __opencodeBrowserGhostCursor?: GhostCursorBrowserApi }).__opencodeBrowserGhostCursor + api?.hide() + }) +} + +export async function setGhostCursorCaption(options: { + readonly page: Page + readonly title: string | null + readonly captionOptions?: GhostCursorCaptionOptions +}): Promise { + await ensureGhostCursor(options.page) + const payload: GhostCursorCaptionPayload | null = options.title + ? { title: options.title, ...(options.captionOptions ? { options: options.captionOptions } : {}) } + : null + await options.page.evaluate((captionPayload: GhostCursorCaptionPayload | null) => { + const api = (globalThis as { __opencodeBrowserGhostCursor?: GhostCursorBrowserApi }).__opencodeBrowserGhostCursor + api?.setCaption(captionPayload) + }, payload) +} + +export async function showGhostCursorCallout(options: { + readonly page: Page + readonly target: Locator | string + readonly label: string + readonly calloutOptions?: GhostCursorCalloutOptions +}): Promise { + await ensureGhostCursor(options.page) + const box = await resolveTargetBox(options.page, options.target) + if (!box) return + const payload: GhostCursorCalloutPayload = { + rect: box, + label: options.label, + ...(options.calloutOptions ? { options: options.calloutOptions } : {}), + } + await options.page.evaluate((calloutPayload: GhostCursorCalloutPayload) => { + const api = (globalThis as { __opencodeBrowserGhostCursor?: GhostCursorBrowserApi }).__opencodeBrowserGhostCursor + api?.showCallout(calloutPayload) + }, payload) +} + +export async function clearGhostCursorCallouts(options: { readonly page: Page }): Promise { + await options.page.evaluate(() => { + const api = (globalThis as { __opencodeBrowserGhostCursor?: GhostCursorBrowserApi }).__opencodeBrowserGhostCursor + api?.clearCallouts() + }) +} + +export async function zoomGhostCursorCamera(options: { + readonly page: Page + readonly target: Locator | string | { readonly x: number; readonly y: number } | null + readonly zoomOptions?: GhostCursorZoomOptions +}): Promise { + await ensureGhostCursor(options.page) + let rect: GhostCursorRect | null = null + if (options.target !== null) { + rect = (Predicate.isString(options.target) || "boundingBox" in options.target) + ? await resolveTargetBox(options.page, options.target) + : { x: options.target.x, y: options.target.y, width: 1, height: 1 } + } + const payload: GhostCursorZoomPayload = { + rect, + scale: options.target === null ? 1 : (options.zoomOptions?.scale ?? 1.75), + durationMs: options.zoomOptions?.durationMs ?? 360, + } + await options.page.evaluate(async (zoomPayload: GhostCursorZoomPayload) => { + const api = (globalThis as { __opencodeBrowserGhostCursor?: GhostCursorBrowserApi }).__opencodeBrowserGhostCursor + await api?.zoomTo(zoomPayload) + }, payload) +} + +export async function setGhostCursorSpotlight(options: { + readonly page: Page + readonly target: Locator | string | null + readonly spotlightOptions?: GhostCursorSpotlightOptions +}): Promise { + await ensureGhostCursor(options.page) + const rect = options.target !== null ? await resolveTargetBox(options.page, options.target) : null + const payload: GhostCursorSpotlightPayload = { + rect, + ...(options.spotlightOptions ? { options: options.spotlightOptions } : {}), + } + await options.page.evaluate(async (spotlightPayload: GhostCursorSpotlightPayload) => { + const api = (globalThis as { __opencodeBrowserGhostCursor?: GhostCursorBrowserApi }).__opencodeBrowserGhostCursor + await api?.setSpotlight(spotlightPayload) + }, payload) +} + +export async function showGhostCursorKeys(options: { + readonly page: Page + readonly keys: string | readonly string[] + readonly label?: string +}): Promise { + await ensureGhostCursor(options.page) + const keys = Predicate.isString(options.keys) ? options.keys.split("+").map((k) => k.trim()).filter(Boolean) : options.keys + const payload: GhostCursorKeysPayload = { + keys, + ...(options.label ? { label: options.label } : {}), + } + await options.page.evaluate((keysPayload: GhostCursorKeysPayload) => { + const api = (globalThis as { __opencodeBrowserGhostCursor?: GhostCursorBrowserApi }).__opencodeBrowserGhostCursor + api?.showKeys(keysPayload) + }, payload) +} + +function parseButton(value: JsonObject[string] | undefined): GhostCursorMouseAction["button"] { + if (value === "left" || value === "right" || value === "middle" || value === "none") { + return value + } + return "none" +} diff --git a/packages/browser-extension/cli/src/handoff.ts b/packages/browser-extension/cli/src/handoff.ts new file mode 100644 index 00000000000..2143c22240b --- /dev/null +++ b/packages/browser-extension/cli/src/handoff.ts @@ -0,0 +1,278 @@ +/** + * Human-in-the-loop handoff registry. + * + * A running execute script can call `await handoff("Complete the 2FA prompt")`. + * The sandbox registers a pending handoff for its OpenCode Browser session and + * exact tab, then blocks until the in-page completion control sends the + * matching handoff id or the timeout elapses. + */ + +export type HandoffCancellationReason = "target-detached" | "target-crashed" + +export type HandoffOutcome = + | "resolved" + | "timeout" + | { readonly type: "cancelled"; readonly reason: HandoffCancellationReason } + +type PendingHandoff = { + readonly id: string + readonly sessionId: string + readonly tabId: number + targetId: string + targetSessionId: string + readonly message: string + readonly resolve: (outcome: HandoffOutcome) => void +} + +export type HandoffWait = { + readonly id: string + readonly outcome: Promise + /** End the wait as a timeout if it is still pending. */ + readonly cancel: () => void + /** Defer human completion once, keeping the deadline and target cancellation live while a start action settles. */ + readonly holdCompletion: () => () => void +} + +export async function awaitHandoffAction(options: { + readonly wait: HandoffWait + readonly present?: () => Promise + readonly start?: () => unknown | Promise + readonly cancelStart?: () => Promise +}): Promise { + const { wait } = options + const outcome = wait.outcome.then((value) => ({ type: "handoff-completed" as const, value })) + if (options.present) { + const presentation = options.present().then( + () => ({ type: "presented" as const }), + (error: unknown) => ({ type: "presentation-failed" as const, error }), + ) + const first = await Promise.race([presentation, outcome]) + if (first.type === "handoff-completed") return first.value + if (first.type === "presentation-failed") { + wait.cancel() + throw first.error + } + } + if (!options.start) return await wait.outcome + const releaseCompletion = wait.holdCompletion() + const action = Promise.resolve().then(options.start).then( + () => { + releaseCompletion() + return { type: "action-completed" as const } + }, + (error: unknown) => ({ type: "action-failed" as const, error }), + ) + const first = await Promise.race([action, outcome]) + if (first.type === "action-failed") { + wait.cancel() + throw first.error + } + if (first.type === "action-completed") return await wait.outcome + // A human completion delivered before the hold still lets the action settle. + if (first.value === "resolved" || !options.cancelStart) { + const actionResult = await action + if (actionResult.type === "action-failed") throw actionResult.error + } else { + await options.cancelStart() + } + return first.value +} + +export type PendingHandoffView = { + readonly id: string + readonly sessionId: string + readonly tabId: number + readonly targetId: string + readonly targetSessionId: string + readonly message: string +} + +export type ToolbarClickAction = "ignore" | "toggle" + +export function toolbarClickAction(options: { + readonly handoffPending: boolean + readonly sessionExecuting: boolean +}): ToolbarClickAction { + return options.handoffPending || options.sessionExecuting ? "ignore" : "toggle" +} + +export class HandoffRegistry { + private readonly pending = new Map() + + constructor(private readonly createId: () => string = () => crypto.randomUUID()) {} + + /** + * Register a pending handoff for a session. Only one handoff can be pending + * per session (execute calls are serialized per session). Returns its unique + * id and an outcome promise. + */ + wait(options: { + readonly sessionId: string + readonly tabId: number + readonly targetId: string + readonly targetSessionId: string + readonly message: string + readonly timeoutMs: number + }): HandoffWait { + const existing = this.pending.get(options.sessionId) + if (existing) { + existing.resolve("timeout") + } + const id = this.createId() + let held = false + let humanCompleted = false + let finish: (outcome: HandoffOutcome) => void + const outcome = new Promise((resolvePromise) => { + let pending: PendingHandoff + const timeout = setTimeout(() => finish("timeout"), options.timeoutMs) + finish = (outcome) => { + clearTimeout(timeout) + if (this.pending.get(options.sessionId) === pending) { + this.pending.delete(options.sessionId) + } + resolvePromise(outcome) + } + pending = { + id, + sessionId: options.sessionId, + tabId: options.tabId, + targetId: options.targetId, + targetSessionId: options.targetSessionId, + message: options.message, + resolve: (outcome) => { + if (outcome === "resolved" && held) { + humanCompleted = true + return + } + finish(outcome) + }, + } + this.pending.set(options.sessionId, pending) + }) + return { + id, + outcome, + cancel: () => { + this.cancel(id) + }, + holdCompletion: () => { + held = true + return () => { + if (!held) return + held = false + if (humanCompleted) finish("resolved") + } + }, + } + } + + /** Resolve only the waiter named by its token and exact registry target. */ + complete(options: { + readonly id: string + readonly tabId: number + readonly targetId: string + readonly targetSessionId: string + }): boolean { + const pending = Array.from(this.pending.values()).find((candidate) => candidate.id === options.id) + if ( + !pending || + pending.tabId !== options.tabId || + pending.targetId !== options.targetId || + pending.targetSessionId !== options.targetSessionId + ) { + return false + } + pending.resolve("resolved") + return true + } + + cancel(id: string): boolean { + const pending = Array.from(this.pending.values()).find((candidate) => candidate.id === id) + if (!pending) return false + pending.resolve("timeout") + return true + } + + pendingForSession(sessionId: string): PendingHandoffView | undefined { + return this.view(this.pending.get(sessionId)) + } + + pendingForTab(tabId: number): PendingHandoffView | undefined { + return this.view(Array.from(this.pending.values()).find((pending) => pending.tabId === tabId)) + } + + get pendingCount(): number { + return this.pending.size + } + + rebindTarget(options: { + readonly tabId: number + readonly previousTargetId: string + readonly previousTargetSessionId: string + readonly targetId: string + readonly targetSessionId: string + }): boolean { + const pending = Array.from(this.pending.values()).find((candidate) => { + return candidate.tabId === options.tabId && + candidate.targetId === options.previousTargetId && + candidate.targetSessionId === options.previousTargetSessionId + }) + if (!pending) return false + pending.targetId = options.targetId + pending.targetSessionId = options.targetSessionId + return true + } + + cancelForTarget(options: { + readonly targetId: string + readonly targetSessionId: string + readonly reason: HandoffCancellationReason + }): readonly PendingHandoffView[] { + const matching = Array.from(this.pending.values()).filter((pending) => { + return pending.targetId === options.targetId && pending.targetSessionId === options.targetSessionId + }) + const cancelled = matching.map((pending) => this.view(pending)).filter((pending) => pending !== undefined) + for (const pending of matching) { + pending.resolve({ type: "cancelled", reason: options.reason }) + } + return cancelled + } + + /** Cancel every pending handoff, resolving waiters as timeouts. */ + cancelAll(): void { + for (const pending of Array.from(this.pending.values())) { + pending.resolve("timeout") + } + this.pending.clear() + } + + private view(pending: PendingHandoff | undefined): PendingHandoffView | undefined { + if (!pending) { + return undefined + } + return { + id: pending.id, + sessionId: pending.sessionId, + tabId: pending.tabId, + targetId: pending.targetId, + targetSessionId: pending.targetSessionId, + message: pending.message, + } + } +} + +export function resolveExactHandoffTarget(options: { + readonly targetId: string + readonly targets: readonly T[] + readonly isVisible: (target: T) => boolean +}): T { + const target = options.targets.find((candidate) => candidate.targetInfo.targetId === options.targetId) + if (!target || !options.isVisible(target)) { + throw new Error("Could not bind handoff to the selected page; its target detached or is no longer visible") + } + return target +} diff --git a/packages/browser-extension/cli/src/http-api.ts b/packages/browser-extension/cli/src/http-api.ts new file mode 100644 index 00000000000..fffb40f452e --- /dev/null +++ b/packages/browser-extension/cli/src/http-api.ts @@ -0,0 +1,669 @@ +import type { JsonObject } from "./protocol.ts" +import http from "node:http" +import { Effect, Match, Predicate, Schema } from "effect" +import * as AuthProfile from "./auth-profile.ts" +import { AuthenticatedOriginError } from "./authenticated-origin.ts" +import { NetworkCaptureError } from "./network-capture.ts" +import { + HttpRouteError, + formatHostForUrl, + headerValue, + optionalSessionId, + readJsonBody, + requiredSessionId, + sendJson, + validateBrowserFetchSite, + validateHostHeader, +} from "./relay-helpers.ts" +import { selectTarget, TargetSelectionError } from "./execute.ts" +import type { FlightRecorderRelay } from "./flight-recorder.ts" +import { + AuthProfileRequest, + AuthenticatedJsonRequest, + AuthRefreshRequest, + AuthRunRequest, + ExecuteRequest, + FlightRecorderSaveRequest, + FlightRecorderStartRequest, + NetworkSessionRequest, + NetworkStartRequest, + NetworkStopRequest, + RecordingStartRequest, + RecordingTargetRequest, + type RelayErrorCode, + RelayShutdownRequest, + SessionAdoptRequest, + SessionIdRequest, + SessionEnsureRequest, + SessionNewRequest, + type ExtensionStatus, + type TargetSummary, +} from "./relay-schema.ts" +import { SessionError, type OpenCodeBrowserSessions } from "./session-manager.ts" +import type { RecordingRelay, RecordingStartOptions, RecordingTargetOptions } from "./recording-relay.ts" +import { TargetOwnershipError, type TargetRegistry } from "./target-registry.ts" +import { opencodeBrowserBuildId, opencodeBrowserVersion } from "./version.ts" +import { RelayShutdown, RelayShutdownError } from "./relay-shutdown.ts" + +export function createHttpRequestHandler(options: { + readonly host: string + readonly port: number + readonly browserId: string + readonly relayInstance: { readonly id: string; readonly startedAt: string; readonly pid: number; readonly managed: boolean } + readonly shutdown: RelayShutdown + readonly extensionStatus: () => Pick + readonly recordingRelay: RecordingRelay + readonly flightRecorder: FlightRecorderRelay + readonly registry: TargetRegistry + readonly sessions: OpenCodeBrowserSessions + /** Asks the extension to close agent-opened tabs idle for `idleMinutes` (its setting when omitted). */ + readonly cleanupTabs: (idleMinutes: number | undefined) => Effect.Effect + /** Reloads the extension so an unpacked install picks up files `install` just replaced. */ + readonly reloadExtension: () => Effect.Effect +}): (request: http.IncomingMessage, response: http.ServerResponse) => void { + options.sessions.setUserAttachedPageUrlsProvider(() => + options.registry.listRootTargets() + .filter((target) => target.owner === "user") + .map((target) => target.targetInfo.url || "about:blank") + ) + return (request, response) => { + const hostError = validateHostHeader({ hostHeader: request.headers.host, host: options.host, port: options.port }) + if (hostError) { + sendJson(response, { error: hostError }, 403) + return + } + const fetchSiteError = validateBrowserFetchSite(request) + if (fetchSiteError) { + sendJson(response, { error: fetchSiteError }, 403) + return + } + const requestUrl = new URL(request.url ?? "/", `http://${formatHostForUrl(options.host)}:${options.port}`) + const pathname = requestUrl.pathname.replace(/\/$/, "") || "/" + const observational = request.method === "GET" || pathname === "/network/status" || pathname === "/auth/status" + const run = (effect: Effect.Effect, settle = false): void => { + runRequestEffect(response, observational ? effect : options.shutdown.track(settle ? Effect.uninterruptible(effect) : effect)) + } + if (pathname === "/" || pathname === "/version") { + sendJson(response, { + version: opencodeBrowserVersion, + buildId: opencodeBrowserBuildId, + instanceId: options.relayInstance.id, + startedAt: options.relayInstance.startedAt, + pid: options.relayInstance.pid, + managed: options.relayInstance.managed, + shutdownProtocol: 2, + }) + return + } + if (pathname === "/shutdown" && request.method === "POST") { + runRequestEffect(response, Effect.gen(function* () { + const body = yield* decodeRequest(RelayShutdownRequest, yield* readJsonBody(request), "relay shutdown") + yield* options.shutdown.request(body) + sendJson(response, { stopping: true }) + })) + return + } + if (pathname === "/json/version") { + const opencodeBrowserSessionId = headerValue(request.headers["opencode-browser-session-id"]) + const webSocketDebuggerUrl = new URL(`ws://${formatHostForUrl(options.host)}:${options.port}/devtools/browser/${options.browserId}`) + if (opencodeBrowserSessionId) { + webSocketDebuggerUrl.searchParams.set("opencodeBrowserSessionId", opencodeBrowserSessionId) + } + sendJson(response, { + Browser: `OpenCode-Browser/${opencodeBrowserVersion}`, + "Protocol-Version": "1.3", + webSocketDebuggerUrl: webSocketDebuggerUrl.toString(), + }) + return + } + if (pathname === "/extension/reload" && request.method === "POST") { + run(Effect.gen(function* () { + sendJson(response, yield* options.reloadExtension()) + })) + return + } + if (pathname === "/tabs/cleanup" && request.method === "POST") { + run(Effect.gen(function* () { + const body = yield* readJsonBody(request) + const idleMinutes = typeof body === "object" && body !== null && "idleMinutes" in body && typeof body.idleMinutes === "number" + ? Math.max(0, body.idleMinutes) + : undefined + sendJson(response, yield* options.cleanupTabs(idleMinutes)) + })) + return + } + if (pathname === "/json/list") { + sendJson(response, targetSummaries(options.registry)) + return + } + if (pathname === "/extension/status") { + const extensionStatus = options.extensionStatus() + sendJson(response, { + connected: extensionStatus.connected, + version: extensionStatus.version, + ...(extensionStatus.build === undefined ? {} : { build: extensionStatus.build }), + ...(extensionStatus.origin === undefined ? {} : { origin: extensionStatus.origin }), + ...(extensionStatus.protocolVersion === undefined ? {} : { protocolVersion: extensionStatus.protocolVersion }), + ...(extensionStatus.protocolCompatible === undefined ? {} : { protocolCompatible: extensionStatus.protocolCompatible }), + ...(extensionStatus.protocolLegacy === undefined ? {} : { protocolLegacy: extensionStatus.protocolLegacy }), + ...(extensionStatus.rejectedConnections === undefined ? {} : { rejectedConnections: extensionStatus.rejectedConnections }), + ...(extensionStatus.cdpClients === undefined ? {} : { cdpClients: extensionStatus.cdpClients }), + activeTargets: options.registry.rootTargetCount(), + childTargets: options.registry.childTargets.size, + sessions: options.sessions.listSummaries(), + targets: targetSummaries(options.registry), + }) + return + } + if (pathname.startsWith("/recording/")) { + run(handleRecordingRequest({ request, response, pathname, requestUrl, registry: options.registry, recordingRelay: options.recordingRelay }), true) + return + } + if (pathname.startsWith("/flight-recorder/")) { + run(handleFlightRecorderRequest({ request, response, pathname, requestUrl, registry: options.registry, flightRecorder: options.flightRecorder }), true) + return + } + if (pathname.startsWith("/network/")) { + run(handleNetworkRequest({ request, response, pathname, sessions: options.sessions })) + return + } + if (pathname.startsWith("/auth/")) { + run(handleAuthRequest({ request, response, pathname, sessions: options.sessions }), pathname === "/auth/run") + return + } + if (pathname.startsWith("/v1/")) { + run(handleClientRequest({ + request, + response, + pathname, + sessions: options.sessions, + })) + return + } + if (pathname.startsWith("/cli/")) { + run(handleCliRequest({ + request, + response, + pathname, + sessions: options.sessions, + registry: options.registry, + })) + return + } + response.writeHead(404) + response.end("Not found") + } +} + +function handleClientRequest(options: { + readonly request: http.IncomingMessage + readonly response: http.ServerResponse + readonly pathname: string + readonly sessions: OpenCodeBrowserSessions +}): Effect.Effect { + return Effect.gen(function* () { + if (options.pathname === "/v1/sessions/ensure" && options.request.method === "POST") { + const request = yield* decodeRequest(SessionEnsureRequest, yield* readJsonBody(options.request), "session ensure") + sendJson(options.response, { + session: yield* options.sessions.ensure(request.id, { + ...(request.readOnly === undefined ? {} : { readOnly: request.readOnly }), + }), + }) + return + } + if (options.pathname === "/v1/authenticated-origin/json" && options.request.method === "POST") { + const request = yield* decodeRequest(AuthenticatedJsonRequest, yield* readJsonBody(options.request), "authenticated origin") + options.response.setHeader("cache-control", "no-store") + sendJson(options.response, yield* options.sessions.authenticatedJson(request)) + return + } + options.response.writeHead(404) + options.response.end("Not found") + }) +} + +function handleNetworkRequest(options: { + readonly request: http.IncomingMessage + readonly response: http.ServerResponse + readonly pathname: string + readonly sessions: OpenCodeBrowserSessions +}): Effect.Effect { + return Effect.gen(function* () { + if (options.pathname === "/network/start" && options.request.method === "POST") { + const request = yield* decodeRequest(NetworkStartRequest, yield* readJsonBody(options.request), "network start") + const { sessionId, ...captureOptions } = request + const result = yield* options.sessions.networkStart(sessionId, captureOptions) + sendJson(options.response, result) + return + } + if (options.pathname === "/network/status" && options.request.method === "POST") { + const request = yield* decodeRequest(NetworkSessionRequest, yield* readJsonBody(options.request), "network status") + sendJson(options.response, yield* options.sessions.networkStatus(request.sessionId)) + return + } + if (options.pathname === "/network/stop" && options.request.method === "POST") { + const request = yield* decodeRequest(NetworkStopRequest, yield* readJsonBody(options.request), "network stop") + const { sessionId, ...stopOptions } = request + sendJson(options.response, yield* options.sessions.networkStop(sessionId, stopOptions)) + return + } + if (options.pathname === "/network/cancel" && options.request.method === "POST") { + const request = yield* decodeRequest(NetworkSessionRequest, yield* readJsonBody(options.request), "network cancel") + sendJson(options.response, yield* options.sessions.networkCancel(request.sessionId)) + return + } + options.response.writeHead(404) + options.response.end("Not found") + }) +} + +function handleAuthRequest(options: { + readonly request: http.IncomingMessage + readonly response: http.ServerResponse + readonly pathname: string + readonly sessions: OpenCodeBrowserSessions +}): Effect.Effect { + return Effect.gen(function* () { + if (options.pathname === "/auth/status" && options.request.method === "POST") { + const request = yield* decodeRequest(AuthProfileRequest, yield* readJsonBody(options.request), "auth status") + sendJson(options.response, yield* AuthProfile.status(request.name)) + return + } + if (options.pathname === "/auth/refresh" && options.request.method === "POST") { + const request = yield* decodeRequest(AuthRefreshRequest, yield* readJsonBody(options.request), "auth refresh") + const { sessionId, ...refreshOptions } = request + sendJson(options.response, yield* options.sessions.authRefresh(sessionId, refreshOptions)) + return + } + if (options.pathname === "/auth/run" && options.request.method === "POST") { + const request = yield* decodeRequest(AuthRunRequest, yield* readJsonBody(options.request), "auth run") + sendJson(options.response, yield* AuthProfile.run(request)) + return + } + options.response.writeHead(404) + options.response.end("Not found") + }) +} + +function runRequestEffect(response: http.ServerResponse, effect: Effect.Effect): void { + const controller = new AbortController() + const onClose = () => controller.abort() + response.once("close", onClose) + Effect.runPromise(effect, { signal: controller.signal }).catch((error: unknown) => { + if (response.destroyed || response.writableEnded) return + const routeError = relayHttpError(error) + sendJson(response, { + error: routeError.message, + code: routeError.code, + }, routeError.status) + }).finally(() => { + response.off("close", onClose) + }) +} + +function handleRecordingRequest(options: { + readonly request: http.IncomingMessage + readonly response: http.ServerResponse + readonly pathname: string + readonly requestUrl: URL + readonly registry: TargetRegistry + readonly recordingRelay: RecordingRelay +}): Effect.Effect { + return Effect.gen(function* () { + if (options.pathname === "/recording/start" && options.request.method === "POST") { + const body = yield* readJsonBody(options.request) + const { tabId, sessionId, ...recordingOptions } = yield* decodeRequest(RecordingStartRequest, body, "recording start") + const target = resolveAttachedRecordingTarget({ registry: options.registry, tabId, sessionId }) + const startOptions: RecordingStartOptions = { + ...recordingOptions, + tabId: target.tabId, + ...(target.sessionId ? { sessionId: target.sessionId } : {}), + owner: target.owner, + } + const result = yield* tryRecordingPromise("start recording", () => options.recordingRelay.startRecording(startOptions)) + sendJson(options.response, result, result.success ? 200 : 500) + return + } + if (options.pathname === "/recording/stop" && options.request.method === "POST") { + const body = yield* readJsonBody(options.request) + const request = yield* decodeRequest(RecordingTargetRequest, body, "recording stop") + const target = recordingTargetFromValues({ registry: options.registry, tabId: request.tabId, sessionId: request.sessionId }) + const result = yield* tryRecordingPromise("stop recording", () => options.recordingRelay.stopRecording(target)) + sendJson(options.response, result, result.success ? 200 : 500) + return + } + if (options.pathname === "/recording/status" && options.request.method === "GET") { + const target = recordingTargetFromQuery({ registry: options.registry, searchParams: options.requestUrl.searchParams }) + const result = yield* tryRecordingPromise("recording status", () => options.recordingRelay.statusRecording(target)) + sendJson(options.response, result) + return + } + if (options.pathname === "/recording/cancel" && options.request.method === "POST") { + const body = yield* readJsonBody(options.request) + const request = yield* decodeRequest(RecordingTargetRequest, body, "recording cancel") + const target = recordingTargetFromValues({ registry: options.registry, tabId: request.tabId, sessionId: request.sessionId }) + const result = yield* tryRecordingPromise("cancel recording", () => options.recordingRelay.cancelRecording(target)) + sendJson(options.response, result, result.success ? 200 : 500) + return + } + options.response.writeHead(404) + options.response.end("Not found") + }) +} + +function handleFlightRecorderRequest(options: { + readonly request: http.IncomingMessage + readonly response: http.ServerResponse + readonly pathname: string + readonly requestUrl: URL + readonly registry: TargetRegistry + readonly flightRecorder: FlightRecorderRelay +}): Effect.Effect { + return Effect.gen(function* () { + if (options.pathname === "/flight-recorder/start" && options.request.method === "POST") { + const request = yield* decodeRequest(FlightRecorderStartRequest, yield* readJsonBody(options.request), "flight recorder start") + const target = resolveAttachedRecordingTarget({ registry: options.registry, tabId: request.tabId, sessionId: request.sessionId }) + const result = yield* tryRecordingPromise("start flight recorder", () => options.flightRecorder.start({ + tabId: target.tabId, + ...(target.sessionId ? { sessionId: target.sessionId } : {}), + ...(request.retentionMs === undefined ? {} : { retentionMs: request.retentionMs }), + ...(request.frameRate === undefined ? {} : { frameRate: request.frameRate }), + })) + sendJson(options.response, result) + return + } + if (options.pathname === "/flight-recorder/status" && options.request.method === "GET") { + sendJson(options.response, options.flightRecorder.status(recordingTargetFromQuery({ registry: options.registry, searchParams: options.requestUrl.searchParams }))) + return + } + if (options.pathname === "/flight-recorder/save-last" && options.request.method === "POST") { + const request = yield* decodeRequest(FlightRecorderSaveRequest, yield* readJsonBody(options.request), "flight recorder save-last") + const target = recordingTargetFromValues({ registry: options.registry, tabId: request.tabId, sessionId: request.sessionId }) + const result = yield* tryRecordingPromise("save flight recorder", () => options.flightRecorder.saveLast({ + ...target, + outputPath: request.outputPath, + ...(request.durationMs === undefined ? {} : { durationMs: request.durationMs }), + })) + sendJson(options.response, result) + return + } + if (options.pathname === "/flight-recorder/cancel" && options.request.method === "POST") { + const request = yield* decodeRequest(RecordingTargetRequest, yield* readJsonBody(options.request), "flight recorder cancel") + const target = recordingTargetFromValues({ registry: options.registry, tabId: request.tabId, sessionId: request.sessionId }) + sendJson(options.response, yield* Effect.promise(() => options.flightRecorder.cancel(target))) + return + } + options.response.writeHead(404) + options.response.end("Not found") + }) +} + +function tryRecordingPromise(label: string, tryFn: () => Promise): Effect.Effect { + return Effect.tryPromise({ + try: tryFn, + catch: (cause) => new Error(formatCauseMessage({ label, cause }), { cause }), + }) +} + +function formatCauseMessage(options: { readonly label: string; readonly cause: unknown }): string { + if (options.cause instanceof Error && options.cause.message) { + return `${options.label}: ${options.cause.message}` + } + if (Predicate.isString(options.cause) && options.cause) { + return `${options.label}: ${options.cause}` + } + return options.label +} + +function handleCliRequest(options: { + readonly request: http.IncomingMessage + readonly response: http.ServerResponse + readonly pathname: string + readonly sessions: OpenCodeBrowserSessions + readonly registry: TargetRegistry +}): Effect.Effect { + return Effect.gen(function* () { + if (options.pathname === "/cli/sessions" && options.request.method === "GET") { + sendJson(options.response, { sessions: options.sessions.listSummaries() }) + return + } + if (options.pathname === "/cli/session/new" && options.request.method === "POST") { + const body = yield* readJsonBody(options.request) + const request = yield* decodeRequest(SessionNewRequest, body, "session new") + const session = yield* options.sessions.create(optionalSessionId(request.id), { readOnly: request.readOnly === true }) + sendJson(options.response, { session: options.sessions.summary(session.id) }) + return + } + if (options.pathname === "/cli/session/delete" && options.request.method === "POST") { + const body = yield* readJsonBody(options.request) + const request = yield* decodeRequest(SessionIdRequest, body, "session delete") + const id = requiredSessionId(request.id) + const deleted = yield* options.sessions.delete(id) + sendJson(options.response, { deleted, id }) + return + } + if (options.pathname === "/cli/session/reset" && options.request.method === "POST") { + const body = yield* readJsonBody(options.request) + const request = yield* decodeRequest(SessionIdRequest, body, "session reset") + const id = requiredSessionId(request.id) + const session = yield* options.sessions.reset(id) + if (!session) { + sendJson(options.response, { error: `Session not found: ${id}`, code: "session-not-found" }, 404) + return + } + sendJson(options.response, { session }) + return + } + if (options.pathname === "/cli/session/adopt" && options.request.method === "POST") { + const body = yield* readJsonBody(options.request) + const request = yield* decodeRequest(SessionAdoptRequest, body, "session adopt") + const requestedSessionId = optionalSessionId(request.sessionId) + const allTargets = options.registry.listRootTargets() + const byTab = request.tabId === undefined ? undefined : allTargets.find((target) => target.tabId === request.tabId) + if (request.tabId !== undefined && !byTab) + throw new Error(`Tab ${request.tabId} is not available to agents. Ask the user to click the OpenCode Browser toolbar button on that tab.`) + const candidates = byTab ? [byTab] : request.targetSelection + ? allTargets + : (() => { + const adoptableUserTargets = allTargets.filter((target) => + target.owner === "user" && (!target.opencodeBrowserSessionId || target.opencodeBrowserSessionId === requestedSessionId) + ) + return adoptableUserTargets.length > 0 ? adoptableUserTargets : allTargets + })() + const selectedTarget = selectTarget({ + targets: candidates, + selection: request.targetSelection ?? {}, + getUrl: (target) => target.targetInfo.url, + getIndex: (target) => allTargets.indexOf(target), + }) + if (!selectedTarget) { + throw new Error("No page matched target selection") + } + const adoptedTargetId = selectedTarget.targetInfo.targetId + const { session, adoptedUrl } = yield* options.sessions.adopt({ + ...(requestedSessionId ? { sessionId: requestedSessionId } : {}), + createIfMissing: request.createIfMissing, + targetId: adoptedTargetId, + targetUrl: selectedTarget.targetInfo.url, + }) + sendJson(options.response, { session, adoptedUrl, adoptedTargetId }) + return + } + if (options.pathname === "/cli/execute" && options.request.method === "POST") { + const body = yield* readJsonBody(options.request) + const request = yield* decodeRequest(ExecuteRequest, body, "execute") + const requestedSessionId = optionalSessionId(request.sessionId) + const { result, session } = yield* options.sessions.execute({ + ...(requestedSessionId ? { sessionId: requestedSessionId } : {}), + code: request.code, + createIfMissing: request.createIfMissing, + ...(request.targetSelection ? { targetSelection: request.targetSelection } : {}), + }) + const { setupFailed: _setupFailed, ...wireResult } = result + sendJson(options.response, { ...wireResult, session }) + return + } + options.response.writeHead(404) + options.response.end("Not found") + }) +} + +function targetSummaries(registry: TargetRegistry): TargetSummary[] { + return registry.listRootTargets().map((target) => { + return { + id: target.targetInfo.targetId, + type: target.targetInfo.type, + title: target.targetInfo.title, + url: target.targetInfo.url, + tabId: target.tabId, + sessionId: target.sessionId, + ...(target.opencodeBrowserSessionId ? { opencodeBrowserSessionId: target.opencodeBrowserSessionId } : {}), + owner: target.owner, + ...(target.crashed ? { crashed: true } : {}), + ...(target.protectedUi ? { protectedUi: true } : {}), + } + }) +} + +function decodeRequest(schema: Schema.ConstraintDecoder, body: unknown, label: string): Effect.Effect { + return Schema.decodeUnknownEffect(schema)(body).pipe( + Effect.mapError((cause) => new HttpRouteError({ + message: `Invalid ${label} request: ${cause.message}`, + status: 400, + code: "invalid-request", + })), + ) +} + +function resolveAttachedRecordingTarget(options: { + readonly registry: TargetRegistry + readonly tabId: unknown + readonly sessionId: unknown +}): { readonly tabId: number; readonly sessionId?: string; readonly owner: "relay" | "user" } { + const tabId = optionalInteger(options.tabId, "tabId") + if (tabId !== undefined) { + const target = options.registry.getRootTargetByTabId(tabId) + if (!target) { + throw new HttpRouteError({ message: `No attached tab found for tabId ${tabId}`, status: 404, code: "target-not-found" }) + } + return { tabId, sessionId: target.sessionId, owner: target.owner } + } + const sessionId = Predicate.isString(options.sessionId) && options.sessionId ? options.sessionId : undefined + if (sessionId) { + const target = options.registry.getRootTargetBySessionId(sessionId) + if (!target) { + throw new HttpRouteError({ message: `No attached tab found for sessionId ${sessionId}`, status: 404, code: "target-not-found" }) + } + return { tabId: target.tabId, sessionId: target.sessionId, owner: target.owner } + } + const targets = options.registry.listRootTargets() + if (targets.length === 0) { + throw new HttpRouteError({ message: "No attached tab available for recording", status: 404, code: "target-not-found" }) + } + if (targets.length > 1) { + throw new HttpRouteError({ message: "Multiple attached tabs available; provide sessionId or tabId", status: 409, code: "target-ambiguous" }) + } + const target = targets[0] + if (!target) { + throw new HttpRouteError({ message: "No attached tab available for recording", status: 404, code: "target-not-found" }) + } + return { tabId: target.tabId, sessionId: target.sessionId, owner: target.owner } +} + +function recordingTargetFromValues(options: { readonly registry: TargetRegistry; readonly tabId: unknown; readonly sessionId: unknown }): RecordingTargetOptions { + const tabId = optionalInteger(options.tabId, "tabId") + const sessionId = Predicate.isString(options.sessionId) && options.sessionId ? options.sessionId : undefined + const target = sessionId ? options.registry.getRootTargetBySessionId(sessionId) : undefined + return { + ...(tabId === undefined ? {} : { tabId }), + ...(target?.sessionId ? { sessionId: target.sessionId } : sessionId ? { sessionId } : {}), + } +} + +function recordingTargetFromQuery(options: { readonly registry: TargetRegistry; readonly searchParams: URLSearchParams }): RecordingTargetOptions { + const tabIdText = options.searchParams.get("tabId") + return recordingTargetFromValues({ + registry: options.registry, + tabId: tabIdText ? Number(tabIdText) : undefined, + sessionId: options.searchParams.get("sessionId") ?? undefined, + }) +} + +function optionalInteger(value: unknown, field: string): number | undefined { + if (value === undefined) { + return undefined + } + if (!Predicate.isNumber(value) || !Number.isInteger(value)) { + throw new HttpRouteError({ message: `${field} must be an integer`, status: 400, code: "invalid-request" }) + } + return value +} + +function relayHttpError(error: unknown): HttpRouteError { + const routeError = (message: string, status: number, code: RelayErrorCode) => + new HttpRouteError({ message, status, code }) + if (error instanceof RelayShutdownError) { + return routeError(error.message, 409, error.reason === "busy" ? "relay-busy" : "invalid-request") + } + if (error instanceof HttpRouteError) { + return error + } + if (error instanceof SessionError) { + const [status, code] = Match.value(error.reason).pipe( + Match.when("already-exists", () => [409, "session-already-exists"] as const), + Match.when("inactive", () => [409, "session-inactive"] as const), + Match.when("invalid-request", () => [400, "invalid-request"] as const), + Match.when("not-found", () => [404, "session-not-found"] as const), + Match.when("target-owned", () => [409, "target-owned"] as const), + Match.when("timeout", () => [409, "session-timeout"] as const), + Match.when("setup-failed", () => [500, "setup-failed"] as const), + Match.exhaustive, + ) + return routeError(error.message, status, code) + } + if (error instanceof NetworkCaptureError) { + const [status, code] = Match.value(error.reason).pipe( + Match.when("invalid-options", () => [400, "invalid-request"] as const), + Match.when("already-active", () => [409, "capture-conflict"] as const), + Match.when("inactive", () => [409, "capture-conflict"] as const), + Match.orElse(() => [500, "internal"] as const), + ) + return routeError(error.message, status, code) + } + if (error instanceof AuthProfile.AuthProfileError) { + const [status, code] = Match.value(error.reason).pipe( + Match.when("invalid-name", () => [400, "invalid-request"] as const), + Match.when("not-found", () => [404, "auth-profile-not-found"] as const), + Match.orElse(() => [500, "internal"] as const), + ) + return routeError(error.message, status, code) + } + if (error instanceof AuthenticatedOriginError) { + return routeError( + error.message, + error.reason === "invalid-request" ? 400 : 500, + error.reason === "invalid-request" ? "invalid-request" : "setup-failed", + ) + } + if (error instanceof TargetSelectionError) { + const [status, code] = Match.value(error.reason).pipe( + Match.when("invalid", () => [400, "invalid-request"] as const), + Match.when("not-found", () => [404, "target-not-found"] as const), + Match.when("ambiguous", () => [409, "target-ambiguous"] as const), + Match.exhaustive, + ) + return routeError(error.message, status, code) + } + if (error instanceof TargetOwnershipError) { + const [status, code] = Match.value(error.reason).pipe( + Match.when("not-found", () => [404, "target-not-found"] as const), + Match.when("owned", () => [409, "target-owned"] as const), + Match.when("generation-changed", () => [409, "target-changed"] as const), + Match.exhaustive, + ) + return routeError(error.message, status, code) + } + return routeError(error instanceof Error ? error.message : String(error), 500, "internal") +} diff --git a/packages/browser-extension/cli/src/human-input.ts b/packages/browser-extension/cli/src/human-input.ts new file mode 100644 index 00000000000..05cb2aaaa2e --- /dev/null +++ b/packages/browser-extension/cli/src/human-input.ts @@ -0,0 +1,251 @@ +// Human-like pointer and keyboard timing for the input agents send through the relay. +// +// Playwright moves the mouse by teleporting: one mouseMoved event straight to the exact center of the target, +// then a press and release a few milliseconds apart. Behavioral bot detection (reCAPTCHA v3, Cloudflare, DataDome, +// HUMAN) scores exactly that. This module sits in the relay's CDP path and, for each Input.dispatchMouseEvent +// that moves the pointer, first sends a curved, eased trajectory from the pointer's last position (a cubic Bezier +// with a perpendicular bow, minimum-jerk velocity, ~60-120 Hz samples, sub-pixel tremor, and an occasional +// overshoot and correction), with a duration that grows with distance (Fitts' law). It also holds a press for a +// human 60-140 ms, settles briefly before pressing, and spaces consecutive key presses 30-110 ms apart. Scrolling +// glides: each wheel event becomes an eased ~60 Hz burst, and scrolling an element into view happens in wheel +// flicks instead of a one-frame jump. +// +// Off with OPENCODE_BROWSER_HUMAN_INPUT=0 (for example for fast test runs). +import type { JsonObject } from "./protocol.ts" +import { relayLog } from "./relay-log.ts" + +type Point = { x: number; y: number } +type Send = (method: string, params: JsonObject) => Promise + +const enabled = !/^(0|false|off|no)$/i.test(process.env.OPENCODE_BROWSER_HUMAN_INPUT ?? "") + +type TabState = { pointer?: Point; aim?: Point & { dx: number; dy: number }; arrivedAt: number; pressedAt?: number; lastKeyAt: number; queue: Promise } +const tabs = new Map() + +function state(tabId: number): TabState { + let value = tabs.get(tabId) + if (!value) { + value = { arrivedAt: 0, lastKeyAt: 0, queue: Promise.resolve() } + tabs.set(tabId, value) + } + return value +} + +export function forgetTab(tabId: number) { + tabs.delete(tabId) +} + +const sleep = (ms: number) => (ms > 0 ? new Promise((resolve) => setTimeout(resolve, ms)) : Promise.resolve()) +const random = (min: number, max: number) => min + Math.random() * (max - min) +/** Normal-ish noise (sum of uniforms). */ +const noise = (scale: number) => (Math.random() + Math.random() + Math.random() - 1.5) * scale + +/** Minimum-jerk position profile: slow start, fast middle, slow arrival. */ +const minimumJerk = (t: number) => t * t * t * (10 - 15 * t + 6 * t * t) + +function bezier(p0: Point, p1: Point, p2: Point, p3: Point, t: number): Point { + const u = 1 - t + return { + x: u * u * u * p0.x + 3 * u * u * t * p1.x + 3 * u * t * t * p2.x + t * t * t * p3.x, + y: u * u * u * p0.y + 3 * u * u * t * p1.y + 3 * u * t * t * p2.y + t * t * t * p3.y, + } +} + +/** Points (with delays) for one human-looking movement from `from` to `to`. */ +export function trajectory(from: Point, to: Point): { point: Point; delay: number }[] { + const dx = to.x - from.x + const dy = to.y - from.y + const distance = Math.hypot(dx, dy) + if (distance < 2) return [] + // Fitts' law with a ~40px target, plus personal variation. + const duration = Math.min(1100, (90 + 110 * Math.log2(distance / 40 + 1)) * random(0.85, 1.25)) + // Bow the path to one side, more for longer moves, never past ~18% of the distance. + const normal = { x: -dy / distance, y: dx / distance } + const bow = (Math.random() < 0.5 ? -1 : 1) * random(0.04, 0.18) * distance + const c1 = { x: from.x + dx * random(0.2, 0.35) + normal.x * bow, y: from.y + dy * random(0.2, 0.35) + normal.y * bow } + const c2 = { x: from.x + dx * random(0.65, 0.8) + normal.x * bow * 0.6, y: from.y + dy * random(0.65, 0.8) + normal.y * bow * 0.6 } + // Long moves sometimes overshoot slightly and come back. + const overshoot = distance > 250 && Math.random() < 0.25 + const end = overshoot ? { x: to.x + (dx / distance) * random(4, 12), y: to.y + (dy / distance) * random(4, 12) } : to + const points: { point: Point; delay: number }[] = [] + let elapsed = 0 + while (elapsed < duration) { + const step = random(8, 17) + elapsed = Math.min(duration, elapsed + step) + const s = minimumJerk(elapsed / duration) + const p = bezier(from, c1, c2, end, s) + // Tremor fades out as the hand settles on the target. + const tremor = (1 - s) * 0.9 + points.push({ point: { x: p.x + noise(tremor), y: p.y + noise(tremor) }, delay: step }) + } + if (overshoot) { + const back = Math.max(3, Math.round(random(4, 7))) + for (let i = 1; i <= back; i++) { + const s = minimumJerk(i / back) + points.push({ point: { x: end.x + (to.x - end.x) * s, y: end.y + (to.y - end.y) * s }, delay: random(10, 18) }) + } + } + // The caller's own event lands exactly on the target; drop a final sample that duplicates it. + points.pop() + return points.map(({ point, delay }) => ({ point: { x: Math.round(point.x * 10) / 10, y: Math.round(point.y * 10) / 10 }, delay })) +} + +/** + * Runs before an input or scroll command is forwarded: sends the movement or scrolling leading up to it and paces + * it. The caller then sends the command itself; only a mouse event's x/y (a few pixels off center) and a wheel's + * remaining delta are adjusted, so Playwright's own semantics (buttons, modifiers, frames) are untouched. `root` + * is false for commands to a child frame, whose coordinates aren't the page's. + */ +export function beforeInput(tabId: number, method: string, params: JsonObject, root: boolean, send: Send): Promise { + if (!enabled || !paced.has(method) || (method === "DOM.scrollIntoViewIfNeeded" && !root)) return Promise.resolve() + // Playwright doesn't always wait for a move before pressing, so one tab's input runs in order: the press + // waits for the movement before it to land. + const tab = state(tabId) + const run = tab.queue.then(() => { + if (method === "Input.dispatchKeyEvent") return paceKey(tab, params) + if (method === "DOM.scrollIntoViewIfNeeded") return scrollToward(tabId, tab, params, send) + return paceMouse(tabId, tab, params, send) + }) + tab.queue = run.catch(() => undefined) + return run +} + +const paced = new Set(["Input.dispatchKeyEvent", "Input.dispatchMouseEvent", "DOM.scrollIntoViewIfNeeded"]) + +async function paceMouse(tabId: number, tab: TabState, params: JsonObject, send: Send): Promise { + const type = params.type + if (typeof params.x !== "number" || typeof params.y !== "number") return + // The relay forwards this same object, so adjustments here are what Chrome receives. + const target = params as Record + if (type === "mouseWheel") { + // One wheel event jumps the page; a hand on a trackpad or wheel scrolls in a burst that slows to a stop. + const frames = glide(Number(params.deltaX ?? 0), Number(params.deltaY ?? 0)) + const last = frames.pop() + await sendFrames(frames, (frame) => send("Input.dispatchMouseEvent", { ...params, deltaX: frame.x, deltaY: frame.y })) + if (last) { + target.deltaX = last.x + target.deltaY = last.y + } + return + } + // Playwright aims at the exact center of an element every time; people land a few pixels off, the same way + // for the move, press and release on one target. The offset stays well inside any clickable element. + if (!tab.aim || Math.hypot(tab.aim.x - params.x, tab.aim.y - params.y) >= 1) + tab.aim = { x: params.x, y: params.y, dx: noise(2.2), dy: noise(1.6) } + const x = Math.round((params.x + tab.aim.dx) * 10) / 10 + const y = Math.round((params.y + tab.aim.dy) * 10) / 10 + target.x = x + target.y = y + if (type === "mouseMoved" || ((type === "mousePressed" || type === "mouseReleased") && tab.pointer && Math.hypot(tab.pointer.x - x, tab.pointer.y - y) >= 2)) + await travel(tabId, tab, { x, y }, params, send) + if (type === "mousePressed") { + // People settle on a target for a moment before pressing. + await sleep(random(45, 130) - (Date.now() - tab.arrivedAt)) + tab.pressedAt = Date.now() + } + if (type === "mouseReleased" && tab.pressedAt !== undefined) { + await sleep(random(60, 140) - (Date.now() - tab.pressedAt)) + delete tab.pressedAt + } + tab.pointer = { x, y } +} + +/** Sends the curved movement from the pointer's last position to `to`, ending just short of it. */ +async function travel(tabId: number, tab: TabState, to: Point, params: JsonObject, send: Send) { + // The first movement on a page starts from somewhere plausible rather than the corner. + const from = tab.pointer ?? { x: to.x + random(-260, 260), y: to.y + random(-180, 180) } + const path = trajectory(from, to) + const started = Date.now() + for (const { point, delay } of path) { + // Each sample waits for the last to land so they don't arrive in bursts; the round trip counts toward the + // gap so it doesn't slow the hand down. + const sent = Date.now() + await send("Input.dispatchMouseEvent", { + type: "mouseMoved", + x: point.x, + y: point.y, + ...(typeof params.button === "string" && params.type === "mouseMoved" ? { button: params.button } : {}), + ...(typeof params.buttons === "number" ? { buttons: params.buttons } : {}), + ...(typeof params.modifiers === "number" ? { modifiers: params.modifiers } : {}), + }).catch(() => undefined) + await sleep(delay - (Date.now() - sent)) + } + tab.arrivedAt = Date.now() + if (path.length) + relayLog("input.move", { tabId, type: params.type, from: `${Math.round(from.x)},${Math.round(from.y)}`, to: `${Math.round(to.x)},${Math.round(to.y)}`, points: path.length, ms: tab.arrivedAt - started }) +} + +/** + * Playwright scrolls an element into view before acting on it, which jumps the page in one frame. When the + * element is off screen, scroll toward it with the wheel first, in flicks the way a person would; the command + * itself then only fine-tunes (or does everything, when the wheel can't move whatever holds the element). + */ +async function scrollToward(tabId: number, tab: TabState, params: JsonObject, send: Send) { + const node = { + ...(params.objectId === undefined ? {} : { objectId: params.objectId }), + ...(params.nodeId === undefined ? {} : { nodeId: params.nodeId }), + ...(params.backendNodeId === undefined ? {} : { backendNodeId: params.backendNodeId }), + } + const metrics = (await send("Page.getLayoutMetrics", {})) as { cssVisualViewport?: { clientWidth: number; clientHeight: number } } + const viewport = metrics.cssVisualViewport + if (!viewport) return + const started = Date.now() + const offset = async () => { + const result = (await send("DOM.getContentQuads", node)) as { quads?: number[][] } + const quad = result.quads?.[0] + if (!quad) return undefined + const ys = [quad[1]!, quad[3]!, quad[5]!, quad[7]!] + if (Math.min(...ys) >= 0 && Math.max(...ys) <= viewport.clientHeight) return 0 + return (Math.min(...ys) + Math.max(...ys)) / 2 - viewport.clientHeight * random(0.35, 0.5) + } + const first = await offset() + if (!first) return + // The wheel scrolls whatever is under the pointer, so it rests over the page first. + if (!tab.pointer) { + const rest = { x: viewport.clientWidth * random(0.35, 0.65), y: viewport.clientHeight * random(0.35, 0.65) } + await travel(tabId, tab, rest, { type: "mouseMoved" }, send) + tab.pointer = rest + } + const pointer = tab.pointer + let remaining = first + let scrolled = 0 + for (let flick = 0; flick < 12 && Math.abs(remaining) > 2; flick++) { + const amount = Math.sign(remaining) * Math.min(Math.abs(remaining), random(450, 900)) + await sendFrames(glide(0, amount), (frame) => + send("Input.dispatchMouseEvent", { type: "mouseWheel", x: pointer.x, y: pointer.y, deltaX: frame.x, deltaY: frame.y }), + ) + scrolled += amount + const next = await offset() + // Stop when the wheel didn't move the element (the page can't scroll further, or something else holds it). + if (next === undefined || Math.abs(next - remaining) < 1) break + remaining = next + if (Math.abs(remaining) > 2) await sleep(random(90, 240)) + } + relayLog("input.scroll", { tabId, distance: Math.round(first), scrolled: Math.round(scrolled), ms: Date.now() - started }) +} + +/** Per-frame wheel deltas for one scroll gesture: a quick start that eases out, at ~60 Hz. */ +function glide(dx: number, dy: number): Point[] { + const distance = Math.hypot(dx, dy) + if (distance < 40) return [{ x: dx, y: dy }] + const frames = Math.max(4, Math.round((Math.min(650, 140 + distance * 0.45) * random(0.85, 1.15)) / 16.7)) + return Array.from({ length: frames }, (_, i) => { + const ease = (t: number) => 1 - (1 - t) ** 3 + return { x: dx * (ease((i + 1) / frames) - ease(i / frames)), y: dy * (ease((i + 1) / frames) - ease(i / frames)) } + }) +} + +async function sendFrames(frames: Point[], send: (frame: Point) => Promise) { + for (const frame of frames) { + const sent = Date.now() + await send({ x: Math.round(frame.x * 100) / 100, y: Math.round(frame.y * 100) / 100 }).catch(() => undefined) + await sleep(random(15.5, 18) - (Date.now() - sent)) + } +} + +async function paceKey(tab: TabState, params: JsonObject) { + if (params.type !== "keyDown" && params.type !== "rawKeyDown") return + const gap = random(30, 110) - (Date.now() - tab.lastKeyAt) + if (gap > 0 && tab.lastKeyAt > 0 && Date.now() - tab.lastKeyAt < 1000) await sleep(gap) + tab.lastKeyAt = Date.now() +} diff --git a/packages/browser-extension/cli/src/index.ts b/packages/browser-extension/cli/src/index.ts new file mode 100644 index 00000000000..fefd18d4d9c --- /dev/null +++ b/packages/browser-extension/cli/src/index.ts @@ -0,0 +1,3 @@ +export * as AuthenticatedOrigin from "./opencode-browser-client.ts" +export * as OpenCodeBrowserClient from "./opencode-browser-client.ts" +export * as SecretProfile from "./secret-profile.ts" diff --git a/packages/browser-extension/cli/src/main.ts b/packages/browser-extension/cli/src/main.ts new file mode 100644 index 00000000000..8679ba189f9 --- /dev/null +++ b/packages/browser-extension/cli/src/main.ts @@ -0,0 +1,37 @@ +#!/usr/bin/env node +// opencode-browser: one command for OpenCode Browser. +// Setup (setup.ts): install, extension, uninstall. +// Driving the browser (cli.ts): serve, relay, execute, session, network, secrets, recording, journal, +// doctor, skill, mcp, status. The relay is the local server agents use; the extension connects to it. +// `opencode-browser-mcp` (or `opencode-browser mcp`) runs the MCP server over stdio. +import path from "node:path" + +const setupCommands = new Set(["install", "uninstall", "extension"]) +const command = process.argv[2] +const invokedAs = path.basename(process.argv[1] ?? "") + +if (invokedAs === "opencode-browser-mcp") { + const { NodeRuntime } = await import("@effect/platform-node") + const { runMcpServer } = await import("./mcp.ts") + runMcpServer.pipe(NodeRuntime.runMain) +} else if (command && setupCommands.has(command)) { + const { runSetup } = await import("./setup.ts") + await runSetup(command, process.argv.slice(3)) +} else { + if (!command || command === "--help" || command === "-h") { + process.stdout.write(`SETUP + install [--opencode ] Install OpenCode Browser: add the browse MCP server to opencode, copy + the extension, and check which browsers have it (opening its Chrome + Web Store listing when none does) + --no-open Print the store link instead of opening it + extension Open the unpacked extension folder (for "Load unpacked") + uninstall Remove everything install set up + +`) + } + if (command === "status") { + const { printSetupStatus } = await import("./setup.ts") + printSetupStatus() + } + await import("./cli.ts") +} diff --git a/packages/browser-extension/cli/src/mcp-main.ts b/packages/browser-extension/cli/src/mcp-main.ts new file mode 100644 index 00000000000..a3cbe2e8ece --- /dev/null +++ b/packages/browser-extension/cli/src/mcp-main.ts @@ -0,0 +1,5 @@ +#!/usr/bin/env node +import { NodeRuntime } from "@effect/platform-node" +import { runMcpServer } from "./mcp.ts" + +runMcpServer.pipe(NodeRuntime.runMain) diff --git a/packages/browser-extension/cli/src/mcp.ts b/packages/browser-extension/cli/src/mcp.ts new file mode 100644 index 00000000000..ba6c7eadae4 --- /dev/null +++ b/packages/browser-extension/cli/src/mcp.ts @@ -0,0 +1,727 @@ +import { NodeStdio } from "@effect/platform-node" +import { Config, Context, Effect, Layer, Option, Predicate } from "effect" +import { McpProtocol, McpSchema, McpServer } from "effect/ai" +import fs from "node:fs/promises" +import path from "node:path" +import { fileURLToPath } from "node:url" +import type { JsonObject } from "./protocol.ts" +import { getObject, getString, parseTargetSelection } from "./relay-helpers.ts" +import * as RelayClient from "./relay-client.ts" +import * as RelayLifecycle from "./relay-lifecycle.ts" +import type { TargetSelection } from "./relay-schema.ts" +import { opencodeBrowserVersion } from "./version.ts" + +const packageRoot = path.dirname(path.dirname(fileURLToPath(import.meta.url))) +type CurrentSession = { id: string; established: boolean } + +type ToolSpec = { + readonly name: string + readonly description: string + readonly inputSchema: JsonObject + readonly readOnly: boolean + readonly destructive: boolean + readonly idempotent: boolean + readonly handle: (input: unknown) => Effect.Effect +} + +type ExecuteArguments = { + readonly code: string + readonly session?: string | undefined + readonly targetSelection?: TargetSelection +} + +type AdoptArguments = { + readonly session?: string | undefined + readonly targetSelection?: TargetSelection + readonly tabId?: number +} + +const emptyInputSchema = objectSchema({}) +const sessionSchemaProperty = { + type: "string", + description: "Optional session id. Defaults to this MCP server's current session.", +} as const +const sessionOnlyInputSchema = objectSchema({ + session: sessionSchemaProperty, +}) + +function makeToolSpecs(relay: RelayClient.Interface, currentSession: CurrentSession): readonly ToolSpec[] { + const resolveSessionId = (input: unknown, field = "session") => optionalStringField(input, field) ?? currentSession.id + const establishCurrentSession = (id: string) => { + currentSession.id = id + currentSession.established = true + } + return [ + { + name: "execute", + description: "Execute trusted Playwright JavaScript against the OpenCode Browser session. The result includes console logs, warnings, a bounded execution-context diagnostic when relevant, and an aftermath summary (URL movement, navigations, error counts, handoffs).", + inputSchema: objectSchema({ + code: { type: "string", description: "JavaScript code to execute. It receives browser, context, page, state, modules, fillInput, fillInputs, snapshot(options?) for compact semantic outlines, search, explicit diffs, or automatic deltas, persistent compatible ref(id) locators, webmcp (list/call), screenshot helpers, ariaSnapshot, ghostCursor, handoff, demonstrate, network capture, and pageConsole (start/stop capturing the page's own console messages and errors, off by default because pages can detect it)." }, + session: { type: "string", description: "Optional existing OpenCode Browser session id. Explicit ids must already exist; omit this field to use the MCP server's current session, which is created when needed." }, + targetUrl: { type: "string", description: "Optional URL substring selecting an existing attached page. This does not navigate or open a URL; use page.goto() for that." }, + targetIndex: { type: "integer", minimum: 0, description: "Optional zero-based attached page index selector." }, + }, ["code"]), + readOnly: false, + destructive: true, + idempotent: false, + handle: (input) => Effect.gen(function* () { + const args = yield* Effect.try(() => parseExecuteArguments(input)) + yield* RelayLifecycle.ensureExtensionConnected({ relay, waitForReconnect: true }) + const sessionId = args.session ?? currentSession.id + const result = yield* relay.execute({ + sessionId, + code: args.code, + createIfMissing: !args.session, + ...(args.targetSelection ? { targetSelection: args.targetSelection } : {}), + }) + const recreated = !args.session && currentSession.established && result.session.created === true + establishCurrentSession(sessionId) + return { + ...result, + ...(recreated ? { notice: `Recreated session '${sessionId}' โ€” relay had no such session; page and state were reset.` } : {}), + } + }), + }, + { + name: "status", + description: "Return relay, extension, target, and session status.", + inputSchema: emptyInputSchema, + readOnly: true, + destructive: false, + idempotent: false, + handle: () => Effect.gen(function* () { + const [version, status] = yield* Effect.all([relay.version, relay.extensionStatus]) + const buildProblem = RelayLifecycle.relayBuildProblem(version) + return { endpoint: relay.endpoint, currentSession: currentSession.id, version, status, ...(buildProblem ? { buildProblem } : {}) } + }), + }, + { + name: "session_new", + description: "Create a OpenCode Browser session and make it current for this MCP server.", + inputSchema: objectSchema({ + id: { type: "string", description: "Optional lowercase session id." }, + readOnly: { type: "boolean", description: "Create a read-only session: the relay rejects input-dispatching CDP so scripts can inspect but not click or type." }, + }), + readOnly: false, + destructive: false, + idempotent: false, + handle: (input) => Effect.gen(function* () { + const requestedId = optionalStringField(input, "id") + const readOnly = optionalBooleanField(input, "readOnly") + const session = yield* relay.sessionNew(requestedId, readOnly ? { readOnly: true } : {}) + establishCurrentSession(session.id) + return { session } + }), + }, + { + name: "session_list", + description: "List OpenCode Browser sessions.", + inputSchema: emptyInputSchema, + readOnly: true, + destructive: false, + idempotent: false, + handle: () => relay.sessions.pipe(Effect.map((sessions) => ({ sessions }))), + }, + { + name: "session_current", + description: "Return this MCP server's current OpenCode Browser session id.", + inputSchema: emptyInputSchema, + readOnly: true, + destructive: false, + idempotent: true, + handle: () => Effect.succeed({ currentSession: currentSession.id }), + }, + { + name: "session_use", + description: "Set this MCP server's current OpenCode Browser session id.", + inputSchema: objectSchema({ + id: { type: "string", description: "Existing OpenCode Browser session id." }, + }, ["id"]), + readOnly: false, + destructive: false, + idempotent: true, + handle: (input) => Effect.gen(function* () { + const id = yield* Effect.try(() => requiredStringField(input, "id")) + yield* ensureSessionExists(relay, id) + establishCurrentSession(id) + return { currentSession: currentSession.id } + }), + }, + { + name: "session_reset", + description: "Reset a OpenCode Browser session's state and page.", + inputSchema: objectSchema({ + id: sessionSchemaProperty, + }), + readOnly: false, + destructive: true, + idempotent: false, + handle: (input) => Effect.gen(function* () { + const id = resolveSessionId(input, "id") + const session = yield* relay.sessionReset(id) + establishCurrentSession(id) + return { session } + }), + }, + { + name: "session_delete", + description: "Delete a OpenCode Browser session.", + inputSchema: objectSchema({ + id: sessionSchemaProperty, + }), + readOnly: false, + destructive: true, + idempotent: true, + handle: (input) => Effect.gen(function* () { + const id = resolveSessionId(input, "id") + const result = yield* relay.sessionDelete(id) + if (currentSession.id === id) { + currentSession.id = `mcp-${crypto.randomUUID().slice(0, 8)}` + currentSession.established = false + } + return { ...result, currentSession: currentSession.id } + }), + }, + { + name: "session_adopt", + description: "Make an attached tab the OpenCode Browser session's default page for subsequent bare execute calls. Omit targetUrl and targetIndex when only one user-attached tab is available.", + inputSchema: objectSchema({ + session: { type: "string", description: "Optional existing OpenCode Browser session id. Explicit ids must already exist; omit this field to use the MCP server's current session, which is created when needed." }, + targetUrl: { type: "string", description: "Adopt an existing attached page whose URL contains this text. Omit when only one user-attached tab is available. This does not navigate or open a URL." }, + targetIndex: { type: "integer", minimum: 0, description: "Adopt the attached page at this zero-based target index." }, + tabId: { type: "integer", description: "Adopt the user's tab with this Chrome tab id (the tab= value in status)." }, + }), + readOnly: false, + destructive: false, + idempotent: false, + handle: (input) => Effect.gen(function* () { + const args = yield* Effect.try(() => parseAdoptArguments(input)) + const sessionId = args.session ?? currentSession.id + const result = yield* relay.sessionAdopt({ + sessionId, + createIfMissing: !args.session, + ...(args.targetSelection ? { targetSelection: args.targetSelection } : {}), + ...(args.tabId === undefined ? {} : { tabId: args.tabId }), + }) + establishCurrentSession(sessionId) + return { ...result, confirmation: `Adopted session '${result.session.id}' default page: ${result.adoptedUrl}` } + }), + }, + { + name: "network_start", + description: "Start session-scoped network capture. OpenCode Browser records normalized Playwright exchanges; HAR is only the optional export format. Bodies are embedded by default with per-body and total memory limits.", + inputSchema: objectSchema({ + session: { type: "string", description: "Optional existing session id. Omit to use or create this MCP server's current session." }, + urlFilter: { type: "string", description: "Capture only request URLs containing this text." }, + resourceTypes: { type: "array", items: { type: "string" }, description: "Optional Playwright resource types such as fetch and xhr." }, + content: { type: "string", enum: ["embed", "omit"], description: "Request and response body mode. Defaults to embed." }, + maxBodyBytes: { type: "integer", minimum: 1, description: "Maximum bytes captured from each body. Defaults to 1000000." }, + maxTotalBodyBytes: { type: "integer", minimum: 1, description: "Maximum body bytes retained for the capture. Defaults to 25000000." }, + maxEntries: { type: "integer", minimum: 1, description: "Maximum captured requests. Defaults to 1000." }, + }), + readOnly: false, + destructive: false, + idempotent: false, + handle: (input) => Effect.gen(function* () { + const object = requireObject(input) + const explicitSession = optionalStringField(object, "session") + const sessionId = explicitSession ?? currentSession.id + if (explicitSession) { + yield* ensureSessionExists(relay, sessionId) + } else { + yield* relay.sessionEnsure(sessionId) + currentSession.established = true + } + yield* RelayLifecycle.ensureExtensionConnected({ relay, waitForReconnect: true }) + const content = optionalStringField(object, "content") + if (content !== undefined && content !== "embed" && content !== "omit") { + return yield* Effect.fail(new Error("content must be embed or omit")) + } + const urlFilter = optionalStringField(object, "urlFilter") + const resourceTypes = optionalStringArrayField(object, "resourceTypes") + const maxBodyBytes = optionalPositiveIntegerField(object, "maxBodyBytes") + const maxTotalBodyBytes = optionalPositiveIntegerField(object, "maxTotalBodyBytes") + const maxEntries = optionalPositiveIntegerField(object, "maxEntries") + const result = yield* relay.networkStart({ + sessionId, + ...(urlFilter ? { urlFilter } : {}), + ...(resourceTypes && resourceTypes.length > 0 ? { resourceTypes } : {}), + ...(content ? { content } : {}), + ...(maxBodyBytes === undefined ? {} : { maxBodyBytes }), + ...(maxTotalBodyBytes === undefined ? {} : { maxTotalBodyBytes }), + ...(maxEntries === undefined ? {} : { maxEntries }), + }) + return { session: sessionId, ...result } + }), + }, + { + name: "network_status", + description: "Return bounded metadata for a session's active network capture. Captured values are never included.", + inputSchema: sessionOnlyInputSchema, + readOnly: true, + destructive: false, + idempotent: true, + handle: (input) => { + const sessionId = resolveSessionId(input) + return relay.networkStatus({ sessionId }).pipe(Effect.map((result) => ({ session: sessionId, ...result }))) + }, + }, + { + name: "network_stop", + description: "Stop network capture. Optionally write a credential-redacted HAR and store lossless credential values in a reusable secret profile. At least one of outputPath or secrets is required.", + inputSchema: objectSchema({ + session: sessionSchemaProperty, + outputPath: { type: "string", description: "Optional artifact path, resolved against the MCP process working directory. The HAR contains stable ${BC_SECRET_N} references, not captured values." }, + secrets: { type: "string", description: "Optional reusable profile name for captured credential values." }, + }), + readOnly: false, + destructive: false, + idempotent: false, + handle: (input) => Effect.gen(function* () { + const sessionId = resolveSessionId(input) + const outputPath = optionalStringField(input, "outputPath") + const secrets = optionalStringField(input, "secrets") + if (!outputPath && !secrets) { + return yield* Effect.fail(new Error("network_stop requires outputPath, secrets, or both")) + } + return yield* relay.networkStop({ + sessionId, + ...(outputPath ? { outputPath: path.resolve(outputPath) } : {}), + ...(secrets ? { secrets } : {}), + }) + }), + }, + { + name: "network_cancel", + description: "Cancel a session's network capture and discard its in-memory exchanges.", + inputSchema: sessionOnlyInputSchema, + readOnly: false, + destructive: true, + idempotent: true, + handle: (input) => relay.networkCancel({ sessionId: resolveSessionId(input) }), + }, + { + name: "recording_start", + description: "Start recording the current session tab. CDP mode records video to WebM or MP4; tab-capture mode supports WebM and optional audio.", + inputSchema: objectSchema({ + session: sessionSchemaProperty, + outputPath: { type: "string", description: "Recording artifact path, resolved against the MCP process working directory." }, + mode: { type: "string", enum: ["auto", "tab-capture", "cdp"], description: "Recording backend. Defaults to auto." }, + audio: { type: "boolean", description: "Capture tab audio in tab-capture mode." }, + frameRate: { type: "integer", minimum: 1, maximum: 60, description: "Requested frame rate." }, + maxDurationMs: { type: "integer", minimum: 1, description: "Maximum recording duration in milliseconds." }, + }, ["outputPath"]), + readOnly: false, + destructive: false, + idempotent: false, + handle: (input) => { + const object = requireObject(input) + const mode = optionalStringField(object, "mode") + if (mode !== undefined && mode !== "auto" && mode !== "tab-capture" && mode !== "cdp") { + return Effect.fail(new Error("mode must be auto, tab-capture, or cdp")) + } + const frameRate = optionalPositiveIntegerField(object, "frameRate") + if (frameRate !== undefined && frameRate > 60) return Effect.fail(new Error("frameRate must be at most 60")) + const maxDurationMs = optionalPositiveIntegerField(object, "maxDurationMs") + const audio = optionalBooleanField(object, "audio") + return relay.recordingStart({ + sessionId: resolveSessionId(object), + outputPath: path.resolve(requiredStringField(object, "outputPath")), + ...(mode ? { mode } : {}), + ...(audio === undefined ? {} : { audio }), + ...(frameRate === undefined ? {} : { frameRate }), + ...(maxDurationMs === undefined ? {} : { maxDurationMs }), + }) + }, + }, + { + name: "recording_stop", + description: "Stop the active recording for a session and finalize its artifact.", + inputSchema: sessionOnlyInputSchema, + readOnly: false, + destructive: false, + idempotent: false, + handle: (input) => relay.recordingStop({ sessionId: resolveSessionId(input) }), + }, + { + name: "tabs_cleanup", + description: "Close tabs agents opened that nobody has used for a while (no agent command and not visited by the user). Tabs the user shared or pinned, the active tab, tabs playing audio, recording, or waiting for a handoff stay open. Call it when you finish a task to leave the user's browser tidy; OpenCode Browser also does this automatically after 10 idle minutes.", + inputSchema: objectSchema({ + idleMinutes: { type: "integer", minimum: 0, description: "Close tabs idle at least this long. 0 closes every eligible agent tab. Defaults to the user's setting (10)." }, + }), + readOnly: false, + destructive: true, + idempotent: true, + handle: (input) => { + const value = typeof input === "object" && input !== null && "idleMinutes" in input ? input.idleMinutes : undefined + return relay.tabsCleanup(typeof value === "number" && value >= 0 ? value : undefined) + }, + }, + { + name: "recording_status", + description: "Return bounded status and quality counters for a session recording.", + inputSchema: sessionOnlyInputSchema, + readOnly: true, + destructive: false, + idempotent: true, + handle: (input) => relay.recordingStatus({ sessionId: resolveSessionId(input) }), + }, + { + name: "recording_cancel", + description: "Cancel a session recording and discard its unfinished artifact.", + inputSchema: sessionOnlyInputSchema, + readOnly: false, + destructive: true, + idempotent: true, + handle: (input) => relay.recordingCancel({ sessionId: resolveSessionId(input) }), + }, + { + name: "flight_recorder_start", + description: "Start a rolling in-memory video buffer for the current session tab. Saving a clip does not stop buffering.", + inputSchema: objectSchema({ + session: sessionSchemaProperty, + retentionMs: { type: "integer", minimum: 1000, maximum: 120000, description: "Rolling retention window. Defaults to 60000." }, + frameRate: { type: "integer", minimum: 1, maximum: 60, description: "Saved clip frame rate. Defaults to 60." }, + }), + readOnly: false, + destructive: false, + idempotent: false, + handle: (input) => { + const object = requireObject(input) + const retentionMs = optionalPositiveIntegerField(object, "retentionMs") + const frameRate = optionalPositiveIntegerField(object, "frameRate") + return relay.flightRecorderStart({ + sessionId: resolveSessionId(object), + ...(retentionMs === undefined ? {} : { retentionMs }), + ...(frameRate === undefined ? {} : { frameRate }), + }) + }, + }, + { + name: "flight_recorder_status", + description: "Return bounded rolling-buffer duration, frame, byte, and drop counters.", + inputSchema: sessionOnlyInputSchema, + readOnly: true, + destructive: false, + idempotent: true, + handle: (input) => relay.flightRecorderStatus({ sessionId: resolveSessionId(input) }), + }, + { + name: "flight_recorder_save_last", + description: "Encode and save the most recent buffered browser video without stopping the flight recorder.", + inputSchema: objectSchema({ + session: sessionSchemaProperty, + outputPath: { type: "string", description: "Fresh .webm or .mp4 path, resolved against the MCP process working directory." }, + durationMs: { type: "integer", minimum: 1, description: "Recent duration to save. Defaults to 30000 and cannot exceed retention." }, + }, ["outputPath"]), + readOnly: false, + destructive: false, + idempotent: false, + handle: (input) => { + const object = requireObject(input) + const durationMs = optionalPositiveIntegerField(object, "durationMs") + return relay.flightRecorderSaveLast({ + sessionId: resolveSessionId(object), + outputPath: path.resolve(requiredStringField(object, "outputPath")), + ...(durationMs === undefined ? {} : { durationMs }), + }) + }, + }, + { + name: "flight_recorder_cancel", + description: "Stop and discard a session's rolling video buffer.", + inputSchema: sessionOnlyInputSchema, + readOnly: false, + destructive: true, + idempotent: true, + handle: (input) => relay.flightRecorderCancel({ sessionId: resolveSessionId(input) }), + }, + { + name: "secrets_status", + description: "Return secret profile references, sources, and expiration metadata without revealing credential values.", + inputSchema: objectSchema({ name: { type: "string", description: "Secret profile name." } }, ["name"]), + readOnly: true, + destructive: false, + idempotent: true, + handle: (input) => relay.authStatus({ name: requiredStringField(input, "name") }), + }, + { + name: "secrets_refresh", + description: "Reload a session page, observe fresh credentials, and update a secret profile while preserving stable BC_SECRET_N references.", + inputSchema: objectSchema({ + name: { type: "string", description: "Existing secret profile name." }, + session: sessionSchemaProperty, + urlFilter: { type: "string", description: "Observe credentials only on matching request URLs." }, + timeoutMs: { type: "integer", minimum: 1, description: "Reload timeout. Defaults to 30000." }, + }, ["name"]), + readOnly: false, + destructive: true, + idempotent: false, + handle: (input) => { + const object = requireObject(input) + const timeoutMs = optionalPositiveIntegerField(object, "timeoutMs") + const urlFilter = optionalStringField(object, "urlFilter") + return relay.authRefresh({ + sessionId: resolveSessionId(object), + name: requiredStringField(object, "name"), + ...(urlFilter ? { urlFilter } : {}), + ...(timeoutMs === undefined ? {} : { timeoutMs }), + }) + }, + }, + { + name: "secrets_run", + description: "Run a local command with a captured profile injected as BC_SECRET_N environment variables. Known values are replaced with their references in stdout and stderr.", + inputSchema: objectSchema({ + name: { type: "string", description: "Secret profile name." }, + command: { type: "string", description: "Executable path or command name." }, + args: { type: "array", items: { type: "string" }, description: "Command arguments." }, + cwd: { type: "string", description: "Optional child working directory." }, + timeoutMs: { type: "integer", minimum: 1, description: "Child timeout. Defaults to 120000." }, + }, ["name", "command"]), + readOnly: false, + destructive: true, + idempotent: false, + handle: (input) => { + const object = requireObject(input) + const args = optionalStringArrayField(object, "args") + const cwd = optionalStringField(object, "cwd") + const timeoutMs = optionalPositiveIntegerField(object, "timeoutMs") + return relay.authRun({ + name: requiredStringField(object, "name"), + command: requiredStringField(object, "command"), + ...(args ? { args } : {}), + cwd: path.resolve(cwd ?? process.cwd()), + ...(timeoutMs === undefined ? {} : { timeoutMs }), + }) + }, + }, + { + name: "skill", + description: "Return the OpenCode Browser agent skill instructions.", + inputSchema: emptyInputSchema, + readOnly: true, + destructive: false, + idempotent: true, + handle: () => Effect.tryPromise({ + try: () => fs.readFile(path.join(packageRoot, "skills", "browse", "SKILL.md"), "utf8"), + catch: (cause) => new Error("read opencode-browser skill", { cause }), + }), + }, + ] +} + +const registerTools = Effect.gen(function* () { + const server = yield* McpServer.McpServer + const relay = yield* RelayClient.Service + const configuredSession = Option.getOrUndefined(yield* Config.option(Config.String("OPENCODE_BROWSER_SESSION"))) + const currentSession: CurrentSession = { + id: configuredSession || `mcp-${crypto.randomUUID().slice(0, 8)}`, + established: Boolean(configuredSession), + } + yield* Effect.forEach(makeToolSpecs(relay, currentSession), (spec) => { + return server.addTool({ + tool: new McpSchema.Tool({ + name: spec.name, + description: spec.description, + inputSchema: spec.inputSchema, + annotations: { + readOnlyHint: spec.readOnly, + destructiveHint: spec.destructive, + idempotentHint: spec.idempotent, + openWorldHint: true, + }, + }), + annotations: Context.empty(), + handle: (payload: unknown) => { + const operation = mcpToolRequiresRelayCompatibility(spec.name) + ? RelayLifecycle.ensureRelay({ relay }).pipe( + Effect.flatMap((readiness) => readiness.buildProblem + ? Effect.fail(new Error(readiness.buildProblem)) + : spec.handle(payload)), + ) + : spec.handle(payload) + return operation.pipe( + Effect.match({ + onFailure: (error) => toolResult({ text: mcpErrorMessage(spec.name, error.message), isError: true }), + onSuccess: (value) => toolResultForValue(value), + }), + ) + }, + }) + }, { discard: true }) +}) + +export function mcpToolRequiresRelayCompatibility(name: string): boolean { + return !["status", "session_list", "session_current", "network_status", "recording_status", "flight_recorder_status", "secrets_status", "skill"].includes(name) +} + +export const mcpServerLayer = McpServer.layerStdio({ + name: "browse", + version: opencodeBrowserVersion, + protocols: [McpProtocol.v2025_06_18, McpProtocol.v2025_11_25, McpProtocol.v2025_03_26, McpProtocol.v2024_11_05], +}) + +export const mcpToolsLayer = Layer.effectDiscard(registerTools) + +export const runMcpServer: Effect.Effect = Layer.launch( + mcpToolsLayer.pipe( + Layer.provide(mcpServerLayer), + Layer.provide(NodeStdio.layer), + Layer.provide(RelayClient.layerFetch), + ), +) + +const ensureSessionExists = Effect.fnUntraced(function* (relay: RelayClient.Interface, id: string) { + const sessions = yield* relay.sessions + const exists = sessions.some((session) => { + return session.id === id + }) + if (!exists) { + return yield* Effect.fail(new Error(`Session not found: ${id}`)) + } +}) + +function parseExecuteArguments(input: unknown): ExecuteArguments { + const object = requireObject(input) + const code = requiredStringField(object, "code") + const session = optionalStringField(object, "session") + const targetSelection = parseMcpTargetSelection(object) + return { + code, + ...(session ? { session } : {}), + ...(targetSelection ? { targetSelection } : {}), + } +} + +function parseAdoptArguments(input: unknown): AdoptArguments { + const object = requireObject(input) + const session = optionalStringField(object, "session") + const targetSelection = parseMcpTargetSelection(object) + const tabId = typeof object.tabId === "number" && Number.isInteger(object.tabId) ? object.tabId : undefined + if (tabId !== undefined && targetSelection) throw new Error("Use only one of tabId, targetUrl, or targetIndex") + return { + ...(session ? { session } : {}), + ...(targetSelection ? { targetSelection } : {}), + ...(tabId === undefined ? {} : { tabId }), + } +} + +function parseMcpTargetSelection(input: JsonObject): TargetSelection | undefined { + const urlIncludes = optionalStringField(input, "targetUrl") + const selection = parseTargetSelection({ + ...(urlIncludes ? { urlIncludes } : {}), + ...(input.targetIndex === undefined ? {} : { index: input.targetIndex }), + }) + return selection?.urlIncludes || selection?.index !== undefined ? selection : undefined +} + +function requiredStringField(input: unknown, field: string): string { + const value = optionalStringField(input, field) + if (!value) { + throw new Error(`${field} is required`) + } + return value +} + +function optionalStringField(input: unknown, field: string): string | undefined { + const value = getString(requireObject(input), field) + return value ? value : undefined +} + +function optionalBooleanField(input: unknown, field: string): boolean | undefined { + const value = requireObject(input)[field] + return Predicate.isBoolean(value) ? value : undefined +} + +function optionalPositiveIntegerField(input: unknown, field: string): number | undefined { + const value = requireObject(input)[field] + if (value === undefined) return undefined + if (!Predicate.isNumber(value) || !Number.isInteger(value) || value <= 0) { + throw new Error(`${field} must be a positive integer`) + } + return value +} + +function optionalStringArrayField(input: unknown, field: string): readonly string[] | undefined { + const value = requireObject(input)[field] + if (value === undefined) return undefined + if (!Array.isArray(value) || !value.every((item): item is string => Predicate.isString(item) && item.length > 0)) { + throw new Error(`${field} must be an array of non-empty strings`) + } + return value +} + +function requireObject(input: unknown): JsonObject { + const object = getObject(input) + if (!object) { + throw new Error("Expected arguments object") + } + return object +} + +function stringifyResult(value: unknown): string { + if (Predicate.isString(value)) { + return value + } + return JSON.stringify(value, null, 2) +} + +export function toolResultForValue(value: unknown): McpSchema.CallToolResult { + const object = getObject(value) + const isError = object?.isError === true + const media = Array.isArray(object?.media) + ? object.media.flatMap((item) => { + const image = getObject(item) + const mimeType = getString(image, "mimeType") + const data = getString(image, "data") + return image?.type === "image" && mimeType !== undefined && data !== undefined + ? [{ data, mimeType }] + : [] + }) + : [] + const errorText = isError ? getString(object, "text") : undefined + if (media.length > 0) { + const { media: _media, ...structuredContent } = object ?? {} + const text = errorText ?? stringifyResult(structuredContent) + return new McpSchema.CallToolResult({ + content: [ + McpSchema.TextContent.make({ text }), + ...media.map((image) => McpSchema.ImageContent.make({ + data: new Uint8Array(Buffer.from(image.data, "base64")), + mimeType: image.mimeType, + })), + ], + structuredContent, + isError, + }) + } + const text = errorText ?? stringifyResult(value) + return toolResult({ text, ...(object ? { structuredContent: object } : {}), isError }) +} + +export function mcpErrorMessage(tool: string, message: string): string { + if (!message.startsWith("Session not found:")) { + return message + } + return tool === "execute" || tool === "session_adopt" + ? `${message} Create it with session_new first, or omit the explicit session id to use the MCP current session.` + : `${message} Create it with session_new first.` +} + +function toolResult(options: { readonly text: string; readonly structuredContent?: unknown; readonly isError: boolean }): McpSchema.CallToolResult { + return new McpSchema.CallToolResult({ + content: [McpSchema.TextContent.make({ text: options.text })], + structuredContent: options.structuredContent, + isError: options.isError, + }) +} + +function objectSchema(properties: JsonObject, required: readonly string[] = []): JsonObject { + return { + type: "object", + properties, + required: [...required], + additionalProperties: false, + } +} diff --git a/packages/browser-extension/cli/src/mjpeg-matroska.ts b/packages/browser-extension/cli/src/mjpeg-matroska.ts new file mode 100644 index 00000000000..4e7e7e1461d --- /dev/null +++ b/packages/browser-extension/cli/src/mjpeg-matroska.ts @@ -0,0 +1,118 @@ +// Minimal streaming Matroska writer for timestamped MJPEG frames. +// References: https://www.matroska.org/technical/elements.html and RFC 8794. + +const ebml = Buffer.from("1A45DFA3", "hex") +const ebmlVersion = Buffer.from("4286", "hex") +const ebmlReadVersion = Buffer.from("42F7", "hex") +const ebmlMaxIdLength = Buffer.from("42F2", "hex") +const ebmlMaxSizeLength = Buffer.from("42F3", "hex") +const docType = Buffer.from("4282", "hex") +const docTypeVersion = Buffer.from("4287", "hex") +const docTypeReadVersion = Buffer.from("4285", "hex") +const segment = Buffer.from("18538067", "hex") +const info = Buffer.from("1549A966", "hex") +const timestampScale = Buffer.from("2AD7B1", "hex") +const muxingApp = Buffer.from("4D80", "hex") +const writingApp = Buffer.from("5741", "hex") +const tracks = Buffer.from("1654AE6B", "hex") +const trackEntry = Buffer.from("AE", "hex") +const trackNumber = Buffer.from("D7", "hex") +const trackUid = Buffer.from("73C5", "hex") +const trackType = Buffer.from("83", "hex") +const flagLacing = Buffer.from("9C", "hex") +const codecId = Buffer.from("86", "hex") +const video = Buffer.from("E0", "hex") +const pixelWidth = Buffer.from("B0", "hex") +const pixelHeight = Buffer.from("BA", "hex") +const cluster = Buffer.from("1F43B675", "hex") +const timestamp = Buffer.from("E7", "hex") +const blockGroup = Buffer.from("A0", "hex") +const block = Buffer.from("A1", "hex") +const blockDuration = Buffer.from("9B", "hex") +const unknownSize = Buffer.from([0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]) + +function variableInteger(value: number): Buffer { + let length = 1 + while (value >= 2 ** (7 * length) - 1) length += 1 + const buffer = Buffer.alloc(length) + let remaining = value + for (let index = length - 1; index >= 0; index -= 1) { + buffer[index] = remaining & 0xff + remaining = Math.floor(remaining / 256) + } + buffer[0] = (buffer[0] ?? 0) | (1 << (8 - length)) + return buffer +} + +function unsignedInteger(value: number): Buffer { + if (value === 0) return Buffer.from([0]) + const bytes: number[] = [] + let remaining = value + while (remaining > 0) { + bytes.unshift(remaining & 0xff) + remaining = Math.floor(remaining / 256) + } + return Buffer.from(bytes) +} + +function element(id: Buffer, payload: Buffer): Buffer { + return Buffer.concat([id, variableInteger(payload.length), payload]) +} + +export function mjpegMatroskaHeader(width: number, height: number): Buffer { + const ebmlHeader = element(ebml, Buffer.concat([ + element(ebmlVersion, unsignedInteger(1)), + element(ebmlReadVersion, unsignedInteger(1)), + element(ebmlMaxIdLength, unsignedInteger(4)), + element(ebmlMaxSizeLength, unsignedInteger(8)), + element(docType, Buffer.from("matroska")), + element(docTypeVersion, unsignedInteger(4)), + element(docTypeReadVersion, unsignedInteger(2)), + ])) + const streamInfo = element(info, Buffer.concat([ + element(timestampScale, unsignedInteger(1_000_000)), + element(muxingApp, Buffer.from("opencode-browser")), + element(writingApp, Buffer.from("opencode-browser")), + ])) + const track = element(trackEntry, Buffer.concat([ + element(trackNumber, unsignedInteger(1)), + element(trackUid, unsignedInteger(1)), + element(trackType, unsignedInteger(1)), + element(flagLacing, unsignedInteger(0)), + element(codecId, Buffer.from("V_MJPEG")), + element(video, Buffer.concat([ + element(pixelWidth, unsignedInteger(width)), + element(pixelHeight, unsignedInteger(height)), + ])), + ])) + return Buffer.concat([ebmlHeader, segment, unknownSize, streamInfo, element(tracks, track)]) +} + +export function mjpegMatroskaFrame(timestampMs: number, durationMs: number, frameLength: number): { + readonly header: Buffer + readonly trailer: Buffer +} { + const blockHeader = Buffer.concat([ + block, + variableInteger(4 + frameLength), + variableInteger(1), + Buffer.from([0x00, 0x00]), + Buffer.from([0x00]), + ]) + const clusterTimestamp = element(timestamp, unsignedInteger(timestampMs)) + const duration = element(blockDuration, unsignedInteger(Math.max(1, durationMs))) + const groupHeader = Buffer.concat([ + blockGroup, + variableInteger(blockHeader.length + frameLength + duration.length), + blockHeader, + ]) + return { + header: Buffer.concat([ + cluster, + variableInteger(clusterTimestamp.length + groupHeader.length + frameLength + duration.length), + clusterTimestamp, + groupHeader, + ]), + trailer: duration, + } +} diff --git a/packages/browser-extension/cli/src/network-capture.ts b/packages/browser-extension/cli/src/network-capture.ts new file mode 100644 index 00000000000..e1be12b9bf0 --- /dev/null +++ b/packages/browser-extension/cli/src/network-capture.ts @@ -0,0 +1,864 @@ +import { Effect, Predicate, Schema, Semaphore } from "effect" +import path from "node:path" +import type { Page, Request, Response } from "patchright-core" +import * as AuthProfile from "./auth-profile.ts" +import { writeJsonFileAtomically } from "./fs-durability.ts" +import { SecretCollector } from "./network-redaction.ts" + +export type NetworkCaptureOptions = { + readonly urlFilter?: string + readonly resourceTypes?: readonly string[] + readonly content?: "omit" | "embed" + readonly maxBodyBytes?: number + readonly maxTotalBodyBytes?: number + readonly maxEntries?: number +} + +export type NetworkCaptureStopOptions = { + readonly outputPath?: string + readonly secrets?: string + readonly requireObservedSecrets?: boolean +} + +export type NetworkCaptureStatus = { + readonly active: boolean + readonly startedAt?: string + readonly entryCount: number + readonly responseCount: number + readonly failureCount: number + readonly capturedBodyBytes: number + readonly truncatedBodyCount: number + readonly droppedEntryCount: number + readonly urlFilter?: string + readonly resourceTypes?: readonly string[] + readonly content?: "omit" | "embed" + readonly secrets?: string +} + +type NetworkEndpointDigest = { + readonly method: string + readonly url: string + readonly status?: number + readonly count: number + readonly requestHeaders?: readonly string[] + readonly requestKeys?: readonly string[] + readonly responseKeys?: readonly string[] +} + +export type NetworkCaptureResult = NetworkCaptureStatus & { + readonly active: false + readonly stoppedAt: string + readonly outputPath?: string + readonly authProfile?: AuthProfile.AuthProfileSummary + readonly updatedSecretRefs: readonly string[] + readonly observedSecretRefs: readonly string[] + readonly endpoints?: readonly NetworkEndpointDigest[] +} + +export class NetworkCaptureError extends Schema.TaggedError()( + "NetworkCapture.Error", + { + message: Schema.String, + operation: Schema.String, + reason: Schema.Literals(["already-active", "inactive", "invalid-options", "finalize-failed", "persistence-failed"]), + cause: Schema.optionalKey(Schema.Defect()), + }, +) {} + +type Header = { readonly name: string; readonly value: string } + +type CapturedBody = { + readonly size: number + readonly mimeType: string + readonly text?: string + readonly truncated: boolean +} + +type CapturedEntry = { + readonly id: string + readonly startedDateTime: string + readonly durationMs: number + readonly request: { + readonly method: string + readonly url: string + readonly headers: readonly Header[] + readonly resourceType: string + readonly body?: CapturedBody + readonly redirectedFrom?: string + } + readonly response?: { + readonly status: number + readonly statusText: string + readonly headers: readonly Header[] + readonly body?: CapturedBody + } + readonly failure?: string +} + +type PendingEntry = { + readonly id: string + readonly startedAt: number + readonly startedDateTime: string + readonly request: Request + response?: Response + failure?: string + finalized: boolean + epoch: number +} + +type FinalizeWork = { + readonly pending: PendingEntry + readonly generation: number +} + +type ActiveCapture = { + readonly startedAt: string + readonly options: Required> & NetworkCaptureOptions + readonly pending: Map + readonly entries: CapturedEntry[] + readonly finalizeQueue: FinalizeWork[] + readonly finalizeWaiters: Set<() => void> + readonly liveCollector: SecretCollector + finalizeWorkers: number + finalizeGeneration: number + capturedBodyBytes: number + truncatedBodyCount: number + droppedEntryCount: number + stopping: boolean + cancelled: boolean + outputUnsafe: boolean +} + +const maxAllowedBodyBytes = 10_000_000 +const maxAllowedTotalBodyBytes = 100_000_000 +const maxAllowedEntries = 10_000 +const maxAllowedResourceTypes = 50 +const maxFinalizeWorkers = 4 + +export class Recorder { + private active: ActiveCapture | undefined + private page: Page | undefined + private pageEpoch = 0 + private readonly transition = Semaphore.makeUnsafe(1) + + constructor(private readonly recorderOptions: { + readonly authProfileBaseDir?: string + readonly outputSettleTimeoutMs?: number + } = {}) {} + + start(page: Page, options: NetworkCaptureOptions = {}): Effect.Effect { + const capture = this + return this.transition.withPermit(Effect.try({ + try: () => { + validateOptions(options) + if (capture.active) { + throw new NetworkCaptureError({ message: "Network capture is already active for this session", operation: "start", reason: "already-active" }) + } + capture.active = { + startedAt: new Date().toISOString(), + options: { + ...options, + content: options.content ?? "embed", + maxBodyBytes: options.maxBodyBytes ?? 1_000_000, + maxTotalBodyBytes: options.maxTotalBodyBytes ?? 25_000_000, + maxEntries: options.maxEntries ?? 1_000, + }, + pending: new Map(), + entries: [], + finalizeQueue: [], + finalizeWaiters: new Set(), + liveCollector: new SecretCollector(), + finalizeWorkers: 0, + finalizeGeneration: 0, + capturedBodyBytes: 0, + truncatedBodyCount: 0, + droppedEntryCount: 0, + stopping: false, + cancelled: false, + outputUnsafe: false, + } + capture.bindPage(page) + return capture.status() + }, + catch: (cause) => cause instanceof NetworkCaptureError + ? cause + : new NetworkCaptureError({ message: "Invalid network capture options", operation: "start", reason: "invalid-options", cause }), + })) + } + + status(): NetworkCaptureStatus { + const active = this.active + if (!active) { + return { + active: false, + entryCount: 0, + responseCount: 0, + failureCount: 0, + capturedBodyBytes: 0, + truncatedBodyCount: 0, + droppedEntryCount: 0, + } + } + return { + active: true, + startedAt: active.startedAt, + entryCount: active.entries.length + active.pending.size, + responseCount: active.entries.filter((entry) => entry.response).length, + failureCount: active.entries.filter((entry) => entry.failure).length, + capturedBodyBytes: active.capturedBodyBytes, + truncatedBodyCount: active.truncatedBodyCount, + droppedEntryCount: active.droppedEntryCount, + ...(active.options.urlFilter ? { urlFilter: active.options.urlFilter } : {}), + ...(active.options.resourceTypes ? { resourceTypes: [...active.options.resourceTypes] } : {}), + content: active.options.content, + } + } + + stop(options: NetworkCaptureStopOptions = {}): Effect.Effect { + const capture = this + return this.transition.withPermit(Effect.gen(function* () { + const active = capture.active + if (!active) { + return yield* new NetworkCaptureError({ message: "Network capture is not active for this session", operation: "stop", reason: "inactive" }) + } + const boundPage = capture.page + active.stopping = true + capture.unbindPage() + const operation = Effect.gen(function* () { + for (const pending of [...active.pending.values()]) { + if (!pending.finalized) { + pending.failure ??= "Capture stopped before request completed" + delete pending.response + } + capture.scheduleFinalize(pending) + } + const settled = yield* Effect.promise(() => settleFinalizers(active, 5_000)) + if (!settled) { + active.droppedEntryCount += active.pending.size + capture.discardFinalizers(active) + } + + const secrets = options.secrets + const profileOptions = capture.recorderOptions.authProfileBaseDir ? { baseDir: capture.recorderOptions.authProfileBaseDir } : {} + const finish = finishCapture(active, options, secrets, profileOptions) + const finished = yield* (secrets + ? AuthProfile.withLock(secrets, profileOptions, finish) + : finish + ).pipe( + Effect.mapError((cause) => cause instanceof NetworkCaptureError + ? cause + : new NetworkCaptureError({ message: cause.message, operation: "auth-profile", reason: "persistence-failed", cause })), + ) + const finalStatus = capture.status() + capture.active = undefined + return { + ...finalStatus, + ...(secrets ? { secrets } : {}), + truncatedBodyCount: finalStatus.truncatedBodyCount + finished.redactionOmissionCount, + active: false as const, + stoppedAt: new Date().toISOString(), + ...(options.outputPath ? { outputPath: path.resolve(options.outputPath) } : {}), + ...(finished.authProfile ? { authProfile: finished.authProfile } : {}), + updatedSecretRefs: finished.updatedSecretRefs, + observedSecretRefs: finished.observedSecretRefs, + ...(finished.endpoints.length > 0 ? { endpoints: finished.endpoints } : {}), + } + }).pipe( + Effect.tapError(() => Effect.sync(() => { + active.stopping = false + if (capture.active === active) capture.bindPage(boundPage) + })), + ) + return yield* operation + })).pipe(Effect.uninterruptible) + } + + cancel(): Effect.Effect<{ readonly cancelled: boolean }> { + const capture = this + return this.transition.withPermit(Effect.gen(function* () { + const active = capture.active + if (!active) return { cancelled: false } + active.stopping = true + active.cancelled = true + capture.unbindPage() + capture.discardFinalizers(active) + yield* Effect.promise(() => settleFinalizers(active, 5_000)) + if (capture.active === active) capture.active = undefined + return { cancelled: true } + })).pipe(Effect.uninterruptible) + } + + bindPage(page: Page | undefined): void { + const active = this.active + if (!active || active.stopping || this.page === page) return + if (this.page) { + for (const pending of active.pending.values()) { + if (pending.epoch !== this.pageEpoch || pending.finalized) continue + pending.failure ??= "Page changed before request completed" + delete pending.response + this.scheduleFinalize(pending) + } + } + this.unbindPage() + if (!page || page.isClosed()) return + this.page = page + this.pageEpoch += 1 + page.on("request", this.onRequest) + page.on("response", this.onResponse) + page.on("requestfinished", this.onRequestFinished) + page.on("requestfailed", this.onRequestFailed) + } + + async settleForOutput(): Promise { + const active = this.active + if (!active) return + active.outputUnsafe = !await settleFinalizers(active, this.recorderOptions.outputSettleTimeoutMs ?? 5_000) + } + + redactText(text: string): string { + const active = this.active + if (!active) return text + return active.outputUnsafe ? "[REDACTED: network capture finalization pending]" : active.liveCollector.redactText(text) + } + + redactValue(value: unknown): unknown { + const active = this.active + if (!active) return value + return active.outputUnsafe ? "[REDACTED: network capture finalization pending]" : active.liveCollector.redactValue(value) + } + + redactUrl(url: string): string { + const active = this.active + if (!active) return url + if (active.outputUnsafe) return "[REDACTED: network capture finalization pending]" + return active.liveCollector.redactText(active.liveCollector.protectUrl(url, "execute")) + } + + private readonly onRequest = (request: Request): void => { + const active = this.active + if (!active || !matches(request, active.options)) return + if (active.entries.length + active.pending.size >= active.options.maxEntries) { + active.droppedEntryCount += 1 + return + } + active.pending.set(request, { + id: `request-${active.entries.length + active.pending.size + 1}`, + startedAt: Date.now(), + startedDateTime: new Date().toISOString(), + request, + finalized: false, + epoch: this.pageEpoch, + }) + } + + private readonly onResponse = (response: Response): void => { + const pending = this.active?.pending.get(response.request()) + if (pending) pending.response = response + } + + private readonly onRequestFinished = (request: Request): void => { + const pending = this.active?.pending.get(request) + if (pending) this.scheduleFinalize(pending) + } + + private readonly onRequestFailed = (request: Request): void => { + const pending = this.active?.pending.get(request) + if (!pending) return + pending.failure = request.failure()?.errorText ?? "Request failed" + this.scheduleFinalize(pending) + } + + private scheduleFinalize(pending: PendingEntry): void { + const active = this.active + if (!active || pending.finalized) return + pending.finalized = true + active.finalizeQueue.push({ pending, generation: active.finalizeGeneration }) + this.pumpFinalizers(active) + } + + private pumpFinalizers(active: ActiveCapture): void { + if (active.cancelled) active.finalizeQueue.length = 0 + while (!active.cancelled && active.finalizeWorkers < maxFinalizeWorkers) { + const work = active.finalizeQueue.shift() + if (!work) break + active.finalizeWorkers += 1 + void this.finalize(work.pending, active, work.generation).catch(() => {}).finally(() => { + active.finalizeWorkers -= 1 + this.pumpFinalizers(active) + notifyFinalizersSettled(active) + }) + } + notifyFinalizersSettled(active) + } + + private discardFinalizers(active: ActiveCapture): void { + active.finalizeGeneration += 1 + active.finalizeQueue.length = 0 + active.pending.clear() + notifyFinalizersSettled(active) + } + + private async finalize(pending: PendingEntry, active: ActiveCapture, generation: number): Promise { + const request = pending.request + try { + const requestHeaders = await safeHeaders(() => request.headersArray()) + const requestLimit = Math.min(active.options.maxBodyBytes, active.options.maxTotalBodyBytes - active.capturedBodyBytes) + const requestSize = declaredBodySize(requestHeaders) + const requestMayHaveBody = requestSize !== undefined + ? requestSize > 0 + : contentType(requestHeaders) !== undefined && !/^(GET|HEAD)$/i.test(request.method()) + const requestBody = active.options.content === "embed" && requestMayHaveBody + ? bodyCanFit(requestHeaders, requestLimit) + ? captureBuffer(request.postDataBuffer(), contentType(requestHeaders), active) + : truncatedBody(contentType(requestHeaders), active, requestSize ?? 0) + : undefined + const response = pending.response + const responseHeaders = response ? await safeHeaders(() => response.headersArray()) : [] + const shouldCaptureResponseBody = response && active.options.content === "embed" + const hasBodyBudget = active.capturedBodyBytes < active.options.maxTotalBodyBytes + let responseBody: CapturedBody | undefined + if (shouldCaptureResponseBody) { + if (hasBodyBudget) { + const responseBuffer = bodyCanFit(responseHeaders, Math.min(active.options.maxBodyBytes, active.options.maxTotalBodyBytes - active.capturedBodyBytes)) + ? await bodyWithTimeout(response, 1_000) + : null + responseBody = responseBuffer === null + ? truncatedBody(contentType(responseHeaders), active, declaredBodySize(responseHeaders) ?? 0) + : captureBuffer(responseBuffer, contentType(responseHeaders), active) + } else { + responseBody = truncatedBody(contentType(responseHeaders), active) + } + } + const redirectedFrom = request.redirectedFrom()?.url() + this.recordEntry(active, generation, { + id: pending.id, + startedDateTime: pending.startedDateTime, + durationMs: Math.max(0, Date.now() - pending.startedAt), + request: { + method: request.method(), + url: request.url(), + headers: requestHeaders, + resourceType: request.resourceType(), + ...(requestBody ? { body: requestBody } : {}), + ...(redirectedFrom ? { redirectedFrom } : {}), + }, + ...(response ? { + response: { + status: response.status(), + statusText: response.statusText(), + headers: responseHeaders, + ...(responseBody ? { body: responseBody } : {}), + }, + } : {}), + ...(pending.failure ? { failure: pending.failure } : {}), + }) + } catch { + this.recordEntry(active, generation, { + id: pending.id, + startedDateTime: pending.startedDateTime, + durationMs: Math.max(0, Date.now() - pending.startedAt), + request: { + method: safeValue(() => request.method(), "UNKNOWN"), + url: safeValue(() => request.url(), ""), + headers: [], + resourceType: safeValue(() => request.resourceType(), "unknown"), + }, + failure: "Capture finalization failed", + }) + } finally { + active.pending.delete(request) + } + } + + private recordEntry(active: ActiveCapture, generation: number, entry: CapturedEntry): void { + if (active.cancelled || generation !== active.finalizeGeneration) return + active.entries.push(entry) + protectEntry(entry, active.liveCollector) + } + + private unbindPage(): void { + const page = this.page + this.page = undefined + if (!page) return + page.off("request", this.onRequest) + page.off("response", this.onResponse) + page.off("requestfinished", this.onRequestFinished) + page.off("requestfailed", this.onRequestFailed) + } +} + +function finishCapture( + active: ActiveCapture, + options: NetworkCaptureStopOptions, + secrets: string | undefined, + profileOptions: { readonly baseDir?: string }, +): Effect.Effect<{ + readonly authProfile?: AuthProfile.AuthProfileSummary + readonly updatedSecretRefs: readonly string[] + readonly observedSecretRefs: readonly string[] + readonly redactionOmissionCount: number + readonly endpoints: readonly NetworkEndpointDigest[] +}, NetworkCaptureError | AuthProfile.AuthProfileError> { + return Effect.gen(function* () { + const existingProfile = secrets + ? yield* AuthProfile.readOptional(secrets, profileOptions) + : undefined + const collector = new SecretCollector(existingProfile?.slots ?? []) + const structurallyProtected = active.entries.map((entry) => protectEntry(entry, collector)) + const protectedEntries = structurallyProtected.map((entry) => redactEntryKnownValues(entry, collector)) + if (options.requireObservedSecrets && collector.observedRefs().length === 0) { + return yield* new NetworkCaptureError({ + message: `Auth refresh did not observe credentials for profile ${secrets ?? "unknown"}`, + operation: "auth-profile", + reason: "persistence-failed", + }) + } + const authProfile = secrets + ? yield* AuthProfile.write({ name: secrets, slots: collector.slots(), ...profileOptions }) + : undefined + if (options.outputPath) { + yield* writeArtifact(options.outputPath, { + log: { + version: "1.2", + creator: { name: "OpenCode Browser", version: "1" }, + entries: protectedEntries.map(toHarEntry), + }, + }) + } + return { + ...(authProfile ? { authProfile } : {}), + updatedSecretRefs: collector.updatedRefs(), + observedSecretRefs: collector.observedRefs(), + redactionOmissionCount: options.outputPath ? countRedactionOmissions(active.entries, protectedEntries) : 0, + endpoints: summarizeEndpoints(protectedEntries), + } + }) +} + +function extractTopLevelJsonKeys(body: CapturedBody | undefined): readonly string[] | undefined { + if (!body?.text || !body.mimeType.toLowerCase().includes("json")) return undefined + try { + const parsed: unknown = JSON.parse(body.text) + if (Predicate.isObject(parsed) && !Array.isArray(parsed)) { + const keys = Object.keys(parsed).slice(0, 15) + return keys.length > 0 ? keys : undefined + } + } catch {} + return undefined +} + +function summarizeEndpoints(entries: readonly CapturedEntry[]): readonly NetworkEndpointDigest[] { + const byRoute = new Map() + for (const entry of entries) { + if (["image", "stylesheet", "font", "media"].includes(entry.request.resourceType)) continue + let routePath = entry.request.url + try { + const u = new URL(entry.request.url) + routePath = `${u.origin}${u.pathname}` + } catch {} + const key = `${entry.request.method} ${routePath}` + const existing = byRoute.get(key) + const notableHeaders = entry.request.headers + .filter((h) => { + const lower = h.name.toLowerCase() + if (lower === "x-client-data" || lower.startsWith("sec-ch-")) return false + return h.value.includes("${BC_SECRET_") || lower === "authorization" || lower.startsWith("x-") + }) + .slice(0, 8) + .map((h) => `${h.name}: ${h.value.slice(0, 80)}`) + const requestKeys = extractTopLevelJsonKeys(entry.request.body) + const responseKeys = extractTopLevelJsonKeys(entry.response?.body) + byRoute.set(key, { + method: entry.request.method, + url: entry.request.url.slice(0, 240), + ...(entry.response ? { status: entry.response.status } : existing?.status !== undefined ? { status: existing.status } : {}), + count: (existing?.count ?? 0) + 1, + ...(notableHeaders.length > 0 ? { requestHeaders: notableHeaders } : existing?.requestHeaders ? { requestHeaders: existing.requestHeaders } : {}), + ...(requestKeys ? { requestKeys } : existing?.requestKeys ? { requestKeys: existing.requestKeys } : {}), + ...(responseKeys ? { responseKeys } : existing?.responseKeys ? { responseKeys: existing.responseKeys } : {}), + }) + if (byRoute.size >= 30) break + } + return [...byRoute.values()] +} + +function countRedactionOmissions(original: readonly CapturedEntry[], protectedEntries: readonly CapturedEntry[]): number { + let count = 0 + for (let index = 0; index < original.length; index += 1) { + const before = original[index] + const after = protectedEntries[index] + if (before?.request.body?.text && !before.request.body.truncated && !after?.request.body?.text) count += 1 + if (before?.response?.body?.text && !before.response.body.truncated && !after?.response?.body?.text) count += 1 + } + return count +} + +function matches(request: Request, options: ActiveCapture["options"]): boolean { + if (options.urlFilter && !request.url().includes(options.urlFilter)) return false + return !options.resourceTypes || options.resourceTypes.includes(request.resourceType()) +} + +function validateOptions(options: NetworkCaptureOptions): void { + if (options.content !== undefined && options.content !== "embed" && options.content !== "omit") { + throw new NetworkCaptureError({ message: "Network content must be embed or omit", operation: "start", reason: "invalid-options" }) + } + validateLimit("maxBodyBytes", options.maxBodyBytes, maxAllowedBodyBytes) + validateLimit("maxTotalBodyBytes", options.maxTotalBodyBytes, maxAllowedTotalBodyBytes) + validateLimit("maxEntries", options.maxEntries, maxAllowedEntries) + if (options.resourceTypes && options.resourceTypes.length > maxAllowedResourceTypes) { + throw new NetworkCaptureError({ message: `resourceTypes cannot contain more than ${maxAllowedResourceTypes} values`, operation: "start", reason: "invalid-options" }) + } +} + +function validateLimit(name: string, value: number | undefined, maximum: number): void { + if (value === undefined) return + if (!Number.isInteger(value) || value <= 0 || value > maximum) { + throw new NetworkCaptureError({ message: `${name} must be an integer from 1 to ${maximum}`, operation: "start", reason: "invalid-options" }) + } +} + +function captureBuffer(buffer: Buffer | null, mimeType: string | undefined, active: ActiveCapture): CapturedBody | undefined { + if (!buffer) return undefined + const remaining = Math.max(0, active.options.maxTotalBodyBytes - active.capturedBodyBytes) + const captureBytes = Math.min(buffer.length, active.options.maxBodyBytes, remaining) + const truncated = captureBytes < buffer.length + active.capturedBodyBytes += captureBytes + const textual = isTextualMimeType(mimeType) + const omitted = truncated || !textual + if (omitted) active.truncatedBodyCount += 1 + return { + size: buffer.length, + mimeType: mimeType ?? "application/octet-stream", + ...(!truncated && textual ? { text: buffer.toString("utf8", 0, captureBytes) } : {}), + truncated: omitted, + } +} + +function bodyCanFit(headers: readonly Header[], limit: number): boolean { + if (limit <= 0) return false + const length = declaredBodySize(headers) + const encoding = header(headers, "content-encoding")?.trim().toLowerCase() + const supportedEncoding = !encoding || encoding === "identity" || encoding === "gzip" || encoding === "br" || encoding === "deflate" || encoding === "zstd" + if (!supportedEncoding) return false + if (length !== undefined) return length <= limit + return Boolean(encoding && isTextualMimeType(contentType(headers))) +} + +function declaredBodySize(headers: readonly Header[]): number | undefined { + const value = header(headers, "content-length") + if (!value) return undefined + const length = Number(value) + return Number.isSafeInteger(length) && length >= 0 ? length : undefined +} + +function truncatedBody(mimeType: string | undefined, active: ActiveCapture, size = 0): CapturedBody { + active.truncatedBodyCount += 1 + return { size, mimeType: mimeType ?? "application/octet-stream", truncated: true } +} + +function protectEntry(entry: CapturedEntry, collector: SecretCollector): CapturedEntry { + const scope = requestScope(entry.request.method, entry.request.url) + const requestHeaders = collector.protectHeaders(entry.request.headers, "request", scope) + const responseHeaders = entry.response ? collector.protectHeaders(entry.response.headers, "response", scope) : undefined + const requestBody = protectCapturedBody(entry.request.body, collector, "request", scope) + const responseBody = protectCapturedBody(entry.response?.body, collector, "response", scope) + return { + ...entry, + request: { + ...entry.request, + url: collector.protectUrl(entry.request.url, scope), + headers: requestHeaders, + ...(requestBody ? { body: requestBody } : {}), + ...(entry.request.redirectedFrom ? { redirectedFrom: collector.protectUrl(entry.request.redirectedFrom, scope) } : {}), + }, + ...(entry.response ? { + response: { + ...entry.response, + headers: responseHeaders ?? [], + ...(responseBody ? { body: responseBody } : {}), + }, + } : {}), + } +} + +function protectCapturedBody( + body: CapturedBody | undefined, + collector: SecretCollector, + location: "request" | "response", + scope: string, +): CapturedBody | undefined { + if (!body) return undefined + if (!body.text) { + return { size: body.size, mimeType: body.mimeType, truncated: true } + } + const text = collector.protectBody(body.text, body.mimeType, location, scope) + return text === undefined + ? { size: body.size, mimeType: body.mimeType, truncated: true } + : { ...body, text } +} + +function redactEntryKnownValues(entry: CapturedEntry, collector: SecretCollector): CapturedEntry { + return { + ...entry, + request: { + ...entry.request, + ...(entry.request.body?.text ? { body: redactStructuredBody(entry.request.body, collector) } : {}), + }, + ...(entry.response ? { + response: { + ...entry.response, + ...(entry.response.body?.text ? { body: redactStructuredBody(entry.response.body, collector) } : {}), + }, + } : {}), + } +} + +function redactStructuredBody(body: CapturedBody, collector: SecretCollector): CapturedBody { + if (!body.text || !body.mimeType.toLowerCase().includes("json")) return body + try { + return { ...body, text: JSON.stringify(redactKnownScalars(JSON.parse(body.text), collector)) } + } catch { + return { size: body.size, mimeType: body.mimeType, truncated: true } + } +} + +function redactKnownScalars(value: unknown, collector: SecretCollector): unknown { + if (Array.isArray(value)) return value.map((item) => redactKnownScalars(item, collector)) + if (Predicate.isObject(value)) { + return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, redactKnownScalars(item, collector)])) + } + return collector.redactExactValue(value, 8) +} + +function toHarEntry(entry: CapturedEntry): Record { + return { + startedDateTime: entry.startedDateTime, + time: entry.durationMs, + request: { + method: entry.request.method, + url: entry.request.url, + httpVersion: "", + cookies: [], + headers: entry.request.headers, + queryString: queryString(entry.request.url), + headersSize: -1, + bodySize: entry.request.body?.size ?? 0, + ...(entry.request.body?.text ? { + postData: { mimeType: entry.request.body.mimeType, text: entry.request.body.text }, + } : {}), + }, + response: entry.response ? { + status: entry.response.status, + statusText: entry.response.statusText, + httpVersion: "", + cookies: [], + headers: entry.response.headers, + content: { + size: entry.response.body?.size ?? 0, + mimeType: entry.response.body?.mimeType ?? contentType(entry.response.headers) ?? "application/octet-stream", + ...(entry.response.body?.text ? { text: entry.response.body.text } : {}), + }, + redirectURL: header(entry.response.headers, "location") ?? "", + headersSize: -1, + bodySize: entry.response.body?.size ?? 0, + } : { status: 0, statusText: entry.failure ?? "No response", httpVersion: "", cookies: [], headers: [], content: { size: 0, mimeType: "application/octet-stream" }, redirectURL: "", headersSize: -1, bodySize: 0 }, + cache: {}, + timings: { send: 0, wait: entry.durationMs, receive: 0 }, + _opencodeBrowser: { + id: entry.id, + resourceType: entry.request.resourceType, + ...(entry.request.redirectedFrom ? { redirectedFrom: entry.request.redirectedFrom } : {}), + ...(entry.failure ? { failure: entry.failure } : {}), + requestBodyTruncated: entry.request.body?.truncated ?? false, + responseBodyTruncated: entry.response?.body?.truncated ?? false, + }, + } +} + +function writeArtifact(outputPath: string, value: unknown): Effect.Effect { + return Effect.tryPromise({ + try: () => writeJsonFileAtomically(path.resolve(outputPath), value), + catch: (cause) => new NetworkCaptureError({ message: `Could not write network capture: ${outputPath}`, operation: "write", reason: "persistence-failed", cause }), + }) +} + +async function safeHeaders(read: () => Promise): Promise { + return read().catch(() => []) +} + +async function bodyWithTimeout(response: Response, timeoutMs: number): Promise { + let timeout: NodeJS.Timeout | undefined + try { + return await Promise.race([ + response.body().catch(() => null), + new Promise((resolve) => { + timeout = setTimeout(() => resolve(null), timeoutMs) + }), + ]) + } finally { + if (timeout) clearTimeout(timeout) + } +} + +async function settleFinalizers(active: ActiveCapture, timeoutMs: number): Promise { + if (active.pending.size === 0 && active.finalizeQueue.length === 0 && active.finalizeWorkers === 0) return true + let timeout: NodeJS.Timeout | undefined + let waiter: (() => void) | undefined + try { + return await Promise.race([ + new Promise((resolve) => { + waiter = () => resolve(true) + active.finalizeWaiters.add(waiter) + }), + new Promise((resolve) => { + timeout = setTimeout(() => resolve(false), timeoutMs) + }), + ]) + } finally { + if (timeout) clearTimeout(timeout) + if (waiter) active.finalizeWaiters.delete(waiter) + } +} + +function notifyFinalizersSettled(active: ActiveCapture): void { + if (active.pending.size > 0 || active.finalizeQueue.length > 0 || active.finalizeWorkers > 0) return + for (const resolve of active.finalizeWaiters) resolve() + active.finalizeWaiters.clear() +} + +function safeValue(read: () => A, fallback: A): A { + try { + return read() + } catch { + return fallback + } +} + +function requestScope(method: string, rawUrl: string): string { + try { + const url = new URL(rawUrl) + return `${method.toUpperCase()} ${url.origin}${url.pathname}` + } catch { + return `${method.toUpperCase()} ${rawUrl.split("?", 1)[0] ?? rawUrl}` + } +} + +function contentType(headers: readonly Header[]): string | undefined { + return header(headers, "content-type")?.trim() +} + +function header(headers: readonly Header[], name: string): string | undefined { + return headers.find((candidate) => candidate.name.toLowerCase() === name)?.value +} + +function queryString(rawUrl: string): Array<{ name: string; value: string }> { + try { + return Array.from(new URL(rawUrl).searchParams, ([name, value]) => ({ name, value })) + } catch { + return [] + } +} + +function isTextualMimeType(mimeType: string | undefined): boolean { + return !mimeType || mimeType.startsWith("text/") || /json|javascript|xml|x-www-form-urlencoded|multipart\/form-data|graphql/.test(mimeType) +} diff --git a/packages/browser-extension/cli/src/network-redaction.ts b/packages/browser-extension/cli/src/network-redaction.ts new file mode 100644 index 00000000000..2cfb422363e --- /dev/null +++ b/packages/browser-extension/cli/src/network-redaction.ts @@ -0,0 +1,378 @@ +import { Predicate } from "effect" + +export type CredentialSlot = { + readonly ref: string + value: string + readonly sources: readonly string[] + expiresAt?: string +} + +type RedactionSlot = Pick +type MutableCredentialSlot = Omit & { readonly sources: string[] } + +const secretNamePattern = /auth(?:orization)?|cookie|credential|csrf|xsrf|token|secret|session|password|passwd|pwd|passcode|otp|(?:^|[-_.])code(?:$|[-_.])|(?:api|access|refresh)[-_.]?key|signature|(?:^|[-_.])sig(?:$|[-_.])/i +const secretHeaders = new Set([ + "authorization", + "proxy-authorization", + "x-api-key", + "api-key", + "x-csrf-token", + "csrf-token", + "x-xsrf-token", +]) + +export class SecretCollector { + private readonly slotsByRef = new Map() + private readonly refsByValue = new Map() + private readonly refsBySource = new Map() + // Retired values are redaction-only: never include them in persisted profile slots. + private readonly retiredRefsByValue = new Map() + private nextRef = 1 + private updated = new Set() + private observed = new Set() + + constructor(existing: readonly CredentialSlot[] = []) { + for (const slot of existing) { + const copy: MutableCredentialSlot = { + ref: slot.ref, + value: slot.value, + sources: [...slot.sources], + ...(slot.expiresAt ? { expiresAt: slot.expiresAt } : {}), + } + this.slotsByRef.set(copy.ref, copy) + this.refsByValue.set(copy.value, copy.ref) + for (const source of copy.sources) { + this.refsBySource.set(source, copy.ref) + } + const number = /^BC_SECRET_(\d+)$/.exec(copy.ref)?.[1] + if (number) this.nextRef = Math.max(this.nextRef, Number(number) + 1) + } + } + + protectHeaders(headers: readonly { readonly name: string; readonly value: string }[], location: "request" | "response", requestScope = ""): Array<{ name: string; value: string }> { + const occurrences = new Map() + return headers.map(({ name, value }) => { + const lowerName = name.toLowerCase() + const occurrence = occurrences.get(lowerName) ?? 0 + occurrences.set(lowerName, occurrence + 1) + return { + name, + value: this.protectHeader(name, value, sourceName(requestScope, `${location}.header.${lowerName}`, occurrence)), + } + }) + } + + protectUrl(rawUrl: string, requestScope = ""): string { + const fragmentStart = rawUrl.indexOf("#") + const base = fragmentStart < 0 ? rawUrl : rawUrl.slice(0, fragmentStart) + const protectQuery = (name: string, value: string, occurrence: number) => this.reference( + value, + sourceName(requestScope, `query.${name}`, occurrence), + ) + let protectedUrl: string + try { + const url = new URL(base) + url.search = protectSearchParams(url.searchParams, protectQuery).toString() + protectedUrl = restoreReferencePlaceholders(url.toString()) + } catch { + protectedUrl = protectRelativeUrl(base, protectQuery) + } + if (fragmentStart < 0) return protectedUrl + const fragment = protectFragment(rawUrl.slice(fragmentStart + 1), (name, value, occurrence) => this.reference( + value, + sourceName(requestScope, `fragment.${name}`, occurrence), + )) + return `${protectedUrl}#${fragment}` + } + + protectBody(body: string, contentType: string | undefined, location: "request" | "response", requestScope = ""): string | undefined { + const type = contentType?.toLowerCase() ?? "" + if (type.includes("json")) { + try { + return JSON.stringify(this.protectJson(JSON.parse(body), sourceName(requestScope, location))) + } catch { + return undefined + } + } + if (type.includes("application/x-www-form-urlencoded")) { + const protectedParams = protectSearchParams(new URLSearchParams(body), (name, value, occurrence) => + this.reference(value, sourceName(requestScope, `${location}.form.${name}`, occurrence))) + return restoreReferencePlaceholders(protectedParams.toString()) + } + if (type.includes("multipart/form-data")) { + return this.protectMultipart(body, contentType ?? "", location, requestScope) + } + return undefined + } + + slots(): readonly CredentialSlot[] { + return Array.from(this.slotsByRef.values()) + .sort((left, right) => left.ref.localeCompare(right.ref, undefined, { numeric: true })) + .map((slot) => ({ ...slot, sources: [...slot.sources] })) + } + + updatedRefs(): readonly string[] { + return Array.from(this.updated).sort() + } + + observedRefs(): readonly string[] { + return Array.from(this.observed).sort() + } + + redactText(text: string): string { + return redactKnownValues(text, this.redactionSlots()) + } + + redactValue(value: unknown): unknown { + return redactKnownValue(value, this.redactionSlots()) + } + + redactExactValue(value: unknown, minimumLength: number): unknown { + if (!Predicate.isString(value) && !Predicate.isNumber(value) && !Predicate.isBoolean(value)) return value + const serialized = String(value) + if (serialized.length < minimumLength) return value + const ref = this.refsByValue.get(serialized) ?? this.retiredRefsByValue.get(serialized) + return ref ? `\${${ref}}` : value + } + + private redactionSlots(): readonly RedactionSlot[] { + return [...this.slotsByRef.values(), ...Array.from(this.retiredRefsByValue, ([value, ref]) => ({ ref, value }))] + } + + private protectHeader(name: string, value: string, source: string): string { + if (!value) return value + const lower = name.toLowerCase() + if (lower === "cookie" || lower === "set-cookie") { + const cookieOccurrences = new Map() + return value.split(/;\s*/).map((part, index) => { + const separator = part.indexOf("=") + if (separator < 1) return part + const cookieName = part.slice(0, separator).trim() + const cookieValue = part.slice(separator + 1) + if (lower === "set-cookie" && index > 0 && /^(domain|path|expires|max-age|samesite)$/i.test(cookieName)) { + return part + } + if (!cookieValue) return part + const occurrence = cookieOccurrences.get(cookieName) ?? 0 + cookieOccurrences.set(cookieName, occurrence + 1) + return `${cookieName}=${this.reference(cookieValue, sourceName("", `${source}.${cookieName}`, occurrence))}` + }).join("; ") + } + if (lower === "location" || lower === "referer" || lower === "referrer") { + return this.protectUrl(value, `${source}.url`) + } + if (lower === "authorization" || lower === "proxy-authorization") { + const match = /^(\S+)\s+(.+)$/.exec(value) + if (match) return `${match[1]} ${this.reference(match[2] ?? "", source)}` + } + if (secretHeaders.has(lower) || secretNamePattern.test(lower)) { + return this.reference(value, source) + } + return value + } + + private protectJson(value: unknown, location: string, path: readonly string[] = [], inSecret = false): unknown { + if (Array.isArray(value)) { + return value.map((item, index) => this.protectJson(item, location, [...path, String(index)], inSecret)) + } + if (Predicate.isObject(value)) { + return Object.fromEntries(Object.entries(value).map(([key, item]) => [ + key, + this.protectJson(item, location, [...path, key], inSecret || secretNamePattern.test(key)), + ])) + } + if (!inSecret || value === null || value === "") return value + return this.reference(String(value), `${location}.json.${path.join(".")}`) + } + + private protectMultipart(body: string, contentType: string, location: "request" | "response", requestScope: string): string | undefined { + const boundary = /boundary=(?:"([^"]+)"|([^;\s]+))/i.exec(contentType)?.slice(1).find(Boolean) + if (!boundary) return undefined + const delimiter = `--${boundary}` + const parts = body.split(delimiter) + if (parts.length < 3) return undefined + const occurrences = new Map() + for (let index = 1; index < parts.length - 1; index += 1) { + const part = parts[index] + if (!part?.startsWith("\r\n")) return undefined + const headerEnd = part.indexOf("\r\n\r\n") + if (headerEnd < 0 || !part.endsWith("\r\n")) return undefined + const headers = part.slice(2, headerEnd) + const disposition = headers.split("\r\n").find((line) => /^content-disposition:/i.test(line)) + if (!disposition || /;\s*filename\*?=/i.test(disposition)) return undefined + const name = /;\s*name="([^"]+)"/i.exec(disposition)?.[1] + if (!name) return undefined + const valueStart = headerEnd + 4 + const valueEnd = part.length - 2 + const value = part.slice(valueStart, valueEnd) + if (!value || !secretNamePattern.test(name)) continue + const occurrence = occurrences.get(name) ?? 0 + occurrences.set(name, occurrence + 1) + const reference = this.reference(value, sourceName(requestScope, `${location}.multipart.${name}`, occurrence)) + parts[index] = `${part.slice(0, valueStart)}${reference}${part.slice(valueEnd)}` + } + return parts.join(delimiter) + } + + private reference(value: string, source: string): string { + const sourceRef = this.refsBySource.get(source) + if (sourceRef) { + const slot = this.slotsByRef.get(sourceRef) + if (slot) { + if (slot.value === value) { + this.observed.add(sourceRef) + return `\${${sourceRef}}` + } + if (slot.sources.length === 1) { + this.retiredRefsByValue.set(slot.value, slot.ref) + if (this.refsByValue.get(slot.value) === sourceRef) this.refsByValue.delete(slot.value) + slot.value = value + const expiresAt = jwtExpiration(value) + if (expiresAt) slot.expiresAt = expiresAt + else delete slot.expiresAt + this.refsByValue.set(value, sourceRef) + this.updated.add(sourceRef) + this.observed.add(sourceRef) + return `\${${sourceRef}}` + } + const sourceIndex = slot.sources.indexOf(source) + if (sourceIndex >= 0) slot.sources.splice(sourceIndex, 1) + const replacementRef = this.refsByValue.get(value) + if (replacementRef) { + this.refsBySource.set(source, replacementRef) + this.addSource(replacementRef, source) + this.updated.add(replacementRef) + this.observed.add(replacementRef) + return `\${${replacementRef}}` + } + } + } + const valueRef = this.refsByValue.get(value) + if (valueRef) { + this.observed.add(valueRef) + this.addSource(valueRef, source) + return `\${${valueRef}}` + } + const ref = `BC_SECRET_${this.nextRef++}` + const expiresAt = jwtExpiration(value) + this.slotsByRef.set(ref, { ref, value, sources: [source], ...(expiresAt ? { expiresAt } : {}) }) + this.refsByValue.set(value, ref) + this.refsBySource.set(source, ref) + this.updated.add(ref) + this.observed.add(ref) + return `\${${ref}}` + } + + private addSource(ref: string, source: string): void { + const slot = this.slotsByRef.get(ref) + if (!slot || slot.sources.includes(source)) return + slot.sources.push(source) + this.refsBySource.set(source, ref) + } +} + +function restoreReferencePlaceholders(value: string): string { + return value.replace(/(?:%24|\$)%7B(BC_SECRET_\d+)%7D/gi, (_match, ref: string) => `\${${ref}}`) +} + +/** Protect the query of a fragment-free URL that `new URL` cannot parse. */ +function protectRelativeUrl( + rawUrl: string, + protect: (name: string, value: string, occurrence: number) => string, +): string { + const queryStart = rawUrl.indexOf("?") + if (queryStart < 0) return rawUrl + const protectedQuery = protectSearchParams(new URLSearchParams(rawUrl.slice(queryStart + 1)), protect).toString() + return restoreReferencePlaceholders(`${rawUrl.slice(0, queryStart)}?${protectedQuery}`) +} + +function protectSearchParams( + params: URLSearchParams, + protect: (name: string, value: string, occurrence: number) => string, +): URLSearchParams { + const result = new URLSearchParams() + const occurrences = new Map() + for (const [name, value] of params) { + const occurrence = occurrences.get(name) ?? 0 + occurrences.set(name, occurrence + 1) + result.append(name, value && secretNamePattern.test(name) ? protect(name, value, occurrence) : value) + } + return result +} + +function protectFragment( + fragment: string, + protect: (name: string, value: string, occurrence: number) => string, +): string { + const occurrences = new Map() + return fragment.split("&").map((part) => { + const separator = part.indexOf("=") + if (separator < 1) return part + const entry = new URLSearchParams(part).entries().next().value + if (!entry) return part + const [name, value] = entry + // Recognize parameter names, not route/anchor text containing token-like words. + if (!/^[\w.-]+$/.test(name) || !secretNamePattern.test(name)) return part + const occurrence = occurrences.get(name) ?? 0 + occurrences.set(name, occurrence + 1) + return value ? `${part.slice(0, separator + 1)}${protect(name, value, occurrence)}` : part + }).join("&") +} + +function sourceName(requestScope: string, location: string, occurrence = 0): string { + const base = requestScope ? `${requestScope}.${location}` : location + return occurrence === 0 ? base : `${base}.${occurrence}` +} + +export function redactKnownValues(text: string, slots: readonly RedactionSlot[]): string { + return [...slots] + .sort((left, right) => right.value.length - left.value.length) + .reduce((output, slot) => replaceOutsideReferences(output, slot.value, `\${${slot.ref}}`), text) +} + +function redactKnownValue(value: unknown, slots: readonly RedactionSlot[]): unknown { + if (Predicate.isString(value)) return redactKnownValues(value, slots) + if (Predicate.isNumber(value) || Predicate.isBoolean(value)) { + const slot = slots.find((candidate) => candidate.value === String(value)) + return slot ? `\${${slot.ref}}` : value + } + if (Array.isArray(value)) return value.map((item) => redactKnownValue(item, slots)) + if (!Predicate.isObject(value)) return value + return Object.fromEntries(Object.entries(value).map(([key, item]) => [ + key, + secretNamePattern.test(key) ? redactSecretValue(item) : redactKnownValue(item, slots), + ])) +} + +function redactSecretValue(value: unknown): unknown { + if (Array.isArray(value)) return value.map(redactSecretValue) + if (Predicate.isObject(value)) { + return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, redactSecretValue(item)])) + } + return value === null || value === "" ? value : "[REDACTED]" +} + +function replaceOutsideReferences(text: string, value: string, replacement: string): string { + if (!value) return text + const referencePattern = /\$\{BC_SECRET_\d+\}/g + let output = "" + let offset = 0 + for (const match of text.matchAll(referencePattern)) { + const index = match.index ?? 0 + output += text.slice(offset, index).split(value).join(replacement) + output += match[0] + offset = index + match[0].length + } + return output + text.slice(offset).split(value).join(replacement) +} + +function jwtExpiration(value: string): string | undefined { + const parts = value.split(".") + if (parts.length !== 3 || !parts[1]) return undefined + try { + const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8")) as { exp?: unknown } + return Predicate.isNumber(payload.exp) ? new Date(payload.exp * 1_000).toISOString() : undefined + } catch { + return undefined + } +} diff --git a/packages/browser-extension/cli/src/opencode-browser-client.ts b/packages/browser-extension/cli/src/opencode-browser-client.ts new file mode 100644 index 00000000000..5ed75127c47 --- /dev/null +++ b/packages/browser-extension/cli/src/opencode-browser-client.ts @@ -0,0 +1,442 @@ +import { fileURLToPath } from "node:url" +import { NodeHttpClient } from "@effect/platform-node" +import { Context, Effect, Layer, Match, Redacted, Schema } from "effect" +import * as AuthenticatedOriginInternal from "./authenticated-origin.ts" +import * as RelayClient from "./relay-client.ts" +import * as RelayLifecycle from "./relay-lifecycle.ts" +import type { + AuthenticatedJsonMethod, + AuthenticatedJsonOutcome, + SessionSummary, +} from "./relay-schema.ts" + +export type Json = Schema.Schema.Type + +export class ClientError extends Schema.TaggedError()( + "OpenCodeBrowserClient.Error", + { + message: Schema.String, + reason: Schema.Literals(["connect", "session", "invalid-request"]), + code: Schema.optionalKey(Schema.String), + status: Schema.optionalKey(Schema.Number), + }, +) {} + +export class OriginMismatch extends Schema.TaggedError()( + "AuthenticatedOrigin.OriginMismatch", + { + expectedOrigin: Schema.String, + actualOrigin: Schema.String, + message: Schema.String, + }, +) {} + +export class HttpError extends Schema.TaggedError()( + "AuthenticatedOrigin.HttpError", + { + status: Schema.Number, + method: Schema.String, + message: Schema.String, + }, +) {} + +export class RequestFailed extends Schema.TaggedError()( + "AuthenticatedOrigin.RequestFailed", + { + method: Schema.String, + message: Schema.String, + }, +) {} + +export class RequestOutcomeUnknown extends Schema.TaggedError()( + "AuthenticatedOrigin.RequestOutcomeUnknown", + { + method: Schema.String, + message: Schema.String, + }, +) {} + +export class InvalidResponse extends Schema.TaggedError()( + "AuthenticatedOrigin.InvalidResponse", + { + reason: Schema.Literals(["invalid-json", "too-large"]), + status: Schema.Number, + maxResponseBytes: Schema.optionalKey(Schema.Number), + message: Schema.String, + }, +) {} + +export class ResponseDecodeFailed extends Schema.TaggedError()( + "AuthenticatedOrigin.ResponseDecodeFailed", + { + message: Schema.String, + }, +) {} + +export class SensitiveCaptureActive extends Schema.TaggedError()( + "AuthenticatedOrigin.SensitiveCaptureActive", + { + message: Schema.String, + }, +) {} + +export type Error = + | ClientError + | OriginMismatch + | HttpError + | RequestFailed + | RequestOutcomeUnknown + | InvalidResponse + | ResponseDecodeFailed + | SensitiveCaptureActive + +export interface JsonOptions { + readonly path: `/${string}` + readonly method?: AuthenticatedJsonMethod + readonly headers?: Readonly> + readonly body?: Json + readonly response: S + readonly sensitive?: boolean + readonly handoffOnAuthFailure?: boolean + readonly handoffMessage?: string + readonly timeoutMs?: number + readonly maxResponseBytes?: number +} + +export interface AuthenticatedOriginCapability { + readonly origin: string + readonly json: { + ( + options: JsonOptions & { readonly sensitive: true }, + ): Effect.Effect, Error, S["DecodingServices"]> + ( + options: JsonOptions & { readonly sensitive?: false }, + ): Effect.Effect + } +} + +export type AuthenticatedOrigin = AuthenticatedOriginCapability + +/** Reveal a sensitive response using OpenCode Browser's Effect runtime. */ +export const reveal = (value: Redacted.Redacted): A => Redacted.value(value) + +export interface AuthenticatedOriginOptions { + readonly origin: string + /** Explicitly navigate here when the session page is not already on `origin`. */ + readonly startUrl?: string + /** Default headers merged into every request on this origin. */ + readonly headers?: Readonly> + /** Present an in-page handoff prompt and retry once if the session is logged out or redirected to auth. */ + readonly handoffOnAuthFailure?: boolean + readonly handoffMessage?: string +} + +export interface OriginClientOptions extends Omit { + readonly session: string + readonly readOnly?: boolean + readonly endpoint?: string +} + +export interface OriginClient { + readonly origin: string + readonly session: string + readonly get: ( + path: `/${string}`, + options?: { readonly headers?: Readonly>; readonly timeoutMs?: number }, + ) => Promise + readonly post: ( + path: `/${string}`, + body?: Json, + options?: { readonly headers?: Readonly>; readonly timeoutMs?: number }, + ) => Promise + readonly json: AuthenticatedOriginCapability["json"] +} + +export interface Session { + readonly id: string + readonly summary: SessionSummary + readonly authenticatedOrigin: ( + options: AuthenticatedOriginOptions, + ) => Effect.Effect +} + +export interface EnsureSessionOptions { + readonly id: string + readonly readOnly?: boolean +} + +export interface Interface { + readonly ensureSession: ( + options: EnsureSessionOptions, + ) => Effect.Effect + readonly resetSession: (id: string) => Effect.Effect +} + +export interface MakeOptions { + readonly endpoint?: string +} + +export class Service extends Context.Service()( + "opencode-browser-cli/OpenCodeBrowserClient", +) {} + +export const make = Effect.fn("OpenCodeBrowserClient.make")(function* (options: MakeOptions = {}) { + const relay = yield* RelayClient.make(options).pipe( + Effect.provide(NodeHttpClient.layerNodeHttp), + Effect.mapError((error) => clientError("connect", error)), + ) + const readiness = yield* RelayLifecycle.ensureRelay({ + relay, + // The consumer may run under Bun; the relay is a Node application. + start: RelayLifecycle.startManagedRelay(fileURLToPath(import.meta.url), "node", []), + }).pipe(Effect.mapError((error) => clientError("connect", error))) + if (readiness.buildProblem) { + return yield* new ClientError({ + message: readiness.buildProblem, + reason: "connect", + }) + } + yield* RelayLifecycle.ensureExtensionConnected({ + relay, + waitForReconnect: true, + }).pipe(Effect.mapError((error) => clientError("connect", error))) + + const ensureSession = Effect.fn("OpenCodeBrowserClient.ensureSession")(function* ( + sessionOptions: EnsureSessionOptions, + ) { + const summary = yield* relay.sessionEnsure(sessionOptions.id, { + ...(sessionOptions.readOnly === undefined ? {} : { readOnly: sessionOptions.readOnly }), + }).pipe(Effect.mapError((error) => clientError("session", error))) + return makeSession(relay, summary) + }) + + const resetSession = Effect.fn("OpenCodeBrowserClient.resetSession")(function* (id: string) { + const summary = yield* relay.sessionReset(id).pipe( + Effect.mapError((error) => clientError("session", error)), + ) + return makeSession(relay, summary) + }) + + return Service.of({ ensureSession, resetSession }) +}) + +export const layer = (options: MakeOptions = {}): Layer.Layer => + Layer.effect(Service, make(options)) + +export function origin(originUrl: string, options: OriginClientOptions): OriginClient { + const normalizedOrigin = AuthenticatedOriginInternal.normalizeOrigin(originUrl) + let cachedOrigin: Promise | undefined + const resolveOrigin = (): Promise => { + cachedOrigin ??= Effect.runPromise( + Effect.gen(function* () { + const client = yield* make(options.endpoint ? { endpoint: options.endpoint } : {}) + const liveSession = yield* client.ensureSession({ + id: options.session, + ...(options.readOnly === undefined ? {} : { readOnly: options.readOnly }), + }) + return yield* liveSession.authenticatedOrigin({ + origin: normalizedOrigin, + startUrl: options.startUrl ?? "/", + ...(options.headers ? { headers: options.headers } : {}), + ...(options.handoffOnAuthFailure === undefined ? {} : { handoffOnAuthFailure: options.handoffOnAuthFailure }), + ...(options.handoffMessage ? { handoffMessage: options.handoffMessage } : {}), + }) + }), + ).catch((error) => { + cachedOrigin = undefined + throw error + }) + return cachedOrigin + } + const json: AuthenticatedOriginCapability["json"] = ((request: JsonOptions) => + Effect.promise(resolveOrigin).pipe( + Effect.flatMap((cap) => cap.json(request as JsonOptions & { readonly sensitive?: false })), + )) as AuthenticatedOriginCapability["json"] + + return { + origin: normalizedOrigin, + session: options.session, + get: async (path: `/${string}`, callOptions?: { readonly headers?: Readonly>; readonly timeoutMs?: number }) => { + const cap = await resolveOrigin() + return (await Effect.runPromise(cap.json({ + path, + method: "GET", + ...(callOptions?.headers ? { headers: callOptions.headers } : {}), + ...(callOptions?.timeoutMs === undefined ? {} : { timeoutMs: callOptions.timeoutMs }), + response: Schema.Json, + }))) as T + }, + post: async (path: `/${string}`, body?: Json, callOptions?: { readonly headers?: Readonly>; readonly timeoutMs?: number }) => { + const cap = await resolveOrigin() + return (await Effect.runPromise(cap.json({ + path, + method: "POST", + ...(body === undefined ? {} : { body }), + ...(callOptions?.headers ? { headers: callOptions.headers } : {}), + ...(callOptions?.timeoutMs === undefined ? {} : { timeoutMs: callOptions.timeoutMs }), + response: Schema.Json, + }))) as T + }, + json, + } +} + +function makeSession(relay: RelayClient.Interface, summary: SessionSummary): Session { + return { + id: summary.id, + summary, + authenticatedOrigin: (options) => Effect.try({ + try: () => makeAuthenticatedOrigin(relay, summary.id, options), + catch: (cause) => cause instanceof ClientError + ? cause + : new ClientError({ + message: cause instanceof globalThis.Error ? cause.message : "Invalid authenticated origin", + reason: "invalid-request", + }), + }), + } +} + +function makeAuthenticatedOrigin( + relay: RelayClient.Interface, + sessionId: string, + options: AuthenticatedOriginOptions, +): AuthenticatedOrigin { + const origin = AuthenticatedOriginInternal.normalizeOrigin(options.origin) + const startUrl = options.startUrl === undefined ? undefined : AuthenticatedOriginInternal.resolveStartUrl(origin, options.startUrl) + + function json( + request: JsonOptions & { readonly sensitive: true }, + ): Effect.Effect, Error, S["DecodingServices"]> + function json( + request: JsonOptions & { readonly sensitive?: false }, + ): Effect.Effect + function json( + request: JsonOptions, + ): Effect.Effect, Error, S["DecodingServices"]> { + const method = request.method ?? "GET" + if (method === "GET" && request.body !== undefined) { + return Effect.fail(new ClientError({ + message: "GET authenticated origin requests cannot include a body", + reason: "invalid-request", + })) + } + const mutation = method !== "GET" + const mergedHeaders = + options.headers || request.headers + ? { ...(options.headers ?? {}), ...(request.headers ?? {}) } + : undefined + const handoffOnAuthFailure = request.handoffOnAuthFailure ?? options.handoffOnAuthFailure + const handoffMessage = request.handoffMessage ?? options.handoffMessage + return relay.authenticatedJson({ + sessionId, + origin, + ...(startUrl ? { startUrl } : {}), + method, + path: request.path, + ...(mergedHeaders ? { headers: mergedHeaders } : {}), + ...(request.body === undefined ? {} : { body: request.body }), + ...(request.sensitive === true ? { sensitive: true } : {}), + ...(handoffOnAuthFailure === undefined ? {} : { handoffOnAuthFailure }), + ...(handoffMessage === undefined ? {} : { handoffMessage }), + ...(request.timeoutMs === undefined ? {} : { timeoutMs: request.timeoutMs }), + ...(request.maxResponseBytes === undefined ? {} : { maxResponseBytes: request.maxResponseBytes }), + }).pipe( + Effect.mapError((error): Error => mutation && ( + error instanceof RelayClient.RelayUnreachable || error instanceof RelayClient.RelayDecodeFailed + ) + ? unknownOutcome(method) + : clientError("session", error)), + Effect.flatMap((outcome) => decodeOutcome(outcome, method, mutation, request)), + ) + } + + return { origin, json } +} + +function decodeOutcome( + outcome: AuthenticatedJsonOutcome, + method: AuthenticatedJsonMethod, + mutation: boolean, + request: JsonOptions, +): Effect.Effect, Error, S["DecodingServices"]> { + return Match.valueTags(outcome, { + Success: (outcome) => { + if (request.sensitive === true) { + return Schema.decodeUnknownEffect(Schema.RedactedFromValue(request.response, { + label: "OpenCode Browser authenticated response", + disallowEncode: true, + }))(outcome.value).pipe( + Effect.mapError(() => mutation + ? unknownOutcome(method) + : new ResponseDecodeFailed({ message: "Sensitive authenticated response did not match the expected schema" })), + ) + } + return Schema.decodeUnknownEffect(request.response)(outcome.value).pipe( + Effect.mapError((cause) => mutation + ? unknownOutcome(method) + : new ResponseDecodeFailed({ message: `Authenticated response did not match the expected schema: ${cause.message}` })), + ) + }, + OriginMismatch: (outcome) => + Effect.fail(new OriginMismatch({ + expectedOrigin: outcome.expectedOrigin, + actualOrigin: outcome.actualOrigin, + message: `Session page origin ${outcome.actualOrigin} does not match ${outcome.expectedOrigin}`, + })), + HttpError: (outcome) => + Effect.fail(new HttpError({ + status: outcome.status, + method, + message: `Authenticated ${method} request was rejected with HTTP ${outcome.status}`, + })), + RequestFailed: (outcome) => + Effect.fail(mutation || outcome.outcome === "unknown" + ? unknownOutcome(method) + : new RequestFailed({ method, message: `Authenticated ${method} request failed before it was sent` })), + InvalidJson: (outcome) => + Effect.fail(mutation + ? unknownOutcome(method) + : new InvalidResponse({ + reason: "invalid-json", + status: outcome.status, + message: "Authenticated response was not valid JSON", + })), + ResponseTooLarge: (outcome) => + Effect.fail(mutation + ? unknownOutcome(method) + : new InvalidResponse({ + reason: "too-large", + status: outcome.status, + maxResponseBytes: outcome.maxResponseBytes, + message: `Authenticated response exceeded ${outcome.maxResponseBytes} bytes`, + })), + SensitiveCaptureActive: () => + Effect.fail(new SensitiveCaptureActive({ + message: "Sensitive authenticated requests are blocked while session network capture is active", + })), + }) +} + +function unknownOutcome(method: AuthenticatedJsonMethod): RequestOutcomeUnknown { + return new RequestOutcomeUnknown({ + method, + message: `Authenticated ${method} request outcome is unknown; reconcile state before retrying`, + }) +} + +function clientError(reason: ClientError["reason"], error: unknown): ClientError { + if (error instanceof ClientError) return error + if (error instanceof RelayClient.RelayRejected) { + return new ClientError({ + message: error.message, + reason, + status: error.status, + ...(error.code ? { code: error.code } : {}), + }) + } + return new ClientError({ + message: error instanceof globalThis.Error ? error.message : "OpenCode Browser request failed", + reason, + }) +} diff --git a/packages/browser-extension/cli/src/page-console.ts b/packages/browser-extension/cli/src/page-console.ts new file mode 100644 index 00000000000..12a74ff661c --- /dev/null +++ b/packages/browser-extension/cli/src/page-console.ts @@ -0,0 +1,72 @@ +// Patchright never enables CDP's Runtime domain: a page can detect that domain (console arguments get inspected +// by the debugger), and bot checks do. Without it, a page's console messages and uncaught errors never reach +// execute. `pageConsole.start()` turns Runtime on for one page, through its own CDP session, when an agent needs +// those logs; that page can then tell it is being debugged, so it stays off by default. +export * as PageConsole from "./page-console.ts" +import type { CDPSession, Page } from "patchright-core" +import type { ExecuteLogEntry } from "./relay-schema.ts" + +type Listener = (entry: ExecuteLogEntry) => void +type RemoteObject = { readonly type: string; readonly value?: unknown; readonly unserializableValue?: string; readonly description?: string } +type CallFrame = { readonly url: string; readonly lineNumber: number; readonly columnNumber: number } + +const sessions = new WeakMap() +const listeners = new WeakMap>() + +/** Starts capturing a page's console messages and uncaught errors into execute's logs. */ +export async function start(page: Page) { + if (sessions.has(page)) return { capturing: true } + const session = await page.context().newCDPSession(page) + sessions.set(page, session) + page.once("close", () => sessions.delete(page)) + // Enabling Runtime first replays what the page logged earlier; only what happens from now on is new. + let live = false + session.on("Runtime.consoleAPICalled", (event: { type: string; args: RemoteObject[]; stackTrace?: { callFrames: CallFrame[] } }) => { + if (!live) return + const frame = event.stackTrace?.callFrames[0] + emit(page, { + source: "page", + type: event.type, + text: event.args.map(describe).join(" "), + ...(frame ? { location: { url: frame.url, lineNumber: frame.lineNumber, columnNumber: frame.columnNumber } } : {}), + }) + }) + session.on("Runtime.exceptionThrown", (event: { exceptionDetails: { text: string; exception?: RemoteObject } }) => { + if (!live) return + emit(page, { source: "page", type: "pageerror", text: event.exceptionDetails.exception?.description ?? event.exceptionDetails.text }) + }) + await session.send("Runtime.enable") + live = true + return { capturing: true } +} + +/** Stops capturing, so the page no longer sees a debugger. */ +export async function stop(page: Page) { + const session = sessions.get(page) + sessions.delete(page) + if (!session) return { capturing: false } + await session.send("Runtime.disable").catch(() => undefined) + await session.detach().catch(() => undefined) + return { capturing: false } +} + +export function capturing(page: Page) { + return sessions.has(page) +} + +/** Receives a page's captured entries while registered; registering doesn't start a capture. */ +export function listen(page: Page, listener: Listener) { + const set = listeners.get(page) ?? new Set() + listeners.set(page, set) + set.add(listener) + return () => set.delete(listener) +} + +function emit(page: Page, entry: ExecuteLogEntry) { + for (const listener of listeners.get(page) ?? []) listener(entry) +} + +function describe(arg: RemoteObject) { + if (arg.value !== undefined) return typeof arg.value === "string" ? arg.value : JSON.stringify(arg.value) + return arg.unserializableValue ?? arg.description ?? arg.type +} diff --git a/packages/browser-extension/cli/src/page-read-timeout.ts b/packages/browser-extension/cli/src/page-read-timeout.ts new file mode 100644 index 00000000000..8a886cbeb10 --- /dev/null +++ b/packages/browser-extension/cli/src/page-read-timeout.ts @@ -0,0 +1,43 @@ +import type { Page } from "patchright-core" + +const installed = new WeakSet() + +export type PageReadOperation = "page.title" | "page.content" + +/** A bounded read did not settle; this does not establish renderer unresponsiveness. */ +export class PageReadTimeoutError extends Error { + constructor( + readonly timeoutMs: number, + readonly operation: PageReadOperation = "page.title", + ) { + super(`${operation}() timed out after ${timeoutMs}ms: the page execution-context read did not complete; the context may be unavailable or busy.`) + this.name = "PageReadTimeoutError" + } +} + +function wrapBoundedPageRead( + read: () => Promise, + operation: PageReadOperation, + timeoutMs: number, +): () => Promise { + return () => new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new PageReadTimeoutError(timeoutMs, operation)), timeoutMs) + Promise.resolve().then(read).then( + (value) => { clearTimeout(timer); resolve(value) }, + (error) => { clearTimeout(timer); reject(error) }, + ) + }) +} + +/** Title and content are read-only, but Playwright passes kNoTimeout (timeout: 0) for their context waits. */ +export function installPageReadTimeout( + page: Pick & Partial>, + timeoutMs = 5_000, +): void { + if (installed.has(page)) return + installed.add(page) + page.title = wrapBoundedPageRead(page.title.bind(page), "page.title", timeoutMs) + if (page.content) { + page.content = wrapBoundedPageRead(page.content.bind(page), "page.content", timeoutMs) + } +} diff --git a/packages/browser-extension/cli/src/patchright-tuning.ts b/packages/browser-extension/cli/src/patchright-tuning.ts new file mode 100644 index 00000000000..e2221f4eb1c --- /dev/null +++ b/packages/browser-extension/cli/src/patchright-tuning.ts @@ -0,0 +1,59 @@ +import { createRequire } from "node:module" +import { relayLog } from "./relay-log.ts" + +type Progress = { race(promise: Promise): Promise } +type Selectors = { + _hasClosedShadowRoots?: () => Promise + queryCount(selector: string): Promise + queryAll(selector: string): Promise +} +type Frame = { + selectors: Selectors + isNonRetriableError(error: unknown): boolean + queryCount?: (progress: Progress, selector: string) => Promise + querySelectorAll?: (progress: Progress, selector: string) => Promise +} +type ServerPage = { mainFrame(): Frame } + +/** + * Patchright finds elements its own way so it can reach into closed shadow roots: it walks the DOM over CDP, + * describing every match. Through the extension that's fine for actions, but calls that return many elements are + * slow: on a 4,000-element page `getByRole("link").count()` took ~650 ms (Playwright: ~9 ms), and before every + * count()/evaluateAll()/all() it also pulled the whole DOM tree (DOM.getDocument depth -1) to look for closed + * shadow roots, ~0.2-2 s. Playwright never reached into closed shadow roots, so count() and querySelectorAll() + * go back to Playwright's lookup (Patchright's injected script, in the isolated world, which pages can't see) and + * the shadow-root scan is off. + * + * The classes aren't exported; they're reached through the first page's main frame. If a Patchright update renames + * these internals, nothing breaks: lookups stay correct but slower, and relay.log says so. + */ +export function tunePatchright() { + const { server } = createRequire(import.meta.url)("patchright-core/lib/coreBundle") as { server?: { Page?: { prototype: ServerPage } } } + const page = server?.Page?.prototype + const mainFrame = page?.mainFrame + if (!page || typeof mainFrame !== "function") { + relayLog("patchright.tuning", { applied: false, reason: "server.Page.mainFrame not found" }) + return + } + page.mainFrame = function () { + const frame = mainFrame.call(this) + page.mainFrame = mainFrame + const frames = Object.getPrototypeOf(frame) as Frame + const selectors = Object.getPrototypeOf(frame.selectors) as Selectors + if (typeof selectors._hasClosedShadowRoots !== "function" || typeof frames.queryCount !== "function" || typeof frames.querySelectorAll !== "function") { + relayLog("patchright.tuning", { applied: false, reason: "Frame or FrameSelectors internals changed" }) + return frame + } + selectors._hasClosedShadowRoots = async () => false + frames.querySelectorAll = function (progress, selector) { + return progress.race(this.selectors.queryAll(selector)) + } + frames.queryCount = async function (progress, selector) { + return progress.race(this.selectors.queryCount(selector)).catch((error: unknown) => { + if (this.isNonRetriableError(error)) throw error + return 0 + }) + } + return frame + } +} diff --git a/packages/browser-extension/cli/src/paths.ts b/packages/browser-extension/cli/src/paths.ts new file mode 100644 index 00000000000..314dc139b17 --- /dev/null +++ b/packages/browser-extension/cli/src/paths.ts @@ -0,0 +1,16 @@ +// Where OpenCode Browser keeps its files: the installed runtime, the relay's log, session catalogs and +// journals, and captured secrets. One root, so `uninstall` can remove it and logs are easy to find. +// macOS/Linux: $XDG_DATA_HOME/opencode-browser, else ~/.local/share/opencode-browser +// Windows: %LOCALAPPDATA%\opencode-browser +// OPENCODE_BROWSER_HOME overrides it (isolated test relays). +import os from "node:os" +import path from "node:path" + +export function dataRoot(home = os.homedir()): string { + const override = process.env.OPENCODE_BROWSER_HOME + if (override) return override + if (process.platform === "win32") + return path.join(process.env.LOCALAPPDATA ?? path.join(home, "AppData", "Local"), "opencode-browser") + const xdg = home === os.homedir() ? process.env.XDG_DATA_HOME : undefined + return path.join(xdg ?? path.join(home, ".local", "share"), "opencode-browser") +} diff --git a/packages/browser-extension/cli/src/protected-frames.ts b/packages/browser-extension/cli/src/protected-frames.ts new file mode 100644 index 00000000000..adf83f2924f --- /dev/null +++ b/packages/browser-extension/cli/src/protected-frames.ts @@ -0,0 +1,109 @@ +import { Predicate } from "effect" +import type { JsonObject } from "./protocol.ts" +import { getObject, getString, isRestrictedUrl } from "./relay-helpers.ts" + +/** + * How a root-session `Page.*` event about a child frame should reach CDP + * clients once the relay knows the frame is protected. + * + * - `forward`: an ordinary frame event. + * - `suppress`: the frame is protected; clients must not learn about it. + * - `retract`: the frame just became protected after its attach was already + * forwarded; emit a synthetic `Page.frameDetached` so clients drop it. + * - `restore`: a protected frame navigated back to an ordinary document; emit + * a synthetic `Page.frameAttached` before forwarding the navigation. + */ +export type ProtectedFrameDecision = + | { readonly kind: "forward" } + | { readonly kind: "suppress" } + | { readonly kind: "retract"; readonly frameId: string } + | { readonly kind: "restore"; readonly frameId: string; readonly parentFrameId: string } + +const navigationIntentMethods = new Set(["Page.frameRequestedNavigation", "Page.frameScheduledNavigation", "Page.frameStartedNavigating"]) + +/** + * Tracks child frames whose document is a restricted URL, such as a password + * manager's `chrome-extension://` inline menu injected into the page. + * + * Chrome reports such a frame to the tab's root session like any other child + * frame, but the relay can never expose its target, so a stock Playwright + * client would keep an empty-URL phantom frame forever. While the frame exists + * `chrome.debugger` also rejects every command for the tab; that block is + * tracked separately by the relay and lifted when the last protected frame in + * the tab goes away. + */ +export class ProtectedFrameTracker { + private readonly framesByTab = new Map>() + + has(tabId: number, frameId: string): boolean { + return this.framesByTab.get(tabId)?.has(frameId) ?? false + } + + hasAny(tabId: number): boolean { + return (this.framesByTab.get(tabId)?.size ?? 0) > 0 + } + + /** Mark a frame protected. Returns true when it was not already tracked. */ + mark(tabId: number, frameId: string): boolean { + const frames = this.framesByTab.get(tabId) ?? new Set() + if (frames.has(frameId)) return false + frames.add(frameId) + this.framesByTab.set(tabId, frames) + return true + } + + /** Forget one frame. Returns true when it was the tab's last protected frame. */ + release(tabId: number, frameId: string): boolean { + const frames = this.framesByTab.get(tabId) + if (!frames?.delete(frameId)) return false + if (frames.size > 0) return false + this.framesByTab.delete(tabId) + return true + } + + forgetTab(tabId: number): void { + this.framesByTab.delete(tabId) + } + + /** + * Classify a root-session `Page.*` event. Only child frames are ever + * protected; the main frame is left to root-target handling, so a frame is + * marked only with positive evidence that it has a parent. + */ + observe(options: { + readonly tabId: number + readonly method: string + readonly params: JsonObject | undefined + readonly mainFrameId: string | undefined + /** Whether a `Page.frameAttached` with a parent was seen for this frame. */ + readonly isChildFrame: (frameId: string) => boolean + }): ProtectedFrameDecision { + const { tabId, method, params } = options + if (!method.startsWith("Page.") || !params) return { kind: "forward" } + const frame = getObject(params.frame) + const frameId = getString(params, "frameId") ?? getString(frame, "id") + if (!frameId || frameId === options.mainFrameId) return { kind: "forward" } + const frameUrl = getString(frame, "url") + const parentId = getString(frame, "parentId") + const intentUrl = navigationIntentMethods.has(method) ? getString(params, "url") : undefined + + if (this.has(tabId, frameId)) { + if (method === "Page.frameDetached") { + this.release(tabId, frameId) + return { kind: "suppress" } + } + if (method === "Page.frameNavigated" && frameUrl !== undefined && !isRestrictedUrl(frameUrl) && Predicate.isString(parentId)) { + this.release(tabId, frameId) + return { kind: "restore", frameId, parentFrameId: parentId } + } + return { kind: "suppress" } + } + + const restricted = intentUrl !== undefined + ? isRestrictedUrl(intentUrl) && options.isChildFrame(frameId) + : method === "Page.frameNavigated" && Predicate.isString(parentId) && isRestrictedUrl(frameUrl) + if (!restricted) return { kind: "forward" } + this.mark(tabId, frameId) + return { kind: "retract", frameId } + } +} diff --git a/packages/browser-extension/cli/src/protocol.ts b/packages/browser-extension/cli/src/protocol.ts new file mode 100644 index 00000000000..68c8320da7b --- /dev/null +++ b/packages/browser-extension/cli/src/protocol.ts @@ -0,0 +1,193 @@ +type JsonPrimitive = string | number | boolean | null + +export type JsonValue = JsonPrimitive | JsonValue[] | { readonly [key: string]: JsonValue } + +export type JsonObject = { readonly [key: string]: JsonValue } + +export const extensionProtocolVersion = 2 + +/** + * Chrome's minimum alarm period. A disconnected extension's MV3 worker sleeps + * until this alarm fires, so relay clients must wait at least this long. + */ +export const extensionReconnectAlarmPeriodMs = 30_000 +const legacyExtensionProtocolVersion = 1 + +export type ExtensionProtocolCompatibility = { + readonly version: number | null + readonly compatible: boolean + readonly legacy: boolean +} + +export function extensionProtocolCompatibility(value: JsonValue | undefined): ExtensionProtocolCompatibility { + const legacy = value === undefined + const valid = typeof value === "number" && Number.isSafeInteger(value) && value > 0 + const version = valid ? value : legacy ? legacyExtensionProtocolVersion : null + return { version, compatible: version === extensionProtocolVersion, legacy } +} + +export type CdpRequest = { + readonly id: number + readonly method: string + readonly params?: JsonObject + readonly sessionId?: string +} + +export type CdpResponse = { + readonly id: number + readonly result?: JsonObject + readonly error?: { + readonly message: string + } + readonly sessionId?: string +} + +export type CdpEvent = { + readonly method: string + readonly params?: JsonObject + readonly sessionId?: string +} + +export type TargetInfo = { + readonly targetId: string + readonly type: "page" | "iframe" | "worker" + readonly title: string + readonly url: string + readonly attached: boolean + readonly canAccessOpener: boolean + readonly browserContextId?: string + readonly openerId?: string + readonly parentFrameId?: string +} + +export type PageStatus = { + readonly state: "attached" | "running" | "waiting" + readonly owner: "session" | "user" + readonly sessionId?: string + readonly readOnly?: boolean + readonly message?: string + readonly handoffId?: string +} + +export function makePageStatus(options: { + readonly state: PageStatus["state"] + readonly targetOwner: "relay" | "user" + readonly sessionId?: string + readonly readOnly?: boolean + readonly message?: string + readonly handoffId?: string +}): PageStatus { + return { + state: options.state, + owner: options.targetOwner === "user" ? "user" : "session", + ...(options.sessionId ? { sessionId: options.sessionId } : {}), + ...(options.sessionId && options.readOnly ? { readOnly: true } : {}), + ...(options.message ? { message: options.message } : {}), + ...(options.handoffId ? { handoffId: options.handoffId } : {}), + } +} + +const extensionCommandMethodValues = [ + "ping", + "debugger.attach", + "debugger.detach", + "debugger.sendCommand", + "tabs.create", + "tabs.remove", + "tabs.group", + "tabs.ungroup", + "action.setAttached", + "action.setBadge", + "pageStatus.set", + "pageStatus.clear", + "runtime.reload", + "recording.start", + "recording.stop", + "recording.status", + "recording.cancel", + "tabs.cleanup", +] as const + +const extensionEventMethodValues = [ + "hello", + "ready", + "toolbar.clicked", + "handoff.completed", + "debugger.event", + "debugger.attached", + "debugger.detached", + "tabs.removed", + "pong", + "log", + "recording.cancelled", + "pageStatus.requested", +] as const + +type ExtensionCommandMethod = typeof extensionCommandMethodValues[number] +type ExtensionEventMethod = typeof extensionEventMethodValues[number] + +export type ExtensionCommand = { + readonly id: number + readonly method: ExtensionCommandMethod + readonly params?: JsonObject +} + +export type ExtensionResponse = { + readonly id: number + readonly result?: JsonObject + readonly error?: string +} + +export type ExtensionEvent = { + readonly method: ExtensionEventMethod + readonly params?: JsonObject +} + +export function parseJsonObject(input: string): JsonObject { + const parsed: unknown = JSON.parse(input) + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) { + throw new Error("Expected JSON object") + } + return parsed as JsonObject +} + +const extensionCommandMethods = new Set(extensionCommandMethodValues) + +const extensionEventMethods = new Set(extensionEventMethodValues) + +export function parseExtensionCommand(input: string): ExtensionCommand { + const parsed = parseJsonObject(input) + if ( + typeof parsed.id !== "number" || + typeof parsed.method !== "string" || + !extensionCommandMethods.has(parsed.method) || + (parsed.params !== undefined && !isJsonObject(parsed.params)) + ) { + throw new Error("Invalid extension command") + } + return parsed as ExtensionCommand +} + +export function isCdpRequest(input: JsonObject): input is CdpRequest { + return typeof input.id === "number" && + typeof input.method === "string" && + (input.params === undefined || isJsonObject(input.params)) && + (input.sessionId === undefined || typeof input.sessionId === "string") +} + +export function isExtensionResponse(input: JsonObject): input is ExtensionResponse { + return typeof input.id === "number" && + (input.result === undefined || isJsonObject(input.result)) && + (input.error === undefined || typeof input.error === "string") && + !(input.result !== undefined && input.error !== undefined) +} + +export function isExtensionEvent(input: JsonObject): input is ExtensionEvent { + return typeof input.method === "string" && + extensionEventMethods.has(input.method) && + (input.params === undefined || isJsonObject(input.params)) +} + +export function isJsonObject(value: unknown): value is JsonObject { + return value !== null && typeof value === "object" && !Array.isArray(value) +} diff --git a/packages/browser-extension/cli/src/recording-protocol.ts b/packages/browser-extension/cli/src/recording-protocol.ts new file mode 100644 index 00000000000..e46c13c074f --- /dev/null +++ b/packages/browser-extension/cli/src/recording-protocol.ts @@ -0,0 +1,62 @@ +const magic = [0x42, 0x43, 0x52, 0x44] as const +const version = 1 +const finalFlag = 1 +const headerLength = 20 + +export const maxRecordingFramePayloadBytes = 4 * 1024 * 1024 + +export type RecordingFrame = { + readonly tabId: number + readonly sequence: number + readonly final: boolean + readonly payload: Uint8Array +} + +export function encodeRecordingFrame(frame: RecordingFrame): Uint8Array { + validateUint32(frame.tabId, "tabId", true) + validateUint32(frame.sequence, "sequence", false) + if (frame.payload.byteLength > maxRecordingFramePayloadBytes) { + throw new Error(`Recording frame payload exceeds ${maxRecordingFramePayloadBytes} bytes`) + } + if (frame.final && frame.payload.byteLength !== 0) throw new Error("Final recording frame must have an empty payload") + if (!frame.final && frame.payload.byteLength === 0) throw new Error("Recording data frame must have a payload") + const encoded = new Uint8Array(headerLength + frame.payload.byteLength) + encoded.set(magic, 0) + const view = new DataView(encoded.buffer) + view.setUint8(4, version) + view.setUint8(5, frame.final ? finalFlag : 0) + view.setUint16(6, headerLength) + view.setUint32(8, frame.tabId) + view.setUint32(12, frame.sequence) + view.setUint32(16, frame.payload.byteLength) + encoded.set(frame.payload, headerLength) + return encoded +} + +export function decodeRecordingFrame(data: Uint8Array): RecordingFrame { + if (data.byteLength < headerLength) throw new Error("Recording frame is shorter than its header") + if (magic.some((byte, index) => data[index] !== byte)) throw new Error("Invalid recording frame magic") + const view = new DataView(data.buffer, data.byteOffset, data.byteLength) + if (view.getUint8(4) !== version) throw new Error(`Unsupported recording frame version: ${view.getUint8(4)}`) + const flags = view.getUint8(5) + if ((flags & ~finalFlag) !== 0) throw new Error(`Invalid recording frame flags: ${flags}`) + if (view.getUint16(6) !== headerLength) throw new Error(`Invalid recording frame header length: ${view.getUint16(6)}`) + const tabId = view.getUint32(8) + const sequence = view.getUint32(12) + const payloadLength = view.getUint32(16) + if (tabId === 0) throw new Error("Recording frame tabId must be positive") + if (payloadLength > maxRecordingFramePayloadBytes) { + throw new Error(`Recording frame payload exceeds ${maxRecordingFramePayloadBytes} bytes`) + } + if (data.byteLength !== headerLength + payloadLength) throw new Error("Recording frame payload length does not match its header") + const final = (flags & finalFlag) !== 0 + if (final && payloadLength !== 0) throw new Error("Final recording frame must have an empty payload") + if (!final && payloadLength === 0) throw new Error("Recording data frame must have a payload") + return { tabId, sequence, final, payload: data.subarray(headerLength) } +} + +function validateUint32(value: number, field: string, positive: boolean): void { + if (!Number.isInteger(value) || value < (positive ? 1 : 0) || value > 0xffff_ffff) { + throw new Error(`Recording frame ${field} must be ${positive ? "a positive" : "an"} uint32`) + } +} diff --git a/packages/browser-extension/cli/src/recording-relay.ts b/packages/browser-extension/cli/src/recording-relay.ts new file mode 100644 index 00000000000..41a30b3dcd3 --- /dev/null +++ b/packages/browser-extension/cli/src/recording-relay.ts @@ -0,0 +1,1199 @@ +import { execFile, spawn } from "node:child_process" +import crypto from "node:crypto" +import { once } from "node:events" +import fs from "node:fs/promises" +import path from "node:path" +import { performance } from "node:perf_hooks" +import { Option, Predicate, Schema } from "effect" +import { terminateChildProcess } from "./child-process.ts" +import { mjpegMatroskaFrame, mjpegMatroskaHeader } from "./mjpeg-matroska.ts" +import type { ExtensionCommand, JsonObject } from "./protocol.ts" +import { getNumber, getObject, getString } from "./relay-helpers.ts" +import type { ConnectedTarget } from "./relay-types.ts" +import { decodeRecordingFrame } from "./recording-protocol.ts" +import type { RecordingCancelResponse, RecordingQuality, RecordingStatusResponse, RecordingTargetRequest } from "./relay-schema.ts" + +const defaultMaxDurationMs = 15 * 60 * 1_000 +const defaultCdpFrameRate = 60 +const maxRecordingFrameRate = 60 +const maxPendingCdpFrames = 30 +const fallbackCdpWidth = 1_280 +const fallbackCdpHeight = 720 +const cdpJpegQuality = 100 +const maxPendingTabCaptureBytes = 16 * 1024 * 1024 +const maxTabCaptureOutputBytes = 1024 * 1024 * 1024 + +type RecordingMode = "auto" | "tab-capture" | "cdp" +type ActiveRecordingMode = "tab-capture" | "cdp" +type RecordingArtifactType = "webm" | "mp4" + +export type SendDebuggerCommand = (options: { + readonly tabId: number + readonly sessionId?: string + readonly method: string + readonly params: JsonObject +}) => Promise + +export type RecordingStartOptions = { + readonly tabId: number + readonly sessionId?: string + readonly owner: ConnectedTarget["owner"] + readonly outputPath: string + readonly mode?: RecordingMode + readonly frameRate?: number + readonly audio?: boolean + readonly videoBitsPerSecond?: number + readonly audioBitsPerSecond?: number + readonly maxDurationMs?: number +} + +export type RecordingTargetOptions = RecordingTargetRequest + +export type RecordingStartResult = + | { + readonly success: true + readonly tabId: number + readonly startedAt: number + readonly path: string + readonly mimeType: string + readonly mode: ActiveRecordingMode + readonly artifactType: RecordingArtifactType + readonly frameRate?: number + } + | { + readonly success: false + readonly error: string + } + +export type RecordingStopResult = + | { + readonly success: true + readonly tabId: number + readonly duration: number + readonly path: string + readonly size: number + readonly mode: ActiveRecordingMode + readonly artifactType: RecordingArtifactType + readonly frameCount?: number + readonly quality?: RecordingQuality + } + | { + readonly success: false + readonly error: string + } + +export type RecordingStatusResult = RecordingStatusResponse + +export type RecordingCancelResult = RecordingCancelResponse + +type ActiveRecordingBase = { + tabId: number + sessionId?: string + outputPath: string + startedAt: number + mode: ActiveRecordingMode + artifactType: RecordingArtifactType + maxDurationTimer?: ReturnType + resolveStop?: (result: RecordingStopResult) => void + cleanupPromise?: Promise +} + +type TabCaptureRecording = ActiveRecordingBase & { + mode: "tab-capture" + artifactType: "webm" + temporaryPath: string + file: Awaited> + expectedSequence: number + receivedBytes: number + pendingWriteBytes: number + writePromise: Promise + writeError?: Error + stopping: boolean + finalized: boolean + stopPromise?: Promise + finalizePromise?: Promise +} + +type CdpRecording = ActiveRecordingBase & { + mode: "cdp" + artifactType: "webm" | "mp4" + frameRate: number + encoder: VideoEncoder + lastFrame?: CdpVideoFrame + frameCount: number + sourceFrameCount: number + encodedSourceFrameCount: number + coalescedFrameCount: number + droppedFrameCount: number + pendingFrameCount: number + width: number + height: number + sourceWidth?: number + sourceHeight?: number + stopped: boolean + stopping: boolean + startedMonotonicAt: number + stopPromise?: Promise + writePromise: Promise + writeError?: Error +} + +type CdpVideoFrame = { + readonly buffer: Buffer + readonly frameNumber: number + readonly surfaceWidth?: number +} + +export type VideoEncoder = { + readonly write: (frame: Buffer, timestampMs: number, durationMs: number, surfaceWidth?: number) => Promise + readonly finish: () => Promise + readonly cancel: () => Promise +} + +export type StartVideoEncoder = (options: { + readonly outputPath: string + readonly artifactType: "webm" | "mp4" + readonly frameRate: number + readonly width: number + readonly height: number +}) => Promise + +type ActiveRecording = TabCaptureRecording | CdpRecording + +type StartingRecording = { + readonly tabId: number + readonly sessionId?: string + cancelled: boolean + promise?: Promise +} + +type ExtensionStartResult = + | { + readonly success: true + readonly tabId: number + readonly startedAt: number + readonly mimeType?: string + } + | { + readonly success: false + readonly error: string + } + +type ExtensionStopResult = + | { + readonly success: true + readonly tabId: number + readonly duration: number + } + | { + readonly success: false + readonly error: string + } + +type ExtensionStatusResult = { + readonly isRecording: boolean + readonly tabId?: number + readonly startedAt?: number +} + +export class RecordingRelay { + private readonly activeRecordings = new Map() + private readonly startingRecordings = new Map() + + constructor(readonly options: { + readonly sendToExtension: (command: Omit) => Promise + readonly sendDebuggerCommand: SendDebuggerCommand + readonly isExtensionConnected: () => boolean + readonly isTabUnavailable?: (tabId: number) => boolean + readonly startVideoEncoder?: StartVideoEncoder + readonly now?: () => number + readonly monotonicNow?: () => number + }) {} + + hasActiveRecordings(): boolean { + return this.activeRecordings.size > 0 || this.startingRecordings.size > 0 + } + + isRecordingTab(tabId: number): boolean { + return this.activeRecordings.has(tabId) || this.startingRecordings.has(tabId) + } + + async startRecording(options: RecordingStartOptions): Promise { + if (options.frameRate !== undefined && (!Number.isInteger(options.frameRate) || options.frameRate < 1 || options.frameRate > maxRecordingFrameRate)) { + return { success: false, error: "Recording frameRate must be an integer from 1 to 60" } + } + if (!this.options.isExtensionConnected()) { + return { success: false, error: "OpenCode Browser extension is not connected" } + } + if (this.activeRecordings.has(options.tabId) || this.startingRecordings.has(options.tabId)) { + return { success: false, error: "Recording already in progress for this tab" } + } + if (this.options.isTabUnavailable?.(options.tabId)) { + return { success: false, error: "Stop the active flight recorder before starting a recording" } + } + const starting: StartingRecording = { + tabId: options.tabId, + ...(options.sessionId ? { sessionId: options.sessionId } : {}), + cancelled: false, + } + this.startingRecordings.set(options.tabId, starting) + const promise = this.startReservedRecording(options, starting) + starting.promise = promise + try { + return await promise + } finally { + if (this.startingRecordings.get(options.tabId) === starting) { + this.startingRecordings.delete(options.tabId) + } + } + } + + async stopRecording(options: RecordingTargetOptions): Promise { + if (!this.options.isExtensionConnected()) { + return { success: false, error: "OpenCode Browser extension is not connected" } + } + const recording = this.findRecording(options) + if (!recording) { + return { success: false, error: "No active recording found" } + } + if (recording.stopPromise) return recording.stopPromise + if (recording.cleanupPromise) { + await recording.cleanupPromise + return { success: false, error: "Recording was cancelled" } + } + if (recording.mode === "cdp") { + return this.stopCdpRecording(recording) + } + const stopPromise = this.stopTabCaptureRecording(recording) + recording.stopPromise = stopPromise + return stopPromise + } + + private async stopTabCaptureRecording(recording: TabCaptureRecording): Promise { + let stopTimeout: ReturnType | undefined + const finalResult = new Promise((resolve) => { + stopTimeout = setTimeout(() => { + delete recording.resolveStop + if (this.activeRecordings.get(recording.tabId) === recording && !recording.cleanupPromise && !recording.finalizePromise) { + const cancel = this.options.isExtensionConnected() + ? this.options.sendToExtension({ method: "recording.cancel", params: { tabId: recording.tabId } }) + : undefined + void this.cleanupTabCaptureRecording(recording, cancel) + } + resolve({ success: false, error: "Timeout waiting for recording data" }) + }, 30_000) + recording.resolveStop = (result) => { + if (stopTimeout) clearTimeout(stopTimeout) + resolve(result) + } + }) + + try { + const result = parseExtensionStopResult(await this.options.sendToExtension({ + method: "recording.stop", + params: { tabId: recording.tabId }, + })) + if (!result.success) { + if (stopTimeout) clearTimeout(stopTimeout) + delete recording.resolveStop + await this.failTabCaptureRecording(recording, result.error) + return result + } + return await finalResult + } catch (error) { + if (stopTimeout) clearTimeout(stopTimeout) + delete recording.resolveStop + const message = error instanceof Error ? error.message : String(error) + await this.failTabCaptureRecording(recording, message) + return { success: false, error: message } + } + } + + async statusRecording(options: RecordingTargetOptions): Promise { + const recording = this.findRecording(options) + if (!recording || !this.options.isExtensionConnected()) { + return { isRecording: false } + } + if (recording.mode === "cdp") { + return { + isRecording: true, + tabId: recording.tabId, + startedAt: recording.startedAt, + path: recording.outputPath, + mode: "cdp", + artifactType: recording.artifactType, + quality: recordingQuality(recording, this.monotonicNow() - recording.startedMonotonicAt), + frameCount: recording.stopping + ? recording.frameCount + : Math.max(0, Math.round(((this.monotonicNow() - recording.startedMonotonicAt) / 1_000) * recording.frameRate)), + } + } + let result: ExtensionStatusResult | undefined + try { + result = parseExtensionStatusResult(await this.options.sendToExtension({ + method: "recording.status", + params: { tabId: recording.tabId }, + })) + } catch { + // A transient status poll failure must not destroy an in-progress + // recording; report last-known local state instead. + } + return { + isRecording: result?.isRecording ?? true, + tabId: recording.tabId, + startedAt: result?.startedAt ?? recording.startedAt, + path: recording.outputPath, + size: recording.receivedBytes, + mode: "tab-capture", + artifactType: "webm", + } + } + + async cancelRecording(options: RecordingTargetOptions): Promise { + const starting = this.findStartingRecording(options) + if (starting) { + starting.cancelled = true + await starting.promise?.catch(() => {}) + return { success: true } + } + const recording = this.findRecording(options) + if (!recording) { + return { success: true } + } + if (recording.cleanupPromise) { + await recording.cleanupPromise + return { success: true } + } + if (recording.mode === "cdp") { + await this.cancelCdpRecording(recording) + return { success: true } + } + if (recording.finalizePromise) { + await recording.finalizePromise + return { success: true } + } + if (!this.options.isExtensionConnected()) { + recording.resolveStop?.({ success: false, error: "Recording was cancelled" }) + await this.cleanupRecording(recording.tabId) + return { success: false, error: "OpenCode Browser extension is not connected" } + } + const result = this.options.sendToExtension({ method: "recording.cancel", params: { tabId: recording.tabId } }).then( + parseCancelResult, + (error: unknown) => ({ success: false, error: error instanceof Error ? error.message : String(error) }), + ).then((result) => { + recording.resolveStop?.({ success: false, error: "Recording was cancelled" }) + return result + }) + await this.cleanupTabCaptureRecording(recording, result) + return result + } + + async cleanupAll(reason: string): Promise { + const starting = Array.from(this.startingRecordings.values()) + const startingTabIds = new Set(starting.map((recording) => recording.tabId)) + const active = Array.from(this.activeRecordings.values()).filter((recording) => { + return !startingTabIds.has(recording.tabId) + }) + for (const recording of starting) recording.cancelled = true + await Promise.all(starting.map(async (recording) => { + await recording.promise?.catch(() => {}) + })) + await Promise.all(active.map(async (recording) => { + await this.abortActiveRecording(recording, reason) + })) + } + + async abortRecordingForTab(options: { readonly tabId: number; readonly reason: string }): Promise { + const starting = this.startingRecordings.get(options.tabId) + if (starting) { + starting.cancelled = true + await starting.promise?.catch(() => {}) + return + } + const recording = this.activeRecordings.get(options.tabId) + if (!recording) { + return + } + await this.abortActiveRecording(recording, options.reason) + } + + private async abortActiveRecording(recording: ActiveRecording, reason: string): Promise { + if (recording.mode === "tab-capture" && recording.finalizePromise) { + await recording.finalizePromise + return + } + recording.resolveStop?.({ success: false, error: reason }) + if (recording.mode === "cdp") { + await this.cancelCdpRecording(recording) + return + } + await this.cleanupTabCaptureRecording(recording) + } + + handleRecordingCancelled(message: JsonObject): void { + const params = getObject(message.params) + const tabId = getNumber(params, "tabId") + const recording = tabId === undefined ? undefined : this.activeRecordings.get(tabId) + if (!recording) { + return + } + void this.abortActiveRecording(recording, "Recording was cancelled") + } + + handleDebuggerEvent(options: { readonly tabId: number; readonly method: string; readonly params: JsonObject | undefined }): boolean { + if (options.method !== "Page.screencastFrame") { + return false + } + const recording = this.activeRecordings.get(options.tabId) + if (!recording || recording.mode !== "cdp") { + return false + } + const frameSessionId = getNumber(options.params, "sessionId") + if (frameSessionId !== undefined) { + void this.options.sendDebuggerCommand({ + tabId: recording.tabId, + method: "Page.screencastFrameAck", + params: { sessionId: frameSessionId }, + }).catch((error: unknown) => { + if (!recording.stopped && !recording.stopping) console.error("CDP recording frame acknowledgement failed", error) + }) + } + const frameData = getString(options.params, "data") + if (recording.stopped || recording.stopping || frameData === undefined) { + return true + } + const metadata = getObject(options.params?.metadata) + recording.sourceFrameCount += 1 + if (recording.pendingFrameCount >= maxPendingCdpFrames || recording.writeError) { + recording.droppedFrameCount += 1 + return true + } + const deviceWidth = getNumber(metadata, "deviceWidth") + const deviceHeight = getNumber(metadata, "deviceHeight") + if (deviceWidth !== undefined) recording.sourceWidth = deviceWidth + if (deviceHeight !== undefined) recording.sourceHeight = deviceHeight + const buffer = Buffer.from(frameData, "base64") + const receivedAt = this.monotonicNow() + const rawFramePosition = ((receivedAt - recording.startedMonotonicAt) / 1_000) * recording.frameRate + let frameNumber = recording.sourceFrameCount === 1 + ? 0 + : Math.max(0, Math.floor(rawFramePosition)) + if (recording.lastFrame && frameNumber === recording.lastFrame.frameNumber && rawFramePosition - frameNumber >= 0.5) { + frameNumber = recording.lastFrame.frameNumber + 1 + } + recording.pendingFrameCount += 1 + recording.writePromise = recording.writePromise.then(async () => { + if (recording.lastFrame && frameNumber !== recording.lastFrame.frameNumber) { + await this.writeSourceFrame(recording, recording.lastFrame, frameNumber) + } else if (recording.lastFrame) { + recording.coalescedFrameCount += 1 + } + recording.lastFrame = { + buffer, + frameNumber, + ...(deviceWidth !== undefined ? { surfaceWidth: deviceWidth } : {}), + } + }).catch((error: unknown) => { + recording.writeError = error instanceof Error ? error : new Error(String(error)) + }).finally(() => { + recording.pendingFrameCount -= 1 + }) + return true + } + + handleBinaryData(data: Buffer): void { + const frame = decodeRecordingFrame(data) + const recording = this.activeRecordings.get(frame.tabId) + if (!recording || recording.mode !== "tab-capture") { + return + } + if (recording.stopping || recording.finalized) return + if (recording.writeError) { + void this.failTabCaptureRecording(recording, recording.writeError.message) + return + } + if (frame.sequence !== recording.expectedSequence) { + void this.failTabCaptureRecording(recording, `Recording frame sequence ${frame.sequence} did not match expected ${recording.expectedSequence}`) + return + } + recording.expectedSequence += 1 + if (frame.final) { + recording.stopping = true + if (recording.maxDurationTimer) clearTimeout(recording.maxDurationTimer) + recording.finalizePromise = this.finishTabCaptureRecording(recording) + void recording.finalizePromise + return + } + if (recording.receivedBytes + frame.payload.byteLength > maxTabCaptureOutputBytes) { + void this.failTabCaptureRecording(recording, `Tab capture exceeds ${maxTabCaptureOutputBytes} bytes`) + return + } + if (recording.pendingWriteBytes + frame.payload.byteLength > maxPendingTabCaptureBytes) { + void this.failTabCaptureRecording(recording, `Tab capture pending writes exceed ${maxPendingTabCaptureBytes} bytes`) + return + } + const payload = frame.payload + recording.receivedBytes += payload.byteLength + recording.pendingWriteBytes += payload.byteLength + recording.writePromise = recording.writePromise.then(async () => { + const result = await recording.file.write(payload) + if (result.bytesWritten !== payload.byteLength) throw new Error(`Short recording write: ${result.bytesWritten}/${payload.byteLength}`) + }).catch((error: unknown) => { + recording.writeError ??= error instanceof Error ? error : new Error(String(error)) + void this.failTabCaptureRecording(recording, recording.writeError.message) + }).finally(() => { + recording.pendingWriteBytes -= payload.byteLength + }) + } + + private async finishTabCaptureRecording(recording: TabCaptureRecording): Promise { + try { + await recording.writePromise + if (recording.writeError) throw recording.writeError + if (recording.receivedBytes === 0) throw new Error("No tab capture data was received") + await recording.file.sync() + await recording.file.close() + await fs.rename(recording.temporaryPath, recording.outputPath) + recording.finalized = true + recording.resolveStop?.({ + success: true, + tabId: recording.tabId, + duration: Date.now() - recording.startedAt, + path: recording.outputPath, + size: recording.receivedBytes, + mode: "tab-capture", + artifactType: "webm", + }) + } catch (error) { + recording.resolveStop?.({ success: false, error: error instanceof Error ? error.message : String(error) }) + } finally { + await this.cleanupTabCaptureRecording(recording) + } + } + + private findRecording(options: RecordingTargetOptions): ActiveRecording | undefined { + return findByRecordingTarget(this.activeRecordings, options, "Multiple active recordings; provide sessionId or tabId") + } + + private findStartingRecording(options: RecordingTargetOptions): StartingRecording | undefined { + return findByRecordingTarget(this.startingRecordings, options, "Multiple recordings are starting; provide sessionId or tabId") + } + + private async cleanupRecording(tabId: number): Promise { + const recording = this.activeRecordings.get(tabId) + if (!recording) return + if (recording.mode === "cdp") { + await this.cancelCdpRecording(recording) + return + } + if (recording.finalizePromise) return recording.finalizePromise + return this.cleanupTabCaptureRecording(recording) + } + + private cleanupTabCaptureRecording(recording: TabCaptureRecording, cancel?: Promise): Promise { + if (recording.cleanupPromise) return recording.cleanupPromise + recording.stopping = true + if (recording.maxDurationTimer) clearTimeout(recording.maxDurationTimer) + recording.cleanupPromise = (async () => { + await cancel?.catch(() => {}) + await recording.writePromise.catch(() => {}) + await recording.file.close().catch(() => {}) + if (!recording.finalized) await fs.rm(recording.temporaryPath, { force: true }).catch(() => {}) + if (this.activeRecordings.get(recording.tabId) === recording) { + this.activeRecordings.delete(recording.tabId) + } + })() + return recording.cleanupPromise + } + + private async failTabCaptureRecording(recording: TabCaptureRecording, message: string): Promise { + if (recording.stopping || recording.finalized) return + recording.stopping = true + recording.resolveStop?.({ success: false, error: message }) + const cancel = this.options.isExtensionConnected() + ? this.options.sendToExtension({ method: "recording.cancel", params: { tabId: recording.tabId } }) + : undefined + await this.cleanupTabCaptureRecording(recording, cancel) + } + + private async startReservedRecording(options: RecordingStartOptions, starting: StartingRecording): Promise { + const mode = selectRecordingMode(options) + if (mode === "cdp") { + return this.startCdpRecording(options, starting) + } + if (cdpArtifactType(options.outputPath) !== "webm") { + return { success: false, error: "tabCapture recording output path must end in .webm; use --mode cdp for MP4" } + } + + await fs.mkdir(path.dirname(options.outputPath), { recursive: true }) + if (starting.cancelled) return { success: false, error: "Recording was cancelled while starting" } + const temporaryPath = `${options.outputPath}.partial-${process.pid}-${crypto.randomUUID()}` + const file = await fs.open(temporaryPath, "wx", 0o600) + const recording: TabCaptureRecording = { + tabId: options.tabId, + ...(options.sessionId ? { sessionId: options.sessionId } : {}), + outputPath: options.outputPath, + temporaryPath, + file, + mode: "tab-capture", + artifactType: "webm", + expectedSequence: 0, + receivedBytes: 0, + pendingWriteBytes: 0, + writePromise: Promise.resolve(), + stopping: false, + finalized: false, + startedAt: this.now(), + } + this.activeRecordings.set(options.tabId, recording) + let result: ExtensionStartResult + try { + result = parseExtensionStartResult(await this.options.sendToExtension({ + method: "recording.start", + params: recordingStartParams(options), + })) + } catch (error) { + await this.cleanupRecording(options.tabId) + throw error + } + if (!result.success || starting.cancelled || result.tabId !== options.tabId || this.activeRecordings.get(options.tabId) !== recording) { + if (result.success) await this.options.sendToExtension({ method: "recording.cancel", params: { tabId: result.tabId } }).catch(() => {}) + await this.cleanupRecording(options.tabId) + if (!result.success) return result + return { + success: false, + error: starting.cancelled + ? "Recording was cancelled while starting" + : result.tabId !== options.tabId + ? `Extension started recording tab ${result.tabId} instead of ${options.tabId}` + : recording.writeError?.message ?? "Recording ended while starting", + } + } + recording.startedAt = result.startedAt + this.armMaxDuration(recording, options.maxDurationMs) + return { + success: true, + tabId: result.tabId, + startedAt: result.startedAt, + frameRate: options.frameRate ?? 30, + path: options.outputPath, + mimeType: result.mimeType ?? "video/webm", + mode: "tab-capture", + artifactType: "webm", + } + } + + private async startCdpRecording(options: RecordingStartOptions, starting: StartingRecording): Promise { + if (options.audio === true) { + return { success: false, error: "CDP recording captures video frames only; audio is not supported" } + } + const artifactType = cdpArtifactType(options.outputPath) + if (!artifactType) { + return { success: false, error: "CDP recording output path must end in .webm or .mp4" } + } + await fs.mkdir(path.dirname(options.outputPath), { recursive: true }) + if (starting.cancelled) return { success: false, error: "Recording was cancelled while starting" } + const frameRate = options.frameRate ?? defaultCdpFrameRate + let size: { readonly width: number; readonly height: number } + try { + size = await prepareCdpScreencastViewport(this.options.sendDebuggerCommand, options.tabId) + } catch (error) { + return { success: false, error: `Could not prepare the page for recording: ${error instanceof Error ? error.message : String(error)}` } + } + if (starting.cancelled) return { success: false, error: "Recording was cancelled while starting" } + let encoder: VideoEncoder + try { + encoder = await (this.options.startVideoEncoder ?? startFfmpegVideoEncoder)({ + outputPath: options.outputPath, + artifactType, + frameRate, + width: size.width, + height: size.height, + }) + } catch (error) { + return { success: false, error: `Could not start CDP video encoder: ${error instanceof Error ? error.message : String(error)}` } + } + if (starting.cancelled) { + await encoder.cancel() + return { success: false, error: "Recording was cancelled while starting" } + } + const startedAt = this.now() + const startedMonotonicAt = this.monotonicNow() + const recording: CdpRecording = { + tabId: options.tabId, + ...(options.sessionId ? { sessionId: options.sessionId } : {}), + outputPath: options.outputPath, + mode: "cdp", + artifactType, + startedAt, + frameRate, + encoder, + frameCount: 0, + sourceFrameCount: 0, + encodedSourceFrameCount: 0, + coalescedFrameCount: 0, + droppedFrameCount: 0, + pendingFrameCount: 0, + width: size.width, + height: size.height, + stopped: false, + stopping: false, + startedMonotonicAt, + writePromise: Promise.resolve(), + } + this.activeRecordings.set(options.tabId, recording) + try { + await this.options.sendDebuggerCommand({ + tabId: recording.tabId, + method: "Page.startScreencast", + params: { + format: "jpeg", + quality: cdpJpegQuality, + everyNthFrame: 1, + }, + }) + } catch (error) { + await this.cleanupCdpRecording(recording) + return { success: false, error: `Could not start CDP screencast: ${error instanceof Error ? error.message : String(error)}` } + } + if (starting.cancelled || this.activeRecordings.get(recording.tabId) !== recording) { + await this.cleanupCdpRecording(recording) + return { success: false, error: "Recording was cancelled while starting" } + } + this.armMaxDuration(recording, options.maxDurationMs) + return { + success: true, + tabId: options.tabId, + startedAt, + path: options.outputPath, + mimeType: artifactType === "mp4" ? "video/mp4" : "video/webm", + mode: "cdp", + artifactType, + frameRate, + } + } + + private async stopCdpRecording(recording: CdpRecording): Promise { + if (recording.stopPromise) return recording.stopPromise + recording.stopping = true + if (recording.maxDurationTimer) clearTimeout(recording.maxDurationTimer) + const stopPromise = this.finishCdpRecording(recording).finally(() => { + if (this.activeRecordings.get(recording.tabId) === recording) { + this.activeRecordings.delete(recording.tabId) + } + recording.stopped = true + }) + recording.stopPromise = stopPromise + return stopPromise + } + + private async cancelCdpRecording(recording: CdpRecording): Promise { + if (recording.stopPromise) { + await recording.stopPromise.catch(() => {}) + return + } + await this.cleanupCdpRecording(recording) + } + + private now(): number { + return this.options.now?.() ?? Date.now() + } + + private armMaxDuration(recording: ActiveRecording, requestedMaxDurationMs: number | undefined): void { + const maxDurationMs = requestedMaxDurationMs ?? defaultMaxDurationMs + if (maxDurationMs <= 0 || !Number.isFinite(maxDurationMs)) return + recording.maxDurationTimer = setTimeout(() => { + void this.stopRecording({ tabId: recording.tabId }).catch((error) => { + console.error("Recording max duration stop failed", error) + }) + }, maxDurationMs) + } + + private monotonicNow(): number { + return this.options.monotonicNow?.() ?? this.options.now?.() ?? performance.now() + } + + private async finishCdpRecording(recording: CdpRecording): Promise { + const stoppedAt = this.now() + const stoppedMonotonicAt = this.monotonicNow() + try { + await this.options.sendDebuggerCommand({ tabId: recording.tabId, method: "Page.stopScreencast", params: {} }).catch(() => {}) + await recording.writePromise + if (recording.writeError) throw recording.writeError + if (!recording.lastFrame) { + const screenshot = await this.options.sendDebuggerCommand({ + tabId: recording.tabId, + method: "Page.captureScreenshot", + params: { format: "jpeg", quality: cdpJpegQuality, fromSurface: true, captureBeyondViewport: false }, + }) + const screenshotData = getString(screenshot, "data") + if (screenshotData === undefined) throw new Error("No video frames were captured") + recording.lastFrame = { buffer: Buffer.from(screenshotData, "base64"), frameNumber: 0 } + } + const durationMs = Math.max(0, stoppedMonotonicAt - recording.startedMonotonicAt) + const expectedFrameCount = Math.max(1, Math.round((durationMs / 1_000) * recording.frameRate)) + const endFrameNumber = Math.max(recording.lastFrame.frameNumber + 1, expectedFrameCount) + await this.writeSourceFrame(recording, recording.lastFrame, endFrameNumber) + recording.frameCount = endFrameNumber + await recording.encoder.finish() + + const stat = await fs.stat(recording.outputPath) + const quality = recordingQuality(recording, durationMs) + const metadata = { + mode: "cdp", + artifactType: recording.artifactType, + tabId: recording.tabId, + ...(recording.sessionId ? { sessionId: recording.sessionId } : {}), + startedAt: new Date(recording.startedAt).toISOString(), + stoppedAt: new Date(stoppedAt).toISOString(), + durationMs, + frameCount: recording.frameCount, + ...quality, + mimeType: recording.artifactType === "mp4" ? "video/mp4" : "video/webm", + } + await fs.writeFile(`${recording.outputPath}.json`, `${JSON.stringify(metadata, null, 2)}\n`, "utf8") + return { + success: true, + tabId: recording.tabId, + duration: durationMs, + path: recording.outputPath, + size: stat.size, + mode: "cdp", + artifactType: recording.artifactType, + frameCount: recording.frameCount, + quality, + } + } catch (error) { + await recording.encoder.cancel().catch(() => {}) + return { success: false, error: `CDP video encoding failed: ${error instanceof Error ? error.message : String(error)}` } + } + } + + private cleanupCdpRecording(recording: CdpRecording): Promise { + if (recording.cleanupPromise) return recording.cleanupPromise + recording.stopped = true + if (recording.maxDurationTimer) clearTimeout(recording.maxDurationTimer) + recording.cleanupPromise = (async () => { + await Promise.all([ + this.options.sendDebuggerCommand({ tabId: recording.tabId, method: "Page.stopScreencast", params: {} }).catch(() => {}), + recording.encoder.cancel().catch(() => {}), + ]) + await recording.writePromise.catch(() => {}) + if (this.activeRecordings.get(recording.tabId) === recording) { + this.activeRecordings.delete(recording.tabId) + } + })() + return recording.cleanupPromise + } + + private async writeSourceFrame(recording: CdpRecording, frame: CdpVideoFrame, endFrameNumber: number): Promise { + const timestampMs = Math.round((frame.frameNumber * 1_000) / recording.frameRate) + const durationMs = Math.max(1, Math.round(((endFrameNumber - frame.frameNumber) * 1_000) / recording.frameRate)) + await recording.encoder.write(frame.buffer, timestampMs, durationMs, frame.surfaceWidth) + recording.encodedSourceFrameCount += 1 + } +} + +function selectRecordingMode(options: RecordingStartOptions): ActiveRecordingMode { + if (options.mode === "cdp") { + return "cdp" + } + if (options.mode === "tab-capture") { + return "tab-capture" + } + return options.owner === "relay" ? "cdp" : "tab-capture" +} + +function recordingStartParams(options: RecordingStartOptions): JsonObject { + return { + tabId: options.tabId, + ...(options.frameRate === undefined ? {} : { frameRate: options.frameRate }), + ...(options.audio === undefined ? {} : { audio: options.audio }), + ...(options.videoBitsPerSecond === undefined ? {} : { videoBitsPerSecond: options.videoBitsPerSecond }), + ...(options.audioBitsPerSecond === undefined ? {} : { audioBitsPerSecond: options.audioBitsPerSecond }), + } +} + +const ExtensionStartResultSchema = Schema.Union([ + Schema.Struct({ + success: Schema.Literal(true), + tabId: Schema.Number, + startedAt: Schema.Number, + mimeType: Schema.optionalKey(Schema.String), + }), + Schema.Struct({ + success: Schema.Literal(false), + error: Schema.String, + }), +]) +const decodeExtensionStartResult = Schema.decodeUnknownOption(ExtensionStartResultSchema) + +const ExtensionStopResultSchema = Schema.Union([ + Schema.Struct({ + success: Schema.Literal(true), + tabId: Schema.Number, + duration: Schema.Number, + }), + Schema.Struct({ + success: Schema.Literal(false), + error: Schema.String, + }), +]) +const decodeExtensionStopResult = Schema.decodeUnknownOption(ExtensionStopResultSchema) + +function parseExtensionStartResult(value: JsonObject): ExtensionStartResult { + return Option.getOrElse(decodeExtensionStartResult(value), () => ({ + success: false, + error: "Invalid recording.start response from extension", + })) +} + +function parseExtensionStopResult(value: JsonObject): ExtensionStopResult { + return Option.getOrElse(decodeExtensionStopResult(value), () => ({ + success: false, + error: "Invalid recording.stop response from extension", + })) +} + +function parseExtensionStatusResult(value: JsonObject): ExtensionStatusResult { + return { + isRecording: value.isRecording === true, + ...(Predicate.isNumber(value.tabId) ? { tabId: value.tabId } : {}), + ...(Predicate.isNumber(value.startedAt) ? { startedAt: value.startedAt } : {}), + } +} + +function parseCancelResult(value: JsonObject): RecordingCancelResult { + return { + success: value.success === true, + ...(Predicate.isString(value.error) ? { error: value.error } : {}), + } +} + +export function findByRecordingTarget( + map: ReadonlyMap, + target: RecordingTargetOptions, + ambiguousMessage: string, +): T | undefined { + if (target.tabId !== undefined) return map.get(target.tabId) + if (target.sessionId) return [...map.values()].find((entry) => entry.sessionId === target.sessionId) + if (map.size > 1) throw new Error(ambiguousMessage) + return map.values().next().value +} + +export function cdpArtifactType(outputPath: string): "webm" | "mp4" | undefined { + const extension = path.extname(outputPath).toLowerCase() + if (extension === ".webm") return "webm" + if (extension === ".mp4") return "mp4" + return undefined +} + +function recordingQuality(recording: CdpRecording, durationMs: number): RecordingQuality { + const seconds = Math.max(0.001, durationMs / 1_000) + return { + width: recording.width, + height: recording.height, + frameRate: recording.frameRate, + sourceFrameCount: recording.sourceFrameCount, + encodedSourceFrameCount: recording.encodedSourceFrameCount, + coalescedFrameCount: recording.coalescedFrameCount, + droppedFrameCount: recording.droppedFrameCount, + achievedSourceFrameRate: recording.sourceFrameCount / seconds, + achievedEncodedSourceFrameRate: recording.encodedSourceFrameCount / seconds, + screenshotFallback: recording.sourceFrameCount === 0 && recording.encodedSourceFrameCount > 0, + ...(recording.sourceWidth === undefined ? {} : { sourceWidth: recording.sourceWidth }), + ...(recording.sourceHeight === undefined ? {} : { sourceHeight: recording.sourceHeight }), + } +} + +export async function prepareCdpScreencastViewport( + sendDebuggerCommand: SendDebuggerCommand, + tabId: number, +): Promise<{ readonly width: number; readonly height: number }> { + await sendDebuggerCommand({ tabId, method: "Page.bringToFront", params: {} }) + const metrics = await sendDebuggerCommand({ tabId, method: "Page.getLayoutMetrics", params: {} }) + return cdpRecordingSize(metrics) +} + +function cdpRecordingSize(metrics: JsonObject): { readonly width: number; readonly height: number } { + const viewport = getObject(metrics.cssVisualViewport) ?? getObject(metrics.visualViewport) + const viewportWidth = Predicate.isNumber(viewport?.clientWidth) ? viewport.clientWidth : fallbackCdpWidth + const viewportHeight = Predicate.isNumber(viewport?.clientHeight) ? viewport.clientHeight : fallbackCdpHeight + return { + width: Math.max(2, Math.floor(viewportWidth) & ~1), + height: Math.max(2, Math.floor(viewportHeight) & ~1), + } +} + +export async function startFfmpegVideoEncoder(options: Parameters[0]): Promise { + // Preserve start-time dependency errors even though geometry arrives later. + await new Promise((resolve, reject) => { + execFile("ffmpeg", ["-version"], { timeout: 5_000 }, (error) => error ? reject(error) : resolve()) + }) + // The first compositor frame supplies the backing surface's CSS width. It can + // differ from both the emulated viewport and the JPEG's Retina pixel width. + let acquisition: Promise | undefined + let cancelled = false + return { + write: async (frame, timestampMs, durationMs, surfaceWidth) => { + if (cancelled) throw new Error("ffmpeg recording was cancelled") + acquisition ??= createFfmpegVideoEncoder({ ...options, surfaceWidth: surfaceWidth ?? options.width }) + const encoder = await acquisition + if (cancelled) throw new Error("ffmpeg recording was cancelled") + await encoder.write(frame, timestampMs, durationMs) + }, + finish: async () => { + if (!acquisition) throw new Error("No recording frames received") + await (await acquisition).finish() + }, + cancel: async () => { + cancelled = true + if (acquisition) await (await acquisition).cancel() + }, + } +} + +async function createFfmpegVideoEncoder(options: { + readonly outputPath: string + readonly artifactType: "webm" | "mp4" + readonly frameRate: number + readonly width: number + readonly height: number + readonly surfaceWidth: number +}): Promise { + const temporaryOutputPath = `${options.outputPath}.partial-${process.pid}-${crypto.randomUUID()}` + const outputArgs = options.artifactType === "webm" + ? ["-c:v", "libvpx", "-crf", "4", "-deadline", "good", "-cpu-used", "4", "-b:v", "6M", "-threads", "2"] + : ["-c:v", "libx264", "-preset", "fast", "-crf", "14", "-tune", "animation", "-pix_fmt", "yuv420p", "-movflags", "+faststart"] + const child = spawn("ffmpeg", [ + "-hide_banner", + "-loglevel", + "error", + "-y", + "-f", + "matroska", + "-fpsprobesize", + "0", + "-probesize", + "32", + "-analyzeduration", + "0", + "-i", + "pipe:0", + "-an", + "-r", + String(options.frameRate), + "-fps_mode", + "cfr", + "-vf", + `scale=min(iw\\,${options.surfaceWidth}):-1:flags=lanczos,pad=ceil(max(iw\\,${options.width})/2)*2:ceil(max(ih\\,${options.height})/2)*2:0:0:gray,crop=${options.width}:${options.height}:0:0`, + ...outputArgs, + "-f", + options.artifactType, + temporaryOutputPath, + ], { detached: process.platform !== "win32", stdio: "pipe" }) + let stderr = "" + child.stderr.setEncoding("utf8") + child.stderr.on("data", (chunk: string) => { + stderr = `${stderr}${chunk}`.slice(-8_000) + }) + const exit = new Promise((resolve) => { + child.once("error", (error) => resolve(error)) + child.once("close", (code, signal) => { + if (code === 0) resolve(undefined) + else resolve(new Error(`ffmpeg exited with ${code ?? signal ?? "unknown status"}${stderr.trim() ? `: ${stderr.trim()}` : ""}`)) + }) + }) + try { + await once(child, "spawn") + await writeStreamChunk(child.stdin, mjpegMatroskaHeader(options.width, options.height)) + } catch (error) { + await exit + await fs.rm(temporaryOutputPath, { force: true }) + throw error + } + let completed = false + let finishingPromise: Promise | undefined + let cancelPromise: Promise | undefined + const terminate = async () => { + child.stdin.destroy() + await terminateChildProcess({ child, exit, graceMs: 2_000 }) + } + return { + write: async (frame, timestampMs, durationMs) => { + if (completed || finishingPromise || cancelPromise) throw new Error("ffmpeg input closed before recording finished") + const envelope = mjpegMatroskaFrame(timestampMs, durationMs, frame.length) + try { + await writeStreamChunk(child.stdin, envelope.header) + await writeStreamChunk(child.stdin, frame) + await writeStreamChunk(child.stdin, envelope.trailer) + } catch (error) { + throw new Error(`${error instanceof Error ? error.message : String(error)}${stderr.trim() ? `: ${stderr.trim()}` : ""}`) + } + }, + finish: async () => { + if (completed) return + if (cancelPromise) throw new Error("ffmpeg recording was cancelled") + if (finishingPromise) return finishingPromise + finishingPromise = (async () => { + child.stdin.end() + const exited = await waitForProcessExit(exit, 30_000) + if (!exited) { + await terminate() + throw new Error("ffmpeg did not finish within 30000ms") + } + const error = await exit + if (error) throw error + await fs.rename(temporaryOutputPath, options.outputPath) + completed = true + })().catch(async (error: unknown) => { + await fs.rm(temporaryOutputPath, { force: true }) + throw error + }) + return finishingPromise + }, + cancel: async () => { + if (completed) return + if (cancelPromise) return cancelPromise + cancelPromise = (async () => { + await terminate() + await fs.rm(temporaryOutputPath, { force: true }) + })() + return cancelPromise + }, + } +} + +async function writeStreamChunk(stream: NodeJS.WritableStream, chunk: Buffer): Promise { + await new Promise((resolve, reject) => { + const onError = (error: Error) => { + cleanup() + reject(error) + } + const onClose = () => { + cleanup() + reject(new Error("ffmpeg input closed before recording finished")) + } + const cleanup = () => { + stream.removeListener("error", onError) + stream.removeListener("close", onClose) + } + stream.once("error", onError) + stream.once("close", onClose) + stream.write(chunk, (error?: Error | null) => { + cleanup() + if (error) reject(error) + else resolve() + }) + }) +} + +async function waitForProcessExit(exit: Promise, timeoutMs: number): Promise { + let timeout: ReturnType | undefined + const timedOut = new Promise((resolve) => { + timeout = setTimeout(() => resolve(false), timeoutMs) + }) + const result = await Promise.race([exit.then(() => true as const), timedOut]) + if (timeout) clearTimeout(timeout) + return result +} diff --git a/packages/browser-extension/cli/src/relay-client.ts b/packages/browser-extension/cli/src/relay-client.ts new file mode 100644 index 00000000000..31157d9fd8e --- /dev/null +++ b/packages/browser-extension/cli/src/relay-client.ts @@ -0,0 +1,312 @@ +import { defaultPort } from "./relay-helpers.ts" +import { NodeHttpClient } from "@effect/platform-node" +import { Config, Context, Effect, Layer, Option, Schema } from "effect" +import { HttpClient, HttpClientRequest, type HttpClientResponse } from "effect/http" +import { + type AuthProfileRequest, + type AuthenticatedJsonRequest, + AuthenticatedJsonOutcome, + AuthProfileSummary, + type AuthRefreshRequest, + type AuthRunRequest, + AuthRunResponse, + ErrorEnvelope, + type ExecuteRequest, + ExecuteResponse, + ExtensionStatus, + FlightRecorderCancelResponse, + type FlightRecorderSaveRequest, + FlightRecorderSaveResponse, + type FlightRecorderStartRequest, + FlightRecorderStatusResponse, + NetworkCancelResponse, + type NetworkSessionRequest, + type NetworkStartRequest, + NetworkStatusResponse, + type NetworkStopRequest, + NetworkStopResponse, + RecordingCancelResponse, + TabsCleanupResponse, + type RecordingStartRequest, + RecordingStartResponse, + RecordingStatusResponse, + RecordingStopResponse, + type RecordingTargetRequest, + RelayErrorCode, + type RelayShutdownRequest, + RelayShutdownResponse, + RelayVersion, + SessionAdoptResponse, + SessionContainer, + SessionDeleted, + SessionsContainer, + TargetSummaries, + type SessionAdoptRequest, + type SessionSummary, + type TargetSummary, +} from "./relay-schema.ts" + +/** + * RelayClient is the single typed client for the relay HTTP API, shared by the + * CLI and the MCP server. All responses are decoded against the shared wire + * schemas in `src/relay-schema.ts`, and failures are tagged errors that keep + * the relay's own error message as the top-level message. + */ + +export const portConfig = Config.Int("OPENCODE_BROWSER_PORT").pipe(Config.withDefault(defaultPort)) + +/** + * Extra `chrome-extension://` origins to allowlist for the extension + * WebSocket, comma- or whitespace-separated. This supports same-host unpacked + * installs whose path-derived id cannot match the relay's bundled path. Parsed + * by `parseAdditionalExtensionOrigins`. + */ +export const extensionOriginsConfig = Config.String("OPENCODE_BROWSER_EXTENSION_ORIGINS").pipe(Config.withDefault("")) + +export const endpointForPort = (port: number): string => `http://127.0.0.1:${port}` + +export class RelayUnreachable extends Schema.TaggedError()( + "RelayClient.RelayUnreachable", + { + message: Schema.String, + endpoint: Schema.String, + path: Schema.String, + cause: Schema.Defect(), + }, +) {} + +export class RelayRejected extends Schema.TaggedError()( + "RelayClient.RelayRejected", + { + message: Schema.String, + status: Schema.Number, + path: Schema.String, + code: Schema.optionalKey(RelayErrorCode), + }, +) {} + +export class RelayDecodeFailed extends Schema.TaggedError()( + "RelayClient.RelayDecodeFailed", + { + message: Schema.String, + path: Schema.String, + cause: Schema.Defect(), + }, +) {} + +class RelayEncodeFailed extends Schema.TaggedError()( + "RelayClient.RelayEncodeFailed", + { + message: Schema.String, + path: Schema.String, + cause: Schema.Defect(), + }, +) {} + +export class RelayConfigInvalid extends Schema.TaggedError()( + "RelayClient.RelayConfigInvalid", + { + message: Schema.String, + cause: Schema.Defect(), + }, +) {} + +export type RelayClientError = RelayUnreachable | RelayRejected | RelayDecodeFailed | RelayEncodeFailed + +export interface Interface { + readonly endpoint: string + readonly version: Effect.Effect + readonly shutdown: (request: RelayShutdownRequest) => Effect.Effect + readonly extensionStatus: Effect.Effect + readonly targets: Effect.Effect + readonly sessions: Effect.Effect + readonly sessionNew: (id?: string | undefined, options?: { readonly readOnly?: boolean }) => Effect.Effect + readonly sessionEnsure: (id: string, options?: { readonly readOnly?: boolean }) => Effect.Effect + readonly sessionReset: (id: string) => Effect.Effect + readonly sessionAdopt: (request: SessionAdoptRequest) => Effect.Effect + readonly sessionDelete: (id: string) => Effect.Effect + readonly execute: (request: ExecuteRequest) => Effect.Effect + readonly authenticatedJson: (request: AuthenticatedJsonRequest) => Effect.Effect + readonly networkStart: (request: NetworkStartRequest) => Effect.Effect + readonly networkStatus: (request: NetworkSessionRequest) => Effect.Effect + readonly networkStop: (request: NetworkStopRequest) => Effect.Effect + readonly networkCancel: (request: NetworkSessionRequest) => Effect.Effect + readonly authStatus: (request: AuthProfileRequest) => Effect.Effect + readonly authRefresh: (request: AuthRefreshRequest) => Effect.Effect + readonly authRun: (request: AuthRunRequest) => Effect.Effect + readonly recordingStart: (request: RecordingStartRequest) => Effect.Effect + readonly recordingStop: (target: RecordingTargetRequest) => Effect.Effect + readonly recordingStatus: (target: RecordingTargetRequest) => Effect.Effect + readonly recordingCancel: (target: RecordingTargetRequest) => Effect.Effect + readonly tabsCleanup: (idleMinutes?: number) => Effect.Effect + readonly flightRecorderStart: (request: FlightRecorderStartRequest) => Effect.Effect + readonly flightRecorderStatus: (target: RecordingTargetRequest) => Effect.Effect + readonly flightRecorderSaveLast: (request: FlightRecorderSaveRequest) => Effect.Effect + readonly flightRecorderCancel: (target: RecordingTargetRequest) => Effect.Effect +} + +export class Service extends Context.Service()("opencode-browser-cli/RelayClient") {} + +const decodeErrorEnvelope = Schema.decodeUnknownOption(ErrorEnvelope) +const decodeErrorMessage = Schema.decodeUnknownOption(Schema.Struct({ error: Schema.String })) + +export const make = Effect.fn("RelayClient.make")(function* (options?: { readonly endpoint?: string }) { + const port = yield* portConfig.pipe( + Effect.mapError((cause) => new RelayConfigInvalid({ + message: `Invalid OPENCODE_BROWSER_PORT configuration: ${cause.message}`, + cause, + })), + ) + const endpoint = options?.endpoint ?? endpointForPort(port) + const httpClient = yield* HttpClient.HttpClient + + const readBody = ( + response: HttpClientResponse.HttpClientResponse, + path: string, + ): Effect.Effect => + response.json.pipe( + Effect.mapError((cause) => + new RelayDecodeFailed({ + message: `Relay returned an unreadable response for ${path}`, + path, + cause, + }) + ), + ) + + const handleResponse = ( + response: HttpClientResponse.HttpClientResponse, + path: string, + schema: Schema.ConstraintDecoder, + ): Effect.Effect => + readBody(response, path).pipe( + Effect.flatMap((body): Effect.Effect => { + if (response.status < 200 || response.status >= 300) { + const envelope = decodeErrorEnvelope(body) + const message = Option.isSome(envelope) + ? envelope.value.error + : Option.getOrElse(Option.map(decodeErrorMessage(body), (value) => value.error), () => `Relay responded with HTTP ${response.status} for ${path}`) + return Effect.fail(new RelayRejected({ + message, + status: response.status, + path, + ...(Option.isSome(envelope) && envelope.value.code ? { code: envelope.value.code } : {}), + })) + } + return Schema.decodeUnknownEffect(schema)(body).pipe( + Effect.mapError((cause) => + new RelayDecodeFailed({ + message: `Relay response for ${path} did not match the expected shape: ${cause.message}`, + path, + cause, + }) + ), + ) + }), + ) + + const transportError = (path: string) => (cause: unknown) => + new RelayUnreachable({ + message: `OpenCode Browser relay is not reachable at ${endpoint}. Relay-backed CLI commands start it automatically; use \`opencode-browser serve\` only for foreground debugging.`, + endpoint, + path, + cause, + }) + + const getJson = (path: string, schema: Schema.ConstraintDecoder): Effect.Effect => + httpClient.get(new URL(path, endpoint)).pipe( + Effect.mapError(transportError(path)), + Effect.flatMap((response) => handleResponse(response, path, schema)), + ) + + const postJson = ( + path: string, + body: Record, + schema: Schema.ConstraintDecoder, + ): Effect.Effect => HttpClientRequest.post(new URL(path, endpoint)).pipe( + HttpClientRequest.bodyJson(body), + Effect.mapError((cause) => new RelayEncodeFailed({ + message: `Could not encode relay request for ${path}`, + path, + cause, + })), + Effect.flatMap((request) => httpClient.execute(request).pipe( + Effect.mapError(transportError(path)), + Effect.flatMap((response) => handleResponse(response, path, schema)), + )), + ) + + const recordingTargetBody = (target: { readonly sessionId?: string | undefined; readonly tabId?: number | undefined }): Record => ({ + ...(target.sessionId ? { sessionId: target.sessionId } : {}), + ...(target.tabId === undefined ? {} : { tabId: target.tabId }), + }) + + const recordingTargetQuery = (target: RecordingTargetRequest): string => { + const searchParams = new URLSearchParams() + if (target.sessionId) { + searchParams.set("sessionId", target.sessionId) + } + if (target.tabId !== undefined) { + searchParams.set("tabId", String(target.tabId)) + } + const text = searchParams.toString() + return text ? `?${text}` : "" + } + + return Service.of({ + endpoint, + version: getJson("/version", RelayVersion), + shutdown: (request) => postJson("/shutdown", { ...request }, RelayShutdownResponse), + extensionStatus: getJson("/extension/status", ExtensionStatus), + targets: getJson("/json/list", TargetSummaries), + sessions: getJson("/cli/sessions", SessionsContainer).pipe(Effect.map((container) => container.sessions)), + sessionNew: (id, options) => + postJson("/cli/session/new", { + ...(id ? { id } : {}), + ...(options?.readOnly ? { readOnly: true } : {}), + }, SessionContainer).pipe(Effect.map((container) => container.session)), + sessionEnsure: (id, options) => + postJson("/v1/sessions/ensure", { + id, + ...(options?.readOnly === undefined ? {} : { readOnly: options.readOnly }), + }, SessionContainer).pipe(Effect.map((container) => container.session)), + sessionReset: (id) => + postJson("/cli/session/reset", { id }, SessionContainer).pipe(Effect.map((container) => container.session)), + sessionAdopt: ({ sessionId, ...request }) => + postJson("/cli/session/adopt", { + ...request, + ...(sessionId ? { sessionId } : {}), + }, SessionAdoptResponse), + sessionDelete: (id) => postJson("/cli/session/delete", { id }, SessionDeleted), + execute: ({ sessionId, ...request }) => + postJson("/cli/execute", { + ...request, + ...(sessionId ? { sessionId } : {}), + }, ExecuteResponse), + authenticatedJson: (request) => postJson("/v1/authenticated-origin/json", { ...request }, AuthenticatedJsonOutcome), + networkStart: (request) => postJson("/network/start", { ...request }, NetworkStatusResponse), + networkStatus: (request) => postJson("/network/status", { ...request }, NetworkStatusResponse), + networkStop: (request) => postJson("/network/stop", { ...request }, NetworkStopResponse), + networkCancel: (request) => postJson("/network/cancel", { ...request }, NetworkCancelResponse), + authStatus: (request) => postJson("/auth/status", { ...request }, AuthProfileSummary), + authRefresh: (request) => postJson("/auth/refresh", { ...request }, NetworkStopResponse), + authRun: (request) => postJson("/auth/run", { ...request }, AuthRunResponse), + recordingStart: ({ sessionId, tabId, ...request }) => + postJson("/recording/start", { ...recordingTargetBody({ sessionId, tabId }), ...request }, RecordingStartResponse), + recordingStop: (target) => postJson("/recording/stop", recordingTargetBody(target), RecordingStopResponse), + recordingStatus: (target) => getJson(`/recording/status${recordingTargetQuery(target)}`, RecordingStatusResponse), + recordingCancel: (target) => postJson("/recording/cancel", recordingTargetBody(target), RecordingCancelResponse), + tabsCleanup: (idleMinutes) => postJson("/tabs/cleanup", idleMinutes === undefined ? {} : { idleMinutes }, TabsCleanupResponse), + flightRecorderStart: ({ sessionId, tabId, ...request }) => + postJson("/flight-recorder/start", { ...recordingTargetBody({ sessionId, tabId }), ...request }, FlightRecorderStatusResponse), + flightRecorderStatus: (target) => getJson(`/flight-recorder/status${recordingTargetQuery(target)}`, FlightRecorderStatusResponse), + flightRecorderSaveLast: ({ sessionId, tabId, ...request }) => + postJson("/flight-recorder/save-last", { ...recordingTargetBody({ sessionId, tabId }), ...request }, FlightRecorderSaveResponse), + flightRecorderCancel: (target) => postJson("/flight-recorder/cancel", recordingTargetBody(target), FlightRecorderCancelResponse), + }) +}) + +const layer: Layer.Layer = Layer.effect(Service, make()) + +/** RelayClient backed by `node:http` (avoiding undici's 5-minute headersTimeout on long handoffs/commands), for standalone CLI/MCP wiring. */ +export const layerFetch: Layer.Layer = layer.pipe(Layer.provide(NodeHttpClient.layerNodeHttp)) diff --git a/packages/browser-extension/cli/src/relay-helpers.ts b/packages/browser-extension/cli/src/relay-helpers.ts new file mode 100644 index 00000000000..ecc50985609 --- /dev/null +++ b/packages/browser-extension/cli/src/relay-helpers.ts @@ -0,0 +1,483 @@ +import http from "node:http" +import crypto from "node:crypto" +import { Effect, Option, Predicate, Schema } from "effect" +import { WebSocket, WebSocketServer } from "ws" +import type { ExecuteTargetSelection } from "./execute.ts" +import type { CdpEvent, CdpResponse, JsonObject, TargetInfo } from "./protocol.ts" +import { parseJsonObject } from "./protocol.ts" +import type { OpenCodeBrowserSession } from "./relay-types.ts" +import { RelayErrorCode } from "./relay-schema.ts" + +export const defaultHost = "127.0.0.1" +/** Not Browser Control's 19989, so an old relay can't hold OpenCode Browser's port. Keep in step with the extension. */ +export const defaultPort = 19988 +/** OpenCode Browser from the Chrome Web Store, and the unpacked build (its ID is pinned by the manifest key). */ +export const chromeWebStoreExtensionOrigin = "chrome-extension://mfnicocicmmlkpjnaffgihfjhdgjkdjg" +export const stableUnpackedExtensionOrigin = "chrome-extension://afeafocngkodbmaipcngoamamfmekgfo" + +export function chromeExtensionOriginForPath(extensionPath: string, platform: NodeJS.Platform = process.platform): string { + const normalizedPath = platform === "win32" && /^[a-z]:/.test(extensionPath) + ? extensionPath.charAt(0).toUpperCase() + extensionPath.slice(1) + : extensionPath + const pathBytes = platform === "win32" ? Buffer.from(normalizedPath, "utf16le") : normalizedPath + const digest = crypto.createHash("sha256").update(pathBytes).digest() + let extensionId = "" + for (const byte of digest.subarray(0, 16)) { + extensionId += String.fromCharCode(97 + (byte >> 4), 97 + (byte & 0x0f)) + } + return `chrome-extension://${extensionId}` +} + +const chromeExtensionOriginPattern = /^chrome-extension:\/\/[a-p]+$/ + +/** + * Parses the operator-supplied `OPENCODE_BROWSER_EXTENSION_ORIGINS` value into a + * de-duplicated list of `chrome-extension://` origins to allowlist in + * addition to the built-ins. Entries are separated by commas or whitespace; + * anything that is not a bare `chrome-extension://` origin (web origins, paths, + * scheme-less ids) is dropped so a malformed value can never widen the origin + * check to a non-extension origin. Used for same-host unpacked installs where + * the path-derived id cannot match the relay's own bundled path. + */ +export function parseAdditionalExtensionOrigins(raw: string | undefined): string[] { + if (!raw) { + return [] + } + const seen = new Set() + const origins: string[] = [] + for (const token of raw.split(/[\s,]+/)) { + const value = token.trim() + if (!value || !chromeExtensionOriginPattern.test(value) || seen.has(value)) { + continue + } + seen.add(value) + origins.push(value) + } + return origins +} + +const maxCliBodyBytes = 1_000_000 + +export class HttpRouteError extends Schema.TaggedError()( + "HttpApi.HttpRouteError", + { message: Schema.String, status: Schema.Number, code: RelayErrorCode }, +) {} + +export function formatHostForUrl(host: string): string { + if (host.includes(":") && !host.startsWith("[")) { + return `[${host}]` + } + return host +} + +export function validateHostHeader(options: { + readonly hostHeader: string | undefined + readonly host: string + readonly port: number +}): string | undefined { + const parsed = parseHostHeader(options.hostHeader) + if (!parsed) { + return "Invalid Host header" + } + if (parsed.port !== undefined && parsed.port !== options.port) { + return "Invalid Host header port" + } + const allowedHosts = new Set(["localhost", "127.0.0.1", "::1", normalizeHostname(options.host)]) + if (!allowedHosts.has(parsed.hostname)) { + return "Invalid Host header" + } + return undefined +} + +export function validateBrowserFetchSite(request: http.IncomingMessage): string | undefined { + const secFetchSite = request.headers["sec-fetch-site"] + const value = Array.isArray(secFetchSite) ? secFetchSite[0] : secFetchSite + if (!value || value === "same-origin" || value === "none") { + return undefined + } + return "Cross-origin browser requests are not allowed" +} + +export function validateWebSocketOrigin(options: { + readonly origin: string | undefined + readonly additionalChromeExtensionOrigins?: ReadonlySet + readonly allowAnyChromeExtension?: boolean + readonly requireChromeExtension?: boolean +}): string | undefined { + if (!options.origin) { + return options.requireChromeExtension ? "Extension WebSocket origin is required" : undefined + } + if ( + options.origin === chromeWebStoreExtensionOrigin + || options.origin === stableUnpackedExtensionOrigin + || options.additionalChromeExtensionOrigins?.has(options.origin) + ) { + return undefined + } + if (options.allowAnyChromeExtension && options.origin.startsWith("chrome-extension://")) { + return undefined + } + if (options.requireChromeExtension) { + return "Extension WebSocket origin is not allowed" + } + return "WebSocket origin is not allowed" +} + +function normalizeHostname(host: string): string { + const value = host.trim().toLowerCase() + if (value.startsWith("[") && value.endsWith("]")) { + return value.slice(1, -1) + } + return value +} + +function parseHostHeader(hostHeader: string | undefined): { readonly hostname: string; readonly port?: number } | undefined { + const value = hostHeader?.trim().toLowerCase() + if (!value) { + return undefined + } + if (value.startsWith("[")) { + const closingBracket = value.indexOf("]") + if (closingBracket === -1) { + return undefined + } + const hostname = value.slice(1, closingBracket) + const rest = value.slice(closingBracket + 1) + if (!hostname) { + return undefined + } + if (!rest) { + return { hostname } + } + if (!rest.startsWith(":")) { + return undefined + } + const port = parsePort(rest.slice(1)) + return port === undefined ? undefined : { hostname, port } + } + if (value === "::1") { + return { hostname: "::1" } + } + const colonCount = value.split(":").length - 1 + if (colonCount > 1) { + return undefined + } + if (colonCount === 0) { + return { hostname: value } + } + const [hostname, portText] = value.split(":") + if (!hostname || portText === undefined) { + return undefined + } + const port = parsePort(portText) + return port === undefined ? undefined : { hostname, port } +} + +function parsePort(value: string): number | undefined { + if (!/^\d+$/.test(value)) { + return undefined + } + const port = Number(value) + if (!Number.isInteger(port) || port < 1 || port > 65_535) { + return undefined + } + return port +} + +export function listenHttpServer(options: { + readonly server: http.Server + readonly host: string + readonly port: number +}): Effect.Effect { + return Effect.callback((resume) => { + const onError = (error: Error) => { + resume(Effect.fail(error)) + } + options.server.once("error", onError) + options.server.listen(options.port, options.host, () => { + options.server.off("error", onError) + resume(Effect.void) + }) + return Effect.sync(() => { + options.server.off("error", onError) + }) + }) +} + +export function closeHttpServer(server: http.Server): Effect.Effect { + if (!server.listening) { + return Effect.void + } + return Effect.callback((resume) => { + server.close((error?: Error) => { + if (error) { + resume(Effect.fail(new Error("close http server", { cause: error }))) + return + } + resume(Effect.void) + }) + return Effect.void + }) +} + +export function closeWebSocketServer(server: WebSocketServer): Effect.Effect { + return Effect.callback((resume) => { + server.close((error?: Error) => { + const nodeError = error as NodeJS.ErrnoException | undefined + if (nodeError?.code === "ERR_SERVER_NOT_RUNNING") { + resume(Effect.void) + return + } + if (error) { + resume(Effect.fail(new Error("close websocket server", { cause: error }))) + return + } + resume(Effect.void) + }) + return Effect.void + }) +} + +export function logCloseError(message: string) { + return (effect: Effect.Effect): Effect.Effect => { + return Effect.catch(effect, (error) => { + return Effect.sync(() => { + console.error(message, error) + }) + }) + } +} + +export function sendJson(response: http.ServerResponse, value: unknown, status = 200): void { + response.writeHead(status, { "content-type": "application/json" }) + response.end(JSON.stringify(value)) +} + +export function readJsonBody(request: http.IncomingMessage): Effect.Effect { + const contentType = request.headers["content-type"] + const contentTypeValue = Array.isArray(contentType) ? contentType[0] : contentType + if (!contentTypeValue?.toLowerCase().includes("application/json")) { + return Effect.fail(new HttpRouteError({ message: "Content-Type must be application/json", status: 415, code: "invalid-request" })) + } + return Effect.callback((resume) => { + const chunks: Buffer[] = [] + let totalBytes = 0 + let completed = false + const onData = (chunk: Buffer) => { + if (completed) { + return + } + totalBytes += chunk.byteLength + if (totalBytes > maxCliBodyBytes) { + completed = true + request.destroy(new Error(`Request body exceeds ${maxCliBodyBytes} bytes`)) + resume(Effect.fail(new HttpRouteError({ message: `Request body exceeds ${maxCliBodyBytes} bytes`, status: 413, code: "invalid-request" }))) + return + } + chunks.push(chunk) + } + const onError = (error: Error) => { + if (completed) { + return + } + completed = true + resume(Effect.fail(new Error("read request body", { cause: error }))) + } + const onAbort = () => { + if (completed) { + return + } + completed = true + resume(Effect.fail(new Error("request body aborted"))) + } + const onClose = () => { + if (completed || request.complete) { + return + } + completed = true + resume(Effect.fail(new Error("request closed before body completed"))) + } + const onEnd = () => { + if (completed) { + return + } + completed = true + const text = Buffer.concat(chunks).toString("utf8") + if (!text.trim()) { + resume(Effect.succeed({})) + return + } + try { + resume(Effect.succeed(parseJsonObject(text))) + } catch (error) { + resume(Effect.fail(new HttpRouteError({ message: "Invalid JSON body", status: 400, code: "invalid-request" }))) + } + } + request.on("data", onData) + request.on("error", onError) + request.on("aborted", onAbort) + request.on("close", onClose) + request.on("end", onEnd) + return Effect.sync(() => { + request.off("data", onData) + request.off("error", onError) + request.off("aborted", onAbort) + request.off("close", onClose) + request.off("end", onEnd) + }) + }) +} + +const RawTargetSelection = Schema.Struct({ + urlIncludes: Schema.optionalKey(Schema.String), + index: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))), +}) +const decodeRawTargetSelection = Schema.decodeUnknownOption(RawTargetSelection) + +const RawTargetInfo = Schema.Struct({ + targetId: Schema.String, + type: Schema.Literals(["page", "iframe", "worker"]), + title: Schema.optionalKey(Schema.String), + url: Schema.String, + canAccessOpener: Schema.optionalKey(Schema.Boolean), + browserContextId: Schema.optionalKey(Schema.String), + openerId: Schema.optionalKey(Schema.String), + parentFrameId: Schema.optionalKey(Schema.String), +}) +const decodeRawTargetInfo = Schema.decodeUnknownOption(RawTargetInfo) + +export function optionalSessionId(value: JsonObject[string] | undefined): string | undefined { + if (!Predicate.isString(value) || !value.trim()) { + return undefined + } + const id = value.trim() + if (!isValidSessionId(id)) { + throw new HttpRouteError({ + message: "Session ids must use lowercase letters, numbers, and dashes, and be at most 63 characters", + status: 400, + code: "invalid-request", + }) + } + return id +} + +export function isValidSessionId(id: string): boolean { + if (id.length < 1 || id.length > 63 || id === "." || id === "..") return false + if (/[A-Z/\\:\0-\x1f\x7f]/.test(id)) return false + return /^(?:[\p{Extended_Pictographic}\u200d\ufe0f]+\s*)?[a-z0-9][a-z0-9\p{Extended_Pictographic}\u200d\ufe0f\s_-]*$/u.test(id) +} + +export function requiredSessionId(value: JsonObject[string] | undefined): string { + const id = optionalSessionId(value) + if (!id) { + throw new HttpRouteError({ message: "sessionId is required", status: 400, code: "invalid-request" }) + } + return id +} + +export function parseTargetSelection(value: JsonObject[string] | undefined): ExecuteTargetSelection | undefined { + if (value === undefined) { + return undefined + } + if (!getObject(value)) { + throw new HttpRouteError({ message: "targetSelection must be an object", status: 400, code: "invalid-request" }) + } + const decoded = decodeRawTargetSelection(value) + if (Option.isNone(decoded)) { + throw new HttpRouteError({ message: "targetSelection.index must be a non-negative integer", status: 400, code: "invalid-request" }) + } + const urlIncludes = decoded.value.urlIncludes ? decoded.value.urlIncludes : undefined + const index = decoded.value.index + if (urlIncludes && index !== undefined) { + throw new HttpRouteError({ message: "Use only one target selector", status: 400, code: "invalid-request" }) + } + return { + ...(urlIncludes ? { urlIncludes } : {}), + ...(index !== undefined ? { index } : {}), + } +} + +export function generateSessionId(existing: ReadonlyMap): string { + const adjectives = ["amber", "brisk", "calm", "clever", "cosmic", "gentle", "lucky", "quiet", "rapid", "tidy"] + const nouns = ["badger", "comet", "falcon", "otter", "panda", "raven", "sparrow", "tiger", "walrus", "wombat"] + for (let attempt = 0; attempt < 100; attempt++) { + const adjective = adjectives[Math.floor(Math.random() * adjectives.length)] ?? "calm" + const noun = nouns[Math.floor(Math.random() * nouns.length)] ?? "otter" + const suffix = String(Math.floor(Math.random() * 1000)).padStart(3, "0") + const id = `${adjective}-${noun}-${suffix}` + if (!existing.has(id)) { + return id + } + } + return `session-${Date.now().toString(36)}` +} + +export function sendCdpResponse(socket: WebSocket, response: CdpResponse): void { + socket.send(JSON.stringify(response)) +} + +export function sendCdpEvent(socket: Pick, event: CdpEvent): void { + socket.send(JSON.stringify(event)) +} + +export function getObject(value: unknown): JsonObject | undefined { + return Predicate.isObject(value) ? (value as JsonObject) : undefined +} + +export function getString(object: JsonObject | undefined, key: string): string | undefined { + const value = object?.[key] + return Predicate.isString(value) ? value : undefined +} + +export function getNumber(object: JsonObject | undefined, key: string): number | undefined { + const value = object?.[key] + return Predicate.isNumber(value) ? value : undefined +} + +export function getIdText(object: JsonObject | undefined, key: string): string | undefined { + const value = object?.[key] + return Predicate.isNumber(value) || Predicate.isString(value) ? String(value) : undefined +} + +export function headerValue(value: string | string[] | undefined): string | undefined { + if (!Predicate.isString(value) || !value) return undefined + try { + return decodeURIComponent(value) + } catch { + return value + } +} + +export function getTargetInfo(value: unknown): TargetInfo | undefined { + return Option.match(decodeRawTargetInfo(value), { + onNone: () => undefined, + onSome: (info) => ({ + targetId: info.targetId, + type: info.type, + title: info.title ?? info.url, + url: info.url, + attached: true, + canAccessOpener: info.canAccessOpener ?? false, + ...(info.browserContextId === undefined ? {} : { browserContextId: info.browserContextId }), + ...(info.openerId === undefined ? {} : { openerId: info.openerId }), + ...(info.parentFrameId === undefined ? {} : { parentFrameId: info.parentFrameId }), + }), + }) +} + +export function isRestrictedTarget(targetInfo: TargetInfo): boolean { + if (targetInfo.type !== "page" && targetInfo.type !== "iframe" && targetInfo.type !== "worker") { + return true + } + return isRestrictedUrl(targetInfo.url) +} + +const restrictedUrlPrefixes = ["chrome://", "chrome-extension://", "chrome-untrusted://", "devtools://", "edge://", "brave://"] + +/** Browser-internal or other-extension documents that `chrome.debugger` refuses to expose. */ +export function isRestrictedUrl(url: string | undefined): boolean { + if (!url) { + return false + } + return restrictedUrlPrefixes.some((prefix) => url.startsWith(prefix)) +} diff --git a/packages/browser-extension/cli/src/relay-lifecycle-log.ts b/packages/browser-extension/cli/src/relay-lifecycle-log.ts new file mode 100644 index 00000000000..8726f0b2b29 --- /dev/null +++ b/packages/browser-extension/cli/src/relay-lifecycle-log.ts @@ -0,0 +1,52 @@ +import fs from "node:fs" +import path from "node:path" +import { Schema } from "effect" +import { isUnsupportedDirectorySyncError } from "./fs-durability.ts" +import { RelayShutdownRequest } from "./relay-schema.ts" + +const requestFields = { + instanceId: RelayShutdownRequest.fields.instanceId, + requestId: RelayShutdownRequest.fields.requestId, + client: RelayShutdownRequest.fields.client, +} + +export const RelayLifecycleEvent = Schema.TaggedUnion({ + Requested: requestFields, + Cancelled: requestFields, + Stopping: requestFields, + Closed: { instanceId: RelayShutdownRequest.fields.instanceId }, + Ready: { + instanceId: RelayShutdownRequest.fields.instanceId, + buildId: RelayShutdownRequest.fields.client.fields.buildId, + restartRequestId: Schema.optionalKey(RelayShutdownRequest.fields.requestId), + }, +}) +export type RelayLifecycleEvent = typeof RelayLifecycleEvent.Type + +// Lifecycle transitions are rare and must be recorded before stopping the relay. +// Synchronous bounded writes cannot finish out of order after request cancellation. +export function appendRelayLifecycleEvent(filePath: string, event: RelayLifecycleEvent): void { + const directory = path.dirname(filePath) + fs.mkdirSync(directory, { recursive: true, mode: 0o700 }) + fs.chmodSync(directory, 0o700) + const entry = `${JSON.stringify({ ...Schema.encodeSync(RelayLifecycleEvent)(event), timestamp: new Date().toISOString() })}\n` + const file = fs.openSync(filePath, "a+", 0o600) + try { + fs.fchmodSync(file, 0o600) + if (fs.fstatSync(file).size + Buffer.byteLength(entry) > 256_000) fs.ftruncateSync(file, 0) + fs.writeFileSync(file, entry) + fs.fsyncSync(file) + } finally { + fs.closeSync(file) + } + const parent = fs.openSync(directory, "r") + try { + try { + fs.fsyncSync(parent) + } catch (error) { + if (!isUnsupportedDirectorySyncError(error)) throw error + } + } finally { + fs.closeSync(parent) + } +} diff --git a/packages/browser-extension/cli/src/relay-lifecycle.ts b/packages/browser-extension/cli/src/relay-lifecycle.ts new file mode 100644 index 00000000000..da8b37e853d --- /dev/null +++ b/packages/browser-extension/cli/src/relay-lifecycle.ts @@ -0,0 +1,337 @@ +import { Config, Effect, Result, Schedule, Schema } from "effect" +import { spawn } from "node:child_process" +import crypto from "node:crypto" +import path from "node:path" +import process from "node:process" +import { fileURLToPath } from "node:url" +import { extensionReconnectAlarmPeriodMs } from "./protocol.ts" +import * as RelayClient from "./relay-client.ts" +import { RelayShutdownRequest, type ExtensionStatus, type RelayVersion } from "./relay-schema.ts" +import { opencodeBrowserBuildId } from "./version.ts" + +// From source the CLI entry is main.ts next to this file; the published bundle is a single file, so it is this file. +const loadedCliEntrypoint = fileURLToPath(import.meta.url.endsWith(".ts") ? new URL("./main.ts", import.meta.url) : import.meta.url) +const clientInstanceId = crypto.randomUUID() + +export type RelayReadiness = { + readonly version: RelayVersion + readonly started: boolean + readonly buildProblem?: string + readonly waitForReconnect?: true +} + +export type EnsureRelayOptions = { + readonly relay: RelayClient.Interface + readonly start?: Effect.Effect + readonly buildId?: string + readonly retryTimes?: number + readonly retryDelayMs?: number +} + +export function shouldWaitForExtensionReconnect(readiness: RelayReadiness): boolean { + return readiness.started || readiness.waitForReconnect === true +} + +class RelayStillRunning extends Error {} + +class RelayStartFailed extends Schema.TaggedError()( + "RelayLifecycle.RelayStartFailed", + { + message: Schema.String, + endpoint: Schema.String, + cause: Schema.Defect(), + }, +) {} + +export class ExtensionDisconnected extends Schema.TaggedError()( + "RelayLifecycle.ExtensionDisconnected", + { message: Schema.String }, +) {} + +export class ExtensionProtocolIncompatible extends Schema.TaggedError()( + "RelayLifecycle.ExtensionProtocolIncompatible", + { + message: Schema.String, + protocolVersion: Schema.NullOr(Schema.Number), + }, +) {} + +export function relayBuildProblem(version: RelayVersion, buildId = opencodeBrowserBuildId): string | undefined { + if (!version.buildId) { + return `Running relay does not report a build id; use \`opencode-browser relay restart\` for upgrade guidance (${buildId}).` + } + if (version.buildId !== buildId) { + if (isNewerBuild(version.buildId, buildId)) { + return `Running relay build ${version.buildId} is newer than CLI build ${buildId}; refresh or restart this CLI or MCP client. Only use \`opencode-browser relay restart\` from the current installation.` + } + return `Running relay build ${version.buildId} does not match CLI build ${buildId}; run \`opencode-browser relay restart\` explicitly. This leaves browser tabs open but resets in-memory JavaScript state.` + } + return undefined +} + +export const ensureRelay = Effect.fn("RelayLifecycle.ensureRelay")(function* (options: EnsureRelayOptions) { + const buildId = options.buildId ?? opencodeBrowserBuildId + const probe = options.relay.version + const initial = yield* Effect.result(probe) + if (Result.isSuccess(initial)) { + const buildProblem = relayBuildProblem(initial.success, buildId) + return { + version: initial.success, + started: false, + ...(buildProblem ? { buildProblem } : {}), + } satisfies RelayReadiness + } + const relayWasAbsent = isRelayUnreachable(initial.failure) + if (!relayWasAbsent && !isRelayStarting(initial.failure)) { + return yield* initial.failure + } + + if (relayWasAbsent) { + const autoStart = yield* Config.Boolean("OPENCODE_BROWSER_AUTOSTART").pipe( + Config.withDefault(true), + Effect.mapError((cause) => new Error("Invalid OPENCODE_BROWSER_AUTOSTART configuration", { cause })), + ) + if (!autoStart) { + return yield* Effect.fail(new Error(`Automatic relay startup is disabled; no relay is available at ${options.relay.endpoint}`)) + } + yield* options.start ?? startManagedRelay() + } + const version = yield* waitForRelayReady(options) + const buildProblem = relayBuildProblem(version, buildId) + return { version, started: relayWasAbsent, ...(buildProblem ? { buildProblem } : {}) } satisfies RelayReadiness +}) + +function waitForRelayReady(options: EnsureRelayOptions): Effect.Effect { + return options.relay.version.pipe( + Effect.retry({ + times: options.retryTimes ?? 200, + schedule: Schedule.spaced(options.retryDelayMs ?? 50), + while: isRelayStartingOrUnreachable, + }), + Effect.mapError((error) => isRelayStartingOrUnreachable(error) + ? new RelayStartFailed({ + message: `OpenCode Browser relay did not start at ${options.relay.endpoint}`, + endpoint: options.relay.endpoint, + cause: error, + }) + : error), + ) +} + +export const restartRelay = Effect.fn("RelayLifecycle.restartRelay")(function* (options: EnsureRelayOptions & { + readonly clientKind?: RelayShutdownRequest["client"]["kind"] +}) { + const buildId = options.buildId ?? opencodeBrowserBuildId + const initial = yield* Effect.result(options.relay.version) + let original: RelayVersion | undefined + let replacement: RelayVersion | undefined + let restartRequestId: string | undefined + if (Result.isSuccess(initial)) { + original = initial.success + } else if (isRelayStarting(initial.failure)) { + original = yield* waitForRelayReady(options) + } else if (!isRelayUnreachable(initial.failure)) { + return yield* initial.failure + } + + if (original) { + if (original.managed !== true || !original.instanceId) { + return yield* Effect.fail(new Error("Cannot restart a foreground or unidentified relay. Stop it manually, then run `opencode-browser relay restart`.")) + } + if (original.shutdownProtocol !== 2) { + return yield* Effect.fail(new Error("This legacy relay does not support safe shutdown protocol 2. Stop it manually once, then run `opencode-browser relay restart` to upgrade; no shutdown request was sent.")) + } + if (!Number.isFinite(Date.parse(buildId)) || !original.buildId || !Number.isFinite(Date.parse(original.buildId))) { + return yield* Effect.fail(new Error("Cannot explicitly replace a source or unorderable relay build. Stop it manually, then launch the intended build.")) + } + if (isNewerBuild(original.buildId, buildId)) { + return yield* Effect.fail(new Error(`Refusing to downgrade relay build ${original.buildId} to ${buildId}; refresh or restart this CLI or MCP client.`)) + } + + const confirmed = yield* Effect.result(options.relay.version) + if (Result.isFailure(confirmed)) { + if (!isRelayUnreachable(confirmed.failure)) return yield* confirmed.failure + } else if (!isSameRelayInstance(original, confirmed.success)) { + replacement = confirmed.success + } else { + if (confirmed.success.managed !== true || confirmed.success.shutdownProtocol !== 2 || confirmed.success.buildId !== original.buildId) { + return yield* Effect.fail(new Error("Relay identity metadata changed during restart; no shutdown request was sent.")) + } + const request = yield* RelayShutdownRequest.makeEffect({ + instanceId: original.instanceId, + requestId: crypto.randomUUID(), + reason: "explicit-restart", + client: { kind: options.clientKind ?? "sdk", instanceId: clientInstanceId, buildId }, + }) + const shutdown = yield* Effect.result(options.relay.shutdown(request)) + if (Result.isSuccess(shutdown)) restartRequestId = request.requestId + else if (!isRelayUnreachable(shutdown.failure) && !isRelayInstanceChanged(shutdown.failure)) { + return yield* shutdown.failure + } + replacement = yield* waitForRelayExitOrReplacement({ ...options, version: original }) + } + } + + const started = replacement === undefined + if (started) { + yield* options.start ?? startManagedRelay(undefined, undefined, undefined, { ...(restartRequestId ? { restartRequestId } : {}) }) + replacement = yield* waitForRelayReady(options) + } + if (!replacement || !replacement.instanceId || replacement.managed !== true || (original && isSameRelayInstance(original, replacement))) { + return yield* Effect.fail(new Error("Relay restart did not produce a new managed instance; no further shutdown was attempted.")) + } + const buildProblem = relayBuildProblem(replacement, buildId) + if (buildProblem) return yield* Effect.fail(new Error(`${buildProblem} A competing relay was left untouched.`)) + return { version: replacement, started, waitForReconnect: true } satisfies RelayReadiness +}) + +function waitForRelayExitOrReplacement(options: { + readonly relay: RelayClient.Interface + readonly version: RelayVersion + readonly retryTimes?: number + readonly retryDelayMs?: number +}): Effect.Effect { + return options.relay.version.pipe( + Effect.flatMap((version) => isSameRelayInstance(options.version, version) + ? Effect.fail(new RelayStillRunning("OpenCode Browser relay is still draining; no replacement was started")) + : Effect.succeed(version)), + Effect.catch((error) => isRelayUnreachable(error) ? Effect.succeed(undefined) : Effect.fail(error)), + Effect.retry({ + times: options.retryTimes ?? 200, + schedule: Schedule.spaced(options.retryDelayMs ?? 50), + while: (error) => error instanceof RelayStillRunning || isRelayStarting(error), + }), + ) +} + +function isSameRelayInstance(left: RelayVersion, right: RelayVersion): boolean { + return left.instanceId !== undefined && left.instanceId === right.instanceId +} + +function isNewerBuild(current: string, running: string | undefined): boolean { + if (!running) return false + const currentTime = Date.parse(current) + const runningTime = Date.parse(running) + return Number.isFinite(currentTime) && Number.isFinite(runningTime) && currentTime > runningTime +} + +function isRelayInstanceChanged(error: unknown): boolean { + return error instanceof RelayClient.RelayRejected && error.status === 409 && error.code === "invalid-request" +} + +// Cover one full reconnect alarm period plus margin for the worker to connect. +export const extensionReconnectWaitMs = extensionReconnectAlarmPeriodMs + 5_000 +const extensionReconnectProbeMs = 200 + +export const ensureExtensionConnected = Effect.fn("RelayLifecycle.ensureExtensionConnected")(function* (options: { + readonly relay: RelayClient.Interface + readonly waitForReconnect?: boolean + readonly retryTimes?: number + readonly retryDelayMs?: number + /** Runs once, when the first probe finds the extension disconnected. */ + readonly onWait?: Effect.Effect +}) { + const check = options.relay.extensionStatus.pipe(Effect.flatMap((status): Effect.Effect< + ExtensionStatus, + ExtensionProtocolIncompatible | ExtensionDisconnected + > => { + if (status.protocolCompatible === false) { + return Effect.fail(new ExtensionProtocolIncompatible({ + message: `OpenCode Browser extension protocol ${status.protocolVersion ?? "unknown"} is incompatible with this relay.`, + protocolVersion: status.protocolVersion ?? null, + })) + } + return status.connected + ? Effect.succeed(status) + : Effect.fail(new ExtensionDisconnected({ + message: "OpenCode Browser extension is not connected. Open the browser with OpenCode Browser installed (`npx opencode-browser-cli install`); it reconnects automatically after relay or browser startup.", + })) + })) + if (!options.waitForReconnect) { + return yield* check + } + let waitAnnounced = false + return yield* check.pipe( + Effect.tapError((error) => { + if (waitAnnounced || !options.onWait || !(error instanceof ExtensionDisconnected)) return Effect.void + waitAnnounced = true + return options.onWait + }), + Effect.retry({ + times: options.retryTimes ?? Math.ceil(extensionReconnectWaitMs / extensionReconnectProbeMs), + schedule: Schedule.spaced(options.retryDelayMs ?? extensionReconnectProbeMs), + while: (error) => error instanceof ExtensionDisconnected || isRelayStartingOrUnreachable(error), + }), + ) +}) + +export function stoppedRelayStatus(endpoint: string): { + readonly endpoint: string + readonly relay: { readonly running: false } + readonly extension: null + readonly sessions: readonly [] + readonly targets: readonly [] +} { + return { endpoint, relay: { running: false }, extension: null, sessions: [], targets: [] } +} + +export function statusCollections(status: ExtensionStatus): { + readonly sessions: NonNullable + readonly targets: NonNullable +} | undefined { + return status.sessions && status.targets ? { sessions: status.sessions, targets: status.targets } : undefined +} + +export function startManagedRelay( + entrypoint = loadedCliEntrypoint, + executable = process.execPath, + execArgv: readonly string[] = process.execArgv, + options: { readonly restartRequestId?: string } = {}, +): Effect.Effect { + return Effect.try({ + try: () => { + if (!entrypoint) { + throw new Error("Cannot locate the opencode-browser CLI entrypoint") + } + const launch = managedRelayLaunch(entrypoint, executable, execArgv) + const { OPENCODE_BROWSER_RESTART_REQUEST_ID: _inheritedRestartRequestId, ...env } = process.env + const child = spawn(launch.executable, launch.args, { + detached: true, + stdio: "ignore", + env: { ...env, OPENCODE_BROWSER_MANAGED_RELAY: "1", ...(options.restartRequestId ? { OPENCODE_BROWSER_RESTART_REQUEST_ID: options.restartRequestId } : {}) }, + }) + child.unref() + }, + catch: (cause) => cause instanceof Error ? cause : new Error("Failed to start OpenCode Browser relay", { cause }), + }) +} + +export function managedRelayLaunch( + entrypoint = loadedCliEntrypoint, + executable = process.execPath, + execArgv: readonly string[] = process.execArgv, +): { readonly executable: string; readonly args: string[] } { + return { + executable, + args: [...execArgv, managedRelayEntrypoint(entrypoint), "serve"], + } +} + +export function managedRelayEntrypoint(entrypoint: string): string { + const name = path.basename(entrypoint) + if (name === "mcp-main.ts" || name === "index.ts" || name === "opencode-browser-client.ts" || name === "cli.ts") + return path.join(path.dirname(entrypoint), "main.ts") + return entrypoint +} + +function isRelayUnreachable(error: unknown): error is RelayClient.RelayUnreachable { + return error instanceof RelayClient.RelayUnreachable +} + +function isRelayStarting(error: unknown): error is RelayClient.RelayRejected { + return error instanceof RelayClient.RelayRejected && error.code === "relay-starting" +} + +function isRelayStartingOrUnreachable(error: unknown): error is RelayClient.RelayRejected | RelayClient.RelayUnreachable { + return isRelayStarting(error) || isRelayUnreachable(error) +} diff --git a/packages/browser-extension/cli/src/relay-log.ts b/packages/browser-extension/cli/src/relay-log.ts new file mode 100644 index 00000000000..e7d6b2d448d --- /dev/null +++ b/packages/browser-extension/cli/src/relay-log.ts @@ -0,0 +1,41 @@ +import { dataRoot } from "./paths.ts" +import fs from "node:fs" +import os from "node:os" +import path from "node:path" + +const maxLogBytes = 1_000_000 +const maxEntryCharacters = 64_000 + +export function managedRelayLogPath(home = os.homedir()): string { + return path.join(dataRoot(home), "logs", "relay.log") +} + +export function appendManagedRelayProcessLog(message: string, home = os.homedir()): void { + try { + const logPath = managedRelayLogPath(home) + const directory = path.dirname(logPath) + fs.mkdirSync(directory, { recursive: true, mode: 0o700 }) + fs.chmodSync(directory, 0o700) + const entry = `${new Date().toISOString()} ${message.slice(0, maxEntryCharacters)}\n` + const stat = fs.statSync(logPath, { throwIfNoEntry: false }) + // Keep the previous file instead of truncating, so a rotation never drops the lines before a failure. + if (stat && stat.size + Buffer.byteLength(entry) > maxLogBytes) fs.renameSync(logPath, `${logPath}.1`) + fs.appendFileSync(logPath, entry, { encoding: "utf8", mode: 0o600 }) + fs.chmodSync(logPath, 0o600) + } catch { + // Process-fault logging must never hide or replace the original fault. + } +} + +/** + * The relay's operational log: one line per lifecycle event (start, extension connects and disconnects, HTTP + * requests with status and duration, faults), always on, in /logs/relay.log. Per-CDP-message + * tracing stays behind OPENCODE_BROWSER_DEBUG. + */ +export function relayLog(event: string, fields: Record = {}): void { + const detail = Object.entries(fields) + .filter(([, value]) => value !== undefined) + .map(([key, value]) => `${key}=${typeof value === "string" && !/\s/.test(value) ? value : JSON.stringify(value)}`) + .join(" ") + appendManagedRelayProcessLog(detail ? `${event} ${detail}` : event) +} diff --git a/packages/browser-extension/cli/src/relay-schema.ts b/packages/browser-extension/cli/src/relay-schema.ts new file mode 100644 index 00000000000..e56688858a3 --- /dev/null +++ b/packages/browser-extension/cli/src/relay-schema.ts @@ -0,0 +1,569 @@ +import { Schema } from "effect" + +/** + * Shared wire contract for the relay HTTP API. + * + * These schemas are the single source of truth for the JSON shapes exchanged + * between the relay's HTTP responders (`src/http-api.ts`) and its clients + * (`src/relay-client.ts`, used by the CLI and the MCP server). Server-side + * producers derive their types from here so the contract cannot drift. + */ + +export const SessionSummary = Schema.Struct({ + id: Schema.String, + createdAt: Schema.String, + updatedAt: Schema.String, + connected: Schema.Boolean, + pageUrl: Schema.NullOr(Schema.String), + stateKeys: Schema.Array(Schema.String), + readOnly: Schema.optionalKey(Schema.Boolean), +}) + +export interface SessionSummary extends Schema.Schema.Type {} + +export const ExecuteSessionSummary = SessionSummary.pipe(Schema.fieldsAssign({ + created: Schema.optionalKey(Schema.Boolean), +})) + +export interface ExecuteSessionSummary extends Schema.Schema.Type {} + +export const SessionContainer = Schema.Struct({ + session: SessionSummary, +}) + +export interface SessionContainer extends Schema.Schema.Type {} + +export const SessionsContainer = Schema.Struct({ + sessions: Schema.Array(SessionSummary), +}) + +export interface SessionsContainer extends Schema.Schema.Type {} + +export const SessionDeleted = Schema.Struct({ + deleted: Schema.Boolean, + id: Schema.String, +}) + +export interface SessionDeleted extends Schema.Schema.Type {} + +export const TargetSelection = Schema.Struct({ + urlIncludes: Schema.optionalKey(Schema.NonEmptyString), + index: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))), +}).check(Schema.makeFilter((selection) => { + const hasUrl = selection.urlIncludes !== undefined + const hasIndex = selection.index !== undefined + return hasUrl !== hasIndex ? undefined : "targetSelection must contain exactly one of urlIncludes or index" +})) + +export interface TargetSelection extends Schema.Schema.Type {} + +export const ExecuteRequest = Schema.Struct({ + sessionId: Schema.optionalKey(Schema.String), + code: Schema.String, + createIfMissing: Schema.Boolean, + targetSelection: Schema.optionalKey(TargetSelection), +}) + +export interface ExecuteRequest extends Schema.Schema.Type {} + +export const SessionAdoptRequest = Schema.Struct({ + sessionId: Schema.optionalKey(Schema.String), + createIfMissing: Schema.Boolean, + targetSelection: Schema.optionalKey(TargetSelection), + /** The Chrome tab id of an attached tab (the tab= value in status). */ + tabId: Schema.optionalKey(Schema.Int), +}) + +export interface SessionAdoptRequest extends Schema.Schema.Type {} + +export const SessionNewRequest = Schema.Struct({ + id: Schema.optionalKey(Schema.String), + readOnly: Schema.optionalKey(Schema.Boolean), +}) + +export interface SessionNewRequest extends Schema.Schema.Type {} + +export const SessionEnsureRequest = Schema.Struct({ + id: Schema.NonEmptyString, + readOnly: Schema.optionalKey(Schema.Boolean), +}) + +export interface SessionEnsureRequest extends Schema.Schema.Type {} + +export const SessionIdRequest = Schema.Struct({ + id: Schema.String, +}) + +export interface SessionIdRequest extends Schema.Schema.Type {} + +export const SessionAdoptResponse = Schema.Struct({ + session: ExecuteSessionSummary, + adoptedUrl: Schema.String, + adoptedTargetId: Schema.String, +}) + +export interface SessionAdoptResponse extends Schema.Schema.Type {} + +const ExecuteLogLocation = Schema.Struct({ + url: Schema.String, + lineNumber: Schema.Number, + columnNumber: Schema.Number, +}) + +interface ExecuteLogLocation extends Schema.Schema.Type {} + +export const ExecuteLogEntry = Schema.Struct({ + source: Schema.Literals(["script", "page"]), + type: Schema.String, + text: Schema.String, + location: Schema.optionalKey(ExecuteLogLocation), + repeatCount: Schema.optionalKey(Schema.Number), +}) + +export interface ExecuteLogEntry extends Schema.Schema.Type {} + +export const ExecuteLogSummary = Schema.Struct({ + totalCount: Schema.Number, + returnedCount: Schema.Number, + repeatedCount: Schema.Number, + omittedCount: Schema.Number, +}) + +export interface ExecuteLogSummary extends Schema.Schema.Type {} + +/** + * What changed in the browser during one execute call: URL movement, main + * frame navigations, error counts, and human handoffs. Delivered with the + * call that caused it so agents never fish warnings out of a later response. + */ +export const ExecuteAftermath = Schema.Struct({ + startUrl: Schema.NullOr(Schema.String), + endUrl: Schema.NullOr(Schema.String), + navigations: Schema.Array(Schema.String), + consoleErrorCount: Schema.Number, + pageErrorCount: Schema.Number, + handoffs: Schema.Number, +}) + +export interface ExecuteAftermath extends Schema.Schema.Type {} + +export const ExecuteMedia = Schema.Struct({ + type: Schema.Literal("image"), + mimeType: Schema.String, + data: Schema.String, + size: Schema.Number, +}) + +export interface ExecuteMedia extends Schema.Schema.Type {} + +export const ExecuteResponse = Schema.Struct({ + text: Schema.String, + value: Schema.optionalKey(Schema.Unknown), + media: Schema.optionalKey(Schema.Array(ExecuteMedia)), + isError: Schema.Boolean, + logs: Schema.Array(ExecuteLogEntry), + logSummary: Schema.optionalKey(ExecuteLogSummary), + warnings: Schema.optionalKey(Schema.Array(Schema.String)), + diagnostic: Schema.optionalKey(Schema.String), + aftermath: Schema.optionalKey(ExecuteAftermath), + session: ExecuteSessionSummary, +}) + +export interface ExecuteResponse extends Schema.Schema.Type {} + +export const AuthenticatedJsonMethod = Schema.Literals(["GET", "POST", "PUT", "PATCH", "DELETE"]) + +export type AuthenticatedJsonMethod = Schema.Schema.Type + +export const AuthenticatedJsonRequest = Schema.Struct({ + sessionId: Schema.NonEmptyString, + origin: Schema.NonEmptyString, + startUrl: Schema.optionalKey(Schema.NonEmptyString), + method: AuthenticatedJsonMethod, + path: Schema.NonEmptyString, + headers: Schema.optionalKey(Schema.Record(Schema.String, Schema.String)), + body: Schema.optionalKey(Schema.Json), + sensitive: Schema.optionalKey(Schema.Boolean), + handoffOnAuthFailure: Schema.optionalKey(Schema.Boolean), + handoffMessage: Schema.optionalKey(Schema.String), + timeoutMs: Schema.optionalKey(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 120_000 }))), + maxResponseBytes: Schema.optionalKey(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 10_000_000 }))), +}) + +export interface AuthenticatedJsonRequest extends Schema.Schema.Type {} + +export const AuthenticatedJsonOutcome = Schema.TaggedUnion({ + Success: { + status: Schema.Int, + value: Schema.Json, + }, + OriginMismatch: { + expectedOrigin: Schema.String, + actualOrigin: Schema.String, + }, + RequestFailed: { + outcome: Schema.Literals(["not-sent", "unknown"]), + }, + HttpError: { + status: Schema.Int, + }, + ResponseTooLarge: { + status: Schema.Int, + maxResponseBytes: Schema.Int, + }, + InvalidJson: { + status: Schema.Int, + }, + SensitiveCaptureActive: {}, +}) + +export type AuthenticatedJsonOutcome = typeof AuthenticatedJsonOutcome.Type + +export const TargetSummary = Schema.Struct({ + id: Schema.String, + type: Schema.String, + title: Schema.String, + url: Schema.String, + tabId: Schema.optionalKey(Schema.Number), + sessionId: Schema.optionalKey(Schema.String), + opencodeBrowserSessionId: Schema.optionalKey(Schema.String), + owner: Schema.optionalKey(Schema.Literals(["relay", "user"])), + crashed: Schema.optionalKey(Schema.Boolean), + /** Chrome is rejecting debugger commands while another extension's UI is open in the tab. */ + protectedUi: Schema.optionalKey(Schema.Boolean), +}) + +export interface TargetSummary extends Schema.Schema.Type {} + +export const TargetSummaries = Schema.Array(TargetSummary) + +export const ExtensionStatus = Schema.Struct({ + connected: Schema.Boolean, + version: Schema.NullOr(Schema.String), + /** When the connected extension was built: changes when a reload or update took effect. */ + build: Schema.optionalKey(Schema.NullOr(Schema.String)), + /** The connected extension's origin: the store build or the unpacked one. */ + origin: Schema.optionalKey(Schema.NullOr(Schema.String)), + protocolVersion: Schema.optionalKey(Schema.NullOr(Schema.Number)), + protocolCompatible: Schema.optionalKey(Schema.NullOr(Schema.Boolean)), + protocolLegacy: Schema.optionalKey(Schema.NullOr(Schema.Boolean)), + rejectedConnections: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))), + activeTargets: Schema.Number, + childTargets: Schema.optionalKey(Schema.Number), + cdpClients: Schema.optionalKey(Schema.Number), + sessions: Schema.optionalKey(Schema.Array(SessionSummary)), + targets: Schema.optionalKey(TargetSummaries), +}) + +export interface ExtensionStatus extends Schema.Schema.Type {} + +export const RelayVersion = Schema.Struct({ + version: Schema.String, + buildId: Schema.optionalKey(Schema.String), + instanceId: Schema.optionalKey(Schema.String), + startedAt: Schema.optionalKey(Schema.String), + pid: Schema.optionalKey(Schema.Number), + managed: Schema.optionalKey(Schema.Boolean), + shutdownProtocol: Schema.optionalKey(Schema.Literal(2)), +}) + +export interface RelayVersion extends Schema.Schema.Type {} + +// Unlike $, this end assertion rejects trailing line breaks in audit identifiers. +const RelayIdentity = Schema.String.check(Schema.isPattern(/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}(?![\s\S])/)) +const RelayBuildId = Schema.String.check(Schema.isPattern(/^[A-Za-z0-9][A-Za-z0-9._:+-]{0,255}(?![\s\S])/)) + +export const RelayShutdownRequest = Schema.Struct({ + instanceId: RelayIdentity, + requestId: RelayIdentity, + reason: Schema.Literal("explicit-restart"), + client: Schema.Struct({ + kind: Schema.Literals(["cli", "mcp", "sdk"]), + instanceId: RelayIdentity, + buildId: RelayBuildId, + }), +}) + +export interface RelayShutdownRequest extends Schema.Schema.Type {} + +export const RelayShutdownResponse = Schema.Struct({ + stopping: Schema.Literal(true), +}) + +export interface RelayShutdownResponse extends Schema.Schema.Type {} + +const NetworkContentMode = Schema.Literals(["omit", "embed"]) + +export const NetworkStartRequest = Schema.Struct({ + sessionId: Schema.NonEmptyString, + urlFilter: Schema.optionalKey(Schema.String), + resourceTypes: Schema.optionalKey(Schema.Array(Schema.NonEmptyString).check(Schema.isMaxLength(50))), + content: Schema.optionalKey(NetworkContentMode), + maxBodyBytes: Schema.optionalKey(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 10_000_000 }))), + maxTotalBodyBytes: Schema.optionalKey(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 100_000_000 }))), + maxEntries: Schema.optionalKey(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 10_000 }))), +}) + +export interface NetworkStartRequest extends Schema.Schema.Type {} + +export const NetworkSessionRequest = Schema.Struct({ sessionId: Schema.NonEmptyString }) +export interface NetworkSessionRequest extends Schema.Schema.Type {} + +export const NetworkStopRequest = NetworkSessionRequest.pipe(Schema.fieldsAssign({ + outputPath: Schema.optionalKey(Schema.String), + secrets: Schema.optionalKey(Schema.NonEmptyString), +})) +export interface NetworkStopRequest extends Schema.Schema.Type {} + +export const NetworkStatusResponse = Schema.Struct({ + active: Schema.Boolean, + startedAt: Schema.optionalKey(Schema.String), + entryCount: Schema.Number, + responseCount: Schema.Number, + failureCount: Schema.Number, + capturedBodyBytes: Schema.Number, + truncatedBodyCount: Schema.Number, + droppedEntryCount: Schema.Number, + urlFilter: Schema.optionalKey(Schema.String), + resourceTypes: Schema.optionalKey(Schema.Array(Schema.String)), + content: Schema.optionalKey(NetworkContentMode), + secrets: Schema.optionalKey(Schema.String), +}) +export interface NetworkStatusResponse extends Schema.Schema.Type {} + +const AuthProfileSlotSummary = Schema.Struct({ + ref: Schema.String, + sources: Schema.Array(Schema.String), + expiresAt: Schema.optionalKey(Schema.String), + expired: Schema.Boolean, +}) + +export const AuthProfileSummary = Schema.Struct({ + name: Schema.String, + createdAt: Schema.String, + updatedAt: Schema.String, + slotCount: Schema.Number, + slots: Schema.Array(AuthProfileSlotSummary), +}) +export interface AuthProfileSummary extends Schema.Schema.Type {} + +const NetworkEndpointDigest = Schema.Struct({ + method: Schema.String, + url: Schema.String, + status: Schema.optionalKey(Schema.Number), + count: Schema.Number, + requestHeaders: Schema.optionalKey(Schema.Array(Schema.String)), + requestKeys: Schema.optionalKey(Schema.Array(Schema.String)), + responseKeys: Schema.optionalKey(Schema.Array(Schema.String)), +}) + +export const NetworkStopResponse = NetworkStatusResponse.pipe(Schema.fieldsAssign({ + active: Schema.Literal(false), + stoppedAt: Schema.String, + outputPath: Schema.optionalKey(Schema.String), + authProfile: Schema.optionalKey(AuthProfileSummary), + updatedSecretRefs: Schema.Array(Schema.String), + observedSecretRefs: Schema.Array(Schema.String), + endpoints: Schema.optionalKey(Schema.Array(NetworkEndpointDigest)), +})) +export interface NetworkStopResponse extends Schema.Schema.Type {} + +export const NetworkCancelResponse = Schema.Struct({ cancelled: Schema.Boolean }) +export interface NetworkCancelResponse extends Schema.Schema.Type {} + +export const AuthProfileRequest = Schema.Struct({ name: Schema.NonEmptyString }) +export interface AuthProfileRequest extends Schema.Schema.Type {} + +export const AuthRefreshRequest = Schema.Struct({ + sessionId: Schema.NonEmptyString, + name: Schema.NonEmptyString, + urlFilter: Schema.optionalKey(Schema.String), + timeoutMs: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThan(0))), +}) +export interface AuthRefreshRequest extends Schema.Schema.Type {} + +export const AuthRunRequest = Schema.Struct({ + name: Schema.NonEmptyString, + command: Schema.NonEmptyString, + args: Schema.optionalKey(Schema.Array(Schema.String)), + cwd: Schema.optionalKey(Schema.String), + timeoutMs: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThan(0))), +}) +export interface AuthRunRequest extends Schema.Schema.Type {} + +export const AuthRunResponse = Schema.Struct({ + exitCode: Schema.Number, + signal: Schema.NullOr(Schema.String), + stdout: Schema.String, + stderr: Schema.String, + stdoutTruncated: Schema.Boolean, + stderrTruncated: Schema.Boolean, + durationMs: Schema.Number, +}) +export interface AuthRunResponse extends Schema.Schema.Type {} + +const RecordingMode = Schema.Literals(["tab-capture", "cdp"]) + +const RecordingRequestedMode = Schema.Literals(["auto", "tab-capture", "cdp"]) + +const RecordingFrameRate = Schema.Number.check(Schema.isInt(), Schema.isBetween({ minimum: 1, maximum: 60 })) + +export const RecordingQuality = Schema.Struct({ + width: Schema.Number, + height: Schema.Number, + frameRate: Schema.Number, + sourceFrameCount: Schema.Number, + encodedSourceFrameCount: Schema.Number, + coalescedFrameCount: Schema.Number, + droppedFrameCount: Schema.Number, + achievedSourceFrameRate: Schema.Number, + achievedEncodedSourceFrameRate: Schema.Number, + screenshotFallback: Schema.Boolean, + sourceWidth: Schema.optionalKey(Schema.Number), + sourceHeight: Schema.optionalKey(Schema.Number), +}) + +export interface RecordingQuality extends Schema.Schema.Type {} + +export const RecordingTargetRequest = Schema.Struct({ + sessionId: Schema.optionalKey(Schema.String), + tabId: Schema.optionalKey(Schema.Number), +}) + +export interface RecordingTargetRequest extends Schema.Schema.Type {} + +export const RecordingStartRequest = RecordingTargetRequest.pipe(Schema.fieldsAssign({ + outputPath: Schema.String, + mode: Schema.optionalKey(RecordingRequestedMode), + audio: Schema.optionalKey(Schema.Boolean), + frameRate: Schema.optionalKey(RecordingFrameRate), + videoBitsPerSecond: Schema.optionalKey(Schema.Number), + audioBitsPerSecond: Schema.optionalKey(Schema.Number), + maxDurationMs: Schema.optionalKey(Schema.Number), +})) + +export interface RecordingStartRequest extends Schema.Schema.Type {} + +const RecordingArtifactType = Schema.Literals(["webm", "mp4"]) + +export const RecordingStartResponse = Schema.Struct({ + success: Schema.Boolean, + tabId: Schema.optionalKey(Schema.Number), + startedAt: Schema.optionalKey(Schema.Number), + path: Schema.optionalKey(Schema.String), + mimeType: Schema.optionalKey(Schema.String), + mode: Schema.optionalKey(RecordingMode), + artifactType: Schema.optionalKey(RecordingArtifactType), + frameRate: Schema.optionalKey(Schema.Number), + error: Schema.optionalKey(Schema.String), +}) + +export interface RecordingStartResponse extends Schema.Schema.Type {} + +export const RecordingStopResponse = Schema.Struct({ + success: Schema.Boolean, + tabId: Schema.optionalKey(Schema.Number), + duration: Schema.optionalKey(Schema.Number), + path: Schema.optionalKey(Schema.String), + size: Schema.optionalKey(Schema.Number), + mode: Schema.optionalKey(RecordingMode), + artifactType: Schema.optionalKey(RecordingArtifactType), + frameCount: Schema.optionalKey(Schema.Number), + quality: Schema.optionalKey(RecordingQuality), + error: Schema.optionalKey(Schema.String), +}) + +export interface RecordingStopResponse extends Schema.Schema.Type {} + +export const RecordingStatusResponse = Schema.Struct({ + isRecording: Schema.Boolean, + tabId: Schema.optionalKey(Schema.Number), + startedAt: Schema.optionalKey(Schema.Number), + path: Schema.optionalKey(Schema.String), + size: Schema.optionalKey(Schema.Number), + mode: Schema.optionalKey(RecordingMode), + artifactType: Schema.optionalKey(RecordingArtifactType), + frameCount: Schema.optionalKey(Schema.Number), + quality: Schema.optionalKey(RecordingQuality), +}) + +export interface RecordingStatusResponse extends Schema.Schema.Type {} + +export const TabsCleanupResponse = Schema.Struct({ + closed: Schema.Array(Schema.Struct({ tabId: Schema.Number, title: Schema.String, idleMinutes: Schema.Number })), +}) +export type TabsCleanupResponse = typeof TabsCleanupResponse.Type + +export const RecordingCancelResponse = Schema.Struct({ + success: Schema.Boolean, + error: Schema.optionalKey(Schema.String), +}) + +export interface RecordingCancelResponse extends Schema.Schema.Type {} + +export const FlightRecorderStartRequest = RecordingTargetRequest.pipe(Schema.fieldsAssign({ + retentionMs: Schema.optionalKey(Schema.Number.check(Schema.isInt(), Schema.isBetween({ minimum: 1_000, maximum: 120_000 }))), + frameRate: Schema.optionalKey(RecordingFrameRate), +})) +export interface FlightRecorderStartRequest extends Schema.Schema.Type {} + +export const FlightRecorderStatusResponse = Schema.Struct({ + active: Schema.Boolean, + tabId: Schema.optionalKey(Schema.Number), + sessionId: Schema.optionalKey(Schema.String), + startedAt: Schema.optionalKey(Schema.Number), + retentionMs: Schema.optionalKey(Schema.Number), + retainedDurationMs: Schema.optionalKey(Schema.Number), + frameRate: Schema.optionalKey(Schema.Number), + bufferedFrames: Schema.optionalKey(Schema.Number), + bufferedBytes: Schema.optionalKey(Schema.Number), + sourceFrameCount: Schema.optionalKey(Schema.Number), + droppedFrameCount: Schema.optionalKey(Schema.Number), + saving: Schema.optionalKey(Schema.Boolean), +}) +export interface FlightRecorderStatusResponse extends Schema.Schema.Type {} + +export const FlightRecorderSaveRequest = RecordingTargetRequest.pipe(Schema.fieldsAssign({ + outputPath: Schema.String, + durationMs: Schema.optionalKey(Schema.Number.check(Schema.isInt(), Schema.isGreaterThan(0))), +})) +export interface FlightRecorderSaveRequest extends Schema.Schema.Type {} + +export const FlightRecorderSaveResponse = Schema.Struct({ + path: Schema.String, + durationMs: Schema.Number, + frameCount: Schema.Number, + sourceFrameCount: Schema.Number, + droppedFrameCount: Schema.Number, +}) +export interface FlightRecorderSaveResponse extends Schema.Schema.Type {} + +export const FlightRecorderCancelResponse = Schema.Struct({ cancelled: Schema.Boolean }) +export interface FlightRecorderCancelResponse extends Schema.Schema.Type {} + +export const RelayErrorCode = Schema.Literals([ + "invalid-request", + "relay-starting", + "relay-busy", + "auth-profile-not-found", + "capture-conflict", + "session-already-exists", + "session-inactive", + "session-not-found", + "session-timeout", + "setup-failed", + "target-ambiguous", + "target-changed", + "target-not-found", + "target-owned", + "internal", +]) + +export type RelayErrorCode = Schema.Schema.Type + +export const ErrorEnvelope = Schema.Struct({ + error: Schema.String, + code: Schema.optionalKey(RelayErrorCode), +}) + +export interface ErrorEnvelope extends Schema.Schema.Type {} diff --git a/packages/browser-extension/cli/src/relay-shutdown.ts b/packages/browser-extension/cli/src/relay-shutdown.ts new file mode 100644 index 00000000000..42b23d18bc3 --- /dev/null +++ b/packages/browser-extension/cli/src/relay-shutdown.ts @@ -0,0 +1,152 @@ +import { Data, Effect, Exit, Latch, Match, Schema } from "effect" +import type { RelayShutdownRequest } from "./relay-schema.ts" +import { RelayLifecycleEvent } from "./relay-lifecycle-log.ts" + +type State = Data.TaggedEnum<{ + Running: {} + Draining: {} + Stopping: {} + Closing: {} +}> +const State = Data.taggedEnum() + +export class RelayShutdownError extends Schema.TaggedError()( + "RelayShutdown.Error", + { + reason: Schema.Literals(["busy", "instance-changed", "not-managed"]), + message: Schema.String, + }, +) {} + +export class RelayShutdown { + private state: State = State.Running() + private requests = 0 + private readonly idle = Latch.makeUnsafe(true) + + constructor(private readonly options: { + readonly instanceId: string + readonly managed: boolean + readonly drain: Effect.Effect + readonly resume: () => void + readonly busy: () => "raw-clients" | "recordings" | undefined + readonly settle: Effect.Effect + readonly quiescent: () => boolean + readonly audit: (event: RelayLifecycleEvent) => Effect.Effect + readonly stop: () => void + readonly timeoutMs?: number + }) {} + + get accepting(): boolean { + return State.$is("Running")(this.state) + } + + get stopping(): boolean { + return State.$is("Stopping")(this.state) || State.$is("Closing")(this.state) + } + + close(): Effect.Effect { + const control = this + return Effect.gen(function* () { + control.state = State.Closing() + yield* Effect.all([control.options.drain, control.idle.await], { concurrency: "unbounded" }) + yield* control.idle.await + yield* control.options.settle + }) + } + + track(effect: Effect.Effect): Effect.Effect { + const control = this + return Effect.acquireUseRelease( + Effect.suspend(() => { + if (!control.accepting) return Effect.fail(control.busyError()) + return Effect.sync(() => control.retain()) + }), + () => effect, + (release) => Effect.sync(release), + ) + } + + // Already-admitted sandbox work needs continuation RPCs during a drain. + // Keep their lifetime independent of the client socket remaining connected. + trackTransport(effect: Effect.Effect): Effect.Effect { + return Effect.acquireUseRelease( + Effect.sync(() => this.retain()), + () => effect, + (release) => Effect.sync(release), + ) + } + + private retain(): () => void { + this.requests += 1 + this.idle.closeUnsafe() + return () => { + if (--this.requests === 0) this.idle.openUnsafe() + } + } + + request(request: RelayShutdownRequest): Effect.Effect { + const control = this + return Effect.uninterruptibleMask((restore) => Effect.gen(function* () { + if (request.instanceId !== control.options.instanceId) { + return yield* new RelayShutdownError({ reason: "instance-changed", message: "Relay shutdown does not match the active managed instance" }) + } + if (!control.options.managed) { + return yield* new RelayShutdownError({ reason: "not-managed", message: "A foreground relay must be stopped by its owner" }) + } + if (!control.accepting) return yield* control.busyError() + control.state = State.Draining() + const fields = { instanceId: request.instanceId, requestId: request.requestId, client: request.client } + yield* Effect.gen(function* () { + yield* control.options.audit(RelayLifecycleEvent.cases.Requested.make(fields)) + const drain = Effect.gen(function* () { + const busy = control.options.busy() + if (busy) return yield* control.busyError(busy) + yield* Effect.all([control.options.drain, control.idle.await], { concurrency: "unbounded" }) + yield* control.idle.await + yield* control.options.settle + const remaining = control.options.busy() + if (remaining) return yield* control.busyError(remaining) + }) + yield* restore(drain.pipe(Effect.timeoutOrElse({ + duration: control.options.timeoutMs ?? 10_000, + orElse: () => control.busyError("timeout"), + }))) + if (!State.$is("Draining")(control.state)) { + return yield* control.busyError() + } + yield* control.options.audit(RelayLifecycleEvent.cases.Stopping.make(fields)) + yield* restore(Effect.void) + if (!State.$is("Draining")(control.state)) { + return yield* control.busyError() + } + if (control.requests !== 0 || !control.options.quiescent()) { + return yield* control.busyError("changed") + } + const busy = control.options.busy() + if (busy) return yield* control.busyError(busy) + control.state = State.Stopping() + control.options.stop() + }).pipe(Effect.onExit((exit) => { + if (Exit.isSuccess(exit) || !State.$is("Draining")(control.state)) return Effect.void + control.options.resume() + control.state = State.Running() + return control.options.audit(RelayLifecycleEvent.cases.Cancelled.make(fields)).pipe( + Effect.catch(() => Effect.sync(() => { + console.error(`Relay cancellation audit failed for request ${request.requestId}`) + })), + ) + })) + })) + } + + private busyError(reason?: "raw-clients" | "recordings" | "timeout" | "changed"): RelayShutdownError { + const message = Match.value(reason).pipe( + Match.when("raw-clients", () => "Relay has raw CDP clients attached; disconnect them before restarting"), + Match.when("recordings", () => "Relay has active recordings or network captures; stop them before restarting"), + Match.when("timeout", () => "Relay restart timed out waiting for accepted work; the relay is still running"), + Match.when("changed", () => "Relay changed while preparing restart; it is still running, retry the restart"), + Match.orElse(() => "Relay is draining for an explicit restart; retry after it completes"), + ) + return new RelayShutdownError({ reason: "busy", message }) + } +} diff --git a/packages/browser-extension/cli/src/relay-types.ts b/packages/browser-extension/cli/src/relay-types.ts new file mode 100644 index 00000000000..2af78a5bf60 --- /dev/null +++ b/packages/browser-extension/cli/src/relay-types.ts @@ -0,0 +1,94 @@ +import type { Effect, Semaphore } from "effect" +import type { ExecuteOptions, ExecuteResult } from "./execute.ts" +import type { NetworkCaptureOptions, NetworkCaptureResult, NetworkCaptureStatus, NetworkCaptureStopOptions } from "./network-capture.ts" +import type { JsonObject, TargetInfo } from "./protocol.ts" +import type { AuthenticatedJsonOutcome, AuthenticatedJsonRequest, SessionSummary } from "./relay-schema.ts" +export type SessionTarget = { + readonly id: string + readonly owner: "relay" | "user" +} + +export type ConnectedTarget = { + readonly tabId: number + readonly sessionId: string + /** + * The OpenCode Browser session the tab was created for. Owned tabs are + * visible only to that session's CDP clients; unowned tabs (user + * toolbar-attached or raw-client-created) are visible to every client. + */ + readonly opencodeBrowserSessionId?: string + readonly targetInfo: TargetInfo + readonly owner: "relay" | "user" + readonly crashed?: boolean + /** + * `chrome.debugger` currently rejects every command for this tab because a + * protected frame (another extension's UI, such as a password manager's + * inline menu) is open inside it. Cleared when a command succeeds again or + * the last protected frame goes away. + */ + readonly protectedUi?: boolean +} + +export type ChildTarget = { + readonly tabId: number + readonly sessionId: string + readonly parentSessionId: string + readonly targetInfo: TargetInfo + readonly waitingForDebugger: boolean +} + +export type StoredFrameEvents = { + readonly frameId: string + readonly attached?: JsonObject + readonly navigated?: JsonObject +} + +export type PendingExtensionRequest = { + readonly resolve: (value: JsonObject) => void + readonly reject: (error: Error) => void + readonly debuggerTabId?: number +} + +/** + * The sandbox seam used by session management. `ExecuteSandbox` is the real + * implementation; tests can substitute a fake. + */ +export interface ExecuteSandboxLike { + execute(code: string, options?: ExecuteOptions): Effect.Effect + authenticatedJson(request: Omit): Effect.Effect + adoptPage(targetId: string): Effect.Effect + /** Shutdown and handoff cancellation await disconnection without closing or forgetting the default tab. */ + disconnectSettled(): Effect.Effect + /** Adoption rollback cleanup does not settle before started Playwright close promises settle. */ + closeSettled(): Effect.Effect + networkStart(options?: NetworkCaptureOptions): Effect.Effect + networkStatus(): NetworkCaptureStatus + networkStop(options?: NetworkCaptureStopOptions): Effect.Effect + networkCancel(): Effect.Effect<{ readonly cancelled: boolean }> + authRefresh(options: { readonly name: string; readonly urlFilter?: string; readonly timeoutMs?: number }): Effect.Effect + redactNetworkCaptureText(text: string): string + markTargetCrashed(targetId: string): boolean + markTargetProtectedUi(targetId: string, protectedUi: boolean): boolean + markTargetDetached(targetId: string): boolean + markTargetReplaced(previousTargetId: string, targetId: string): boolean + restore(target: SessionTarget | undefined): void + getStatus(): { + readonly sessionId?: string + readonly connected: boolean + readonly pageUrl: string | null + readonly stateKeys: string[] + } +} + +export type OpenCodeBrowserSession = { + readonly id: string + readonly createdAt: string + readonly readOnly: boolean + readonly sandbox: ExecuteSandboxLike + readonly executeSemaphore: Semaphore.Semaphore + /** Durable default-target identity. Authoritative live ownership remains in TargetRegistry. */ + target?: SessionTarget + updatedAt: string +} + +export type { SessionSummary } diff --git a/packages/browser-extension/cli/src/relay.ts b/packages/browser-extension/cli/src/relay.ts new file mode 100644 index 00000000000..f32fdd50249 --- /dev/null +++ b/packages/browser-extension/cli/src/relay.ts @@ -0,0 +1,1627 @@ +import http from "node:http" +import stream from "node:stream" +import crypto from "node:crypto" +import fs from "node:fs" +import path from "node:path" +import { fileURLToPath } from "node:url" +import { Clock, Config, Effect, Option } from "effect" +import { WebSocket, WebSocketServer, type RawData } from "ws" +import { + removeDefaultLightColorSchemeEmulation, + replayChildFrameNavigation, + replayChildTargetsForParent, + replayTargetCreated, +} from "./cdp-shims.ts" +import { CdpClientPool } from "./cdp-client-pool.ts" +import { beforeInput, forgetTab } from "./human-input.ts" +import { CdpRouter } from "./cdp-router.ts" +import { CdpRuntime } from "./cdp-runtime.ts" +import { ExtensionRpc } from "./extension-rpc.ts" +import { createHttpRequestHandler } from "./http-api.ts" +import type { CdpEvent, CdpRequest, JsonObject, PageStatus } from "./protocol.ts" +import { extensionProtocolCompatibility, isCdpRequest, isExtensionEvent, isExtensionResponse, makePageStatus, parseJsonObject } from "./protocol.ts" +import { + closeHttpServer, + closeWebSocketServer, + chromeExtensionOriginForPath, + defaultHost, + defaultPort, + formatHostForUrl, + getIdText, + getNumber, + getObject, + getString, + getTargetInfo, + headerValue, + isRestrictedTarget, + listenHttpServer, + logCloseError, + sendCdpEvent, + sendCdpResponse, + validateHostHeader, + validateWebSocketOrigin, +} from "./relay-helpers.ts" +import type { ChildTarget, ConnectedTarget } from "./relay-types.ts" +import { ghostCursorMouseActionExpression, ghostCursorRestoreExpression, inputDispatchMouseEventToGhostCursorAction } from "./ghost-cursor.ts" +import { guardCdpMethod } from "./cdp-guardrails.ts" +import { + awaitHandoffAction, + HandoffRegistry, + resolveExactHandoffTarget, + toolbarClickAction, + type HandoffCancellationReason, + type HandoffOutcome, +} from "./handoff.ts" +import { ExecuteSandbox, type HandoffPageTarget } from "./execute.ts" +import { appendJournalEntry, defaultJournalBaseDir, makeJournalEntry } from "./session-journal.ts" +import { defaultSessionCatalogPath, SessionCatalog } from "./session-catalog.ts" +import { OpenCodeBrowserSessions } from "./session-manager.ts" +import { RecordingRelay } from "./recording-relay.ts" +import { FlightRecorderRelay } from "./flight-recorder.ts" +import { appendManagedRelayProcessLog, relayLog } from "./relay-log.ts" +import { appendRelayLifecycleEvent, RelayLifecycleEvent } from "./relay-lifecycle-log.ts" +import { RelayShutdown } from "./relay-shutdown.ts" +import { ProtectedFrameTracker } from "./protected-frames.ts" +import { RootTargetLifecycle } from "./root-target-lifecycle.ts" +import { boundedToken, runtimeFailureKind, summarizeDiagnosticUrl, summarizeRuntimeEvaluate } from "./runtime-diagnostics.ts" +import { shouldExposeChildTarget, TargetRegistry, type RootTargetChange, type TargetOwnershipChange } from "./target-registry.ts" +import { opencodeBrowserBuildId, opencodeBrowserVersion } from "./version.ts" + +export const startRelay = Effect.fn("Relay.start")(function* (options: { + readonly port?: number + readonly releaseTargetGraceMs?: number + readonly sessionCatalogPath?: string | null + readonly additionalExtensionOrigins?: readonly string[] +} = {}) { + yield* installRelayProcessGuard + return yield* Effect.acquireRelease(makeRelay(options), (server) => { + return server.close() + }) +}) + +type RelayProcessFaultKind = "uncaughtException" | "unhandledRejection" + +const installRelayProcessGuard = Effect.acquireRelease( + Effect.sync(() => { + const onUncaughtException = (error: Error, origin: NodeJS.UncaughtExceptionOrigin) => { + handleRelayProcessFault("uncaughtException", error, { origin }) + } + const onUnhandledRejection = (reason: unknown, promise: Promise) => { + handleRelayProcessFault("unhandledRejection", reason, { promise }) + } + process.on("uncaughtException", onUncaughtException) + process.on("unhandledRejection", onUnhandledRejection) + return { onUncaughtException, onUnhandledRejection } + }), + (handlers) => { + return Effect.sync(() => { + process.off("uncaughtException", handlers.onUncaughtException) + process.off("unhandledRejection", handlers.onUnhandledRejection) + }) + }, +) + +export function shouldSuppressRelayProcessFault(cause: unknown): boolean { + const errorText = cause instanceof Error ? `${cause.message}\n${cause.stack ?? ""}` : String(cause) + return /playwright-core|patchright-core|coreBundle|Duplicate target/i.test(errorText) +} + +export function handleRelayProcessFault( + kind: RelayProcessFaultKind, + cause: unknown, + detail: Record, + options: { readonly rethrow?: (cause: unknown) => never } = {}, +): void { + if (shouldSuppressRelayProcessFault(cause)) { + logProcessFault(kind, cause, detail, "keeping relay alive") + return + } + logProcessFault(kind, cause, detail, "not a known Playwright dispatch fault; rethrowing") + const rethrow = options.rethrow ?? rethrowProcessFault + rethrow(cause) +} + +function rethrowProcessFault(cause: unknown): never { + if (cause instanceof Error) { + throw cause + } + throw new Error(String(cause)) +} + +function logProcessFault(kind: RelayProcessFaultKind, cause: unknown, detail: Record, disposition: string): void { + const errorText = cause instanceof Error ? cause.stack ?? cause.message : String(cause) + const message = `[opencode-browser relay] ${kind}; ${disposition}\n${errorText}` + console.error(message) + if (process.env.OPENCODE_BROWSER_MANAGED_RELAY === "1") appendManagedRelayProcessLog(message) + if (debugEnvironmentEnabled(process.env.OPENCODE_BROWSER_DEBUG)) { + console.error(`[opencode-browser relay] ${kind} detail`, detail) + } +} + +function debugEnvironmentEnabled(value: string | undefined): boolean { + return value !== undefined && ["1", "true", "yes", "on"].includes(value.toLowerCase()) +} + +const makeRelay = Effect.fnUntraced(function* (options: { + readonly port?: number + readonly releaseTargetGraceMs?: number + readonly sessionCatalogPath?: string | null + readonly additionalExtensionOrigins?: readonly string[] +} = {}) { + const host = defaultHost + const port = options.port ?? defaultPort + const releaseTargetGraceMs = Math.max(0, options.releaseTargetGraceMs ?? 10_000) + const browserId = crypto.randomUUID() + const endpointUrl = `http://${formatHostForUrl(host)}:${port}` + const allowAnyChromeExtension = opencodeBrowserVersion === "0.0.0-dev" + const additionalChromeExtensionOrigins = new Set(options.additionalExtensionOrigins ?? []) + const sessionCatalog = options.sessionCatalogPath === null + ? undefined + : new SessionCatalog(options.sessionCatalogPath ?? defaultSessionCatalogPath(port)) + let catalogWritesEnabled = false + const registry = new TargetRegistry() + type TabGroupingMethod = "tabs.group" | "tabs.ungroup" + const pendingTabGrouping = new Map() + const tabGroupingWorkers = new Map>() + let extensionGeneration = 0 + let rejectedExtensionConnections = 0 + let extensionBuild: string | undefined + let extensionOrigin: string | undefined + const extensionRpc = new ExtensionRpc() + const sendToExtension = (command: Parameters[0]) => extensionRpc.send(command) + const sendExtensionBestEffort = (command: Parameters[0]): void => { + Effect.runPromise(Effect.ignore(sendToExtension(command))).catch(() => {}) + } + const sendDebuggerCommand = Effect.fnUntraced(function* (options: { + readonly tabId: number + readonly sessionId?: string + readonly method: string + readonly params: JsonObject + }) { + const finishDisable = options.method === "Runtime.disable" ? cdpRuntime.beginDisable(options.tabId, options.sessionId) : undefined + return yield* sendToExtension({ + method: "debugger.sendCommand", + params: { + tabId: options.tabId, + method: options.method, + params: options.params, + ...(options.sessionId === undefined ? {} : { sessionId: options.sessionId }), + }, + }).pipe(Effect.ensuring(Effect.sync(() => { finishDisable?.() }))) + }) + const recordingRelay = new RecordingRelay({ + sendToExtension: (command) => { + return Effect.runPromise(extensionRpc.send(command)) + }, + sendDebuggerCommand: (command) => { + return Effect.runPromise(sendDebuggerCommand(command)) + }, + isExtensionConnected: () => { + return extensionRpc.connected + }, + isTabUnavailable: (tabId) => flightRecorder.isActiveTab(tabId), + }) + const flightRecorder = new FlightRecorderRelay({ + sendDebuggerCommand: (command) => Effect.runPromise(sendDebuggerCommand(command)), + isExtensionConnected: () => extensionRpc.connected, + isTabRecording: (tabId) => recordingRelay.isRecordingTab(tabId), + }) + const handoffs = new HandoffRegistry() + const activeHandoffTabs = new Map>() + const clearLiveExtensionState = (reason: string) => { + void recordingRelay.cleanupAll(reason).catch(() => {}) + void flightRecorder.cleanupAll().catch(() => {}) + pendingTabGrouping.clear() + for (const target of [...registry.listRootTargets()]) { + detachTargetState(target.tabId, { preserveSessionTarget: true, updateExtension: false }) + } + registry.clear() + suppressedChildSessions.clear() + } + const releaseRelayTarget = Effect.fnUntraced(function* (targetId: string) { + const deadline = (yield* Clock.currentTimeMillis) + releaseTargetGraceMs + while (true) { + const target = registry.targetsByTargetId.get(targetId) + if (target && (extensionRpc.connected || extensionRpc.protocolLegacy === true)) { + yield* sendToExtension({ method: "tabs.remove", params: { tabId: target.tabId } }) + return + } + // Protocol v1 reports ready only after its complete attached-tab inventory + // has reconciled. Legacy shims need the full grace because hello came first. + if (extensionRpc.connected && extensionRpc.protocolLegacy === false) return + const remaining = deadline - (yield* Clock.currentTimeMillis) + if (remaining <= 0) return + yield* Effect.sleep(Math.min(50, remaining)) + } + }) + const journalBaseDir = defaultJournalBaseDir() + const attachedBadge = { text: "ON", color: "#7c3aed", title: "Detach from OpenCode Browser" } + const executingBadge = { text: "RUN", color: "#f59e0b", title: "OpenCode Browser is running a script" } + const waitingBadge = (message: string) => ({ text: "WAIT", color: "#2563eb", title: `OpenCode Browser is waiting for you: ${message}` }) + const executionBadge = (sessionId: string, executing: boolean) => executing && !sessions.isReadOnly(sessionId) ? executingBadge : attachedBadge + const setActivityForSessionTabs = ( + opencodeBrowserSessionId: string, + state: PageStatus["state"], + badge: { readonly text: string; readonly color: string; readonly title: string }, + ) => { + for (const target of registry.listRootTargets()) { + if (pageStatusSessionId(target) !== opencodeBrowserSessionId) { + continue + } + // Best-effort: older shims without action.setBadge just reject the command. + sendExtensionBestEffort({ method: "action.setBadge", params: { tabId: target.tabId, ...badge } }) + sendPageStatus(target, state) + } + } + const setActivityForTarget = ( + target: ConnectedTarget, + state: PageStatus["state"], + badge: { readonly text: string; readonly color: string; readonly title: string }, + options: { readonly sessionId?: string; readonly message?: string; readonly handoffId?: string } = {}, + ) => { + sendExtensionBestEffort({ method: "action.setBadge", params: { tabId: target.tabId, ...badge } }) + sendPageStatus(target, state, options) + } + const setActivityForTargetAcknowledged = async ( + target: ConnectedTarget, + state: PageStatus["state"], + badge: { readonly text: string; readonly color: string; readonly title: string }, + options: { readonly sessionId?: string; readonly message?: string; readonly handoffId?: string } = {}, + ): Promise => { + sendExtensionBestEffort({ method: "action.setBadge", params: { tabId: target.tabId, ...badge } }) + await Effect.runPromise(sendPageStatusEffect(target, state, options)) + } + const removeActiveHandoffTab = (sessionId: string, tabId: number): void => { + const tabIds = activeHandoffTabs.get(sessionId) + if (!tabIds) { + return + } + tabIds.delete(tabId) + if (tabIds.size === 0) { + activeHandoffTabs.delete(sessionId) + } + } + const cancelTargetHandoffs = (target: ConnectedTarget, reason: HandoffCancellationReason): void => { + const cancelled = handoffs.cancelForTarget({ + targetId: target.targetInfo.targetId, + targetSessionId: target.sessionId, + reason, + }) + for (const pending of cancelled) { + removeActiveHandoffTab(pending.sessionId, pending.tabId) + } + } + const requestHandoff = async (options: { + readonly sessionId: string + readonly message: string + readonly timeoutMs: number + readonly target: HandoffPageTarget + readonly start?: () => unknown | Promise + readonly cancelStart?: () => Promise + }): Promise => { + const target = resolveHandoffTarget(options.sessionId, options.target) + const sessionTabs = activeHandoffTabs.get(options.sessionId) ?? new Set() + sessionTabs.add(target.tabId) + activeHandoffTabs.set(options.sessionId, sessionTabs) + const wait = handoffs.wait({ + sessionId: options.sessionId, + tabId: target.tabId, + targetId: target.targetInfo.targetId, + targetSessionId: target.sessionId, + message: options.message, + timeoutMs: options.timeoutMs, + }) + let outcome: HandoffOutcome | undefined + try { + outcome = await awaitHandoffAction({ + wait, + present: () => setActivityForTargetAcknowledged(target, "waiting", waitingBadge(options.message), { + sessionId: options.sessionId, + message: options.message, + handoffId: wait.id, + }), + ...(options.start ? { start: options.start } : {}), + ...(options.cancelStart ? { cancelStart: options.cancelStart } : {}), + }) + return outcome + } catch (error) { + wait.cancel() + removeActiveHandoffTab(options.sessionId, target.tabId) + throw error + } finally { + if (outcome !== undefined && outcome !== "resolved" && outcome !== "timeout") { + removeActiveHandoffTab(options.sessionId, target.tabId) + } + const currentTarget = registry.tabTargets.get(target.tabId) + if (currentTarget) { + if (outcome !== undefined && outcome !== "resolved" && outcome !== "timeout") { + refreshPageStatus(currentTarget.tabId) + } else { + const executing = sessions.isExecuting(options.sessionId) + setActivityForTarget(currentTarget, executing ? "running" : "attached", executionBadge(options.sessionId, executing), { sessionId: options.sessionId }) + } + } + } + } + const sessions: OpenCodeBrowserSessions = new OpenCodeBrowserSessions( + endpointUrl, + (id, onDefaultTargetChange) => + new ExecuteSandbox({ + endpointUrl, + sessionId: id, + onDefaultTargetChange, + requestHandoff: ({ message, timeoutMs, target, start, cancelStart }) => requestHandoff({ + sessionId: id, + message, + timeoutMs, + target, + ...(start ? { start } : {}), + ...(cancelStart ? { cancelStart } : {}), + }), + }), + { + onExecuteStateChange: (sessionId, executing) => { + setActivityForSessionTabs(sessionId, executing ? "running" : "attached", executionBadge(sessionId, executing)) + if (!executing) { + for (const tabId of activeHandoffTabs.get(sessionId) ?? []) { + const target = registry.tabTargets.get(tabId) + if (target) { + setActivityForTarget(target, "attached", attachedBadge, { sessionId }) + } + } + activeHandoffTabs.delete(sessionId) + } + }, + onExecuteRecord: (record) => { + const entry = makeJournalEntry({ + sessionId: record.sessionId, + code: record.code, + isError: record.result.isError, + durationMs: record.durationMs, + resultText: record.result.text, + logCount: record.result.logs.length, + startUrl: record.result.aftermath?.startUrl, + endUrl: record.result.aftermath?.endUrl, + navigations: record.result.aftermath?.navigations, + warnings: record.result.warnings, + diagnostic: record.result.diagnostic, + handoffs: record.result.aftermath?.handoffs, + }) + return appendJournalEntry({ baseDir: journalBaseDir, entry }) + }, + onTargetOwnershipChange: (change) => { + reconcileTargetOwnership(change) + }, + onReleaseRelayTarget: (targetId) => releaseRelayTarget(targetId), + onSessionsChanged: async (entries) => { + if (catalogWritesEnabled) await sessionCatalog?.save(entries) + }, + }, + registry, + ) + function pageStatusSessionId(target: ConnectedTarget): string | undefined { + return target.opencodeBrowserSessionId + } + + function activeHandoffSessionIdForTab(tabId: number): string | undefined { + return Array.from(activeHandoffTabs.entries()).find(([, tabIds]) => tabIds.has(tabId))?.[0] + } + + function resolveHandoffTarget(sessionId: string, selectedPage: HandoffPageTarget): ConnectedTarget { + return resolveExactHandoffTarget({ + targetId: selectedPage.targetId, + targets: registry.listRootTargets(), + isVisible: (target) => cdpRouter.canSessionSeeTarget(sessionId, target), + }) + } + + function sendPageStatusEffect( + target: ConnectedTarget, + state: PageStatus["state"], + options: { readonly sessionId?: string; readonly message?: string; readonly handoffId?: string } = {}, + ): Effect.Effect { + const sessionId = options.sessionId ?? pageStatusSessionId(target) + const status = makePageStatus({ + state, + targetOwner: target.owner, + ...(sessionId ? { sessionId, readOnly: sessions.isReadOnly(sessionId) } : {}), + ...(options.message ? { message: options.message } : {}), + ...(options.handoffId ? { handoffId: options.handoffId } : {}), + }) + return sendToExtension({ + method: "pageStatus.set", + params: { tabId: target.tabId, status }, + }).pipe(Effect.asVoid) + } + + function sendPageStatus( + target: ConnectedTarget, + state: PageStatus["state"], + options: { readonly sessionId?: string; readonly message?: string; readonly handoffId?: string } = {}, + ): void { + Effect.runPromise(Effect.ignore(sendPageStatusEffect(target, state, options))).catch(() => {}) + } + + function refreshPageStatus(tabId: number): void { + const target = registry.tabTargets.get(tabId) + if (!target) { + sendExtensionBestEffort({ method: "pageStatus.clear", params: { tabId } }) + return + } + const pending = handoffs.pendingForTab(tabId) + if (pending) { + sendPageStatus(target, "waiting", { sessionId: pending.sessionId, message: pending.message, handoffId: pending.id }) + return + } + const sessionId = pageStatusSessionId(target) ?? activeHandoffSessionIdForTab(tabId) + sendPageStatus(target, sessionId && sessions.isExecuting(sessionId) ? "running" : "attached", sessionId ? { sessionId } : {}) + } + function scheduleTabGrouping(tabId: number, method: TabGroupingMethod): void { + pendingTabGrouping.set(tabId, method) + if (tabGroupingWorkers.has(tabId)) return + const worker = (async () => { + while (true) { + const next = pendingTabGrouping.get(tabId) + if (!next) return + pendingTabGrouping.delete(tabId) + const target = registry.tabTargets.get(tabId) + const sessionId = target ? pageStatusSessionId(target) : undefined + const params: JsonObject = next === "tabs.group" && sessionId + ? { tabId, sessionId } + : { tabId } + await Effect.runPromise(Effect.ignore(sendToExtension({ method: next, params }))) + } + })().finally(() => { + if (tabGroupingWorkers.get(tabId) !== worker) return + tabGroupingWorkers.delete(tabId) + const next = pendingTabGrouping.get(tabId) + if (next) scheduleTabGrouping(tabId, next) + }) + tabGroupingWorkers.set(tabId, worker) + } + function refreshTabGrouping(tabId: number): void { + const target = registry.tabTargets.get(tabId) + scheduleTabGrouping(tabId, target && pageStatusSessionId(target) ? "tabs.group" : "tabs.ungroup") + } + function refreshTabPresentation(tabId: number): void { + refreshPageStatus(tabId) + refreshTabGrouping(tabId) + } + const managed = yield* Config.Boolean("OPENCODE_BROWSER_MANAGED_RELAY").pipe(Config.withDefault(false)) + const restartTimeoutMs = yield* Config.Int("OPENCODE_BROWSER_RESTART_TIMEOUT_MS").pipe(Config.withDefault(10_000)) + const restartRequestId = yield* Config.option(Config.String("OPENCODE_BROWSER_RESTART_REQUEST_ID")) + const lifecycleLogPath = path.join(path.dirname(defaultSessionCatalogPath(port)), "lifecycle.jsonl") + const audit = (event: RelayLifecycleEvent) => Effect.try(() => appendRelayLifecycleEvent(lifecycleLogPath, event)) + const settleRootWork = Effect.fnUntraced(function* () { + yield* rootLifecycle.settle() + yield* sessions.beginDrain() + }) + const shutdownControl = new RelayShutdown({ + instanceId: browserId, + managed, + timeoutMs: Math.max(0, restartTimeoutMs), + drain: sessions.beginDrain(), + resume: () => sessions.resume(), + busy: () => { + if (Array.from(cdpClients).some((client) => !cdpClients.isSandbox(client))) return "raw-clients" + if (recordingRelay.hasActiveRecordings() || flightRecorder.hasActiveRecorders() || sessions.hasActiveNetworkCapture()) return "recordings" + return undefined + }, + settle: settleRootWork(), + quiescent: () => rootLifecycle.isIdle() && sessions.isDrained(), + audit, + stop: () => { setImmediate(() => process.kill(process.pid, "SIGTERM")) }, + }) + const relayRequestHandler = createHttpRequestHandler({ + host, + port, + browserId, + relayInstance: { id: browserId, startedAt: new Date().toISOString(), pid: process.pid, managed }, + shutdown: shutdownControl, + registry, + recordingRelay, + flightRecorder, + sessions, + reloadExtension: () => sendToExtension({ method: "runtime.reload" }), + cleanupTabs: (idleMinutes) => + sendToExtension({ method: "tabs.cleanup", ...(idleMinutes === undefined ? {} : { params: { idleMinutes } }) }), + extensionStatus: () => { + return { + connected: extensionRpc.connected, + version: extensionRpc.version ?? null, + build: extensionBuild ?? null, + origin: extensionOrigin ?? null, + protocolVersion: extensionRpc.protocolVersion ?? null, + protocolCompatible: extensionRpc.protocolCompatible ?? null, + protocolLegacy: extensionRpc.protocolLegacy ?? null, + rejectedConnections: rejectedExtensionConnections, + cdpClients: cdpClients.size, + } + }, + }) + let relayReady = false + const httpServer = http.createServer((request, response) => { + if (!relayReady) { + response.writeHead(503, { "content-type": "application/json; charset=utf-8", "retry-after": "1" }) + response.end(JSON.stringify({ error: "OpenCode Browser relay is starting", code: "relay-starting" })) + return + } + const started = performance.now() + response.once("finish", () => { + const pathname = (request.url ?? "").split("?")[0] + // Health, version, and connection polls (every 200ms while a client waits) are frequent and uninteresting. + if (pathname === "/version" || pathname === "/json/version" || pathname === "/json/version/" || pathname === "/extension/status") return + relayLog("http", { method: request.method, path: pathname, status: response.statusCode, ms: Math.round(performance.now() - started) }) + }) + relayRequestHandler(request, response) + }) + // Handoffs and secrets run commands legitimately outlive Node's 5-minute default request timeout. + httpServer.requestTimeout = 0 + httpServer.timeout = 0 + + const debugEnabled = yield* Config.Boolean("OPENCODE_BROWSER_DEBUG").pipe(Config.withDefault(false)) + const debugLog = debugEnabled ? (line: string) => console.error(`[bc ${new Date().toISOString().slice(11, 23)}] ${line}`) : undefined + const contextDebugLog = debugLog ? (line: string) => debugLog(`[bc:ctx] ${line}`) : undefined + const websocketServer = new WebSocketServer({ noServer: true }) + const cdpClients = new CdpClientPool( + (client, event) => cdpRuntime.deliver(client, event), + (client, sessionId) => cdpRuntime.detach(client, sessionId), + ) + const cdpRouter = new CdpRouter(cdpClients, registry) + const cdpRuntime = new CdpRuntime({ + registry, + generation: () => extensionGeneration, + send: sendDebuggerCommand, + sendEvent: sendCdpEvent, + ...(contextDebugLog ? { trace: contextDebugLog } : {}), + }) + const mainFrameIdsByTab = new Map() + const ghostCursorPositionsByTab = new Map() + const suppressedChildSessions = new Map() + const protectedFrames = new ProtectedFrameTracker() + + function setProtectedUi(tabId: number, protectedUi: boolean): void { + const changed = registry.markRootTargetProtectedUi(tabId, protectedUi) + if (!changed) return + contextDebugLog?.(`protected-ui blocked=${protectedUi} ${targetDiagnosticIdentity(changed)}`) + sessions.markTargetProtectedUi(changed.targetInfo.targetId, protectedUi) + } + + /** Hide a protected frame from clients that already saw it attach. */ + function retractProtectedFrame(target: ConnectedTarget, frameId: string, url: string | undefined): void { + contextDebugLog?.(`protected-frame frame=${boundedToken(frameId)} ${targetDiagnosticIdentity(target)} ${summarizeDiagnosticUrl(url)}`) + sendEventToTargetViewers(target.sessionId, { method: "Page.frameDetached", params: { frameId, reason: "remove" }, sessionId: target.sessionId }) + } + + function forgetProtectedFrames(tabId: number): void { + protectedFrames.forgetTab(tabId) + setProtectedUi(tabId, false) + } + + function targetDiagnosticIdentity(target: ConnectedTarget | ChildTarget | undefined): string { + if (!target) { + return "target=unknown" + } + const root = registry.tabTargets.get(target.tabId) + const isRoot = "owner" in target + return [ + `tab=${target.tabId}`, + `target=${boundedToken(target.targetInfo.targetId)}`, + `cdpSession=${boundedToken(target.sessionId)}`, + `owner=${isRoot ? target.owner : root?.owner ?? "child"}`, + `bcSession=${boundedToken(isRoot ? target.opencodeBrowserSessionId : root?.opencodeBrowserSessionId)}`, + `browserContext=${boundedToken(target.targetInfo.browserContextId ?? root?.targetInfo.browserContextId)}`, + ].join(" ") + } + + function targetForCdpSession(tabId: number, sessionId: string | undefined): ConnectedTarget | ChildTarget | undefined { + if (sessionId) { + return registry.targets.get(sessionId) ?? registry.childTargets.get(sessionId) ?? registry.tabTargets.get(tabId) + } + return registry.tabTargets.get(tabId) + } + + function diagnosticTargetForClient(socket: WebSocket, sessionId: string | undefined): ConnectedTarget | ChildTarget | undefined { + return sessionId + ? cdpRouter.targetInfo(socket, { sessionId }) + : cdpRouter.preferredRoot(socket) + } + + function isRuntimeEvaluationMethod(method: string): boolean { + return method === "Runtime.evaluate" || method === "Runtime.callFunctionOn" + } + + const cleanup = Effect.fnUntraced(function* () { + yield* shutdownControl.close().pipe(Effect.ignore) + yield* sessions.closeAll() + yield* rootLifecycle.close() + if (managed) { + yield* audit(RelayLifecycleEvent.cases.Closed.make({ instanceId: browserId })).pipe( + Effect.catch(() => Effect.sync(() => console.error("Failed to record relay shutdown lifecycle event"))), + ) + } + handoffs.cancelAll() + extensionRpc.rejectPending(new Error("Relay closed")) + yield* Effect.tryPromise(() => recordingRelay.cleanupAll("Relay closed")).pipe(Effect.ignore) + yield* Effect.tryPromise(() => flightRecorder.cleanupAll()).pipe(Effect.ignore) + for (const socket of cdpClients) { + socket.close() + } + extensionRpc.close() + yield* closeWebSocketServer(websocketServer).pipe(logCloseError("Failed to close websocket server")) + yield* closeHttpServer(httpServer).pipe(logCloseError("Failed to close http server")) + }) + + httpServer.on("upgrade", (request, socket, head) => { + if (!relayReady) { + sendUpgradeError({ socket, status: 404, message: "OpenCode Browser relay is starting" }) + return + } + const hostError = validateHostHeader({ hostHeader: request.headers.host, host, port }) + if (hostError) { + sendUpgradeError({ socket, status: 403, message: hostError }) + return + } + const requestUrl = new URL(request.url ?? "/", endpointUrl) + const origin = Array.isArray(request.headers.origin) ? request.headers.origin[0] : request.headers.origin + if (requestUrl.pathname === "/extension") { + const originError = validateWebSocketOrigin({ + origin, + requireChromeExtension: true, + allowAnyChromeExtension, + additionalChromeExtensionOrigins, + }) + if (originError) { + sendUpgradeError({ socket, status: 403, message: originError }) + return + } + websocketServer.handleUpgrade(request, socket, head, (websocket) => { + websocketServer.emit("connection", websocket, request) + }) + return + } + if (requestUrl.pathname.startsWith("/devtools/browser/")) { + const sessionId = requestUrl.searchParams.get("opencodeBrowserSessionId") ?? headerValue(request.headers["opencode-browser-session-id"]) + if (!shutdownControl.accepting && (headerValue(request.headers["opencode-browser-client-kind"]) !== "sandbox" || !sessionId || !sessions.hasPendingWork(sessionId))) { + sendUpgradeError({ socket, status: 503, message: "Relay is draining for an explicit restart" }) + return + } + const originError = validateWebSocketOrigin({ origin, allowAnyChromeExtension, additionalChromeExtensionOrigins }) + if (originError) { + sendUpgradeError({ socket, status: 403, message: originError }) + return + } + websocketServer.handleUpgrade(request, socket, head, (websocket) => { + websocketServer.emit("connection", websocket, request) + }) + return + } + socket.destroy() + }) + + let currentAnnouncedRootTabIds: Set | undefined + websocketServer.on("connection", (socket, request) => { + const requestUrl = new URL(request.url ?? "/", endpointUrl) + if (requestUrl.pathname === "/extension") { + let handshaken = false + let socketGeneration = 0 + const announcedRootTabIds = new Set() + currentAnnouncedRootTabIds = announcedRootTabIds + socket.on("message", (data, isBinary) => { + try { + if (!handshaken) { + const acceptedGeneration = isBinary ? undefined : acceptExtensionHello(socket, data.toString(), headerValue(request.headers.origin)) + if (acceptedGeneration === undefined) { + socket.close(4002, "Extension hello required") + return + } + socketGeneration = acceptedGeneration + handshaken = true + return + } + if (!extensionRpc.isCurrent(socket) || !extensionRpc.acceptsEvents) { + return + } + if (isBinary) { + try { + recordingRelay.handleBinaryData(rawDataToBuffer(data)) + } catch { + socket.close(1002, "Invalid recording frame") + } + return + } + handleExtensionMessage(socket, data.toString(), socketGeneration, announcedRootTabIds) + } catch (error) { + console.error("Extension message handling failed", error) + } + }) + socket.on("close", (code, reason) => { + relayLog("extension.close", { code, reason: reason.toString() || undefined, current: extensionRpc.isCurrent(socket) }) + if (extensionRpc.disconnectIfCurrent(socket)) { + rejectedExtensionConnections = 0 + clearLiveExtensionState("Extension disconnected") + } + }) + return + } + + const opencodeBrowserSessionId = requestUrl.searchParams.get("opencodeBrowserSessionId") ?? headerValue(request.headers["opencode-browser-session-id"]) + cdpClients.register(socket, opencodeBrowserSessionId, headerValue(request.headers["opencode-browser-client-kind"]) === "sandbox" ? "sandbox" : "raw") + debugLog?.(`client+ ${opencodeBrowserSessionId ?? "raw"} total=${cdpClients.size}`) + socket.on("message", (data) => { + Effect.runPromise(shutdownControl.trackTransport(handleCdpMessage(socket, data.toString()))).catch((error: unknown) => { + sendCdpResponse(socket, { + id: 0, + error: { message: error instanceof Error ? error.message : String(error) }, + }) + }) + }) + socket.on("close", () => { + debugLog?.(`client- ${cdpClients.sessionId(socket) ?? "raw"} total=${cdpClients.size - 1}`) + cdpRuntime.disconnect(socket) + const idleGeneration = cdpClients.unregister(socket) + if (idleGeneration !== undefined && !shutdownControl.stopping) { + Effect.runPromise(shutdownControl.trackTransport(cdpRuntime.disableIdle(() => cdpClients.isCurrentIdleGeneration(idleGeneration))).pipe(Effect.ignore)).catch((error: unknown) => { + console.error("Failed to reset idle runtime domains", error) + }) + } + }) + }) + + const close = cleanup() + + const closeTargetByTargetId = Effect.fnUntraced(function* (targetId: string) { + const target = registry.targetsByTargetId.get(targetId) + if (!target) { + return + } + yield* sendToExtension({ method: "tabs.remove", params: { tabId: target.tabId } }) + detachTargetState(target.tabId) + }) + + function acceptExtensionHello(socket: WebSocket, raw: string, origin: string | undefined): number | undefined { + const message = parseJsonObject(raw) + if (!isExtensionEvent(message) || message.method !== "hello") { + return undefined + } + const protocol = extensionProtocolCompatibility(message.params?.protocolVersion) + if (!protocol.compatible && extensionRpc.protocolCompatible === true) { + relayLog("extension.rejected", { reason: "incompatible", protocol: protocol.version, version: getString(message.params, "version") }) + socket.close(4003, "Extension protocol incompatible") + return extensionGeneration + } + // Protect an OPEN compatible connection, including its inventory handshake. + // Competing browser retries must not erase targets, handoffs, or pending RPCs. + if (extensionRpc.acceptsEvents) { + rejectedExtensionConnections += 1 + relayLog("extension.rejected", { reason: "another connection is active", profile: getString(message.params, "profileName") }) + extensionRpc.probeLiveness() + socket.close(4004, "Another browser or profile is already connected") + return extensionGeneration + } + extensionGeneration += 1 + rejectedExtensionConnections = 0 + clearLiveExtensionState("Extension replaced") + extensionRpc.replaceSocket(socket) + extensionRpc.markHandshake( + getString(message.params, "version"), + message.params?.protocolVersion, + ) + extensionBuild = getString(message.params, "build") + extensionOrigin = origin + relayLog("extension.connected", { + version: getString(message.params, "version"), + build: getString(message.params, "build"), + protocol: protocol.version, + profile: getString(message.params, "profileName"), + generation: extensionGeneration, + }) + return extensionGeneration + } + + function resumeIfWaitingForDebugger(tabId: number, childSessionId: string, params: JsonObject | undefined, label: string): void { + if (params?.waitingForDebugger !== true) return + Effect.runPromise( + sendDebuggerCommand({ + tabId, + sessionId: childSessionId, + method: "Runtime.runIfWaitingForDebugger", + params: {}, + }).pipe(Effect.ignore), + ).catch((error: unknown) => { + console.error(label, error) + }) + } + + function handleExtensionMessage(socket: WebSocket, raw: string, generation: number, announcedRootTabIds: Set): void { + const message = parseJsonObject(raw) + if (isExtensionResponse(message)) { + extensionRpc.handleResponse(message) + return + } + + if (!isExtensionEvent(message)) { + return + } + const extensionMethod = message.method as string + const eventTabId = getNumber(message.params, "tabId") + if (extensionMethod === "hello") { + return + } + if (extensionMethod === "log") { + const text = getString(message.params, "message") + if (!text) return + const level = message.params?.level === "error" || message.params?.level === "warn" ? message.params.level : "log" + console[level](`[opencode-browser extension] ${text}`) + return + } + if (extensionMethod === "ready") { + void Effect.runPromise(rootLifecycle.settle(generation)).then((reconciled) => { + if (!extensionRpc.isCurrent(socket) || generation !== extensionGeneration) return + if (reconciled) { + for (const target of registry.listRootTargets()) { + if (!announcedRootTabIds.has(target.tabId)) detachTargetState(target.tabId) + } + extensionRpc.markReady() + for (const target of registry.listRootTargets()) refreshTabGrouping(target.tabId) + } else { + socket.close(1011, "Target inventory reconciliation failed") + } + }) + return + } + if (extensionMethod === "debugger.attached") { + if (eventTabId) { + announcedRootTabIds.add(eventTabId) + rootLifecycle.queue({ tabId: eventTabId, attachIfMissing: true, verificationRetries: 0, errorMessage: "Debugger re-announce failed", generation }) + } + return + } + if (extensionMethod === "toolbar.clicked") { + if (eventTabId) { + announcedRootTabIds.add(eventTabId) + handleToolbarClick(eventTabId) + } + return + } + if (extensionMethod === "handoff.completed") { + const handoffId = getString(message.params, "handoffId") + const target = eventTabId ? registry.tabTargets.get(eventTabId) : undefined + if (target && handoffId) { + const completed = handoffs.complete({ + id: handoffId, + tabId: target.tabId, + targetId: target.targetInfo.targetId, + targetSessionId: target.sessionId, + }) + if (completed) { + refreshPageStatus(target.tabId) + } + } + return + } + if (extensionMethod === "pageStatus.requested") { + if (eventTabId) { + refreshPageStatus(eventTabId) + } + return + } + if (extensionMethod === "debugger.detached") { + const detachedSessionId = getString(message.params, "sessionId") + const reason = getString(message.params, "reason") + if (detachedSessionId) { + suppressedChildSessions.delete(detachedSessionId) + detachChildTargetState(detachedSessionId) + return + } + if (reason === "target_closed") { + if (eventTabId) { + rootLifecycle.queue({ tabId: eventTabId, attachIfMissing: false, verificationRetries: 3, errorMessage: "Failed to reconcile ambiguous debugger detach" }) + } + return + } + if (eventTabId) { + detachTargetState(eventTabId) + } + return + } + if (extensionMethod === "tabs.removed") { + if (eventTabId) { + detachTargetState(eventTabId) + } + return + } + if (extensionMethod === "recording.cancelled") { + recordingRelay.handleRecordingCancelled(message) + return + } + if (extensionMethod !== "debugger.event" || !eventTabId) { + return + } + + const tabId = eventTabId + const target = registry.routingRootTarget(tabId) + if (!target) { + return + } + const method = getString(message.params, "method") ?? "" + const params = getObject(message.params?.params) + const sourceSessionId = getString(message.params, "sessionId") + debugLog?.(`evt tab=${tabId} ${method} src=${sourceSessionId ?? "root"}`) + const sourceChild = sourceSessionId ? registry.childTargets.get(sourceSessionId) : undefined + if (sourceSessionId && sourceSessionId !== target.sessionId && !sourceChild) { + return + } + if ( + sourceSessionId && + method !== "Target.attachedToTarget" && + method !== "Target.detachedFromTarget" && + method !== "Target.targetInfoChanged" && + (suppressedChildSessions.has(sourceSessionId) || (sourceChild && !shouldExposeChildTarget(sourceChild))) + ) { + return + } + if (flightRecorder.handleDebuggerEvent({ tabId, method, params }) || recordingRelay.handleDebuggerEvent({ tabId, method, params })) { + return + } + let shouldBroadcast = true + let attachedChildTarget: ChildTarget | undefined + + if ((method === "Inspector.targetCrashed" || method === "Target.targetCrashed") && (sourceSessionId === undefined || sourceSessionId === target.sessionId)) { + const crashedTarget = registry.markRootTargetCrashed(tabId) + if (crashedTarget) { + cancelTargetHandoffs(crashedTarget, "target-crashed") + const affectedSessions = sessions.markTargetCrashed(crashedTarget.targetInfo.targetId) + extensionRpc.rejectDebuggerCommandsForTab(tabId, new Error(`Target crashed: ${crashedTarget.targetInfo.targetId}`)) + contextDebugLog?.(`target-crashed ${targetDiagnosticIdentity(crashedTarget)} affectedSessions=${affectedSessions.length}`) + } + } + if (method === "Target.attachedToTarget") { + const childSessionId = getString(params, "sessionId") + const targetInfo = getTargetInfo(params?.targetInfo) + if (childSessionId && !targetInfo) { + resumeIfWaitingForDebugger(tabId, childSessionId, params, "Failed to resume unsupported target") + return + } + if (childSessionId && targetInfo) { + if (isRestrictedTarget(targetInfo)) { + suppressedChildSessions.set(childSessionId, tabId) + if (targetInfo.type === "iframe" && protectedFrames.mark(tabId, targetInfo.targetId)) { + retractProtectedFrame(target, targetInfo.targetId, targetInfo.url) + } + resumeIfWaitingForDebugger(tabId, childSessionId, params, "Failed to resume restricted target") + return + } + suppressedChildSessions.delete(childSessionId) + shouldBroadcast = false + const parentSessionId = sourceSessionId ?? target.sessionId + const childTarget: ChildTarget = { + tabId, + sessionId: childSessionId, + parentSessionId, + targetInfo, + waitingForDebugger: params?.waitingForDebugger === true, + } + for (const previous of registry.addChildTarget(childTarget)) { + cdpClients.detachTarget(previous) + } + contextDebugLog?.(`target-attached kind=child parentSession=${boundedToken(parentSessionId)} ${targetDiagnosticIdentity(childTarget)} ${summarizeDiagnosticUrl(targetInfo.url)}`) + if (shouldExposeChildTarget(childTarget)) { + attachedChildTarget = childTarget + } + } + } + if (method === "Target.detachedFromTarget") { + const childSessionId = getString(params, "sessionId") + if (childSessionId) { + shouldBroadcast = false + suppressedChildSessions.delete(childSessionId) + contextDebugLog?.(`target-detached kind=child ${targetDiagnosticIdentity(registry.childTargets.get(childSessionId))}`) + detachChildTargetState(childSessionId) + } + } + if (method === "Target.targetInfoChanged") { + const targetInfo = getTargetInfo(params?.targetInfo) + if (!targetInfo) { + return + } + const childTarget = registry.childTargetsByTargetId.get(targetInfo.targetId) + const wasExposed = childTarget ? shouldExposeChildTarget(childTarget) : false + if (isRestrictedTarget(targetInfo)) { + if (childTarget) { + suppressedChildSessions.set(childTarget.sessionId, tabId) + detachChildTargetState(childTarget.sessionId) + if (targetInfo.type === "iframe" && protectedFrames.mark(tabId, targetInfo.targetId)) { + retractProtectedFrame(target, targetInfo.targetId, targetInfo.url) + } + } + return + } + const changed = registry.updateConnectedTargetInfo({ tabId, targetInfo }) + if (!changed) { + const currentRoot = registry.routingRootTarget(tabId) + if (targetInfo.type === "page" && currentRoot && currentRoot.targetInfo.targetId !== targetInfo.targetId) { + rootLifecycle.queue({ tabId, attachIfMissing: false, verificationRetries: 1, errorMessage: "Failed to reconcile changed root target info" }) + } + return + } + contextDebugLog?.(`target-info-changed ${targetDiagnosticIdentity(changed.target)} ${summarizeDiagnosticUrl(targetInfo.url)}`) + if (changed.kind === "child" && !wasExposed && shouldExposeChildTarget(changed.target)) { + announceAttachedChildTarget(target.sessionId, changed.target) + } + } else if (method.startsWith("Target.") && params?.targetInfo !== undefined) { + const eventTargetInfo = getTargetInfo(params.targetInfo) + if (!eventTargetInfo || isRestrictedTarget(eventTargetInfo)) { + return + } + } + if (sourceSessionId === undefined || sourceSessionId === target.sessionId) { + const decision = protectedFrames.observe({ + tabId, + method, + params, + mainFrameId: mainFrameIdsByTab.get(tabId), + isChildFrame: (frameId) => getString(registry.tabFrameEvents.get(tabId)?.get(frameId)?.attached, "parentFrameId") !== undefined, + }) + if (decision.kind === "retract") { + const frame = getObject(params?.frame) + retractProtectedFrame(target, decision.frameId, getString(params, "url") ?? getString(frame, "url")) + return + } + if (decision.kind === "suppress") { + // Dismissed protected UI lifts Chrome's debugger block for the tab. + if (method === "Page.frameDetached" && !protectedFrames.hasAny(tabId)) setProtectedUi(tabId, false) + return + } + if (decision.kind === "restore") { + sendEventToTargetViewers(target.sessionId, { method: "Page.frameAttached", params: { frameId: decision.frameId, parentFrameId: decision.parentFrameId }, sessionId: target.sessionId }) + } + } + if (method === "Page.frameNavigated") { + const frame = getObject(params?.frame) + const frameId = getString(frame, "id") + const frameUrl = getString(frame, "url") + const frameParentId = getString(frame, "parentId") + if (frameUrl !== undefined && frameParentId === undefined && (sourceSessionId === undefined || sourceSessionId === target.sessionId)) { + if (frameId !== undefined) { + mainFrameIdsByTab.set(tabId, frameId) + } + // The previous document's frames, protected ones included, are gone. + forgetProtectedFrames(tabId) + contextDebugLog?.(`main-frame-navigated frame=${boundedToken(frameId)} loader=${boundedToken(getString(frame, "loaderId"))} ${targetDiagnosticIdentity(target)} ${summarizeDiagnosticUrl(frameUrl)}`) + registry.updateTargetUrl(tabId, frameUrl) + } + if (frameId !== undefined && frameParentId !== undefined && params) { + registry.rememberFrameEvent({ tabId, frameId, navigated: params }) + } + } + if (method === "Page.navigatedWithinDocument") { + const frameId = getString(params, "frameId") + const url = getString(params, "url") + if ( + url !== undefined + && (sourceSessionId === undefined || sourceSessionId === target.sessionId) + && (frameId === mainFrameIdsByTab.get(tabId) || frameId === target.targetInfo.targetId || !mainFrameIdsByTab.has(tabId)) + ) { + if (frameId !== undefined) { + mainFrameIdsByTab.set(tabId, frameId) + } + contextDebugLog?.(`main-frame-same-document frame=${boundedToken(frameId)} ${targetDiagnosticIdentity(target)} ${summarizeDiagnosticUrl(url)}`) + registry.updateTargetUrl(tabId, url) + } + } + if (method === "Page.lifecycleEvent") { + const frameId = getString(params, "frameId") + if (frameId && frameId === mainFrameIdsByTab.get(tabId)) { + contextDebugLog?.(`main-frame-lifecycle name=${boundedToken(getString(params, "name"))} frame=${boundedToken(frameId)} loader=${boundedToken(getString(params, "loaderId"))} ${targetDiagnosticIdentity(target)}`) + } + } + if (method === "Page.frameAttached") { + const frameId = getString(params, "frameId") + if (frameId && params) { + registry.rememberFrameEvent({ tabId, frameId, attached: params }) + } + } + if (method === "Page.frameDetached") { + const frameId = getString(params, "frameId") + if (frameId) { + registry.tabFrameEvents.get(tabId)?.delete(frameId) + } + } + + const eventSessionId = sourceSessionId ?? target.sessionId + const event: CdpEvent = { method, ...(params === undefined ? {} : { params }), sessionId: eventSessionId } + if (method === "Runtime.executionContextCreated") { + const context = getObject(params?.context) + const auxData = getObject(context?.auxData) + const contextTarget = targetForCdpSession(tabId, eventSessionId) + contextDebugLog?.(`context-created id=${boundedToken(getIdText(context, "id"))} unique=${boundedToken(getString(context, "uniqueId"))} default=${auxData?.isDefault === true} type=${boundedToken(getString(auxData, "type"))} frame=${boundedToken(getString(auxData, "frameId"))} ${targetDiagnosticIdentity(contextTarget)} ${summarizeDiagnosticUrl(getString(context, "origin"))}`) + const cursorPosition = ghostCursorPositionsByTab.get(tabId) + if (cursorPosition && auxData?.isDefault === true && auxData.frameId === mainFrameIdsByTab.get(tabId)) { + Effect.runPromise(Effect.ignore(sendDebuggerCommand({ + tabId, + method: "Runtime.evaluate", + params: { expression: ghostCursorRestoreExpression(cursorPosition) }, + }))).catch(() => {}) + } + } else if (method === "Runtime.executionContextDestroyed") { + const contextTarget = targetForCdpSession(tabId, eventSessionId) + contextDebugLog?.(`context-destroyed id=${boundedToken(getIdText(params, "executionContextId"))} unique=${boundedToken(getString(params, "executionContextUniqueId"))} ${targetDiagnosticIdentity(contextTarget)}`) + } else if (method === "Runtime.executionContextsCleared") { + contextDebugLog?.(`contexts-cleared ${targetDiagnosticIdentity(targetForCdpSession(tabId, eventSessionId))}`) + } + cdpRuntime.notify(event) + if (attachedChildTarget) { + announceAttachedChildTarget(target.sessionId, attachedChildTarget) + return + } + if (shouldBroadcast) { + sendEventToTargetViewers(target.sessionId, event) + } + } + + function handleToolbarClick(tabId: number): void { + const target = registry.tabTargets.get(tabId) + if (target) { + const sessionId = pageStatusSessionId(target) ?? activeHandoffSessionIdForTab(tabId) + const action = toolbarClickAction({ + handoffPending: handoffs.pendingForTab(tabId) !== undefined, + sessionExecuting: sessionId !== undefined && sessions.isExecuting(sessionId), + }) + if (action === "ignore") { + if (sessionId) { + console.error(`Ignored toolbar detach for tab ${tabId}: session ${sessionId} is executing`) + } + return + } + } + Effect.runPromise(toggleTab(tabId)).catch((error: unknown) => { + console.error("Toolbar toggle failed", error) + }) + } + + const handleCdpMessage = Effect.fnUntraced(function* (socket: WebSocket, raw: string) { + const message = parseJsonObject(raw) + if (!isCdpRequest(message)) { + return yield* Effect.fail(new Error("Invalid CDP request")) + } + + const frameTreeSent = message.method === "Page.getFrameTree" ? admitFrameTreeResponse(socket, message.sessionId) : undefined + debugLog?.(`cdp<- ${cdpClients.sessionId(socket) ?? "raw"} #${message.id} ${message.method} ${message.sessionId ?? ""}`) + yield* Effect.matchEffect(routeCdpCommand(socket, message), { + onFailure: (error) => { + return Effect.sync(() => { + const runtimeEvaluation = isRuntimeEvaluationMethod(message.method) + const errorDetail = runtimeEvaluation ? runtimeFailureKind(error) : error.message + debugLog?.(`cdp-> ${cdpClients.sessionId(socket) ?? "raw"} #${message.id} ${message.method} ERROR ${errorDetail}`) + if (runtimeEvaluation) { + contextDebugLog?.(`evaluation-failed method=${message.method} failure=${runtimeFailureKind(error)} client=${boundedToken(cdpClients.sessionId(socket) ?? "raw")} ${targetDiagnosticIdentity(diagnosticTargetForClient(socket, message.sessionId))} ${summarizeRuntimeEvaluate(message.params)}`) + } + sendCdpResponse(socket, { + id: message.id, + error: { message: error.message }, + ...(message.sessionId === undefined ? {} : { sessionId: message.sessionId }), + }) + }) + }, + onSuccess: (result) => { + return Effect.sync(() => { + debugLog?.(`cdp-> ${cdpClients.sessionId(socket) ?? "raw"} #${message.id} ${message.method} ok`) + const resultObject = getObject(result) + const exceptionDetails = isRuntimeEvaluationMethod(message.method) ? getObject(resultObject?.exceptionDetails) : undefined + if (exceptionDetails) { + contextDebugLog?.(`evaluation-exception method=${message.method} exceptionId=${boundedToken(getIdText(exceptionDetails, "exceptionId"))} line=${getNumber(exceptionDetails, "lineNumber") ?? "none"} column=${getNumber(exceptionDetails, "columnNumber") ?? "none"} client=${boundedToken(cdpClients.sessionId(socket) ?? "raw")} ${targetDiagnosticIdentity(diagnosticTargetForClient(socket, message.sessionId))} ${summarizeRuntimeEvaluate(message.params)}`) + } + sendCdpResponse(socket, { + id: message.id, + result, + ...(message.sessionId === undefined ? {} : { sessionId: message.sessionId }), + }) + frameTreeSent?.(result) + }) + }, + }) + }) + + /** A client can keep using a session only while it still routes to a visible target. */ + function clientRoutesSession(socket: WebSocket, sessionId: string): boolean { + return socket.readyState === WebSocket.OPEN && cdpRouter.session(socket, sessionId) !== undefined + } + + /** Canonical sessions may later receive cached Runtime replay; aliases keep the native path. */ + function admitFrameTreeResponse(socket: WebSocket, sessionId: string | undefined): ((result: unknown) => void) | undefined { + if (sessionId === undefined || !cdpClients.hasSession(socket, sessionId)) return undefined + const route = cdpRouter.session(socket, sessionId) + // Detaching the announcement retires the requester through the client pool. + return route && cdpRuntime.frameTreeResponse(socket, route, () => clientRoutesSession(socket, sessionId)) + } + + const routeCdpCommand = Effect.fn("Relay.routeCdpCommand")(function* (socket: WebSocket, message: CdpRequest) { + const clientOpenCodeBrowserSessionId = cdpClients.sessionId(socket) + if (!shutdownControl.accepting && (!cdpClients.isSandbox(socket) || !clientOpenCodeBrowserSessionId || !sessions.hasPendingWork(clientOpenCodeBrowserSessionId))) { + return yield* Effect.fail(new Error("Relay is draining for an explicit restart")) + } + const guardMessage = guardCdpMethod({ + method: message.method, + readOnly: clientOpenCodeBrowserSessionId ? sessions.isReadOnly(clientOpenCodeBrowserSessionId) : false, + sessionId: clientOpenCodeBrowserSessionId, + }) + if (guardMessage) { + return yield* Effect.fail(new Error(guardMessage)) + } + if (message.method === "Browser.getVersion") { + return { + protocolVersion: "1.3", + product: "OpenCode-Browser/0.0.0", + revision: "0", + userAgent: "OpenCode-Browser", + jsVersion: "V8", + } + } + if (message.method === "Browser.setDownloadBehavior") { + return {} + } + if (message.method === "Target.setDiscoverTargets") { + if (message.params?.discover === true) { + replayTargetCreated({ socket, targetInfos: cdpRouter.visibleTargetInfos(socket) }) + } + return {} + } + if (message.method === "Target.setAutoAttach" && !message.sessionId) { + cdpClients.setAutoAttachParams(socket, message.params) + for (const target of cdpRouter.visibleRoots(socket)) { + yield* Effect.ignore(sendDebuggerCommand({ tabId: target.tabId, method: "Target.setAutoAttach", params: message.params ?? {} })) + cdpClients.announce(socket, target) + } + return {} + } + if (message.method === "Target.setAutoAttach" && message.sessionId && registry.targets.has(message.sessionId)) { + const target = cdpRouter.rootForSession(socket, message.sessionId) + if (!target) { + return yield* Effect.fail(new Error(`Target not found: ${message.sessionId}`)) + } + const result = yield* sendDebuggerCommand({ tabId: target.tabId, method: "Target.setAutoAttach", params: message.params ?? {} }) + replayChildTargetsForParent({ socket, parentSessionId: target.sessionId, registry, clients: cdpClients }) + return result + } + if (message.method === "Target.getTargets") { + return { + targetInfos: cdpRouter.visibleTargetInfos(socket), + } + } + if (message.method === "Target.attachToBrowserTarget") { + return { sessionId: cdpClients.createBrowserAlias(socket) } + } + if (message.method === "Target.attachToTarget") { + const targetId = getString(message.params, "targetId") ?? "" + const target = cdpRouter.targetForAttach(socket, targetId) + if (target) { + if (cdpClients.hasSession(socket, target.sessionId)) { + return { sessionId: cdpClients.createTargetAlias(socket, target) } + } + cdpClients.announce(socket, target) + if ("parentSessionId" in target) replayChildFrameNavigation({ socket, registry, target }) + return { sessionId: target.sessionId } + } + return yield* Effect.fail(new Error(`Target not found: ${targetId}`)) + } + if (message.method === "Target.getTargetInfo") { + const targetId = getString(message.params, "targetId") ?? "" + const target = cdpRouter.targetInfo(socket, { + ...(targetId ? { targetId } : {}), + ...(message.sessionId ? { sessionId: message.sessionId } : {}), + }) + if (!target) { + if (!targetId && !message.sessionId) { + return {} + } + return yield* Effect.fail(new Error(`Target not found: ${targetId || message.sessionId || "unknown"}`)) + } + return { targetInfo: target.targetInfo } + } + if (message.method === "Target.createTarget" || message.method === "Target.closeTarget") { + if (message.method === "Target.createTarget") { + const url = getString(message.params, "url") ?? "about:blank" + const opencodeBrowserSessionId = cdpClients.sessionId(socket) + const autoAttachParams = cdpClients.autoAttachParams(socket) + const target = yield* createAndAttachTab({ + url, + active: false, + ...(opencodeBrowserSessionId ? { opencodeBrowserSessionId } : {}), + ...(autoAttachParams ? { autoAttachParams } : {}), + }) + return { targetId: target.targetInfo.targetId } + } + const targetId = getString(message.params, "targetId") ?? "" + const target = cdpRouter.targetForAttach(socket, targetId) + if (!target || !("owner" in target)) { + return { success: false } + } + yield* closeTargetByTargetId(targetId) + return { success: true } + } + if (message.method === "Target.detachFromTarget") { + const childSessionId = getString(message.params, "sessionId") + if (childSessionId) cdpClients.detach(socket, childSessionId) + return {} + } + const normalizedMessage = removeDefaultLightColorSchemeEmulation(message) + const route = yield* Effect.try({ + try: () => cdpRouter.resolveCommandRoute(socket, message), + catch: (error) => error instanceof Error ? error : new Error(String(error)), + }) + const { tabId } = route + const command = { + tabId, + method: normalizedMessage.method, + params: normalizedMessage.params ?? {}, + ...(route.chromeSessionId === undefined ? {} : { sessionId: route.chromeSessionId }), + } + const sessionId = message.sessionId + const announced = sessionId !== undefined && cdpClients.hasSession(socket, sessionId) + // The visible cursor animates while the human-like movement leading up to the event is sent. + yield* Effect.all([ + applyGhostCursorMouseEvent({ tabId, message }).pipe(Effect.ignore), + Effect.promise(() => + beforeInput(tabId, command.method, command.params, route.chromeSessionId === undefined, (method, params) => + Effect.runPromise(sendDebuggerCommand({ ...command, method, params })), + ).catch(() => undefined), + ), + ], { concurrency: "unbounded", discard: true }) + const result = yield* (message.method === "Runtime.enable" && sessionId + ? cdpRuntime.enable(route, command.params, () => clientRoutesSession(socket, sessionId) && (!announced || cdpClients.hasSession(socket, sessionId)), announced ? socket : undefined) + : sendDebuggerCommand(command)).pipe( + // Chrome rejects every command for a tab while another extension's frame + // is open in it; clients only see the rejection, so record it per tab. + Effect.tapError((error) => Effect.sync(() => { + if (runtimeFailureKind(error) === "cross-extension-page") setProtectedUi(tabId, true) + })), + Effect.tap(() => Effect.sync(() => setProtectedUi(tabId, false))), + ) + return result + }) + + const toggleTab = Effect.fnUntraced(function* (tabId: number) { + if (registry.tabTargets.has(tabId)) { + yield* sendToExtension({ method: "debugger.detach", params: { tabId } }) + detachTargetState(tabId) + yield* Effect.ignore(sendToExtension({ method: "action.setAttached", params: { tabId, attached: false } })) + return + } + currentAnnouncedRootTabIds?.add(tabId) + yield* rootLifecycle.attach({ tabId, owner: "user" }) + }) + + const createAndAttachTab = Effect.fnUntraced(function* (options: { + readonly url: string + readonly active: boolean + readonly opencodeBrowserSessionId?: string + readonly autoAttachParams?: JsonObject + }) { + const result = yield* sendToExtension({ method: "tabs.create", params: { url: options.url, active: options.active } }) + const tabId = getNumber(result, "tabId") + if (!tabId) { + return yield* Effect.fail(new Error("tabs.create did not return a tabId")) + } + currentAnnouncedRootTabIds?.add(tabId) + return yield* rootLifecycle.attach({ + tabId, + owner: "relay", + ...(options.opencodeBrowserSessionId ? { opencodeBrowserSessionId: options.opencodeBrowserSessionId } : {}), + ...(options.autoAttachParams ? { autoAttachParams: options.autoAttachParams } : {}), + }) + }) + + const rootLifecycle = yield* RootTargetLifecycle.make({ + registry, + sessions, + handoffs, + clients: cdpClients, + extension: { generation: () => extensionGeneration, send: sendToExtension }, + presentation: { + replaced: recordRootReplacement, + committed: presentAttachedTarget, + announceRoot: announceAttachedTarget, + announceChild: announceAttachedChildTarget, + }, + reportError: (message, error) => console.error(message, error), + }) + + function presentAttachedTarget(committedTarget: ConnectedTarget): void { + const tabId = committedTarget.tabId + mainFrameIdsByTab.set(tabId, committedTarget.targetInfo.targetId) + contextDebugLog?.(`target-attached kind=root ${targetDiagnosticIdentity(committedTarget)} ${summarizeDiagnosticUrl(committedTarget.targetInfo.url)}`) + if (committedTarget.opencodeBrowserSessionId) { + pruneInvisibleAnnouncementsForSession(committedTarget.opencodeBrowserSessionId) + } + if (extensionRpc.connected) { + refreshTabGrouping(tabId) + } + const pendingHandoff = handoffs.pendingForTab(tabId) + if (pendingHandoff) { + setActivityForTarget(committedTarget, "waiting", waitingBadge(pendingHandoff.message), { + sessionId: pendingHandoff.sessionId, + message: pendingHandoff.message, + handoffId: pendingHandoff.id, + }) + } else { + sendPageStatus(committedTarget, committedTarget.opencodeBrowserSessionId && sessions.isExecuting(committedTarget.opencodeBrowserSessionId) ? "running" : "attached") + } + } + + const applyGhostCursorMouseEvent = Effect.fnUntraced(function* (options: { readonly tabId: number; readonly message: CdpRequest }) { + if (options.message.method !== "Input.dispatchMouseEvent") { + return + } + const action = inputDispatchMouseEventToGhostCursorAction(options.message.params) + if (!action) { + return + } + ghostCursorPositionsByTab.set(options.tabId, { x: action.x, y: action.y }) + yield* sendDebuggerCommand({ + tabId: options.tabId, + method: "Runtime.evaluate", + params: { expression: ghostCursorMouseActionExpression(action), awaitPromise: true }, + }).pipe(Effect.timeout("2 seconds"), Effect.ignore) + }) + + function clearTabRuntimeState(tabId: number): void { + mainFrameIdsByTab.delete(tabId) + protectedFrames.forgetTab(tabId) + ghostCursorPositionsByTab.delete(tabId) + forgetTab(tabId) + for (const [sessionId, childTabId] of suppressedChildSessions) { + if (childTabId === tabId) { + suppressedChildSessions.delete(sessionId) + } + } + } + + function detachTargetState(tabId: number, options: { + readonly preserveSessionTarget?: boolean + readonly updateExtension?: boolean + } = {}): void { + rootLifecycle.invalidate(tabId) + if (options.updateExtension !== false) { + sendExtensionBestEffort({ method: "pageStatus.clear", params: { tabId } }) + scheduleTabGrouping(tabId, "tabs.ungroup") + sendExtensionBestEffort({ method: "action.setAttached", params: { tabId, attached: false } }) + void recordingRelay.abortRecordingForTab({ tabId, reason: "Tab detached" }).catch((error: unknown) => { + console.error("Failed to abort recording for detached tab", error) + }) + void flightRecorder.cancel({ tabId }).catch((error: unknown) => { + console.error("Failed to stop flight recorder for detached tab", error) + }) + } + const detached = registry.detachRootTargetState(tabId) + if (detached) { + cancelTargetHandoffs(detached.target, "target-detached") + if (!options.preserveSessionTarget) sessions.markTargetDetached(detached.target.targetInfo.targetId) + contextDebugLog?.(`target-detached kind=root ${targetDiagnosticIdentity(detached.target)}`) + } + // A staged-only root has no committed target but may already own tab-scoped relay state. + cdpClients.detachTab(tabId, { destroyed: true }) + clearTabRuntimeState(tabId) + } + + function recordRootReplacement(change: Extract): void { + clearTabRuntimeState(change.target.tabId) + contextDebugLog?.(`target-replaced kind=root old=${targetDiagnosticIdentity(change.previous)} new=${targetDiagnosticIdentity(change.target)}`) + } + + function detachChildTargetState(sessionId: string): void { + const detached = registry.detachChildTargetState(sessionId) + if (detached) { + cdpClients.detachTarget(detached) + } + } + + // Deliver a session-scoped event only to clients that have been told about + // the tab's root target. Broadcasting to every client lets concurrently + // connected sandboxes attach to each other's pages and interfere. + function sendEventToTargetViewers(rootSessionId: string, event: CdpEvent): void { + cdpClients.sendToViewers(rootSessionId, event, (client, tabId) => cdpRouter.canSeeTab(client, tabId)) + } + + function pruneInvisibleAnnouncementsForSession(opencodeBrowserSessionId: string): void { + for (const client of cdpClients) { + if (cdpClients.sessionId(client) === opencodeBrowserSessionId) { + cdpRouter.reconcileClient(client) + } + } + } + + function reconcileTargetOwnership(change: TargetOwnershipChange): void { + for (const client of cdpClients) { + cdpRouter.reconcileClient(client) + } + for (const targetId of change.targetIds) { + const target = registry.targetsByTargetId.get(targetId) + if (target) { + announceAttachedTarget(target) + } + } + for (const tabId of change.tabIds) { + refreshTabPresentation(tabId) + } + } + + function announceAttachedTarget(target: ConnectedTarget): void { + for (const client of cdpClients) { + if (cdpRouter.canSeeTarget(client, target)) { + cdpClients.announce(client, target) + } + } + } + + function announceAttachedChildTarget(rootSessionId: string, target: ChildTarget): void { + for (const client of cdpClients) { + if (cdpClients.hasSession(client, rootSessionId) && cdpRouter.canSeeTab(client, target.tabId)) { + cdpClients.announce(client, target) + } + } + } + + yield* Effect.catch(listenHttpServer({ server: httpServer, host, port }), (error) => { + return Effect.gen(function* () { + yield* cleanup() + return yield* Effect.fail(error) + }) + }) + + yield* Effect.catch( + Effect.gen(function* () { + const restoredSessions = yield* Effect.tryPromise({ + try: () => sessionCatalog?.load() ?? Promise.resolve([]), + catch: (cause) => cause instanceof Error ? cause : new Error("Load OpenCode Browser session catalog", { cause }), + }) + yield* Effect.try({ + try: () => sessions.restore(restoredSessions), + catch: (cause) => cause instanceof Error ? cause : new Error("Restore OpenCode Browser sessions", { cause }), + }) + catalogWritesEnabled = true + if (managed) { + yield* audit(yield* RelayLifecycleEvent.cases.Ready.makeEffect({ + instanceId: browserId, + buildId: opencodeBrowserBuildId, + ...(Option.isSome(restartRequestId) ? { restartRequestId: restartRequestId.value } : {}), + })) + } + relayReady = true + relayLog("relay.ready", { url: endpointUrl, version: opencodeBrowserVersion, build: opencodeBrowserBuildId, pid: process.pid, managed }) + }), + (error) => Effect.gen(function* () { + yield* cleanup() + return yield* Effect.fail(error) + }), + ) + + return { + url: endpointUrl, + close: () => { + return close + }, + } +}) + +function sendUpgradeError(options: { + readonly socket: stream.Duplex + readonly status: 400 | 403 | 404 | 503 + readonly message: string +}): void { + const statusText = http.STATUS_CODES[options.status] ?? "Error" + options.socket.write( + `HTTP/1.1 ${options.status} ${statusText}\r\ncontent-type: text/plain; charset=utf-8\r\nconnection: close\r\n\r\n${options.message}`, + ) + options.socket.destroy() +} + +function rawDataToBuffer(data: RawData): Buffer { + if (Buffer.isBuffer(data)) { + return data + } + if (Array.isArray(data)) { + return Buffer.concat(data) + } + return Buffer.from(data) +} diff --git a/packages/browser-extension/cli/src/root-target-lifecycle.ts b/packages/browser-extension/cli/src/root-target-lifecycle.ts new file mode 100644 index 00000000000..4b337135cb1 --- /dev/null +++ b/packages/browser-extension/cli/src/root-target-lifecycle.ts @@ -0,0 +1,341 @@ +import { Effect, Exit, Latch, Schedule, Schema, Scope, Semaphore } from "effect" +import type { CdpClientPool } from "./cdp-client-pool.ts" +import { ghostCursorClientSource } from "./ghost-cursor.ts" +import type { HandoffRegistry } from "./handoff.ts" +import type { ExtensionCommand, JsonObject } from "./protocol.ts" +import { getTargetInfo } from "./relay-helpers.ts" +import type { ChildTarget, ConnectedTarget } from "./relay-types.ts" +import type { OpenCodeBrowserSessions } from "./session-manager.ts" +import { shouldExposeChildTarget, type RootTargetChange, type TargetRegistry } from "./target-registry.ts" + +type AttachOptions = { + readonly tabId: number + readonly owner: "relay" | "user" + readonly opencodeBrowserSessionId?: string + readonly alreadyAttached?: boolean + readonly expectedExtensionGeneration?: number + readonly autoAttachParams?: JsonObject +} + +type Options = { + readonly registry: TargetRegistry + readonly sessions: Pick + readonly handoffs: Pick + readonly clients: Pick, "detachTab"> + readonly extension: { + readonly generation: () => number + readonly send: (command: Omit) => Effect.Effect + } + readonly presentation: { + readonly replaced: (change: Extract) => void + readonly committed: (target: ConnectedTarget) => void + readonly announceRoot: (target: ConnectedTarget) => void + readonly announceChild: (rootSessionId: string, target: ChildTarget) => void + } + readonly reportError: (message: string, error: unknown) => void +} + +type TabWork = { readonly semaphore: Semaphore.Semaphore; revision: number; users: number } +type Transition = { + readonly tabId: number + readonly generation: number + readonly work: TabWork + readonly revision: number + root: ConnectedTarget | undefined + staged: ConnectedTarget | undefined +} +type Worker = { + readonly generation: number + readonly done: Latch.Latch + attachIfMissing: boolean + pending: boolean + verificationRetries: number +} + +class GenerationChanged extends Schema.TaggedError()("RootTargetLifecycle.GenerationChanged", { + message: Schema.String, +}) {} + +/** Owns root setup and replacement, not target ownership or client announcement indexes. */ +export class RootTargetLifecycle { + static readonly make = Effect.fn("RootTargetLifecycle.make")(function* (options: Options) { + const scope = yield* Scope.make() + const run = Effect.runForkWith(yield* Effect.context()) + return yield* Effect.acquireRelease( + Effect.sync(() => new RootTargetLifecycle(options, scope, run)), + (lifecycle) => lifecycle.close(), + ) + }) + + private readonly tabs = new Map() + private readonly workers = new Map() + private readonly idle = Latch.makeUnsafe(true) + private active = 0 + private closing = false + private readonly failedTabs = new Map() + private nextSessionId = 1 + + private constructor( + private readonly options: Options, + private readonly scope: Scope.Closeable, + private readonly run: ReturnType>, + ) {} + + isIdle(): boolean { + return this.active === 0 && this.workers.size === 0 + } + + /** Invalidate in-flight work before removing a tab, including a not-yet-staged attach. */ + invalidate(tabId: number): void { + const work = this.tabs.get(tabId) + if (work) work.revision += 1 + this.failedTabs.delete(tabId) + } + + readonly attach = Effect.fn("RootTargetLifecycle.attach")((options: AttachOptions) => + this.withPermit(options.tabId, options.expectedExtensionGeneration, (transition) => this.attachUnlocked(transition, options))) + + readonly reconcile = Effect.fn("RootTargetLifecycle.reconcile")((tabId: number, generation?: number) => + this.withPermit(tabId, generation, (transition) => this.reconcileUnlocked(transition))) + + queue(options: { + readonly tabId: number + readonly attachIfMissing: boolean + readonly verificationRetries: number + readonly errorMessage: string + readonly generation?: number + }): void { + if (this.closing) return + const lifecycle = this + const generation = options.generation ?? this.options.extension.generation() + if (generation !== this.options.extension.generation()) return + for (const [tabId, failedGeneration] of this.failedTabs) { + if (failedGeneration !== generation) this.failedTabs.delete(tabId) + } + const work = this.tabWork(options.tabId) + const revision = work.revision + const key = `${generation}:${options.tabId}:${revision}` + const existing = this.workers.get(key) + if (existing) { + existing.pending = true + existing.attachIfMissing ||= options.attachIfMissing + existing.verificationRetries = Math.max(existing.verificationRetries, options.verificationRetries) + return + } + work.users += 1 + const worker: Worker = { + generation, + done: Latch.makeUnsafe(), + attachIfMissing: options.attachIfMissing, + pending: false, + verificationRetries: options.verificationRetries, + } + this.workers.set(key, worker) + const pass = Effect.gen(function* () { + worker.pending = false + const mayAttach = worker.attachIfMissing + worker.attachIfMissing = false + yield* Effect.suspend(() => { + if (revision !== work.revision) return new GenerationChanged({ message: "Tab detached during root reconciliation" }) + return lifecycle.withPermit(options.tabId, generation, (transition) => { + if (lifecycle.options.registry.routingRootTarget(options.tabId)) return lifecycle.reconcileUnlocked(transition) + return mayAttach + ? lifecycle.attachUnlocked(transition, { tabId: options.tabId, owner: "user", alreadyAttached: true }).pipe(Effect.asVoid) + : Effect.void + }) + }).pipe( + Effect.tapError((error) => Effect.sync(() => lifecycle.options.reportError(options.errorMessage, error))), + Effect.retry({ + times: 2, + schedule: Schedule.spaced(0).pipe(Schedule.modifyDelay(({ attempt }) => Effect.succeed(100 * attempt))), + while: (error) => !(error instanceof GenerationChanged) && !lifecycle.closing && generation === lifecycle.options.extension.generation() && revision === work.revision, + }), + ) + if (lifecycle.closing || generation !== lifecycle.options.extension.generation()) return null + if (worker.verificationRetries > 0) { + const delay = 50 * (4 - worker.verificationRetries) + worker.verificationRetries -= 1 + return delay + } + return worker.pending ? 0 : null + }).pipe( + Effect.repeat({ + while: (delay) => delay !== null && !lifecycle.closing, + schedule: Schedule.spaced(0).pipe( + Schedule.setInputType(), + Schedule.modifyDelay(({ input }) => Effect.succeed(input ?? 0)), + ), + }), + Effect.onExit((exit) => Effect.sync(() => { + if (generation === lifecycle.options.extension.generation() && revision === work.revision) { + if (Exit.isFailure(exit)) lifecycle.failedTabs.set(options.tabId, generation) + else lifecycle.failedTabs.delete(options.tabId) + } + lifecycle.workers.delete(key) + if (--work.users === 0 && !lifecycle.options.registry.routingRootTarget(options.tabId)) lifecycle.tabs.delete(options.tabId) + worker.done.openUnsafe() + })), + ) + // The scope is closed only after settlement; queued browser work is never interrupted by drain. + this.run(pass.pipe(Effect.forkIn(this.scope))) + } + + /** Readiness retains failed inventory results even when a worker finished before `ready`. */ + readonly settle = Effect.fn("RootTargetLifecycle.settle")(function* (this: RootTargetLifecycle, generation?: number) { + while (true) { + const workers = Array.from(this.workers.values()).filter((worker) => generation === undefined || worker.generation === generation) + yield* Effect.forEach(workers, (worker) => worker.done.await, { concurrency: "unbounded", discard: true }) + if (generation === undefined) yield* this.idle.await + if (!Array.from(this.workers.values()).some((worker) => generation === undefined || worker.generation === generation)) break + } + return generation === undefined || (generation === this.options.extension.generation() && !Array.from(this.failedTabs.values()).includes(generation)) + }) + + readonly close = Effect.fn("RootTargetLifecycle.close")(function* (this: RootTargetLifecycle) { + this.closing = true + yield* this.settle() + yield* Scope.close(this.scope, Exit.void) + this.tabs.clear() + }) + + private withPermit(tabId: number, expectedGeneration: number | undefined, use: (transition: Transition) => Effect.Effect): Effect.Effect { + const lifecycle = this + return Effect.suspend(() => { + if (lifecycle.closing) return Effect.fail(new Error("Relay is closing")) + const generation = expectedGeneration ?? lifecycle.options.extension.generation() + const work = lifecycle.tabWork(tabId) + const revision = work.revision + work.users += 1 + lifecycle.active += 1 + lifecycle.idle.closeUnsafe() + return work.semaphore.withPermit(Effect.suspend(() => { + const transition: Transition = { + tabId, generation, work, revision, + root: lifecycle.options.registry.tabTargets.get(tabId), + staged: lifecycle.options.registry.stagedRootTarget(tabId), + } + return lifecycle.check(transition).pipe(Effect.andThen(() => use(transition))) + })).pipe(Effect.ensuring(Effect.sync(() => { + if (--work.users === 0 && !lifecycle.options.registry.routingRootTarget(tabId)) lifecycle.tabs.delete(tabId) + if (--lifecycle.active === 0) lifecycle.idle.openUnsafe() + }))) + }) + } + + private tabWork(tabId: number): TabWork { + const work = this.tabs.get(tabId) ?? { semaphore: Semaphore.makeUnsafe(1), revision: 0, users: 0 } + this.tabs.set(tabId, work) + return work + } + + private readonly check = Effect.fnUntraced(function* (this: RootTargetLifecycle, transition: Transition) { + const { registry, extension } = this.options + const root = registry.tabTargets.get(transition.tabId) + const staged = registry.stagedRootTarget(transition.tabId) + if ( + transition.generation !== extension.generation() || transition.revision !== transition.work.revision || + transition.root?.sessionId !== root?.sessionId || transition.root?.targetInfo.targetId !== root?.targetInfo.targetId || + transition.staged?.sessionId !== staged?.sessionId || transition.staged?.targetInfo.targetId !== staged?.targetInfo.targetId + ) return yield* new GenerationChanged({ message: "Root target generation changed during reconciliation" }) + }) + + private step(transition: Transition, effect: Effect.Effect): Effect.Effect { + return this.check(transition).pipe( + Effect.andThen(effect), + Effect.catch((error) => this.check(transition).pipe(Effect.andThen(Effect.fail(error)))), + Effect.tap(() => this.check(transition)), + ) + } + + private command(transition: Transition, method: string, params: JsonObject = {}): Effect.Effect { + return this.step(transition, this.options.extension.send({ method: "debugger.sendCommand", params: { tabId: transition.tabId, method, params } })) + } + + private readonly attachUnlocked = Effect.fnUntraced(function* (this: RootTargetLifecycle, transition: Transition, options: AttachOptions) { + const { tabId } = transition + if (!options.alreadyAttached) yield* this.step(transition, this.options.extension.send({ method: "debugger.attach", params: { tabId } })) + yield* this.command(transition, "Page.enable") + yield* Effect.gen({ self: this }, function* () { + yield* this.command(transition, "Emulation.setFocusEmulationEnabled", { enabled: true }) + yield* this.command(transition, "Page.addScriptToEvaluateOnNewDocument", { source: ghostCursorClientSource }) + yield* this.command(transition, "Runtime.evaluate", { expression: ghostCursorClientSource }) + }).pipe(Effect.ignore) + yield* this.check(transition) + const result = yield* this.command(transition, "Target.getTargetInfo") + const targetInfo = getTargetInfo(result.targetInfo) + if (!targetInfo) return yield* Effect.fail(new Error("Target.getTargetInfo did not return targetInfo")) + const restored = options.opencodeBrowserSessionId ? undefined : this.options.sessions.persistedTargetOwner(targetInfo.targetId) + const opencodeBrowserSessionId = options.opencodeBrowserSessionId ?? restored?.sessionId + const target = this.options.registry.stageRootTarget({ + tabId, + sessionId: `bc-tab-${this.nextSessionId++}`, + targetInfo, + owner: restored?.owner ?? options.owner, + ...(opencodeBrowserSessionId ? { opencodeBrowserSessionId } : {}), + }) + transition.staged = target + return yield* this.finish(transition, target, options.autoAttachParams) + }) + + private readonly reconcileUnlocked = Effect.fnUntraced(function* (this: RootTargetLifecycle, transition: Transition) { + const { registry } = this.options + const expected = registry.tabTargets.get(transition.tabId) + const staged = registry.stagedRootTarget(transition.tabId) + if (!expected && !staged) return + const result = yield* this.command(transition, "Target.getTargetInfo").pipe( + Effect.retry({ times: 1, schedule: Schedule.spaced(50), while: (error) => !(error instanceof GenerationChanged) }), + ) + yield* this.check(transition) + const targetInfo = getTargetInfo(result.targetInfo) + if (!targetInfo) { + return yield* Effect.fail(new Error(staged ? "Unable to verify staged root target" : "Unable to verify committed root target")) + } + if (staged?.targetInfo.targetId === targetInfo.targetId) { + yield* this.finish(transition, staged) + return + } + if (!staged && expected?.targetInfo.targetId === targetInfo.targetId) return + const owner = expected ?? staged + if (!owner) return + yield* this.attachUnlocked(transition, { + tabId: transition.tabId, owner: owner.owner, alreadyAttached: true, + ...(owner.opencodeBrowserSessionId ? { opencodeBrowserSessionId: owner.opencodeBrowserSessionId } : {}), + }) + }) + + private readonly finish = Effect.fnUntraced(function* (this: RootTargetLifecycle, transition: Transition, target: ConnectedTarget, autoAttachParams?: JsonObject) { + const { registry, handoffs, sessions, clients, presentation } = this.options + // Stage before auto-attach: synchronous child events must route to this generation. + yield* this.command(transition, "Target.setAutoAttach", autoAttachParams ?? { autoAttach: true, waitForDebuggerOnStart: false, flatten: true }) + const result = yield* this.command(transition, "Target.getTargetInfo") + if (getTargetInfo(result.targetInfo)?.targetId !== target.targetInfo.targetId) { + return yield* Effect.fail(new Error(`Root target changed while preparing ${target.targetInfo.targetId}`)) + } + const change = registry.commitStagedRootTarget(target.tabId, target.sessionId) + if (!change) return yield* Effect.fail(new Error(`Staged root target changed before commit: ${target.targetInfo.targetId}`)) + transition.root = change.target + transition.staged = undefined + if (change.kind === "replaced") { + handoffs.rebindTarget({ + tabId: target.tabId, + previousTargetId: change.previous.targetInfo.targetId, + previousTargetSessionId: change.previous.sessionId, + targetId: change.target.targetInfo.targetId, + targetSessionId: change.target.sessionId, + }) + sessions.markTargetReplaced(change.previous.targetInfo.targetId, change.target.targetInfo.targetId) + clients.detachTab(target.tabId) + presentation.replaced(change) + } + // No asynchronous gap between retiring old views and publishing the committed tree. + presentation.committed(change.target) + presentation.announceRoot(change.target) + for (const child of registry.childTargets.values()) { + if (child.tabId === target.tabId && child.parentSessionId === change.target.sessionId && shouldExposeChildTarget(child)) { + presentation.announceChild(change.target.sessionId, child) + } + } + yield* this.step(transition, this.options.extension.send({ method: "action.setAttached", params: { tabId: target.tabId, attached: true } }).pipe(Effect.ignore)) + return change.target + }) +} diff --git a/packages/browser-extension/cli/src/runtime-diagnostics.ts b/packages/browser-extension/cli/src/runtime-diagnostics.ts new file mode 100644 index 00000000000..6a03fc148f2 --- /dev/null +++ b/packages/browser-extension/cli/src/runtime-diagnostics.ts @@ -0,0 +1,112 @@ +import crypto from "node:crypto" +import { Predicate } from "effect" +import { PageReadTimeoutError } from "./page-read-timeout.ts" +import { getIdText, getString } from "./relay-helpers.ts" +import type { ExecuteAftermath } from "./relay-schema.ts" +import type { JsonObject } from "./protocol.ts" + +export type RuntimeFailureKind = "context-destroyed" | "context-missing" | "cross-extension-page" | "target-closed" | "timeout" | "other" + +const maxDiagnosticTokenLength = 48 + +export function runtimeFailureKind(cause: unknown): RuntimeFailureKind { + for (const message of errorMessages(cause)) { + if (/cannot access a chrome-extension:\/\/ url of different extension/i.test(message)) { + return "cross-extension-page" + } + if (/execution context was destroyed|context.*destroyed/i.test(message)) { + return "context-destroyed" + } + if (/cannot find context with (?:specified )?id|execution context.*(?:not found|not available|does not exist)|context.*detached frame|frame (?:was|got) detached/i.test(message)) { + return "context-missing" + } + if (/target page, context or browser has been closed|target closed|session closed/i.test(message)) { + return "target-closed" + } + if (/timed out|timeout/i.test(message)) { + return "timeout" + } + } + return "other" +} + +export function executionContextFailureDiagnostic(cause: unknown, aftermath: ExecuteAftermath | undefined): string | undefined { + const kind = runtimeFailureKind(cause) + if (kind === "cross-extension-page") { + return "target/cross-extension-page" + } + for (const error of errorCauses(cause)) { + if (error instanceof PageReadTimeoutError) { + // This is read-deadline evidence, not a lost context requiring page recovery. + return `session-page/context-read-timeout; operation=${error.operation}; timeoutMs=${error.timeoutMs}` + } + } + if (kind !== "context-destroyed" && kind !== "context-missing") { + return undefined + } + const pageClosed = aftermath?.endUrl === null + const urlChanged = aftermath ? aftermath.startUrl !== aftermath.endUrl : false + const navigationCount = aftermath?.navigations.length ?? 0 + return `execution-context/${kind}; pageClosed=${pageClosed}; urlChanged=${urlChanged}; mainFrameNavigations=${navigationCount}` +} + +export function summarizeDiagnosticUrl(value: string | undefined): string { + if (!value) { + return "url=none" + } + const fingerprint = crypto.createHash("sha256").update(value).digest("hex").slice(0, 12) + try { + const parsed = new URL(value) + const pathSegments = parsed.pathname.split("/").filter(Boolean).length + const origin = parsed.origin === "null" ? `${parsed.protocol}//` : parsed.origin + return `origin=${boundedToken(origin)} pathSegments=${pathSegments} query=${parsed.search ? "yes" : "no"} fragment=${parsed.hash ? "yes" : "no"} urlHash=${fingerprint}` + } catch { + return `url=unparseable chars=${value.length} urlHash=${fingerprint}` + } +} + +export function summarizeRuntimeEvaluate(params: JsonObject | undefined): string { + const source = getString(params, "expression") ?? getString(params, "functionDeclaration") + const sourceLength = source?.length ?? 0 + const rawContextId = getIdText(params, "contextId") ?? getIdText(params, "executionContextId") + const contextId = rawContextId !== undefined ? boundedToken(rawContextId) : "default" + return [ + `sourceChars=${sourceLength}`, + `argumentCount=${Array.isArray(params?.arguments) ? params.arguments.length : 0}`, + `context=${contextId}`, + `awaitPromise=${params?.awaitPromise === true}`, + `returnByValue=${params?.returnByValue === true}`, + `userGesture=${params?.userGesture === true}`, + ].join(" ") +} + +export function boundedToken(value: string | undefined): string { + if (!value) { + return "none" + } + const normalized = value.replace(/[^a-zA-Z0-9:._/-]/g, "_") + if (normalized.length <= maxDiagnosticTokenLength) { + return normalized + } + return `${normalized.slice(0, maxDiagnosticTokenLength - 9)}~${crypto.createHash("sha256").update(value).digest("hex").slice(0, 8)}` +} + +function errorMessages(cause: unknown): string[] { + return errorCauses(cause).flatMap((error) => error instanceof Error ? [error.message] : Predicate.isString(error) ? [error] : []) +} + +function errorCauses(cause: unknown): unknown[] { + const causes: unknown[] = [] + const seen = new Set() + let current = cause + for (let depth = 0; depth < 5 && current !== undefined && current !== null && !seen.has(current); depth++) { + seen.add(current) + causes.push(current) + if (current instanceof Error) { + current = current.cause + continue + } + break + } + return causes +} diff --git a/packages/browser-extension/cli/src/screenshot-diff.ts b/packages/browser-extension/cli/src/screenshot-diff.ts new file mode 100644 index 00000000000..11d0f08c203 --- /dev/null +++ b/packages/browser-extension/cli/src/screenshot-diff.ts @@ -0,0 +1,104 @@ +import fs from "node:fs/promises" +import path from "node:path" +import { Predicate } from "effect" +import pixelmatch from "pixelmatch" +import { PNG } from "pngjs" +import type { Page } from "patchright-core" + +const maxImageBytes = 32 * 1024 * 1024 +const maxImagePixels = 16 * 1024 * 1024 +const pngSignature = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]) + +export type ScreenshotDiffOptions = { + readonly baseline: string | Buffer + readonly path?: string + /** Per-pixel perceptual color threshold, 0..1. Not a changed-area allowance. */ + readonly threshold?: number + readonly fullPage?: boolean +} + +export type ScreenshotDiffResult = { + readonly matches: boolean + readonly width: number + readonly height: number + readonly changedPixels: number + readonly totalPixels: number + readonly changedRatio: number + readonly threshold: number + readonly image?: Buffer + readonly path?: string +} + +export function createScreenshotDiff(page: Pick): (options: ScreenshotDiffOptions) => Promise { + return async (options) => { + const threshold = validateThreshold(options.threshold ?? 0.1) + if (options.path !== undefined && (!path.isAbsolute(options.path) || path.extname(options.path).toLowerCase() !== ".png")) { + throw new Error("screenshotDiff output path must be an absolute .png path") + } + const baseline = Predicate.isString(options.baseline) ? await readBaseline(options.baseline) : options.baseline + const before = decodePng(baseline) + const current = await page.screenshot({ type: "png", scale: "css", fullPage: options.fullPage ?? false }) + const after = decodePng(current) + if (before.width !== after.width || before.height !== after.height) { + throw new Error(`Screenshot dimensions differ: baseline ${before.width}ร—${before.height}, current ${after.width}ร—${after.height}. Capture both at the same CSS viewport and fullPage setting; images are never resized.`) + } + const diff = new PNG({ width: before.width, height: before.height }) + const changedPixels = pixelmatch(before.data, after.data, diff.data, before.width, before.height, { + threshold, + includeAA: true, + }) + const image = PNG.sync.write(diff) + const totalPixels = before.width * before.height + // Exclusive creation also rejects symlinks/hardlinks to the baseline. + if (options.path) await fs.writeFile(options.path, image, { flag: "wx", mode: 0o600 }) + return { + matches: changedPixels === 0, + width: before.width, + height: before.height, + changedPixels, + totalPixels, + changedRatio: changedPixels / totalPixels, + threshold, + ...(options.path ? { path: options.path } : { image }), + } + } +} + +async function readBaseline(filename: string): Promise { + if (!path.isAbsolute(filename)) throw new Error("screenshotDiff baseline path must be absolute") + const file = await fs.open(filename, "r") + try { + const stat = await file.stat() + if (!stat.isFile() || stat.size > maxImageBytes) throw new Error("Screenshot baseline must be a PNG file no larger than 32 MiB") + // Bound the read even if another process grows the file after stat. + const buffer = Buffer.alloc(stat.size) + let offset = 0 + while (offset < buffer.length) { + const { bytesRead } = await file.read(buffer, offset, buffer.length - offset, offset) + if (!bytesRead) break + offset += bytesRead + } + return buffer.subarray(0, offset) + } finally { + await file.close() + } +} + +function validateThreshold(threshold: number): number { + if (!Number.isFinite(threshold) || threshold < 0 || threshold > 1) { + throw new Error("screenshotDiff threshold must be a finite number from 0 to 1") + } + return threshold +} + +function decodePng(buffer: Buffer): PNG { + if (!Buffer.isBuffer(buffer) || buffer.length > maxImageBytes || buffer.length < 24 || !buffer.subarray(0, 8).equals(pngSignature) || buffer.toString("ascii", 12, 16) !== "IHDR") { + throw new Error("Screenshot must be a PNG buffer no larger than 32 MiB") + } + const width = buffer.readUInt32BE(16) + const height = buffer.readUInt32BE(20) + if (width === 0 || height === 0 || width * height > maxImagePixels) { + throw new Error("Screenshot exceeds the 16 megapixel comparison limit") + } + return PNG.sync.read(buffer) +} diff --git a/packages/browser-extension/cli/src/secret-profile.ts b/packages/browser-extension/cli/src/secret-profile.ts new file mode 100644 index 00000000000..a640f4101ad --- /dev/null +++ b/packages/browser-extension/cli/src/secret-profile.ts @@ -0,0 +1,17 @@ +import * as AuthProfile from "./auth-profile.ts" + +export type Summary = AuthProfile.AuthProfileSummary +export type RunResult = AuthProfile.AuthRunResult +export type RunOptions = AuthProfile.AuthRunOptions +export type StatusOptions = AuthProfile.AuthProfileOptions +export type Error = AuthProfile.AuthProfileError +export const Error = AuthProfile.AuthProfileError + +/** Return profile metadata without revealing credential values. */ +export const status = AuthProfile.status + +/** + * Run a trusted credential-bearing worker with profile slots injected as BC_SECRET_N. + * Known values are redacted from bounded stdout and stderr before they return. + */ +export const run = AuthProfile.run diff --git a/packages/browser-extension/cli/src/session-catalog.ts b/packages/browser-extension/cli/src/session-catalog.ts new file mode 100644 index 00000000000..a392858376c --- /dev/null +++ b/packages/browser-extension/cli/src/session-catalog.ts @@ -0,0 +1,88 @@ +import { dataRoot } from "./paths.ts" +import fs from "node:fs/promises" +import os from "node:os" +import path from "node:path" +import crypto from "node:crypto" +import { Schema } from "effect" +import { isNodeError, isUnsupportedDirectorySyncError } from "./fs-durability.ts" +import { isValidSessionId } from "./relay-helpers.ts" + +export const PersistedSession = Schema.Struct({ + id: Schema.String, + createdAt: Schema.String, + updatedAt: Schema.String, + readOnly: Schema.Boolean, + target: Schema.optionalKey(Schema.Struct({ + id: Schema.String, + owner: Schema.Literals(["relay", "user"]), + })), +}) + +export type PersistedSession = Schema.Schema.Type + +const Catalog = Schema.Struct({ + version: Schema.Literal(1), + sessions: Schema.Array(PersistedSession), +}) + +export function defaultSessionCatalogPath(port: number, home = os.homedir()): string { + return path.join(dataRoot(home), "relays", String(port), "sessions.json") +} + +export class SessionCatalog { + constructor(readonly filePath: string) {} + + async load(): Promise { + let text: string + try { + text = await fs.readFile(this.filePath, "utf8") + } catch (error) { + if (isNodeError(error) && error.code === "ENOENT") return [] + throw new Error(`Could not read OpenCode Browser session catalog at ${this.filePath}`, { cause: error }) + } + try { + const sessions = Schema.decodeUnknownSync(Catalog)(JSON.parse(text)).sessions + const invalid = sessions.find((session) => !isValidSessionId(session.id)) + if (invalid) throw new Error(`Invalid persisted session id: ${invalid.id}`) + return sessions + } catch (error) { + const detail = error instanceof Error && error.message ? `: ${error.message}` : "" + throw new Error(`Could not decode OpenCode Browser session catalog at ${this.filePath}${detail}`, { cause: error }) + } + } + + async save(sessions: readonly PersistedSession[]): Promise { + const directory = path.dirname(this.filePath) + const temporaryPath = `${this.filePath}.${process.pid}.${crypto.randomUUID()}.tmp` + const contents = `${JSON.stringify({ version: 1, sessions }, null, 2)}\n` + let temporaryFile: fs.FileHandle | undefined + try { + await fs.mkdir(directory, { recursive: true, mode: 0o700 }) + await fs.chmod(directory, 0o700) + temporaryFile = await fs.open(temporaryPath, "wx", 0o600) + await temporaryFile.writeFile(contents, "utf8") + await temporaryFile.sync() + await temporaryFile.close() + temporaryFile = undefined + await fs.rename(temporaryPath, this.filePath) + const directoryHandle = await fs.open(directory, "r") + try { + try { + await directoryHandle.sync() + } catch (error) { + if (!isUnsupportedDirectorySyncError(error)) throw error + } + } finally { + await directoryHandle.close() + } + } catch (error) { + try { + await temporaryFile?.close() + } catch {} + try { + await fs.rm(temporaryPath, { force: true }) + } catch {} + throw new Error(`Could not write OpenCode Browser session catalog at ${this.filePath}`, { cause: error }) + } + } +} diff --git a/packages/browser-extension/cli/src/session-journal.ts b/packages/browser-extension/cli/src/session-journal.ts new file mode 100644 index 00000000000..1f0c2109655 --- /dev/null +++ b/packages/browser-extension/cli/src/session-journal.ts @@ -0,0 +1,149 @@ +import { dataRoot } from "./paths.ts" +import fs from "node:fs" +import os from "node:os" +import path from "node:path" +import { Option, Schema } from "effect" +import { isNodeError } from "./fs-durability.ts" + +/** + * Session journal: an auditable per-session record of what agents did to the + * user's browser. The relay appends one JSON line per execute call to + * `/sessions//journal.jsonl` (see paths.ts); the CLI `journal` command + * reads the file locally and renders a human-readable timeline. + */ + +export const JournalEntry = Schema.Struct({ + ts: Schema.String, + sessionId: Schema.String, + code: Schema.String, + isError: Schema.Boolean, + durationMs: Schema.Number, + resultPreview: Schema.String, + logCount: Schema.Number, + startUrl: Schema.optionalKey(Schema.NullOr(Schema.String)), + endUrl: Schema.optionalKey(Schema.NullOr(Schema.String)), + navigations: Schema.optionalKey(Schema.Array(Schema.String)), + warnings: Schema.optionalKey(Schema.Array(Schema.String)), + diagnostic: Schema.optionalKey(Schema.String), + handoffs: Schema.optionalKey(Schema.Number), +}) + +export interface JournalEntry extends Schema.Schema.Type {} + +const decodeJournalEntry = Schema.decodeUnknownOption(JournalEntry) + +export const defaultJournalBaseDir = (): string => { + return path.join(dataRoot(), "sessions") +} + +export function journalPathForSession(baseDir: string, sessionId: string): string { + return path.join(baseDir, sessionId, "journal.jsonl") +} + +const maxJournalCodeLength = 2_000 +const maxJournalPreviewLength = 400 +const maxJournalDiagnosticLength = 240 + +export function truncateForJournal(text: string, maxLength: number): string { + if (text.length <= maxLength) { + return text + } + return `${text.slice(0, maxLength)}โ€ฆ [truncated ${text.length - maxLength} chars]` +} + +export function makeJournalEntry(options: { + readonly sessionId: string + readonly code: string + readonly isError: boolean + readonly durationMs: number + readonly resultText: string + readonly logCount: number + readonly startUrl?: string | null | undefined + readonly endUrl?: string | null | undefined + readonly navigations?: readonly string[] | undefined + readonly warnings?: readonly string[] | undefined + readonly diagnostic?: string | undefined + readonly handoffs?: number | undefined +}): JournalEntry { + return { + ts: new Date().toISOString(), + sessionId: options.sessionId, + code: truncateForJournal(options.code, maxJournalCodeLength), + isError: options.isError, + durationMs: options.durationMs, + resultPreview: truncateForJournal(options.resultText, maxJournalPreviewLength), + logCount: options.logCount, + ...(options.startUrl === undefined ? {} : { startUrl: options.startUrl }), + ...(options.endUrl === undefined ? {} : { endUrl: options.endUrl }), + ...(options.navigations && options.navigations.length > 0 ? { navigations: options.navigations } : {}), + ...(options.warnings && options.warnings.length > 0 ? { warnings: options.warnings } : {}), + ...(options.diagnostic ? { diagnostic: truncateForJournal(options.diagnostic, maxJournalDiagnosticLength) } : {}), + ...(options.handoffs ? { handoffs: options.handoffs } : {}), + } +} + +/** + * Append a journal entry, creating the session directory if needed. Journal + * writes are best-effort: failures are reported to the callback (or ignored) + * and never fail the execute call they describe. + */ +export async function appendJournalEntry(options: { + readonly baseDir: string + readonly entry: JournalEntry +}): Promise { + const filePath = journalPathForSession(options.baseDir, options.entry.sessionId) + await fs.promises.mkdir(path.dirname(filePath), { recursive: true }) + await fs.promises.appendFile(filePath, `${JSON.stringify(options.entry)}\n`, "utf8") +} + +/** Read the last `limit` journal entries for a session; skips corrupt lines. */ +export async function readJournalEntries(options: { + readonly baseDir: string + readonly sessionId: string + readonly limit: number +}): Promise { + const filePath = journalPathForSession(options.baseDir, options.sessionId) + let raw: string + try { + raw = await fs.promises.readFile(filePath, "utf8") + } catch (error) { + if (isNodeError(error) && error.code === "ENOENT") { + return [] + } + throw error + } + return parseJournalLines(raw).slice(-options.limit) +} + +export function parseJournalLines(raw: string): JournalEntry[] { + const entries: JournalEntry[] = [] + for (const line of raw.split("\n")) { + const trimmed = line.trim() + if (!trimmed) { + continue + } + let parsed: unknown + try { + parsed = JSON.parse(trimmed) + } catch { + continue + } + const decoded = decodeJournalEntry(parsed) + if (Option.isSome(decoded)) { + entries.push(decoded.value) + } + } + return entries +} + +export function formatJournalEntry(entry: JournalEntry): string { + const time = entry.ts.slice(11, 19) || entry.ts + const status = entry.isError ? "ERR" : "ok " + const codePreview = entry.code.replace(/\s+/g, " ").trim().slice(0, 80) + const urlPart = entry.endUrl ? ` ${entry.endUrl}` : "" + const navPart = entry.navigations && entry.navigations.length > 0 ? ` nav=${entry.navigations.length}` : "" + const handoffPart = entry.handoffs ? ` handoffs=${entry.handoffs}` : "" + const warningPart = entry.warnings && entry.warnings.length > 0 ? ` warnings=${entry.warnings.length}` : "" + const diagnosticPart = entry.diagnostic ? ` diagnostic=${entry.diagnostic}` : "" + return `${time} ${status} ${String(entry.durationMs).padStart(5)}ms${urlPart}${navPart}${handoffPart}${warningPart}${diagnosticPart} ${codePreview}` +} diff --git a/packages/browser-extension/cli/src/session-manager.ts b/packages/browser-extension/cli/src/session-manager.ts new file mode 100644 index 00000000000..e68d89e6ee1 --- /dev/null +++ b/packages/browser-extension/cli/src/session-manager.ts @@ -0,0 +1,990 @@ +import { Deferred, Effect, Exit, Fiber, Latch, Result, Schema, Semaphore } from "effect" +import { defaultPageClosedWarning, ExecuteSandbox, hasExplicitTargetSelection, type ExecuteResult, type ExecuteTargetSelection } from "./execute.ts" +import type { NetworkCaptureOptions, NetworkCaptureResult, NetworkCaptureStatus, NetworkCaptureStopOptions } from "./network-capture.ts" +import { generateSessionId } from "./relay-helpers.ts" +import type { OpenCodeBrowserSession, ExecuteSandboxLike, SessionSummary, SessionTarget } from "./relay-types.ts" +import type { AuthenticatedJsonOutcome, AuthenticatedJsonRequest } from "./relay-schema.ts" +import type { PersistedSession } from "./session-catalog.ts" +import { + MemoryTargetOwnership, + type TargetOwnership, + type TargetOwnershipChange, + type TargetOwnershipReservation, +} from "./target-registry.ts" + +export type SessionExecuteRecord = { + readonly sessionId: string + readonly code: string + readonly durationMs: number + readonly result: ExecuteResult +} + +type CreatedSessionSummary = SessionSummary & { readonly created?: boolean } + +type ExecutionResponse = { readonly result: ExecuteResult; readonly session: CreatedSessionSummary } + +type AdoptionResult = { + readonly adoptedUrl: string + readonly session: CreatedSessionSummary + readonly releasedTargetIds: readonly string[] +} + +export type SessionHooks = { + /** Called when a session starts (true) or finishes (false) an execute. */ + readonly onExecuteStateChange?: (sessionId: string, executing: boolean) => void + /** Called after each execute completes, for journaling. Failure is logged and ignored. */ + readonly onExecuteRecord?: (record: SessionExecuteRecord) => unknown | Promise + /** How long lifecycle commands wait for a permit or sandbox operation. */ + readonly lifecycleTimeoutMs?: number + /** Maximum time best-effort journal I/O may retain an execute permit. */ + readonly journalTimeoutMs?: number + /** Current user-owned attached page URLs, used for relay-side adoption hints. */ + readonly getUserAttachedPageUrls?: () => readonly string[] + /** Reconcile relay visibility and presentation after authoritative ownership changes. */ + readonly onTargetOwnershipChange?: (change: TargetOwnershipChange) => void + /** Close a live relay-owned target by its durable target id. */ + readonly onReleaseRelayTarget?: (targetId: string) => Effect.Effect + /** Persist session identity and target continuity after durable lifecycle changes. */ + readonly onSessionsChanged?: (sessions: readonly PersistedSession[]) => unknown | Promise +} + +export class SessionError extends Schema.TaggedError()( + "OpenCodeBrowserSessions.SessionError", + { + message: Schema.String, + reason: Schema.Literals([ + "already-exists", + "inactive", + "invalid-request", + "not-found", + "setup-failed", + "target-owned", + "timeout", + ]), + sessionId: Schema.optionalKey(Schema.String), + }, +) {} + +const sessionError = ( + reason: SessionError["reason"], + message: string, + sessionId?: string, +): SessionError => new SessionError({ message, reason, ...(sessionId ? { sessionId } : {}) }) + +export const adoptionTipForUrl = (url: string): string => { + const selector = targetUrlHintSelector(url) + return `Tip: an attached tab is open (${url}). Use opencode-browser session adopt --target-url '${selector}' to drive it instead of this new tab.` +} + +export const shouldAppendAdoptionTip = (options: { + readonly explicitTargetSelection: boolean + readonly sessionCreated: boolean + readonly warnings: readonly string[] + readonly userAttachedPageUrls: readonly string[] +}): boolean => { + if (options.explicitTargetSelection || options.userAttachedPageUrls.length === 0) { + return false + } + return options.sessionCreated || options.warnings.includes(defaultPageClosedWarning) +} + +export class OpenCodeBrowserSessions { + readonly sessions = new Map() + private readonly createSandbox: (id: string, onDefaultTargetChange: (target: SessionTarget | undefined) => void) => ExecuteSandboxLike + private readonly hooks: SessionHooks + private readonly executing = new Set() + private readonly adoptSemaphore = Semaphore.makeUnsafe(1) + private readonly targetOwnership: TargetOwnership + private persistenceTail = Promise.resolve() + private drainedPersistenceTail: Promise | undefined + private admission: "open" | "draining" | "closed" = "open" + private pendingWork = 0 + private readonly pendingSessionWork = new Map() + private readonly identityChanges = new Map>() + private readonly idle = Latch.makeUnsafe(true) + private userAttachedPageUrlsProvider: (() => readonly string[]) | undefined + + constructor( + private readonly endpointUrl: string, + createSandbox?: (id: string, onDefaultTargetChange: (target: SessionTarget | undefined) => void) => ExecuteSandboxLike, + hooks?: SessionHooks, + targetOwnership?: TargetOwnership, + ) { + this.createSandbox = createSandbox ?? ((id, onDefaultTargetChange) => new ExecuteSandbox({ endpointUrl: this.endpointUrl, sessionId: id, onDefaultTargetChange })) + this.hooks = hooks ?? {} + this.targetOwnership = targetOwnership ?? new MemoryTargetOwnership() + this.userAttachedPageUrlsProvider = this.hooks.getUserAttachedPageUrls + } + + setUserAttachedPageUrlsProvider(provider: () => readonly string[]): void { + this.userAttachedPageUrlsProvider = provider + } + + listSummaries(): SessionSummary[] { + return Array.from(this.sessions.values()).map((session) => { + return this.sessionSummary(session) + }) + } + + restore(entries: readonly PersistedSession[]): void { + this.assertAdmission() + if (this.sessions.size > 0) throw new Error("Cannot restore sessions after session management has started") + const ids = new Set() + const targetOwners = new Set() + for (const entry of entries) { + if (ids.has(entry.id)) throw new Error(`Duplicate persisted session: ${entry.id}`) + ids.add(entry.id) + if (entry.target && targetOwners.has(entry.target.id)) { + throw new Error(`Duplicate persisted target owner: ${entry.target.id}`) + } + if (entry.target) targetOwners.add(entry.target.id) + } + for (const entry of entries) { + const session = this.createOpenCodeBrowserSession(entry.id, entry.readOnly, { + createdAt: entry.createdAt, + updatedAt: entry.updatedAt, + }) + if (entry.target) session.target = entry.target + session.sandbox.restore(entry.target) + this.sessions.set(entry.id, session) + } + } + + persistedTargetOwner(targetId: string): { readonly sessionId: string; readonly owner: "relay" | "user" } | undefined { + for (const session of this.sessions.values()) { + const target = session.target + if (target?.id === targetId) return { sessionId: session.id, owner: target.owner } + } + return undefined + } + + private updateTarget(session: OpenCodeBrowserSession, target: SessionTarget | undefined): void { + if (this.sessions.get(session.id) !== session) return + if (session.target?.id === target?.id && session.target?.owner === target?.owner) return + if (target) session.target = target + else delete session.target + session.updatedAt = new Date().toISOString() + this.schedulePersistence() + } + + createNew(id: string | undefined, options?: { readonly readOnly?: boolean }): OpenCodeBrowserSession { + this.assertAdmission() + if (id !== undefined) this.assertStableIdentity(id) + return this.createAcceptedSession(id, options) + } + + private createAcceptedSession(id: string | undefined, options?: { readonly readOnly?: boolean }): OpenCodeBrowserSession { + const sessionId = id ?? generateSessionId(this.sessions) + if (this.sessions.has(sessionId)) { + throw sessionError("already-exists", `Session already exists: ${sessionId}`, sessionId) + } + const session = this.createOpenCodeBrowserSession(sessionId, options?.readOnly === true) + this.sessions.set(sessionId, session) + this.schedulePersistence() + return session + } + + create(id: string | undefined, options?: { readonly readOnly?: boolean }): Effect.Effect { + return this.withAdmission(id, this.createPersistedSession(id, options).pipe(Effect.uninterruptible)) + } + + ensure(id: string, options?: { readonly readOnly?: boolean }): Effect.Effect { + const manager = this + return this.withAdmission(id, Effect.gen(function* () { + const existing = manager.sessions.get(id) + if (existing) { + if (options?.readOnly === true && !existing.readOnly) { + return yield* sessionError( + "invalid-request", + `Session ${id} already exists with write access and cannot be ensured as read-only`, + id, + ) + } + return manager.sessionSummary(existing) + } + const session = yield* manager.createPersistedSession(id, options) + return manager.sessionSummary(session) + }).pipe(Effect.uninterruptible)) + } + + private readonly createPersistedSession = Effect.fnUntraced(function* (this: OpenCodeBrowserSessions, id: string | undefined, options?: { readonly readOnly?: boolean }) { + const manager = this + const sessionId = id ?? generateSessionId(this.sessions) + return yield* manager.withIdentityChange(sessionId, Effect.gen(function* () { + const session = manager.createAcceptedSession(sessionId, options) + yield* manager.flushPersistenceWithRollback(() => Effect.gen(function* () { + if (manager.sessions.get(session.id) === session) manager.sessions.delete(session.id) + yield* manager.closeOpenCodeBrowserSession(session) + })) + return session + })) + }) + + getOrCreate(id: string): { readonly session: OpenCodeBrowserSession; readonly created: boolean } { + this.assertAdmission() + this.assertStableIdentity(id) + return this.getOrCreateAcceptedSession(id) + } + + private getOrCreateAcceptedSession(id: string): { readonly session: OpenCodeBrowserSession; readonly created: boolean } { + const existing = this.sessions.get(id) + if (existing) { + return { session: existing, created: false } + } + return { session: this.createAcceptedSession(id), created: true } + } + + isReadOnly(id: string): boolean { + return this.sessions.get(id)?.readOnly === true + } + + isExecuting(id: string): boolean { + return this.executing.has(id) + } + + hasPendingWork(id: string): boolean { + return this.pendingSessionWork.has(id) + } + + hasActiveNetworkCapture(): boolean { + return Array.from(this.sessions.values()).some((session) => session.sandbox.networkStatus().active) + } + + private collectSessionIds(matches: (session: OpenCodeBrowserSession) => boolean): string[] { + const affectedSessionIds: string[] = [] + for (const session of this.sessions.values()) { + if (matches(session)) { + affectedSessionIds.push(session.id) + } + } + return affectedSessionIds + } + + markTargetCrashed(targetId: string): string[] { + return this.collectSessionIds((session) => session.sandbox.markTargetCrashed(targetId)) + } + + markTargetProtectedUi(targetId: string, protectedUi: boolean): string[] { + return this.collectSessionIds((session) => session.sandbox.markTargetProtectedUi(targetId, protectedUi)) + } + + markTargetDetached(targetId: string): string[] { + return this.collectSessionIds((session) => { + const detached = session.sandbox.markTargetDetached(targetId) + if (session.target?.id === targetId && session.target.owner === "user") { + this.notifyTargetOwnershipChange(this.targetOwnership.releaseTargetOwnership(targetId, session.id)) + } + if (session.target?.id === targetId) { + this.updateTarget(session, undefined) + } + return detached + }) + } + + markTargetReplaced(previousTargetId: string, targetId: string): string[] { + return this.collectSessionIds((session) => { + if (session.target?.id === previousTargetId) this.updateTarget(session, { ...session.target, id: targetId }) + return session.sandbox.markTargetReplaced(previousTargetId, targetId) + }) + } + + delete(id: string): Effect.Effect { + const manager = this + return this.withAdmission(id, Effect.gen(function* () { + const session = manager.sessions.get(id) + if (!session) { + return false + } + return yield* manager.withLifecyclePermit(session, "delete", manager.withIdentityChange(id, Effect.gen(function* () { + if (manager.sessions.get(id) !== session) { + return false + } + if (session.target?.owner === "relay") yield* manager.closeRelayTarget(session.target.id).pipe(Effect.ignore) + manager.sessions.delete(id) + yield* manager.commitPersistence(() => Effect.sync(() => { + manager.sessions.set(id, session) + })) + yield* manager.releaseSessionTargetOwnership(session) + yield* manager.closeOpenCodeBrowserSession(session) + return true + }))) + })) + } + + reset(id: string): Effect.Effect { + const manager = this + return this.withAdmission(id, Effect.gen(function* () { + const existing = manager.sessions.get(id) + if (!existing) { + return undefined + } + return yield* manager.withLifecyclePermit(existing, "reset", manager.withIdentityChange(id, Effect.gen(function* () { + if (manager.sessions.get(id) !== existing) { + return yield* sessionError("inactive", `Session is no longer active: ${id}`, id) + } + if (existing.target?.owner === "relay") yield* manager.closeRelayTarget(existing.target.id).pipe(Effect.ignore) + const session = manager.createOpenCodeBrowserSession(id, existing.readOnly) + manager.sessions.set(id, session) + yield* manager.commitPersistence(() => Effect.sync(() => { + manager.sessions.set(id, existing) + })) + yield* manager.releaseSessionTargetOwnership(existing) + yield* manager.closeOpenCodeBrowserSession(existing) + return manager.sessionSummary(session) + }))) + })) + } + + adoptedTargetId(id: string): string | undefined { + const target = this.sessions.get(id)?.target + return target?.owner === "user" ? target.id : undefined + } + + networkStart(id: string, options: NetworkCaptureOptions = {}): Effect.Effect { + return this.withSessionOperation(id, "network start", (session) => session.sandbox.networkStart(options)) + } + + networkStatus(id: string): Effect.Effect { + const session = this.sessions.get(id) + return session + ? Effect.succeed(session.sandbox.networkStatus()) + : Effect.fail(sessionError("not-found", `Session not found: ${id}`, id)) + } + + networkStop(id: string, options: NetworkCaptureStopOptions = {}): Effect.Effect { + return this.withSessionOperation(id, "network stop", (session) => session.sandbox.networkStop(options)) + } + + networkCancel(id: string): Effect.Effect<{ readonly cancelled: boolean }, Error> { + return this.withSessionOperation(id, "network cancel", (session) => session.sandbox.networkCancel()) + } + + authRefresh(id: string, options: { readonly name: string; readonly urlFilter?: string; readonly timeoutMs?: number }): Effect.Effect { + return this.withSessionOperation(id, "auth refresh", (session) => session.sandbox.authRefresh(options)) + } + + private withSessionOperation( + id: string, + operation: string, + use: (session: OpenCodeBrowserSession) => Effect.Effect, + beforePermit?: (session: OpenCodeBrowserSession) => Effect.Effect, + ): Effect.Effect { + const manager = this + return this.withAdmission(id, Effect.suspend(() => { + const session = manager.sessions.get(id) + if (!session) return Effect.fail(sessionError("not-found", `Session not found: ${id}`, id)) + return (beforePermit ? beforePermit(session) : Effect.void).pipe( + Effect.andThen(manager.withLifecyclePermit(session, operation, Effect.gen(function* () { + if (manager.sessions.get(id) !== session) { + return yield* sessionError("inactive", `Session is no longer active: ${id}`, id) + } + return yield* use(session) + }))), + ) + })) + } + + authenticatedJson( + request: AuthenticatedJsonRequest, + ): Effect.Effect { + const manager = this + const { sessionId, ...pageRequest } = request + return this.withSessionOperation( + sessionId, + "authenticated request", + (session) => Effect.gen(function* () { + manager.setExecuting(session.id, true) + const result = yield* session.sandbox.authenticatedJson(pageRequest).pipe( + Effect.ensuring(Effect.sync(() => manager.setExecuting(session.id, false))), + ) + session.updatedAt = new Date().toISOString() + yield* manager.commitPersistence() + return result + }), + (session) => session.readOnly && request.method !== "GET" + ? Effect.fail(sessionError( + "invalid-request", + `Read-only session ${sessionId} cannot make ${request.method} authenticated requests`, + sessionId, + )) + : Effect.void, + ) + } + + execute(options: { + readonly sessionId?: string + readonly code: string + readonly createIfMissing: boolean + readonly targetSelection?: ExecuteTargetSelection + }): Effect.Effect { + const manager = this + return this.withAdmission(options.sessionId, Effect.uninterruptibleMask((restore) => Effect.gen(function* () { + const resolved = yield* manager.resolveWorkSession(options.sessionId, options.createIfMissing) + const session = resolved.session + const response = yield* Deferred.make() + let started = false + let cancelled = false + const operation = Effect.gen(function* () { + if (cancelled) { + return yield* sessionError("inactive", `Session execute was cancelled before starting: ${session.id}`, session.id) + } + if (manager.sessions.get(session.id) !== session) { + return yield* sessionError("inactive", `Session is no longer active: ${session.id}`, session.id) + } + started = true + session.updatedAt = new Date().toISOString() + manager.setExecuting(session.id, true) + const startedAt = Date.now() + const result = yield* session.sandbox + .execute(options.code, { ...(options.targetSelection ? { targetSelection: options.targetSelection } : {}) }) + .pipe(Effect.ensuring(Effect.sync(() => manager.setExecuting(session.id, false)))) + if (resolved.created && result.setupFailed) { + return yield* sessionError("setup-failed", result.text, session.id) + } + const userAttachedPageUrls = manager.userAttachedPageUrlsProvider?.() ?? [] + const resultWithHint = shouldAppendAdoptionTip({ + explicitTargetSelection: hasExplicitTargetSelection(options.targetSelection), + sessionCreated: resolved.created, + warnings: result.warnings, + userAttachedPageUrls, + }) + ? { ...result, warnings: [...result.warnings, adoptionTipForUrl(userAttachedPageUrls[0] ?? "about:blank")] } + : result + session.updatedAt = new Date().toISOString() + yield* manager.recordExecute({ + sessionId: session.id, + code: session.sandbox.redactNetworkCaptureText(options.code), + durationMs: Date.now() - startedAt, + result: resultWithHint, + }) + yield* manager.commitPersistence() + return { result: resultWithHint, session: manager.createdSummary(session, resolved.created) } + }) + const worker = session.executeSemaphore.withPermit(operation.pipe(Effect.matchEffect({ + onFailure: (error) => (resolved.created + ? manager.cleanupCreatedSession(session) + : Effect.void).pipe(Effect.andThen(Deferred.fail(response, error))), + onSuccess: (value) => Deferred.succeed(response, value), + }))) + const workerFiber = yield* manager.forkTracked(worker, session.id) + return yield* restore(Deferred.await(response)).pipe( + Effect.onInterrupt(() => Effect.suspend(() => { + if (started) return Effect.void + cancelled = true + return Fiber.interrupt(workerFiber).pipe( + Effect.asVoid, + Effect.andThen(resolved.created + ? session.executeSemaphore.withPermit(manager.cleanupCreatedSession(session)) + : Effect.void), + ) + })), + ) + }))) + } + + adopt(options: { + readonly sessionId?: string + readonly createIfMissing: boolean + readonly targetId: string + readonly targetUrl: string + }): Effect.Effect { + const manager = this + return this.withAdmission(options.sessionId, Effect.uninterruptibleMask((restore) => Effect.gen(function* () { + const resolved = yield* manager.resolveWorkSession(options.sessionId, options.createIfMissing) + const session = resolved.session + const result = yield* Deferred.make() + let state: "pending" | "reserved" | "committed" = "pending" + let cancelled = false + let reservation: TargetOwnershipReservation | undefined + let previousTarget: SessionTarget | undefined + let previousRelayClosed = false + const timeoutMs = manager.hooks.lifecycleTimeoutMs ?? 10_000 + const timeoutError = sessionError("timeout", `Session adopt for ${session.id} timed out after ${timeoutMs}ms`, session.id) + const adoptionCancelled = () => cancelled + const cancel = Effect.sync(() => { + if (cancelled) { + return + } + cancelled = true + if (reservation && state === "reserved") { + manager.notifyTargetOwnershipChange(manager.targetOwnership.rollbackTargetOwnership(reservation)) + } + }) + const operation = Effect.gen(function* () { + if (manager.sessions.get(session.id) !== session) { + return yield* sessionError("inactive", `Session is no longer active: ${session.id}`, session.id) + } + if (adoptionCancelled()) { + return yield* timeoutError + } + reservation = yield* Effect.try({ + try: () => manager.targetOwnership.reserveTargetOwnership(options.targetId, session.id), + catch: (cause) => cause instanceof Error ? cause : new Error("Reserve target ownership", { cause }), + }) + state = "reserved" + manager.notifyTargetOwnershipChange({ targetIds: [options.targetId], tabIds: reservation.tabId < 0 ? [] : [reservation.tabId] }) + previousTarget = session.target + yield* session.sandbox.adoptPage(options.targetId) + if (adoptionCancelled()) { + return yield* timeoutError + } + const activeReservation = reservation + previousTarget = session.target ?? previousTarget + const previousTargetId = previousTarget?.id + if (previousTarget?.owner === "relay" && previousTarget.id !== options.targetId) { + yield* manager.closeRelayTarget(previousTarget.id) + previousRelayClosed = true + } + session.target = { id: options.targetId, owner: "user" } + session.updatedAt = new Date().toISOString() + yield* manager.commitPersistence() + if (adoptionCancelled()) { + return yield* timeoutError + } + yield* Effect.try({ + try: () => { + manager.notifyTargetOwnershipChange(manager.targetOwnership.commitTargetOwnership({ + reservation: activeReservation, + ...(previousTargetId ? { previousAdoptedTargetId: previousTargetId } : {}), + })) + state = "committed" + }, + catch: (cause) => cause instanceof Error ? cause : new Error("Commit target ownership", { cause }), + }) + const releasedTargetIds = previousTargetId && previousTargetId !== options.targetId ? [previousTargetId] : [] + const value = { adoptedUrl: options.targetUrl, releasedTargetIds, session: manager.createdSummary(session, resolved.created) } + yield* Deferred.succeed(result, value) + return value + }) + const transaction = session.executeSemaphore.withPermit(operation.pipe(Effect.matchEffect({ + onFailure: (error) => Effect.gen(function* () { + if (reservation && state !== "committed") { + manager.notifyTargetOwnershipChange(manager.targetOwnership.rollbackTargetOwnership(reservation)) + } + if (manager.sessions.get(session.id) === session && (resolved.created || state !== "pending")) { + const cleanup = yield* Effect.result(manager.cleanupSettledAdoption(session, resolved.created, previousTarget, previousRelayClosed)) + if (Result.isFailure(cleanup)) { + yield* Deferred.fail(result, cleanup.failure) + return + } + } + yield* Deferred.fail(result, error) + }), + onSuccess: () => Effect.void, + }))) + const worker = manager.adoptSemaphore.withPermit(transaction) + yield* manager.forkTracked(worker, session.id) + return yield* restore(Deferred.await(result).pipe( + Effect.timeoutOrElse({ + duration: timeoutMs, + orElse: () => cancel.pipe(Effect.andThen(Effect.fail(timeoutError))), + }), + Effect.onInterrupt(() => cancel), + )) + }))) + } + + /** Stop admission without cancelling accepted work or disconnecting sessions. */ + beginDrain(): Effect.Effect { + const manager = this + return Effect.gen(function* () { + if (manager.admission === "open") manager.admission = "draining" + while (true) { + yield* manager.idle.await + const pending = manager.persistenceTail + yield* manager.flushPersistence() + // Target callbacks can append persistence while the previous tail settles. + if (manager.pendingWork === 0 && pending === manager.persistenceTail) { + manager.drainedPersistenceTail = pending + return + } + } + }) + } + + /** Recheck synchronously at commit: late catalog writes invalidate a completed drain. */ + isDrained(): boolean { + return this.admission !== "open" + && this.pendingWork === 0 + && this.drainedPersistenceTail === this.persistenceTail + } + + /** Call only after cancelling or completing the reversible drain waiter. */ + resume(): void { + if (this.admission === "draining") this.admission = "open" + } + + closeAll(): Effect.Effect { + const manager = this + return Effect.gen(function* () { + manager.admission = "closed" + yield* manager.beginDrain().pipe(Effect.ignore) + yield* manager.adoptSemaphore.withPermit(Effect.gen(function* () { + yield* Effect.forEach(Array.from(manager.sessions.values()), (session) => { + return session.executeSemaphore.withPermit( + manager.disconnectOpenCodeBrowserSession(session), + ) + }, { concurrency: "unbounded", discard: true }) + yield* manager.flushPersistence().pipe(Effect.ignore) + manager.sessions.clear() + })) + }).pipe(Effect.uninterruptible) + } + + summary(id: string): SessionSummary | undefined { + const session = this.sessions.get(id) + if (!session) { + return undefined + } + return this.sessionSummary(session) + } + + private setExecuting(id: string, executing: boolean): void { + if (executing) { + this.executing.add(id) + } else { + this.executing.delete(id) + } + try { + this.hooks.onExecuteStateChange?.(id, executing) + } catch (error) { + console.error("Session execute-state hook failed", error) + } + } + + private recordExecute(record: SessionExecuteRecord): Effect.Effect { + const hook = this.hooks.onExecuteRecord + if (!hook) return Effect.void + return Effect.tryPromise({ + try: async () => { + const release = this.retainWork(record.sessionId) + try { + return await hook(record) + } finally { + release() + } + }, + catch: (cause) => cause, + }).pipe( + Effect.timeoutOrElse({ + duration: this.hooks.journalTimeoutMs ?? 2_000, + orElse: () => Effect.fail(new Error(`Session journal write timed out after ${this.hooks.journalTimeoutMs ?? 2_000}ms`)), + }), + Effect.catch((error) => Effect.sync(() => { + console.error("Session execute-record hook failed", error) + })), + Effect.asVoid, + ) + } + + private createOpenCodeBrowserSession(id: string, readOnly: boolean, timestamps?: { + readonly createdAt: string + readonly updatedAt?: string + }): OpenCodeBrowserSession { + const now = new Date().toISOString() + let session: OpenCodeBrowserSession | undefined + session = { + id, + createdAt: timestamps?.createdAt ?? now, + updatedAt: timestamps?.updatedAt ?? now, + readOnly, + sandbox: this.createSandbox(id, (target) => { + if (session) this.updateTarget(session, target) + }), + executeSemaphore: Semaphore.makeUnsafe(1), + } + return session + } + + /** Resolve execute/adopt work before any permit; the caller owns cleanup of a created session. */ + private resolveWorkSession(id: string | undefined, createIfMissing: boolean): Effect.Effect<{ readonly session: OpenCodeBrowserSession; readonly created: boolean }, SessionError> { + return Effect.suspend(() => { + if (id === undefined) { + return createIfMissing + ? Effect.succeed({ session: this.createAcceptedSession(undefined), created: true }) + : Effect.fail(sessionError("invalid-request", "sessionId is required when createIfMissing is false")) + } + if (createIfMissing) return Effect.succeed(this.getOrCreateAcceptedSession(id)) + const session = this.sessions.get(id) + return session ? Effect.succeed({ session, created: false }) : Effect.fail(sessionError("not-found", `Session not found: ${id}`, id)) + }) + } + + private createdSummary(session: OpenCodeBrowserSession, created: boolean): CreatedSessionSummary { + return { ...this.sessionSummary(session), ...(created ? { created: true } : {}) } + } + + private sessionSummary(session: OpenCodeBrowserSession): SessionSummary { + const status = session.sandbox.getStatus() + return { + id: session.id, + createdAt: session.createdAt, + updatedAt: session.updatedAt, + connected: status.connected, + pageUrl: status.pageUrl, + stateKeys: status.stateKeys, + ...(session.readOnly ? { readOnly: true } : {}), + } + } + + private closeOpenCodeBrowserSession(session: OpenCodeBrowserSession): Effect.Effect { + return this.forkTracked(this.closeOpenCodeBrowserSessionSettled(session), session.id).pipe( + Effect.flatMap((worker) => this.withLifecycleTimeout(Fiber.join(worker), `Close session ${session.id}`)), + Effect.ignore, + ) + } + + private disconnectOpenCodeBrowserSession(session: OpenCodeBrowserSession): Effect.Effect { + return Effect.acquireUseRelease( + Effect.sync(() => this.retainWork(session.id)), + () => session.sandbox.disconnectSettled().pipe(Effect.ignore), + (release) => Effect.sync(release), + ) + } + + private closeOpenCodeBrowserSessionSettled(session: OpenCodeBrowserSession): Effect.Effect { + return session.sandbox.closeSettled().pipe(Effect.ignore) + } + + private releaseSessionTargetOwnership(session: OpenCodeBrowserSession): Effect.Effect { + const target = session.target + if (!target) return Effect.void + this.notifyTargetOwnershipChange(this.targetOwnership.releaseTargetOwnership(target.id, session.id)) + delete session.target + return Effect.void + } + + private closeRelayTarget(targetId: string): Effect.Effect { + const close = this.hooks.onReleaseRelayTarget?.(targetId) + return close ?? Effect.void + } + + private notifyTargetOwnershipChange(change: TargetOwnershipChange): void { + if (change.targetIds.length === 0 && change.tabIds.length === 0) { + return + } + try { + this.hooks.onTargetOwnershipChange?.(change) + } catch (error) { + console.error("Target ownership hook failed", error) + } + } + + private persistedSession(session: OpenCodeBrowserSession): PersistedSession { + const target = session.target + return { + id: session.id, + createdAt: session.createdAt, + updatedAt: session.updatedAt, + readOnly: session.readOnly, + ...(target ? { target } : {}), + } + } + + private persistedSessions(): PersistedSession[] { + return Array.from(this.sessions.values(), (session) => this.persistedSession(session)) + } + + private schedulePersistence(sessions = this.persistedSessions()): void { + const hook = this.hooks.onSessionsChanged + if (!hook) return + const release = this.retainWork() + const previous = this.persistenceTail + this.persistenceTail = previous.catch(() => {}).then(async () => { + try { + await hook(sessions) + } finally { + release() + } + }) + void this.persistenceTail.catch((error) => { + console.error("Failed to persist OpenCode Browser sessions", error) + }) + } + + private flushPersistence(): Effect.Effect { + return Effect.tryPromise({ + try: () => this.persistenceTail, + catch: (cause) => cause instanceof Error ? cause : new Error("Persist OpenCode Browser sessions", { cause }), + }) + } + + private commitPersistence(rollback?: () => Effect.Effect): Effect.Effect { + this.schedulePersistence() + return rollback ? this.flushPersistenceWithRollback(rollback) : this.flushPersistence() + } + + private flushPersistenceWithRollback(rollback: () => Effect.Effect): Effect.Effect { + return this.flushPersistence().pipe(Effect.catch((error) => Effect.gen({ self: this }, function* () { + yield* rollback() + this.schedulePersistence() + yield* this.flushPersistence().pipe(Effect.ignore) + return yield* Effect.fail(error) + }))) + } + + persist(): Effect.Effect { + return this.flushPersistence() + } + + private cleanupSettledAdoption( + session: OpenCodeBrowserSession, + created: boolean, + previousTarget?: SessionTarget, + previousRelayClosed = false, + ): Effect.Effect { + const manager = this + return Effect.gen(function* () { + const activeTarget = session.target + yield* manager.releaseSessionTargetOwnership(session) + if (previousTarget && previousTarget.id !== activeTarget?.id) { + manager.notifyTargetOwnershipChange(manager.targetOwnership.releaseTargetOwnership(previousTarget.id, session.id)) + if (previousTarget.owner === "relay" && !previousRelayClosed) yield* manager.closeRelayTarget(previousTarget.id) + } + yield* manager.closeOpenCodeBrowserSessionSettled(session) + if (manager.sessions.get(session.id) !== session) { + return + } + if (created) { + manager.sessions.delete(session.id) + } else { + const replacement = manager.createOpenCodeBrowserSession(session.id, session.readOnly, { + createdAt: session.createdAt, + }) + manager.sessions.set(session.id, replacement) + } + yield* manager.commitPersistence() + }) + } + + private cleanupCreatedSession(session: OpenCodeBrowserSession): Effect.Effect { + const manager = this + return Effect.gen(function* () { + if (manager.sessions.get(session.id) !== session) return + manager.sessions.delete(session.id) + yield* manager.releaseSessionTargetOwnership(session) + yield* manager.closeOpenCodeBrowserSession(session) + yield* manager.commitPersistence().pipe(Effect.ignore) + }) + } + + private assertAdmission(): void { + if (this.admission !== "open") { + throw sessionError("inactive", this.admission === "closed" + ? "OpenCode Browser sessions are closing" + : "OpenCode Browser sessions are draining") + } + } + + private assertStableIdentity(id: string): void { + if (this.identityChanges.has(id)) { + throw sessionError("inactive", `Session lifecycle change is still committing: ${id}`, id) + } + } + + private awaitStableIdentity(id: string | undefined): Effect.Effect { + return Effect.suspend(() => { + const pending = id === undefined ? undefined : this.identityChanges.get(id) + return pending ? Deferred.await(pending).pipe(Effect.andThen(this.awaitStableIdentity(id))) : Effect.void + }) + } + + /** Keep same-ID callers behind the entire commit/rollback, including corrective persistence. */ + private withIdentityChange(id: string, effect: Effect.Effect): Effect.Effect { + return Effect.suspend(() => { + // Check and claim synchronously: the run loop may yield between separate effects. + const pending = this.identityChanges.get(id) + if (pending) return Deferred.await(pending).pipe(Effect.andThen(this.withIdentityChange(id, effect))) + const settled = Deferred.makeUnsafe() + this.identityChanges.set(id, settled) + return effect.pipe(Effect.onExit((exit) => Effect.suspend(() => { + if (this.identityChanges.get(id) === settled) this.identityChanges.delete(id) + // Waiters observe the change's failure or interruption and do not proceed past it. + return Deferred.done(settled, Exit.asVoid(exit)) + }))) + }) + } + + private retainWork(sessionId?: string): () => void { + this.pendingWork += 1 + if (sessionId !== undefined) this.pendingSessionWork.set(sessionId, (this.pendingSessionWork.get(sessionId) ?? 0) + 1) + this.idle.closeUnsafe() + return () => { + this.pendingWork -= 1 + if (sessionId !== undefined) { + const remaining = (this.pendingSessionWork.get(sessionId) ?? 1) - 1 + if (remaining === 0) this.pendingSessionWork.delete(sessionId) + else this.pendingSessionWork.set(sessionId, remaining) + } + if (this.pendingWork === 0) this.idle.openUnsafe() + } + } + + private withAdmission(sessionId: string | undefined, effect: Effect.Effect): Effect.Effect { + return Effect.acquireUseRelease( + Effect.try({ + try: () => { + this.assertAdmission() + return this.retainWork(sessionId) + }, + catch: (cause) => cause instanceof Error ? cause : new Error("Admit session operation", { cause }), + }), + () => this.awaitStableIdentity(sessionId).pipe(Effect.andThen(effect)), + (release) => Effect.sync(release), + ) + } + + private forkTracked(effect: Effect.Effect, sessionId: string): Effect.Effect, never, R> { + return Effect.uninterruptibleMask(() => Effect.suspend(() => { + // Transfer the lease before forking; caller interruption cannot strand it. + const release = this.retainWork(sessionId) + return effect.pipe( + Effect.ensuring(Effect.sync(release)), + Effect.forkDetach({ startImmediately: true }), + ) + })) + } + + private withLifecyclePermit( + session: OpenCodeBrowserSession, + operation: string, + effect: Effect.Effect, + ): Effect.Effect { + return Effect.suspend(() => { + let state: "waiting" | "started" | "timed-out" = "waiting" + const timeout = sessionError("timeout", `Session ${operation} timed out waiting for active execute in ${session.id}`, session.id) + // withPermit installs release atomically; racing a bare take can lose a granted permit. + return Effect.raceFirst( + session.executeSemaphore.withPermit(Effect.suspend((): Effect.Effect => { + if (state === "timed-out") return Effect.fail(timeout) + state = "started" + return effect + }).pipe(Effect.uninterruptible)), + Effect.sleep(this.hooks.lifecycleTimeoutMs ?? 10_000).pipe(Effect.flatMap(() => { + if (state === "started") return Effect.never + state = "timed-out" + return Effect.fail(timeout) + })), + ) + }) + } + + private withLifecycleTimeout(effect: Effect.Effect, label: string): Effect.Effect { + const timeoutMs = this.hooks.lifecycleTimeoutMs ?? 10_000 + return effect.pipe( + Effect.timeoutOrElse({ + duration: timeoutMs, + orElse: () => Effect.fail(sessionError("timeout", `${label} timed out after ${timeoutMs}ms`)), + }), + ) + } +} + +function targetUrlHintSelector(rawUrl: string): string { + try { + const parsed = new URL(rawUrl) + return parsed.host || rawUrl + } catch { + return rawUrl + } +} diff --git a/packages/browser-extension/cli/src/session-store.ts b/packages/browser-extension/cli/src/session-store.ts new file mode 100644 index 00000000000..d1432c5f33c --- /dev/null +++ b/packages/browser-extension/cli/src/session-store.ts @@ -0,0 +1,129 @@ +import { defaultPort } from "./relay-helpers.ts" +import { dataRoot } from "./paths.ts" +import { Context, Effect, FileSystem, Layer, Option, Path, Predicate, Schema } from "effect" +import os from "node:os" +import { endpointForPort, portConfig } from "./relay-client.ts" + +/** + * SessionStore persists the CLI's current OpenCode Browser session id, scoped + * by relay endpoint so switching `OPENCODE_BROWSER_PORT` cannot silently reuse + * a session id created against a different relay. + * + * File format (v2): `{ "endpoints": { "": { "id": "..." } } }`. + * Legacy `{ "id": "..." }` files are read as belonging to the default + * endpoint and migrated on the next write. + */ + +export class SessionStoreError extends Schema.TaggedError()( + "SessionStore.SessionStoreError", + { + message: Schema.String, + operation: Schema.String, + cause: Schema.Defect(), + }, +) {} + +const StoreFile = Schema.Struct({ + id: Schema.optionalKey(Schema.String), + endpoints: Schema.optionalKey(Schema.Record(Schema.String, Schema.Struct({ + id: Schema.String, + }))), +}) + +export interface Interface { + readonly endpoint: string + readonly filePath: string + readonly read: Effect.Effect + readonly write: (id: string) => Effect.Effect + readonly clear: Effect.Effect +} + +export class Service extends Context.Service()("opencode-browser-cli/SessionStore") {} + +const defaultFilePath = (): string => { + return `${dataRoot()}/session.json` +} + +export const make = Effect.fn("SessionStore.make")(function* (options?: { + readonly filePath?: string + readonly endpoint?: string +}) { + const fs = yield* FileSystem.FileSystem + const path = yield* Path.Path + const filePath = options?.filePath ?? defaultFilePath() + const port = yield* portConfig.pipe( + Effect.mapError((cause) => new SessionStoreError({ + message: `Invalid OPENCODE_BROWSER_PORT configuration: ${cause.message}`, + operation: "configure", + cause, + })), + ) + const endpoint = options?.endpoint ?? endpointForPort(port) + const defaultEndpoint = endpointForPort(defaultPort) + + const storeError = (operation: string) => (cause: unknown) => + new SessionStoreError({ + message: `Could not ${operation} the current session file at ${filePath}`, + operation, + cause, + }) + + const readStore: Effect.Effect, SessionStoreError> = fs + .readFileString(filePath) + .pipe( + Effect.map(Option.some), + Effect.catchTag("PlatformError", (error) => + Predicate.isTagged(error.reason, "NotFound") ? Effect.succeed(Option.none()) : Effect.fail(error)), + Effect.mapError(storeError("read")), + Effect.flatMap(Option.match({ + onNone: () => Effect.succeed({}), + onSome: (text) => Effect.try({ + try: () => JSON.parse(text) as unknown, + catch: (cause) => cause, + }).pipe( + Effect.flatMap(Schema.decodeUnknownEffect(StoreFile)), + Effect.mapError(storeError("decode")), + ), + })), + ) + + const currentEntries = (store: Schema.Schema.Type): Record => { + const entries = { ...(store.endpoints ?? {}) } + // Migrate the legacy top-level id to the default endpoint. + if (store.id && entries[defaultEndpoint] === undefined) { + entries[defaultEndpoint] = { id: store.id } + } + return entries + } + + const writeStore = (entries: Record) => + fs.makeDirectory(path.dirname(filePath), { recursive: true }).pipe( + Effect.andThen(fs.writeFileString(filePath, `${JSON.stringify({ endpoints: entries }, null, 2)}\n`)), + Effect.mapError(storeError("write")), + ) + + const read = readStore.pipe( + Effect.map((store) => currentEntries(store)[endpoint]?.id), + ) + + const write = (id: string) => + readStore.pipe( + Effect.flatMap((store) => { + const entries = currentEntries(store) + entries[endpoint] = { id } + return writeStore(entries) + }), + ) + + const clear = readStore.pipe( + Effect.flatMap((store) => { + const entries = currentEntries(store) + delete entries[endpoint] + return writeStore(entries) + }), + ) + + return Service.of({ endpoint, filePath, read, write, clear }) +}) + +export const layer: Layer.Layer = Layer.effect(Service, make()) diff --git a/packages/browser-extension/cli/src/setup.ts b/packages/browser-extension/cli/src/setup.ts new file mode 100644 index 00000000000..d3bcba38692 --- /dev/null +++ b/packages/browser-extension/cli/src/setup.ts @@ -0,0 +1,575 @@ +// Setup for OpenCode Browser, without changing opencode itself: +// install install the runtime, add the browse MCP server to opencode's config, copy the unpacked extension +// (reloading a connected one), then check which browsers have the extension and open the Chrome Web +// Store listing when none does +// extension open the unpacked extension folder (for "Load unpacked") +// uninstall remove everything install wrote +// Earlier versions registered a native messaging host and wrote an opencode plugin; install and uninstall +// remove those leftovers. +import { spawn, spawnSync } from "node:child_process" +import { createHash } from "node:crypto" +import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs" +import { homedir } from "node:os" +import path from "node:path" +import { fileURLToPath } from "node:url" +import { applyEdits, modify, parse } from "jsonc-parser" +import { dataRoot } from "./paths.ts" +import { opencodeBrowserVersion } from "./version.ts" + +const STORE_ID = "mfnicocicmmlkpjnaffgihfjhdgjkdjg" +/** The unpacked build; its ID is pinned by the manifest key. */ +const UNPACKED_ID = "afeafocngkodbmaipcngoamamfmekgfo" +const STORE_URL = `https://chromewebstore.google.com/detail/${STORE_ID}` +const PACKAGE = "opencode-browser-cli" +const MCP_NAME = "browse" +/** The MCP server's name before it was renamed to `browse`. */ +const LEGACY_MCP_NAME = "opencode-browser" +const LEGACY_HOST_NAME = "ai.opencode.browser" +const LEGACY_REGISTRY_ROOTS = ["HKCU\\Software\\Google\\Chrome", "HKCU\\Software\\Microsoft\\Edge"] +const windows = process.platform === "win32" + +const home = homedir() +const root = dataRoot() +const configRoot = process.env.XDG_CONFIG_HOME ?? path.join(home, ".config") +const files = { + dir: root, + /** A pinned npm install of this package: the MCP server runs from here, not the npx cache. */ + runtime: path.join(root, "runtime"), + settings: path.join(root, "settings.json"), + extension: path.join(root, "extension"), +} +/** Files the native messaging host of earlier versions left behind. */ +const legacyFiles = [ + path.join(root, "host"), + path.join(root, "host.bat"), + path.join(root, `${LEGACY_HOST_NAME}.json`), + path.join(root, "state.json"), + path.join(root, "logs", "host.log"), + path.join(configRoot, "opencode", "plugins", "opencode-browser.ts"), +] +/** This package's root: dist/cli.mjs when published, src/setup.ts from source. */ +const packageRoot = path.dirname(path.dirname(fileURLToPath(import.meta.url))) +/** Running from a source checkout without a package to install: the MCP server runs main.ts in place with bun. */ +const fromSource = existsSync(path.join(packageRoot, "src", "main.ts")) && !process.env.OPENCODE_BROWSER_PACKAGE +const bundledExtension = path.join(packageRoot, "extension") + +type Settings = { opencode?: string; entry?: string; version?: string } + +type Browser = { + name: string + /** The Chromium user data directory: `Local State` and one directory per profile. */ + userData: string + /** Where earlier versions wrote the native messaging host manifest. */ + manifests: string[] + /** How the OS names this browser as the default: bundle IDs, desktop files, or URL ProgIds. */ + defaultIDs: string[] + /** macOS application name, for `/Applications/.app` and `open -a`. */ + app?: string + /** Linux: binary names on PATH. Windows: full executable paths. */ + executables: string[] +} + +function browsers(): Browser[] { + if (process.platform === "darwin") { + const support = (dir: string) => path.join(home, "Library/Application Support", dir) + const browser = (name: string, app: string, bundleID: string, dirs: string[]): Browser => ({ + name, + app, + userData: support(dirs[0]!), + manifests: dirs.map((dir) => path.join(support(dir), "NativeMessagingHosts")), + defaultIDs: [bundleID], + executables: [], + }) + return [ + browser("Google Chrome", "Google Chrome", "com.google.Chrome", ["Google/Chrome"]), + browser("Chrome for Testing", "Google Chrome for Testing", "com.google.chrome.for.testing", ["Google/Chrome for Testing", "Google/ChromeForTesting"]), + browser("Google Chrome Beta", "Google Chrome Beta", "com.google.Chrome.beta", ["Google/Chrome Beta"]), + browser("Google Chrome Canary", "Google Chrome Canary", "com.google.Chrome.canary", ["Google/Chrome Canary"]), + browser("Chromium", "Chromium", "org.chromium.Chromium", ["Chromium"]), + browser("Microsoft Edge", "Microsoft Edge", "com.microsoft.edgemac", ["Microsoft Edge"]), + browser("Brave", "Brave Browser", "com.brave.Browser", ["BraveSoftware/Brave-Browser"]), + browser("Opera", "Opera", "com.operasoftware.Opera", ["com.operasoftware.Opera"]), + browser("Vivaldi", "Vivaldi", "com.vivaldi.Vivaldi", ["Vivaldi"]), + browser("Helium", "Helium", "net.imput.helium", ["net.imput.helium"]), + browser("Arc", "Arc", "company.thebrowser.Browser", ["Arc/User Data"]), + browser("Dia", "Dia", "company.thebrowser.dia", ["Dia/User Data"]), + browser("Comet", "Comet", "ai.perplexity.comet", ["Comet"]), + ] + } + if (windows) { + const local = process.env.LOCALAPPDATA ?? path.join(home, "AppData", "Local") + const roaming = process.env.APPDATA ?? path.join(home, "AppData", "Roaming") + const programs = [process.env.ProgramFiles, process.env["ProgramFiles(x86)"], local].filter((dir): dir is string => !!dir) + const installs = (relative: string) => programs.map((dir) => path.join(dir, relative)) + return [ + { name: "Google Chrome", userData: path.join(local, "Google", "Chrome", "User Data"), manifests: [], defaultIDs: ["ChromeHTML"], executables: installs("Google\\Chrome\\Application\\chrome.exe") }, + { name: "Microsoft Edge", userData: path.join(local, "Microsoft", "Edge", "User Data"), manifests: [], defaultIDs: ["MSEdgeHTM"], executables: installs("Microsoft\\Edge\\Application\\msedge.exe") }, + { name: "Brave", userData: path.join(local, "BraveSoftware", "Brave-Browser", "User Data"), manifests: [], defaultIDs: ["BraveHTML"], executables: installs("BraveSoftware\\Brave-Browser\\Application\\brave.exe") }, + { name: "Opera", userData: path.join(roaming, "Opera Software", "Opera Stable"), manifests: [], defaultIDs: ["OperaStable"], executables: installs("Programs\\Opera\\opera.exe") }, + { name: "Vivaldi", userData: path.join(local, "Vivaldi", "User Data"), manifests: [], defaultIDs: ["VivaldiHTM"], executables: installs("Vivaldi\\Application\\vivaldi.exe") }, + ] + } + // Chrome-family builds honor CHROME_CONFIG_HOME before XDG_CONFIG_HOME. + const chrome = process.env.CHROME_CONFIG_HOME ?? configRoot + const browser = (name: string, root: string, dir: string, executables: string[]): Browser => ({ + name, + userData: path.join(root, dir), + manifests: [path.join(root, dir, "NativeMessagingHosts")], + defaultIDs: executables, + executables, + }) + return [ + browser("Google Chrome", chrome, "google-chrome", ["google-chrome", "google-chrome-stable"]), + browser("Google Chrome Beta", chrome, "google-chrome-beta", ["google-chrome-beta"]), + browser("Google Chrome Unstable", chrome, "google-chrome-unstable", ["google-chrome-unstable"]), + browser("Chrome for Testing", chrome, "google-chrome-for-testing", ["google-chrome-for-testing"]), + browser("Chromium", chrome, "chromium", ["chromium", "chromium-browser"]), + browser("Microsoft Edge", configRoot, "microsoft-edge", ["microsoft-edge", "microsoft-edge-stable"]), + browser("Brave", configRoot, "BraveSoftware/Brave-Browser", ["brave-browser", "brave"]), + browser("Opera", configRoot, "opera", ["opera"]), + browser("Vivaldi", configRoot, "vivaldi", ["vivaldi", "vivaldi-stable"]), + browser("Helium", configRoot, "net.imput.helium", ["helium", "helium-browser"]), + ] +} + +/** The opencode binary (recorded for status): --opencode, $OPENCODE_BIN, or `opencode` on PATH. */ +function findOpencode(args: string[]) { + const explicit = flag(args, "--opencode") ?? process.env.OPENCODE_BIN + if (explicit) return path.resolve(explicit) + return findOnPath("opencode") +} + +function flag(args: string[], name: string) { + const index = args.indexOf(name) + return index === -1 ? undefined : args[index + 1] +} + +function readJson(file: string): T | undefined { + try { + return JSON.parse(readFileSync(file, "utf8")) as T + } catch { + return undefined + } +} + +// ---- opencode config: the browse MCP server --------------------------------------------------------- + +function configFile() { + const directory = path.join(configRoot, "opencode") + const candidates = ["opencode.json", "opencode.jsonc", ".opencode/opencode.json", ".opencode/opencode.jsonc"].map( + (name) => path.join(directory, name), + ) + return candidates.find((file) => existsSync(file) && statSync(file).isFile()) ?? candidates[0]! +} + +type Servers = Record + +/** Changes whenever the installed runtime does. */ +function fingerprint(entry: string) { + return createHash("sha256").update(readFileOr(entry, entry)).digest("hex").slice(0, 16) +} + +/** + * After an update, a relay still running the old build refuses the new CLI and MCP server; restart it from + * the new runtime. Restarting keeps browser tabs open but ends in-flight agent work, so it's announced. + */ +function restartOutdatedRelay(entry: string, node: string) { + const status = spawnSync(node, [entry, "status", "--json"], { encoding: "utf8", timeout: 15_000 }) + if (!/"stale":\s*true/.test(status.stdout ?? "")) return undefined + const restart = spawnSync(node, [entry, "relay", "restart"], { encoding: "utf8", timeout: 60_000 }) + return restart.status === 0 ? "restarted with the new version" : `could not restart: ${(restart.stderr || restart.stdout).trim()}` +} + +function mcpServers() { + return ((parse(readFileOr(configFile(), "{}")) ?? {}) as { mcp?: { servers?: Servers } }).mcp?.servers ?? {} +} + +/** Writes (or rewrites) the browse MCP server so it runs the installed runtime, replacing the old entry. */ +function configureMcp(entry: string) { + const file = configFile() + // A running MCP server keeps its old code after an update, and its relay calls then fail on the build check. + // Stamping the runtime's fingerprint into the entry changes the config whenever the runtime changes, which + // makes opencode restart the server with the new code. + const server = { type: "local", command: [process.execPath, entry, "mcp"], environment: { OPENCODE_BROWSER_RUNTIME: fingerprint(entry) } } + const renamed = removeMcp(LEGACY_MCP_NAME) + const existing = mcpServers()[MCP_NAME] + if (existing && JSON.stringify(existing) === JSON.stringify(server)) return `"${MCP_NAME}" is up to date` + const text = readFileOr(file, "{}") + const edits = modify(text, ["mcp", "servers", MCP_NAME], server, { formattingOptions: { tabSize: 2, insertSpaces: true } }) + mkdirSync(path.dirname(file), { recursive: true }) + writeFileSync(file, applyEdits(text, edits)) + if (renamed) return `"${LEGACY_MCP_NAME}" renamed to "${MCP_NAME}" in ${file}` + return existing ? `"${MCP_NAME}" updated in ${file}` : `"${MCP_NAME}" added to ${file}` +} + +function removeMcp(name: string) { + const file = configFile() + const text = readFileOr(file, "") + if (!text || !mcpServers()[name]) return false + writeFileSync(file, applyEdits(text, modify(text, ["mcp", "servers", name], undefined, {}))) + return true +} + +/** MCP servers from the separate Browser Control product, which OpenCode Browser replaces. */ +function legacyBrowserControl() { + return Object.entries(mcpServers()) + .filter(([name, server]) => name === "browser-control" || JSON.stringify(server.command ?? "").includes("browser-control")) + .map(([name]) => name) +} + +function readFileOr(file: string, fallback: string) { + try { + return readFileSync(file, "utf8") + } catch { + return fallback + } +} + +/** Removes the native messaging host and opencode plugin of earlier versions; true when any was there. */ +function removeLegacyHost() { + const leftovers = [ + ...browsers().flatMap((browser) => browser.manifests.map((directory) => path.join(directory, `${LEGACY_HOST_NAME}.json`))), + ...legacyFiles, + ].filter((file) => existsSync(file)) + leftovers.forEach((file) => rmSync(file, { force: true })) + const keys = windows + ? LEGACY_REGISTRY_ROOTS.map((root) => `${root}\\NativeMessagingHosts\\${LEGACY_HOST_NAME}`).filter( + (key) => spawnSync("reg", ["query", key, "/ve"]).status === 0, + ) + : [] + keys.forEach((key) => spawnSync("reg", ["delete", key, "/f"])) + return leftovers.length + keys.length > 0 +} + +// ---- runtime ---------------------------------------------------------------------------------------- + +/** + * Installs this exact version into the data root, so the MCP server keeps working after the npx cache is + * cleared, and an update is one `install` away. From source (development), runs in place. + * OPENCODE_BROWSER_PACKAGE installs a specific spec instead, for example a local tarball. + */ +function installRuntime() { + if (fromSource) return path.join(packageRoot, "src", "main.ts") + const spec = process.env.OPENCODE_BROWSER_PACKAGE ?? `${PACKAGE}@${opencodeBrowserVersion}` + mkdirSync(files.runtime, { recursive: true }) + if (!existsSync(path.join(files.runtime, "package.json"))) writeFileSync(path.join(files.runtime, "package.json"), "{\"private\":true}\n") + const npm = spawnSync(windows ? "npm.cmd" : "npm", ["install", "--prefix", files.runtime, "--no-audit", "--no-fund", "--loglevel=error", spec], { + encoding: "utf8", + shell: windows, + }) + if (npm.status !== 0) fail(`Could not install ${spec}: ${(npm.stderr || npm.stdout || "npm failed").trim()}`) + return path.join(files.runtime, "node_modules", PACKAGE, "dist", "cli.mjs") +} + +// ---- commands ------------------------------------------------------------------------------------- + +async function install(args: string[]) { + const opencode = findOpencode(args) + + mkdirSync(files.dir, { recursive: true }) + const entry = installRuntime() + log(`โœ“ OpenCode Browser ${opencodeBrowserVersion} installed${fromSource ? " (from source)" : ""}`) + writeFileSync(files.settings, JSON.stringify({ ...(opencode ? { opencode } : {}), entry, version: opencodeBrowserVersion } satisfies Settings, null, 2) + "\n") + if (removeLegacyHost()) log("โœ“ Removed the native messaging host of an earlier version") + + const node = fromSource ? (findOnPath("bun") ?? process.execPath) : process.execPath + log(opencode ? `โœ“ Using opencode at ${opencode}` : "! opencode not found. Install it (https://opencode.ai) to use the browse tools; they're configured for it.") + log(`โœ“ MCP server ${configureMcp(entry)}`) + const relay = restartOutdatedRelay(entry, node) + if (relay) log(`${relay.startsWith("restarted") ? "โœ“" : "!"} Relay ${relay}`) + const legacy = legacyBrowserControl() + if (legacy.length) + log(`! Browser Control MCP server${legacy.length === 1 ? "" : "s"} ${legacy.map((name) => `"${name}"`).join(", ")} also configured. OpenCode Browser replaces it; remove ${legacy.length === 1 ? "it" : "them"} from ${configFile()} to avoid two sets of browser tools.`) + + const connected = await connectedExtension() + if (existsSync(bundledExtension)) { + rmSync(files.extension, { recursive: true, force: true }) + cpSync(bundledExtension, files.extension, { recursive: true }) + // A browser already running an older unpacked build keeps its old code until it reloads; ask it to. + const reload = connected ? await reloadOutdatedExtension(connected) : "current" + if (reload === "reloaded") log("โœ“ Reloaded OpenCode Browser in your browser") + if (reload === "stale") + log("! OpenCode Browser didn't reload in your browser. Reload it on the browser's extensions page to finish the update.") + } + log("") + locateExtension({ allowOpen: !args.includes("--no-open"), connected: !!connected }) +} + +/** Printed before the relay's status by `opencode-browser status`. */ +export function printSetupStatus() { + const settings = readJson(files.settings) + log(settings?.version ? `Setup: installed` : "Setup: not installed. Run `npx opencode-browser-cli install`.") + log(`Version: ${settings?.version ?? "not installed"}${settings?.entry ? ` (${settings.entry})` : ""}`) + log(`opencode: ${settings?.opencode ?? findOpencode([]) ?? "not found"}`) + log(mcpServers()[MCP_NAME] ? `MCP: "${MCP_NAME}" configured` : "MCP: not configured") + log(`Logs: ${path.join(files.dir, "logs")}`) + log("") +} + +function extension() { + if (!existsSync(files.extension)) { + if (!existsSync(bundledExtension)) fail("This package has no bundled extension.") + mkdirSync(files.dir, { recursive: true }) + cpSync(bundledExtension, files.extension, { recursive: true }) + } + const opener = windows ? "explorer" : process.platform === "darwin" ? "open" : "xdg-open" + spawnSync(opener, [files.extension]) + log(`Load unpacked from: ${files.extension}`) +} + +function uninstall() { + const host = removeLegacyHost() + const mcp = [MCP_NAME, LEGACY_MCP_NAME].filter((name) => removeMcp(name)) + rmSync(files.dir, { recursive: true, force: true }) + log(`โœ“ Removed ${files.dir}`) + if (host) log("โœ“ Removed the native messaging host of an earlier version") + if (mcp.length) log(`โœ“ Removed the ${mcp.map((name) => `"${name}"`).join(" and ")} MCP server${mcp.length === 1 ? "" : "s"}`) + log("Remove the extension from your browser to finish.") +} + +type ExtensionStatus = { connected?: boolean; build?: string | null; origin?: string | null } + +const relayBase = () => `http://127.0.0.1:${Number(process.env.OPENCODE_BROWSER_PORT) || 19988}` + +const extensionStatus = () => + fetch(`${relayBase()}/extension/status`, { signal: AbortSignal.timeout(3_000) }) + .then((response) => (response.ok ? (response.json() as Promise) : undefined)) + .catch(() => undefined) + +/** The extension connected to the relay, if any; a relay restarted moments ago waits a second or two for it. */ +async function connectedExtension() { + let status = await extensionStatus() + for (let attempt = 0; status?.connected === false && attempt < 10; attempt++) { + await new Promise((resolve) => setTimeout(resolve, 500)) + status = await extensionStatus() + } + return status?.connected ? status : undefined +} + +/** + * Reloads the connected extension when it's the unpacked build (the store updates its own) and older than the files + * just copied, then checks the reload took effect: the build it reports after reconnecting must be the new one. + */ +async function reloadOutdatedExtension(before: ExtensionStatus): Promise<"reloaded" | "stale" | "current"> { + if (before.origin !== `chrome-extension://${UNPACKED_ID}`) return "current" + const bundled = readJson<{ build?: string }>(path.join(files.extension, "build.json"))?.build + if (bundled && before.build === bundled) return "current" + const sent = await fetch(`${relayBase()}/extension/reload`, { + method: "POST", + body: "{}", + headers: { "content-type": "application/json" }, + signal: AbortSignal.timeout(5_000), + }).then( + (response) => response.ok, + () => false, + ) + if (!sent) return "stale" + for (let attempt = 0; attempt < 20; attempt++) { + await new Promise((resolve) => setTimeout(resolve, 500)) + const after = await extensionStatus() + if (after?.connected && after.build !== before.build) return "reloaded" + } + return "stale" +} + +function findOnPath(name: string) { + const found = spawnSync(windows ? "where" : "which", [name], { encoding: "utf8" }) + return found.status === 0 ? found.stdout.split(/\r?\n/)[0]?.trim() || undefined : undefined +} + +// ---- which browsers have the extension ------------------------------------------------------------- + +type Profile = { dir: string; name: string } +type Match = { browser: Browser; profile: Profile; id: string } +/** blocked: the OS refused to read the browser's data (macOS privacy protection), so it may have the extension. */ +type Detection = { browser: Browser; blocked: boolean; enabled: Match[]; disabled: Match[] } + +/** + * Reports the browsers and profiles that have OpenCode Browser. When none does (and none is connected to the relay), + * opens its Chrome Web Store listing in the default browser, unless there is no browser to open here (SSH, no + * display, no terminal, --no-open) or a browser couldn't be checked and may already have it. + */ +function locateExtension(options: { allowOpen: boolean; connected: boolean }) { + const ready = "โœ“ Agents can use OpenCode Browser now. Click its toolbar button on a tab to let them use that tab too." + // Over SSH the browsers here aren't the ones the user looks at. + if (process.env.SSH_CONNECTION || process.env.SSH_TTY) + return log(options.connected ? ready : `Install OpenCode Browser in your browser from the Chrome Web Store: ${STORE_URL}`) + const detections = detectBrowsers() + const preferred = defaultBrowser(detections.map((detection) => detection.browser)) + reportDetections(detections, preferred) + // A connected extension is installed, even somewhere the scan doesn't look (a custom profile directory, a snap). + if (options.connected || detections.some((detection) => detection.enabled.length)) + return log(ready) + const off = detections.flatMap((detection) => detection.disabled) + if (off.length) + return log(`! OpenCode Browser is turned off in ${off.map((match) => `${match.browser.name} (${match.profile.name})`).join(", ")}. Turn it on in the browser's extensions page.`) + const blocked = detections.filter((detection) => detection.blocked) + const display = process.platform !== "linux" || !!(process.env.DISPLAY || process.env.WAYLAND_DISPLAY) + const target = preferred ?? detections.find((detection) => !detection.blocked)?.browser + const opened = options.allowOpen && display && !!process.stdout.isTTY && !blocked.length && target !== undefined + if (opened) open(target, STORE_URL) + log(`Install OpenCode Browser from the Chrome Web Store${opened ? ` (opened in ${target.name})` : ""}:`) + log(` ${STORE_URL}`) + if (blocked.length) log(` Already installed in ${blocked.map((detection) => detection.browser.name).join(", ")}? Then you're set.`) + log(` Or load the unpacked build: npx ${PACKAGE} extension`) +} + +/** Every browser with user data here, and the profiles that have OpenCode Browser. */ +function detectBrowsers() { + return browsers().flatMap((browser): Detection[] => { + const state = readLocked(path.join(browser.userData, "Local State")) + if (state.missing) return [] + // Leftover data of an uninstalled browser: nothing to open it with. + if (state.blocked) return launcher(browser) ? [{ browser, blocked: true, enabled: [], disabled: [] }] : [] + const matches = listProfiles(browser, state.text).flatMap((profile) => { + const settings = ["Secure Preferences", "Preferences"].map( + (file) => + (parseJson(readLocked(path.join(browser.userData, profile.dir, file)).text) as { extensions?: { settings?: Record } } | undefined) + ?.extensions?.settings ?? {}, + ) + const id = [STORE_ID, UNPACKED_ID].find((candidate) => settings.some((entries) => entries[candidate])) + if (!id) return [] + const setting = settings.find((entries) => entries[id])![id]! + return [{ browser, profile, id, enabled: !disabled(setting) }] + }) + return [ + { + browser, + blocked: false, + enabled: matches.filter((match) => match.enabled), + disabled: matches.filter((match) => !match.enabled), + }, + ] + }) +} + +type ExtensionSetting = { disable_reasons?: unknown } + +function disabled(setting: ExtensionSetting) { + const reasons = setting.disable_reasons + if (Array.isArray(reasons)) return reasons.length > 0 + return typeof reasons === "number" && reasons !== 0 +} + +/** Profiles from `Local State` (with their display names), else the profile directories themselves. */ +function listProfiles(browser: Browser, localState: string | undefined): Profile[] { + const cache = (parseJson(localState) as { profile?: { info_cache?: Record } } | undefined)?.profile?.info_cache + if (cache && Object.keys(cache).length) + return Object.entries(cache).map(([dir, info]) => ({ dir, name: info.name || dir })) + const dirs = (() => { + try { + return readdirSync(browser.userData) + } catch { + return [] + } + })() + return dirs.filter((dir) => /^(Default|Profile \d+)$/.test(dir)).map((dir) => ({ dir, name: dir })) +} + +function readLocked(file: string) { + try { + return { text: readFileSync(file, "utf8"), missing: false, blocked: false } + } catch (error) { + const code = (error as NodeJS.ErrnoException).code + return { text: undefined, missing: code === "ENOENT" || code === "ENOTDIR", blocked: code === "EPERM" || code === "EACCES" } + } +} + +function parseJson(text: string | undefined): unknown { + if (!text) return undefined + try { + return JSON.parse(text) + } catch { + return undefined + } +} + +/** The OS default web browser among the known ones; undefined when it can't be told or isn't Chromium. */ +function defaultBrowser(candidates: Browser[]) { + const id = defaultBrowserID() + if (!id) return undefined + const known = browsers().find((browser) => + browser.defaultIDs.some((name) => name.toLowerCase() === id.toLowerCase() || id.startsWith(`${name}.`)), + ) + return known && (candidates.find((browser) => browser.name === known.name) ?? known) +} + +function defaultBrowserID() { + if (process.platform === "darwin") { + const plist = path.join(home, "Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist") + const json = spawnSync("plutil", ["-convert", "json", "-o", "-", plist], { encoding: "utf8" }) + const handlers = + (parseJson(json.stdout) as { LSHandlers?: { LSHandlerURLScheme?: string; LSHandlerRoleAll?: string }[] } | undefined)?.LSHandlers ?? [] + return ["https", "http"] + .map((scheme) => handlers.find((handler) => handler.LSHandlerURLScheme === scheme)?.LSHandlerRoleAll) + .find((bundle) => !!bundle) + } + if (windows) { + const key = "HKCU\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\https\\UserChoice" + const query = spawnSync("reg", ["query", key, "/v", "ProgId"], { encoding: "utf8" }) + return /ProgId\s+REG_SZ\s+(\S+)/.exec(query.stdout ?? "")?.[1] + } + const xdg = spawnSync("xdg-settings", ["get", "default-web-browser"], { encoding: "utf8" }) + return xdg.status === 0 ? xdg.stdout.trim().replace(/\.desktop$/, "") || undefined : undefined +} + +function reportDetections(detections: Detection[], preferred: Browser | undefined) { + log(`Default browser: ${preferred?.name ?? "unknown"}`) + detections.forEach((detection) => { + const name = detection.browser.name + if (detection.blocked) return log(` ${name}: couldn't check (${blockedReason()})`) + if (detection.enabled.length) return log(` ${name}: OpenCode Browser in ${detection.enabled.map(describe).join(", ")}`) + if (detection.disabled.length) return log(` ${name}: OpenCode Browser turned off in ${detection.disabled.map(describe).join(", ")}`) + log(` ${name}: no OpenCode Browser`) + }) +} + +const describe = (match: Match) => `${match.profile.name}${match.id === UNPACKED_ID ? " (unpacked)" : ""}` +const blockedReason = () => (process.platform === "darwin" ? "macOS privacy protection" : "permission denied") + +/** Opens a URL in a specific browser; launching its executable forwards the URL to a running instance. */ +function open(browser: Browser, url: string) { + const executable = launcher(browser)?.executable + if (executable) { + const child = spawn(executable, [url], { detached: true, stdio: "ignore" }) + child.on("error", () => openWithSystem(browser, url)) + child.unref() + return + } + openWithSystem(browser, url) +} + +function openWithSystem(browser: Browser, url: string) { + if (process.platform === "darwin") return void spawnSync("open", browser.app ? ["-a", browser.app, url] : [url]) + // rundll32 hands the URL to its handler without cmd parsing the & in it. + if (windows) return void spawnSync("rundll32", ["url.dll,FileProtocolHandler", url]) + spawnSync("xdg-open", [url]) +} + +/** The browser's executable, or (macOS) just its app bundle when the executable can't be read. */ +function launcher(browser: Browser): { executable?: string } | undefined { + if (process.platform === "darwin") { + const bundle = [path.join("/Applications", `${browser.app}.app`), path.join(home, "Applications", `${browser.app}.app`)].find((dir) => existsSync(dir)) + if (!bundle) return undefined + const name = spawnSync("plutil", ["-extract", "CFBundleExecutable", "raw", "-o", "-", path.join(bundle, "Contents", "Info.plist")], { encoding: "utf8" }).stdout?.trim() + const executable = name ? path.join(bundle, "Contents", "MacOS", name) : undefined + return executable && existsSync(executable) ? { executable } : {} + } + const executable = windows ? browser.executables.find((file) => existsSync(file)) : browser.executables.map(findOnPath).find((file) => !!file) + return executable ? { executable } : undefined +} + +function log(line: string) { + process.stdout.write(line + "\n") +} + +function fail(message: string): never { + process.stderr.write(message + "\n") + process.exit(1) +} + +export async function runSetup(command: string, args: string[]) { + if (command === "install") return install(args) + if (command === "extension") return extension() + if (command === "uninstall") return uninstall() +} diff --git a/packages/browser-extension/cli/src/snapshot.ts b/packages/browser-extension/cli/src/snapshot.ts new file mode 100644 index 00000000000..1f117988685 --- /dev/null +++ b/packages/browser-extension/cli/src/snapshot.ts @@ -0,0 +1,1717 @@ +import path from "node:path" +import { Effect, Predicate } from "effect" +import type { ElementHandle, Frame, Locator, Page } from "patchright-core" +import { ariaSnapshotWithoutTextControlValues } from "./aria-snapshot.ts" +import { runPlaywrightOperation } from "./execute.ts" +import { runtimeFailureKind } from "./runtime-diagnostics.ts" + +type AriaSnapshotTarget = Locator | string + +type AriaSnapshotOptions = { + readonly timeout?: number +} + +export type AriaSnapshotHelper = (target?: AriaSnapshotTarget, options?: AriaSnapshotOptions) => Promise + +type SnapshotOptions = { + readonly within?: AriaSnapshotTarget + readonly interactive?: boolean + readonly compact?: boolean + readonly diff?: boolean + readonly delta?: boolean + readonly find?: string | RegExp + readonly context?: number + readonly depth?: number + readonly maxItems?: number + readonly timeout?: number +} + +export type SnapshotHelper = (options?: SnapshotOptions) => Promise +export type SnapshotRefHelper = (id: string) => Locator + +type SnapshotEntry = { + readonly depth: number + readonly baseDepth?: number + readonly key?: string + readonly parentKeys?: readonly string[] + readonly role: string + readonly name: string + readonly identityName?: string + readonly details?: string + readonly selector?: string + readonly selectorRole?: string + readonly priority: number +} + +export type SnapshotRefRegistry = { + page?: Page + url?: string + selectors: Map + previousSnapshot?: SnapshotBaseline + nextRef?: number + locatorScopes?: WeakMap + nextLocatorScope?: number + removeNavigationListener?: () => void +} + +type SnapshotRenderedEntry = { + readonly prefix: string + readonly details?: string + readonly selector?: string + readonly role?: string + readonly identityName?: string + readonly refId?: string +} + +type SnapshotBaseline = { + readonly page: Page + readonly signature: string + readonly entries: readonly SnapshotRenderedEntry[] +} + +export type InputTarget = AriaSnapshotTarget + +export const defaultAriaSnapshotTimeoutMs = 5_000 +const defaultSnapshotTimeoutMs = 10_000 +const snapshotRetryDelayMs = 25 + +export type InputField = { + readonly selector: InputTarget + readonly value: string +} + +export type ScreenshotWithLabelsOptions = { + readonly page?: Page + readonly path?: string + readonly registry?: SnapshotRefRegistry +} + +export type ScreenshotWithLabelsResult = { + readonly path?: string + readonly image?: Buffer + readonly size: number + readonly labelCount: number + readonly labels: readonly ScreenshotLabel[] +} + +type ScreenshotLabel = { + readonly ref: string + readonly selector: string + readonly role: string + readonly text: string + readonly context?: string + readonly tagName: string + readonly rect: ScreenshotLabelRect +} + +type ScreenshotLabelRect = { + readonly x: number + readonly y: number + readonly width: number + readonly height: number +} + +const delay = (milliseconds: number): Promise => + new Promise((resolve) => setTimeout(resolve, milliseconds)) + +export function createAriaSnapshotHelper(page: Pick): AriaSnapshotHelper { + return async (target, options) => { + const locator = target === undefined ? page.locator("body") : Predicate.isString(target) ? page.locator(target) : target + return await ariaSnapshotWithoutTextControlValues(locator, { + timeout: options?.timeout ?? defaultAriaSnapshotTimeoutMs, + }) + } +} + +/** Refs and diff baselines never survive the document they were captured from. */ +export function invalidateSnapshotDocument(registry: SnapshotRefRegistry): void { + registry.selectors.clear() + delete registry.page + delete registry.url + delete registry.previousSnapshot +} + +export function createSnapshotHelpers(page: Page, registry: SnapshotRefRegistry): { + readonly snapshot: SnapshotHelper + readonly ref: SnapshotRefHelper +} { + const refRoots = new WeakMap() + const snapshot: SnapshotHelper = async (options = {}) => { + const within = options.within + const withinSelector = Predicate.isString(within) ? within : undefined + const withinLocator = within !== undefined && !Predicate.isString(within) ? within : undefined + const refRoot = withinLocator ? refRoots.get(withinLocator) : undefined + const locator = withinLocator && !refRoot ? withinLocator : undefined + let locatorScope: number | undefined + if (locator) { + const scopes = registry.locatorScopes ??= new WeakMap() + locatorScope = scopes.get(locator) + if (locatorScope === undefined) { + locatorScope = registry.nextLocatorScope ?? 1 + registry.nextLocatorScope = locatorScope + 1 + scopes.set(locator, locatorScope) + } + } + const depth = Math.max(1, Math.min(16, Math.floor(options.depth ?? 10))) + const maxItems = Math.max(1, Math.min(200, Math.floor(options.maxItems ?? 80))) + const settings = { + compact: options.compact ?? true, + depth, + interactive: options.interactive ?? false, + maxCandidates: Math.max(1_000, maxItems * 20), + maxItems, + rootSelector: withinSelector ?? refRoot?.selector, + rootRole: refRoot?.role, + rootName: refRoot?.name, + } + const signature = JSON.stringify({ + compact: settings.compact, + depth: settings.depth, + interactive: settings.interactive, + maxItems: settings.maxItems, + scope: withinSelector !== undefined + ? { kind: "selector", selector: withinSelector } + : refRoot + ? { kind: "ref", selector: refRoot.selector, role: refRoot.role, name: refRoot.name } + : locator + ? { kind: "locator", scope: locatorScope } + : { kind: "page" }, + }) + const previousSnapshot = registry.previousSnapshot + if (options.diff && options.delta) { + throw new Error("snapshot() accepts either diff or delta, not both") + } + if (options.diff && !previousSnapshot) { + throw new Error("snapshot({ diff: true }) requires a previous snapshot() baseline in this session") + } + if (options.diff && (previousSnapshot?.page !== page || previousSnapshot.signature !== signature)) { + throw new Error("snapshot({ diff: true }) must use the same page and snapshot options as the previous snapshot") + } + + registry.removeNavigationListener?.() + registry.selectors.clear() + delete registry.page + delete registry.url + let navigatedDuringCapture = false + const onFrameNavigated = (frame: Frame) => { + if (frame !== page.mainFrame()) return + navigatedDuringCapture = true + invalidateSnapshotDocument(registry) + } + const removeNavigationListener = () => page.off("framenavigated", onFrameNavigated) + page.on("framenavigated", onFrameNavigated) + registry.removeNavigationListener = removeNavigationListener + + const capture = (rootOrSettings: Element | typeof settings, locatorSettings?: typeof settings) => { + type BrowserEntry = SnapshotEntry + const settings = locatorSettings ?? rootOrSettings as typeof locatorSettings & typeof rootOrSettings + + const normalize = (value: string): string => value.replace(/\s+/g, " ").trim() + const truncate = (value: string, maxLength: number): string => { + if (value.length <= maxLength) return value + const prefix = value.slice(0, maxLength + 1) + const boundary = prefix.lastIndexOf(" ") + return `${prefix.slice(0, boundary >= Math.floor(maxLength * 0.6) ? boundary : maxLength).trimEnd()}...` + } + const quote = (value: string): string => value.replace(/\\/g, "\\\\").replace(/"/g, '\\"') + const styleCache = new WeakMap() + const styleOf = (element: Element): CSSStyleDeclaration => { + let cached = styleCache.get(element) + if (!cached) { + cached = window.getComputedStyle(element) + styleCache.set(element, cached) + } + return cached + } + const visibleCache = new WeakMap() + const visibleAssociatedLabel = (element: Element): HTMLLabelElement | undefined => { + if (!(element instanceof HTMLInputElement) || (element.type !== "radio" && element.type !== "checkbox")) { + return undefined + } + return Array.from(element.labels ?? []).find((label) => isVisible(label)) + } + const isVisible = (element: Element): boolean => { + const cached = visibleCache.get(element) + if (cached !== undefined) return cached + const style = styleOf(element) + let result = true + if (style.display === "none" || style.visibility === "hidden") { + result = false + } else if (style.opacity === "0") { + result = Boolean(visibleAssociatedLabel(element)) + } else if (style.display === "contents") { + const children = [ + ...Array.from(element.children ?? []), + ...Array.from(element.shadowRoot?.children ?? []), + ] + result = children.some(isVisible) + } else { + const rect = element.getBoundingClientRect() + result = (rect.width >= 1 && rect.height >= 1) || Boolean(visibleAssociatedLabel(element)) + } + visibleCache.set(element, result) + return result + } + const explicitAriaName = (element: Element): string => { + const ariaLabel = element.getAttribute("aria-label") + if (ariaLabel) return normalize(ariaLabel) + const labelledBy = element.getAttribute("aria-labelledby") + if (labelledBy) { + const rootNode = element.getRootNode() as Document | ShadowRoot + const labelled = normalize(labelledBy.split(/\s+/).map((id) => (rootNode.getElementById?.(id) ?? document.getElementById(id))?.textContent ?? "").join(" ")) + if (labelled) return labelled + } + return "" + } + const titleName = (element: Element): string => normalize(element.getAttribute("title") ?? "") + const labelledName = (element: Element): string => explicitAriaName(element) || titleName(element) + const safeTextCache = new WeakMap() + const safeText = (element: Element): string => { + const cached = safeTextCache.get(element) + if (cached !== undefined) return cached + const parts: string[] = [] + const nearestBlock = (start: Element | null): Element => { + let current = start + while (current && current !== element && element.contains(current)) { + const display = styleOf(current).display + if (display && display !== "inline" && display !== "contents") return current + current = current.parentElement + } + return element + } + let lastBlock: Element | undefined + const rootStyle = styleOf(element) + if (element.hasAttribute("hidden") || element.getAttribute("aria-hidden") === "true" || rootStyle.display === "none" || rootStyle.visibility === "hidden" || rootStyle.opacity === "0") { + safeTextCache.set(element, "") + return "" + } + const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT, { + acceptNode(node) { + if (node instanceof Element) { + if (node.matches("input, textarea, select, script, style, noscript, template")) { + return NodeFilter.FILTER_REJECT + } + const style = styleOf(node) + if (node.hasAttribute("hidden") || node.getAttribute("aria-hidden") === "true" || style.display === "none" || style.visibility === "hidden" || style.opacity === "0") { + return NodeFilter.FILTER_REJECT + } + if (node !== element && (node.hasAttribute("aria-label") || node.hasAttribute("aria-labelledby"))) { + const ariaText = explicitAriaName(node) + if (ariaText) { + parts.push(` ${ariaText} `) + lastBlock = undefined + } + return NodeFilter.FILTER_REJECT + } + } + return NodeFilter.FILTER_ACCEPT + }, + }) + let node = walker.nextNode() + while (node) { + if (node.nodeType === Node.TEXT_NODE) { + const block = nearestBlock(node.parentElement) + if (lastBlock && lastBlock !== block) parts.push(" ") + parts.push(node.textContent ?? "") + lastBlock = block + } else if (node instanceof HTMLImageElement) { + const alt = node.getAttribute("alt") + if (alt) parts.push(` ${alt} `) + lastBlock = undefined + } else if (typeof HTMLSlotElement !== "undefined" && node instanceof HTMLSlotElement) { + for (const assigned of node.assignedNodes({ flatten: true })) { + if (assigned.nodeType === Node.TEXT_NODE) { + parts.push(assigned.textContent ?? "") + } else if (assigned instanceof Element) { + parts.push(safeText(assigned)) + } + } + lastBlock = undefined + } else if (node instanceof Element && node.tagName === "BR") { + parts.push(" ") + lastBlock = undefined + } + node = walker.nextNode() + } + const result = normalize(parts.join("")) + safeTextCache.set(element, result) + return result + } + const authorAccessibleName = (element: Element): string => { + const labelled = explicitAriaName(element) + if (labelled) return labelled + if ( + element instanceof HTMLInputElement || + element instanceof HTMLTextAreaElement || + element instanceof HTMLSelectElement || + element instanceof HTMLButtonElement + ) { + const label = element.labels?.[0] + if (label) { + const labelText = safeText(label) + if (labelText) return labelText + } + } + if (element instanceof HTMLInputElement && (element.type === "button" || element.type === "submit" || element.type === "reset")) { + const buttonValue = normalize(element.value || (element.type === "submit" ? "Submit" : element.type === "reset" ? "Reset" : "")) + if (buttonValue) return buttonValue + } + const title = titleName(element) + if (title) return title + const placeholder = element.getAttribute("placeholder") + if (placeholder) return normalize(placeholder) + return "" + } + const accessibleNameCache = new WeakMap() + const accessibleName = (element: Element): string => { + const cached = accessibleNameCache.get(element) + if (cached !== undefined) return cached + let result = "" + const labelled = explicitAriaName(element) + if (labelled) { + result = labelled + } else if (element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement || element instanceof HTMLSelectElement) { + result = authorAccessibleName(element) + } else { + const alt = element.getAttribute("alt") + const childAria = element.querySelector?.("[aria-label]")?.getAttribute("aria-label") || element.querySelector?.("svg title")?.textContent || "" + result = normalize(alt || safeText(element) || titleName(element) || childAria) + } + accessibleNameCache.set(element, result) + return result + } + const roleFor = (element: Element): string => { + const explicit = element.getAttribute("role") + if (explicit) return explicit + if (/^H[1-6]$/.test(element.tagName)) return "heading" + if (element instanceof HTMLAnchorElement || (element.tagName.toLowerCase() === "a" && element.hasAttribute("href"))) return "link" + if (element instanceof HTMLButtonElement) return "button" + if (element.tagName === "SUMMARY") return "summary" + if (element instanceof HTMLTextAreaElement) return "textbox" + if (element instanceof HTMLSelectElement) return element.hasAttribute("multiple") || element.size > 1 ? "listbox" : "combobox" + if (element instanceof HTMLInputElement) { + if (element.type === "checkbox") return "checkbox" + if (element.type === "radio") return "radio" + if (element.type === "number") return "spinbutton" + if (element.type === "range") return "slider" + if (["email", "search", "tel", "text", "url"].includes(element.type)) { + const listId = element.getAttribute("list")?.trim().split(/\s+/)[0] + const list = listId ? (element.getRootNode() as Document | ShadowRoot).getElementById(listId) : null + if (list?.tagName === "DATALIST") return "combobox" + } + if (element.type === "search") return "searchbox" + if (element.type === "button" || element.type === "submit" || element.type === "reset" || element.type === "file") return "button" + return "textbox" + } + if (element instanceof HTMLDialogElement) return "dialog" + if (element instanceof HTMLFieldSetElement || element.tagName === "DETAILS") return "group" + if (element instanceof HTMLTableElement) return "table" + if (element instanceof HTMLTableRowElement) return "row" + if (element instanceof HTMLUListElement || element instanceof HTMLOListElement) return "list" + if (element instanceof HTMLLIElement) return "listitem" + if (element.tagName === "PRE" || element.tagName === "CODE") return "code" + if (element.tagName === "NAV") return "navigation" + return element.tagName.toLowerCase() + } + const structuralName = (element: Element, role: string): string => { + const labelled = labelledName(element) + if (labelled) return labelled + if (element instanceof HTMLFieldSetElement) return normalize(element.querySelector(":scope > legend")?.textContent ?? "") + if (element instanceof HTMLTableElement) return normalize(element.caption?.textContent ?? "") + if (element instanceof HTMLDetailsElement) return normalize(element.querySelector(":scope > summary")?.textContent ?? "") + if (role === "dialog" || role === "alertdialog" || role === "group") { + return normalize(element.querySelector("h1, h2, h3, h4, h5, h6, [role='heading']")?.textContent ?? "") + } + if (role === "code") return normalize(element.textContent ?? "") + if (role === "row") { + const cells = Array.from(element.children).filter((child) => child.matches("th, td, [role='columnheader'], [role='rowheader'], [role='cell'], [role='gridcell']")) + const values = cells.map((cell) => safeText(cell)) + if (values.length === 0) return safeText(element) + const headerCells = cells.filter((cell) => cell.matches("th, [role='columnheader'], [role='rowheader']")) + const table = element.closest("table, [role='table'], [role='grid']") + const tableRows = table ? Array.from(table.querySelectorAll("tr, [role='row']")) : [] + const headerRow = tableRows.find((row) => { + if (row === element) return false + const rowCells = Array.from(row.children).filter((child) => child.matches("th, td, [role='columnheader'], [role='rowheader'], [role='cell'], [role='gridcell']")) + return rowCells.length > 0 && (rowCells.every((cell) => cell.matches("th, [role='columnheader']")) || rowCells.some((cell) => cell.matches("th[scope='col'], [role='columnheader']"))) + }) + if (headerRow) { + const headers = Array.from(headerRow.children) + .filter((child) => child.matches("th, [role='columnheader']")) + .map((cell) => safeText(cell)) + if (headers.length === values.length && headers.every(Boolean)) { + return values.map((value, index) => `${headers[index]}: ${value}`).join(" | ") + } + } + if (headerCells.length === cells.length) return values.join(" | ") + if (headerCells.length > 0) { + const headers = headerCells.map((cell) => safeText(cell)).filter(Boolean) + const data = cells.filter((cell) => !headerCells.includes(cell)).map((cell) => safeText(cell)).filter(Boolean) + return headers.length === 1 && data.length > 0 ? `${headers[0]}: ${data.join(" | ")}` : values.join(" | ") + } + return values.join(" | ") + } + if (role === "listitem") return safeText(element) + return "" + } + let autoScopedMain = false + const root = rootOrSettings instanceof Element + ? rootOrSettings + : (() => { + if (settings.rootSelector) { + const matches = document.querySelectorAll(settings.rootSelector) + if (matches.length !== 1) { + throw new Error(`snapshot within expects exactly one match for selector: ${settings.rootSelector}; got ${matches.length}`) + } + return matches[0] as Element + } + const fallbackRoot = (document.body ?? document.documentElement) as Element | null + if (!fallbackRoot) return null + const dialogs = Array.from(document.querySelectorAll("dialog, [role='dialog'], [role='alertdialog']")).filter(isVisible) + const modals = dialogs.filter((dialog) => dialog.matches(":modal, [aria-modal='true']") || Boolean(dialog.closest?.("[data-focus-lock-disabled='false']"))) + if (modals.length === 1) return modals[0] as Element + const isOpenListboxOrMenu = (menu: Element): boolean => { + if (!isVisible(menu)) return false + if (menu.getAttribute("aria-label") === "slider" || menu.getAttribute("aria-roledescription") === "carousel") return false + const items = Array.from(menu.querySelectorAll("[role='option'], [role^='menuitem']")).filter(isVisible) + return items.length > 0 && !items.some((item) => item.getAttribute("role") === "option" && item.querySelector?.("a[href], button")) + } + const portalMenus = Array.from(document.querySelectorAll("[role='listbox'], [role='menu']")).filter(isOpenListboxOrMenu) + const mains = Array.from(document.querySelectorAll("main")).filter(isVisible) + if (dialogs.length > 0 || (mains.length === 1 && portalMenus.some((menu) => !mains[0]!.contains?.(menu)))) { + return fallbackRoot + } + if (mains.length === 1) { + autoScopedMain = true + return mains[0] as Element + } + return fallbackRoot + })() + if (!root) { + return { entries: [], truncated: false } + } + if ((settings.rootRole && roleFor(root) !== settings.rootRole) || (settings.rootName && accessibleName(root) !== settings.rootName)) { + throw new Error("Snapshot ref no longer identifies the captured element; call snapshot() again") + } + const detailsFor = (element: Element): string | undefined => { + const details: string[] = [] + if (element instanceof HTMLInputElement) { + if (element.type === "checkbox" || element.type === "radio") details.push(element.checked ? "checked" : "unchecked") + } + const ariaChecked = element.getAttribute("aria-checked") + if ((ariaChecked === "true" || ariaChecked === "false" || ariaChecked === "mixed") && !(element instanceof HTMLInputElement)) { + details.push(ariaChecked === "true" ? "checked" : ariaChecked === "false" ? "unchecked" : "checked=mixed") + } + if (element instanceof HTMLSelectElement) { + const selected = element.selectedOptions[0]?.textContent + if (selected) details.push(`selected="${quote(normalize(selected).slice(0, 80))}"`) + details.push(`${element.options.length} options`) + } + if (element instanceof HTMLButtonElement || element instanceof HTMLInputElement || element instanceof HTMLSelectElement || element instanceof HTMLTextAreaElement) { + if (element.disabled) details.push("disabled") + } + if (element.getAttribute("aria-disabled") === "true" && !details.includes("disabled")) { + details.push("disabled") + } + const expanded = element.getAttribute("aria-expanded") + if (expanded) details.push(`expanded=${expanded}`) + if (element instanceof HTMLDetailsElement) details.push(`expanded=${element.open}`) + if (element instanceof HTMLDialogElement) { + details.push(`open=${element.open}`) + const modal = element.getAttribute("aria-modal") + if (modal) details.push(`modal=${modal}`) + } + if (element.tagName === "SUMMARY" && element.parentElement instanceof HTMLDetailsElement) details.push(`expanded=${element.parentElement.open}`) + const selected = element.getAttribute("aria-selected") + if (selected) details.push(`selected=${selected}`) + const current = element.getAttribute("aria-current") + if (current) details.push(`current=${current}`) + if (element instanceof HTMLTableElement) details.push(`${element.rows.length} rows`) + if (element instanceof HTMLUListElement || element instanceof HTMLOListElement) details.push(`${element.children.length} items`) + if (element instanceof HTMLFieldSetElement) details.push(`${element.elements.length} controls`) + return details.length ? details.join(" ") : undefined + } + const isShadowRoot = (node: unknown): node is ShadowRoot => + typeof ShadowRoot !== "undefined" && node instanceof ShadowRoot + const parentElementOrHost = (node: Element | null): Element | null => { + if (!node) return null + if (node.parentElement) return node.parentElement + const rootNode = node.getRootNode?.() + return isShadowRoot(rootNode) ? rootNode.host : null + } + const closestDeep = (element: Element, selector: string): Element | null => { + let current: Element | null = element + while (current) { + const match = current.closest?.(selector) ?? null + if (match) return match + const rootNode = current.getRootNode?.() + current = isShadowRoot(rootNode) ? rootNode.host : null + } + return null + } + const querySelectorAllDeep = (scope: Element | Document | ShadowRoot, selector: string): Element[] => { + if (!scope.children) { + return Array.from(scope.querySelectorAll(selector)) + } + const results: Element[] = [] + const visit = (node: Element | Document | ShadowRoot) => { + for (let child = node.firstElementChild; child; child = child.nextElementSibling) { + if (child.matches(selector)) results.push(child) + if (child.shadowRoot) visit(child.shadowRoot) + if (child.firstElementChild) visit(child) + } + } + if (scope instanceof Element && scope.shadowRoot) visit(scope.shadowRoot) + visit(scope) + return results + } + const localCssCache = new WeakMap() + const localCssPath = (element: Element, scope: Document | ShadowRoot): string => { + const cached = localCssCache.get(element) + if (cached !== undefined) return cached + const compute = (): string => { + const id = element.getAttribute("id") + if (id) { + const candidate = `#${CSS.escape(id)}` + if (scope.querySelectorAll(candidate).length === 1) return candidate + } + for (const attribute of ["data-testid", "data-test-id", "data-test", "name", "aria-label", "placeholder"]) { + const value = element.getAttribute(attribute) + if (value) { + const candidate = `[${attribute}="${CSS.escape(value)}"]` + if (scope.querySelectorAll(candidate).length === 1) return candidate + } + } + const tag = element.tagName.toLowerCase() + const role = element.getAttribute("role") + const roleSuffix = role ? `[role="${quote(role)}"]` : "" + let checkedClasses = 0 + for (const className of element.classList ?? []) { + if (className.includes(":") || className.includes("[") || className.includes("/")) continue + if (++checkedClasses > 4) break + const candidate = `${tag}.${CSS.escape(className)}${roleSuffix}` + if (scope.querySelectorAll(candidate).length === 1) return candidate + } + const parent = element.parentElement + if (!parent) { + if (isShadowRoot(scope)) { + const siblings = Array.from(scope.children).filter((sibling) => sibling.tagName === element.tagName) + return `${tag}:nth-of-type(${siblings.indexOf(element) + 1})` + } + return tag + } + const siblings = Array.from(parent.children).filter((sibling) => sibling.tagName === element.tagName) + return `${localCssPath(parent, scope)} > ${tag}:nth-of-type(${siblings.indexOf(element) + 1})` + } + const result = compute() + localCssCache.set(element, result) + return result + } + const cssPath = (element: Element): string => { + const rootNode = element.getRootNode?.() + if (isShadowRoot(rootNode)) { + return `${cssPath(rootNode.host)} >> ${localCssPath(element, rootNode)}` + } + return localCssPath(element, document) + } + const rootHeadings = Array.from(root.querySelectorAll("h1, h2, h3, h4, h5, h6, [role='heading']")).map((heading) => { + const candidate = /^H([1-6])$/.exec(heading.tagName)?.[1] + return { + heading, + level: candidate ? Number(candidate) : Number(heading.getAttribute("aria-level") ?? 1), + } + }) + const headingDepthCache = new WeakMap() + const headingDepth = (element: Element): number => { + const cached = headingDepthCache.get(element) + if (cached !== undefined) return cached + const ownLevel = /^H([1-6])$/.exec(element.tagName)?.[1] + if (ownLevel) { + const depth = Number(ownLevel) - 1 + headingDepthCache.set(element, depth) + return depth + } + let treeTarget = element + while (isShadowRoot(treeTarget.getRootNode?.())) { + treeTarget = (treeTarget.getRootNode() as ShadowRoot).host + } + let level = 0 + for (const { heading, level: candidateLevel } of rootHeadings) { + if (heading === treeTarget || (heading.compareDocumentPosition(treeTarget) & Node.DOCUMENT_POSITION_FOLLOWING) === 0) continue + level = candidateLevel + } + headingDepthCache.set(element, level) + return level + } + + const structuralSelector = "fieldset, [role='group'], [role='radiogroup'], dialog, [role='dialog'], [role='alertdialog'], [role='listbox'], [role='menu'], [role='tablist'], details, table, [role='table'], tr, [role='row'], ul, ol, [role='list'], li, [role='listitem'], pre" + const interactiveSelector = [ + "a[href]", "button", "input", "textarea", "select", "summary", + "[role='button']", "[role='link']", "[role='tab']", + "[role='menuitem']", "[role='menuitemcheckbox']", "[role='menuitemradio']", + "[role='option']", "[role='switch']", "[role='checkbox']", "[role='radio']", + "[role='combobox']", "[role='searchbox']", "[role='textbox']", + "[role='slider']", "[role='spinbutton']", "[role='treeitem']", + "[contenteditable]", + ].join(",") + const structuralKeys = new WeakMap() + let nextStructuralKey = 1 + const structuralKey = (element: Element): string => { + const existing = structuralKeys.get(element) + if (existing) return existing + const key = `s${nextStructuralKey++}` + structuralKeys.set(element, key) + return key + } + const structuralParentKeys = (element: Element): string[] => { + const keys: string[] = [] + let parent = parentElementOrHost(element) + while (parent && parent !== root) { + if (parent.matches(structuralSelector)) keys.push(structuralKey(parent)) + parent = parentElementOrHost(parent) + } + return keys + } + const primaryLinks = new WeakMap() + const isPrimaryLink = (element: Element): boolean => { + if ( + element.closest?.("h1, h2, h3, h4, h5, h6, [role='heading']") || + element.querySelector?.("h1, h2, h3, h4, h5, h6, [role='heading']") + ) { + return true + } + const group = element.closest("article, li, tr, dt, [role='listitem'], [role='row']") + if (!group || !root.contains(group)) return false + if (!primaryLinks.has(group)) { + const rawLinks = Array.from(group.querySelectorAll("a[href]")) + if (group.matches("article, [role='article']") && rawLinks.length > 12) { + primaryLinks.set(group, null) + return false + } + const links = rawLinks.filter(isVisible) + let primary: Element | null = null + let primaryScore = -1 + for (const link of links) { + const name = accessibleName(link) + const headingBonus = link.closest("h1, h2, h3, h4, h5, h6, [role='heading']") ? 1_000 : 0 + const commentBonus = /\b\d+\s+comments?\b/i.test(name) ? 500 : 0 + const score = name.length + headingBonus + commentBonus + if (score > primaryScore) { + primary = link + primaryScore = score + } + } + primaryLinks.set(group, primary) + } + if (primaryLinks.get(group) !== element) return false + if (group.matches("tr, [role='row']")) { + const groupTextLength = safeText(group).length + return groupTextLength > 0 && accessibleName(element).length / groupTextLength >= 0.15 + } + return true + } + const isLayoutTable = (table: Element | null): boolean => { + if (!table || !settings.compact) return false + if (table.querySelector?.("table, [role='table']")) return true + const hasHeaders = Boolean( + labelledName(table) || + (table as HTMLTableElement).caption || + table.querySelector?.("th, [role='columnheader'], [role='rowheader']"), + ) + if (hasHeaders) return false + const rowCount = table instanceof HTMLTableElement + ? table.rows.length + : table.querySelectorAll("tr, [role='row']").length + return rowCount <= 1 || rowCount >= 20 + } + const isRedundantHeadingForLink = (element: Element): boolean => { + if (!settings.compact || element === root) return false + const parentInteractive = element.closest?.("a[href], button, [role='button'], [role='option'], [role='menuitem'], [role='menuitemradio'], [role='menuitemcheckbox']") + if (parentInteractive && (root.contains?.(parentInteractive) ?? true) && isVisible(parentInteractive)) { + return true + } + const headingText = accessibleName(element) + if (!headingText) return false + const childLinks = Array.from(element.querySelectorAll?.("a[href]") ?? []).filter(isVisible) + if (childLinks.length === 1) { + const linkText = accessibleName(childLinks[0]!) + if (linkText && (linkText === headingText || linkText.startsWith(headingText))) { + return true + } + } + const card = element.closest?.("article, [role='article']") + if (card && (root.contains?.(card) ?? true)) { + const rawCardLinks = Array.from(card.querySelectorAll("a[href]")) + if (rawCardLinks.length <= 12 && rawCardLinks.filter(isVisible).some((link) => accessibleName(link) === headingText)) { + return true + } + } + return false + } + const seenCardLinks = new WeakMap>() + const isDuplicateCardLink = (element: Element, displayName: string): boolean => { + if (!settings.compact || !displayName || !element.matches("a[href]")) return false + const card = element.closest?.("article, [role='article'], li, [role='listitem'], tr, [role='row']") + if (!card || !(root.contains?.(card) ?? true)) return false + const href = element.getAttribute("href") ?? "" + if (!href) return false + let seen = seenCardLinks.get(card) + if (!seen) { + seen = new Set() + seenCardLinks.set(card, seen) + } + const key = `${href}\0${displayName}` + if (seen.has(key)) return true + seen.add(key) + return false + } + const isRedundantListItem = (element: Element): boolean => { + if (!settings.compact || element === root) return false + if (element.querySelector?.("ul, ol, [role='list'], h1, h2, h3, h4, h5, h6, [role='heading']")) { + return true + } + if (element.querySelector?.("p")) return false + const controls = Array.from(element.querySelectorAll?.("a[href], button") ?? []).filter(isVisible) + if (controls.length === 0) return false + const itemLength = safeText(element).length + return itemLength > 0 && controls.some((control) => accessibleName(control).length >= itemLength * 0.65) + } + const priorityFor = (options: { readonly role: string; readonly interactive: boolean; readonly primaryLink: boolean; readonly structuralEssential: boolean; readonly inActiveOverlay: boolean }): number => { + if (options.role === "alert" || options.role === "status" || options.role === "navigation" || options.structuralEssential || options.inActiveOverlay) return -1 + if (options.role === "heading") return 0 + if (options.role === "link" && options.primaryLink) return 0 + if (options.interactive && (options.role !== "link" || options.primaryLink)) return 1 + if (options.role === "link") return 3 + return 2 + } + + type PendingEntry = BrowserEntry & { readonly interactiveElement?: Element } + const entries: PendingEntry[] = [] + let truncated = false + const add = (entry: PendingEntry): void => { + if (entry.depth > settings.depth) return + if (entries.length >= settings.maxCandidates) { + truncated = true + return + } + entries.push(entry) + } + const candidateSelector = [ + "h1", "h2", "h3", "h4", "h5", "h6", "[role='heading']", + "nav", "[role='navigation']", "[role='alert']", "[role='status']", "p", + structuralSelector, + interactiveSelector, + ].join(",") + const headerSelector = "input, textarea, select, button, [role='searchbox'], [role='combobox'], [role='button'], a[href][aria-label]" + const headerRoots = autoScopedMain && typeof document.querySelectorAll === "function" + ? Array.from(document.querySelectorAll("header, [role='banner']")).filter((h) => isVisible(h) && !root.contains?.(h)) + : [] + const headerCandidateSet = new Set( + headerRoots.flatMap((h) => + querySelectorAllDeep(h, headerSelector).filter((el) => !el.closest?.("nav, [role='navigation']")), + ), + ) + const candidates = [ + ...headerCandidateSet, + ...(root.matches(candidateSelector) ? [root] : []), + ...querySelectorAllDeep(root, candidateSelector), + ] + const collapsedNavigation = new Set() + const nonCollapsibleNavigation = new WeakSet() + let reservedLists = 0 + + for (const element of candidates) { + if (entries.length >= settings.maxCandidates) { + truncated = true + break + } + if (settings.compact && !headerCandidateSet.has(element)) { + const navigation = closestDeep(element, "nav, [role='navigation'], aside, [role='complementary'], [data-slot='sidebar'], [data-sidebar='sidebar']") + if (navigation && collapsedNavigation.has(navigation)) { + continue + } + if (navigation && navigation !== root && !navigation.contains?.(root) && !nonCollapsibleNavigation.has(navigation)) { + const isCollapsibleNav = isVisible(navigation) && ( + navigation.matches("nav, [role='navigation']") || + (querySelectorAllDeep(navigation, "a[href]").length >= 8 && !navigation.querySelector?.("h1, main, [role='main'], input, textarea, select")) + ) + if (isCollapsibleNav) { + collapsedNavigation.add(navigation) + const count = querySelectorAllDeep(navigation, "a[href], button").length + add({ depth: headingDepth(navigation), role: "navigation", name: truncate(labelledName(navigation), 100) || "Navigation", details: `${count} controls`, priority: 0 }) + continue + } + nonCollapsibleNavigation.add(navigation) + } + } + if (!isVisible(element)) continue + const role = roleFor(element) + const isHeading = role === "heading" + if (isHeading && isRedundantHeadingForLink(element)) continue + if ( + role === "combobox" && + !(element instanceof HTMLInputElement || element instanceof HTMLButtonElement || element instanceof HTMLSelectElement || element instanceof HTMLTextAreaElement) && + element.querySelector?.("input, textarea, select") + ) { + continue + } + if (role === "option" && element.querySelector?.("a[href], button")) { + continue + } + const isInteractive = element.matches(interactiveSelector) + const isSafetyText = role === "alert" || role === "status" + const isParagraph = element.matches("p") + const isStructural = !isInteractive && element.matches(structuralSelector) + if (isStructural) { + if (role === "listbox" && (element.getAttribute("aria-label") === "slider" || element.getAttribute("aria-roledescription") === "carousel")) { + continue + } + if (role === "listitem" && isRedundantListItem(element)) { + continue + } + if (role === "table" && isLayoutTable(element)) { + continue + } + if (role === "row" && (element.querySelector?.("table, [role='table']") || isLayoutTable(element.closest?.("table, [role='table']") ?? null))) { + continue + } + } + if (!isHeading && !isInteractive && !isSafetyText && !isStructural && (settings.interactive || !isParagraph)) continue + if (settings.interactive && isParagraph && !isSafetyText) continue + if ( + settings.compact && + isParagraph && + !isSafetyText && + element.parentElement?.matches("li, [role='listitem']") && + !isRedundantListItem(element.parentElement) && + safeText(element).length >= safeText(element.parentElement).length * 0.8 + ) { + continue + } + const displayName = isStructural ? structuralName(element, role) : accessibleName(element) + if (isInteractive && isDuplicateCardLink(element, displayName)) continue + const nameFromAuthorOnly = role === "combobox" || role === "listbox" || role === "textbox" || role === "searchbox" || role === "spinbutton" || role === "slider" + const identityName = isInteractive + ? (nameFromAuthorOnly ? authorAccessibleName(element) : displayName) + : displayName + const isDisabled = ((element as HTMLButtonElement).disabled === true) || element.getAttribute("aria-disabled") === "true" + if (isInteractive && isDisabled && !displayName && !element.getAttribute("name")) continue + const fallbackName = role === "group" ? "Group" + : role === "dialog" || role === "alertdialog" ? "Dialog" + : role === "listbox" ? "Listbox" + : role === "menu" ? "Menu" + : role === "table" ? "Table" + : role === "list" ? "List" + : role === "tablist" ? "Tab list" + : isInteractive ? element.getAttribute("name") || element.getAttribute("data-testid") || element.getAttribute("data-test-id") || element.getAttribute("data-test") || role + : "" + const name = truncate(displayName || fallbackName, isParagraph || isSafetyText || isStructural ? 180 : 120) + if (!name) continue + const details = isHeading ? `level=${headingDepth(element) + 1}` : detailsFor(element) + const primaryLink = (role === "link" && isPrimaryLink(element)) || headerCandidateSet.has(element) + const baseDepth = headingDepth(element) + const parentKeys = structuralParentKeys(element) + const overlayAncestor = element.closest?.("dialog, [role='dialog'], [role='alertdialog'], [role='listbox'], [role='menu']") ?? null + const inActiveOverlay = Boolean( + (isInteractive || role === "dialog" || role === "alertdialog" || role === "listbox" || role === "menu") && + overlayAncestor && + overlayAncestor.getAttribute("aria-label") !== "slider" && + overlayAncestor.getAttribute("aria-roledescription") !== "carousel", + ) + const labelProxy = (() => { + if (!isInteractive) return undefined + const label = visibleAssociatedLabel(element) + if (!label) return undefined + const rect = element.getBoundingClientRect() + if (rect.width < 1 || rect.height < 1) return label + if (styleOf(element).opacity !== "0") return undefined + const hit = document.elementFromPoint?.(rect.left + rect.width / 2, rect.top + rect.height / 2) + return hit === element ? undefined : label + })() + add({ + depth: baseDepth + parentKeys.length, + baseDepth, + ...(isStructural ? { key: structuralKey(element) } : {}), + ...(parentKeys.length > 0 ? { parentKeys } : {}), + role, + name, + ...(isInteractive && identityName && !labelProxy ? { identityName } : {}), + ...(labelProxy ? { selectorRole: "label" } : {}), + ...(isInteractive ? { interactiveElement: labelProxy ?? element } : {}), + ...(details ? { details } : {}), + priority: priorityFor({ + role: headerCandidateSet.has(element) ? "heading" : role, + interactive: isInteractive, + primaryLink, + inActiveOverlay, + structuralEssential: isStructural && + role !== "row" && + role !== "listitem" && + role !== "code" && + (role !== "group" || Boolean(displayName)) && + (role !== "list" || reservedLists++ < Math.max(1, Math.floor(settings.maxItems / 10))), + }), + }) + } + const selected: BrowserEntry[] = entries + .map((entry, index) => ({ entry, index })) + .sort((left, right) => left.entry.priority - right.entry.priority || left.index - right.index) + .slice(0, settings.maxItems) + .sort((left, right) => left.index - right.index) + .map(({ entry: { interactiveElement, ...rest } }) => ({ + ...rest, + ...(interactiveElement ? { selector: cssPath(interactiveElement) } : {}), + })) + const needsSettle = Boolean( + !settings.rootSelector && + typeof MutationObserver !== "undefined" && + document.body && + ( + Boolean(document.querySelector?.("[aria-busy='true'], .skeleton:not(.no-skeleton)")) || + (!selected.some((entry) => Boolean(entry.selector)) && typeof performance !== "undefined" && performance.now() < 2_500) + ), + ) + return { + entries: selected, + truncated: truncated || selected.length < entries.length, + ...(needsSettle ? { needsSettle: true } : {}), + } + } + const browserCapture = new Function( + "rootOrSettings", + "locatorSettings", + `const __name = (target) => target +return (${capture.toString()})(rootOrSettings, locatorSettings)`, + ) as typeof capture + const timeoutMs = options.timeout ?? defaultSnapshotTimeoutMs + let result: Awaited> + if (locator) { + result = await locator.evaluate(browserCapture, settings, { timeout: timeoutMs }) + } else { + const deadline = Date.now() + timeoutMs + let captureAttempts = 0 + while (true) { + navigatedDuringCapture = false + try { + result = await Effect.runPromise(runPlaywrightOperation({ + label: "Compact snapshot", + timeoutMs: Math.max(100, deadline - Date.now()), + run: () => page.evaluate(browserCapture, settings), + })) + if (navigatedDuringCapture && !options.diff && ++captureAttempts < 3 && Date.now() + snapshotRetryDelayMs < deadline) { + await delay(snapshotRetryDelayMs) + continue + } + if (result.needsSettle && !options.diff && captureAttempts === 0 && Date.now() + 120 < deadline) { + captureAttempts++ + await page.evaluate(`new Promise((resolve) => { + let quietTimer = window.setTimeout(done, 120); + const maxTimer = window.setTimeout(done, 550); + const observer = new MutationObserver(() => { + window.clearTimeout(quietTimer); + quietTimer = window.setTimeout(done, 55); + }); + function done() { + observer.disconnect(); + window.clearTimeout(quietTimer); + window.clearTimeout(maxTimer); + resolve(); + } + if (document.body) { + observer.observe(document.body, { childList: true, subtree: true, attributes: true }); + } else { + done(); + } + })`).catch(() => {}) + continue + } + break + } catch (error) { + if (withinSelector !== undefined && /not a valid selector|querySelectorAll/i.test(error instanceof Error ? error.message : String(error))) { + result = await page.locator(withinSelector).evaluate(browserCapture, { ...settings, rootSelector: undefined }, { timeout: timeoutMs }) + break + } + const kind = runtimeFailureKind(error) + if ((kind === "context-destroyed" || kind === "context-missing") && !options.diff && Date.now() + snapshotRetryDelayMs < deadline) { + await delay(snapshotRetryDelayMs) + continue + } + throw error + } + } + } + + if (navigatedDuringCapture) { + removeNavigationListener() + delete registry.removeNavigationListener + throw new Error("Page navigated while snapshot() was capturing; call snapshot() again") + } + registry.page = page + registry.url = page.url() + registry.selectors.clear() + const structuralEntries = new Map(result.entries.flatMap((entry) => entry.key ? [[entry.key, entry] as const] : [])) + const resolvedDepths = new Map() + const resolvedDepth = (entry: SnapshotEntry): number => { + const cached = resolvedDepths.get(entry) + if (cached !== undefined) return cached + const parent = entry.parentKeys?.map((key) => structuralEntries.get(key)).find((candidate) => candidate !== undefined) + const depth = parent ? resolvedDepth(parent) + 1 : entry.baseDepth ?? entry.depth + resolvedDepths.set(entry, depth) + return depth + } + const minimumDepth = result.entries.reduce((minimum, entry) => Math.min(minimum, resolvedDepth(entry)), Number.POSITIVE_INFINITY) + const depthOffset = Number.isFinite(minimumDepth) ? minimumDepth : 0 + const rawEntries: SnapshotRenderedEntry[] = result.entries.map((entry) => { + const name = entry.name.replace(/\\/g, "\\\\").replace(/"/g, '\\"') + return { + prefix: `${" ".repeat(Math.max(0, resolvedDepth(entry) - depthOffset))}- ${entry.role} "${name}"`, + ...(entry.details ? { details: entry.details } : {}), + ...(entry.selector ? { selector: entry.selector, role: entry.selectorRole ?? entry.role } : {}), + ...(entry.identityName ? { identityName: entry.identityName } : {}), + } + }) + if (result.truncated) rawEntries.push({ prefix: `- ... truncated after ${maxItems} items` }) + + const compatiblePrevious = previousSnapshot?.page === page && previousSnapshot.signature === signature + ? previousSnapshot + : undefined + let nextRef = registry.nextRef ?? 1 + const reusableRefs = new Map() + for (const entry of compatiblePrevious?.entries ?? []) { + if (!entry.refId) continue + const key = snapshotRefIdentity(entry) + if (!key) continue + const refs = reusableRefs.get(key) ?? [] + refs.push(entry.refId) + reusableRefs.set(key, refs) + } + const entries = rawEntries.map((entry): SnapshotRenderedEntry => { + const key = snapshotRefIdentity(entry) + if (!key) return entry + const reused = reusableRefs.get(key)?.shift() + return { ...entry, refId: reused ?? `e${nextRef++}` } + }) + registry.nextRef = nextRef + + const registerRef = (entry: SnapshotRenderedEntry, id: string): void => { + if (!entry.selector || !entry.role) return + registry.selectors.set(id, { + selector: entry.selector, + role: entry.role, + ...(entry.identityName ? { name: entry.identityName } : {}), + }) + } + + for (const entry of entries) { + if (entry.refId) registerRef(entry, entry.refId) + } + + const useDiff = options.diff === true || (options.delta === true && compatiblePrevious !== undefined) + if (!useDiff) { + const lines = entries.map((entry) => { + return formatSnapshotLine(entry, entry.refId) + }) + registry.previousSnapshot = { page, signature, entries } + return options.find === undefined + ? lines.join("\n") + : findSnapshotLines(lines, options.find, options.context) + } + + const operations = diffSnapshotEntries(compatiblePrevious?.entries ?? [], entries) + const lines: string[] = [] + let additions = 0 + let removals = 0 + let unchanged = 0 + for (const operation of operations) { + if (operation.kind === "unchanged") { + unchanged++ + continue + } + if (operation.kind === "removed") { + removals++ + lines.push(formatSnapshotDiffLine("-", operation.entry)) + continue + } + additions++ + lines.push(formatSnapshotDiffLine("+", operation.entry, operation.entry.refId)) + } + lines.push(`${additions} ${additions === 1 ? "addition" : "additions"}, ${removals} ${removals === 1 ? "removal" : "removals"}, ${unchanged} unchanged`) + registry.previousSnapshot = { page, signature, entries } + return lines.join("\n") + } + + const ref: SnapshotRefHelper = (id) => { + if (!Predicate.isString(id) || !id.trim()) { + throw new Error(`Unknown snapshot ref: ${String(id)}; call snapshot() to get current refs`) + } + const normalized = id.startsWith("@") ? id.slice(1) : id + if (registry.page !== page || registry.url !== page.url()) { + throw new Error("Snapshot refs are stale after a page change; call snapshot() again") + } + const snapshotRef = registry.selectors.get(normalized) + if (!snapshotRef) { + throw new Error(`Unknown snapshot ref: ${id}; call snapshot() to get current refs`) + } + const locator = page.locator(snapshotRef.selector) + const role = snapshotRefAriaRole(snapshotRef.role) + const resolved = role + ? locator.and(page.getByRole(role, snapshotRef.name ? { name: snapshotRef.name, exact: true } : undefined)) + : locator + refRoots.set(resolved, snapshotRef) + return resolved + } + + return { snapshot, ref } +} + +function snapshotRefIdentity(entry: SnapshotRenderedEntry): string | undefined { + if (!entry.selector || !entry.role) return undefined + return JSON.stringify([entry.selector, entry.role, entry.identityName ?? null]) +} + +function findSnapshotLines(lines: readonly string[], query: string | RegExp, requestedContext: number | undefined): string { + const context = Math.max(0, Math.min(10, Math.floor(requestedContext ?? 2))) + const matches: number[] = [] + for (const [index, line] of lines.entries()) { + const matched = Predicate.isString(query) + ? line.toLowerCase().includes(query.toLowerCase()) + : (() => { + query.lastIndex = 0 + return query.test(line) + })() + if (matched) matches.push(index) + } + if (matches.length === 0) { + return `No snapshot lines matched ${Predicate.isString(query) ? JSON.stringify(query) : query.toString()}.` + } + const included = new Set() + for (const index of matches) { + for (let candidate = Math.max(0, index - context); candidate <= Math.min(lines.length - 1, index + context); candidate++) { + included.add(candidate) + } + } + const output: string[] = [] + let previous = -2 + for (const index of [...included].sort((left, right) => left - right)) { + if (index > previous + 1) output.push("...") + output.push(lines[index]!) + previous = index + } + return [`${matches.length} matching snapshot ${matches.length === 1 ? "line" : "lines"}:`, ...output].join("\n") +} + +function formatSnapshotLine(entry: SnapshotRenderedEntry, id?: string): string { + const suffix = [id ? `ref=${id}` : undefined, entry.details].filter(Boolean).join(" ") + return `${entry.prefix}${suffix ? ` [${suffix}]` : ""}` +} + +function formatSnapshotDiffLine(marker: "+" | "-", entry: SnapshotRenderedEntry, id?: string): string { + const line = formatSnapshotLine(entry, id) + const bullet = /^(\s*)- (.*)$/.exec(line) + return bullet ? `${marker} ${bullet[1]}${bullet[2]}` : `${marker} ${line}` +} + +function diffSnapshotEntries( + previous: readonly SnapshotRenderedEntry[], + current: readonly SnapshotRenderedEntry[], +): readonly ( + | { readonly kind: "unchanged"; readonly entry: SnapshotRenderedEntry } + | { readonly kind: "removed"; readonly entry: SnapshotRenderedEntry } + | { readonly kind: "added"; readonly entry: SnapshotRenderedEntry } +)[] { + const previousLines = previous.map((entry) => formatSnapshotLine(entry)) + const currentLines = current.map((entry) => formatSnapshotLine(entry)) + const lengths = Array.from({ length: previous.length + 1 }, () => Array(current.length + 1).fill(0)) + for (let previousIndex = previous.length - 1; previousIndex >= 0; previousIndex--) { + for (let currentIndex = current.length - 1; currentIndex >= 0; currentIndex--) { + lengths[previousIndex]![currentIndex] = previousLines[previousIndex] === currentLines[currentIndex] + ? lengths[previousIndex + 1]![currentIndex + 1]! + 1 + : Math.max(lengths[previousIndex + 1]![currentIndex]!, lengths[previousIndex]![currentIndex + 1]!) + } + } + + const operations: Array< + | { readonly kind: "unchanged"; readonly entry: SnapshotRenderedEntry } + | { readonly kind: "removed"; readonly entry: SnapshotRenderedEntry } + | { readonly kind: "added"; readonly entry: SnapshotRenderedEntry } + > = [] + let previousIndex = 0 + let currentIndex = 0 + while (previousIndex < previous.length || currentIndex < current.length) { + if ( + previousIndex < previous.length && + currentIndex < current.length && + previousLines[previousIndex] === currentLines[currentIndex] + ) { + operations.push({ kind: "unchanged", entry: current[currentIndex]! }) + previousIndex++ + currentIndex++ + continue + } + if ( + previousIndex < previous.length && + (currentIndex >= current.length || lengths[previousIndex + 1]![currentIndex]! >= lengths[previousIndex]![currentIndex + 1]!) + ) { + operations.push({ kind: "removed", entry: previous[previousIndex]! }) + previousIndex++ + continue + } + operations.push({ kind: "added", entry: current[currentIndex]! }) + currentIndex++ + } + return operations +} + +function snapshotRefAriaRole(role: string): Parameters[0] | undefined { + switch (role) { + case "button": + case "checkbox": + case "combobox": + case "link": + case "listbox": + case "menuitem": + case "menuitemcheckbox": + case "menuitemradio": + case "option": + case "radio": + case "searchbox": + case "slider": + case "spinbutton": + case "switch": + case "tab": + case "textbox": + case "treeitem": + return role + default: + return undefined + } +} + +export async function fillInput(options: { readonly page: Page; readonly target: InputTarget; readonly value: string }): Promise { + if (Predicate.isString(options.target)) { + await fillInputs(options.page, [{ selector: options.target, value: options.value }]) + return + } + const locator = options.target + await locator.evaluate((element, nextValue) => { + if (element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement) { + const prototype = Object.getPrototypeOf(element) as HTMLInputElement | HTMLTextAreaElement + const valueSetter = Object.getOwnPropertyDescriptor(element, "value")?.set + const prototypeValueSetter = Object.getOwnPropertyDescriptor(prototype, "value")?.set + if (prototypeValueSetter && valueSetter !== prototypeValueSetter) { + prototypeValueSetter.call(element, nextValue) + } else { + element.value = nextValue + } + } else if (element instanceof HTMLElement && element.isContentEditable) { + element.textContent = nextValue + } else { + throw new Error("fillInput expects an input, textarea, or contenteditable locator") + } + element.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "insertText", data: nextValue })) + element.dispatchEvent(new Event("change", { bubbles: true })) + }, options.value, { timeout: 30_000 }) +} + +export async function fillInputs(page: Page, fields: ReadonlyArray): Promise { + const locatorHandles: ElementHandle[] = [] + try { + const resolvedFields: Array<{ readonly target: string | ElementHandle; readonly label: string; readonly value: string }> = [] + for (const field of fields) { + if (Predicate.isString(field.selector)) { + resolvedFields.push({ target: field.selector, label: `selector: ${field.selector}`, value: field.value }) + continue + } + const matches = await field.selector.elementHandles() + locatorHandles.push(...matches) + if (matches.length !== 1) { + throw new Error(`fillInputs expects exactly one match for locator; got ${matches.length}`) + } + resolvedFields.push({ target: matches[0]!, label: "locator", value: field.value }) + } + + await page.evaluate((inputFields) => { + return inputFields.map((field) => { + let element: Node | undefined + if (typeof field.target === "string") { + const matches: Element[] = [] + const roots: Array = [document] + for (let index = 0; index < roots.length; index += 1) { + const root = roots[index] + if (!root) continue + matches.push(...root.querySelectorAll(field.target)) + for (const candidate of root.querySelectorAll("*")) { + if (candidate.shadowRoot) roots.push(candidate.shadowRoot) + } + } + if (matches.length !== 1) { + if (matches.length === 0) { + throw new Error(`fillInputs found no match for ${field.label} in the document or open shadow roots; closed shadow roots are unavailable. Try locator.fill() if Playwright can resolve the field.`) + } + throw new Error(`fillInputs expects exactly one match for ${field.label}; got ${matches.length}`) + } + element = matches[0] + } else { + element = field.target + } + if (element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement) { + const prototype = Object.getPrototypeOf(element) as HTMLInputElement | HTMLTextAreaElement + const valueSetter = Object.getOwnPropertyDescriptor(element, "value")?.set + const prototypeValueSetter = Object.getOwnPropertyDescriptor(prototype, "value")?.set + if (prototypeValueSetter && valueSetter !== prototypeValueSetter) { + prototypeValueSetter.call(element, field.value) + } else { + element.value = field.value + } + } else if (element instanceof HTMLElement && element.isContentEditable) { + element.textContent = field.value + } else { + throw new Error(`fillInputs expects input, textarea, or contenteditable ${field.label}`) + } + element.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "insertText", data: field.value })) + element.dispatchEvent(new Event("change", { bubbles: true })) + return field.label + }) + }, resolvedFields) + } finally { + await Promise.all(locatorHandles.map((handle) => handle.dispose().catch(() => {}))) + } +} + +export async function screenshotWithLabels(options: ScreenshotWithLabelsOptions = {}): Promise { + if (!options.page) { + throw new Error("screenshotWithLabels requires a page") + } + if (options.path !== undefined && !path.isAbsolute(options.path)) { + throw new Error("screenshotWithLabels requires an absolute path") + } + + const page = options.page + const labels = await showScreenshotLabels(page) + if (options.registry) { + const registry = options.registry + registry.removeNavigationListener?.() + registry.selectors.clear() + registry.page = page + registry.url = page.url() + for (const label of labels) { + registry.selectors.set(label.ref, { + selector: label.selector, + role: "screenshot-label", + }) + } + const onFrameNavigated = (frame: Frame) => { + if (frame !== page.mainFrame()) return + invalidateSnapshotDocument(registry) + } + const removeNavigationListener = () => page.off("framenavigated", onFrameNavigated) + page.on("framenavigated", onFrameNavigated) + registry.removeNavigationListener = removeNavigationListener + } + try { + const screenshot = await page.screenshot(options.path ? { path: options.path } : {}) + return { + ...(options.path ? { path: options.path } : { image: screenshot }), + size: screenshot.byteLength, + labelCount: labels.length, + labels, + } + } finally { + await hideScreenshotLabels(page) + } +} + +async function showScreenshotLabels(page: Page): Promise { + return await page.evaluate(() => { + type BrowserLabel = { + readonly ref: string + readonly selector: string + readonly role: string + readonly text: string + readonly context?: string + readonly tagName: string + readonly rect: { + readonly x: number + readonly y: number + readonly width: number + readonly height: number + } + } + + const containerId = "__opencode_browser_screenshot_labels__" + const markerClass = "__opencode_browser_screenshot_label__" + const opencodeBrowserWindow = window as Window & { __opencodeBrowserScreenshotLabelsTimer?: number } + if (opencodeBrowserWindow.__opencodeBrowserScreenshotLabelsTimer) { + window.clearTimeout(opencodeBrowserWindow.__opencodeBrowserScreenshotLabelsTimer) + delete opencodeBrowserWindow.__opencodeBrowserScreenshotLabelsTimer + } + document.getElementById(containerId)?.remove() + + const selectors = [ + "button", + "a[href]", + "input", + "textarea", + "select", + "summary", + '[role="button"]', + '[role="link"]', + '[role="tab"]', + '[role="menuitem"]', + '[role="menuitemcheckbox"]', + '[role="menuitemradio"]', + '[role="option"]', + '[role="switch"]', + '[role="checkbox"]', + '[role="radio"]', + '[role="combobox"]', + '[role="searchbox"]', + '[role="textbox"]', + '[role="slider"]', + '[role="spinbutton"]', + '[role="treeitem"]', + "[onclick]", + "[contenteditable]", + ] + const selectorString = selectors.join(",") + const isShadowRoot = (node: unknown): node is ShadowRoot => + typeof ShadowRoot !== "undefined" && node instanceof ShadowRoot + const queryDeep = (scope: Element | Document | ShadowRoot): Element[] => { + if (!scope.children) { + return Array.from(scope.querySelectorAll(selectorString)) + } + const results: Element[] = [] + const visit = (node: Element | Document | ShadowRoot) => { + for (let child = node.firstElementChild; child; child = child.nextElementSibling) { + if (child.matches(selectorString)) results.push(child) + if (child.shadowRoot) visit(child.shadowRoot) + if (child.firstElementChild) visit(child) + } + } + visit(scope) + return results + } + const candidates = queryDeep(document) + .filter((element) => { + const rect = element.getBoundingClientRect() + const style = window.getComputedStyle(element) + if (rect.width < 4 || rect.height < 4) { + return false + } + if (rect.right < 0 || rect.bottom < 0 || rect.left > window.innerWidth || rect.top > window.innerHeight) { + return false + } + return style.visibility !== "hidden" && style.display !== "none" && style.opacity !== "0" + }) + .slice(0, 80) + + const localSelectorForElement = (element: Element, scope: Document | ShadowRoot): string => { + const id = element.getAttribute("id") + if (id) { + return `#${CSS.escape(id)}` + } + for (const attr of ["data-testid", "data-test-id", "data-test"]) { + const val = element.getAttribute(attr) + if (val) return `[${attr}="${CSS.escape(val)}"]` + } + const name = element.getAttribute("name") + if (name) { + return `${element.tagName.toLowerCase()}[name="${CSS.escape(name)}"]` + } + const parent = element.parentElement + if (!parent) { + if (isShadowRoot(scope)) { + const siblings = Array.from(scope.children).filter((child) => child.tagName === element.tagName) + return `${element.tagName.toLowerCase()}:nth-of-type(${siblings.indexOf(element) + 1})` + } + return element.tagName.toLowerCase() + } + const siblings = Array.from(parent.children).filter((child) => { + return child.tagName === element.tagName + }) + const index = siblings.indexOf(element) + 1 + return `${localSelectorForElement(parent, scope)} > ${element.tagName.toLowerCase()}:nth-of-type(${index})` + } + + const selectorForElement = (element: Element): string => { + const rootNode = element.getRootNode?.() + if (isShadowRoot(rootNode)) { + return `${selectorForElement(rootNode.host)} >> ${localSelectorForElement(element, rootNode)}` + } + return localSelectorForElement(element, document) + } + + const roleForElement = (element: Element): string => { + const explicitRole = element.getAttribute("role") + if (explicitRole) { + return explicitRole + } + if (element instanceof HTMLAnchorElement) { + return "link" + } + if (element instanceof HTMLButtonElement) { + return "button" + } + if (element instanceof HTMLInputElement) { + return element.type || "input" + } + if (element instanceof HTMLTextAreaElement) { + return "textarea" + } + if (element instanceof HTMLSelectElement) { + return "select" + } + if (element instanceof HTMLElement && element.isContentEditable) { + return "contenteditable" + } + return element.getAttribute("onclick") ? "onclick" : element.tagName.toLowerCase() + } + + const textForElement = (element: Element): string => { + const ariaLabel = element.getAttribute("aria-label") + const title = element.getAttribute("title") + const placeholder = element.getAttribute("placeholder") + const value = element instanceof HTMLInputElement ? element.value : "" + return (ariaLabel || placeholder || value || title || element.textContent || "").replace(/\s+/g, " ").trim().slice(0, 80) + } + + const normalizeText = (value: string): string => { + return value.replace(/\s+/g, " ").trim() + } + + const trimContext = (value: string): string => { + return normalizeText(value).slice(0, 60) + } + + const accessibleTextForElement = (element: Element): string => { + const ariaLabel = element.getAttribute("aria-label") + if (ariaLabel) { + return ariaLabel + } + const labelledBy = element.getAttribute("aria-labelledby") + if (labelledBy) { + const text = labelledBy + .split(/\s+/) + .map((id) => document.getElementById(id)?.textContent ?? "") + .join(" ") + if (normalizeText(text)) { + return text + } + } + if (element instanceof HTMLFieldSetElement) { + const legend = element.querySelector(":scope > legend") + if (legend?.textContent) { + return legend.textContent + } + } + const heading = element.querySelector(":scope > h1, :scope > h2, :scope > h3, :scope > h4, :scope > h5, :scope > h6") + if (heading?.textContent) { + return heading.textContent + } + return element.textContent ?? "" + } + + const nearestPrecedingHeading = (element: Element): string => { + const elementRect = element.getBoundingClientRect() + const headings = Array.from(document.querySelectorAll("h1, h2, h3, h4, h5, h6, [role='heading']")) + let nearest: Element | undefined + let nearestDistance = Number.POSITIVE_INFINITY + for (const heading of headings) { + const rect = heading.getBoundingClientRect() + if (rect.bottom > elementRect.top || rect.right < 0 || rect.left > window.innerWidth) { + continue + } + const distance = elementRect.top - rect.bottom + if (distance < nearestDistance) { + nearest = heading + nearestDistance = distance + } + } + return nearest?.textContent ?? "" + } + + const contextForElement = (element: Element, ownText: string): string | undefined => { + const contextElement = element.closest("tr, [role='row'], li, [role='listitem'], fieldset, section, article, form, [aria-label], [aria-labelledby]") + const rawContext = contextElement && contextElement !== element + ? accessibleTextForElement(contextElement) + : nearestPrecedingHeading(element) + const context = trimContext(rawContext) + const label = trimContext(ownText) + if (!context || context.toLowerCase() === label.toLowerCase()) { + return undefined + } + return context + } + + const labels: BrowserLabel[] = candidates.map((element, index) => { + const rect = element.getBoundingClientRect() + const text = textForElement(element) + const context = contextForElement(element, text) + return { + ref: `e${index + 1}`, + selector: selectorForElement(element), + role: roleForElement(element), + text, + ...(context ? { context } : {}), + tagName: element.tagName.toLowerCase(), + rect: { + x: Math.round(rect.left), + y: Math.round(rect.top), + width: Math.round(rect.width), + height: Math.round(rect.height), + }, + } + }) + + const container = document.createElement("div") + container.id = containerId + container.style.cssText = "position:fixed;left:0;top:0;z-index:2147483647;pointer-events:none;font:12px ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;" + + const style = document.createElement("style") + style.textContent = ` + .${markerClass} { + position: fixed; + min-width: 18px; + box-sizing: border-box; + padding: 1px 4px; + border: 1px solid #7c3aed; + border-radius: 4px; + background: #a78bfa; + color: #111827; + font-weight: 700; + line-height: 16px; + text-align: center; + box-shadow: 0 1px 3px rgba(17, 24, 39, 0.35); + } + ` + container.appendChild(style) + + const markers = labels.map((label) => { + const marker = document.createElement("div") + marker.className = markerClass + marker.textContent = label.ref + marker.style.left = `${Math.max(0, label.rect.x)}px` + marker.style.top = `${Math.max(0, label.rect.y - 18)}px` + return marker + }) + container.append(...markers) + + document.documentElement.appendChild(container) + opencodeBrowserWindow.__opencodeBrowserScreenshotLabelsTimer = window.setTimeout(() => { + document.getElementById(containerId)?.remove() + delete opencodeBrowserWindow.__opencodeBrowserScreenshotLabelsTimer + }, 30_000) + return labels + }) +} + +async function hideScreenshotLabels(page: Page): Promise { + await page.evaluate(() => { + const opencodeBrowserWindow = window as Window & { __opencodeBrowserScreenshotLabelsTimer?: number } + if (opencodeBrowserWindow.__opencodeBrowserScreenshotLabelsTimer) { + window.clearTimeout(opencodeBrowserWindow.__opencodeBrowserScreenshotLabelsTimer) + delete opencodeBrowserWindow.__opencodeBrowserScreenshotLabelsTimer + } + document.getElementById("__opencode_browser_screenshot_labels__")?.remove() + }) +} diff --git a/packages/browser-extension/cli/src/target-registry.ts b/packages/browser-extension/cli/src/target-registry.ts new file mode 100644 index 00000000000..36e54d9060b --- /dev/null +++ b/packages/browser-extension/cli/src/target-registry.ts @@ -0,0 +1,489 @@ +import { Schema } from "effect" +import { isJsonObject, type JsonObject, type TargetInfo } from "./protocol.ts" +import type { ChildTarget, ConnectedTarget, StoredFrameEvents } from "./relay-types.ts" + +export type TargetOwnershipReservation = { + readonly targetId: string + readonly targetSessionId: string + readonly tabId: number + readonly sessionId: string + readonly previousOpenCodeBrowserSessionId?: string +} + +export type TargetOwnershipChange = { + readonly targetIds: readonly string[] + readonly tabIds: readonly number[] +} + +export interface TargetOwnership { + reserveTargetOwnership(targetId: string, sessionId: string): TargetOwnershipReservation + rollbackTargetOwnership(reservation: TargetOwnershipReservation): TargetOwnershipChange + commitTargetOwnership(options: { + readonly reservation: TargetOwnershipReservation + readonly previousAdoptedTargetId?: string + }): TargetOwnershipChange + releaseTargetOwnership(targetId: string, sessionId: string): TargetOwnershipChange +} + +export class TargetOwnershipError extends Schema.TaggedError()( + "TargetRegistry.TargetOwnershipError", + { + message: Schema.String, + reason: Schema.Literals(["not-found", "owned", "generation-changed"]), + ownerSessionId: Schema.optionalKey(Schema.String), + }, +) {} + +export class MemoryTargetOwnership implements TargetOwnership { + private readonly owners = new Map() + + reserveTargetOwnership(targetId: string, sessionId: string): TargetOwnershipReservation { + const owner = this.owners.get(targetId) + if (owner && owner !== sessionId) { + throw targetOwnedError(owner) + } + this.owners.set(targetId, sessionId) + return { + targetId, + targetSessionId: targetId, + tabId: -1, + sessionId, + ...(owner ? { previousOpenCodeBrowserSessionId: owner } : {}), + } + } + + rollbackTargetOwnership(reservation: TargetOwnershipReservation): TargetOwnershipChange { + if (this.owners.get(reservation.targetId) !== reservation.sessionId) { + return emptyOwnershipChange + } + if (reservation.previousOpenCodeBrowserSessionId) { + this.owners.set(reservation.targetId, reservation.previousOpenCodeBrowserSessionId) + } else { + this.owners.delete(reservation.targetId) + } + return ownershipChange(reservation.targetId, reservation.tabId) + } + + commitTargetOwnership(options: { + readonly reservation: TargetOwnershipReservation + readonly previousAdoptedTargetId?: string + }): TargetOwnershipChange { + const changed = [options.reservation.targetId] + if (options.previousAdoptedTargetId && options.previousAdoptedTargetId !== options.reservation.targetId) { + if (this.owners.get(options.previousAdoptedTargetId) === options.reservation.sessionId) { + this.owners.delete(options.previousAdoptedTargetId) + changed.push(options.previousAdoptedTargetId) + } + } + return { targetIds: changed, tabIds: [] } + } + + releaseTargetOwnership(targetId: string, sessionId: string): TargetOwnershipChange { + if (this.owners.get(targetId) !== sessionId) { + return emptyOwnershipChange + } + this.owners.delete(targetId) + return { targetIds: [targetId], tabIds: [] } + } +} + +export type ConnectedTargetInfoUpdate = + | { readonly kind: "root"; readonly target: ConnectedTarget } + | { readonly kind: "child"; readonly target: ChildTarget } + +export type RootTargetChange = + | { readonly kind: "added" | "updated"; readonly target: ConnectedTarget } + | { + readonly kind: "replaced" + readonly target: ConnectedTarget + readonly previous: ConnectedTarget + readonly childSessionIds: readonly string[] + } + +export function shouldExposeChildTarget(target: ChildTarget): boolean { + return target.targetInfo.type !== "page" || target.targetInfo.url !== "" +} + +export class TargetRegistry { + readonly targets = new Map() + readonly tabTargets = new Map() + readonly targetsByTargetId = new Map() + readonly childTargets = new Map() + readonly childTargetsByTargetId = new Map() + readonly tabFrameEvents = new Map>() + private readonly pendingOwnershipReservations = new Map() + private readonly stagedRootTargets = new Map() + + clear(): void { + this.targets.clear() + this.tabTargets.clear() + this.targetsByTargetId.clear() + this.childTargets.clear() + this.childTargetsByTargetId.clear() + this.tabFrameEvents.clear() + this.pendingOwnershipReservations.clear() + this.stagedRootTargets.clear() + } + + addRootTarget(target: ConnectedTarget, options: { + readonly preserveChildParentSessionId?: string + readonly preserveFrameEvents?: boolean + } = {}): RootTargetChange { + const existingForTab = this.tabTargets.get(target.tabId) + const generationChanged = existingForTab !== undefined && ( + existingForTab.sessionId !== target.sessionId || + existingForTab.targetInfo.targetId !== target.targetInfo.targetId + ) + const nextTarget = generationChanged ? this.inheritRootOwnership(target, existingForTab) : target + const detached = generationChanged + ? this.detachRootTargetState(target.tabId, options) + : undefined + const childSessionIds = detached?.childSessionIds ?? [] + if (existingForTab && !generationChanged) { + this.targets.delete(existingForTab.sessionId) + this.targetsByTargetId.delete(existingForTab.targetInfo.targetId) + } + const existingForTargetId = this.targetsByTargetId.get(nextTarget.targetInfo.targetId) + if (existingForTargetId) { + this.targets.delete(existingForTargetId.sessionId) + this.tabTargets.delete(existingForTargetId.tabId) + } + this.targets.set(nextTarget.sessionId, nextTarget) + this.tabTargets.set(nextTarget.tabId, nextTarget) + this.targetsByTargetId.set(nextTarget.targetInfo.targetId, nextTarget) + return generationChanged + ? { kind: "replaced", target: nextTarget, previous: existingForTab, childSessionIds } + : { kind: existingForTab ? "updated" : "added", target: nextTarget } + } + + stageRootTarget(target: ConnectedTarget): ConnectedTarget { + const existing = this.tabTargets.get(target.tabId) + const staged = existing ? this.inheritRootOwnership(target, existing) : target + this.stagedRootTargets.set(target.tabId, staged) + this.tabFrameEvents.delete(target.tabId) + return staged + } + + private inheritRootOwnership(target: ConnectedTarget, existing: ConnectedTarget): ConnectedTarget { + const pendingReservation = this.pendingOwnershipReservations.get(existing.targetInfo.targetId) + const inheritedOpenCodeBrowserSessionId = pendingReservation + ? pendingReservation.previousOpenCodeBrowserSessionId + : existing.opencodeBrowserSessionId + const { opencodeBrowserSessionId: _incomingOwner, ...targetWithoutOwner } = target + return { + ...targetWithoutOwner, + owner: existing.owner, + ...(inheritedOpenCodeBrowserSessionId ? { opencodeBrowserSessionId: inheritedOpenCodeBrowserSessionId } : {}), + } + } + + stagedRootTarget(tabId: number): ConnectedTarget | undefined { + return this.stagedRootTargets.get(tabId) + } + + routingRootTarget(tabId: number): ConnectedTarget | undefined { + return this.stagedRootTargets.get(tabId) ?? this.tabTargets.get(tabId) + } + + commitStagedRootTarget(tabId: number, sessionId: string): RootTargetChange | undefined { + const staged = this.stagedRootTargets.get(tabId) + if (!staged || staged.sessionId !== sessionId) return undefined + this.stagedRootTargets.delete(tabId) + return this.addRootTarget(staged, { + preserveChildParentSessionId: staged.sessionId, + preserveFrameEvents: true, + }) + } + + addChildTarget(target: ChildTarget): readonly ChildTarget[] { + const replaced: ChildTarget[] = [] + const existingForSession = this.childTargets.get(target.sessionId) + if (existingForSession && existingForSession.targetInfo.targetId !== target.targetInfo.targetId) { + replaced.push(existingForSession) + this.detachChildTargetState(existingForSession.sessionId) + } + const existingForTargetId = this.childTargetsByTargetId.get(target.targetInfo.targetId) + if (existingForTargetId && existingForTargetId.sessionId !== target.sessionId) { + replaced.push(existingForTargetId) + this.detachChildTargetState(existingForTargetId.sessionId) + } + this.childTargets.set(target.sessionId, target) + this.childTargetsByTargetId.set(target.targetInfo.targetId, target) + return replaced + } + + rootTargetCount(): number { + return this.targets.size + } + + listRootTargets(): ConnectedTarget[] { + return Array.from(this.targets.values()) + } + + getRootTargetByTabId(tabId: number): ConnectedTarget | undefined { + return this.tabTargets.get(tabId) + } + + getRootTargetBySessionId(sessionId: string): ConnectedTarget | undefined { + return this.targets.get(sessionId) ?? this.listRootTargets().find((target) => { + return target.opencodeBrowserSessionId === sessionId + }) + } + + reserveTargetOwnership(targetId: string, sessionId: string): TargetOwnershipReservation { + const target = this.targetsByTargetId.get(targetId) + if (!target) { + throw new TargetOwnershipError({ reason: "not-found", message: `Target detached before adoption: ${targetId}` }) + } + const owner = target.opencodeBrowserSessionId + if (owner && owner !== sessionId) { + throw targetOwnedError(owner) + } + this.addRootTarget({ ...target, opencodeBrowserSessionId: sessionId }) + const reservation = { + targetId, + targetSessionId: target.sessionId, + tabId: target.tabId, + sessionId, + ...(owner ? { previousOpenCodeBrowserSessionId: owner } : {}), + } + this.pendingOwnershipReservations.set(targetId, reservation) + return reservation + } + + rollbackTargetOwnership(reservation: TargetOwnershipReservation): TargetOwnershipChange { + this.pendingOwnershipReservations.delete(reservation.targetId) + const target = this.targetsByTargetId.get(reservation.targetId) + if (!target || target.sessionId !== reservation.targetSessionId || target.opencodeBrowserSessionId !== reservation.sessionId) { + return emptyOwnershipChange + } + const { opencodeBrowserSessionId: _owner, ...unowned } = target + this.addRootTarget(reservation.previousOpenCodeBrowserSessionId + ? { ...unowned, opencodeBrowserSessionId: reservation.previousOpenCodeBrowserSessionId } + : unowned) + return ownershipChange(target.targetInfo.targetId, target.tabId) + } + + commitTargetOwnership(options: { + readonly reservation: TargetOwnershipReservation + readonly previousAdoptedTargetId?: string + }): TargetOwnershipChange { + this.pendingOwnershipReservations.delete(options.reservation.targetId) + const target = this.targetsByTargetId.get(options.reservation.targetId) + if (!target || target.sessionId !== options.reservation.targetSessionId || target.opencodeBrowserSessionId !== options.reservation.sessionId) { + throw new TargetOwnershipError({ + reason: "generation-changed", + message: `Target detached or changed during adoption: ${options.reservation.targetId}`, + }) + } + const targetIds = [target.targetInfo.targetId] + const tabIds = [target.tabId] + if (options.previousAdoptedTargetId && options.previousAdoptedTargetId !== target.targetInfo.targetId) { + const released = this.releaseTargetOwnership(options.previousAdoptedTargetId, options.reservation.sessionId) + targetIds.push(...released.targetIds) + tabIds.push(...released.tabIds) + } + return { targetIds: Array.from(new Set(targetIds)), tabIds: Array.from(new Set(tabIds)) } + } + + releaseTargetOwnership(targetId: string, sessionId: string): TargetOwnershipChange { + const target = this.targetsByTargetId.get(targetId) + if (!target || target.opencodeBrowserSessionId !== sessionId) { + return emptyOwnershipChange + } + const { opencodeBrowserSessionId: _owner, ...released } = target + this.addRootTarget(released) + return ownershipChange(target.targetInfo.targetId, target.tabId) + } + + detachRootTargetState(tabId: number, options: { + readonly preserveChildParentSessionId?: string + readonly preserveFrameEvents?: boolean + } = {}): { readonly target: ConnectedTarget; readonly childSessionIds: string[] } | undefined { + this.stagedRootTargets.delete(tabId) + const target = this.tabTargets.get(tabId) + // Resolve the entire staged subtree before recursive detach mutates the indexes. + const preservedSessionIds = new Set() + if (options.preserveChildParentSessionId !== undefined) { + preservedSessionIds.add(options.preserveChildParentSessionId) + for (const parentSessionId of preservedSessionIds) { + for (const child of this.childTargets.values()) { + if (child.tabId === tabId && child.parentSessionId === parentSessionId) { + preservedSessionIds.add(child.sessionId) + } + } + } + } + const childSessionIds = Array.from(this.childTargets.values()) + .filter((child) => child.tabId === tabId && !preservedSessionIds.has(child.sessionId)) + .map((child) => child.sessionId) + if (target) { + this.targets.delete(target.sessionId) + this.tabTargets.delete(tabId) + this.targetsByTargetId.delete(target.targetInfo.targetId) + this.pendingOwnershipReservations.delete(target.targetInfo.targetId) + } + if (!options.preserveFrameEvents) this.tabFrameEvents.delete(tabId) + for (const sessionId of childSessionIds) this.detachChildTargetState(sessionId) + return target ? { target, childSessionIds } : undefined + } + + detachChildTargetState(sessionId: string): ChildTarget | undefined { + const target = this.childTargets.get(sessionId) + this.childTargets.delete(sessionId) + if (target) { + this.childTargetsByTargetId.delete(target.targetInfo.targetId) + } + for (const child of this.childTargets.values()) { + if (child.parentSessionId === sessionId) this.detachChildTargetState(child.sessionId) + } + return target + } + + updateTargetUrl(tabId: number, url: string): void { + const staged = this.stagedRootTargets.get(tabId) + if (staged) { + this.stagedRootTargets.set(tabId, { ...staged, targetInfo: { ...staged.targetInfo, title: url, url }, crashed: false }) + return + } + const target = this.tabTargets.get(tabId) + if (!target) { + return + } + this.addRootTarget({ ...target, targetInfo: { ...target.targetInfo, title: url, url }, crashed: false }) + } + + /** Record or lift a protected-frame debugger block. Returns the target only when its state changed. */ + markRootTargetProtectedUi(tabId: number, protectedUi: boolean): ConnectedTarget | undefined { + const target = this.tabTargets.get(tabId) + if (!target || (target.protectedUi === true) === protectedUi) { + return undefined + } + const updated: ConnectedTarget = { ...target, protectedUi } + this.addRootTarget(updated) + return updated + } + + markRootTargetCrashed(tabId: number): ConnectedTarget | undefined { + const staged = this.stagedRootTargets.get(tabId) + if (staged) { + const crashed = { ...staged, crashed: true } + this.stagedRootTargets.set(tabId, crashed) + return crashed + } + const target = this.tabTargets.get(tabId) + if (!target) { + return undefined + } + const crashed: ConnectedTarget = { ...target, crashed: true } + this.addRootTarget(crashed) + return crashed + } + + updateConnectedTargetInfo(options: { readonly tabId: number; readonly targetInfo: TargetInfo }): ConnectedTargetInfoUpdate | undefined { + if (this.childTargetsByTargetId.has(options.targetInfo.targetId)) { + this.updateChildTargetInfo(options.targetInfo) + const target = this.childTargetsByTargetId.get(options.targetInfo.targetId) + return target ? { kind: "child", target } : undefined + } + const root = this.stagedRootTargets.get(options.tabId) ?? this.tabTargets.get(options.tabId) + if (root?.targetInfo.targetId !== options.targetInfo.targetId) { + return undefined + } + this.updateRootTargetInfo(options.tabId, options.targetInfo) + const target = this.tabTargets.get(options.tabId) + return target ? { kind: "root", target } : undefined + } + + updateRootTargetInfo(tabId: number, targetInfo: TargetInfo): void { + const staged = this.stagedRootTargets.get(tabId) + if (staged?.targetInfo.targetId === targetInfo.targetId) { + this.stagedRootTargets.set(tabId, { ...staged, targetInfo }) + return + } + const target = this.tabTargets.get(tabId) + if (!target) { + return + } + const updated: ConnectedTarget = { ...target, targetInfo } + this.targets.set(updated.sessionId, updated) + this.tabTargets.set(tabId, updated) + this.targetsByTargetId.delete(target.targetInfo.targetId) + this.targetsByTargetId.set(targetInfo.targetId, updated) + } + + updateChildTargetInfo(targetInfo: TargetInfo): void { + const target = this.childTargetsByTargetId.get(targetInfo.targetId) + if (!target) { + return + } + const updated: ChildTarget = { ...target, targetInfo } + this.childTargets.set(updated.sessionId, updated) + this.childTargetsByTargetId.delete(target.targetInfo.targetId) + this.childTargetsByTargetId.set(targetInfo.targetId, updated) + } + + rememberFrameEvent(options: { + readonly tabId: number + readonly frameId: string + readonly attached?: JsonObject + readonly navigated?: JsonObject + }): void { + const frameEvents = this.tabFrameEvents.get(options.tabId) ?? new Map() + const existing = frameEvents.get(options.frameId) + const attached = options.attached ?? existing?.attached + const navigated = options.navigated ?? existing?.navigated + const next: StoredFrameEvents = { + frameId: options.frameId, + ...(attached ? { attached } : {}), + ...(navigated ? { navigated } : {}), + } + frameEvents.set(options.frameId, next) + this.tabFrameEvents.set(options.tabId, frameEvents) + } + + allTargetInfos(options: { + readonly isRestrictedTarget: (targetInfo: TargetInfo) => boolean + readonly isVisibleTarget?: (target: ConnectedTarget | ChildTarget) => boolean + }): TargetInfo[] { + return [...this.targets.values(), ...this.childTargets.values()].flatMap((target) => { + if (!(options.isVisibleTarget?.(target) ?? true)) return [] + if (options.isRestrictedTarget(target.targetInfo)) return [] + return [{ ...target.targetInfo, attached: true }] + }) + } + + findFrameEventsForChild(target: ChildTarget): StoredFrameEvents | undefined { + const frameEvents = this.tabFrameEvents.get(target.tabId) + if (!frameEvents) { + return undefined + } + const exactMatch = frameEvents.get(target.targetInfo.targetId) + if (exactMatch) { + return exactMatch + } + return Array.from(frameEvents.values()).find((candidate) => { + const frame = isJsonObject(candidate.navigated?.frame) ? candidate.navigated.frame : undefined + if (!frame) { + return false + } + const parentMatches = !target.targetInfo.parentFrameId || frame.parentId === target.targetInfo.parentFrameId + const urlMatches = !target.targetInfo.url || frame.url === target.targetInfo.url + return parentMatches && urlMatches + }) + } +} + +const emptyOwnershipChange: TargetOwnershipChange = { targetIds: [], tabIds: [] } + +function ownershipChange(targetId: string, tabId: number): TargetOwnershipChange { + return { targetIds: [targetId], tabIds: tabId < 0 ? [] : [tabId] } +} + +function targetOwnedError(owner: string): Error { + return new TargetOwnershipError({ + reason: "owned", + ownerSessionId: owner, + message: `Target is already adopted by session ${owner}. Use that session, or reset/delete it to release the tab before adopting it elsewhere.`, + }) +} diff --git a/packages/browser-extension/cli/src/version.ts b/packages/browser-extension/cli/src/version.ts new file mode 100644 index 00000000000..bc2b2ba0c46 --- /dev/null +++ b/packages/browser-extension/cli/src/version.ts @@ -0,0 +1,37 @@ +import crypto from "node:crypto" +import fs from "node:fs" +import path from "node:path" +import { fileURLToPath } from "node:url" + +declare global { + // Injected by scripts/build-cli.ts at build time. + var __OPENCODE_BROWSER_VERSION__: string | undefined + var __OPENCODE_BROWSER_BUILD_ID__: string | undefined +} + +export const opencodeBrowserVersion: string = globalThis.__OPENCODE_BROWSER_VERSION__ ?? "0.0.0-dev" +export const opencodeBrowserBuildId: string = globalThis.__OPENCODE_BROWSER_BUILD_ID__ ?? sourceBuildId() + +export function sourceBuildIdForFiles(files: readonly { readonly name: string; readonly content: string | Buffer }[]): string { + const hash = crypto.createHash("sha256") + for (const file of [...files].sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0)) { + hash.update(file.name) + hash.update("\0") + hash.update(file.content) + hash.update("\0") + } + return `source-${hash.digest("hex").slice(0, 16)}` +} + +function sourceBuildId(): string { + const srcDir = path.dirname(fileURLToPath(import.meta.url)) + const rootDir = path.join(srcDir, "..") + const files = fs.readdirSync(srcDir, { withFileTypes: true }) + .filter((entry) => entry.isFile() && entry.name.endsWith(".ts")) + .map((entry) => ({ name: `src/${entry.name}`, content: fs.readFileSync(path.join(srcDir, entry.name)) })) + for (const name of ["package.json", "bun.lock"]) { + const file = path.join(rootDir, name) + if (fs.existsSync(file)) files.push({ name, content: fs.readFileSync(file) }) + } + return sourceBuildIdForFiles(files) +} diff --git a/packages/browser-extension/cli/src/webmcp.ts b/packages/browser-extension/cli/src/webmcp.ts new file mode 100644 index 00000000000..0a1ea0e2ef2 --- /dev/null +++ b/packages/browser-extension/cli/src/webmcp.ts @@ -0,0 +1,210 @@ +import type { Frame, Page } from "patchright-core" + +const defaultFrameTimeoutMs = 5_000 +const maxTools = 100 +const maxDescriptionLength = 1_000 +const maxSchemaLength = 32_000 + +type WebMcpTool = { + readonly name: string + readonly title?: string + readonly description: string + readonly inputSchema?: unknown + readonly annotations?: { + readonly readOnly?: boolean + readonly untrustedContent?: boolean + readonly consequential?: boolean + } + readonly origin?: string + readonly frame: string + readonly frameUrl: string +} + +type WebMcpListing = { + readonly available: boolean + readonly tools: readonly WebMcpTool[] + readonly omitted: number +} + +export type WebMcpHelper = { + readonly list: () => Promise + readonly call: (name: string, input?: Record, options?: { + readonly frame?: string + readonly timeout?: number + }) => Promise +} + +type CollectedTool = Omit + +export function createWebMcpHelper(page: Page): WebMcpHelper { + return { + list: async () => { + const listing = await collectWebMcpToolsWithFrames(page, defaultFrameTimeoutMs) + return { + available: listing.available, + tools: listing.tools.map(({ tool }) => tool), + omitted: listing.omitted, + } + }, + call: async (name, input = {}, options = {}) => { + if (!name.trim()) throw new Error("webmcp.call requires a non-empty tool name") + const listing = await collectWebMcpToolsWithFrames(page, options.timeout ?? defaultFrameTimeoutMs) + const matches = listing.tools.filter((candidate) => { + return candidate.tool.name === name && + (options.frame === undefined || candidate.tool.frame === options.frame || candidate.tool.frameUrl === options.frame) + }) + if (matches.length === 0) { + const available = listing.tools.map(({ tool }) => tool.name) + throw new Error(`No WebMCP tool named ${JSON.stringify(name)}${options.frame ? ` in frame ${options.frame}` : ""}.${available.length > 0 ? ` Available tools: ${[...new Set(available)].join(", ")}.` : " The page does not register any WebMCP tools."}`) + } + if (matches.length > 1) { + throw new Error(`WebMCP tool ${JSON.stringify(name)} is registered in multiple frames; pass { frame }. Matching frames: ${matches.map(({ tool }) => tool.frame).join(", ")}`) + } + const match = matches[0]! + return await withTimeout( + match.frame.evaluate(callWebMcpToolInPage, { name, inputJson: JSON.stringify(input) }), + options.timeout ?? defaultFrameTimeoutMs, + `WebMCP tool ${JSON.stringify(name)} timed out`, + ) + }, + } +} + +async function collectWebMcpToolsWithFrames(page: Page, timeoutMs: number): Promise<{ + readonly available: boolean + readonly tools: readonly { readonly frame: Frame; readonly tool: WebMcpTool }[] + readonly omitted: number +}> { + const frames = page.frames() + const urlCounts = new Map() + for (const frame of frames) urlCounts.set(frame.url(), (urlCounts.get(frame.url()) ?? 0) + 1) + const results = await Promise.all(frames.map(async (frame, index) => { + const frameUrl = frame.url() + const frameLabel = (urlCounts.get(frameUrl) ?? 0) > 1 ? `${frameUrl} (frame ${index})` : frameUrl + const result = await withTimeout(frame.evaluate(collectWebMcpToolsInPage), timeoutMs, "WebMCP discovery timed out") + .catch(() => null) + return { frame, frameUrl, frameLabel, result } + })) + const available = results.some(({ result }) => result !== null) + let discovered = 0 + const collected: Array<{ readonly frame: Frame; readonly tool: WebMcpTool }> = [] + for (const { frame, frameUrl, frameLabel, result } of results) { + if (!result) continue + for (const raw of result) { + discovered += 1 + if (collected.length >= maxTools) continue + const tool = normalizeCollectedTool(raw, frameLabel, frameUrl) + if (tool) collected.push({ frame, tool }) + } + } + return { available, tools: collected, omitted: Math.max(0, discovered - maxTools) } +} + +function collectWebMcpToolsInPage(): Promise | null { + type PageTool = { + readonly name?: unknown + readonly title?: unknown + readonly description?: unknown + readonly inputSchema?: unknown + readonly annotations?: Record + readonly origin?: unknown + readonly window?: Window + } + type ModelContext = { readonly getTools?: () => Promise } + const context = (document as Document & { modelContext?: ModelContext }).modelContext ?? + (navigator as Navigator & { modelContext?: ModelContext }).modelContext + if (!context?.getTools) return null + return Promise.resolve(context.getTools()).then((tools) => tools + .filter((tool) => !("window" in tool) || tool.window === window) + .map((tool) => { + let inputSchema = tool.inputSchema + if (typeof inputSchema === "string") { + try { + inputSchema = JSON.parse(inputSchema) + } catch { + inputSchema = undefined + } + } + return { + name: typeof tool.name === "string" ? tool.name : "", + ...(typeof tool.title === "string" ? { title: tool.title } : {}), + description: typeof tool.description === "string" ? tool.description : "", + ...(inputSchema === undefined ? {} : { inputSchema }), + ...(tool.annotations ? { + annotations: { + readOnly: Boolean(tool.annotations.readOnlyHint ?? tool.annotations.readOnly), + untrustedContent: Boolean(tool.annotations.untrustedContentHint ?? tool.annotations.untrustedContent), + consequential: Boolean(tool.annotations.consequentialHint ?? tool.annotations.consequential), + }, + } : {}), + ...(typeof tool.origin === "string" ? { origin: tool.origin } : {}), + } + })) +} + +function callWebMcpToolInPage(options: { readonly name: string; readonly inputJson: string }): Promise { + type PageTool = { readonly name?: unknown; readonly window?: Window } + type ModelContext = { + readonly getTools?: () => Promise + readonly executeTool?: (tool: PageTool, input: string) => Promise + readonly invokeTool?: (name: string, input: unknown) => Promise + } + const context = (document as Document & { modelContext?: ModelContext }).modelContext ?? + (navigator as Navigator & { modelContext?: ModelContext }).modelContext + if (!context?.getTools) throw new Error("WebMCP is not available on this page") + return Promise.resolve(context.getTools()).then(async (tools) => { + const tool = tools.filter((candidate) => !("window" in candidate) || candidate.window === window) + .find((candidate) => candidate.name === options.name) + if (!tool) throw new Error(`WebMCP tool ${JSON.stringify(options.name)} is not registered in this frame`) + const result = context.executeTool + ? await context.executeTool(tool, options.inputJson) + : context.invokeTool + ? await context.invokeTool(options.name, JSON.parse(options.inputJson)) + : (() => { throw new Error("WebMCP tool execution is not available on this page") })() + if (typeof result !== "string") return result ?? null + try { + return JSON.parse(result) + } catch { + return result + } + }) +} + +function normalizeCollectedTool(raw: CollectedTool, frame: string, frameUrl: string): WebMcpTool | undefined { + const name = typeof raw.name === "string" ? raw.name.trim() : "" + if (!name) return undefined + let inputSchema = raw.inputSchema + if (inputSchema !== undefined) { + try { + const serialized = JSON.stringify(inputSchema) + inputSchema = serialized.length <= maxSchemaLength ? JSON.parse(serialized) : undefined + } catch { + inputSchema = undefined + } + } + const annotations = raw.annotations && Object.values(raw.annotations).some(Boolean) ? raw.annotations : undefined + return { + name, + ...(raw.title ? { title: raw.title.slice(0, 200) } : {}), + description: raw.description.slice(0, maxDescriptionLength), + ...(inputSchema === undefined ? {} : { inputSchema }), + ...(annotations ? { annotations } : {}), + ...(raw.origin ? { origin: raw.origin } : {}), + frame, + frameUrl, + } +} + +async function withTimeout(promise: Promise, timeoutMs: number, message: string): Promise { + let timer: ReturnType | undefined + try { + return await Promise.race([ + promise, + new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error(`${message} after ${timeoutMs}ms`)), timeoutMs) + }), + ]) + } finally { + if (timer) clearTimeout(timer) + } +} diff --git a/packages/browser-extension/cli/tsconfig.json b/packages/browser-extension/cli/tsconfig.json new file mode 100644 index 00000000000..0c0377e5531 --- /dev/null +++ b/packages/browser-extension/cli/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "strict": true, + "exactOptionalPropertyTypes": true, + "noUncheckedIndexedAccess": true, + "moduleDetection": "force", + "allowImportingTsExtensions": true, + "noEmit": true, + "skipLibCheck": true, + "types": [ + "node", + "chrome" + ] + }, + "include": [ + "src/**/*.ts", + "build.ts" + ] +} \ No newline at end of file