@hmharness/browser 0.0.0-stage → 0.23.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cdp.d.ts ADDED
@@ -0,0 +1,60 @@
1
+ /**
2
+ * @hmharness/browser - persistent CDP client for a driven browser
3
+ *
4
+ * BrowserOS is a Chromium fork, so plain Chrome DevTools Protocol over
5
+ * the built-in Node >= 22 WebSocket drives it — zero dependencies (same
6
+ * stance as environments/cdp-act, but persistent + multi-tab: one
7
+ * browser-level WebSocket, one FLAT session per attached page target).
8
+ *
9
+ * Meant for OWNED instances launched by lifecycle.ts with
10
+ * --remote-debugging-port + a dedicated profile. The discovery endpoints
11
+ * (/json/version, /json/list) are only relied on for such instances:
12
+ * Chromium 144+ blocks them on the DEFAULT user-data-dir.
13
+ */
14
+ export interface CdpTabInfo {
15
+ targetId: string;
16
+ url: string;
17
+ title: string;
18
+ }
19
+ export interface CdpBrowserOptions {
20
+ port: number;
21
+ /** per-command timeout (default 10s) */
22
+ timeoutMs?: number;
23
+ }
24
+ export declare class CdpBrowser {
25
+ private opts;
26
+ private ws;
27
+ private wsReady;
28
+ private nextId;
29
+ private pending;
30
+ private sessions;
31
+ constructor(opts: CdpBrowserOptions);
32
+ get port(): number;
33
+ private get base();
34
+ private get timeout();
35
+ /** is a debuggable browser reachable at the port? */
36
+ up(): Promise<boolean>;
37
+ /** lazily open (and keep) the browser-level WebSocket */
38
+ private connect;
39
+ private dropSocket;
40
+ /** send one command; auto-reconnects once if the socket died */
41
+ private send;
42
+ private sendOnce;
43
+ /** browser version string (e.g. "BrowserOS 155.x …") */
44
+ version(): Promise<string>;
45
+ /** open page targets (via /json/list — reliable on owned instances) */
46
+ tabs(): Promise<CdpTabInfo[]>;
47
+ openTab(url: string): Promise<string>;
48
+ closeTab(targetId: string): Promise<void>;
49
+ activateTab(targetId: string): Promise<void>;
50
+ /** attach (once) to a page target and enable the domains we use */
51
+ private session;
52
+ /** evaluate an expression in a page (returnByValue; optional awaitPromise) */
53
+ evaluate(targetId: string, expression: string, awaitPromise?: boolean): Promise<unknown>;
54
+ /** navigate + wait for the load to settle (polled readyState — never
55
+ * fails the navigation itself, worst case reports interactive) */
56
+ navigate(targetId: string, url: string, timeoutMs?: number): Promise<void>;
57
+ /** full-page PNG screenshot as a Buffer */
58
+ screenshot(targetId: string): Promise<Buffer>;
59
+ close(): Promise<void>;
60
+ }
package/dist/cdp.js ADDED
@@ -0,0 +1,189 @@
1
+ export class CdpBrowser {
2
+ opts;
3
+ ws = null;
4
+ wsReady = null;
5
+ nextId = 1;
6
+ pending = new Map();
7
+ sessions = new Map();
8
+ constructor(opts) {
9
+ this.opts = opts;
10
+ }
11
+ get port() {
12
+ return this.opts.port;
13
+ }
14
+ get base() {
15
+ return `http://127.0.0.1:${this.opts.port}`;
16
+ }
17
+ get timeout() {
18
+ return this.opts.timeoutMs ?? 10_000;
19
+ }
20
+ /** is a debuggable browser reachable at the port? */
21
+ async up() {
22
+ try {
23
+ await fetch(this.base + '/json/version', { signal: AbortSignal.timeout(1_500) });
24
+ return true;
25
+ }
26
+ catch {
27
+ return false;
28
+ }
29
+ }
30
+ /** lazily open (and keep) the browser-level WebSocket */
31
+ connect() {
32
+ if (this.ws && this.ws.readyState === WebSocket.OPEN)
33
+ return Promise.resolve(this.ws);
34
+ if (this.wsReady)
35
+ return this.wsReady;
36
+ this.wsReady = (async () => {
37
+ const res = await fetch(this.base + '/json/version', { signal: AbortSignal.timeout(2_000) }).catch(() => null);
38
+ const wsUrl = res && res.ok ? (await res.json()).webSocketDebuggerUrl : undefined;
39
+ if (!wsUrl) {
40
+ this.wsReady = null;
41
+ throw new Error(`no debuggable browser at ${this.base} (start it: hmh browser start)`);
42
+ }
43
+ const ws = new WebSocket(wsUrl);
44
+ await new Promise((resolve, reject) => {
45
+ const t = setTimeout(() => reject(new Error('CDP WebSocket connect timeout')), 3_000);
46
+ ws.addEventListener('open', () => { clearTimeout(t); resolve(); }, { once: true });
47
+ ws.addEventListener('error', () => { clearTimeout(t); reject(new Error('CDP WebSocket error')); }, { once: true });
48
+ });
49
+ ws.addEventListener('message', (ev) => {
50
+ const raw = typeof ev.data === 'string' ? ev.data : Buffer.from(ev.data).toString('utf8');
51
+ let msg;
52
+ try {
53
+ msg = JSON.parse(raw);
54
+ }
55
+ catch {
56
+ return;
57
+ }
58
+ if (msg.id === undefined)
59
+ return; // events (Target, Runtime, …) — not used yet
60
+ const p = this.pending.get(msg.id);
61
+ if (!p)
62
+ return;
63
+ this.pending.delete(msg.id);
64
+ clearTimeout(p.timer);
65
+ if (msg.error)
66
+ p.reject(new Error(msg.error.message ?? 'CDP error'));
67
+ else
68
+ p.resolve(msg.result);
69
+ });
70
+ ws.addEventListener('close', () => this.dropSocket());
71
+ ws.addEventListener('error', () => this.dropSocket());
72
+ this.ws = ws;
73
+ return ws;
74
+ })().catch((err) => {
75
+ this.wsReady = null;
76
+ throw err;
77
+ });
78
+ return this.wsReady;
79
+ }
80
+ dropSocket() {
81
+ this.ws = null;
82
+ this.wsReady = null;
83
+ this.sessions.clear();
84
+ for (const [, p] of this.pending) {
85
+ clearTimeout(p.timer);
86
+ p.reject(new Error('CDP connection closed'));
87
+ }
88
+ this.pending.clear();
89
+ }
90
+ /** send one command; auto-reconnects once if the socket died */
91
+ async send(method, params = {}, sessionId) {
92
+ try {
93
+ return await this.sendOnce(method, params, sessionId);
94
+ }
95
+ catch (err) {
96
+ if (!this.ws && sessionId === undefined)
97
+ return await this.sendOnce(method, params, sessionId);
98
+ throw err;
99
+ }
100
+ }
101
+ async sendOnce(method, params, sessionId) {
102
+ const ws = await this.connect();
103
+ return new Promise((resolve, reject) => {
104
+ const id = this.nextId++;
105
+ const timer = setTimeout(() => {
106
+ this.pending.delete(id);
107
+ reject(new Error(`CDP ${method} timeout`));
108
+ }, this.timeout);
109
+ this.pending.set(id, { resolve, reject, timer });
110
+ ws.send(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) }));
111
+ });
112
+ }
113
+ /** browser version string (e.g. "BrowserOS 155.x …") */
114
+ async version() {
115
+ try {
116
+ const res = await fetch(this.base + '/json/version', { signal: AbortSignal.timeout(2_000) });
117
+ const j = (await res.json());
118
+ return j.Browser ?? 'unknown';
119
+ }
120
+ catch {
121
+ return 'unreachable';
122
+ }
123
+ }
124
+ /** open page targets (via /json/list — reliable on owned instances) */
125
+ async tabs() {
126
+ try {
127
+ const res = await fetch(this.base + '/json/list', { signal: AbortSignal.timeout(2_000) });
128
+ const list = (await res.json());
129
+ return list.filter((t) => t.type === 'page').map((t) => ({ targetId: t.id, url: t.url, title: t.title }));
130
+ }
131
+ catch {
132
+ return [];
133
+ }
134
+ }
135
+ async openTab(url) {
136
+ const r = (await this.send('Target.createTarget', { url }));
137
+ return r.targetId;
138
+ }
139
+ async closeTab(targetId) {
140
+ await this.send('Target.closeTarget', { targetId }).catch(() => undefined);
141
+ this.sessions.delete(targetId);
142
+ }
143
+ async activateTab(targetId) {
144
+ await this.send('Target.activateTarget', { targetId }).catch(() => undefined);
145
+ }
146
+ /** attach (once) to a page target and enable the domains we use */
147
+ async session(targetId) {
148
+ const cached = this.sessions.get(targetId);
149
+ if (cached)
150
+ return cached;
151
+ const r = (await this.send('Target.attachToTarget', { targetId, flatten: true }));
152
+ await this.send('Runtime.enable', {}, r.sessionId).catch(() => undefined);
153
+ await this.send('Page.enable', {}, r.sessionId).catch(() => undefined);
154
+ this.sessions.set(targetId, r.sessionId);
155
+ return r.sessionId;
156
+ }
157
+ /** evaluate an expression in a page (returnByValue; optional awaitPromise) */
158
+ async evaluate(targetId, expression, awaitPromise = false) {
159
+ const sessionId = await this.session(targetId);
160
+ const r = (await this.send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise }, sessionId));
161
+ if (r.exceptionDetails) {
162
+ throw new Error('page exception: ' + (r.exceptionDetails.exception?.description ?? r.exceptionDetails.text ?? 'unknown').slice(0, 200));
163
+ }
164
+ return r.result?.value;
165
+ }
166
+ /** navigate + wait for the load to settle (polled readyState — never
167
+ * fails the navigation itself, worst case reports interactive) */
168
+ async navigate(targetId, url, timeoutMs = 20_000) {
169
+ await this.send('Page.navigate', { url }, await this.session(targetId));
170
+ const deadline = Date.now() + timeoutMs;
171
+ while (Date.now() < deadline) {
172
+ const state = await this.evaluate(targetId, 'document.readyState').catch(() => null);
173
+ if (state === 'complete' || state === 'interactive')
174
+ return;
175
+ await new Promise((r) => setTimeout(r, 250));
176
+ }
177
+ }
178
+ /** full-page PNG screenshot as a Buffer */
179
+ async screenshot(targetId) {
180
+ const sessionId = await this.session(targetId);
181
+ const r = (await this.send('Page.captureScreenshot', { format: 'png' }, sessionId));
182
+ if (!r.data)
183
+ throw new Error('screenshot returned no data');
184
+ return Buffer.from(r.data, 'base64');
185
+ }
186
+ async close() {
187
+ this.dropSocket();
188
+ }
189
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * @hmharness/browser - BrowserOS driver for the agent
3
+ *
4
+ * Client ONLY: we discover, trust-pin, launch and DRIVE the BrowserOS AI
5
+ * browser (Chromium fork) over the Chrome DevTools Protocol — we never
6
+ * touch the user's daily browser (dedicated profile under HMH_HOME,
7
+ * loopback CDP only). Supply-chain guard in trust.ts (same contract as
8
+ * @hmharness/lsp); agent surface in tools.ts (browser_* family).
9
+ */
10
+ export { discoverBrowsers, detectRunning, browserosRoots, browserosUserDataDir, BROWSEROS_INSTALL_URL, BROWSEROS_REPO_URL, type DiscoveredBrowser, type RunningDetection } from './registry.js';
11
+ export { checkBrowserTrust, trustBrowser, untrustBrowser, listBrowserTrust, browserHash, browserTrustPath, type BrowserTrustEntry, type BrowserTrustStore, type BrowserTrustVerdict } from './trust.js';
12
+ export { CdpBrowser, type CdpTabInfo, type CdpBrowserOptions } from './cdp.js';
13
+ export { startBrowser, stopBrowser, ownedInstance, clientForInstance, killTree, DEFAULT_CDP_PORT, type OwnedInstance, type StartBrowserOptions } from './lifecycle.js';
14
+ export { SNAPSHOT_EXPR, READ_EXPR, clickExpr, typeExpr, scrollExpr, parseSnapshot, parseRead, formatSnapshot, type Snapshot, type SnapshotElement, type ReadResult } from './page.js';
15
+ export { browserTools, shutdownBrowser, type BrowserToolContext } from './tools.js';
package/dist/index.js ADDED
@@ -0,0 +1,15 @@
1
+ /**
2
+ * @hmharness/browser - BrowserOS driver for the agent
3
+ *
4
+ * Client ONLY: we discover, trust-pin, launch and DRIVE the BrowserOS AI
5
+ * browser (Chromium fork) over the Chrome DevTools Protocol — we never
6
+ * touch the user's daily browser (dedicated profile under HMH_HOME,
7
+ * loopback CDP only). Supply-chain guard in trust.ts (same contract as
8
+ * @hmharness/lsp); agent surface in tools.ts (browser_* family).
9
+ */
10
+ export { discoverBrowsers, detectRunning, browserosRoots, browserosUserDataDir, BROWSEROS_INSTALL_URL, BROWSEROS_REPO_URL } from "./registry.js";
11
+ export { checkBrowserTrust, trustBrowser, untrustBrowser, listBrowserTrust, browserHash, browserTrustPath } from "./trust.js";
12
+ export { CdpBrowser } from "./cdp.js";
13
+ export { startBrowser, stopBrowser, ownedInstance, clientForInstance, killTree, DEFAULT_CDP_PORT } from "./lifecycle.js";
14
+ export { SNAPSHOT_EXPR, READ_EXPR, clickExpr, typeExpr, scrollExpr, parseSnapshot, parseRead, formatSnapshot } from "./page.js";
15
+ export { browserTools, shutdownBrowser } from "./tools.js";
@@ -0,0 +1,38 @@
1
+ import { CdpBrowser } from './cdp.js';
2
+ /** hmh-owned instance CDP port. 9222 is the generic Chrome convention and
3
+ * often occupied by a user-launched debug browser; +1 keeps ours distinct. */
4
+ export declare const DEFAULT_CDP_PORT = 9223;
5
+ export interface OwnedInstance {
6
+ pid: number;
7
+ port: number;
8
+ profileDir: string;
9
+ startedAt: string;
10
+ }
11
+ export interface StartBrowserOptions {
12
+ executablePath?: string;
13
+ port?: number;
14
+ headless?: boolean;
15
+ /** true when an agent tool auto-started the instance (vs an explicit
16
+ * `hmh browser start`): only implicit headless instances are killed
17
+ * with the host — an explicit user start persists until `stop`. */
18
+ implicit?: boolean;
19
+ }
20
+ /** kill a process TREE (browsers spawn children; a bare kill orphans them) */
21
+ export declare function killTree(pid: number): void;
22
+ /** Read the owned-instance state (for status/stop). */
23
+ export declare function ownedInstance(home: string): Promise<{
24
+ instance: OwnedInstance;
25
+ alive: boolean;
26
+ reachable: boolean;
27
+ } | null>;
28
+ export declare function startBrowser(home: string, opts?: StartBrowserOptions): Promise<OwnedInstance>;
29
+ /** Stop the owned instance (never touches the user's daily browser). */
30
+ export declare function stopBrowser(home: string): Promise<{
31
+ stopped: boolean;
32
+ detail: string;
33
+ }>;
34
+ /** Create a client bound to the owned instance (convenience for tools). */
35
+ export declare function clientForInstance(home: string, opts?: StartBrowserOptions): Promise<{
36
+ client: CdpBrowser;
37
+ instance: OwnedInstance;
38
+ }>;
@@ -0,0 +1,189 @@
1
+ /**
2
+ * @hmharness/browser - owned-instance lifecycle
3
+ *
4
+ * Launches a DEDICATED BrowserOS with:
5
+ * --remote-debugging-port=<port> (standard Chromium switch — takes
6
+ * precedence over BrowserOS's managed
7
+ * CDP server, so no port fights)
8
+ * --user-data-dir=HMH_HOME/browser/profile (never the daily profile)
9
+ * and waits for the debugging endpoint. The instance SURVIVES the process
10
+ * that started it (a visible window the user can watch and log into;
11
+ * `hmh browser stop` is the off switch) — unlike LSP daemons, which are
12
+ * invisible and therefore killed with the host. Exception: a headless
13
+ * instance auto-started by an agent tool is killed on host exit so it
14
+ * cannot rot as an invisible zombie.
15
+ */
16
+ import { spawn, spawnSync } from 'node:child_process';
17
+ import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
18
+ import { join } from 'node:path';
19
+ import { discoverBrowsers, BROWSEROS_INSTALL_URL } from "./registry.js";
20
+ import { checkBrowserTrust } from "./trust.js";
21
+ import { CdpBrowser } from "./cdp.js";
22
+ /** hmh-owned instance CDP port. 9222 is the generic Chrome convention and
23
+ * often occupied by a user-launched debug browser; +1 keeps ours distinct. */
24
+ export const DEFAULT_CDP_PORT = 9223;
25
+ function statePath(home) {
26
+ return join(home, 'browser', 'instance.json');
27
+ }
28
+ async function readState(home) {
29
+ try {
30
+ return JSON.parse(await readFile(statePath(home), 'utf8'));
31
+ }
32
+ catch {
33
+ return null;
34
+ }
35
+ }
36
+ async function portReachable(port) {
37
+ try {
38
+ await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(1_000) });
39
+ return true;
40
+ }
41
+ catch {
42
+ return false;
43
+ }
44
+ }
45
+ function pidAlive(pid) {
46
+ try {
47
+ process.kill(pid, 0);
48
+ return true;
49
+ }
50
+ catch {
51
+ return false;
52
+ }
53
+ }
54
+ /** kill a process TREE (browsers spawn children; a bare kill orphans them) */
55
+ export function killTree(pid) {
56
+ try {
57
+ if (process.platform === 'win32') {
58
+ spawnSync('taskkill', ['/pid', String(pid), '/T', '/F'], { timeout: 10_000, windowsHide: true });
59
+ }
60
+ else {
61
+ process.kill(pid, 'SIGTERM');
62
+ }
63
+ }
64
+ catch { /* already gone */ }
65
+ }
66
+ /** Read the owned-instance state (for status/stop). */
67
+ export async function ownedInstance(home) {
68
+ const st = await readState(home);
69
+ if (!st)
70
+ return null;
71
+ return { instance: st, alive: pidAlive(st.pid), reachable: await portReachable(st.port) };
72
+ }
73
+ /**
74
+ * Ensure an owned BrowserOS is running. Idempotent: reuses the recorded
75
+ * instance when its port answers; refuses to touch a foreign browser that
76
+ * happens to sit on the port. Throws with actionable guidance otherwise.
77
+ */
78
+ /** Resolve the pid actually LISTENING on a loopback port. On Windows a
79
+ * spawned chrome-family launcher hands off to a detached real browser
80
+ * process and exits — the child pid we hold is NOT the browser, so the
81
+ * port's listener is the only reliable handle for stop/kill. */
82
+ function pidForPort(port) {
83
+ try {
84
+ if (process.platform === 'win32') {
85
+ const r = spawnSync('netstat', ['-ano', '-p', 'tcp'], { encoding: 'utf8', timeout: 5_000, windowsHide: true });
86
+ if (r.status !== 0)
87
+ return null;
88
+ for (const line of (r.stdout || '').split('\n')) {
89
+ const t = line.trim().split(/\s+/);
90
+ if (t.length >= 5 && t[0] === 'TCP' && t[3] === 'LISTENING' && t[1]?.endsWith(`:${port}`)) {
91
+ const pid = Number(t[4]);
92
+ if (Number.isInteger(pid) && pid > 0)
93
+ return pid;
94
+ }
95
+ }
96
+ return null;
97
+ }
98
+ const r = spawnSync('lsof', ['-t', `-iTCP:${port}`, '-sTCP:LISTEN'], { encoding: 'utf8', timeout: 5_000 });
99
+ if (r.status !== 0)
100
+ return null;
101
+ const pid = Number((r.stdout || '').split('\n').filter(Boolean)[0]);
102
+ return Number.isInteger(pid) && pid > 0 ? pid : null;
103
+ }
104
+ catch {
105
+ return null;
106
+ }
107
+ }
108
+ export async function startBrowser(home, opts = {}) {
109
+ const port = opts.port ?? DEFAULT_CDP_PORT;
110
+ const existing = await readState(home);
111
+ if (existing && await portReachable(existing.port) && pidAlive(existing.pid)) {
112
+ return existing; // already ours, still alive
113
+ }
114
+ if (existing && !pidAlive(existing.pid)) {
115
+ await rm(statePath(home), { force: true }); // stale record for a dead browser
116
+ }
117
+ if (await portReachable(port)) {
118
+ throw new Error(`port ${port} answers but is NOT an hmh-started browser (no live instance record) — pass --port=<other> or free the port`);
119
+ }
120
+ // force re-discovery when an explicit executable is configured (the
121
+ // memoized cache may predate the config)
122
+ const found = discoverBrowsers(Boolean(opts.executablePath), { executablePath: opts.executablePath }).filter((b) => b.healthy);
123
+ const browser = found[0];
124
+ if (!browser) {
125
+ throw new Error(`BrowserOS not found on this machine — install it from ${BROWSEROS_INSTALL_URL} (or set browser.executablePath in config.json). Discovered: ${found.length ? 'only unhealthy candidates' : 'nothing'}`);
126
+ }
127
+ const verdict = await checkBrowserTrust(home, browser);
128
+ if (!verdict.trusted) {
129
+ throw new Error(`browseros blocked by source trust: ${verdict.reason}`);
130
+ }
131
+ const profileDir = join(home, 'browser', 'profile');
132
+ await mkdir(profileDir, { recursive: true });
133
+ const args = [
134
+ `--remote-debugging-port=${port}`,
135
+ `--user-data-dir=${profileDir}`,
136
+ '--no-first-run',
137
+ '--no-default-browser-check',
138
+ '--window-size=1440,900',
139
+ ];
140
+ if (opts.headless)
141
+ args.push('--headless=new');
142
+ args.push('about:blank');
143
+ // The spawned process is only a LAUNCHER on Windows (it re-execs the
144
+ // real browser detached and exits), so the port — not the child — is
145
+ // the source of truth for "up", and the listener pid is the only
146
+ // reliable handle for stopping.
147
+ const child = spawn(browser.command, args, { stdio: 'ignore', detached: process.platform === 'win32', windowsHide: false });
148
+ if (child.pid === undefined) {
149
+ throw new Error(`failed to spawn BrowserOS (binary: ${browser.command})`);
150
+ }
151
+ child.unref();
152
+ const deadline = Date.now() + 25_000;
153
+ while (Date.now() < deadline) {
154
+ if (await portReachable(port)) {
155
+ const pid = pidForPort(port) ?? child.pid;
156
+ const instance = { pid, port, profileDir, startedAt: new Date().toISOString() };
157
+ const record = { ...instance, killOnExit: Boolean(opts.implicit && opts.headless) && process.env.HMH_BROWSER_PERSIST !== '1' };
158
+ await mkdir(join(home, 'browser'), { recursive: true });
159
+ await writeFile(statePath(home), JSON.stringify(record, null, 1), 'utf8');
160
+ if (record.killOnExit)
161
+ process.once('exit', () => killTree(pid));
162
+ return instance;
163
+ }
164
+ if (process.platform !== 'win32' && child.exitCode !== null)
165
+ break; // unix: no handoff, a dead child stays dead
166
+ await new Promise((r) => setTimeout(r, 300));
167
+ }
168
+ killTree(pidForPort(port) ?? child.pid);
169
+ throw new Error(`BrowserOS did not open its debugging port ${port} within 25s (binary: ${browser.command})`);
170
+ }
171
+ /** Stop the owned instance (never touches the user's daily browser). */
172
+ export async function stopBrowser(home) {
173
+ const st = await readState(home);
174
+ if (!st) {
175
+ return { stopped: false, detail: `no hmh-owned browser recorded (nothing was started via hmh browser start)` };
176
+ }
177
+ if (!pidAlive(st.pid)) {
178
+ await rm(statePath(home), { force: true });
179
+ return { stopped: false, detail: 'recorded instance is already gone (state cleaned)' };
180
+ }
181
+ killTree(st.pid);
182
+ await rm(statePath(home), { force: true });
183
+ return { stopped: true, detail: `killed pid ${st.pid} (CDP port ${st.port})` };
184
+ }
185
+ /** Create a client bound to the owned instance (convenience for tools). */
186
+ export async function clientForInstance(home, opts = {}) {
187
+ const instance = await startBrowser(home, opts);
188
+ return { client: new CdpBrowser({ port: instance.port }), instance };
189
+ }
package/dist/page.d.ts ADDED
@@ -0,0 +1,48 @@
1
+ /**
2
+ * @hmharness/browser - page expressions (snapshot / read / act)
3
+ *
4
+ * The DOM side of the CDP driving, as pure string builders + parsers so
5
+ * they are unit-testable without a browser. Interaction targets use
6
+ * data-hmh-ref attributes STAMPED INTO the DOM by the snapshot: refs stay
7
+ * stable between snapshot and click/type, survive DOM reads, and are
8
+ * visible to the user in DevTools when debugging a stuck agent.
9
+ */
10
+ export interface SnapshotElement {
11
+ ref: number;
12
+ tag: string;
13
+ role?: string;
14
+ text?: string;
15
+ placeholder?: string;
16
+ value?: string;
17
+ href?: string;
18
+ }
19
+ export interface Snapshot {
20
+ title: string;
21
+ url: string;
22
+ elements: SnapshotElement[];
23
+ }
24
+ /** Stamp [data-hmh-ref] onto visible interactive elements and return the
25
+ * serialized snapshot. Cap 80 elements — a longer list stops paying for
26
+ * its own tokens. Password VALUES are never read back. */
27
+ export declare const SNAPSHOT_EXPR = "(() => {\n for (const el of document.querySelectorAll('[data-hmh-ref]')) el.removeAttribute('data-hmh-ref');\n const sels = 'a[href], button, input, select, textarea, summary, [role], [contenteditable=\"true\"], [onclick], [tabindex]';\n const nodes = Array.from(document.querySelectorAll(sels));\n const out = [];\n let ref = 0;\n for (const el of nodes) {\n if (out.length >= 80) break;\n const r = el.getBoundingClientRect();\n const st = getComputedStyle(el);\n if (r.width < 1 || r.height < 1 || st.visibility === 'hidden' || st.display === 'none') continue;\n if (el.closest('[aria-hidden=\"true\"]')) continue;\n ref += 1;\n el.setAttribute('data-hmh-ref', String(ref));\n const e = { ref: ref, tag: el.tagName.toLowerCase() };\n const role = el.getAttribute('role');\n if (role) e.role = role;\n const t = (el.innerText || el.textContent || '').replace(/\\s+/g, ' ').trim().slice(0, 80);\n if (t) e.text = t;\n const ph = el.getAttribute('placeholder');\n if (ph) e.placeholder = ph.slice(0, 60);\n const kind = el.getAttribute('type');\n if ((el.tagName === 'INPUT' && kind !== 'password' || el.tagName === 'TEXTAREA') && el.value) e.value = String(el.value).slice(0, 60);\n const href = el.getAttribute('href');\n if (href) e.href = href.slice(0, 120);\n out.push(e);\n }\n return JSON.stringify({ title: document.title, url: location.href, elements: out });\n})()";
28
+ /** Page text for reading (innerText keeps visual order; capped for context). */
29
+ export declare const READ_EXPR = "(() => {\n const text = (document.body ? document.body.innerText : '').replace(/\\n{3,}/g, '\\n\\n');\n return JSON.stringify({ title: document.title, url: location.href, text: text.slice(0, 12000), truncated: text.length > 12000 });\n})()";
30
+ export interface ReadResult {
31
+ title: string;
32
+ url: string;
33
+ text: string;
34
+ truncated?: boolean;
35
+ }
36
+ /** Click a snapshot ref (scrolls into view first). */
37
+ export declare function clickExpr(ref: number): string;
38
+ /** Type into a snapshot ref — native value setter + input/change events
39
+ * (React/Vue-compatible), optional submit via form.requestSubmit(). */
40
+ export declare function typeExpr(ref: number, text: string, submit?: boolean): string;
41
+ /** Scroll: down|up|top|bottom (default 600px steps). */
42
+ export declare function scrollExpr(direction: string, amount?: number): string;
43
+ /** Parse + validate a snapshot payload from the page. */
44
+ export declare function parseSnapshot(raw: unknown): Snapshot;
45
+ /** Parse + validate a read payload from the page. */
46
+ export declare function parseRead(raw: unknown): ReadResult;
47
+ /** Human/model-readable snapshot rendering. */
48
+ export declare function formatSnapshot(s: Snapshot): string;
package/dist/page.js ADDED
@@ -0,0 +1,112 @@
1
+ /** Stamp [data-hmh-ref] onto visible interactive elements and return the
2
+ * serialized snapshot. Cap 80 elements — a longer list stops paying for
3
+ * its own tokens. Password VALUES are never read back. */
4
+ export const SNAPSHOT_EXPR = `(() => {
5
+ for (const el of document.querySelectorAll('[data-hmh-ref]')) el.removeAttribute('data-hmh-ref');
6
+ const sels = 'a[href], button, input, select, textarea, summary, [role], [contenteditable="true"], [onclick], [tabindex]';
7
+ const nodes = Array.from(document.querySelectorAll(sels));
8
+ const out = [];
9
+ let ref = 0;
10
+ for (const el of nodes) {
11
+ if (out.length >= 80) break;
12
+ const r = el.getBoundingClientRect();
13
+ const st = getComputedStyle(el);
14
+ if (r.width < 1 || r.height < 1 || st.visibility === 'hidden' || st.display === 'none') continue;
15
+ if (el.closest('[aria-hidden="true"]')) continue;
16
+ ref += 1;
17
+ el.setAttribute('data-hmh-ref', String(ref));
18
+ const e = { ref: ref, tag: el.tagName.toLowerCase() };
19
+ const role = el.getAttribute('role');
20
+ if (role) e.role = role;
21
+ const t = (el.innerText || el.textContent || '').replace(/\\s+/g, ' ').trim().slice(0, 80);
22
+ if (t) e.text = t;
23
+ const ph = el.getAttribute('placeholder');
24
+ if (ph) e.placeholder = ph.slice(0, 60);
25
+ const kind = el.getAttribute('type');
26
+ if ((el.tagName === 'INPUT' && kind !== 'password' || el.tagName === 'TEXTAREA') && el.value) e.value = String(el.value).slice(0, 60);
27
+ const href = el.getAttribute('href');
28
+ if (href) e.href = href.slice(0, 120);
29
+ out.push(e);
30
+ }
31
+ return JSON.stringify({ title: document.title, url: location.href, elements: out });
32
+ })()`;
33
+ /** Page text for reading (innerText keeps visual order; capped for context). */
34
+ export const READ_EXPR = `(() => {
35
+ const text = (document.body ? document.body.innerText : '').replace(/\\n{3,}/g, '\\n\\n');
36
+ return JSON.stringify({ title: document.title, url: location.href, text: text.slice(0, 12000), truncated: text.length > 12000 });
37
+ })()`;
38
+ /** the querySelector string for a snapshot ref (ref is a validated
39
+ * integer, so single-quote wrapping needs no escaping) */
40
+ function refQuery(ref) {
41
+ return `'[data-hmh-ref="${ref}"]'`;
42
+ }
43
+ /** Click a snapshot ref (scrolls into view first). */
44
+ export function clickExpr(ref) {
45
+ return `(() => { const el = document.querySelector(${refQuery(ref)}); if (!el) return 'E_NO_REF'; el.scrollIntoView({ block: 'center' }); el.click(); return 'ok'; })()`;
46
+ }
47
+ /** Type into a snapshot ref — native value setter + input/change events
48
+ * (React/Vue-compatible), optional submit via form.requestSubmit(). */
49
+ export function typeExpr(ref, text, submit = false) {
50
+ return `(() => { const el = document.querySelector(${refQuery(ref)}); if (!el) return 'E_NO_REF'; el.focus(); el.scrollIntoView({ block: 'center' });
51
+ const value = ${JSON.stringify(text)};
52
+ if (el.isContentEditable) { el.textContent = value; }
53
+ else {
54
+ const proto = el.tagName === 'TEXTAREA' ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
55
+ const setter = Object.getOwnPropertyDescriptor(proto, 'value') && Object.getOwnPropertyDescriptor(proto, 'value').set;
56
+ if (setter) setter.call(el, value); else el.setAttribute('value', value);
57
+ }
58
+ el.dispatchEvent(new Event('input', { bubbles: true }));
59
+ el.dispatchEvent(new Event('change', { bubbles: true }));
60
+ if (${submit ? 'true' : 'false'}) {
61
+ const form = el.closest('form');
62
+ if (form) form.requestSubmit(); else el.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }));
63
+ }
64
+ return 'ok'; })()`;
65
+ }
66
+ /** Scroll: down|up|top|bottom (default 600px steps). */
67
+ export function scrollExpr(direction, amount = 600) {
68
+ const d = ['down', 'up', 'top', 'bottom'].includes(direction) ? direction : 'down';
69
+ if (d === 'top')
70
+ return `(() => { window.scrollTo(0, 0); return 'ok:' + Math.round(window.scrollY); })()`;
71
+ if (d === 'bottom')
72
+ return `(() => { window.scrollTo(0, document.body.scrollHeight); return 'ok:' + Math.round(window.scrollY); })()`;
73
+ const delta = d === 'up' ? -amount : amount;
74
+ return `(() => { window.scrollBy(0, ${delta}); return 'ok:' + Math.round(window.scrollY); })()`;
75
+ }
76
+ /** Parse + validate a snapshot payload from the page. */
77
+ export function parseSnapshot(raw) {
78
+ if (typeof raw !== 'string')
79
+ throw new Error('snapshot returned no JSON');
80
+ const j = JSON.parse(raw);
81
+ if (!j || !Array.isArray(j.elements))
82
+ throw new Error('snapshot payload malformed');
83
+ return j;
84
+ }
85
+ /** Parse + validate a read payload from the page. */
86
+ export function parseRead(raw) {
87
+ if (typeof raw !== 'string')
88
+ throw new Error('read returned no JSON');
89
+ const j = JSON.parse(raw);
90
+ if (!j || typeof j.text !== 'string')
91
+ throw new Error('read payload malformed');
92
+ return j;
93
+ }
94
+ /** Human/model-readable snapshot rendering. */
95
+ export function formatSnapshot(s) {
96
+ const lines = s.elements.map((e) => {
97
+ const bits = [`[${e.ref}]`, e.tag];
98
+ if (e.role)
99
+ bits.push(`role=${e.role}`);
100
+ if (e.text)
101
+ bits.push(JSON.stringify(e.text));
102
+ if (e.placeholder)
103
+ bits.push(`placeholder=${JSON.stringify(e.placeholder)}`);
104
+ if (e.value)
105
+ bits.push(`value=${JSON.stringify(e.value)}`);
106
+ if (e.href)
107
+ bits.push(`-> ${e.href}`);
108
+ return ' ' + bits.join(' ');
109
+ });
110
+ const head = `${s.title}\n${s.url}\n${s.elements.length} interactive elements (refs are stable until the page changes; re-snapshot after navigation)`;
111
+ return head + (lines.length ? '\n' + lines.join('\n') : '\n (none found)');
112
+ }