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
@@ -9,187 +9,196 @@ import { ActionableError } from '../utils/errors.js';
9
9
  * serialization overhead. Frames: same-origin iframes and open shadow roots
10
10
  * are traversed; each element records its frame chain / shadow host.
11
11
  */
12
- const SNAPSHOT_SCRIPT = String.raw `
13
- (() => {
14
- const MAX_NAME = 120;
15
- const MAX_TEXT = 30000;
16
- const MAX_ELEMENTS = 5000;
17
- let dropped = 0;
18
-
19
- function esc(value) {
20
- return String(value == null ? '' : value);
21
- }
22
-
23
- function collapse(text) {
24
- return text.replace(/\s+/g, ' ').trim();
25
- }
26
-
27
- function roleOf(el) {
28
- const explicit = el.getAttribute('role');
29
- if (explicit) return explicit;
30
- const tag = el.tagName.toLowerCase();
31
- if (tag === 'a') return 'link';
32
- if (tag === 'button' || tag === 'summary') return 'button';
33
- if (tag === 'select') return 'combobox';
34
- if (tag === 'option') return 'option';
35
- if (tag === 'textarea') return 'textbox';
36
- if (tag === 'label') return 'label';
37
- if (tag === 'img') return 'img';
38
- if (tag === 'progress') return 'progressbar';
39
- if (tag === 'meter') return 'meter';
40
- if (/^h[1-6]$/.test(tag)) return 'heading';
41
- if (tag === 'input') {
42
- const type = (el.getAttribute('type') || 'text').toLowerCase();
43
- if (type === 'checkbox') return 'checkbox';
44
- if (type === 'radio') return 'radio';
45
- if (type === 'range') return 'slider';
46
- if (type === 'file') return 'fileinput';
47
- if (type === 'submit' || type === 'button' || type === 'reset') return 'button';
48
- if (type === 'image') return 'button';
49
- return 'textbox';
50
- }
51
- if (el.isContentEditable) return 'textbox';
52
- return tag;
53
- }
54
-
55
- function nameOf(el, role) {
56
- const label = el.getAttribute('aria-label');
57
- if (label && collapse(label)) return collapse(label).slice(0, MAX_NAME);
58
- const tag = el.tagName.toLowerCase();
59
- if (role === 'textbox' || role === 'combobox' || role === 'fileinput' || role === 'slider') {
60
- // Never read a live field value: it can hold a password, a session token,
61
- // or PII, and the snapshot travels into agent context and client logs.
62
- // Only static attributes are exposed.
63
- return collapse(
64
- el.getAttribute('placeholder') || el.getAttribute('name') || el.getAttribute('title') || ''
65
- ).slice(0, MAX_NAME);
66
- }
67
- if (role === 'img') return collapse(el.getAttribute('alt') || el.getAttribute('title') || '').slice(0, MAX_NAME);
68
- if (role === 'heading') return collapse(el.textContent || '').slice(0, MAX_NAME);
69
- const text = collapse(el.textContent || '');
70
- if (text) return text.slice(0, MAX_NAME);
71
- return collapse(el.getAttribute('title') || el.getAttribute('name') || '').slice(0, MAX_NAME);
72
- }
73
-
74
- function cssPath(el, doc) {
75
- if (el.id) {
76
- try { if (doc.getElementById(el.id) === el) return '#' + CSS.escape(el.id); } catch (e) {}
77
- }
78
- const parts = [];
79
- let node = el;
80
- while (node && node.nodeType === 1) {
81
- let segment = node.tagName.toLowerCase();
82
- if (node.id) {
83
- try {
84
- if (doc.getElementById(node.id) === node) {
85
- parts.unshift('#' + CSS.escape(node.id));
86
- break;
87
- }
88
- } catch (e) {}
89
- }
90
- const parent = node.parentElement;
91
- if (parent) {
92
- const sameTag = Array.prototype.filter.call(parent.children, (c) => c.tagName === node.tagName);
93
- if (sameTag.length > 1) segment += ':nth-of-type(' + (sameTag.indexOf(node) + 1) + ')';
94
- parts.unshift(segment);
95
- node = parent;
96
- } else {
97
- parts.unshift(segment);
98
- break;
99
- }
100
- }
101
- return parts.join(' > ');
102
- }
103
-
104
- function interesting(el) {
105
- const tag = el.tagName.toLowerCase();
106
- if (tag === 'script' || tag === 'style' || tag === 'noscript' || tag === 'template' || tag === 'head' || tag === 'meta' || tag === 'link') return false;
107
- if (tag === 'a' || tag === 'button' || tag === 'select' || tag === 'textarea' || tag === 'label' || tag === 'img' || tag === 'summary' || tag === 'option' || tag === 'input' || tag === 'progress' || tag === 'meter') return true;
108
- if (/^h[1-6]$/.test(tag)) return true;
109
- if (el.hasAttribute('role') || el.hasAttribute('onclick') || el.hasAttribute('tabindex')) return true;
110
- if (el.isContentEditable) return true;
111
- return false;
112
- }
113
-
114
- function statesOf(el, doc) {
115
- const states = {};
116
- if (el.disabled || el.getAttribute('aria-disabled') === 'true') states.disabled = true;
117
- if (doc.activeElement === el) states.focused = true;
118
- if (el.tagName.toLowerCase() === 'input') {
119
- const type = (el.getAttribute('type') || '').toLowerCase();
120
- if (type === 'checkbox' || type === 'radio') states.checked = el.checked;
121
- if (type === 'password') states.masked = true;
122
- }
123
- const expanded = el.getAttribute('aria-expanded');
124
- if (expanded === 'true' || expanded === 'false') states.expanded = expanded === 'true';
125
- if (el.required || el.getAttribute('aria-required') === 'true') states.required = true;
126
- if (el.readOnly) states.readonly = true;
127
- if (/^h[1-6]$/.test(el.tagName.toLowerCase())) states.level = Number(el.tagName.slice(1));
128
- return states;
129
- }
130
-
131
- function visible(el) {
132
- const rect = el.getBoundingClientRect();
133
- if (rect.width === 0 && rect.height === 0) return false;
134
- return true;
135
- }
136
-
137
- function collectFrom(root, doc, out, frameChain, shadowHost) {
138
- const all = root.querySelectorAll('*');
139
- for (const el of all) {
140
- // Shadow hosts may be plain divs, so recurse before the filter.
141
- if (el.shadowRoot) {
142
- collectFrom(el.shadowRoot, doc, out, frameChain, cssPath(el, doc));
143
- }
144
- if (!interesting(el) || !visible(el)) continue;
145
- if (out.length >= MAX_ELEMENTS) {
146
- dropped += 1;
147
- continue;
148
- }
149
- const role = roleOf(el);
150
- const rect = el.getBoundingClientRect();
151
- const states = statesOf(el, doc);
152
- const info = {
153
- role: role,
154
- name: nameOf(el, role),
155
- tag: el.tagName.toLowerCase(),
156
- bounds: [Math.round(rect.x), Math.round(rect.y), Math.round(rect.width), Math.round(rect.height)],
157
- selector: cssPath(el, doc),
158
- };
159
- if (frameChain.length > 0) info.frame = frameChain;
160
- if (shadowHost !== null) info.shadowHost = shadowHost;
161
- if (Object.keys(states).length > 0) info.states = states;
162
- out.push(info);
163
- }
164
- }
165
-
166
- function walkFrames(doc, out, texts, frameChain) {
167
- collectFrom(doc.body || doc.documentElement, doc, out, frameChain, null);
168
- const frames = doc.querySelectorAll('iframe');
169
- for (const frame of frames) {
170
- try {
171
- const inner = frame.contentDocument;
172
- if (inner && inner.body) {
173
- texts.push(inner.body.innerText);
174
- collectFrom(inner.body, inner, out, frameChain.concat(cssPath(frame, doc)), null);
175
- }
176
- } catch (e) {}
177
- }
178
- }
179
-
180
- const doc = document;
181
- const elements = [];
182
- const texts = [];
183
- if (doc.body) texts.push(doc.body.innerText);
184
- walkFrames(doc, elements, texts, []);
185
-
186
- return JSON.stringify({
187
- title: doc.title || '',
188
- url: String(doc.location ? doc.location.href : ''),
189
- text: texts.join('\n\n--- frame ---\n\n').slice(0, MAX_TEXT),
190
- elements: elements,
191
- droppedElements: dropped,
192
- });
12
+ const SNAPSHOT_SCRIPT = String.raw `
13
+ (() => {
14
+ const MAX_NAME = 120;
15
+ const MAX_TEXT = 30000;
16
+ const MAX_ELEMENTS = 5000;
17
+ let dropped = 0;
18
+
19
+ function esc(value) {
20
+ return String(value == null ? '' : value);
21
+ }
22
+
23
+ function collapse(text) {
24
+ return text.replace(/\s+/g, ' ').trim();
25
+ }
26
+
27
+ function roleOf(el) {
28
+ const explicit = el.getAttribute('role');
29
+ if (explicit) return explicit;
30
+ const tag = el.tagName.toLowerCase();
31
+ if (tag === 'a') return 'link';
32
+ if (tag === 'button' || tag === 'summary') return 'button';
33
+ if (tag === 'select') return 'combobox';
34
+ if (tag === 'option') return 'option';
35
+ if (tag === 'textarea') return 'textbox';
36
+ if (tag === 'label') return 'label';
37
+ if (tag === 'img') return 'img';
38
+ if (tag === 'progress') return 'progressbar';
39
+ if (tag === 'meter') return 'meter';
40
+ if (/^h[1-6]$/.test(tag)) return 'heading';
41
+ if (tag === 'input') {
42
+ const type = (el.getAttribute('type') || 'text').toLowerCase();
43
+ if (type === 'checkbox') return 'checkbox';
44
+ if (type === 'radio') return 'radio';
45
+ if (type === 'range') return 'slider';
46
+ if (type === 'file') return 'fileinput';
47
+ if (type === 'submit' || type === 'button' || type === 'reset') return 'button';
48
+ if (type === 'image') return 'button';
49
+ return 'textbox';
50
+ }
51
+ if (el.isContentEditable) return 'textbox';
52
+ return tag;
53
+ }
54
+
55
+ function nameOf(el, role) {
56
+ const label = el.getAttribute('aria-label');
57
+ if (label && collapse(label)) return collapse(label).slice(0, MAX_NAME);
58
+ const tag = el.tagName.toLowerCase();
59
+ if (role === 'textbox' || role === 'combobox' || role === 'fileinput' || role === 'slider') {
60
+ // Never read a live field value: it can hold a password, a session token,
61
+ // or PII, and the snapshot travels into agent context and client logs.
62
+ // Only static attributes are exposed.
63
+ return collapse(
64
+ el.getAttribute('placeholder') || el.getAttribute('name') || el.getAttribute('title') || ''
65
+ ).slice(0, MAX_NAME);
66
+ }
67
+ if (role === 'img') return collapse(el.getAttribute('alt') || el.getAttribute('title') || '').slice(0, MAX_NAME);
68
+ if (role === 'heading') return collapse(el.textContent || '').slice(0, MAX_NAME);
69
+ const text = collapse(el.textContent || '');
70
+ if (text) return text.slice(0, MAX_NAME);
71
+ return collapse(el.getAttribute('title') || el.getAttribute('name') || '').slice(0, MAX_NAME);
72
+ }
73
+
74
+ function cssPath(el, doc) {
75
+ if (el.id) {
76
+ try { if (doc.getElementById(el.id) === el) return '#' + CSS.escape(el.id); } catch (e) {}
77
+ }
78
+ const parts = [];
79
+ let node = el;
80
+ while (node && node.nodeType === 1) {
81
+ let segment = node.tagName.toLowerCase();
82
+ if (node.id) {
83
+ try {
84
+ if (doc.getElementById(node.id) === node) {
85
+ parts.unshift('#' + CSS.escape(node.id));
86
+ break;
87
+ }
88
+ } catch (e) {}
89
+ }
90
+ const parent = node.parentElement;
91
+ if (parent) {
92
+ const sameTag = Array.prototype.filter.call(parent.children, (c) => c.tagName === node.tagName);
93
+ if (sameTag.length > 1) segment += ':nth-of-type(' + (sameTag.indexOf(node) + 1) + ')';
94
+ parts.unshift(segment);
95
+ node = parent;
96
+ } else {
97
+ parts.unshift(segment);
98
+ break;
99
+ }
100
+ }
101
+ return parts.join(' > ');
102
+ }
103
+
104
+ function interesting(el) {
105
+ const tag = el.tagName.toLowerCase();
106
+ if (tag === 'script' || tag === 'style' || tag === 'noscript' || tag === 'template' || tag === 'head' || tag === 'meta' || tag === 'link') return false;
107
+ if (tag === 'a' || tag === 'button' || tag === 'select' || tag === 'textarea' || tag === 'label' || tag === 'img' || tag === 'summary' || tag === 'option' || tag === 'input' || tag === 'progress' || tag === 'meter') return true;
108
+ if (/^h[1-6]$/.test(tag)) return true;
109
+ if (el.hasAttribute('role') || el.hasAttribute('onclick') || el.hasAttribute('tabindex')) return true;
110
+ if (el.isContentEditable) return true;
111
+ return false;
112
+ }
113
+
114
+ function statesOf(el, doc) {
115
+ const states = {};
116
+ if (el.disabled || el.getAttribute('aria-disabled') === 'true') states.disabled = true;
117
+ if (doc.activeElement === el) states.focused = true;
118
+ if (el.tagName.toLowerCase() === 'input') {
119
+ const type = (el.getAttribute('type') || '').toLowerCase();
120
+ if (type === 'checkbox' || type === 'radio') states.checked = el.checked;
121
+ if (type === 'password') states.masked = true;
122
+ }
123
+ const expanded = el.getAttribute('aria-expanded');
124
+ if (expanded === 'true' || expanded === 'false') states.expanded = expanded === 'true';
125
+ if (el.required || el.getAttribute('aria-required') === 'true') states.required = true;
126
+ if (el.readOnly) states.readonly = true;
127
+ if (/^h[1-6]$/.test(el.tagName.toLowerCase())) states.level = Number(el.tagName.slice(1));
128
+ return states;
129
+ }
130
+
131
+ function visible(el) {
132
+ const rect = el.getBoundingClientRect();
133
+ if (rect.width === 0 && rect.height === 0) return false;
134
+ return true;
135
+ }
136
+
137
+ function collectFrom(root, doc, out, frameChain, shadowHost) {
138
+ const all = root.querySelectorAll('*');
139
+ for (const el of all) {
140
+ // Shadow hosts may be plain divs, so recurse before the filter.
141
+ if (el.shadowRoot) {
142
+ collectFrom(el.shadowRoot, doc, out, frameChain, cssPath(el, doc));
143
+ }
144
+ if (!interesting(el) || !visible(el)) continue;
145
+ if (out.length >= MAX_ELEMENTS) {
146
+ dropped += 1;
147
+ continue;
148
+ }
149
+ const role = roleOf(el);
150
+ const rect = el.getBoundingClientRect();
151
+ const states = statesOf(el, doc);
152
+ // Document-space coordinates: the traversal and uid verification (plan
153
+ // §3) both add the frame's scroll offsets, so scrolling never makes a
154
+ // uid look stale.
155
+ const view = doc.defaultView;
156
+ const info = {
157
+ role: role,
158
+ name: nameOf(el, role),
159
+ tag: el.tagName.toLowerCase(),
160
+ bounds: [
161
+ Math.round(rect.x + (view ? view.pageXOffset || 0 : 0)),
162
+ Math.round(rect.y + (view ? view.pageYOffset || 0 : 0)),
163
+ Math.round(rect.width),
164
+ Math.round(rect.height),
165
+ ],
166
+ selector: cssPath(el, doc),
167
+ };
168
+ if (frameChain.length > 0) info.frame = frameChain;
169
+ if (shadowHost !== null) info.shadowHost = shadowHost;
170
+ if (Object.keys(states).length > 0) info.states = states;
171
+ out.push(info);
172
+ }
173
+ }
174
+
175
+ function walkFrames(doc, out, texts, frameChain) {
176
+ collectFrom(doc.body || doc.documentElement, doc, out, frameChain, null);
177
+ const frames = doc.querySelectorAll('iframe');
178
+ for (const frame of frames) {
179
+ try {
180
+ const inner = frame.contentDocument;
181
+ if (inner && inner.body) {
182
+ texts.push(inner.body.innerText);
183
+ collectFrom(inner.body, inner, out, frameChain.concat(cssPath(frame, doc)), null);
184
+ }
185
+ } catch (e) {}
186
+ }
187
+ }
188
+
189
+ const doc = document;
190
+ const elements = [];
191
+ const texts = [];
192
+ if (doc.body) texts.push(doc.body.innerText);
193
+ walkFrames(doc, elements, texts, []);
194
+
195
+ return JSON.stringify({
196
+ title: doc.title || '',
197
+ url: String(doc.location ? doc.location.href : ''),
198
+ text: texts.join('\n\n--- frame ---\n\n').slice(0, MAX_TEXT),
199
+ elements: elements,
200
+ droppedElements: dropped,
201
+ });
193
202
  })()`;
194
203
  /** Assign uids and validate the raw traversal output. Pure. */
195
204
  export function parseSnapshotResult(context, raw) {
@@ -0,0 +1,23 @@
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 interface ElementPlan {
19
+ readonly frame?: readonly string[];
20
+ readonly shadowHost?: string;
21
+ readonly selector: string;
22
+ }
23
+ export declare function elementScriptSource(plan: ElementPlan, body: string, extraArgs?: Record<string, unknown>): string;
@@ -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 {};