@browserbridge/bbx 1.1.0 → 1.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.
@@ -0,0 +1,296 @@
1
+ // @ts-check
2
+
3
+ import {
4
+ bridgeMethodNeedsTab,
5
+ DEFAULT_MAX_HTML_LENGTH,
6
+ estimateJsonPayloadCost,
7
+ getBudgetPreset,
8
+ getErrorRecovery,
9
+ isBudgetPresetName,
10
+ summarizeBatchErrorItem,
11
+ summarizeBatchResponseItem,
12
+ } from '../../protocol/src/index.js';
13
+ import {
14
+ getDoctorReport,
15
+ requestBridge,
16
+ resolveRef,
17
+ withBridgeClient,
18
+ } from '../../agent-client/src/runtime.js';
19
+ import { annotateBridgeSummary, summarizeBridgeResponse } from '../../agent-client/src/subagent.js';
20
+
21
+ /** @typedef {import('../../protocol/src/types.js').BridgeMethod} BridgeMethod */
22
+ /** @typedef {import('../../protocol/src/types.js').BridgeResponse} BridgeResponse */
23
+
24
+ export const REQUEST_SOURCE = 'mcp';
25
+
26
+ /**
27
+ * @typedef {{
28
+ * content: Array<{ type: 'text', text: string }>,
29
+ * structuredContent: Record<string, unknown>,
30
+ * isError?: boolean
31
+ * }} ToolResult
32
+ */
33
+
34
+ /**
35
+ * @param {string} summary
36
+ * @param {Record<string, unknown>} [structuredContent={}]
37
+ * @param {boolean} [isError=false]
38
+ * @returns {ToolResult}
39
+ */
40
+ export function createToolResult(summary, structuredContent = {}, isError = false) {
41
+ const toolResult = {
42
+ content: [{ type: /** @type {'text'} */ ('text'), text: summary }],
43
+ structuredContent,
44
+ ...(isError ? { isError: true } : {}),
45
+ };
46
+ const delivered = estimateJsonPayloadCost(toolResult);
47
+ return {
48
+ ...toolResult,
49
+ structuredContent: {
50
+ ...structuredContent,
51
+ deliveredBytes: delivered.bytes,
52
+ deliveredTokens: delivered.approxTokens,
53
+ deliveredCostClass: delivered.costClass,
54
+ },
55
+ };
56
+ }
57
+
58
+ /**
59
+ * @param {BridgeResponse} response
60
+ * @param {string} [method]
61
+ * @returns {ToolResult}
62
+ */
63
+ export function summarizeToolResponse(response, method) {
64
+ const summary = annotateBridgeSummary(summarizeBridgeResponse(response, method), response);
65
+ return createToolResult(summary.summary, summary, !summary.ok);
66
+ }
67
+
68
+ /**
69
+ * @param {unknown} error
70
+ * @returns {ToolResult}
71
+ */
72
+ export function summarizeToolError(error) {
73
+ const message = error instanceof Error ? error.message : String(error);
74
+ return createToolResult(
75
+ `ERROR: ${message}`,
76
+ {
77
+ ok: false,
78
+ evidence: null,
79
+ },
80
+ true
81
+ );
82
+ }
83
+
84
+ /**
85
+ * @param {(client: import('../../agent-client/src/client.js').BridgeClient) => Promise<ToolResult>} callback
86
+ * @returns {Promise<ToolResult>}
87
+ */
88
+ export async function withToolClient(callback) {
89
+ try {
90
+ return await withBridgeClient(callback);
91
+ } catch (error) {
92
+ return summarizeToolError(error);
93
+ }
94
+ }
95
+
96
+ /**
97
+ * @param {import('../../agent-client/src/client.js').BridgeClient} client
98
+ * @param {{ elementRef?: string | undefined, selector?: string | undefined }} input
99
+ * @param {number | null | undefined} [tabId]
100
+ * @returns {Promise<string>}
101
+ */
102
+ export async function resolveToolRef(client, input, tabId = null) {
103
+ if (typeof input.elementRef === 'string' && input.elementRef) {
104
+ return input.elementRef;
105
+ }
106
+ if (typeof input.selector === 'string' && input.selector) {
107
+ return resolveRef(client, input.selector, tabId, REQUEST_SOURCE);
108
+ }
109
+ throw new Error('Provide either elementRef or selector.');
110
+ }
111
+
112
+ /**
113
+ * @param {unknown} value
114
+ * @returns {'quick' | 'normal' | 'deep' | null}
115
+ */
116
+ export function getBudgetPresetName(value) {
117
+ return isBudgetPresetName(value) ? value : null;
118
+ }
119
+
120
+ /**
121
+ * @param {{ budgetPreset?: unknown, selector?: unknown, elementRef?: unknown }} args
122
+ * @returns {'quick' | 'normal' | 'deep' | null}
123
+ */
124
+ export function inferBudgetFromSelector(args) {
125
+ if (getBudgetPresetName(args.budgetPreset)) return null;
126
+ if (typeof args.elementRef === 'string' && args.elementRef) return 'quick';
127
+ const sel = typeof args.selector === 'string' ? args.selector.trim() : '';
128
+ if (!sel || sel === '*' || sel === 'body') return null;
129
+ if (/^#[\w-]+$/.test(sel)) return 'quick';
130
+ if ((sel.match(/\s/g) || []).length >= 3) return 'deep';
131
+ return 'normal';
132
+ }
133
+
134
+ /**
135
+ * @param {{ budgetPreset?: unknown }} args
136
+ * @returns {number | null}
137
+ */
138
+ export function getToolTokenBudget(args) {
139
+ const presetName = getBudgetPresetName(args.budgetPreset);
140
+ return presetName ? getBudgetPreset(presetName).tokenBudget : null;
141
+ }
142
+
143
+ /**
144
+ * @template {{ budgetPreset?: unknown, maxNodes?: unknown, maxDepth?: unknown, textBudget?: unknown }} T
145
+ * @param {T} args
146
+ * @returns {T}
147
+ */
148
+ export function applyTreeBudgetPreset(args) {
149
+ const presetName = getBudgetPresetName(args.budgetPreset);
150
+ if (!presetName) {
151
+ return args;
152
+ }
153
+ const preset = getBudgetPreset(presetName);
154
+ return /** @type {T} */ ({
155
+ ...args,
156
+ maxNodes: args.maxNodes ?? preset.maxNodes,
157
+ maxDepth: args.maxDepth ?? preset.maxDepth,
158
+ textBudget: args.textBudget ?? preset.textBudget,
159
+ });
160
+ }
161
+
162
+ /**
163
+ * @template {{ budgetPreset?: unknown, textBudget?: unknown }} T
164
+ * @param {T} args
165
+ * @returns {T}
166
+ */
167
+ export function applyTextBudgetPreset(args) {
168
+ const presetName = getBudgetPresetName(args.budgetPreset);
169
+ if (!presetName) {
170
+ return args;
171
+ }
172
+ const preset = getBudgetPreset(presetName);
173
+ return /** @type {T} */ ({
174
+ ...args,
175
+ textBudget: args.textBudget ?? preset.textBudget,
176
+ });
177
+ }
178
+
179
+ /**
180
+ * @template {{ budgetPreset?: unknown, limit?: unknown }} T
181
+ * @param {T} args
182
+ * @param {{ quick: number, normal: number, deep: number }} defaults
183
+ * @returns {T}
184
+ */
185
+ export function applyLimitBudgetPreset(args, defaults) {
186
+ const presetName = getBudgetPresetName(args.budgetPreset);
187
+ if (!presetName) {
188
+ return args;
189
+ }
190
+ return /** @type {T} */ ({
191
+ ...args,
192
+ limit: args.limit ?? defaults[presetName],
193
+ });
194
+ }
195
+
196
+ /**
197
+ * @template {{ budgetPreset?: unknown, maxLength?: unknown }} T
198
+ * @param {T} args
199
+ * @returns {T}
200
+ */
201
+ export function applyHtmlBudgetPreset(args) {
202
+ const presetName = getBudgetPresetName(args.budgetPreset);
203
+ if (!presetName) {
204
+ return args;
205
+ }
206
+ const maxLengthByPreset = {
207
+ quick: 600,
208
+ normal: DEFAULT_MAX_HTML_LENGTH,
209
+ deep: 6000,
210
+ };
211
+ return /** @type {T} */ ({
212
+ ...args,
213
+ maxLength: args.maxLength ?? maxLengthByPreset[presetName],
214
+ });
215
+ }
216
+
217
+ /**
218
+ * @param {import('../../agent-client/src/client.js').BridgeClient} client
219
+ * @param {BridgeMethod} method
220
+ * @param {Record<string, unknown>} params
221
+ * @param {{ tabId?: number | null, source?: import('../../protocol/src/types.js').BridgeRequestSource, tokenBudget?: number | null }} options
222
+ * @returns {Promise<BridgeResponse>}
223
+ */
224
+ export async function requestBridgeWithRetry(client, method, params, options) {
225
+ const response = await requestBridge(client, method, params, options);
226
+ const recovery = !response.ok && response.error ? getErrorRecovery(response.error.code) : null;
227
+ if (!response.ok && recovery?.retry) {
228
+ const delay = recovery.retryAfterMs ?? 1000;
229
+ process.stderr.write(
230
+ `[bbx-mcp] Retrying ${method} after ${delay}ms (${response.error.code})\n`
231
+ );
232
+ await new Promise((r) => setTimeout(r, delay));
233
+ return requestBridge(client, method, params, options);
234
+ }
235
+ return response;
236
+ }
237
+
238
+ /**
239
+ * @param {BridgeMethod} method
240
+ * @param {Record<string, unknown>} [params={}]
241
+ * @param {{ tabId?: number | null, summaryMethod?: string, tokenBudget?: number | null }} [options]
242
+ * @returns {Promise<ToolResult>}
243
+ */
244
+ export async function callBridgeTool(method, params = {}, options = {}) {
245
+ return withToolClient(async (client) => {
246
+ const response = await requestBridgeWithRetry(client, method, params, {
247
+ tabId: options.tabId ?? null,
248
+ source: REQUEST_SOURCE,
249
+ tokenBudget: options.tokenBudget ?? null,
250
+ });
251
+ return summarizeToolResponse(response, options.summaryMethod || method);
252
+ });
253
+ }
254
+
255
+ /**
256
+ * @typedef {{ ref: boolean, method: BridgeMethod, params: (args: Record<string, unknown>, ref?: string) => Record<string, unknown> }} ToolAction
257
+ */
258
+
259
+ /**
260
+ * @param {Record<string, ToolAction>} actions
261
+ * @param {Record<string, unknown> & { action: string }} args
262
+ * @param {string} toolName
263
+ * @returns {Promise<ToolResult>}
264
+ */
265
+ export async function dispatchToolAction(actions, args, toolName) {
266
+ const entry = actions[args.action];
267
+ if (!entry) return summarizeToolError(`Unsupported ${toolName} action "${args.action}".`);
268
+ return withToolClient(async (client) => {
269
+ const requestedTabId = typeof args.tabId === 'number' ? args.tabId : null;
270
+ const ref = entry.ref
271
+ ? await resolveToolRef(
272
+ client,
273
+ /** @type {{ elementRef?: string, selector?: string }} */ (args),
274
+ requestedTabId
275
+ )
276
+ : undefined;
277
+ const response = await requestBridgeWithRetry(client, entry.method, entry.params(args, ref), {
278
+ tabId: requestedTabId,
279
+ source: REQUEST_SOURCE,
280
+ tokenBudget: getToolTokenBudget(/** @type {{ budgetPreset?: unknown }} */ (args)),
281
+ });
282
+ return summarizeToolResponse(response, entry.method);
283
+ });
284
+ }
285
+
286
+ export {
287
+ bridgeMethodNeedsTab,
288
+ getDoctorReport,
289
+ requestBridge,
290
+ resolveRef,
291
+ withBridgeClient,
292
+ annotateBridgeSummary,
293
+ summarizeBridgeResponse,
294
+ summarizeBatchErrorItem,
295
+ summarizeBatchResponseItem,
296
+ };