bidi-browser-mcp 0.1.9

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 (61) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +343 -0
  3. package/dist/bin.d.ts +6 -0
  4. package/dist/bin.js +37 -0
  5. package/dist/config.d.ts +6 -0
  6. package/dist/config.js +122 -0
  7. package/dist/connection/bidi-client.d.ts +29 -0
  8. package/dist/connection/bidi-client.js +298 -0
  9. package/dist/connection/browser-discovery.d.ts +30 -0
  10. package/dist/connection/browser-discovery.js +393 -0
  11. package/dist/connection/chromium-mapper.d.ts +55 -0
  12. package/dist/connection/chromium-mapper.js +293 -0
  13. package/dist/connection/event-pipeline.d.ts +37 -0
  14. package/dist/connection/event-pipeline.js +167 -0
  15. package/dist/index.d.ts +19 -0
  16. package/dist/index.js +66 -0
  17. package/dist/profile/profile-store.d.ts +88 -0
  18. package/dist/profile/profile-store.js +350 -0
  19. package/dist/session/context-manager.d.ts +17 -0
  20. package/dist/session/context-manager.js +179 -0
  21. package/dist/session/session-manager.d.ts +31 -0
  22. package/dist/session/session-manager.js +366 -0
  23. package/dist/snapshot/cache.d.ts +15 -0
  24. package/dist/snapshot/cache.js +37 -0
  25. package/dist/snapshot/dom-snapshot.d.ts +5 -0
  26. package/dist/snapshot/dom-snapshot.js +270 -0
  27. package/dist/snapshot/element-resolver.d.ts +13 -0
  28. package/dist/snapshot/element-resolver.js +25 -0
  29. package/dist/snapshot/token-optimizer.d.ts +16 -0
  30. package/dist/snapshot/token-optimizer.js +103 -0
  31. package/dist/tools/base-tool.d.ts +34 -0
  32. package/dist/tools/base-tool.js +55 -0
  33. package/dist/tools/browser.d.ts +1 -0
  34. package/dist/tools/browser.js +75 -0
  35. package/dist/tools/cleanup.d.ts +1 -0
  36. package/dist/tools/cleanup.js +64 -0
  37. package/dist/tools/console.d.ts +1 -0
  38. package/dist/tools/console.js +87 -0
  39. package/dist/tools/context.d.ts +1 -0
  40. package/dist/tools/context.js +156 -0
  41. package/dist/tools/observe.d.ts +1 -0
  42. package/dist/tools/observe.js +92 -0
  43. package/dist/tools/page.d.ts +1 -0
  44. package/dist/tools/page.js +139 -0
  45. package/dist/tools/ping.d.ts +1 -0
  46. package/dist/tools/ping.js +71 -0
  47. package/dist/tools/registry.d.ts +13 -0
  48. package/dist/tools/registry.js +47 -0
  49. package/dist/tools/spaces.d.ts +1 -0
  50. package/dist/tools/spaces.js +98 -0
  51. package/dist/tools/tabs.d.ts +1 -0
  52. package/dist/tools/tabs.js +155 -0
  53. package/dist/types.d.ts +277 -0
  54. package/dist/types.js +5 -0
  55. package/dist/utils/assert.d.ts +12 -0
  56. package/dist/utils/assert.js +74 -0
  57. package/dist/utils/errors.d.ts +24 -0
  58. package/dist/utils/errors.js +60 -0
  59. package/dist/utils/result.d.ts +14 -0
  60. package/dist/utils/result.js +37 -0
  61. package/package.json +86 -0
@@ -0,0 +1,350 @@
1
+ import { closeSync, existsSync, fstatSync, openSync, readSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ const CONTAINERS_FILE = 'containers.json';
4
+ const ZEN_SESSIONS_FILE = 'zen-sessions.jsonlz4';
5
+ /** Refuse to decode an unbounded session store into the MCP process. */
6
+ export const MAX_SESSION_STORE_BYTES = 16 * 1024 * 1024;
7
+ /** containers.json holds a handful of identities; anything larger is corrupt. */
8
+ export const MAX_CONTAINERS_BYTES = 1024 * 1024;
9
+ /** How many opening braces to try before giving up on one uuid anchor. */
10
+ const MAX_BRACE_CANDIDATES = 24;
11
+ /** A space object is small; a larger candidate is not a space object. */
12
+ const MAX_SPACE_OBJECT_CHARS = 256 * 1024;
13
+ /**
14
+ * Read a file with a hard size cap.
15
+ *
16
+ * The size comes from the open file descriptor, so a file that grows after
17
+ * the check cannot push the read past the cap: at most `maxBytes` are read,
18
+ * and a truncated stream fails the decode instead of being buffered.
19
+ */
20
+ function readBoundedFile(path, maxBytes) {
21
+ let fd;
22
+ try {
23
+ fd = openSync(path, 'r');
24
+ const size = fstatSync(fd).size;
25
+ if (size > maxBytes) {
26
+ return { ok: false, tooLarge: true };
27
+ }
28
+ const buffer = Buffer.alloc(size);
29
+ let offset = 0;
30
+ while (offset < buffer.length) {
31
+ const read = readSync(fd, buffer, offset, buffer.length - offset, offset);
32
+ if (read <= 0) {
33
+ break;
34
+ }
35
+ offset += read;
36
+ }
37
+ return { ok: true, data: buffer.subarray(0, offset) };
38
+ }
39
+ catch {
40
+ return { ok: false, tooLarge: false };
41
+ }
42
+ finally {
43
+ if (fd !== undefined) {
44
+ try {
45
+ closeSync(fd);
46
+ }
47
+ catch {
48
+ // Ignore close errors — the data is already read.
49
+ }
50
+ }
51
+ }
52
+ }
53
+ /**
54
+ * Hard ceiling for decoded output. The input cap does not bound expansion:
55
+ * LZ4 overlapping matches can inflate a small file enormously.
56
+ */
57
+ export const MAX_DECODED_BYTES = 64 * 1024 * 1024;
58
+ /**
59
+ * Decode an LZ4 block (Firefox's mozLz4 payload). Minimal, dev-stable.
60
+ * `expectedSize` preallocates the output buffer — the byte-per-number array
61
+ * this replaced cost ~8 bytes per decoded byte.
62
+ *
63
+ * Safety: buffers are zero-filled (never `allocUnsafe`), a short literal read
64
+ * is an error instead of a gap, and the decoded size is capped.
65
+ */
66
+ export function lz4BlockDecode(input, expectedSize) {
67
+ const declared = expectedSize !== undefined && expectedSize > 0 ? expectedSize : 0;
68
+ if (declared > MAX_DECODED_BYTES) {
69
+ throw new Error(`Declared size ${declared} exceeds the decode limit.`);
70
+ }
71
+ let out = Buffer.alloc(declared > 0
72
+ ? declared
73
+ : Math.min(Math.max(input.length * 4, 1024), 1024 * 1024));
74
+ let length = 0;
75
+ const ensure = (extra) => {
76
+ if (length + extra > MAX_DECODED_BYTES) {
77
+ throw new Error(`Decoded size exceeds ${MAX_DECODED_BYTES} bytes.`);
78
+ }
79
+ if (length + extra <= out.length) {
80
+ return;
81
+ }
82
+ let size = Math.max(out.length * 2, 1024);
83
+ while (size < length + extra) {
84
+ size *= 2;
85
+ }
86
+ size = Math.min(size, MAX_DECODED_BYTES);
87
+ const grown = Buffer.alloc(size);
88
+ out.copy(grown, 0, 0, length);
89
+ out = grown;
90
+ };
91
+ let pos = 0;
92
+ while (pos < input.length) {
93
+ const token = input[pos++];
94
+ let literalLength = token >> 4;
95
+ if (literalLength === 15) {
96
+ let extension;
97
+ do {
98
+ if (pos >= input.length) {
99
+ throw new Error('Truncated LZ4 literal length.');
100
+ }
101
+ extension = input[pos++];
102
+ literalLength += extension;
103
+ } while (extension === 255);
104
+ }
105
+ ensure(literalLength);
106
+ // A short read must not advance `length`: the gap would stay
107
+ // uninitialized and leak into the decoded text.
108
+ const copied = input.copy(out, length, pos, pos + literalLength);
109
+ if (copied !== literalLength) {
110
+ throw new Error('Truncated LZ4 literal run.');
111
+ }
112
+ pos += copied;
113
+ length += copied;
114
+ if (pos >= input.length) {
115
+ break;
116
+ }
117
+ if (pos + 1 >= input.length) {
118
+ throw new Error('Truncated LZ4 match offset.');
119
+ }
120
+ const offset = input[pos] | (input[pos + 1] << 8);
121
+ pos += 2;
122
+ let matchLength = token & 0x0f;
123
+ if (matchLength === 15) {
124
+ let extension;
125
+ do {
126
+ if (pos >= input.length) {
127
+ throw new Error('Truncated LZ4 match length.');
128
+ }
129
+ extension = input[pos++];
130
+ matchLength += extension;
131
+ } while (extension === 255);
132
+ }
133
+ matchLength += 4;
134
+ const matchPos = length - offset;
135
+ if (matchPos < 0 || offset === 0) {
136
+ throw new Error('Invalid LZ4 match offset.');
137
+ }
138
+ ensure(matchLength);
139
+ for (let i = 0; i < matchLength; i++) {
140
+ out[length++] = out[matchPos + i];
141
+ }
142
+ }
143
+ return out.subarray(0, length);
144
+ }
145
+ /** Decode a Firefox mozLz4 container (8-byte magic + size + LZ4 block). */
146
+ export function decodeMozLz4(raw) {
147
+ if (raw.subarray(0, 8).toString('latin1') !== 'mozLz40\0') {
148
+ throw new Error('Not a mozLz4 file.');
149
+ }
150
+ const size = raw.readUInt32LE(8);
151
+ return lz4BlockDecode(raw.subarray(12), size).toString('utf8');
152
+ }
153
+ export function parseContainersJson(text) {
154
+ let parsed;
155
+ try {
156
+ parsed = JSON.parse(text);
157
+ }
158
+ catch {
159
+ return [];
160
+ }
161
+ if (!Array.isArray(parsed.identities)) {
162
+ return [];
163
+ }
164
+ const identities = [];
165
+ for (const entry of parsed.identities) {
166
+ // One malformed entry must not throw away every valid identity.
167
+ if (entry === null || typeof entry !== 'object') {
168
+ continue;
169
+ }
170
+ const identity = entry;
171
+ if (!Number.isSafeInteger(identity.userContextId)) {
172
+ continue;
173
+ }
174
+ identities.push({
175
+ userContextId: identity.userContextId,
176
+ ...(typeof identity.name === 'string' && identity.name !== '' ? { name: identity.name } : {}),
177
+ ...(typeof identity.icon === 'string' && identity.icon !== '' ? { icon: identity.icon } : {}),
178
+ ...(typeof identity.color === 'string' && identity.color !== '' ? { color: identity.color } : {}),
179
+ isPublic: identity.public === true,
180
+ });
181
+ }
182
+ return identities;
183
+ }
184
+ /**
185
+ * Extract space definitions from the session store. Objects look like
186
+ * `{"uuid":"{...}","name":"...","theme":{...},"containerTabId":N,...}`;
187
+ * the anchor regex hits inside the object, so scanning resumes from the
188
+ * nearest preceding `{` and parses a balanced object. The anchor tolerates
189
+ * whitespace and any key order, so a Zen format change does not silently
190
+ * empty the list.
191
+ */
192
+ export function parseSpaces(text) {
193
+ const spaces = [];
194
+ const anchor = /"uuid"\s*:\s*"\{[0-9a-fA-F-]+\}"/g;
195
+ let match;
196
+ while ((match = anchor.exec(text)) !== null) {
197
+ // The anchor can sit inside a nested object (a theme before the uuid, for
198
+ // example), so walk back over opening braces until one object parses as a
199
+ // space. The nearest enclosing brace is tried first.
200
+ let searchFrom = match.index;
201
+ for (let attempt = 0; attempt < MAX_BRACE_CANDIDATES; attempt++) {
202
+ const objStart = text.lastIndexOf('{', searchFrom - 1);
203
+ if (objStart < 0) {
204
+ break;
205
+ }
206
+ const obj = readBalancedObject(text, objStart);
207
+ if (obj === null || obj.length > MAX_SPACE_OBJECT_CHARS) {
208
+ break;
209
+ }
210
+ const space = parseSpaceObject(obj);
211
+ if (space !== undefined) {
212
+ spaces.push(space);
213
+ anchor.lastIndex = objStart + obj.length;
214
+ break;
215
+ }
216
+ searchFrom = objStart;
217
+ }
218
+ }
219
+ return spaces;
220
+ }
221
+ /** Parse one candidate object as a Zen space. Pure. */
222
+ function parseSpaceObject(obj) {
223
+ let parsed;
224
+ try {
225
+ parsed = JSON.parse(obj);
226
+ }
227
+ catch {
228
+ return undefined;
229
+ }
230
+ if (typeof parsed.uuid !== 'string' || typeof parsed.name !== 'string') {
231
+ return undefined;
232
+ }
233
+ return {
234
+ uuid: parsed.uuid,
235
+ name: parsed.name,
236
+ ...(typeof parsed.theme?.type === 'string' ? { themeType: parsed.theme.type } : {}),
237
+ ...(typeof parsed.containerTabId === 'number' ? { containerId: parsed.containerTabId } : {}),
238
+ };
239
+ }
240
+ /** Read the `{...}` JSON object starting at `start`. Pure text scan. */
241
+ function readBalancedObject(text, start) {
242
+ let depth = 0;
243
+ let inString = false;
244
+ let escaped = false;
245
+ for (let i = start; i < text.length; i++) {
246
+ const ch = text[i];
247
+ if (inString) {
248
+ if (escaped) {
249
+ escaped = false;
250
+ }
251
+ else if (ch === '\\') {
252
+ escaped = true;
253
+ }
254
+ else if (ch === '"') {
255
+ inString = false;
256
+ }
257
+ continue;
258
+ }
259
+ if (ch === '"') {
260
+ inString = true;
261
+ }
262
+ else if (ch === '{') {
263
+ depth++;
264
+ }
265
+ else if (ch === '}') {
266
+ depth--;
267
+ if (depth === 0) {
268
+ return text.slice(start, i + 1);
269
+ }
270
+ }
271
+ }
272
+ return null;
273
+ }
274
+ /**
275
+ * Join BiDi user context ids (uuids, 'default' first in id order) with
276
+ * containers.json identities. Verified on Firefox 158/Zen 1.23: BiDi lists
277
+ * public containers in internal-id order; names join positionally. The
278
+ * "default" context has no containers.json identity.
279
+ *
280
+ * The join is positional because Firefox exposes no id bridge, so it is only
281
+ * trustworthy while the counts line up. A mismatch means a name could land on
282
+ * the wrong container — names are dropped instead.
283
+ */
284
+ export function joinContainerNames(bidiIds, containers) {
285
+ const byId = [...containers]
286
+ .filter((identity) => identity.isPublic)
287
+ .sort((a, b) => a.userContextId - b.userContextId);
288
+ const names = new Map();
289
+ const nonDefault = bidiIds.filter((id) => id !== 'default');
290
+ if (nonDefault.length !== byId.length) {
291
+ return { names, aligned: false };
292
+ }
293
+ nonDefault.forEach((id, index) => {
294
+ const identity = byId[index];
295
+ if (identity !== undefined) {
296
+ names.set(id, identity);
297
+ }
298
+ });
299
+ return { names, aligned: true };
300
+ }
301
+ /** Read container identities only. Never touches the session store. */
302
+ export function readContainers(profilePath) {
303
+ const read = readBoundedFile(join(profilePath, CONTAINERS_FILE), MAX_CONTAINERS_BYTES);
304
+ if (!read.ok) {
305
+ return [];
306
+ }
307
+ try {
308
+ return parseContainersJson(read.data.toString('utf8'));
309
+ }
310
+ catch {
311
+ return [];
312
+ }
313
+ }
314
+ /**
315
+ * Read Zen spaces from the session store. The file can hold open-tab URLs and
316
+ * form state — only derived metadata (uuid, name, theme, container id) leaves
317
+ * this function.
318
+ */
319
+ export function readSpaces(profilePath) {
320
+ const warnings = [];
321
+ const spaces = [];
322
+ const sessionsPath = join(profilePath, ZEN_SESSIONS_FILE);
323
+ if (!existsSync(sessionsPath)) {
324
+ return { spaces, warnings };
325
+ }
326
+ const read = readBoundedFile(sessionsPath, MAX_SESSION_STORE_BYTES);
327
+ if (!read.ok) {
328
+ return {
329
+ spaces,
330
+ warnings: read.tooLarge
331
+ ? [
332
+ `Session store is over the ${MAX_SESSION_STORE_BYTES}-byte limit; Zen spaces were skipped.`,
333
+ ]
334
+ : ['Session store could not be read; Zen spaces were skipped.'],
335
+ };
336
+ }
337
+ try {
338
+ spaces.push(...parseSpaces(decodeMozLz4(read.data)));
339
+ }
340
+ catch (error) {
341
+ warnings.push(`Could not decode the session store: ${error instanceof Error ? error.message : String(error)}`);
342
+ }
343
+ return { spaces, warnings };
344
+ }
345
+ /** Read profile data; missing files degrade to empty lists. */
346
+ export function readProfileStore(profilePath) {
347
+ const { spaces, warnings } = readSpaces(profilePath);
348
+ return { containers: readContainers(profilePath), spaces, warnings };
349
+ }
350
+ //# sourceMappingURL=profile-store.js.map
@@ -0,0 +1,17 @@
1
+ import type { BiDiClientLike, BiDiEvent, ContextManagerLike, TabInfo } from '../types.js';
2
+ /**
3
+ * Tracks top-level tabs for the live session. The browser stays the source of
4
+ * truth (list() re-reads the tree); events only keep the cache and selection
5
+ * consistent between calls.
6
+ */
7
+ export declare class ContextManager implements ContextManagerLike {
8
+ #private;
9
+ constructor(client: BiDiClientLike);
10
+ /** Seed the cache from the current tree. Called right after connect. */
11
+ sync(): Promise<void>;
12
+ list(): Promise<readonly TabInfo[]>;
13
+ ensureContext(context?: string): Promise<string>;
14
+ select(context: string): Promise<TabInfo>;
15
+ handleEvent(event: BiDiEvent): void;
16
+ forget(context: string): void;
17
+ }
@@ -0,0 +1,179 @@
1
+ import { ActionableError } from '../utils/errors.js';
2
+ /**
3
+ * Tracks top-level tabs for the live session. The browser stays the source of
4
+ * truth (list() re-reads the tree); events only keep the cache and selection
5
+ * consistent between calls.
6
+ */
7
+ export class ContextManager {
8
+ #client;
9
+ #tabs = new Map();
10
+ /** Last URL seen in the tree per context, to spot a stale tree after SPA navigation. */
11
+ #lastTreeUrl = new Map();
12
+ /** URL reported by a browsingContext event, which can be newer than the tree. */
13
+ #eventUrl = new Map();
14
+ #selected;
15
+ constructor(client) {
16
+ this.#client = client;
17
+ }
18
+ /** Seed the cache from the current tree. Called right after connect. */
19
+ async sync() {
20
+ const tree = await this.#client.request('browsingContext.getTree', { maxDepth: 1 });
21
+ this.#mergeTree(tree);
22
+ }
23
+ async list() {
24
+ const tree = await this.#client.request('browsingContext.getTree', { maxDepth: 1 });
25
+ this.#mergeTree(tree);
26
+ const tabs = [...this.#tabs.values()];
27
+ const selected = this.#resolveSelectedId(tabs);
28
+ return tabs.map((tab) => ({
29
+ context: tab.context,
30
+ url: tab.url,
31
+ ...(tab.children > 0 ? { children: tab.children } : {}),
32
+ ...(tab.userContext === undefined ? {} : { userContext: tab.userContext }),
33
+ ...(tab.context === selected ? { selected: true } : {}),
34
+ }));
35
+ }
36
+ async ensureContext(context) {
37
+ if (context !== undefined && context !== '') {
38
+ // The id may be a frame context, which the top-level tree does not
39
+ // list — existence is checked by the browser when the id is used.
40
+ return context;
41
+ }
42
+ const tabs = [...this.#tabs.values()];
43
+ const selected = this.#resolveSelectedId(tabs);
44
+ const fallback = tabs.find((tab) => tab.context === selected) ?? tabs[0];
45
+ if (fallback === undefined) {
46
+ throw new ActionableError('CONTEXT_NOT_FOUND', 'No browsing contexts are open.', {
47
+ fix: 'Open a tab, or use tabs.new to create one.',
48
+ });
49
+ }
50
+ return fallback.context;
51
+ }
52
+ async select(context) {
53
+ const tabs = await this.list();
54
+ const tab = tabs.find((candidate) => candidate.context === context);
55
+ if (tab === undefined) {
56
+ throw new ActionableError('TAB_NOT_FOUND', `Unknown context: ${context}.`, {
57
+ fix: 'Call tabs.list to see open contexts.',
58
+ details: { open: tabs.map((candidate) => candidate.context) },
59
+ });
60
+ }
61
+ this.#selected = context;
62
+ return { ...tab, selected: true };
63
+ }
64
+ handleEvent(event) {
65
+ const params = event.params;
66
+ const context = typeof params.context === 'string' ? params.context : undefined;
67
+ if (context === undefined) {
68
+ return;
69
+ }
70
+ switch (event.method) {
71
+ case 'browsingContext.contextCreated':
72
+ this.#tabs.set(context, { context, url: '', children: 0 });
73
+ break;
74
+ case 'browsingContext.contextDestroyed':
75
+ this.#tabs.delete(context);
76
+ this.#lastTreeUrl.delete(context);
77
+ this.#eventUrl.delete(context);
78
+ if (this.#selected === context) {
79
+ this.#selected = undefined;
80
+ }
81
+ break;
82
+ case 'browsingContext.domContentLoaded':
83
+ case 'browsingContext.urlChanged':
84
+ // urlChanged fires on SPA navigation, where no domContentLoaded
85
+ // arrives — without it, tabs.list keeps a stale URL.
86
+ if (typeof params.url === 'string') {
87
+ const tab = this.#tabs.get(context);
88
+ if (tab !== undefined) {
89
+ tab.url = params.url;
90
+ }
91
+ else {
92
+ this.#tabs.set(context, { context, url: params.url, children: 0 });
93
+ }
94
+ // Remember that this URL came from an event: the tree may still
95
+ // report the previous one.
96
+ this.#eventUrl.set(context, params.url);
97
+ }
98
+ break;
99
+ default:
100
+ break;
101
+ }
102
+ }
103
+ forget(context) {
104
+ this.#tabs.delete(context);
105
+ this.#lastTreeUrl.delete(context);
106
+ this.#eventUrl.delete(context);
107
+ if (this.#selected === context) {
108
+ this.#selected = undefined;
109
+ }
110
+ }
111
+ #mergeTree(tree) {
112
+ const contexts = tree.contexts;
113
+ if (!Array.isArray(contexts)) {
114
+ return;
115
+ }
116
+ const seen = new Set();
117
+ for (const entry of contexts) {
118
+ if (entry === null || typeof entry !== 'object') {
119
+ continue;
120
+ }
121
+ const node = entry;
122
+ if (typeof node.context !== 'string') {
123
+ continue;
124
+ }
125
+ seen.add(node.context);
126
+ const children = Array.isArray(node.children) ? node.children.length : 0;
127
+ const existing = this.#tabs.get(node.context);
128
+ const treeUrl = typeof node.url === 'string' && node.url !== '' ? node.url : undefined;
129
+ const previousTreeUrl = this.#lastTreeUrl.get(node.context);
130
+ // A urlChanged event (SPA navigation) can be newer than the tree
131
+ // snapshot. Keep the event URL while the tree still reports the old
132
+ // one; once the tree moves, the tree wins.
133
+ const treeMoved = previousTreeUrl !== undefined &&
134
+ treeUrl !== undefined &&
135
+ treeUrl !== previousTreeUrl;
136
+ if (treeMoved) {
137
+ // The tree reports a newer navigation — the event URL is superseded.
138
+ this.#eventUrl.delete(node.context);
139
+ }
140
+ const eventUrl = this.#eventUrl.get(node.context);
141
+ if (eventUrl !== undefined && treeUrl === eventUrl) {
142
+ // The tree caught up with the event.
143
+ this.#eventUrl.delete(node.context);
144
+ }
145
+ this.#tabs.set(node.context, {
146
+ context: node.context,
147
+ url: eventUrl !== undefined && treeUrl !== undefined && treeUrl !== eventUrl
148
+ ? eventUrl
149
+ : (treeUrl ?? existing?.url ?? eventUrl ?? ''),
150
+ children,
151
+ ...(typeof node.userContext === 'string'
152
+ ? { userContext: node.userContext }
153
+ : existing?.userContext === undefined
154
+ ? {}
155
+ : { userContext: existing.userContext }),
156
+ });
157
+ if (treeUrl !== undefined) {
158
+ this.#lastTreeUrl.set(node.context, treeUrl);
159
+ }
160
+ }
161
+ for (const context of [...this.#tabs.keys()]) {
162
+ if (!seen.has(context)) {
163
+ this.#tabs.delete(context);
164
+ this.#lastTreeUrl.delete(context);
165
+ this.#eventUrl.delete(context);
166
+ if (this.#selected === context) {
167
+ this.#selected = undefined;
168
+ }
169
+ }
170
+ }
171
+ }
172
+ #resolveSelectedId(tabs) {
173
+ if (this.#selected !== undefined && tabs.some((tab) => tab.context === this.#selected)) {
174
+ return this.#selected;
175
+ }
176
+ return tabs[0]?.context;
177
+ }
178
+ }
179
+ //# sourceMappingURL=context-manager.js.map
@@ -0,0 +1,31 @@
1
+ import type { Config, ConnectionRuntimeLike, DiscoveryCandidate, SessionManagerLike, SessionStatus } from '../types.js';
2
+ /**
3
+ * The mapper reports CDP-shaped capabilities: `browserName` is a product
4
+ * string ("Chrome/153.0.8010.53"), `browserVersion` is the CDP revision, and
5
+ * unused fields are empty strings. Normalize to the BiDi shape tools expect.
6
+ */
7
+ export declare function normalizeChromiumCapabilities(capabilities: Record<string, unknown>): Record<string, unknown>;
8
+ export interface SessionManagerOptions {
9
+ readonly config: Config;
10
+ readonly serverVersion: string;
11
+ }
12
+ /**
13
+ * Owns the single BiDi session for this MCP server process.
14
+ * It never relaunches, mutates, or closes the user's browser.
15
+ */
16
+ export declare class SessionManager implements SessionManagerLike {
17
+ #private;
18
+ /** Live-session services (events, contexts); undefined when disconnected. */
19
+ get runtime(): ConnectionRuntimeLike | undefined;
20
+ constructor(options: SessionManagerOptions);
21
+ connect(): Promise<SessionStatus>;
22
+ disconnect(): Promise<void>;
23
+ status(): Promise<SessionStatus>;
24
+ /** Send a BiDi command on the live session. */
25
+ request(method: string, params?: Record<string, unknown>): Promise<Record<string, unknown>>;
26
+ profiles(): Promise<readonly DiscoveryCandidate[]>;
27
+ version(): Promise<{
28
+ serverVersion: string;
29
+ browserVersion?: string;
30
+ }>;
31
+ }