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.
- package/LICENSE +21 -0
- package/README.md +343 -0
- package/dist/bin.d.ts +6 -0
- package/dist/bin.js +37 -0
- package/dist/config.d.ts +6 -0
- package/dist/config.js +122 -0
- package/dist/connection/bidi-client.d.ts +29 -0
- package/dist/connection/bidi-client.js +298 -0
- package/dist/connection/browser-discovery.d.ts +30 -0
- package/dist/connection/browser-discovery.js +393 -0
- package/dist/connection/chromium-mapper.d.ts +55 -0
- package/dist/connection/chromium-mapper.js +293 -0
- package/dist/connection/event-pipeline.d.ts +37 -0
- package/dist/connection/event-pipeline.js +167 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.js +66 -0
- package/dist/profile/profile-store.d.ts +88 -0
- package/dist/profile/profile-store.js +350 -0
- package/dist/session/context-manager.d.ts +17 -0
- package/dist/session/context-manager.js +179 -0
- package/dist/session/session-manager.d.ts +31 -0
- package/dist/session/session-manager.js +366 -0
- package/dist/snapshot/cache.d.ts +15 -0
- package/dist/snapshot/cache.js +37 -0
- package/dist/snapshot/dom-snapshot.d.ts +5 -0
- package/dist/snapshot/dom-snapshot.js +270 -0
- package/dist/snapshot/element-resolver.d.ts +13 -0
- package/dist/snapshot/element-resolver.js +25 -0
- package/dist/snapshot/token-optimizer.d.ts +16 -0
- package/dist/snapshot/token-optimizer.js +103 -0
- package/dist/tools/base-tool.d.ts +34 -0
- package/dist/tools/base-tool.js +55 -0
- package/dist/tools/browser.d.ts +1 -0
- package/dist/tools/browser.js +75 -0
- package/dist/tools/cleanup.d.ts +1 -0
- package/dist/tools/cleanup.js +64 -0
- package/dist/tools/console.d.ts +1 -0
- package/dist/tools/console.js +87 -0
- package/dist/tools/context.d.ts +1 -0
- package/dist/tools/context.js +156 -0
- package/dist/tools/observe.d.ts +1 -0
- package/dist/tools/observe.js +92 -0
- package/dist/tools/page.d.ts +1 -0
- package/dist/tools/page.js +139 -0
- package/dist/tools/ping.d.ts +1 -0
- package/dist/tools/ping.js +71 -0
- package/dist/tools/registry.d.ts +13 -0
- package/dist/tools/registry.js +47 -0
- package/dist/tools/spaces.d.ts +1 -0
- package/dist/tools/spaces.js +98 -0
- package/dist/tools/tabs.d.ts +1 -0
- package/dist/tools/tabs.js +155 -0
- package/dist/types.d.ts +277 -0
- package/dist/types.js +5 -0
- package/dist/utils/assert.d.ts +12 -0
- package/dist/utils/assert.js +74 -0
- package/dist/utils/errors.d.ts +24 -0
- package/dist/utils/errors.js +60 -0
- package/dist/utils/result.d.ts +14 -0
- package/dist/utils/result.js +37 -0
- package/package.json +86 -0
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
import { ActionableError } from '../utils/errors.js';
|
|
2
|
+
/**
|
|
3
|
+
* Firefox has no accessibility tree in BiDi, so the snapshot is built by a
|
|
4
|
+
* DOM traversal script: interactive/form nodes with computed role, name,
|
|
5
|
+
* bounds, states, and a CSS resolution path (selector-first; the sharedId
|
|
6
|
+
* route stays open for the interaction wave).
|
|
7
|
+
*
|
|
8
|
+
* The script returns ONE JSON string to avoid per-node RemoteValue
|
|
9
|
+
* serialization overhead. Frames: same-origin iframes and open shadow roots
|
|
10
|
+
* are traversed; each element records its frame chain / shadow host.
|
|
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
|
+
});
|
|
193
|
+
})()`;
|
|
194
|
+
/** Assign uids and validate the raw traversal output. Pure. */
|
|
195
|
+
export function parseSnapshotResult(context, raw) {
|
|
196
|
+
if (typeof raw !== 'string' || raw === '') {
|
|
197
|
+
throw new ActionableError('SCRIPT_ERROR', 'The snapshot script returned no data.', {
|
|
198
|
+
fix: 'Retry with a normal web page open in the tab.',
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
let parsed;
|
|
202
|
+
try {
|
|
203
|
+
parsed = JSON.parse(raw);
|
|
204
|
+
}
|
|
205
|
+
catch {
|
|
206
|
+
throw new ActionableError('SCRIPT_ERROR', 'The snapshot script returned malformed JSON.');
|
|
207
|
+
}
|
|
208
|
+
if (!Array.isArray(parsed.elements)) {
|
|
209
|
+
throw new ActionableError('SCRIPT_ERROR', 'The snapshot script returned no element list.');
|
|
210
|
+
}
|
|
211
|
+
const elements = [];
|
|
212
|
+
parsed.elements.forEach((entry, index) => {
|
|
213
|
+
if (entry === null || typeof entry !== 'object') {
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
const el = entry;
|
|
217
|
+
if (typeof el.role !== 'string' || typeof el.selector !== 'string') {
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
const bounds = Array.isArray(el.bounds)
|
|
221
|
+
? el.bounds.slice(0, 4)
|
|
222
|
+
: [0, 0, 0, 0];
|
|
223
|
+
elements.push({
|
|
224
|
+
uid: `e${index + 1}`,
|
|
225
|
+
role: el.role,
|
|
226
|
+
name: typeof el.name === 'string' ? el.name : '',
|
|
227
|
+
tag: typeof el.tag === 'string' ? el.tag : 'unknown',
|
|
228
|
+
bounds: [bounds[0] ?? 0, bounds[1] ?? 0, bounds[2] ?? 0, bounds[3] ?? 0],
|
|
229
|
+
selector: el.selector,
|
|
230
|
+
...(Array.isArray(el.frame) ? { frame: el.frame.filter((f) => typeof f === 'string') } : {}),
|
|
231
|
+
...(typeof el.shadowHost === 'string' ? { shadowHost: el.shadowHost } : {}),
|
|
232
|
+
...(el.states !== null && typeof el.states === 'object'
|
|
233
|
+
? { states: el.states }
|
|
234
|
+
: {}),
|
|
235
|
+
});
|
|
236
|
+
});
|
|
237
|
+
return {
|
|
238
|
+
context,
|
|
239
|
+
url: typeof parsed.url === 'string' ? parsed.url : '',
|
|
240
|
+
title: typeof parsed.title === 'string' ? parsed.title : '',
|
|
241
|
+
text: typeof parsed.text === 'string' ? parsed.text : '',
|
|
242
|
+
elements,
|
|
243
|
+
...(typeof parsed.droppedElements === 'number' && parsed.droppedElements > 0
|
|
244
|
+
? { droppedElements: parsed.droppedElements }
|
|
245
|
+
: {}),
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
/** Build a fresh snapshot for one context via script.evaluate. */
|
|
249
|
+
export async function buildSnapshot(request, context) {
|
|
250
|
+
let result;
|
|
251
|
+
try {
|
|
252
|
+
// Firefox asserts that awaitPromise is present (verified on Zen/Firefox 158).
|
|
253
|
+
result = await request('script.evaluate', {
|
|
254
|
+
expression: SNAPSHOT_SCRIPT,
|
|
255
|
+
target: { context },
|
|
256
|
+
awaitPromise: false,
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
catch (error) {
|
|
260
|
+
if (error instanceof ActionableError) {
|
|
261
|
+
throw error;
|
|
262
|
+
}
|
|
263
|
+
throw new ActionableError('SCRIPT_ERROR', 'Failed to run the snapshot script.', {
|
|
264
|
+
cause: error,
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
const value = result.result;
|
|
268
|
+
return parseSnapshotResult(context, value?.value);
|
|
269
|
+
}
|
|
270
|
+
//# sourceMappingURL=dom-snapshot.js.map
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { ElementInfo, PageSnapshot } from '../types.js';
|
|
2
|
+
/** Look up an element by uid inside a snapshot. */
|
|
3
|
+
export declare function resolveElement(snapshot: PageSnapshot, uid: string): ElementInfo;
|
|
4
|
+
/**
|
|
5
|
+
* Resolution plan for an element: query the frame chain (if any), pierce the
|
|
6
|
+
* shadow host (if any), then match the selector. Pure — the interaction wave
|
|
7
|
+
* executes this against the page.
|
|
8
|
+
*/
|
|
9
|
+
export declare function resolvePlan(element: ElementInfo): {
|
|
10
|
+
frame?: readonly string[];
|
|
11
|
+
shadowHost?: string;
|
|
12
|
+
selector: string;
|
|
13
|
+
};
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { ActionableError } from '../utils/errors.js';
|
|
2
|
+
/** Look up an element by uid inside a snapshot. */
|
|
3
|
+
export function resolveElement(snapshot, uid) {
|
|
4
|
+
const element = snapshot.elements.find((candidate) => candidate.uid === uid);
|
|
5
|
+
if (element === undefined) {
|
|
6
|
+
throw new ActionableError('UID_NOT_FOUND', `Unknown element uid: ${uid}.`, {
|
|
7
|
+
fix: 'Take a fresh page.snapshot to get current uids.',
|
|
8
|
+
details: { context: snapshot.context, url: snapshot.url },
|
|
9
|
+
});
|
|
10
|
+
}
|
|
11
|
+
return element;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Resolution plan for an element: query the frame chain (if any), pierce the
|
|
15
|
+
* shadow host (if any), then match the selector. Pure — the interaction wave
|
|
16
|
+
* executes this against the page.
|
|
17
|
+
*/
|
|
18
|
+
export function resolvePlan(element) {
|
|
19
|
+
return {
|
|
20
|
+
...(element.frame === undefined ? {} : { frame: element.frame }),
|
|
21
|
+
...(element.shadowHost === undefined ? {} : { shadowHost: element.shadowHost }),
|
|
22
|
+
selector: element.selector,
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
//# sourceMappingURL=element-resolver.js.map
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { ElementInfo, PageSnapshot, TruncationMeta } from '../types.js';
|
|
2
|
+
export interface FittedSnapshot {
|
|
3
|
+
readonly url: string;
|
|
4
|
+
readonly title: string;
|
|
5
|
+
readonly elements: readonly ElementInfo[];
|
|
6
|
+
readonly text?: string;
|
|
7
|
+
readonly meta: TruncationMeta;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Fit a snapshot into a character budget. Order of sacrifice: text body
|
|
11
|
+
* first (it is the bulkiest), then tail elements. Interactive heads of the
|
|
12
|
+
* page are worth more than the tail.
|
|
13
|
+
*/
|
|
14
|
+
export declare function fitToBudget(snapshot: PageSnapshot, budget: number, options?: {
|
|
15
|
+
includeText?: boolean;
|
|
16
|
+
}): FittedSnapshot;
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Fit a snapshot into a character budget. Order of sacrifice: text body
|
|
3
|
+
* first (it is the bulkiest), then tail elements. Interactive heads of the
|
|
4
|
+
* page are worth more than the tail.
|
|
5
|
+
*/
|
|
6
|
+
export function fitToBudget(snapshot, budget, options = {}) {
|
|
7
|
+
const includeText = options.includeText === true;
|
|
8
|
+
// Elements the DOM traversal dropped before serialization (hard cap).
|
|
9
|
+
const droppedByCap = snapshot.droppedElements ?? 0;
|
|
10
|
+
const meta = () => ({
|
|
11
|
+
truncated: droppedByCap > 0,
|
|
12
|
+
originalChars: 0,
|
|
13
|
+
omittedElements: droppedByCap,
|
|
14
|
+
omittedTextChars: 0,
|
|
15
|
+
});
|
|
16
|
+
const chars = (value) => JSON.stringify(value ?? '').length;
|
|
17
|
+
// Budget the whole payload, not just the element list — url and title cost
|
|
18
|
+
// characters too.
|
|
19
|
+
const payloadChars = (elements, text) => chars({
|
|
20
|
+
url: snapshot.url,
|
|
21
|
+
title: snapshot.title,
|
|
22
|
+
elements,
|
|
23
|
+
...(text === undefined ? {} : { text }),
|
|
24
|
+
});
|
|
25
|
+
if (!includeText) {
|
|
26
|
+
const original = payloadChars(snapshot.elements);
|
|
27
|
+
if (original <= budget) {
|
|
28
|
+
return {
|
|
29
|
+
url: snapshot.url,
|
|
30
|
+
title: snapshot.title,
|
|
31
|
+
elements: snapshot.elements,
|
|
32
|
+
meta: { ...meta(), originalChars: original },
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
// Binary-search the largest element prefix that fits (plus overhead).
|
|
36
|
+
let low = 0;
|
|
37
|
+
let high = snapshot.elements.length;
|
|
38
|
+
let best = 0;
|
|
39
|
+
while (low <= high) {
|
|
40
|
+
const mid = Math.floor((low + high) / 2);
|
|
41
|
+
if (payloadChars(snapshot.elements.slice(0, mid)) <= budget) {
|
|
42
|
+
best = mid;
|
|
43
|
+
low = mid + 1;
|
|
44
|
+
}
|
|
45
|
+
else {
|
|
46
|
+
high = mid - 1;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return {
|
|
50
|
+
url: snapshot.url,
|
|
51
|
+
title: snapshot.title,
|
|
52
|
+
elements: snapshot.elements.slice(0, best),
|
|
53
|
+
meta: {
|
|
54
|
+
truncated: true,
|
|
55
|
+
originalChars: original,
|
|
56
|
+
omittedElements: snapshot.elements.length - best + droppedByCap,
|
|
57
|
+
omittedTextChars: 0,
|
|
58
|
+
},
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
const original = chars(snapshot.text) + chars(snapshot.elements);
|
|
62
|
+
if (payloadChars(snapshot.elements, snapshot.text) <= budget) {
|
|
63
|
+
return {
|
|
64
|
+
url: snapshot.url,
|
|
65
|
+
title: snapshot.title,
|
|
66
|
+
elements: snapshot.elements,
|
|
67
|
+
text: snapshot.text,
|
|
68
|
+
meta: { ...meta(), originalChars: original },
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
// Drop text first; keep as much as fits alongside a reduced element list.
|
|
72
|
+
const elementsBudgetShare = Math.floor(budget * 0.6);
|
|
73
|
+
let fittedElements = snapshot.elements;
|
|
74
|
+
let truncatedElements = false;
|
|
75
|
+
if (payloadChars(fittedElements) > elementsBudgetShare) {
|
|
76
|
+
const fit = fitToBudget(snapshot, elementsBudgetShare, { includeText: false });
|
|
77
|
+
fittedElements = fit.elements;
|
|
78
|
+
truncatedElements = fit.meta.truncated;
|
|
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;
|
|
83
|
+
let omittedTextChars = 0;
|
|
84
|
+
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;
|
|
89
|
+
}
|
|
90
|
+
return {
|
|
91
|
+
url: snapshot.url,
|
|
92
|
+
title: snapshot.title,
|
|
93
|
+
elements: fittedElements,
|
|
94
|
+
...(text.length > 0 ? { text } : {}),
|
|
95
|
+
meta: {
|
|
96
|
+
truncated: truncatedElements || omittedTextChars > 0 || droppedByCap > 0,
|
|
97
|
+
originalChars: original,
|
|
98
|
+
omittedElements: snapshot.elements.length - fittedElements.length + droppedByCap,
|
|
99
|
+
omittedTextChars,
|
|
100
|
+
},
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
//# sourceMappingURL=token-optimizer.js.map
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { JsonSchema, ToolAnnotations, ToolDefinition, ToolHandler, Toolset } from '../types.js';
|
|
2
|
+
export interface DefineToolOptions {
|
|
3
|
+
name: string;
|
|
4
|
+
title: string;
|
|
5
|
+
description: string;
|
|
6
|
+
toolset: Toolset;
|
|
7
|
+
actions: readonly string[];
|
|
8
|
+
inputSchema: JsonSchema;
|
|
9
|
+
outputSchema?: JsonSchema;
|
|
10
|
+
annotations?: ToolAnnotations;
|
|
11
|
+
handler: ToolHandler;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* The single way to define a tool. It validates the cheap invariants once at
|
|
15
|
+
* registration time so handlers can stay focused on browser work.
|
|
16
|
+
*/
|
|
17
|
+
export declare function defineTool(options: DefineToolOptions): ToolDefinition;
|
|
18
|
+
/** Parameters every tool may accept later. Kept small on purpose. */
|
|
19
|
+
export declare const COMMON_PARAMS: {
|
|
20
|
+
readonly context: {
|
|
21
|
+
readonly type: "string";
|
|
22
|
+
readonly description: "Optional browsing context (tab) ID. Defaults to the active tab.";
|
|
23
|
+
};
|
|
24
|
+
readonly timeout: {
|
|
25
|
+
readonly type: "number";
|
|
26
|
+
readonly description: "Optional timeout in milliseconds. Defaults to BIDI_TIMEOUT.";
|
|
27
|
+
};
|
|
28
|
+
};
|
|
29
|
+
export declare function requireAction(args: Record<string, unknown>, toolName: string, actions: readonly string[]): string;
|
|
30
|
+
/**
|
|
31
|
+
* Gate Firefox-family-only features (containers, Zen spaces). Unknown
|
|
32
|
+
* browser names pass — only a confidently-Chromium name is refused.
|
|
33
|
+
*/
|
|
34
|
+
export declare function assertFirefoxFamily(browserName: unknown, feature: string): void;
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { assertString } from '../utils/assert.js';
|
|
2
|
+
import { ActionableError } from '../utils/errors.js';
|
|
3
|
+
/**
|
|
4
|
+
* The single way to define a tool. It validates the cheap invariants once at
|
|
5
|
+
* registration time so handlers can stay focused on browser work.
|
|
6
|
+
*/
|
|
7
|
+
export function defineTool(options) {
|
|
8
|
+
const name = options.name.trim();
|
|
9
|
+
if (name === '') {
|
|
10
|
+
throw new ActionableError('INTERNAL_ERROR', 'Tool name must not be empty.');
|
|
11
|
+
}
|
|
12
|
+
if (options.actions.length === 0) {
|
|
13
|
+
throw new ActionableError('INTERNAL_ERROR', `Tool "${name}" must declare at least one action.`);
|
|
14
|
+
}
|
|
15
|
+
return Object.freeze({
|
|
16
|
+
...options,
|
|
17
|
+
name,
|
|
18
|
+
actions: Object.freeze([...options.actions]),
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
/** Parameters every tool may accept later. Kept small on purpose. */
|
|
22
|
+
export const COMMON_PARAMS = {
|
|
23
|
+
context: {
|
|
24
|
+
type: 'string',
|
|
25
|
+
description: 'Optional browsing context (tab) ID. Defaults to the active tab.',
|
|
26
|
+
},
|
|
27
|
+
timeout: {
|
|
28
|
+
type: 'number',
|
|
29
|
+
description: 'Optional timeout in milliseconds. Defaults to BIDI_TIMEOUT.',
|
|
30
|
+
},
|
|
31
|
+
};
|
|
32
|
+
export function requireAction(args, toolName, actions) {
|
|
33
|
+
const action = assertString(args.action, `${toolName}.action`);
|
|
34
|
+
if (!actions.includes(action)) {
|
|
35
|
+
throw new ActionableError('INVALID_ACTION', `Unknown action "${action}" for ${toolName}.`, {
|
|
36
|
+
fix: `Use one of: ${actions.join(', ')}.`,
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
return action;
|
|
40
|
+
}
|
|
41
|
+
const FIREFOX_FAMILY_NAMES = ['firefox', 'zen', 'librewolf', 'waterfox', 'floorp'];
|
|
42
|
+
/**
|
|
43
|
+
* Gate Firefox-family-only features (containers, Zen spaces). Unknown
|
|
44
|
+
* browser names pass — only a confidently-Chromium name is refused.
|
|
45
|
+
*/
|
|
46
|
+
export function assertFirefoxFamily(browserName, feature) {
|
|
47
|
+
const name = String(browserName ?? '').toLowerCase();
|
|
48
|
+
if (name === '' || FIREFOX_FAMILY_NAMES.includes(name)) {
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
throw new ActionableError('UNSUPPORTED', `${feature} is a Firefox-family feature; this session reports browser "${name}".`, {
|
|
52
|
+
fix: 'Connect to a Firefox-family browser (Firefox, Zen, LibreWolf, Waterfox, Floorp).',
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
//# sourceMappingURL=base-tool.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const browserTool: import("../types.js").ToolDefinition;
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { defineTool, requireAction } from './base-tool.js';
|
|
2
|
+
import { ActionableError } from '../utils/errors.js';
|
|
3
|
+
import { ok } from '../utils/result.js';
|
|
4
|
+
const ACTIONS = ['status', 'profiles', 'version', 'connect', 'disconnect'];
|
|
5
|
+
const INPUT_SCHEMA = {
|
|
6
|
+
type: 'object',
|
|
7
|
+
properties: {
|
|
8
|
+
action: {
|
|
9
|
+
type: 'string',
|
|
10
|
+
enum: [...ACTIONS],
|
|
11
|
+
description: 'status: connection state; profiles: discovery candidates; version: server + browser; connect: attach; disconnect: end session',
|
|
12
|
+
},
|
|
13
|
+
},
|
|
14
|
+
required: ['action'],
|
|
15
|
+
additionalProperties: false,
|
|
16
|
+
};
|
|
17
|
+
const OUTPUT_SCHEMA = {
|
|
18
|
+
type: 'object',
|
|
19
|
+
properties: {
|
|
20
|
+
ok: { type: 'boolean' },
|
|
21
|
+
action: { type: 'string' },
|
|
22
|
+
data: { type: ['object', 'null'] },
|
|
23
|
+
error: {
|
|
24
|
+
type: 'object',
|
|
25
|
+
properties: {
|
|
26
|
+
code: { type: 'string' },
|
|
27
|
+
message: { type: 'string' },
|
|
28
|
+
fix: { type: 'string' },
|
|
29
|
+
details: { type: 'object' },
|
|
30
|
+
},
|
|
31
|
+
required: ['code', 'message'],
|
|
32
|
+
},
|
|
33
|
+
warnings: { type: 'array', items: { type: 'string' } },
|
|
34
|
+
},
|
|
35
|
+
required: ['ok', 'action'],
|
|
36
|
+
additionalProperties: false,
|
|
37
|
+
};
|
|
38
|
+
export const browserTool = defineTool({
|
|
39
|
+
name: 'browser',
|
|
40
|
+
title: 'Browser session',
|
|
41
|
+
description: 'Inspect and control the single BiDi session. This never launches, closes, or mutates the user’s browser.',
|
|
42
|
+
toolset: 'core',
|
|
43
|
+
actions: ACTIONS,
|
|
44
|
+
inputSchema: INPUT_SCHEMA,
|
|
45
|
+
outputSchema: OUTPUT_SCHEMA,
|
|
46
|
+
annotations: {
|
|
47
|
+
readOnlyHint: false,
|
|
48
|
+
destructiveHint: false,
|
|
49
|
+
idempotentHint: false,
|
|
50
|
+
openWorldHint: false,
|
|
51
|
+
},
|
|
52
|
+
handler: async (args, ctx) => {
|
|
53
|
+
const action = requireAction(args, 'browser', ACTIONS);
|
|
54
|
+
const session = ctx.session;
|
|
55
|
+
if (session === undefined) {
|
|
56
|
+
throw new ActionableError('INTERNAL_ERROR', 'No session manager is attached to this server context.', { fix: 'Rebuild the server, then restart the MCP client.' });
|
|
57
|
+
}
|
|
58
|
+
switch (action) {
|
|
59
|
+
case 'status':
|
|
60
|
+
return ok(action, await session.status());
|
|
61
|
+
case 'profiles':
|
|
62
|
+
return ok(action, { candidates: await session.profiles() });
|
|
63
|
+
case 'version':
|
|
64
|
+
return ok(action, await session.version());
|
|
65
|
+
case 'connect':
|
|
66
|
+
return ok(action, await session.connect());
|
|
67
|
+
case 'disconnect':
|
|
68
|
+
await session.disconnect();
|
|
69
|
+
return ok(action, { connected: false });
|
|
70
|
+
default:
|
|
71
|
+
throw new ActionableError('INVALID_ACTION', `Unknown browser action: ${action}.`);
|
|
72
|
+
}
|
|
73
|
+
},
|
|
74
|
+
});
|
|
75
|
+
//# sourceMappingURL=browser.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const cleanupTool: import("../types.js").ToolDefinition;
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { defineTool, requireAction } from './base-tool.js';
|
|
2
|
+
import { ActionableError } from '../utils/errors.js';
|
|
3
|
+
import { ok } from '../utils/result.js';
|
|
4
|
+
const ACTIONS = ['disconnect'];
|
|
5
|
+
const INPUT_SCHEMA = {
|
|
6
|
+
type: 'object',
|
|
7
|
+
properties: {
|
|
8
|
+
action: {
|
|
9
|
+
type: 'string',
|
|
10
|
+
enum: [...ACTIONS],
|
|
11
|
+
description: 'disconnect: end the BiDi session without closing the browser',
|
|
12
|
+
},
|
|
13
|
+
},
|
|
14
|
+
required: ['action'],
|
|
15
|
+
additionalProperties: false,
|
|
16
|
+
};
|
|
17
|
+
const OUTPUT_SCHEMA = {
|
|
18
|
+
type: 'object',
|
|
19
|
+
properties: {
|
|
20
|
+
ok: { type: 'boolean' },
|
|
21
|
+
action: { type: 'string' },
|
|
22
|
+
data: { type: ['object', 'null'] },
|
|
23
|
+
error: {
|
|
24
|
+
type: 'object',
|
|
25
|
+
properties: {
|
|
26
|
+
code: { type: 'string' },
|
|
27
|
+
message: { type: 'string' },
|
|
28
|
+
fix: { type: 'string' },
|
|
29
|
+
details: { type: 'object' },
|
|
30
|
+
},
|
|
31
|
+
required: ['code', 'message'],
|
|
32
|
+
},
|
|
33
|
+
warnings: { type: 'array', items: { type: 'string' } },
|
|
34
|
+
},
|
|
35
|
+
required: ['ok', 'action'],
|
|
36
|
+
additionalProperties: false,
|
|
37
|
+
};
|
|
38
|
+
export const cleanupTool = defineTool({
|
|
39
|
+
name: 'cleanup',
|
|
40
|
+
title: 'Cleanup',
|
|
41
|
+
description: 'End the BiDi session cleanly. The browser and its tabs stay open; no session is left behind.',
|
|
42
|
+
toolset: 'core',
|
|
43
|
+
actions: ACTIONS,
|
|
44
|
+
inputSchema: INPUT_SCHEMA,
|
|
45
|
+
outputSchema: OUTPUT_SCHEMA,
|
|
46
|
+
annotations: {
|
|
47
|
+
readOnlyHint: false,
|
|
48
|
+
destructiveHint: false,
|
|
49
|
+
idempotentHint: true,
|
|
50
|
+
openWorldHint: false,
|
|
51
|
+
},
|
|
52
|
+
handler: async (args, ctx) => {
|
|
53
|
+
const action = requireAction(args, 'cleanup', ACTIONS);
|
|
54
|
+
const session = ctx.session;
|
|
55
|
+
if (session === undefined) {
|
|
56
|
+
throw new ActionableError('INTERNAL_ERROR', 'No session manager is attached.', {
|
|
57
|
+
fix: 'Rebuild the server, then restart the MCP client.',
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
await session.disconnect();
|
|
61
|
+
return ok(action, { connected: false });
|
|
62
|
+
},
|
|
63
|
+
});
|
|
64
|
+
//# sourceMappingURL=cleanup.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const consoleTool: import("../types.js").ToolDefinition;
|