bidi-browser-mcp 0.1.9 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +398 -343
  3. package/dist/bin.js +3 -2
  4. package/dist/config.js +4 -0
  5. package/dist/connection/bidi-client.d.ts +13 -1
  6. package/dist/connection/bidi-client.js +59 -8
  7. package/dist/connection/browser-discovery.d.ts +20 -0
  8. package/dist/connection/browser-discovery.js +76 -12
  9. package/dist/connection/chromium-mapper.d.ts +9 -0
  10. package/dist/connection/chromium-mapper.js +24 -0
  11. package/dist/connection/event-pipeline.d.ts +15 -2
  12. package/dist/connection/event-pipeline.js +45 -3
  13. package/dist/connection/protocol-probe.d.ts +43 -0
  14. package/dist/connection/protocol-probe.js +112 -0
  15. package/dist/index.js +6 -0
  16. package/dist/session/session-manager.d.ts +26 -1
  17. package/dist/session/session-manager.js +262 -6
  18. package/dist/snapshot/cache.d.ts +4 -0
  19. package/dist/snapshot/cache.js +8 -0
  20. package/dist/snapshot/dom-snapshot.js +190 -181
  21. package/dist/snapshot/element-script.d.ts +23 -0
  22. package/dist/snapshot/element-script.js +70 -0
  23. package/dist/snapshot/token-optimizer.js +26 -8
  24. package/dist/snapshot/uid-verify.d.ts +43 -0
  25. package/dist/snapshot/uid-verify.js +154 -0
  26. package/dist/tools/browser.js +21 -6
  27. package/dist/tools/context.js +4 -6
  28. package/dist/tools/interact.d.ts +1 -0
  29. package/dist/tools/interact.js +593 -0
  30. package/dist/tools/network.d.ts +1 -0
  31. package/dist/tools/network.js +166 -0
  32. package/dist/tools/page.js +53 -2
  33. package/dist/tools/ping.js +5 -1
  34. package/dist/tools/script.d.ts +1 -0
  35. package/dist/tools/script.js +166 -0
  36. package/dist/types.d.ts +50 -1
  37. package/dist/utils/bidi-value.d.ts +10 -0
  38. package/dist/utils/bidi-value.js +56 -0
  39. package/dist/utils/errors.d.ts +3 -1
  40. package/dist/utils/errors.js +13 -7
  41. package/dist/utils/redact.d.ts +16 -0
  42. package/dist/utils/redact.js +47 -0
  43. package/package.json +86 -86
@@ -0,0 +1,112 @@
1
+ import { request as httpRequest } from 'node:http';
2
+ import { WebSocket } from 'ws';
3
+ /** Plain node:http GET — undici's fetch has proven flaky to loopback servers. */
4
+ export async function fingerprintHttpPort(port, timeoutMs = 1500) {
5
+ return new Promise((resolve) => {
6
+ let settled = false;
7
+ const finish = (fingerprint) => {
8
+ if (settled) {
9
+ return;
10
+ }
11
+ settled = true;
12
+ request.destroy();
13
+ resolve(fingerprint);
14
+ };
15
+ const request = httpRequest({ host: '127.0.0.1', port, path: '/', method: 'GET', timeout: timeoutMs }, (response) => {
16
+ const chunks = [];
17
+ response.on('data', (chunk) => chunks.push(chunk));
18
+ response.on('end', () => finish({
19
+ answered: true,
20
+ status: response.statusCode,
21
+ server: Array.isArray(response.headers.server)
22
+ ? response.headers.server[0]
23
+ : response.headers.server,
24
+ body: Buffer.concat(chunks).toString('utf8').slice(0, 4096),
25
+ }));
26
+ response.on('error', () => finish({ answered: false }));
27
+ });
28
+ request.on('timeout', () => finish({ answered: false }));
29
+ request.on('error', () => finish({ answered: false }));
30
+ request.end();
31
+ });
32
+ }
33
+ /**
34
+ * Firefox's Remote Agent serves its httpd.js index page at `/` — a stable
35
+ * protocol fingerprint that separates a live Firefox from Chromium's DevTools
36
+ * server (which answers 404 on every HTTP path since the `/json` endpoints
37
+ * were removed).
38
+ */
39
+ export function isFirefoxAgentFingerprint(fingerprint) {
40
+ if (!fingerprint.answered) {
41
+ return false;
42
+ }
43
+ if (fingerprint.server === 'httpd.js') {
44
+ return true;
45
+ }
46
+ return fingerprint.status === 200 && (fingerprint.body?.includes('httpd.js') ?? false);
47
+ }
48
+ /**
49
+ * Real WebDriver BiDi handshake: open the socket, send `session.status`, read
50
+ * the reply, close. This is what "connectable" means for a Firefox-family
51
+ * endpoint — a TCP port being open proves nothing about the protocol.
52
+ */
53
+ export async function probeBiDiHandshake(endpoint, timeoutMs = 1500) {
54
+ return new Promise((resolve) => {
55
+ let settled = false;
56
+ const socket = new WebSocket(endpoint, { handshakeTimeout: timeoutMs });
57
+ const finish = (result) => {
58
+ if (settled) {
59
+ return;
60
+ }
61
+ settled = true;
62
+ clearTimeout(timer);
63
+ socket.removeAllListeners();
64
+ // ws emits the handshake-abort 'error' asynchronously; never leave the
65
+ // socket without a listener or the process crashes.
66
+ socket.on('error', () => { });
67
+ try {
68
+ socket.terminate();
69
+ }
70
+ catch {
71
+ // The socket never opened; nothing to tear down.
72
+ }
73
+ resolve(result);
74
+ };
75
+ const timer = setTimeout(() => finish({ ok: false, error: 'handshake timed out' }), timeoutMs);
76
+ socket.on('unexpected-response', (_request, response) => {
77
+ finish({ ok: false, error: `HTTP ${response.statusCode ?? '?'}` });
78
+ });
79
+ socket.on('error', (error) => finish({ ok: false, error: error.message }));
80
+ socket.on('open', () => {
81
+ socket.send(JSON.stringify({ id: 1, method: 'session.status', params: {} }));
82
+ });
83
+ socket.on('message', (data) => {
84
+ const raw = Buffer.isBuffer(data)
85
+ ? data
86
+ : Array.isArray(data)
87
+ ? Buffer.concat(data)
88
+ : Buffer.from(data);
89
+ let parsed;
90
+ try {
91
+ parsed = JSON.parse(raw.toString('utf8'));
92
+ }
93
+ catch {
94
+ finish({ ok: false, error: 'non-JSON reply' });
95
+ return;
96
+ }
97
+ if (parsed.id !== 1) {
98
+ return; // Not the reply to our handshake command.
99
+ }
100
+ if (parsed.type === 'success') {
101
+ finish({ ok: true, ready: parsed.result?.ready === true });
102
+ }
103
+ else if (parsed.type === 'error') {
104
+ finish({ ok: true, ready: false, error: parsed.error ?? 'BiDi error' });
105
+ }
106
+ else {
107
+ finish({ ok: false, error: 'not a WebDriver BiDi reply' });
108
+ }
109
+ });
110
+ });
111
+ }
112
+ //# sourceMappingURL=protocol-probe.js.map
package/dist/index.js CHANGED
@@ -12,8 +12,11 @@ import { browserTool } from './tools/browser.js';
12
12
  import { cleanupTool } from './tools/cleanup.js';
13
13
  import { consoleTool } from './tools/console.js';
14
14
  import { contextTool } from './tools/context.js';
15
+ import { interactTool } from './tools/interact.js';
16
+ import { networkTool } from './tools/network.js';
15
17
  import { observeTool } from './tools/observe.js';
16
18
  import { pageTool } from './tools/page.js';
19
+ import { scriptTool } from './tools/script.js';
17
20
  import { spacesTool } from './tools/spaces.js';
18
21
  import { pingTool } from './tools/ping.js';
19
22
  import { tabsTool } from './tools/tabs.js';
@@ -44,6 +47,9 @@ export function createServer(options = {}) {
44
47
  registry.register(observeTool);
45
48
  registry.register(cleanupTool);
46
49
  registry.register(pageTool);
50
+ registry.register(interactTool);
51
+ registry.register(networkTool);
52
+ registry.register(scriptTool);
47
53
  registry.register(contextTool);
48
54
  registry.register(spacesTool);
49
55
  const server = new Server({ name: 'bidi-browser-mcp', version: VERSION }, { capabilities: { tools: {} } });
@@ -1,4 +1,7 @@
1
- import type { Config, ConnectionRuntimeLike, DiscoveryCandidate, SessionManagerLike, SessionStatus } from '../types.js';
1
+ import type { Config, ConnectionRuntimeLike, DiscoveryCandidate, ElementInfo, PageSnapshot, SessionManagerLike, SessionStatus } from '../types.js';
2
+ /** Expand a leading `~` — the redacted form of the home directory in tool
3
+ * output — so an agent can pass a listed profile path back to connect. */
4
+ export declare function expandHomeTilde(path: string): string;
2
5
  /**
3
6
  * The mapper reports CDP-shaped capabilities: `browserName` is a product
4
7
  * string ("Chrome/153.0.8010.53"), `browserVersion` is the CDP revision, and
@@ -18,14 +21,36 @@ export declare class SessionManager implements SessionManagerLike {
18
21
  /** Live-session services (events, contexts); undefined when disconnected. */
19
22
  get runtime(): ConnectionRuntimeLike | undefined;
20
23
  constructor(options: SessionManagerOptions);
24
+ /** The recorded plan for a uid, even after the snapshot cache was dropped. */
25
+ planFor(context: string, uid: string): ElementInfo | undefined;
21
26
  connect(): Promise<SessionStatus>;
22
27
  disconnect(): Promise<void>;
23
28
  status(): Promise<SessionStatus>;
24
29
  /** Send a BiDi command on the live session. */
25
30
  request(method: string, params?: Record<string, unknown>): Promise<Record<string, unknown>>;
26
31
  profiles(): Promise<readonly DiscoveryCandidate[]>;
32
+ /**
33
+ * Connect to a specific discovered browser: candidate id ('f-9444'), a
34
+ * port ('9444'), an exact endpoint, or a profile/user-data path (the
35
+ * redacted `~\…` form from profiles works). Undefined keeps the default
36
+ * ordered auto-connect. Switching ends the current session first — tabs
37
+ * stay open (the browser itself is never closed or restarted).
38
+ */
39
+ connectTo(target?: string): Promise<SessionStatus>;
27
40
  version(): Promise<{
28
41
  serverVersion: string;
29
42
  browserVersion?: string;
30
43
  }>;
44
+ /**
45
+ * Re-resolve a snapshot uid in the live page before dispatching input
46
+ * commands (plan §3). Silent when the element still matches; otherwise the
47
+ * mapped actionable error (UID_NOT_FOUND / ELEMENT_NOT_FOUND / STALE_UID).
48
+ */
49
+ verifyElement(snapshot: PageSnapshot, uid: string): Promise<void>;
50
+ /**
51
+ * Verify a known element plan against the live page in the given context
52
+ * (interact's plan-cache fallback). Same verdicts as verifyElement (§3):
53
+ * the plan is only a resolution hint, verification is the safety.
54
+ */
55
+ verifyElementPlan(element: ElementInfo, context: string, uid: string): Promise<void>;
31
56
  }
@@ -1,14 +1,165 @@
1
1
  import { BiDiClient } from '../connection/bidi-client.js';
2
2
  import { openChromiumMapperSocket } from '../connection/chromium-mapper.js';
3
3
  import { discoverBrowsers, endpointAllowed, } from '../connection/browser-discovery.js';
4
- import { EventPipeline } from '../connection/event-pipeline.js';
4
+ import { EventPipeline, NETWORK_SUBSCRIBED_EVENTS } from '../connection/event-pipeline.js';
5
5
  import { ContextManager } from './context-manager.js';
6
6
  import { SnapshotCache } from '../snapshot/cache.js';
7
+ import { resolveElement } from '../snapshot/element-resolver.js';
8
+ import { verifyElementRef } from '../snapshot/uid-verify.js';
7
9
  import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
10
+ import { homedir, platform } from 'node:os';
8
11
  import { join } from 'node:path';
9
12
  import { ActionableError, formatError } from '../utils/errors.js';
13
+ import { fingerprintHttpPort, isFirefoxAgentFingerprint, probeBiDiHandshake, } from '../connection/protocol-probe.js';
14
+ import { connect as tcpConnect } from 'node:net';
10
15
  /** Disk record so a later process can end a session this one left behind. */
11
16
  const LAST_SESSION_FILE = 'last-bidi-session.json';
17
+ /** Port from a ws endpoint path (`ws://127.0.0.1:9444/…` → '9444'). */
18
+ function portOf(endpoint) {
19
+ return /:(\d{2,5})\//.exec(endpoint)?.[1];
20
+ }
21
+ /**
22
+ * Family initial for a candidate id: `c` (Chromium/CDP), `f` (Firefox/BiDi),
23
+ * `x` (unidentified — a port that answers but speaks neither protocol).
24
+ */
25
+ function familyInitial(candidate) {
26
+ if (candidate.browserFamily === 'chromium') {
27
+ return 'c';
28
+ }
29
+ if (candidate.browserFamily === 'firefox') {
30
+ return 'f';
31
+ }
32
+ return 'x';
33
+ }
34
+ /**
35
+ * Stable short handles for a discovery list: family initial + port
36
+ * (`f-9223`, `c-9222`); a repeated family/port pair gets a running index
37
+ * suffix. The agent passes this (or a port, or the full endpoint) to
38
+ * browser.connect's target.
39
+ */
40
+ function assignIds(candidates) {
41
+ const used = new Map();
42
+ return candidates.map((candidate, index) => {
43
+ const base = `${familyInitial(candidate)}-${portOf(candidate.endpoint) ?? index}`;
44
+ const seen = used.get(base) ?? 0;
45
+ used.set(base, seen + 1);
46
+ return { ...candidate, id: seen === 0 ? base : `${base}-${seen}` };
47
+ });
48
+ }
49
+ /**
50
+ * TCP reachability probe for the candidate listing — a connect attempt with
51
+ * a short cap, nothing else. Loopback connects answer in milliseconds; the
52
+ * cap only bounds dead ports and firewalled hosts.
53
+ */
54
+ async function portReachable(endpoint, timeoutMs = 600) {
55
+ let url;
56
+ try {
57
+ url = new URL(endpoint);
58
+ }
59
+ catch {
60
+ return false;
61
+ }
62
+ const port = Number(url.port);
63
+ if (!Number.isInteger(port) || port <= 0) {
64
+ return false;
65
+ }
66
+ return new Promise((resolve) => {
67
+ const socket = tcpConnect({ host: url.hostname, port });
68
+ const done = (result) => {
69
+ socket.destroy();
70
+ resolve(result);
71
+ };
72
+ socket.once('connect', () => done(true));
73
+ socket.once('error', () => done(false));
74
+ socket.setTimeout(timeoutMs, () => done(false));
75
+ });
76
+ }
77
+ /** Listing probe budget: loopback answers in milliseconds; this bounds hangs. */
78
+ const PROBE_TIMEOUT_MS = 1500;
79
+ /**
80
+ * Enrich one discovery candidate for the listing: port, TCP reachability,
81
+ * and a connectability verdict.
82
+ *
83
+ * Chromium candidates are never WebSocket-probed: attaching to their browser
84
+ * endpoint may require the user to approve a new debugging client, and the
85
+ * handshake blocks until granted — a listing must not pop that dialog or
86
+ * hang on it. The DevToolsActivePort record plus TCP reachability is the
87
+ * verdict, and a port that now answers with Firefox's httpd.js fingerprint
88
+ * proves the record is stale (§6).
89
+ *
90
+ * BiDi-shaped candidates get a real `session.status` handshake — a TCP port
91
+ * being open proves nothing about the protocol, and `session.status` never
92
+ * creates a session, so probing cannot take Firefox's single-session slot.
93
+ */
94
+ async function enrichCandidate(candidate) {
95
+ const port = portOf(candidate.endpoint);
96
+ const portNumber = port === undefined ? undefined : Number(port);
97
+ const withPort = {
98
+ ...candidate,
99
+ ...(portNumber === undefined ? {} : { port: portNumber }),
100
+ };
101
+ const unreachable = `no listener on port ${port ?? candidate.endpoint}`;
102
+ if (candidate.browserFamily === 'chromium') {
103
+ const reachable = await portReachable(candidate.endpoint);
104
+ if (!reachable) {
105
+ return { ...withPort, reachable: false, connectable: false, reason: unreachable };
106
+ }
107
+ const fingerprint = await fingerprintHttpPort(portNumber ?? 0, PROBE_TIMEOUT_MS);
108
+ if (isFirefoxAgentFingerprint(fingerprint)) {
109
+ return {
110
+ ...withPort,
111
+ reachable: true,
112
+ connectable: false,
113
+ reason: 'port now serves a Firefox Remote Agent — the recorded DevToolsActivePort is stale',
114
+ };
115
+ }
116
+ return { ...withPort, reachable: true, connectable: true };
117
+ }
118
+ const reachable = await portReachable(candidate.endpoint);
119
+ if (!reachable) {
120
+ return { ...withPort, reachable: false, connectable: false, reason: unreachable };
121
+ }
122
+ const handshake = await probeBiDiHandshake(candidate.endpoint, PROBE_TIMEOUT_MS);
123
+ if (handshake.ok && handshake.ready !== false) {
124
+ // The handshake also proves the family for the speculative port-probe
125
+ // source: an endpoint that answers BiDi is a Firefox Remote Agent.
126
+ return {
127
+ ...withPort,
128
+ reachable: true,
129
+ connectable: true,
130
+ browserFamily: candidate.browserFamily ?? 'firefox',
131
+ };
132
+ }
133
+ return {
134
+ ...withPort,
135
+ reachable: true,
136
+ connectable: false,
137
+ reason: handshake.ready === false
138
+ ? `BiDi endpoint reports it is not accepting sessions (${handshake.error ?? 'not ready'})`
139
+ : `port answers but not with WebDriver BiDi (${handshake.error ?? 'no BiDi reply'})`,
140
+ };
141
+ }
142
+ /** Expand a leading `~` — the redacted form of the home directory in tool
143
+ * output — so an agent can pass a listed profile path back to connect. */
144
+ export function expandHomeTilde(path) {
145
+ if (path === '~') {
146
+ return homedir();
147
+ }
148
+ if (path.startsWith('~/') || path.startsWith('~\\')) {
149
+ return join(homedir(), path.slice(2));
150
+ }
151
+ return path;
152
+ }
153
+ /** Path equality: case-insensitive on Windows, exact elsewhere. */
154
+ function samePath(a, b) {
155
+ if (a === b) {
156
+ return true;
157
+ }
158
+ if (platform() !== 'win32') {
159
+ return false;
160
+ }
161
+ return a.replace(/\//g, '\\').toLowerCase() === b.replace(/\//g, '\\').toLowerCase();
162
+ }
12
163
  /**
13
164
  * The mapper reports CDP-shaped capabilities: `browserName` is a product
14
165
  * string ("Chrome/153.0.8010.53"), `browserVersion` is the CDP revision, and
@@ -49,6 +200,13 @@ export class SessionManager {
49
200
  #profile;
50
201
  #connecting;
51
202
  #runtime;
203
+ /**
204
+ * uid → element plans per context, indexed on every snapshot set. Interact
205
+ * consults these when the snapshot cache was invalidated by a previous
206
+ * dispatch: the plan is only a resolution hint, and live verification
207
+ * (§3) still guards every dispatch.
208
+ */
209
+ #plans = new Map();
52
210
  /** Live-session services (events, contexts); undefined when disconnected. */
53
211
  get runtime() {
54
212
  return this.#runtime;
@@ -57,6 +215,17 @@ export class SessionManager {
57
215
  this.#config = options.config;
58
216
  this.#serverVersion = options.serverVersion;
59
217
  }
218
+ /** The recorded plan for a uid, even after the snapshot cache was dropped. */
219
+ planFor(context, uid) {
220
+ return this.#plans.get(context)?.get(uid);
221
+ }
222
+ #indexPlans(snapshot) {
223
+ const plans = new Map();
224
+ for (const element of snapshot.elements) {
225
+ plans.set(element.uid, element);
226
+ }
227
+ this.#plans.set(snapshot.context, plans);
228
+ }
60
229
  async connect() {
61
230
  const existing = this.#status();
62
231
  if (existing.connected) {
@@ -123,14 +292,78 @@ export class SessionManager {
123
292
  }
124
293
  return client.request(method, params);
125
294
  }
126
- async profiles() {
295
+ /**
296
+ * Enriched discovery: protocol classification, connectability verdicts,
297
+ * and stable ids — the single source both the listing and connect-target
298
+ * resolution use, so an id shown by profiles() always resolves.
299
+ */
300
+ async #discoverEnriched() {
127
301
  const candidates = await discoverBrowsers(this.#config);
302
+ const enriched = await Promise.all(candidates.map((candidate) => enrichCandidate(candidate)));
303
+ return assignIds(enriched);
304
+ }
305
+ /**
306
+ * Auto-connect order, skipping endpoints the listing already proved dead
307
+ * or non-BiDi. When nothing survives the filter, fall back to the full
308
+ * list so the final error carries each attempt's real failure.
309
+ */
310
+ async #autoConnectCandidates() {
311
+ const enriched = await this.#discoverEnriched();
312
+ const viable = enriched.filter((candidate) => candidate.connectable !== false);
313
+ return viable.length > 0 ? viable : enriched;
314
+ }
315
+ async profiles() {
316
+ const enriched = await this.#discoverEnriched();
128
317
  const connectedEndpoint = this.#client?.url;
129
- return candidates.map((candidate) => ({
318
+ return enriched.map((candidate) => ({
130
319
  ...candidate,
131
320
  ...(connectedEndpoint === candidate.endpoint ? { live: true } : {}),
132
321
  }));
133
322
  }
323
+ /**
324
+ * Connect to a specific discovered browser: candidate id ('f-9444'), a
325
+ * port ('9444'), an exact endpoint, or a profile/user-data path (the
326
+ * redacted `~\…` form from profiles works). Undefined keeps the default
327
+ * ordered auto-connect. Switching ends the current session first — tabs
328
+ * stay open (the browser itself is never closed or restarted).
329
+ */
330
+ async connectTo(target) {
331
+ if (target === undefined || target.trim() === '') {
332
+ return this.connect();
333
+ }
334
+ const candidates = await this.#discoverEnriched();
335
+ if (candidates.length === 0) {
336
+ throw new ActionableError('DISCOVERY_FAILED', 'No reachable browser endpoint was found.', { fix: 'Start Firefox or Zen with --remote-debugging-port, or set BIDI_WS_URL.' });
337
+ }
338
+ const needle = target.trim();
339
+ const chosen = this.#resolveTarget(candidates, needle);
340
+ if (chosen === undefined) {
341
+ throw new ActionableError('INVALID_ARGUMENT', `No discovery candidate matches "${needle}".`, {
342
+ fix: `Pick one of: ${candidates
343
+ .map((entry) => `${entry.id} (${entry.endpoint})`)
344
+ .join(', ')}.`,
345
+ });
346
+ }
347
+ if (this.#client?.url === chosen.endpoint) {
348
+ return this.status();
349
+ }
350
+ if (this.#client !== undefined) {
351
+ // Explicit switch: end the owned session (tabs stay open), then attach
352
+ // to the requested candidate through the same busy/recovery flow.
353
+ await this.disconnect();
354
+ }
355
+ return this.#connectOnce([chosen]);
356
+ }
357
+ /** Resolve a connect target string against the discovery list. */
358
+ #resolveTarget(candidates, needle) {
359
+ const endpoint = needle.startsWith('ws://') ? needle : undefined;
360
+ const port = /^\d{2,5}$/.test(needle) ? needle : undefined;
361
+ const pathNeedle = expandHomeTilde(needle);
362
+ return (candidates.find((entry) => entry.endpoint === endpoint) ??
363
+ candidates.find((entry) => port !== undefined && portOf(entry.endpoint) === port) ??
364
+ candidates.find((entry) => entry.id === needle) ??
365
+ candidates.find((entry) => entry.profilePath !== undefined && samePath(entry.profilePath, pathNeedle)));
366
+ }
134
367
  async version() {
135
368
  const status = this.#status();
136
369
  const browserVersion = status.browser?.browserVersion;
@@ -139,8 +372,24 @@ export class SessionManager {
139
372
  ...(browserVersion === undefined ? {} : { browserVersion }),
140
373
  };
141
374
  }
142
- async #connectOnce() {
143
- const candidates = await discoverBrowsers(this.#config);
375
+ /**
376
+ * Re-resolve a snapshot uid in the live page before dispatching input
377
+ * commands (plan §3). Silent when the element still matches; otherwise the
378
+ * mapped actionable error (UID_NOT_FOUND / ELEMENT_NOT_FOUND / STALE_UID).
379
+ */
380
+ async verifyElement(snapshot, uid) {
381
+ await verifyElementRef((method, params) => this.request(method, params), resolveElement(snapshot, uid), snapshot.context, uid);
382
+ }
383
+ /**
384
+ * Verify a known element plan against the live page in the given context
385
+ * (interact's plan-cache fallback). Same verdicts as verifyElement (§3):
386
+ * the plan is only a resolution hint, verification is the safety.
387
+ */
388
+ async verifyElementPlan(element, context, uid) {
389
+ await verifyElementRef((method, params) => this.request(method, params), element, context, uid);
390
+ }
391
+ async #connectOnce(only) {
392
+ const candidates = only ?? (await this.#autoConnectCandidates());
144
393
  if (candidates.length === 0) {
145
394
  throw new ActionableError('DISCOVERY_FAILED', 'No reachable browser endpoint was found.', {
146
395
  fix: 'Start Firefox or Zen with --remote-debugging-port, start a Chromium browser' +
@@ -208,13 +457,20 @@ export class SessionManager {
208
457
  : rawCapabilities;
209
458
  const pipeline = new EventPipeline();
210
459
  const contexts = new ContextManager(client);
211
- const snapshots = new SnapshotCache();
460
+ const snapshots = new SnapshotCache((snapshot) => this.#indexPlans(snapshot));
212
461
  pipeline.registerSink((event) => {
213
462
  contexts.handleEvent(event);
214
463
  snapshots.handleEvent(event);
215
464
  });
216
465
  try {
217
466
  await pipeline.attach(client);
467
+ if (this.#config.enableNetwork) {
468
+ // Network waits match traffic buffered since the subscription
469
+ // point, so subscribing at connect (not first wait) makes the
470
+ // common trigger-then-wait flow work. Failure here is fine — the
471
+ // tool re-subscribes and surfaces the error when actually used.
472
+ await pipeline.addSubscription(NETWORK_SUBSCRIBED_EVENTS).catch(() => undefined);
473
+ }
218
474
  await contexts.sync();
219
475
  }
220
476
  catch (error) {
@@ -3,9 +3,13 @@ import type { BiDiEvent, PageSnapshot, SnapshotCacheLike } from '../types.js';
3
3
  * Per-context snapshot cache. Entries live until the page navigates
4
4
  * (domContentLoaded), the context closes, or the session ends — the browser
5
5
  * tree and page events are the source of truth, so there is no TTL.
6
+ * @param onSet Optional hook fired on every set; the session manager uses it
7
+ * to keep its uid→plan index current (interact needs plans after
8
+ * invalidation, and verification provides the staleness safety).
6
9
  */
7
10
  export declare class SnapshotCache implements SnapshotCacheLike {
8
11
  #private;
12
+ constructor(onSet?: (snapshot: PageSnapshot) => void);
9
13
  get(context: string): PageSnapshot | undefined;
10
14
  set(snapshot: PageSnapshot): void;
11
15
  invalidate(context: string): void;
@@ -2,14 +2,22 @@
2
2
  * Per-context snapshot cache. Entries live until the page navigates
3
3
  * (domContentLoaded), the context closes, or the session ends — the browser
4
4
  * tree and page events are the source of truth, so there is no TTL.
5
+ * @param onSet Optional hook fired on every set; the session manager uses it
6
+ * to keep its uid→plan index current (interact needs plans after
7
+ * invalidation, and verification provides the staleness safety).
5
8
  */
6
9
  export class SnapshotCache {
7
10
  #entries = new Map();
11
+ #onSet;
12
+ constructor(onSet) {
13
+ this.#onSet = onSet;
14
+ }
8
15
  get(context) {
9
16
  return this.#entries.get(context);
10
17
  }
11
18
  set(snapshot) {
12
19
  this.#entries.set(snapshot.context, snapshot);
20
+ this.#onSet?.(snapshot);
13
21
  }
14
22
  invalidate(context) {
15
23
  this.#entries.delete(context);