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.
- package/README.md +64 -9
- package/dist/bin.js +3 -2
- package/dist/config.js +4 -0
- package/dist/connection/bidi-client.d.ts +13 -1
- package/dist/connection/bidi-client.js +59 -8
- package/dist/connection/browser-discovery.d.ts +20 -0
- package/dist/connection/browser-discovery.js +76 -12
- package/dist/connection/chromium-mapper.d.ts +9 -0
- package/dist/connection/chromium-mapper.js +24 -0
- package/dist/connection/event-pipeline.d.ts +15 -2
- package/dist/connection/event-pipeline.js +45 -3
- package/dist/connection/protocol-probe.d.ts +43 -0
- package/dist/connection/protocol-probe.js +112 -0
- package/dist/index.js +6 -0
- package/dist/session/session-manager.d.ts +26 -1
- package/dist/session/session-manager.js +262 -6
- package/dist/snapshot/cache.d.ts +4 -0
- package/dist/snapshot/cache.js +8 -0
- package/dist/snapshot/dom-snapshot.js +10 -1
- package/dist/snapshot/element-script.d.ts +23 -0
- package/dist/snapshot/element-script.js +70 -0
- package/dist/snapshot/token-optimizer.js +26 -8
- package/dist/snapshot/uid-verify.d.ts +43 -0
- package/dist/snapshot/uid-verify.js +154 -0
- package/dist/tools/browser.js +21 -6
- package/dist/tools/context.js +4 -6
- package/dist/tools/interact.d.ts +1 -0
- package/dist/tools/interact.js +593 -0
- package/dist/tools/network.d.ts +1 -0
- package/dist/tools/network.js +166 -0
- package/dist/tools/page.js +53 -2
- package/dist/tools/ping.js +5 -1
- package/dist/tools/script.d.ts +1 -0
- package/dist/tools/script.js +166 -0
- package/dist/types.d.ts +50 -1
- package/dist/utils/bidi-value.d.ts +10 -0
- package/dist/utils/bidi-value.js +56 -0
- package/dist/utils/errors.d.ts +3 -1
- package/dist/utils/errors.js +13 -7
- package/dist/utils/redact.d.ts +16 -0
- package/dist/utils/redact.js +47 -0
- package/package.json +1 -1
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import { COMMON_PARAMS, defineTool, requireAction } from './base-tool.js';
|
|
2
|
+
import { ActionableError } from '../utils/errors.js';
|
|
3
|
+
import { NETWORK_SUBSCRIBED_EVENTS } from '../connection/event-pipeline.js';
|
|
4
|
+
import { ok } from '../utils/result.js';
|
|
5
|
+
const ACTIONS = ['wait'];
|
|
6
|
+
const INPUT_SCHEMA = {
|
|
7
|
+
type: 'object',
|
|
8
|
+
properties: {
|
|
9
|
+
action: {
|
|
10
|
+
type: 'string',
|
|
11
|
+
enum: [...ACTIONS],
|
|
12
|
+
description: 'wait: wait for a request or response matching filters',
|
|
13
|
+
},
|
|
14
|
+
until: {
|
|
15
|
+
type: 'string',
|
|
16
|
+
enum: ['request', 'response'],
|
|
17
|
+
description: 'Which network event to wait for. Default response.',
|
|
18
|
+
},
|
|
19
|
+
method: {
|
|
20
|
+
type: 'string',
|
|
21
|
+
description: 'HTTP method filter, e.g. POST.',
|
|
22
|
+
},
|
|
23
|
+
urlPattern: {
|
|
24
|
+
type: 'string',
|
|
25
|
+
description: 'Substring match on the request URL (case-insensitive).',
|
|
26
|
+
},
|
|
27
|
+
timeout: {
|
|
28
|
+
type: 'number',
|
|
29
|
+
description: 'Deadline in milliseconds. Default 10000, capped at 30000.',
|
|
30
|
+
},
|
|
31
|
+
context: COMMON_PARAMS.context,
|
|
32
|
+
},
|
|
33
|
+
required: ['action'],
|
|
34
|
+
additionalProperties: false,
|
|
35
|
+
};
|
|
36
|
+
const OUTPUT_SCHEMA = {
|
|
37
|
+
type: 'object',
|
|
38
|
+
properties: {
|
|
39
|
+
ok: { type: 'boolean' },
|
|
40
|
+
action: { type: 'string' },
|
|
41
|
+
data: { type: ['object', 'null'] },
|
|
42
|
+
error: {
|
|
43
|
+
type: 'object',
|
|
44
|
+
properties: {
|
|
45
|
+
code: { type: 'string' },
|
|
46
|
+
message: { type: 'string' },
|
|
47
|
+
fix: { type: 'string' },
|
|
48
|
+
details: { type: 'object' },
|
|
49
|
+
},
|
|
50
|
+
required: ['code', 'message'],
|
|
51
|
+
},
|
|
52
|
+
warnings: { type: 'array', items: { type: 'string' } },
|
|
53
|
+
},
|
|
54
|
+
required: ['ok', 'action'],
|
|
55
|
+
additionalProperties: false,
|
|
56
|
+
};
|
|
57
|
+
const DEFAULT_TIMEOUT_MS = 10_000;
|
|
58
|
+
const MAX_TIMEOUT_MS = 30_000;
|
|
59
|
+
const POLL_INTERVAL_MS = 100;
|
|
60
|
+
/**
|
|
61
|
+
* Extract metadata (never bodies) from a network event record.
|
|
62
|
+
* Kinds:
|
|
63
|
+
* - network.beforeRequestSent → request
|
|
64
|
+
* - network.responseStarted /
|
|
65
|
+
* network.responseCompleted → response (status)
|
|
66
|
+
* - network.fetchError → error
|
|
67
|
+
*/
|
|
68
|
+
function summarize(params) {
|
|
69
|
+
const request = asObject(params.request);
|
|
70
|
+
const method = typeof request?.method === 'string' ? request.method : null;
|
|
71
|
+
const url = typeof request?.url === 'string'
|
|
72
|
+
? request.url
|
|
73
|
+
: typeof params.url === 'string'
|
|
74
|
+
? params.url
|
|
75
|
+
: null;
|
|
76
|
+
const response = asObject(params.response);
|
|
77
|
+
const status = typeof response?.status === 'number' ? response.status : null;
|
|
78
|
+
const errorText = typeof params.errorText === 'string' ? params.errorText : null;
|
|
79
|
+
if (status !== null) {
|
|
80
|
+
return { event: 'response', method, url: typeof response?.url === 'string' ? response.url : url, status };
|
|
81
|
+
}
|
|
82
|
+
if (errorText !== null) {
|
|
83
|
+
return { event: 'error', method, url, status: null };
|
|
84
|
+
}
|
|
85
|
+
if (request !== undefined) {
|
|
86
|
+
return { event: 'request', method, url, status: null };
|
|
87
|
+
}
|
|
88
|
+
return null;
|
|
89
|
+
}
|
|
90
|
+
function asObject(value) {
|
|
91
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
92
|
+
? value
|
|
93
|
+
: undefined;
|
|
94
|
+
}
|
|
95
|
+
export const networkTool = defineTool({
|
|
96
|
+
name: 'network',
|
|
97
|
+
title: 'Network',
|
|
98
|
+
description: 'Read-only network waits: wait for a request or response matching method/URL filters. Metadata only — no bodies, no interception. Requires BIDI_ENABLE_NETWORK.',
|
|
99
|
+
toolset: 'network',
|
|
100
|
+
actions: ACTIONS,
|
|
101
|
+
inputSchema: INPUT_SCHEMA,
|
|
102
|
+
outputSchema: OUTPUT_SCHEMA,
|
|
103
|
+
annotations: {
|
|
104
|
+
readOnlyHint: true,
|
|
105
|
+
destructiveHint: false,
|
|
106
|
+
idempotentHint: true,
|
|
107
|
+
openWorldHint: false,
|
|
108
|
+
},
|
|
109
|
+
handler: async (args, ctx) => {
|
|
110
|
+
requireAction(args, 'network', ACTIONS);
|
|
111
|
+
const session = ctx.session;
|
|
112
|
+
const runtime = session?.runtime;
|
|
113
|
+
if (session === undefined || runtime === undefined) {
|
|
114
|
+
throw new ActionableError('CONNECTION_FAILED', 'No live browser session.', {
|
|
115
|
+
fix: 'Call browser.connect first.',
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
if (!ctx.config.enableNetwork) {
|
|
119
|
+
// Visible tool, actionable failure (same shape as the script gate).
|
|
120
|
+
throw new ActionableError('UNSUPPORTED', 'network waits are opt-in: set BIDI_ENABLE_NETWORK=1.', {
|
|
121
|
+
fix: 'Add BIDI_ENABLE_NETWORK=1 to the server environment and reconnect.',
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
const until = args.until === 'request' ? 'request' : 'response';
|
|
125
|
+
const methodFilter = typeof args.method === 'string' ? args.method.toLowerCase() : undefined;
|
|
126
|
+
const urlFilter = typeof args.urlPattern === 'string' ? args.urlPattern.toLowerCase() : undefined;
|
|
127
|
+
const timeout = typeof args.timeout === 'number' && args.timeout > 0
|
|
128
|
+
? Math.min(args.timeout, MAX_TIMEOUT_MS)
|
|
129
|
+
: DEFAULT_TIMEOUT_MS;
|
|
130
|
+
const context = await runtime.contexts.ensureContext(typeof args.context === 'string' ? args.context : undefined);
|
|
131
|
+
// One additive subscription (decisions §5). First-ever call subscribes;
|
|
132
|
+
// waits match everything buffered since that point, so the common
|
|
133
|
+
// "trigger, then wait" flow still finds the completed exchange.
|
|
134
|
+
await runtime.events.addSubscription(NETWORK_SUBSCRIBED_EVENTS);
|
|
135
|
+
const started = Date.now();
|
|
136
|
+
for (;;) {
|
|
137
|
+
const records = runtime.events.events({ methods: [...NETWORK_SUBSCRIBED_EVENTS] });
|
|
138
|
+
for (const record of records) {
|
|
139
|
+
const summary = summarize(record.params);
|
|
140
|
+
if (summary === null)
|
|
141
|
+
continue;
|
|
142
|
+
if (summary.event !== until && !(until === 'response' && summary.event === 'error'))
|
|
143
|
+
continue;
|
|
144
|
+
if (methodFilter !== undefined && (summary.method ?? '').toLowerCase() !== methodFilter)
|
|
145
|
+
continue;
|
|
146
|
+
if (urlFilter !== undefined && !(summary.url ?? '').toLowerCase().includes(urlFilter))
|
|
147
|
+
continue;
|
|
148
|
+
if (context !== undefined && record.params.context !== context)
|
|
149
|
+
continue;
|
|
150
|
+
return ok('wait', {
|
|
151
|
+
waitedMs: Date.now() - started,
|
|
152
|
+
...summary,
|
|
153
|
+
source: record.method,
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
if (Date.now() - started >= timeout) {
|
|
157
|
+
throw new ActionableError('TIMEOUT', `network.wait found no matching ${until} within ${timeout}ms.`, {
|
|
158
|
+
fix: 'Widen method/urlPattern. The first ever wait subscribes to network events — traffic from before that point is invisible.',
|
|
159
|
+
details: { until, waitedMs: Date.now() - started, buffered: records.length },
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
|
|
163
|
+
}
|
|
164
|
+
},
|
|
165
|
+
});
|
|
166
|
+
//# sourceMappingURL=network.js.map
|
package/dist/tools/page.js
CHANGED
|
@@ -1,16 +1,17 @@
|
|
|
1
1
|
import { COMMON_PARAMS, defineTool, requireAction } from './base-tool.js';
|
|
2
2
|
import { ActionableError, toContextError } from '../utils/errors.js';
|
|
3
|
+
import { assertNavigableUrl } from '../utils/assert.js';
|
|
3
4
|
import { ok } from '../utils/result.js';
|
|
4
5
|
import { buildSnapshot } from '../snapshot/dom-snapshot.js';
|
|
5
6
|
import { fitToBudget } from '../snapshot/token-optimizer.js';
|
|
6
|
-
const ACTIONS = ['snapshot', 'content'];
|
|
7
|
+
const ACTIONS = ['snapshot', 'content', 'navigate'];
|
|
7
8
|
const INPUT_SCHEMA = {
|
|
8
9
|
type: 'object',
|
|
9
10
|
properties: {
|
|
10
11
|
action: {
|
|
11
12
|
type: 'string',
|
|
12
13
|
enum: [...ACTIONS],
|
|
13
|
-
description: 'snapshot: interactive element map with uids (or text mode); content: readable page text',
|
|
14
|
+
description: 'snapshot: interactive element map with uids (or text mode); content: readable page text; navigate: go to a URL, optionally waiting for a load milestone',
|
|
14
15
|
},
|
|
15
16
|
context: COMMON_PARAMS.context,
|
|
16
17
|
mode: {
|
|
@@ -18,6 +19,15 @@ const INPUT_SCHEMA = {
|
|
|
18
19
|
enum: ['interactive', 'text'],
|
|
19
20
|
description: 'snapshot mode. Default interactive (element map).',
|
|
20
21
|
},
|
|
22
|
+
url: {
|
|
23
|
+
type: 'string',
|
|
24
|
+
description: 'URL for page.navigate. Only http:, https:, and about:blank are allowed.',
|
|
25
|
+
},
|
|
26
|
+
wait: {
|
|
27
|
+
type: 'string',
|
|
28
|
+
enum: ['none', 'domContentLoaded', 'load'],
|
|
29
|
+
description: 'page.navigate milestone to wait for. Default domContentLoaded.',
|
|
30
|
+
},
|
|
21
31
|
refresh: {
|
|
22
32
|
type: 'boolean',
|
|
23
33
|
description: 'Bypass the cache and rebuild the snapshot. Default false.',
|
|
@@ -99,6 +109,47 @@ export const pageTool = defineTool({
|
|
|
99
109
|
});
|
|
100
110
|
}
|
|
101
111
|
const context = await runtime.contexts.ensureContext(typeof args.context === 'string' ? args.context : undefined);
|
|
112
|
+
if (action === 'navigate') {
|
|
113
|
+
const url = args.url === undefined ? undefined : assertNavigableUrl(args.url, 'page.navigate url');
|
|
114
|
+
if (url === undefined) {
|
|
115
|
+
throw new ActionableError('INVALID_ARGUMENT', 'page.navigate requires url.', {
|
|
116
|
+
fix: 'Pass an http:, https:, or about:blank URL.',
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
const wait = args.wait === 'none' || args.wait === 'load' ? args.wait : 'domContentLoaded';
|
|
120
|
+
// BiDi's wait enum is none|interactive|complete; the friendly schema
|
|
121
|
+
// names map onto it (domContentLoaded ≙ interactive, load ≙ complete).
|
|
122
|
+
const waitValue = wait === 'load' ? 'complete' : wait === 'none' ? 'none' : 'interactive';
|
|
123
|
+
try {
|
|
124
|
+
const navigated = await session.request('browsingContext.navigate', {
|
|
125
|
+
context,
|
|
126
|
+
url,
|
|
127
|
+
wait: waitValue,
|
|
128
|
+
});
|
|
129
|
+
// The cached snapshot described the old document: drop it (§5).
|
|
130
|
+
runtime.snapshots.invalidate(context);
|
|
131
|
+
return ok(action, {
|
|
132
|
+
url,
|
|
133
|
+
navigation: navigated.navigation === undefined || navigated.navigation === null
|
|
134
|
+
? null
|
|
135
|
+
: String(navigated.navigation),
|
|
136
|
+
wait,
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
catch (error) {
|
|
140
|
+
// Navigation failures get the dedicated code (decisions §5) while the
|
|
141
|
+
// BiDi code and method survive in details for diagnosis.
|
|
142
|
+
if (error instanceof ActionableError && error.code === 'NAVIGATION_FAILED') {
|
|
143
|
+
throw error;
|
|
144
|
+
}
|
|
145
|
+
const cause = toContextError(error);
|
|
146
|
+
throw new ActionableError('NAVIGATION_FAILED', `Navigation to ${url} failed: ${cause.message}`, {
|
|
147
|
+
fix: 'Check that the URL is reachable and the scheme is allowed, then retry.',
|
|
148
|
+
cause,
|
|
149
|
+
details: { url, wait, ...(cause.details ?? {}) },
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
}
|
|
102
153
|
const refresh = args.refresh === true;
|
|
103
154
|
if (action === 'content') {
|
|
104
155
|
const snapshot = await snapshotFor(ctx, context, refresh).catch((error) => {
|
package/dist/tools/ping.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { defineTool, requireAction } from './base-tool.js';
|
|
2
|
+
import { redactStatusProfile } from '../utils/redact.js';
|
|
2
3
|
import { ok } from '../utils/result.js';
|
|
3
4
|
const ACTIONS = ['status'];
|
|
4
5
|
const INPUT_SCHEMA = {
|
|
@@ -59,7 +60,10 @@ export const pingTool = defineTool({
|
|
|
59
60
|
},
|
|
60
61
|
handler: async (args, ctx) => {
|
|
61
62
|
const action = requireAction(args, 'ping', ACTIONS);
|
|
62
|
-
const
|
|
63
|
+
const raw = ctx.session === undefined ? { connected: false } : await ctx.session.status();
|
|
64
|
+
// Browser capabilities can carry the profile path (moz:profile), which
|
|
65
|
+
// embeds the OS username — redact before the payload leaves the tool.
|
|
66
|
+
const status = redactStatusProfile(raw);
|
|
63
67
|
return ok(action, {
|
|
64
68
|
serverVersion: ctx.version,
|
|
65
69
|
connected: status.connected,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const scriptTool: import("../types.js").ToolDefinition;
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import { COMMON_PARAMS, defineTool, requireAction } from './base-tool.js';
|
|
2
|
+
import { ActionableError, toContextError } from '../utils/errors.js';
|
|
3
|
+
import { unwrapBiDiValue } from '../utils/bidi-value.js';
|
|
4
|
+
import { ok } from '../utils/result.js';
|
|
5
|
+
const ACTIONS = ['evaluate', 'waitFor'];
|
|
6
|
+
const INPUT_SCHEMA = {
|
|
7
|
+
type: 'object',
|
|
8
|
+
properties: {
|
|
9
|
+
action: {
|
|
10
|
+
type: 'string',
|
|
11
|
+
enum: [...ACTIONS],
|
|
12
|
+
description: 'evaluate: run a JS expression on the page (credential-unsafe, gated by BIDI_ALLOW_SCRIPT_EVAL); waitFor: poll an expression until it is truthy (safe default)',
|
|
13
|
+
},
|
|
14
|
+
expression: {
|
|
15
|
+
type: 'string',
|
|
16
|
+
description: 'JavaScript source. evaluate: an expression; waitFor: a condition that returns a truthy value.',
|
|
17
|
+
},
|
|
18
|
+
context: COMMON_PARAMS.context,
|
|
19
|
+
timeout: {
|
|
20
|
+
type: 'number',
|
|
21
|
+
description: 'waitFor deadline in milliseconds. Default 10000, capped at 120000.',
|
|
22
|
+
},
|
|
23
|
+
},
|
|
24
|
+
required: ['action', 'expression'],
|
|
25
|
+
additionalProperties: false,
|
|
26
|
+
};
|
|
27
|
+
const OUTPUT_SCHEMA = {
|
|
28
|
+
type: 'object',
|
|
29
|
+
properties: {
|
|
30
|
+
ok: { type: 'boolean' },
|
|
31
|
+
action: { type: 'string' },
|
|
32
|
+
data: { type: ['object', 'null'] },
|
|
33
|
+
error: {
|
|
34
|
+
type: 'object',
|
|
35
|
+
properties: {
|
|
36
|
+
code: { type: 'string' },
|
|
37
|
+
message: { type: 'string' },
|
|
38
|
+
fix: { type: 'string' },
|
|
39
|
+
details: { type: 'object' },
|
|
40
|
+
},
|
|
41
|
+
required: ['code', 'message'],
|
|
42
|
+
},
|
|
43
|
+
warnings: { type: 'array', items: { type: 'string' } },
|
|
44
|
+
},
|
|
45
|
+
required: ['ok', 'action'],
|
|
46
|
+
additionalProperties: false,
|
|
47
|
+
};
|
|
48
|
+
/** waitFor polls with short per-call scripts (decisions §5). */
|
|
49
|
+
const WAIT_POLL_INTERVAL_MS = 250;
|
|
50
|
+
const WAIT_MAX_MS = 120_000;
|
|
51
|
+
function wrapCondition(expression) {
|
|
52
|
+
// A syntax error in the condition surfaces on the first call, not silently
|
|
53
|
+
// as "never true".
|
|
54
|
+
return `() => { try { return (${expression}); } catch (e) { return { __error: String(e && e.message) }; } }`;
|
|
55
|
+
}
|
|
56
|
+
export const scriptTool = defineTool({
|
|
57
|
+
name: 'script',
|
|
58
|
+
title: 'Script',
|
|
59
|
+
description: 'Run JavaScript in the page: evaluate (gated, credential-unsafe) or waitFor (safe polling wait). Tool-internal scripts used by other tools need no flag.',
|
|
60
|
+
toolset: 'core',
|
|
61
|
+
actions: ACTIONS,
|
|
62
|
+
inputSchema: INPUT_SCHEMA,
|
|
63
|
+
outputSchema: OUTPUT_SCHEMA,
|
|
64
|
+
annotations: {
|
|
65
|
+
readOnlyHint: true,
|
|
66
|
+
destructiveHint: true,
|
|
67
|
+
idempotentHint: true,
|
|
68
|
+
openWorldHint: false,
|
|
69
|
+
},
|
|
70
|
+
handler: async (args, ctx) => {
|
|
71
|
+
const action = requireAction(args, 'script', ACTIONS);
|
|
72
|
+
const session = ctx.session;
|
|
73
|
+
const runtime = session?.runtime;
|
|
74
|
+
if (session === undefined || runtime === undefined) {
|
|
75
|
+
throw new ActionableError('CONNECTION_FAILED', 'No live browser session.', {
|
|
76
|
+
fix: 'Call browser.connect first.',
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
const expression = typeof args.expression === 'string' ? args.expression : undefined;
|
|
80
|
+
if (expression === undefined || expression.trim() === '') {
|
|
81
|
+
throw new ActionableError('INVALID_ARGUMENT', `script.${action} requires expression.`, {
|
|
82
|
+
fix: 'Pass the JavaScript source as expression.',
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
if (action === 'evaluate' && !ctx.config.allowScriptEval) {
|
|
86
|
+
// The tool stays visible (decisions §2): the agent can discover it and
|
|
87
|
+
// the error names the exact flag to ask for.
|
|
88
|
+
throw new ActionableError('UNSUPPORTED', 'script.evaluate is gated by BIDI_ALLOW_SCRIPT_EVAL: it can read credentials and needs explicit opt-in.', {
|
|
89
|
+
fix: 'Set BIDI_ALLOW_SCRIPT_EVAL=1 in the server environment and reconnect. Use script.waitFor for condition waits.',
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
const context = await runtime.contexts.ensureContext(typeof args.context === 'string' ? args.context : undefined);
|
|
93
|
+
if (action === 'evaluate') {
|
|
94
|
+
const result = await session.request('script.evaluate', {
|
|
95
|
+
expression,
|
|
96
|
+
awaitPromise: true,
|
|
97
|
+
target: { context },
|
|
98
|
+
});
|
|
99
|
+
const value = unwrapBiDiValue(result.result);
|
|
100
|
+
return ok(action, { context, value });
|
|
101
|
+
}
|
|
102
|
+
// waitFor: poll the condition with short calls so no single command
|
|
103
|
+
// outlives the client timeout (decisions §5).
|
|
104
|
+
const deadline = typeof args.timeout === 'number' && args.timeout > 0
|
|
105
|
+
? Math.min(args.timeout, WAIT_MAX_MS)
|
|
106
|
+
: 10_000;
|
|
107
|
+
const started = Date.now();
|
|
108
|
+
let last = null;
|
|
109
|
+
for (;;) {
|
|
110
|
+
let result;
|
|
111
|
+
try {
|
|
112
|
+
result = await session.request('script.callFunction', {
|
|
113
|
+
functionDeclaration: wrapCondition(expression),
|
|
114
|
+
awaitPromise: true,
|
|
115
|
+
target: { context },
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
catch (error) {
|
|
119
|
+
// A condition that cannot even run (syntax error) is permanent —
|
|
120
|
+
// surface it instead of polling a falsy deadline.
|
|
121
|
+
const cause = toContextError(error);
|
|
122
|
+
throw new ActionableError('SCRIPT_ERROR', `script.waitFor condition failed to run: ${cause.message}`, {
|
|
123
|
+
fix: 'Fix the expression; it must be valid JavaScript in the page context.',
|
|
124
|
+
cause,
|
|
125
|
+
details: { method: 'script.callFunction', ...(cause.details ?? {}) },
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
const raw = result.result;
|
|
129
|
+
if (raw === undefined) {
|
|
130
|
+
// A broken functionDeclaration (syntax error) resolves with no result
|
|
131
|
+
// at all — permanent, so surface it instead of polling a deadline.
|
|
132
|
+
throw new ActionableError('SCRIPT_ERROR', 'script.waitFor condition failed to run (the browser returned no result).', {
|
|
133
|
+
fix: 'Fix the expression; it must be valid JavaScript in the page context.',
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
if (raw !== null && typeof raw === 'object' && raw.type === 'exception') {
|
|
137
|
+
const details = raw.exceptionDetails;
|
|
138
|
+
const exception = details?.exception;
|
|
139
|
+
const text = exception?.value ?? details?.text ?? 'condition threw';
|
|
140
|
+
throw new ActionableError('SCRIPT_ERROR', `script.waitFor condition threw: ${String(text)}`, {
|
|
141
|
+
fix: 'Fix the expression; it must be valid JavaScript in the page context.',
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
const value = unwrapBiDiValue(raw);
|
|
145
|
+
if (value !== null && typeof value === 'object' && '__error' in value) {
|
|
146
|
+
throw new ActionableError('SCRIPT_ERROR', `script.waitFor condition threw: ${String(value.__error)}`, {
|
|
147
|
+
fix: 'Fix the expression; it must be valid JavaScript in the page context.',
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
if (value === undefined || value === null || value === false) {
|
|
151
|
+
last = value;
|
|
152
|
+
}
|
|
153
|
+
else {
|
|
154
|
+
return ok(action, { context, value, waitedMs: Date.now() - started });
|
|
155
|
+
}
|
|
156
|
+
if (Date.now() - started >= deadline) {
|
|
157
|
+
throw new ActionableError('TIMEOUT', `script.waitFor condition stayed falsy for ${deadline}ms.`, {
|
|
158
|
+
fix: 'Raise timeout, or check the expression against the page state.',
|
|
159
|
+
details: { last, waitedMs: Date.now() - started },
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
await new Promise((resolve) => setTimeout(resolve, WAIT_POLL_INTERVAL_MS));
|
|
163
|
+
}
|
|
164
|
+
},
|
|
165
|
+
});
|
|
166
|
+
//# sourceMappingURL=script.js.map
|
package/dist/types.d.ts
CHANGED
|
@@ -19,6 +19,10 @@ export interface Config {
|
|
|
19
19
|
readonly allowExtensionInstall: boolean;
|
|
20
20
|
readonly allowBrowserClose: boolean;
|
|
21
21
|
readonly allowRemote: boolean;
|
|
22
|
+
/** BIDI_ENABLE_NETWORK: the network wait tool is active. */
|
|
23
|
+
readonly enableNetwork: boolean;
|
|
24
|
+
/** BIDI_ALLOW_SCRIPT_EVAL: free-form script.evaluate is allowed. */
|
|
25
|
+
readonly allowScriptEval: boolean;
|
|
22
26
|
readonly discoveryRoots: readonly string[];
|
|
23
27
|
/** Chromium user-data dirs to look for a `DevToolsActivePort` file in. */
|
|
24
28
|
readonly chromiumDataDirs: readonly string[];
|
|
@@ -55,7 +59,7 @@ export interface ToolDefinition {
|
|
|
55
59
|
readonly annotations?: ToolAnnotations;
|
|
56
60
|
readonly handler: ToolHandler;
|
|
57
61
|
}
|
|
58
|
-
export type ActionableErrorCode = 'INVALID_CONFIG' | 'INVALID_ARGUMENT' | 'INVALID_ACTION' | 'TOOL_NOT_FOUND' | 'DISCOVERY_FAILED' | 'SESSION_BUSY' | 'SESSION_FAILED' | 'CONNECTION_FAILED' | 'CONNECTION_CLOSED' | 'TIMEOUT' | 'CONTEXT_NOT_FOUND' | 'TAB_NOT_FOUND' | 'UID_NOT_FOUND' | 'NAVIGATION_FAILED' | 'SCRIPT_ERROR' | 'UNSUPPORTED' | 'MISSING_DEPENDENCY' | 'NETWORK_ERROR' | 'EXTENSION_ERROR' | 'INTERNAL_ERROR';
|
|
62
|
+
export type ActionableErrorCode = 'INVALID_CONFIG' | 'INVALID_ARGUMENT' | 'INVALID_ACTION' | 'TOOL_NOT_FOUND' | 'DISCOVERY_FAILED' | 'SESSION_BUSY' | 'SESSION_FAILED' | 'CONNECTION_FAILED' | 'CONNECTION_CLOSED' | 'TIMEOUT' | 'CONTEXT_NOT_FOUND' | 'TAB_NOT_FOUND' | 'UID_NOT_FOUND' | 'FRAME_NOT_FOUND' | 'ELEMENT_NOT_FOUND' | 'NOT_INTERACTABLE' | 'STALE_UID' | 'NAVIGATION_FAILED' | 'SCRIPT_ERROR' | 'UNSUPPORTED' | 'MISSING_DEPENDENCY' | 'NETWORK_ERROR' | 'EXTENSION_ERROR' | 'INTERNAL_ERROR';
|
|
59
63
|
export interface ActionableErrorShape {
|
|
60
64
|
code: ActionableErrorCode;
|
|
61
65
|
message: string;
|
|
@@ -105,6 +109,23 @@ export type BrowserFamily = 'firefox' | 'chromium';
|
|
|
105
109
|
export interface DiscoveryCandidate {
|
|
106
110
|
readonly endpoint: string;
|
|
107
111
|
readonly source: DiscoverySource;
|
|
112
|
+
/** Stable short handle for browser.connect target ('f-9223', 'c-9222'). */
|
|
113
|
+
readonly id?: string;
|
|
114
|
+
/** Port of the endpoint, when it carries one. */
|
|
115
|
+
readonly port?: number;
|
|
116
|
+
/** TCP probe of the endpoint port — listing only, not a handshake. */
|
|
117
|
+
readonly reachable?: boolean;
|
|
118
|
+
/**
|
|
119
|
+
* Protocol-level verdict: a BiDi endpoint answered `session.status`, or a
|
|
120
|
+
* Chromium DevTools endpoint is recorded and its port answers. Chromium is
|
|
121
|
+
* never WebSocket-probed by the listing — attaching may require the user to
|
|
122
|
+
* approve a new debugging client, and the handshake blocks until granted.
|
|
123
|
+
*/
|
|
124
|
+
readonly connectable?: boolean;
|
|
125
|
+
/** Why the endpoint is not connectable; absent when it is. */
|
|
126
|
+
readonly reason?: string;
|
|
127
|
+
/** True when this candidate is the currently connected endpoint. */
|
|
128
|
+
readonly live?: boolean;
|
|
108
129
|
readonly profilePath?: string;
|
|
109
130
|
readonly processId?: number;
|
|
110
131
|
readonly browserFamily?: BrowserFamily;
|
|
@@ -132,9 +153,26 @@ export interface SessionManagerLike {
|
|
|
132
153
|
browserVersion?: string;
|
|
133
154
|
}>;
|
|
134
155
|
connect(): Promise<SessionStatus>;
|
|
156
|
+
/**
|
|
157
|
+
* Connect to a specific discovered browser: candidate id ('f-9444'), a
|
|
158
|
+
* port ('9444'), an exact endpoint, or a profile/user-data path. Undefined
|
|
159
|
+
* keeps the default ordered auto-connect. Switching ends the current
|
|
160
|
+
* session first (tabs stay open — the browser is never closed).
|
|
161
|
+
*/
|
|
162
|
+
connectTo(target?: string): Promise<SessionStatus>;
|
|
135
163
|
disconnect(): Promise<void>;
|
|
136
164
|
/** Send a BiDi command on the live session. */
|
|
137
165
|
request(method: string, params?: Record<string, unknown>): Promise<Record<string, unknown>>;
|
|
166
|
+
/**
|
|
167
|
+
* Re-resolve a snapshot uid in the live page before dispatching input
|
|
168
|
+
* commands (plan §3). Silent on a match; otherwise throws
|
|
169
|
+
* UID_NOT_FOUND / ELEMENT_NOT_FOUND / STALE_UID.
|
|
170
|
+
*/
|
|
171
|
+
verifyElement(snapshot: PageSnapshot, uid: string): Promise<void>;
|
|
172
|
+
/** The recorded uid→element plan, even after the snapshot cache dropped. */
|
|
173
|
+
planFor(context: string, uid: string): ElementInfo | undefined;
|
|
174
|
+
/** Verify one known element plan against the live page (§3 verdicts). */
|
|
175
|
+
verifyElementPlan(element: ElementInfo, context: string, uid: string): Promise<void>;
|
|
138
176
|
/** Present while a session is live; undefined after disconnect. */
|
|
139
177
|
readonly runtime?: ConnectionRuntimeLike;
|
|
140
178
|
}
|
|
@@ -205,6 +243,13 @@ export interface EventPipelineLike {
|
|
|
205
243
|
record(event: BiDiEvent): void;
|
|
206
244
|
/** Return buffered events matching the filter; optionally drain them. */
|
|
207
245
|
events(filter?: EventFilter): readonly EventRecord[];
|
|
246
|
+
/**
|
|
247
|
+
* Add an additive mid-session subscription (network gate). Idempotent:
|
|
248
|
+
* already-subscribed methods are skipped.
|
|
249
|
+
*/
|
|
250
|
+
addSubscription(events: readonly string[]): Promise<void>;
|
|
251
|
+
/** Methods this pipeline currently subscribes to (base + additive). */
|
|
252
|
+
subscribedMethods(): readonly string[];
|
|
208
253
|
/** Buffered console entries mapped from log.eventAdded frames. */
|
|
209
254
|
consoleEntries(filter?: {
|
|
210
255
|
level?: string;
|
|
@@ -238,6 +283,10 @@ export interface ElementInfo {
|
|
|
238
283
|
readonly role: string;
|
|
239
284
|
readonly name: string;
|
|
240
285
|
readonly tag: string;
|
|
286
|
+
/**
|
|
287
|
+
* Size and position as [x, y, width, height] in document-space
|
|
288
|
+
* coordinates (rect + the frame's scroll offsets at traverse time).
|
|
289
|
+
*/
|
|
241
290
|
readonly bounds: readonly [number, number, number, number];
|
|
242
291
|
/** CSS path within its document or shadow root. */
|
|
243
292
|
readonly selector: string;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Unwrap one BiDi serialized value into plain JS.
|
|
3
|
+
*
|
|
4
|
+
* BiDi encodes objects as `{type: 'object', value: [[key, serialized], …]}`,
|
|
5
|
+
* arrays as `{type: 'array', value: [...]}`, primitives as `{type, value}`,
|
|
6
|
+
* null as `{type: 'null'}`, and element references as
|
|
7
|
+
* `{type: 'element', value: {sharedId, handle?}}`. Tools consume plain values,
|
|
8
|
+
* so the unwrap lives here once and every consumer keeps the same semantics.
|
|
9
|
+
*/
|
|
10
|
+
export declare function unwrapBiDiValue(value: unknown): unknown;
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Unwrap one BiDi serialized value into plain JS.
|
|
3
|
+
*
|
|
4
|
+
* BiDi encodes objects as `{type: 'object', value: [[key, serialized], …]}`,
|
|
5
|
+
* arrays as `{type: 'array', value: [...]}`, primitives as `{type, value}`,
|
|
6
|
+
* null as `{type: 'null'}`, and element references as
|
|
7
|
+
* `{type: 'element', value: {sharedId, handle?}}`. Tools consume plain values,
|
|
8
|
+
* so the unwrap lives here once and every consumer keeps the same semantics.
|
|
9
|
+
*/
|
|
10
|
+
export function unwrapBiDiValue(value) {
|
|
11
|
+
if (value === null || typeof value !== 'object') {
|
|
12
|
+
return value;
|
|
13
|
+
}
|
|
14
|
+
if (Array.isArray(value)) {
|
|
15
|
+
return value;
|
|
16
|
+
}
|
|
17
|
+
const record = value;
|
|
18
|
+
if (typeof record.type !== 'string') {
|
|
19
|
+
return record;
|
|
20
|
+
}
|
|
21
|
+
switch (record.type) {
|
|
22
|
+
case 'null':
|
|
23
|
+
return null;
|
|
24
|
+
case 'undefined':
|
|
25
|
+
return undefined;
|
|
26
|
+
case 'object': {
|
|
27
|
+
const inner = record.value;
|
|
28
|
+
if (!Array.isArray(inner)) {
|
|
29
|
+
return unwrapBiDiValue(inner);
|
|
30
|
+
}
|
|
31
|
+
const result = {};
|
|
32
|
+
for (const entry of inner) {
|
|
33
|
+
if (Array.isArray(entry) && entry.length === 2 && typeof entry[0] === 'string') {
|
|
34
|
+
result[entry[0]] = unwrapBiDiValue(entry[1]);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return result;
|
|
38
|
+
}
|
|
39
|
+
case 'array': {
|
|
40
|
+
const inner = record.value;
|
|
41
|
+
return Array.isArray(inner) ? inner.map((item) => unwrapBiDiValue(item)) : [];
|
|
42
|
+
}
|
|
43
|
+
case 'node':
|
|
44
|
+
// Firefox serializes DOM nodes as `{type:'node', sharedId, handle?}`;
|
|
45
|
+
// keep the reference (input.setFiles consumes it) instead of the value.
|
|
46
|
+
// Chromium dedupes repeat nodes to `internalId` only.
|
|
47
|
+
return {
|
|
48
|
+
...(typeof record.sharedId === 'string' ? { sharedId: record.sharedId } : {}),
|
|
49
|
+
...(typeof record.internalId === 'string' ? { internalId: record.internalId } : {}),
|
|
50
|
+
...(record.handle === undefined ? {} : { handle: record.handle }),
|
|
51
|
+
};
|
|
52
|
+
default:
|
|
53
|
+
return 'value' in record ? unwrapBiDiValue(record.value) : record;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
//# sourceMappingURL=bidi-value.js.map
|
package/dist/utils/errors.d.ts
CHANGED
|
@@ -19,6 +19,8 @@ export declare function toActionableError(error: unknown): ActionableError;
|
|
|
19
19
|
export declare function formatError(error: unknown): string;
|
|
20
20
|
/**
|
|
21
21
|
* Turn the browser's "no such context" rejection into CONTEXT_NOT_FOUND, so
|
|
22
|
-
* callers get the documented code instead of a raw BiDi message.
|
|
22
|
+
* callers get the documented code instead of a raw BiDi message. The flat
|
|
23
|
+
* `details.biDiCode` stamped by BiDiClient is checked before the message, so
|
|
24
|
+
* mapped errors keep their meaning regardless of prose.
|
|
23
25
|
*/
|
|
24
26
|
export declare function toContextError(error: unknown): ActionableError;
|
package/dist/utils/errors.js
CHANGED
|
@@ -45,15 +45,21 @@ export function formatError(error) {
|
|
|
45
45
|
const CONTEXT_NOT_FOUND_PATTERN = /no such context|unknown context|invalid context/i;
|
|
46
46
|
/**
|
|
47
47
|
* Turn the browser's "no such context" rejection into CONTEXT_NOT_FOUND, so
|
|
48
|
-
* callers get the documented code instead of a raw BiDi message.
|
|
48
|
+
* callers get the documented code instead of a raw BiDi message. The flat
|
|
49
|
+
* `details.biDiCode` stamped by BiDiClient is checked before the message, so
|
|
50
|
+
* mapped errors keep their meaning regardless of prose.
|
|
49
51
|
*/
|
|
50
52
|
export function toContextError(error) {
|
|
51
|
-
if (error instanceof ActionableError
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
53
|
+
if (error instanceof ActionableError) {
|
|
54
|
+
const biDiCode = error.details?.biDiCode;
|
|
55
|
+
if ((typeof biDiCode === 'string' && CONTEXT_NOT_FOUND_PATTERN.test(biDiCode)) ||
|
|
56
|
+
CONTEXT_NOT_FOUND_PATTERN.test(error.message)) {
|
|
57
|
+
return new ActionableError('CONTEXT_NOT_FOUND', error.message, {
|
|
58
|
+
fix: 'Call tabs.list to see open contexts.',
|
|
59
|
+
cause: error,
|
|
60
|
+
details: error.details,
|
|
61
|
+
});
|
|
62
|
+
}
|
|
57
63
|
}
|
|
58
64
|
return toActionableError(error);
|
|
59
65
|
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { SessionStatus } from '../types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Replace the user-specific prefix of a profile path with `~` while keeping
|
|
4
|
+
* everything above it: `C:\Users\me\AppData\…\Zen\Profiles\xxx` becomes
|
|
5
|
+
* `~\AppData\…\Zen\Profiles\xxx`, which still identifies the profile file
|
|
6
|
+
* but carries no username. Paths without a home prefix are returned as they
|
|
7
|
+
* are (portable installs use their own drive or a flat config).
|
|
8
|
+
*/
|
|
9
|
+
export declare function redactProfilePath(path: string): string;
|
|
10
|
+
/**
|
|
11
|
+
* Redact every path a status payload can carry: the resolved `profile` of the
|
|
12
|
+
* live session and the `moz:profile` capability the browser reports. Raw paths
|
|
13
|
+
* stay available to internal callers (profile reads in the container and
|
|
14
|
+
* spaces tools) — this copy is for tool output.
|
|
15
|
+
*/
|
|
16
|
+
export declare function redactStatusProfile(status: SessionStatus): SessionStatus;
|