bidi-browser-mcp 0.1.10 → 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 (42) hide show
  1. package/README.md +64 -9
  2. package/dist/bin.js +3 -2
  3. package/dist/config.js +4 -0
  4. package/dist/connection/bidi-client.d.ts +13 -1
  5. package/dist/connection/bidi-client.js +59 -8
  6. package/dist/connection/browser-discovery.d.ts +20 -0
  7. package/dist/connection/browser-discovery.js +76 -12
  8. package/dist/connection/chromium-mapper.d.ts +9 -0
  9. package/dist/connection/chromium-mapper.js +24 -0
  10. package/dist/connection/event-pipeline.d.ts +15 -2
  11. package/dist/connection/event-pipeline.js +45 -3
  12. package/dist/connection/protocol-probe.d.ts +43 -0
  13. package/dist/connection/protocol-probe.js +112 -0
  14. package/dist/index.js +6 -0
  15. package/dist/session/session-manager.d.ts +26 -1
  16. package/dist/session/session-manager.js +262 -6
  17. package/dist/snapshot/cache.d.ts +4 -0
  18. package/dist/snapshot/cache.js +8 -0
  19. package/dist/snapshot/dom-snapshot.js +10 -1
  20. package/dist/snapshot/element-script.d.ts +23 -0
  21. package/dist/snapshot/element-script.js +70 -0
  22. package/dist/snapshot/token-optimizer.js +26 -8
  23. package/dist/snapshot/uid-verify.d.ts +43 -0
  24. package/dist/snapshot/uid-verify.js +154 -0
  25. package/dist/tools/browser.js +21 -6
  26. package/dist/tools/context.js +4 -6
  27. package/dist/tools/interact.d.ts +1 -0
  28. package/dist/tools/interact.js +593 -0
  29. package/dist/tools/network.d.ts +1 -0
  30. package/dist/tools/network.js +166 -0
  31. package/dist/tools/page.js +53 -2
  32. package/dist/tools/ping.js +5 -1
  33. package/dist/tools/script.d.ts +1 -0
  34. package/dist/tools/script.js +166 -0
  35. package/dist/types.d.ts +50 -1
  36. package/dist/utils/bidi-value.d.ts +10 -0
  37. package/dist/utils/bidi-value.js +56 -0
  38. package/dist/utils/errors.d.ts +3 -1
  39. package/dist/utils/errors.js +13 -7
  40. package/dist/utils/redact.d.ts +16 -0
  41. package/dist/utils/redact.js +47 -0
  42. package/package.json +1 -1
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Build the script source that runs a body against the element a resolution
3
+ * plan describes (interact dispatch, 0.2.0 decisions §4/§5).
4
+ *
5
+ * The plan is embedded as JSON, so page strings can never break the source.
6
+ * The body is called as `body(element, args, document)` inside the element's
7
+ * own document and the wrapper always returns:
8
+ * - `rect`: viewport-space `[x, y, width, height]` of that document — the
9
+ * same space `elementFromPoint` and `input.performActions` use;
10
+ * - `value`: the body's return value;
11
+ * - `element`: the element reference when the body returned the node itself
12
+ * (upload needs it for `input.setFiles`);
13
+ * - `error`: a resolution failure (frame/shadow/selector), else null.
14
+ *
15
+ * `value` is the only field that can carry page data, and callers treat it as
16
+ * untrusted content.
17
+ */
18
+ export function elementScriptSource(plan, body, extraArgs) {
19
+ const planJson = JSON.stringify({
20
+ frame: plan.frame ?? null,
21
+ shadowHost: plan.shadowHost ?? null,
22
+ selector: plan.selector,
23
+ });
24
+ // Arguments travel as one plain object; bodies read named fields instead of
25
+ // relying on positional bookkeeping or string interpolation.
26
+ const argsJson = JSON.stringify(extraArgs ?? {});
27
+ return `(function runOnElement (args) {
28
+ args = ${argsJson};
29
+ var plan = ${planJson};
30
+ var out = { value: null, rect: null, element: null, error: null };
31
+ try {
32
+ var doc = document;
33
+ var frames = plan.frame || [];
34
+ for (var i = 0; i < frames.length; i++) {
35
+ var frame = doc.querySelector(frames[i]);
36
+ var inner = frame ? frame.contentDocument : null;
37
+ if (!inner || !inner.documentElement) { out.error = 'frame unavailable'; return out; }
38
+ doc = inner;
39
+ }
40
+ var scope = doc;
41
+ if (plan.shadowHost !== null) {
42
+ var host = doc.querySelector(plan.shadowHost);
43
+ var root = host ? host.shadowRoot : null;
44
+ if (!root) { out.error = 'shadow root unavailable'; return out; }
45
+ scope = root;
46
+ }
47
+ var matches = scope.querySelectorAll(plan.selector);
48
+ if (matches.length !== 1) {
49
+ out.error = matches.length === 0 ? 'no such element' : 'ambiguous selector';
50
+ return out;
51
+ }
52
+ var el = matches[0];
53
+ var r = el.getBoundingClientRect();
54
+ out.rect = [r.x, r.y, r.width, r.height];
55
+ var result = (${body})(el, args, doc);
56
+ if (result && result.nodeType === 1) {
57
+ // The node goes to 'element' alone: serializing it twice makes the
58
+ // second occurrence a by-reference stub (Chromium dedupes), which
59
+ // input.setFiles cannot use.
60
+ out.element = result;
61
+ } else {
62
+ out.value = result === undefined ? null : result;
63
+ }
64
+ } catch (e) {
65
+ out.error = String(e && e.message ? e.message : e);
66
+ }
67
+ return out;
68
+ })`;
69
+ }
70
+ //# sourceMappingURL=element-script.js.map
@@ -77,21 +77,39 @@ export function fitToBudget(snapshot, budget, options = {}) {
77
77
  fittedElements = fit.elements;
78
78
  truncatedElements = fit.meta.truncated;
79
79
  }
80
- // Whatever is left after url, title, and elements belongs to the text.
81
- const remaining = budget - payloadChars(fittedElements);
82
- let text = snapshot.text;
80
+ // Whatever is left after url, title, elements, and the `text` key costs
81
+ // belongs to the text. The budget is measured on the JSON encoding —
82
+ // escaped characters (quotes, newlines, non-ASCII) cost more than raw
83
+ // characters, so a raw slice overshoots the declared budget.
84
+ const textKeyCost = chars('"text":');
85
+ const remaining = budget - payloadChars(fittedElements) - 1 - textKeyCost;
86
+ const text = snapshot.text;
87
+ let keptText = text;
83
88
  let omittedTextChars = 0;
84
89
  if (chars(text) > remaining) {
85
- // Two characters for the JSON quotes around the string.
86
- const largest = Math.max(0, remaining - 2);
87
- text = text.slice(0, largest);
88
- omittedTextChars = snapshot.text.length - text.length;
90
+ const quotedLength = (value) => JSON.stringify(value).length;
91
+ // Binary-search the largest raw prefix whose JSON encoding fits.
92
+ let low = 0;
93
+ let high = text.length;
94
+ let best = 0;
95
+ while (low <= high) {
96
+ const mid = Math.floor((low + high) / 2);
97
+ if (quotedLength(text.slice(0, mid)) <= remaining) {
98
+ best = mid;
99
+ low = mid + 1;
100
+ }
101
+ else {
102
+ high = mid - 1;
103
+ }
104
+ }
105
+ keptText = text.slice(0, best);
106
+ omittedTextChars = text.length - best;
89
107
  }
90
108
  return {
91
109
  url: snapshot.url,
92
110
  title: snapshot.title,
93
111
  elements: fittedElements,
94
- ...(text.length > 0 ? { text } : {}),
112
+ ...(keptText.length > 0 ? { text: keptText } : {}),
95
113
  meta: {
96
114
  truncated: truncatedElements || omittedTextChars > 0 || droppedByCap > 0,
97
115
  originalChars: original,
@@ -0,0 +1,43 @@
1
+ import type { ElementInfo, PageSnapshot } from '../types.js';
2
+ /** Same request shape the snapshot builders use. */
3
+ type BiDiRequest = (method: string, params?: Record<string, unknown>) => Promise<Record<string, unknown>>;
4
+ export interface VerifyProbe {
5
+ readonly found: boolean;
6
+ readonly tag: string | null;
7
+ readonly rect: readonly [number, number, number, number] | null;
8
+ readonly matches: number;
9
+ readonly reason: string | null;
10
+ }
11
+ export type VerifyVerdict = 'ok' | 'missing' | 'ambiguous' | 'stale';
12
+ /**
13
+ * Compare a probe result with the snapshot entry.
14
+ * Precedence (§3): nothing resolved → missing; selector ambiguous → ambiguous;
15
+ * resolved but no longer the same element → stale.
16
+ */
17
+ export declare function compareElement(probe: VerifyProbe, element: ElementInfo): VerifyVerdict;
18
+ /**
19
+ * The verify function: resolve the recorded plan (iframe chain → shadow root →
20
+ * selector) and report what is there now, in document-space coordinates.
21
+ * The plan is embedded as JSON, so page strings cannot break the source.
22
+ */
23
+ export declare function verifyFunctionSource(plan: {
24
+ readonly frame?: readonly string[];
25
+ readonly shadowHost?: string;
26
+ readonly selector: string;
27
+ }): string;
28
+ /** Parse a `script.callFunction` result into a probe; bad shapes probe absent. */
29
+ export declare function parseVerifyProbe(raw: unknown): VerifyProbe;
30
+ /**
31
+ * Re-resolve one snapshot uid in the live page. Resolves silently when the
32
+ * element still matches; otherwise throws ELEMENT_NOT_FOUND / STALE_UID
33
+ * with the precedence from plan decisions §3. Wave 1 actions call this
34
+ * before dispatching BiDi input commands.
35
+ */
36
+ export declare function verifySnapshotElement(request: BiDiRequest, snapshot: PageSnapshot, uid: string): Promise<void>;
37
+ /**
38
+ * Verify one known element reference (the plan cache path) against the live
39
+ * page. Same verdicts and precedence as verifySnapshotElement (§3): the plan
40
+ * is only a resolution hint, verification is the safety.
41
+ */
42
+ export declare function verifyElementRef(request: BiDiRequest, element: ElementInfo, context: string, uid: string): Promise<void>;
43
+ export {};
@@ -0,0 +1,154 @@
1
+ import { ActionableError } from '../utils/errors.js';
2
+ import { unwrapBiDiValue } from '../utils/bidi-value.js';
3
+ import { resolveElement, resolvePlan } from './element-resolver.js';
4
+ /**
5
+ * Document-space rects may drift before an action runs; the size keeps its
6
+ * meaning across scrolls, DOM shifts, and reflow (plan decisions §3).
7
+ */
8
+ const SIZE_TOLERANCE = 4;
9
+ /**
10
+ * Compare a probe result with the snapshot entry.
11
+ * Precedence (§3): nothing resolved → missing; selector ambiguous → ambiguous;
12
+ * resolved but no longer the same element → stale.
13
+ */
14
+ export function compareElement(probe, element) {
15
+ if (!probe.found) {
16
+ return 'missing';
17
+ }
18
+ if (probe.matches !== 1) {
19
+ return 'ambiguous';
20
+ }
21
+ if (probe.tag === null || probe.tag !== element.tag) {
22
+ return 'stale';
23
+ }
24
+ if (probe.rect === null) {
25
+ return 'stale';
26
+ }
27
+ return (Math.abs(probe.rect[2] - (element.bounds[2] ?? 0)) <= SIZE_TOLERANCE &&
28
+ Math.abs(probe.rect[3] - (element.bounds[3] ?? 0)) <= SIZE_TOLERANCE
29
+ ? 'ok'
30
+ : 'stale');
31
+ }
32
+ /**
33
+ * The verify function: resolve the recorded plan (iframe chain → shadow root →
34
+ * selector) and report what is there now, in document-space coordinates.
35
+ * The plan is embedded as JSON, so page strings cannot break the source.
36
+ */
37
+ export function verifyFunctionSource(plan) {
38
+ const planJson = JSON.stringify({
39
+ frame: plan.frame ?? null,
40
+ shadowHost: plan.shadowHost ?? null,
41
+ selector: plan.selector,
42
+ });
43
+ return `(function verifyUid () {
44
+ var plan = ${planJson};
45
+ var out = { found: false, tag: null, rect: null, matches: 0, reason: null };
46
+ try {
47
+ var doc = document;
48
+ var frames = plan.frame || [];
49
+ for (var i = 0; i < frames.length; i++) {
50
+ var frame = doc.querySelector(frames[i]);
51
+ var inner = frame ? frame.contentDocument : null;
52
+ if (!inner || !inner.documentElement) { out.reason = 'frame unavailable'; return out; }
53
+ doc = inner;
54
+ }
55
+ var scope = doc;
56
+ if (plan.shadowHost !== null) {
57
+ var host = doc.querySelector(plan.shadowHost);
58
+ var root = host ? host.shadowRoot : null;
59
+ if (!root) { out.reason = 'shadow root unavailable'; return out; }
60
+ scope = root;
61
+ }
62
+ var matches = scope.querySelectorAll(plan.selector);
63
+ out.matches = matches.length;
64
+ var el = matches[0];
65
+ if (!el) return out;
66
+ var rect = el.getBoundingClientRect();
67
+ var view = doc.defaultView;
68
+ out.found = true;
69
+ out.tag = el.tagName.toLowerCase();
70
+ out.rect = [
71
+ rect.x + (view ? view.pageXOffset || 0 : 0),
72
+ rect.y + (view ? view.pageYOffset || 0 : 0),
73
+ rect.width,
74
+ rect.height
75
+ ];
76
+ } catch (e) {
77
+ out.reason = String(e && e.message ? e.message : e);
78
+ }
79
+ return out;
80
+ })`;
81
+ }
82
+ /** Parse a `script.callFunction` result into a probe; bad shapes probe absent. */
83
+ export function parseVerifyProbe(raw) {
84
+ const value = unwrapBiDiValue(raw);
85
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
86
+ return { found: false, tag: null, rect: null, matches: 0, reason: 'unparsable result' };
87
+ }
88
+ const record = value;
89
+ const rect = record.rect;
90
+ return {
91
+ found: record.found === true,
92
+ tag: typeof record.tag === 'string' ? record.tag : null,
93
+ rect: Array.isArray(rect) &&
94
+ rect.length === 4 &&
95
+ rect.every((entry) => typeof entry === 'number')
96
+ ? [rect[0], rect[1], rect[2], rect[3]]
97
+ : null,
98
+ matches: typeof record.matches === 'number' ? record.matches : 0,
99
+ reason: typeof record.reason === 'string' ? record.reason : null,
100
+ };
101
+ }
102
+ function verdictError(verdict, element, probe, probeReason) {
103
+ const fix = 'Take a fresh page.snapshot and retry with the new uid.';
104
+ const details = {
105
+ uid: element.uid,
106
+ selector: element.selector,
107
+ ...(probeReason === null ? {} : { probeReason }),
108
+ };
109
+ switch (verdict) {
110
+ case 'missing':
111
+ return new ActionableError('ELEMENT_NOT_FOUND', `Element ${element.uid} no longer exists: its selector resolves to nothing.`, { fix, details });
112
+ case 'ambiguous':
113
+ return new ActionableError('STALE_UID', `Element ${element.uid} is stale: its selector now matches ${probe.matches} elements.`, { fix, details });
114
+ default:
115
+ return new ActionableError('STALE_UID', `Element ${element.uid} no longer matches its snapshot identity (tag or size changed).`, { fix, details });
116
+ }
117
+ }
118
+ /**
119
+ * Re-resolve one snapshot uid in the live page. Resolves silently when the
120
+ * element still matches; otherwise throws ELEMENT_NOT_FOUND / STALE_UID
121
+ * with the precedence from plan decisions §3. Wave 1 actions call this
122
+ * before dispatching BiDi input commands.
123
+ */
124
+ export async function verifySnapshotElement(request, snapshot, uid) {
125
+ await verifyElementRef(request, resolveElement(snapshot, uid), snapshot.context, uid);
126
+ }
127
+ /**
128
+ * Verify one known element reference (the plan cache path) against the live
129
+ * page. Same verdicts and precedence as verifySnapshotElement (§3): the plan
130
+ * is only a resolution hint, verification is the safety.
131
+ */
132
+ export async function verifyElementRef(request, element, context, uid) {
133
+ const plan = resolvePlan(element);
134
+ let result;
135
+ try {
136
+ result = await request('script.callFunction', {
137
+ functionDeclaration: verifyFunctionSource(plan),
138
+ target: { context },
139
+ awaitPromise: false,
140
+ });
141
+ }
142
+ catch (error) {
143
+ if (error instanceof ActionableError) {
144
+ throw error;
145
+ }
146
+ throw new ActionableError('SCRIPT_ERROR', 'Failed to run the uid verification script.', { cause: error, details: { context, uid } });
147
+ }
148
+ const probe = parseVerifyProbe(result.result !== undefined ? result.result : result);
149
+ const verdict = compareElement(probe, element);
150
+ if (verdict !== 'ok') {
151
+ throw verdictError(verdict, element, probe, probe.reason);
152
+ }
153
+ }
154
+ //# sourceMappingURL=uid-verify.js.map
@@ -1,5 +1,6 @@
1
1
  import { defineTool, requireAction } from './base-tool.js';
2
2
  import { ActionableError } from '../utils/errors.js';
3
+ import { redactProfilePath, redactStatusProfile } from '../utils/redact.js';
3
4
  import { ok } from '../utils/result.js';
4
5
  const ACTIONS = ['status', 'profiles', 'version', 'connect', 'disconnect'];
5
6
  const INPUT_SCHEMA = {
@@ -8,7 +9,11 @@ const INPUT_SCHEMA = {
8
9
  action: {
9
10
  type: 'string',
10
11
  enum: [...ACTIONS],
11
- description: 'status: connection state; profiles: discovery candidates; version: server + browser; connect: attach; disconnect: end session',
12
+ description: 'status: connection state; profiles: discovery candidates (id, family, port, protocol reachability, connectable verdict, reason when not); version: server + browser; connect: attach (optionally to a specific candidate); disconnect: end session',
13
+ },
14
+ target: {
15
+ type: 'string',
16
+ description: "connect: which browser to attach to — candidate id from browser.profiles ('f-9444', 'c-9222'), a port ('9444'), an exact ws endpoint, or a profile/user-data path (the redacted '~\\…' form works). Omit for ordered auto-connect. Switching ends the current session first (tabs stay open).",
12
17
  },
13
18
  },
14
19
  required: ['action'],
@@ -38,7 +43,7 @@ const OUTPUT_SCHEMA = {
38
43
  export const browserTool = defineTool({
39
44
  name: 'browser',
40
45
  title: 'Browser session',
41
- description: 'Inspect and control the single BiDi session. This never launches, closes, or mutates the user’s browser.',
46
+ description: 'Inspect and control the single BiDi session. This never launches, closes, or mutates the user’s browser. connect accepts a target (candidate id, port, endpoint, or profile path) to pick a specific browser — profiles lists every discovered browser with its id, family, port, whether it is reachable and connectable (BiDi handshake verdict; Chromium is never WS-probed by the listing because attaching may require the user to approve a debugging prompt), and the live one.',
42
47
  toolset: 'core',
43
48
  actions: ACTIONS,
44
49
  inputSchema: INPUT_SCHEMA,
@@ -57,13 +62,23 @@ export const browserTool = defineTool({
57
62
  }
58
63
  switch (action) {
59
64
  case 'status':
60
- return ok(action, await session.status());
65
+ return ok(action, redactStatusProfile(await session.status()));
61
66
  case 'profiles':
62
- return ok(action, { candidates: await session.profiles() });
67
+ return ok(action, {
68
+ // Profile paths embed the OS username; redact before the tool answer.
69
+ candidates: (await session.profiles()).map((candidate) => ({
70
+ ...candidate,
71
+ ...(candidate.profilePath === undefined
72
+ ? {}
73
+ : { profilePath: redactProfilePath(candidate.profilePath) }),
74
+ })),
75
+ });
63
76
  case 'version':
64
77
  return ok(action, await session.version());
65
- case 'connect':
66
- return ok(action, await session.connect());
78
+ case 'connect': {
79
+ const target = typeof args.target === 'string' ? args.target : undefined;
80
+ return ok(action, await session.connectTo(target));
81
+ }
67
82
  case 'disconnect':
68
83
  await session.disconnect();
69
84
  return ok(action, { connected: false });
@@ -133,12 +133,10 @@ export const contextTool = defineTool({
133
133
  return ok(action, { removed: userContext });
134
134
  }
135
135
  case 'tabs-in': {
136
- const userContext = typeof args.userContext === 'string' ? args.userContext : undefined;
137
- if (userContext === undefined || userContext === '') {
138
- throw new ActionableError('INVALID_ARGUMENT', 'context.tabs-in requires userContext.', {
139
- fix: 'Pass the id from context.list.',
140
- });
141
- }
136
+ // Tab-in-container queries usually mean the default container, so a
137
+ // missing id defaults there instead of failing (Wave 0 small fix).
138
+ const raw = typeof args.userContext === 'string' ? args.userContext.trim() : '';
139
+ const userContext = raw === '' ? 'default' : raw;
142
140
  const tree = await session.request('browsingContext.getTree', { maxDepth: 1 });
143
141
  const tabs = (tree.contexts ?? [])
144
142
  .filter((entry) => entry.userContext === userContext)
@@ -0,0 +1 @@
1
+ export declare const interactTool: import("../types.js").ToolDefinition;