oira666_pi-browser-agent 0.0.24 → 0.0.25

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 CHANGED
@@ -62,7 +62,6 @@ The full toolkit registered for the session is:
62
62
  - `browser_get_network`
63
63
  - `browser_get_accessibility_tree`
64
64
  - `browser_get_performance_metrics`
65
- - `browser_evaluate_js`
66
65
  - `browser_run_js`
67
66
  - `browser_create_tab`
68
67
  - `browser_list_tabs`
@@ -74,9 +73,13 @@ The full toolkit registered for the session is:
74
73
  - `browser_wait_for`
75
74
  - `browser_clear_site_data`
76
75
 
76
+ ## Tab targeting
77
+
78
+ Create a background tab with `browser_create_tab` and pass its returned ID as `tab_id` to each tab-scoped tool. Inspection tools never navigate: call `browser_navigate` with the same `tab_id` first. Use `browser_switch_tab` or `active: true` on creation only when you intend to bring the tab forward. Pi tasks require tab-scoped CDP input. Tab listing, task history, and bridge maintenance do not target a tab.
79
+
77
80
  ## JavaScript input safety
78
81
 
79
- `browser_evaluate_js` and `browser_run_js` send every supplied script to the Chrome extension's configured AI provider. The extension translates source into a validated plan rather than executing it in the page. Clicks, focus, typing, keys, shortcuts and scrolling use the input backend selected in extension settings, either CDP or Python. It scrolls off-screen targets into view before interacting, then reads their coordinates again. CDP works without the Python service installed. Only the Python backend needs that service and can affect the foreground desktop.
82
+ `browser_run_js` sends every supplied script to the Chrome extension's configured AI provider. To read a value, pass code such as `return document.title;`. The extension translates source into a validated plan rather than executing it in the page. Clicks, focus, typing, keys, shortcuts and scrolling use the input backend selected in extension settings, either CDP or Python. It scrolls off-screen targets into view before interacting, then reads their coordinates again. CDP works without the Python service installed. Only the Python backend needs that service and can affect the foreground desktop.
80
83
 
81
84
  This is a bounded JavaScript translation interface, not an arbitrary JavaScript runtime. Supported actions and fixed DOM reads preserve the plan's result. Unsupported code, invalid model responses, missing provider configuration, cancellation and native-input failures return errors. They never fall back to `element.click()`, synthetic events or direct DOM input. Requesting remote object handles or disabling promise awaiting is unsupported. Console capture is limited to entries represented by the translated plan.
82
85
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "oira666_pi-browser-agent",
3
- "version": "0.0.24",
3
+ "version": "0.0.25",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Pi browser agent broker skeleton with lazy browser tool registration",
@@ -5,7 +5,7 @@
5
5
  * signal, ...)` in pi's extension API) and fires it when the user presses
6
6
  * Escape. Before this module nothing in this package listened to that signal,
7
7
  * so an aborted call stayed pending inside `broker.request()` until its own
8
- * timeout expired — up to 15s for browser_evaluate_js, 30s for browser_run_js
8
+ * timeout expired — up to 120s for browser_run_js
9
9
  * and longer for navigation waits. Escape looked like it did nothing.
10
10
  *
11
11
  * Everything here is host-side only: it releases pi immediately and drops the
@@ -24,7 +24,6 @@ const PLACEHOLDER_TOOL_SPECS = [
24
24
  ['browser_get_network', 'Inspect network requests from the browser.'],
25
25
  ['browser_get_accessibility_tree', 'Read the accessibility tree.'],
26
26
  ['browser_get_performance_metrics', 'Read performance metrics.'],
27
- ['browser_evaluate_js', 'AI-translate a JavaScript expression into validated native input and page reads.'],
28
27
  ['browser_run_js', 'AI-translate JavaScript into validated native input and page reads.'],
29
28
  ['browser_create_tab', 'Create a new browser tab.'],
30
29
  ['browser_list_tabs', 'List browser tabs.'],
@@ -4,6 +4,7 @@ import type { ProbeResult } from '../broker/protocol.ts';
4
4
  import type { BrowserAgentBroker } from '../broker/server.ts';
5
5
  import { formatBridgeFailure } from '../broker/diagnostics.ts';
6
6
  import { truncateAndSpill } from '../util/truncate.ts';
7
+ import { assertExplicitTabTarget, tabIdSchema } from './tab-target.ts';
7
8
  import { abortError, isAbortError, sleepUnlessAborted } from '../broker/abort.ts';
8
9
 
9
10
  interface ToolResult {
@@ -40,6 +41,7 @@ async function brokerToolRequest(
40
41
  signal?: AbortSignal,
41
42
  ): Promise<{ ok: true; data: unknown } | { ok: false; error: { code: string; message: string; details?: unknown } }> {
42
43
  try {
44
+ assertExplicitTabTarget(type, params);
43
45
  // Cancellation can arrive before we touch the broker at all.
44
46
  if (signal?.aborted) throw abortError(type, signal);
45
47
  // Lazily (re)acquire the broker (and wait out the extension's reconnect
@@ -87,34 +89,6 @@ function createToolDescription(summary: string): string {
87
89
  return `${summary} If the returned payload is large, it is truncated and the full result is written to a temp file whose path is included in the response.`;
88
90
  }
89
91
 
90
- function withDefaultActiveTabTarget(params: Record<string, unknown>) {
91
- if (typeof params.tab_id === 'number' || params.use_active_tab === true) {
92
- return params;
93
- }
94
- return {
95
- ...params,
96
- use_active_tab: true,
97
- };
98
- }
99
-
100
- // browser_clear_site_data accepts explicit origin/url targets. If either is
101
- // supplied, do not inject use_active_tab — that would send conflicting
102
- // selectors to the bridge and risk clearing the wrong site's data.
103
- function withClearSiteDataTarget(params: Record<string, unknown>) {
104
- if (
105
- typeof params.tab_id === 'number'
106
- || params.use_active_tab === true
107
- || typeof params.origin === 'string'
108
- || typeof params.url === 'string'
109
- ) {
110
- return params;
111
- }
112
- return {
113
- ...params,
114
- use_active_tab: true,
115
- };
116
- }
117
-
118
92
  function createSuccessText(name: string, data: any, spill?: { text: string; truncated: boolean; fullOutputPath?: string }) {
119
93
  const headline =
120
94
  name === 'browser_create_tab'
@@ -131,9 +105,7 @@ function createSuccessText(name: string, data: any, spill?: { text: string; trun
131
105
  ? `Cleared site data for ${data?.origin ?? 'unknown origin'}.`
132
106
  : name === 'browser_reload_extension'
133
107
  ? `Reloaded browser extension ${data?.extensionId ?? 'unknown'}.`
134
- : name === 'browser_evaluate_js'
135
- ? `Evaluated JavaScript in tab ${data?.tabId ?? 'unknown'}.`
136
- : `Ran JavaScript in tab ${data?.tabId ?? 'unknown'}.`;
108
+ : `Ran JavaScript in tab ${data?.tabId ?? 'unknown'}.`;
137
109
 
138
110
  if (!spill) {
139
111
  return headline;
@@ -155,7 +127,6 @@ function validateSuccessPayload(name: string, data: any): { code: string; messag
155
127
  'browser_switch_tab',
156
128
  'browser_close_tab',
157
129
  'browser_reload',
158
- 'browser_evaluate_js',
159
130
  'browser_run_js',
160
131
  ]);
161
132
  if (needsTabId.has(name) && typeof (data as any).tabId !== 'number') {
@@ -231,16 +202,10 @@ function createRequestTool(options: {
231
202
  params: Record<string, unknown>,
232
203
  signal?: AbortSignal,
233
204
  ): Promise<ToolResult> {
234
- const requestParams = options.name === 'browser_clear_site_data'
235
- ? withClearSiteDataTarget(params)
236
- : [
237
- 'browser_evaluate_js',
238
- 'browser_run_js',
239
- 'browser_navigate',
240
- 'browser_reload',
241
- ].includes(options.name)
242
- ? withDefaultActiveTabTarget(params)
243
- : params;
205
+ // New tabs open in the background; the user's focused tab is only changed by browser_switch_tab.
206
+ const requestParams = options.name === 'browser_create_tab'
207
+ ? { ...params, active: params.active ?? false }
208
+ : params;
244
209
 
245
210
  const outcome = await brokerToolRequest(
246
211
  broker,
@@ -280,28 +245,12 @@ function createRequestTool(options: {
280
245
  });
281
246
  }
282
247
 
283
- export const browserEvaluateJsDefinition = {
284
- name: 'browser_evaluate_js',
285
- description: 'Translate a JavaScript expression with the configured browser AI model, then execute its validated native-input/read plan. Clicks, typing, keys and scrolling use the input backend selected in extension settings, either CDP or Python, with off-screen targets scrolled into view first. Unsupported JavaScript is rejected, never executed directly. Requires a configured browser AI provider.',
286
- promptSnippet: 'Translate a JavaScript expression into validated native input and page reads.',
287
- parameters: Type.Object({
288
- tab_id: Type.Optional(Type.Number()),
289
- use_active_tab: Type.Optional(Type.Boolean()),
290
- expression: Type.String({ minLength: 1 }),
291
- await_promise: Type.Optional(Type.Boolean({ default: true })),
292
- return_by_value: Type.Optional(Type.Boolean({ default: true })),
293
- world: Type.Optional(Type.Literal('main', { default: 'main' })),
294
- timeout_ms: Type.Optional(Type.Number({ minimum: 1, default: 120_000 })),
295
- }),
296
- } as const;
297
-
298
248
  export const browserRunJsDefinition = {
299
249
  name: 'browser_run_js',
300
- description: 'Translate a JavaScript program with the configured browser AI model, then execute its validated native-input/read plan. All input uses the backend selected in extension settings, either CDP or Python; off-screen targets are scrolled into view first. Supports a bounded set of actions and reads, not arbitrary page JavaScript. Unsupported code fails without direct JavaScript execution.',
250
+ description: 'Translate a JavaScript program with the configured browser AI model, then execute its validated native-input/read plan. All input uses the backend selected in extension settings, either CDP or Python; off-screen targets are scrolled into view first. Supports a bounded set of actions and reads, not arbitrary page JavaScript. Use `return` to get a value (e.g. `return document.title;`). Unsupported code fails without direct JavaScript execution.',
301
251
  promptSnippet: 'Translate JavaScript into validated native input and page reads.',
302
252
  parameters: Type.Object({
303
- tab_id: Type.Optional(Type.Number()),
304
- use_active_tab: Type.Optional(Type.Boolean()),
253
+ tab_id: tabIdSchema(),
305
254
  code: Type.String({ minLength: 1 }),
306
255
  args: Type.Optional(Type.Array(Type.Unknown())),
307
256
  return_by_value: Type.Optional(Type.Boolean({ default: true })),
@@ -313,7 +262,7 @@ export const browserRunJsDefinition = {
313
262
 
314
263
  export const browserCreateTabDefinition = {
315
264
  name: 'browser_create_tab',
316
- description: 'Create a new browser tab and return its tab id for later browser tool calls.',
265
+ description: 'Create a new browser tab in the background (it does not take focus unless active=true) and return its tab id; pass that tab_id to later browser tool calls.',
317
266
  promptSnippet: 'Create a new browser tab for isolated browser work. Use the returned tab_id in later browser tool calls.',
318
267
  parameters: Type.Object({
319
268
  url: Type.Optional(Type.String({ format: 'uri', minLength: 1 })),
@@ -332,12 +281,11 @@ export const browserCreateTabDefinition = {
332
281
 
333
282
  export const browserNavigateDefinition = {
334
283
  name: 'browser_navigate',
335
- description: 'Navigate a browser tab to a URL and wait for it to settle.',
284
+ description: 'Navigate the tab given by tab_id to a URL and wait for it to settle. Never targets the active tab implicitly.',
336
285
  promptSnippet: 'Navigate a browser tab to a URL.',
337
286
  parameters: Type.Object({
287
+ tab_id: tabIdSchema(),
338
288
  url: Type.String({ format: 'uri', minLength: 1 }),
339
- tab_id: Type.Optional(Type.Number()),
340
- use_active_tab: Type.Optional(Type.Boolean()),
341
289
  wait_until: Type.Optional(Type.Union([
342
290
  Type.Literal('load'),
343
291
  Type.Literal('networkidle'),
@@ -350,10 +298,10 @@ export const browserNavigateDefinition = {
350
298
 
351
299
  export const browserSwitchTabDefinition = {
352
300
  name: 'browser_switch_tab',
353
- description: 'Activate a browser tab and optionally wait for it to settle.',
301
+ description: 'Explicitly focus the tab given by tab_id and optionally wait for it to settle. This is the only way to change the focused tab besides browser_create_tab with active=true.',
354
302
  promptSnippet: 'Switch to a browser tab.',
355
303
  parameters: Type.Object({
356
- tab_id: Type.Number(),
304
+ tab_id: tabIdSchema(),
357
305
  wait_until: Type.Optional(Type.Union([
358
306
  Type.Literal('load'),
359
307
  Type.Literal('networkidle'),
@@ -369,7 +317,7 @@ export const browserCloseTabDefinition = {
369
317
  description: 'Close a browser tab.',
370
318
  promptSnippet: 'Close a browser tab.',
371
319
  parameters: Type.Object({
372
- tab_id: Type.Number(),
320
+ tab_id: tabIdSchema(),
373
321
  }),
374
322
  } as const;
375
323
 
@@ -378,8 +326,7 @@ export const browserReloadDefinition = {
378
326
  description: 'Reload a browser tab.',
379
327
  promptSnippet: 'Reload a browser tab.',
380
328
  parameters: Type.Object({
381
- tab_id: Type.Optional(Type.Number()),
382
- use_active_tab: Type.Optional(Type.Boolean()),
329
+ tab_id: tabIdSchema(),
383
330
  bypass_cache: Type.Optional(Type.Boolean({ default: false })),
384
331
  wait_until: Type.Optional(Type.Union([
385
332
  Type.Literal('load'),
@@ -407,8 +354,7 @@ export const browserClearSiteDataDefinition = {
407
354
  parameters: Type.Object({
408
355
  url: Type.Optional(Type.String({ format: 'uri' })),
409
356
  origin: Type.Optional(Type.String({ format: 'uri' })),
410
- tab_id: Type.Optional(Type.Number()),
411
- use_active_tab: Type.Optional(Type.Boolean()),
357
+ tab_id: tabIdSchema(),
412
358
  types: Type.Optional(Type.Array(Type.Union([
413
359
  Type.Literal('cookies'),
414
360
  Type.Literal('local_storage'),
@@ -419,11 +365,6 @@ export const browserClearSiteDataDefinition = {
419
365
  }),
420
366
  } as const;
421
367
 
422
- export const createBrowserEvaluateJsTool = createRequestTool({
423
- ...browserEvaluateJsDefinition,
424
- timeoutFromParams: (params) => Number(params.timeout_ms ?? 120_000) + 1_000,
425
- });
426
-
427
368
  export const createBrowserRunJsTool = createRequestTool({
428
369
  ...browserRunJsDefinition,
429
370
  timeoutFromParams: (params) => Number(params.timeout_ms ?? 120_000) + 1_000,
@@ -526,7 +467,6 @@ export function createBrowserReloadExtensionTool(broker: BrowserAgentBroker) {
526
467
 
527
468
  export function createBrowserJsNavigationToolFamily(broker: BrowserAgentBroker) {
528
469
  return [
529
- createBrowserEvaluateJsTool(broker),
530
470
  createBrowserRunJsTool(broker),
531
471
  createBrowserCreateTabTool(broker),
532
472
  createBrowserNavigateTool(broker),
@@ -10,18 +10,9 @@ import {
10
10
  textResult,
11
11
  } from './read_only/common.ts';
12
12
  import { isAbortError } from '../broker/abort.ts';
13
+ import { tabIdSchema } from './tab-target.ts';
13
14
  import type { ToolResult } from './read_only/common.ts';
14
15
 
15
- function withDefaultActiveTabTarget(params: Record<string, unknown>) {
16
- if (typeof params.tab_id === 'number' || typeof params.url === 'string' || params.use_active_tab === true) {
17
- return params;
18
- }
19
- return {
20
- ...params,
21
- use_active_tab: true,
22
- };
23
- }
24
-
25
16
  function consoleLogText(details: any) {
26
17
  return [
27
18
  `Console log query returned ${details.returned} entry(s) from tab ${details.tabId}.`,
@@ -43,12 +34,10 @@ export function createBrowserGetConsoleLogsTool(broker: BrowserAgentBroker) {
43
34
  name: 'browser_get_console_logs',
44
35
  label: 'browser_get_console_logs',
45
36
  description:
46
- 'Read buffered browser console logs. If you do not pass tab_id or url, this tool defaults to the active tab. Prefer passing filters such as levels, substring, regex, since, or last to narrow the result. If the output is large, it is truncated and the full result is written to a temp file whose path is included in the response.',
37
+ 'Read buffered browser console logs. Requires an explicit tab_id. Prefer passing filters such as levels, substring, regex, since, or last to narrow the result. If the output is large, it is truncated and the full result is written to a temp file whose path is included in the response.',
47
38
  promptSnippet: 'Read filtered browser console logs.',
48
39
  parameters: Type.Object({
49
- tab_id: Type.Optional(Type.Number()),
50
- url: Type.Optional(Type.String()),
51
- use_active_tab: Type.Optional(Type.Boolean()),
40
+ tab_id: tabIdSchema(),
52
41
  levels: Type.Optional(Type.Array(Type.Union([
53
42
  Type.Literal('log'), Type.Literal('info'), Type.Literal('warn'), Type.Literal('error'), Type.Literal('debug'),
54
43
  ]))),
@@ -65,7 +54,7 @@ export function createBrowserGetConsoleLogsTool(broker: BrowserAgentBroker) {
65
54
  params: Record<string, unknown>,
66
55
  signal?: AbortSignal,
67
56
  ): Promise<ToolResult> {
68
- const requestParams = withDefaultActiveTabTarget(params);
57
+ const requestParams = params;
69
58
  try {
70
59
  const { data } = await requestBridge<Record<string, unknown>>(broker, 'browser_get_console_logs', requestParams, {
71
60
  timeoutMs: Number(requestParams.timeout_ms || defaultTimeoutMs('browser_get_console_logs')),
@@ -102,12 +91,10 @@ export function createBrowserGetNetworkTool(broker: BrowserAgentBroker) {
102
91
  name: 'browser_get_network',
103
92
  label: 'browser_get_network',
104
93
  description:
105
- 'Read buffered browser network activity. If you do not pass tab_id or url, this tool defaults to the active tab. Always pass filters such as status, type, url_contains, failed_only, since, or last, because unfiltered results may be large. Use include_request_body or include_response_body only when needed; bodies are size-capped. Large output is truncated and the full result is written to a temp file whose path is included in the response.',
94
+ 'Read buffered browser network activity. Requires an explicit tab_id. Always pass filters such as status, type, url_contains, failed_only, since, or last, because unfiltered results may be large. Use include_request_body or include_response_body only when needed; bodies are size-capped. Large output is truncated and the full result is written to a temp file whose path is included in the response.',
106
95
  promptSnippet: 'Read filtered browser network activity.',
107
96
  parameters: Type.Object({
108
- tab_id: Type.Optional(Type.Number()),
109
- url: Type.Optional(Type.String()),
110
- use_active_tab: Type.Optional(Type.Boolean()),
97
+ tab_id: tabIdSchema(),
111
98
  filter: Type.Optional(Type.Object({
112
99
  method: Type.Optional(Type.Union([Type.String(), Type.Array(Type.String())])),
113
100
  status: Type.Optional(Type.Union([Type.Number(), Type.Array(Type.Number())])),
@@ -137,7 +124,7 @@ export function createBrowserGetNetworkTool(broker: BrowserAgentBroker) {
137
124
  params: Record<string, unknown>,
138
125
  signal?: AbortSignal,
139
126
  ): Promise<ToolResult> {
140
- const requestParams = withDefaultActiveTabTarget(params);
127
+ const requestParams = params;
141
128
  try {
142
129
  const { data } = await requestBridge<Record<string, unknown>>(broker, 'browser_get_network', requestParams, {
143
130
  timeoutMs: Number(requestParams.timeout_ms || defaultTimeoutMs('browser_get_network')),
@@ -7,6 +7,7 @@ import type { ResponseFrame } from '../broker/protocol.ts';
7
7
  import { formatBridgeFailure } from '../broker/diagnostics.ts';
8
8
  import { assertValidTaskId, TaskCorruptionError, type TaskStoreEntry } from '../broker/task-store.ts';
9
9
  import { ABORT_ERROR_CODE, isAbortError } from '../broker/abort.ts';
10
+ import { assertExplicitTabTarget, tabIdSchema, type TabTargetError } from './tab-target.ts';
10
11
 
11
12
  interface ToolResult {
12
13
  content: Array<{ type: 'text'; text: string }>;
@@ -197,22 +198,32 @@ export function createBrowserRunTaskTool(broker: BrowserAgentBroker) {
197
198
  return {
198
199
  name: 'browser_run_task',
199
200
  label: 'browser_run_task',
200
- description: 'Run a browser task end-to-end. The task may be described in natural English. Defaults to the active browser tab; pass tab_id for deterministic targeting.',
201
- promptSnippet: 'Run a browser task in the active or explicitly targeted tab.',
201
+ description: 'Run a browser task end-to-end. The task may be described in natural English. Requires an explicit tab_id; the active tab is never used implicitly.',
202
+ promptSnippet: 'Run a browser task in the tab given by tab_id.',
202
203
  parameters: Type.Object({
203
204
  task: Type.String({ minLength: 1 }),
204
- tab_id: Type.Optional(Type.Number()),
205
- use_active_tab: Type.Optional(Type.Boolean()),
205
+ tab_id: tabIdSchema(),
206
206
  debugMode: Type.Optional(Type.Boolean()),
207
207
  timeoutMs: Type.Optional(Type.Number({ minimum: 1 })),
208
208
  }),
209
209
  async execute(
210
210
  _toolCallId: string,
211
- params: { task: string; tab_id?: number; use_active_tab?: boolean; debugMode?: boolean; timeoutMs?: number },
211
+ params: { task: string; tab_id: number; debugMode?: boolean; timeoutMs?: number },
212
212
  signal?: AbortSignal,
213
213
  ): Promise<ToolResult> {
214
214
  // Lazily (re)acquire the broker so a killed primary is replaced on demand,
215
215
  // and wait out the extension's reconnect window before deciding we are down.
216
+ try {
217
+ assertExplicitTabTarget('browser_run_task', params);
218
+ } catch (error) {
219
+ const { code, message } = error as TabTargetError;
220
+ return textResult(`browser_run_task failed: ${message}`, {
221
+ ok: false,
222
+ success: false,
223
+ status: 'error',
224
+ error: { code, message },
225
+ });
226
+ }
216
227
  await broker.ensureReady?.({ signal });
217
228
  if (signal?.aborted) {
218
229
  return textResult('browser_run_task cancelled before the task was started.', {
@@ -240,14 +251,11 @@ export function createBrowserRunTaskTool(broker: BrowserAgentBroker) {
240
251
 
241
252
  const taskId = randomUUID();
242
253
  const startedAt = Date.now();
243
- const target = typeof params.tab_id === 'number'
244
- ? { tab_id: params.tab_id }
245
- : { use_active_tab: params.use_active_tab ?? true };
246
254
  const request = {
247
255
  taskId,
248
256
  task: params.task,
249
257
  debugMode: params.debugMode ?? false,
250
- ...target,
258
+ tab_id: params.tab_id,
251
259
  };
252
260
 
253
261
  await appendSafe(broker, taskId, {
@@ -11,6 +11,7 @@ import type { ResponseFrame } from '../../broker/protocol.ts';
11
11
  import { formatBridgeFailure } from '../../broker/diagnostics.ts';
12
12
  import { truncateAndSpill } from '../../util/truncate.ts';
13
13
  import { abortError, isAbortError, type BrokerRequestOptions } from '../../broker/abort.ts';
14
+ import { assertExplicitTabTarget } from '../tab-target.ts';
14
15
 
15
16
  const SCREENSHOT_TEMP_DIR = join(tmpdir(), 'pi-browser-agent', 'screenshots');
16
17
  const SCREENSHOT_TEMP_MAX_AGE_MS = 24 * 60 * 60 * 1000;
@@ -118,6 +119,11 @@ export async function requestBridge<TData>(
118
119
  options: BrokerRequestOptions = {},
119
120
  ): Promise<{ response: ResponseFrame; data: TData }> {
120
121
  const { signal } = options;
122
+ try {
123
+ assertExplicitTabTarget(type, params);
124
+ } catch (error) {
125
+ throw coerceError(error);
126
+ }
121
127
  if (signal?.aborted) throw coerceError(abortError(type, signal));
122
128
  // Lazily (re)acquire the broker before the readiness check so a killed
123
129
  // primary is replaced (or reconnected to) on this request instead of failing.
@@ -4,6 +4,7 @@ import { Type } from 'typebox';
4
4
 
5
5
  import type { BrowserAgentBroker } from '../../broker/server.ts';
6
6
  import { isAbortError } from '../../broker/abort.ts';
7
+ import { tabIdSchema } from '../tab-target.ts';
7
8
  import {
8
9
  BrowserReadOnlyToolError,
9
10
  type ReadOnlyToolDefinition,
@@ -111,9 +112,7 @@ function createScreenshotTool(broker: BrowserAgentBroker): ReadOnlyToolDefinitio
111
112
  'Capture a compressed browser screenshot. Prefer selector/full_page options only when you need them. Large screenshots are spilled to a temp file and the file path is returned.',
112
113
  promptSnippet: 'Capture a browser screenshot.',
113
114
  parameters: Type.Object({
114
- url: Type.Optional(Type.String({ minLength: 1 })),
115
- tab_id: Type.Optional(Type.Number()),
116
- use_active_tab: Type.Optional(Type.Boolean()),
115
+ tab_id: tabIdSchema(),
117
116
  full_page: Type.Optional(Type.Boolean()),
118
117
  selector: Type.Optional(Type.String({ minLength: 1 })),
119
118
  wait_until: Type.Optional(waitUntilType()),
@@ -189,9 +188,7 @@ function createHtmlTool(broker: BrowserAgentBroker): ReadOnlyToolDefinition<any>
189
188
  'Extract HTML from a page. Prefer a CSS selector to return only the subtree you need. If the output is large, it is truncated and the full HTML is written to a temp file.',
190
189
  promptSnippet: 'Get rendered HTML from the browser.',
191
190
  parameters: Type.Object({
192
- url: Type.Optional(Type.String({ minLength: 1 })),
193
- tab_id: Type.Optional(Type.Number()),
194
- use_active_tab: Type.Optional(Type.Boolean()),
191
+ tab_id: tabIdSchema(),
195
192
  selector: Type.Optional(Type.String({ minLength: 1 })),
196
193
  selector_all: Type.Optional(Type.Boolean()),
197
194
  rendered: Type.Optional(Type.Boolean()),
@@ -213,7 +210,7 @@ function createHtmlTool(broker: BrowserAgentBroker): ReadOnlyToolDefinition<any>
213
210
  );
214
211
  }
215
212
  const html = typeof data?.html === 'string' ? data.html : (data.content as string);
216
- const formatted = await formatTextResult(`HTML for ${data?.url || params.url || 'current page'}`, html, 'html');
213
+ const formatted = await formatTextResult(`HTML for ${data?.url || 'tab ' + params.tab_id}`, html, 'html');
217
214
  return textResult(formatted.text, {
218
215
  ok: true,
219
216
  requestType: 'browser_get_html',
@@ -246,11 +243,11 @@ export function createReadOnlyBrowserTools(broker: BrowserAgentBroker): ReadOnly
246
243
  'Inspect DOM details for matching elements. Prefer a specific selector and narrow include fields. Supported include values: attributes, rect, textContent, innerHTML, accessibility, visibility, event_listeners, outer_html. Aliases also accepted: text -> textContent, html -> innerHTML, boundingBox -> rect. Large results are truncated and spilled to a temp file.',
247
244
  promptSnippet: 'Inspect DOM details for selected elements.',
248
245
  parameters: Type.Object({
249
- url: Type.Optional(Type.String({ minLength: 1 })),
246
+ tab_id: tabIdSchema(),
250
247
  selector: Type.String({ minLength: 1 }),
251
248
  selector_all: Type.Optional(Type.Boolean()),
252
249
  limit: Type.Optional(Type.Number({ minimum: 1, maximum: 200 })),
253
- include: Type.Optional(includeType(['attributes', 'rect', 'textContent', 'innerHTML', 'accessibility', 'visibility', 'event_listeners', 'outer_html', 'text', 'html', 'boundingBox'])),},{
250
+ include: Type.Optional(includeType(['attributes', 'rect', 'textContent', 'innerHTML', 'accessibility', 'visibility', 'event_listeners', 'outer_html', 'text', 'html', 'boundingBox'])),
254
251
  }),
255
252
  title: (_data, params) => `DOM info for selector ${String((params as any).selector)}`,
256
253
  }),
@@ -261,7 +258,7 @@ export function createReadOnlyBrowserTools(broker: BrowserAgentBroker): ReadOnly
261
258
  'Read computed CSS styles. Prefer listing only the properties you need. Large results are truncated and spilled to a temp file.',
262
259
  promptSnippet: 'Read computed CSS styles for a selector.',
263
260
  parameters: Type.Object({
264
- url: Type.Optional(Type.String({ minLength: 1 })),
261
+ tab_id: tabIdSchema(),
265
262
  selector: Type.String({ minLength: 1 }),
266
263
  properties: Type.Optional(Type.Array(Type.String({ minLength: 1 }))),
267
264
  pseudo: Type.Optional(Type.String({ minLength: 1 })),
@@ -286,8 +283,7 @@ export function createReadOnlyBrowserTools(broker: BrowserAgentBroker): ReadOnly
286
283
  description: 'Wait for a selector, text, or URL condition. Returns the matched condition and timing details.',
287
284
  promptSnippet: 'Wait for a page condition.',
288
285
  parameters: Type.Object({
289
- url: Type.Optional(Type.String({ minLength: 1 })),
290
- tab_id: Type.Optional(Type.Number()),
286
+ tab_id: tabIdSchema(),
291
287
  selector: Type.Optional(Type.String({ minLength: 1 })),
292
288
  text: Type.Optional(Type.String({ minLength: 1 })),
293
289
  url_matches: Type.Optional(Type.String({ minLength: 1 })),
@@ -307,7 +303,7 @@ export function createReadOnlyBrowserTools(broker: BrowserAgentBroker): ReadOnly
307
303
  'Read the accessibility tree. Prefer a root selector or include filters when possible. Large trees are truncated and spilled to a temp file.',
308
304
  promptSnippet: 'Read the accessibility tree.',
309
305
  parameters: Type.Object({
310
- url: Type.Optional(Type.String({ minLength: 1 })),
306
+ tab_id: tabIdSchema(),
311
307
  root_selector: Type.Optional(Type.String({ minLength: 1 })),
312
308
  interesting_only: Type.Optional(Type.Boolean()),
313
309
  max_depth: Type.Optional(Type.Number({ minimum: 1 })),
@@ -321,7 +317,7 @@ export function createReadOnlyBrowserTools(broker: BrowserAgentBroker): ReadOnly
321
317
  description: 'Read performance metrics, timing, layout, memory, paint, and optional web-vitals data.',
322
318
  promptSnippet: 'Read browser performance metrics.',
323
319
  parameters: Type.Object({
324
- url: Type.Optional(Type.String({ minLength: 1 })),
320
+ tab_id: tabIdSchema(),
325
321
  include: Type.Optional(includeType(['metrics', 'timing', 'web_vitals', 'layout', 'memory', 'paint'])),
326
322
  }),
327
323
  title: () => 'Performance metrics',
@@ -0,0 +1,56 @@
1
+ import { Type } from 'typebox';
2
+
3
+ /**
4
+ * Every tool that acts on a tab needs an explicit tab id. The extension never
5
+ * falls back to the active tab or to a tab matched by URL: that is how an
6
+ * unrelated tab (e.g. a chat app the user is working in) gets navigated.
7
+ */
8
+ const TAB_TARGETED_TOOLS = new Set([
9
+ 'browser_run_task',
10
+ 'browser_get_screenshot',
11
+ 'browser_get_html',
12
+ 'browser_get_dom_info',
13
+ 'browser_get_computed_styles',
14
+ 'browser_get_console_logs',
15
+ 'browser_get_network',
16
+ 'browser_get_accessibility_tree',
17
+ 'browser_get_performance_metrics',
18
+ 'browser_run_js',
19
+ 'browser_navigate',
20
+ 'browser_switch_tab',
21
+ 'browser_close_tab',
22
+ 'browser_reload',
23
+ 'browser_wait_for',
24
+ 'browser_clear_site_data',
25
+ ]);
26
+
27
+ /** Tools whose `url` is a destination or an origin to act on, not a way to pick a tab. */
28
+ const URL_ALLOWED_TOOLS = new Set(['browser_navigate', 'browser_clear_site_data']);
29
+
30
+ export const tabIdSchema = () => Type.Integer({
31
+ minimum: 1,
32
+ maximum: Number.MAX_SAFE_INTEGER,
33
+ description: 'Id of the tab to act on, from browser_create_tab or browser_list_tabs. Required.',
34
+ });
35
+
36
+ export class TabTargetError extends Error {
37
+ readonly code = 'E_INVALID_ARGS';
38
+ }
39
+
40
+ /** Throws unless a tab-targeting call names its tab explicitly and unambiguously. */
41
+ export function assertExplicitTabTarget(tool: string, params: unknown): void {
42
+ if (!TAB_TARGETED_TOOLS.has(tool)) return;
43
+ const input = (params && typeof params === 'object' ? params : {}) as Record<string, unknown>;
44
+ const tabId = input.tab_id;
45
+ if (typeof tabId !== 'number' || !Number.isSafeInteger(tabId) || tabId < 1) {
46
+ throw new TabTargetError(
47
+ `${tool} requires an explicit positive integer tab_id. Create a tab with browser_create_tab or pick one from browser_list_tabs; the active tab is never used implicitly.`,
48
+ );
49
+ }
50
+ if ('use_active_tab' in input) {
51
+ throw new TabTargetError(`${tool} does not support use_active_tab; pass tab_id instead.`);
52
+ }
53
+ if ('url' in input && !URL_ALLOWED_TOOLS.has(tool)) {
54
+ throw new TabTargetError(`${tool} does not select tabs by url; pass tab_id instead.`);
55
+ }
56
+ }
@@ -10,7 +10,7 @@ import WebSocket from 'ws';
10
10
  import { BrowserAgentBroker } from '../src/broker/server.ts';
11
11
  import { TaskStore } from '../src/broker/task-store.ts';
12
12
  import { ABORT_ERROR_CODE, isAbortError, sleepUnlessAborted } from '../src/broker/abort.ts';
13
- import { createBrowserEvaluateJsTool } from '../src/tools/browser_js_navigation_tools.ts';
13
+ import { createBrowserRunJsTool } from '../src/tools/browser_js_navigation_tools.ts';
14
14
  import { createReadOnlyBrowserTools } from '../src/tools/read_only/index.ts';
15
15
  import type { ResponseFrame } from '../src/broker/protocol.ts';
16
16
 
@@ -19,7 +19,7 @@ import type { ResponseFrame } from '../src/broker/protocol.ts';
19
19
  *
20
20
  * Before this, every browser_* tool ignored the AbortSignal pi passes as the
21
21
  * third argument of execute(), so pressing Escape left the call pending until
22
- * its own timeout (15s for browser_evaluate_js, 30s for browser_run_js, 5min
22
+ * its own timeout (120s for browser_run_js, 5min
23
23
  * for browser_run_task). Each test below asserts we now settle promptly and
24
24
  * report the cancellation as such instead of as a browser failure.
25
25
  */
@@ -50,7 +50,7 @@ async function connectSilentBridge(port: number): Promise<WebSocket> {
50
50
  kind: 'hello',
51
51
  extensionId: 'ext-abort-test',
52
52
  version: '0.1.0',
53
- capabilities: ['browser_evaluate_js', 'browser_get_html'],
53
+ capabilities: ['browser_run_js', 'browser_get_html'],
54
54
  })));
55
55
  socket.once('message', () => resolve(socket));
56
56
  });
@@ -83,7 +83,7 @@ test('broker.request rejects immediately when the caller aborts mid-flight', asy
83
83
  const startedAt = Date.now();
84
84
  // A 30s timeout stands in for browser_run_js: without abort support the
85
85
  // promise below could only settle after those 30 seconds.
86
- const pending = broker.request('browser_evaluate_js', { expression: 'while(true){}' }, {
86
+ const pending = broker.request('browser_run_js', { tab_id: 7, code: 'return document.title;' }, {
87
87
  timeoutMs: 30_000,
88
88
  signal: controller.signal,
89
89
  });
@@ -115,7 +115,7 @@ test('broker.request refuses to send a request that is already cancelled', async
115
115
  controller.abort();
116
116
 
117
117
  const error = await broker
118
- .request('browser_evaluate_js', { expression: '1' }, { signal: controller.signal })
118
+ .request('browser_run_js', { tab_id: 7, code: 'return 1;' }, { signal: controller.signal })
119
119
  .then(() => null, (reason) => reason);
120
120
 
121
121
  assert.ok(error);
@@ -150,7 +150,7 @@ test('waitForBridge stops waiting when the tool call is cancelled', async () =>
150
150
  }
151
151
  });
152
152
 
153
- test('browser_evaluate_js reports cancellation instead of a browser failure', async () => {
153
+ test('browser_run_js reports cancellation instead of a browser failure', async () => {
154
154
  let capturedSignal: AbortSignal | undefined;
155
155
  const broker = {
156
156
  async ensureReady(options: { signal?: AbortSignal } = {}) {
@@ -168,7 +168,7 @@ test('browser_evaluate_js reports cancellation instead of a browser failure', as
168
168
  async request(_type: string, _params: unknown, options: { signal?: AbortSignal } = {}): Promise<ResponseFrame> {
169
169
  return await new Promise((_resolve, reject) => {
170
170
  options.signal?.addEventListener('abort', () => {
171
- const error: any = new Error('browser_evaluate_js was cancelled');
171
+ const error: any = new Error('browser_run_js was cancelled');
172
172
  error.code = ABORT_ERROR_CODE;
173
173
  reject(error);
174
174
  });
@@ -176,9 +176,9 @@ test('browser_evaluate_js reports cancellation instead of a browser failure', as
176
176
  },
177
177
  } as any;
178
178
 
179
- const tool = createBrowserEvaluateJsTool(broker);
179
+ const tool = createBrowserRunJsTool(broker);
180
180
  const controller = new AbortController();
181
- const pending = tool.execute('call-1', { expression: 'document.title' }, controller.signal);
181
+ const pending = tool.execute('call-1', { tab_id: 7, code: 'return document.title;' }, controller.signal);
182
182
  setTimeout(() => controller.abort(), 20);
183
183
 
184
184
  const result: any = await pending;
@@ -220,7 +220,7 @@ test('read-only tools forward the abort signal and label cancellation', async ()
220
220
  assert.ok(htmlTool);
221
221
 
222
222
  const controller = new AbortController();
223
- const pending = htmlTool.execute('call-2', { url: 'https://example.com' }, controller.signal);
223
+ const pending = htmlTool.execute('call-2', { tab_id: 7 }, controller.signal);
224
224
  setTimeout(() => controller.abort(), 20);
225
225
 
226
226
  const result: any = await pending;
@@ -77,8 +77,7 @@ async function freePort(): Promise<number> {
77
77
 
78
78
  interface Scenario {
79
79
  task: string;
80
- params: { tab_id?: number; use_active_tab?: boolean; debugMode?: boolean; timeoutMs: number };
81
- target: { tab_id: number } | { use_active_tab: boolean };
80
+ params: { tab_id: number; debugMode?: boolean; timeoutMs: number };
82
81
  reply: Pick<ResponseFrame, 'ok' | 'data' | 'error'>;
83
82
  status: string;
84
83
  code?: string;
@@ -86,9 +85,8 @@ interface Scenario {
86
85
 
87
86
  const scenarios: Scenario[] = [
88
87
  {
89
- task: 'Read the active page',
90
- params: { timeoutMs: 2_000 },
91
- target: { use_active_tab: true },
88
+ task: 'Read the selected page',
89
+ params: { tab_id: 41, timeoutMs: 2_000 },
92
90
  reply: {
93
91
  ok: true,
94
92
  data: { status: 'done', message: 'Read page', historySummary: { steps: 1, text: '1. Read page' } },
@@ -97,32 +95,28 @@ const scenarios: Scenario[] = [
97
95
  },
98
96
  {
99
97
  task: 'Fail on the selected tab',
100
- params: { tab_id: 42, use_active_tab: true, debugMode: true, timeoutMs: 3_000 },
101
- target: { tab_id: 42 },
98
+ params: { tab_id: 42, debugMode: true, timeoutMs: 3_000 },
102
99
  reply: { ok: true, data: { status: 'error', error: { code: 'E_RUNTIME', message: 'Model failed' } } },
103
100
  status: 'error',
104
101
  code: 'E_RUNTIME',
105
102
  },
106
103
  {
107
104
  task: 'Reject a busy task',
108
- params: { use_active_tab: false, timeoutMs: 2_000 },
109
- target: { use_active_tab: false },
105
+ params: { tab_id: 43, timeoutMs: 2_000 },
110
106
  reply: { ok: false, error: { code: 'E_BUSY', message: 'Already running' } },
111
107
  status: 'rejected',
112
108
  code: 'E_BUSY',
113
109
  },
114
110
  {
115
111
  task: 'Reject a malformed success',
116
- params: { timeoutMs: 2_000 },
117
- target: { use_active_tab: true },
112
+ params: { tab_id: 44, timeoutMs: 2_000 },
118
113
  reply: { ok: true, data: {} },
119
114
  status: 'error',
120
115
  code: 'E_PROTOCOL',
121
116
  },
122
117
  {
123
118
  task: 'Report a bridge failure',
124
- params: { timeoutMs: 2_000 },
125
- target: { use_active_tab: true },
119
+ params: { tab_id: 45, timeoutMs: 2_000 },
126
120
  reply: { ok: false, error: { code: 'E_EXTENSION', message: 'Browser action failed' } },
127
121
  status: 'error',
128
122
  code: 'E_EXTENSION',
@@ -208,7 +202,7 @@ test('secondary task tools forward through the primary bridge and retain history
208
202
  assert.match(result.content[0].text, /History summary:\n1\. Read page/);
209
203
  }
210
204
  const expectedRequest = {
211
- taskId, task: scenario.task, debugMode: scenario.params.debugMode ?? false, ...scenario.target,
205
+ taskId, task: scenario.task, debugMode: scenario.params.debugMode ?? false, tab_id: scenario.params.tab_id,
212
206
  };
213
207
  assert.deepEqual(received.at(-1), expectedRequest);
214
208
  const history = records(result.details.history);
@@ -55,12 +55,14 @@ test('every registered browser implementation declares native output and preserv
55
55
  const broker = new BrowserAgentBroker({ port: 0, taskStore: new TaskStore({ dir }) });
56
56
  try {
57
57
  registerAllTools({ registerTool(tool) { tools.push(tool); } }, { broker });
58
- assert.equal(tools.length, 22);
58
+ assert.equal(tools.length, 21);
59
+ assert.ok(tools.some((tool) => tool.name === 'browser_run_js'));
60
+ assert.ok(!tools.some((tool) => tool.name === 'browser_evaluate_js'));
59
61
  assert.ok(tools.every((tool) => tool.outputSchema), 'no family may miss the registration adapter');
60
62
  for (const name of ['browser_list_tabs', 'browser_get_html', 'browser_get_console_logs', 'browser_run_task']) {
61
63
  const tool = tools.find((item) => item.name === name);
62
64
  assert.ok(tool && typeof tool.execute === 'function');
63
- const result = await Reflect.apply(tool.execute, undefined, ['call', { task: 'sentinel' }, undefined]);
65
+ const result = await Reflect.apply(tool.execute, undefined, ['call', { task: 'sentinel', tab_id: 7 }, undefined]);
64
66
  assert.equal(result.isError, true, name);
65
67
  assert.deepEqual(result.structuredContent, JSON.parse(JSON.stringify(result.details)), name);
66
68
  assert.match(JSON.stringify(result.content), /bridge|broker/i);
@@ -14,7 +14,7 @@ const piBin = process.env.EVERGREEN_PI_BIN || 'pi';
14
14
  const names = ['activate_browser_agent_tools', 'browser_run_task', 'browser_get_task_history',
15
15
  'browser_list_tasks', 'browser_get_screenshot', 'browser_get_html', 'browser_get_dom_info',
16
16
  'browser_get_computed_styles', 'browser_get_console_logs', 'browser_get_network',
17
- 'browser_get_accessibility_tree', 'browser_get_performance_metrics', 'browser_evaluate_js',
17
+ 'browser_get_accessibility_tree', 'browser_get_performance_metrics',
18
18
  'browser_run_js', 'browser_create_tab', 'browser_list_tabs', 'browser_switch_tab',
19
19
  'browser_close_tab', 'browser_navigate', 'browser_reload', 'browser_reload_extension',
20
20
  'browser_wait_for', 'browser_clear_site_data'].sort();
@@ -71,7 +71,7 @@ test('global Pi declares all tools offline, forwards tasks, persists history acr
71
71
  const port = await freePort();
72
72
  const requests: RecordValue[] = [];
73
73
  let selectedTool = 'browser_run_task';
74
- let selectedParams: RecordValue = { task: 'EVERGREEN_TASK_INTENT' };
74
+ let selectedParams: RecordValue = { task: 'EVERGREEN_TASK_INTENT', tab_id: 7 };
75
75
  let bridgeFailure = false;
76
76
  const bridges = new Set<WebSocket>();
77
77
  // A local transport fixture makes declaration/result assertions deterministic;
@@ -118,6 +118,7 @@ test('global Pi declares all tools offline, forwards tasks, persists history acr
118
118
  if (frame.kind !== 'request') return;
119
119
  assert.equal(frame.type, 'browser_run_task');
120
120
  assert.equal(object(frame.params).task, 'EVERGREEN_TASK_INTENT');
121
+ assert.equal(object(frame.params).tab_id, 7);
121
122
  bridge.send(JSON.stringify({ v: 1, kind: 'response', id: frame.id, ok: !bridgeFailure,
122
123
  ...(bridgeFailure ? { error: { code: 'E_RUNTIME', message: 'EVERGREEN_BRIDGE_FAILURE' } }
123
124
  : { data: { status: 'done', message: 'EVERGREEN_BRIDGE_RESULT' } }) }));
@@ -139,7 +140,7 @@ test('global Pi declares all tools offline, forwards tasks, persists history acr
139
140
  assert.match(JSON.stringify(toolEnd(history, selectedTool)), /EVERGREEN_BRIDGE_RESULT/);
140
141
  assert.match(JSON.stringify(requests.at(-1)), /Loaded 2 history event/);
141
142
  selectedTool = 'browser_run_task';
142
- selectedParams = { task: 'EVERGREEN_TASK_INTENT' };
143
+ selectedParams = { task: 'EVERGREEN_TASK_INTENT', tab_id: 7 };
143
144
  bridgeFailure = true;
144
145
  const failed = toolEnd(await runPi(dir, port, 'evergreen/evergreen-fixture', 'Run the task.'), selectedTool);
145
146
  assert.equal(failed.isError, true);
@@ -5,12 +5,10 @@ import type { ResponseFrame } from '../../src/broker/protocol.ts';
5
5
  import {
6
6
  browserClearSiteDataDefinition,
7
7
  browserCreateTabDefinition,
8
- browserEvaluateJsDefinition,
9
8
  browserRunJsDefinition,
10
9
  createBrowserClearSiteDataTool,
11
10
  createBrowserCloseTabTool,
12
11
  createBrowserCreateTabTool,
13
- createBrowserEvaluateJsTool,
14
12
  createBrowserJsNavigationToolFamily,
15
13
  createBrowserNavigateTool,
16
14
  createBrowserReloadExtensionTool,
@@ -19,13 +17,11 @@ import {
19
17
  createBrowserSwitchTabTool,
20
18
  } from '../../src/tools/browser_js_navigation_tools.ts';
21
19
 
22
- test('JavaScript tools disclose AI translation and native-only input instead of arbitrary page execution', () => {
23
- for (const definition of [browserEvaluateJsDefinition, browserRunJsDefinition]) {
24
- assert.match(definition.description, /configured browser AI model/);
25
- assert.match(definition.description, /CDP or Python/);
26
- assert.match(definition.description, /Unsupported/);
27
- assert.match(definition.description, /off-screen/);
28
- }
20
+ test('browser_run_js discloses AI translation and native-only input instead of arbitrary page execution', () => {
21
+ assert.match(browserRunJsDefinition.description, /configured browser AI model/);
22
+ assert.match(browserRunJsDefinition.description, /CDP or Python/);
23
+ assert.match(browserRunJsDefinition.description, /Unsupported/);
24
+ assert.match(browserRunJsDefinition.description, /off-screen/);
29
25
  });
30
26
 
31
27
  function textOf(result: any): string {
@@ -58,7 +54,6 @@ test('tool family builders expose all expected JS/navigation/destructive tools',
58
54
  const broker = createBrokerStub(async () => ({ v: 1, kind: 'response', id: 'unused', ok: true, data: {} }));
59
55
  const family = createBrowserJsNavigationToolFamily(broker).map((tool) => tool.name);
60
56
  assert.deepEqual(family, [
61
- 'browser_evaluate_js',
62
57
  'browser_run_js',
63
58
  'browser_create_tab',
64
59
  'browser_navigate',
@@ -68,13 +63,12 @@ test('tool family builders expose all expected JS/navigation/destructive tools',
68
63
  'browser_reload_extension',
69
64
  'browser_clear_site_data',
70
65
  ]);
71
- assert.equal('url' in (browserEvaluateJsDefinition.parameters as any).properties, false);
72
66
  assert.equal('url' in (browserRunJsDefinition.parameters as any).properties, false);
73
67
  assert.equal('url' in (browserCreateTabDefinition.parameters as any).properties, true);
74
68
  assert.equal((browserClearSiteDataDefinition.parameters as any).properties.types.minItems, 1);
75
69
  });
76
70
 
77
- test('browser_evaluate_js forwards timeout-aware requests, defaults to the active tab, and truncates large payloads', async () => {
71
+ test('browser_run_js forwards timeout-aware requests, uses the explicit tab, and truncates large payloads', async () => {
78
72
  let captured: { type: string; params: any; timeoutMs?: number } | null = null;
79
73
  const broker = createBrokerStub(async (type, params, options) => {
80
74
  captured = { type, params, timeoutMs: options.timeoutMs };
@@ -87,14 +81,14 @@ test('browser_evaluate_js forwards timeout-aware requests, defaults to the activ
87
81
  };
88
82
  });
89
83
 
90
- const tool = createBrowserEvaluateJsTool(broker);
91
- const result = await tool.execute('call-1', { expression: 'document.title', timeout_ms: 1234 });
84
+ const tool = createBrowserRunJsTool(broker);
85
+ const result = await tool.execute('call-1', { tab_id: 7, code: 'return document.title;', timeout_ms: 1234 });
92
86
 
93
87
  const recorded = captured as any;
94
88
  assert.ok(recorded);
95
- assert.equal(recorded.type, 'browser_evaluate_js');
96
- assert.equal(recorded.params.expression, 'document.title');
97
- assert.equal(recorded.params.use_active_tab, true);
89
+ assert.equal(recorded.type, 'browser_run_js');
90
+ assert.equal(recorded.params.code, 'return document.title;');
91
+ assert.equal(recorded.params.tab_id, 7);
98
92
  assert.equal(recorded.timeoutMs, 2234);
99
93
  assert.equal(result.details.ok, true);
100
94
  assert.equal(result.details.truncated, true);
@@ -107,9 +101,8 @@ test('script transport defaults allow 120 seconds for AI translation plus bridge
107
101
  budgets.push(options.timeoutMs ?? 0);
108
102
  return { v: 1, kind: 'response', id: 'script-budget', ok: true, data: { tabId: 7, value: 1 } };
109
103
  });
110
- await createBrowserEvaluateJsTool(broker).execute('evaluate-budget', { expression: '1' });
111
- await createBrowserRunJsTool(broker).execute('program-budget', { code: 'return 1;' });
112
- assert.deepEqual(budgets, [121_000, 121_000]);
104
+ await createBrowserRunJsTool(broker).execute('program-budget', { tab_id: 7, code: 'return 1;' });
105
+ assert.deepEqual(budgets, [121_000]);
113
106
  });
114
107
 
115
108
  test('browser_run_js returns structured bridge failures instead of throwing', async () => {
@@ -122,7 +115,7 @@ test('browser_run_js returns structured bridge failures instead of throwing', as
122
115
  }));
123
116
 
124
117
  const tool = createBrowserRunJsTool(broker);
125
- const result = await tool.execute('call-2', { code: 'return 1;' });
118
+ const result = await tool.execute('call-2', { tab_id: 7, code: 'return 1;' });
126
119
 
127
120
  assert.equal(result.details.ok, false);
128
121
  assert.equal((result.details as any).error.code, 'E_TIMEOUT');
@@ -153,7 +146,7 @@ test('browser_create_tab returns a tab id without defaulting to the active tab',
153
146
  assert.match(textOf(result), /Created tab 15/);
154
147
  });
155
148
 
156
- test('navigation/destructive tool builders pass through successful bridge responses and default relevant tools to the active tab', async () => {
149
+ test('navigation/destructive tool builders pass through successful bridge responses and use explicit tabs', async () => {
157
150
  const calls: Array<{ type: string; params: any }> = [];
158
151
  const broker = createBrokerStub(async (type, params) => {
159
152
  calls.push({ type, params });
@@ -166,10 +159,10 @@ test('navigation/destructive tool builders pass through successful bridge respon
166
159
  };
167
160
  });
168
161
 
169
- const navigate = await createBrowserNavigateTool(broker).execute('call-3', { url: 'https://example.com' });
162
+ const navigate = await createBrowserNavigateTool(broker).execute('call-3', { tab_id: 9, url: 'https://example.com' });
170
163
  assert.equal(navigate.details.ok, true);
171
164
  assert.match(textOf(navigate), /Navigated tab 9/);
172
- assert.equal(calls[0]?.params?.use_active_tab, true);
165
+ assert.equal(calls[0]?.params?.tab_id, 9);
173
166
 
174
167
  const switchTab = await createBrowserSwitchTabTool(broker).execute('call-4', { tab_id: 9 });
175
168
  assert.match(textOf(switchTab), /Switched to tab 9/);
@@ -180,7 +173,7 @@ test('navigation/destructive tool builders pass through successful bridge respon
180
173
  const reload = await createBrowserReloadTool(broker).execute('call-6', { tab_id: 9 });
181
174
  assert.match(textOf(reload), /Reloaded tab 9/);
182
175
 
183
- const clear = await createBrowserClearSiteDataTool(broker).execute('call-7', { origin: 'https://example.com' });
176
+ const clear = await createBrowserClearSiteDataTool(broker).execute('call-7', { tab_id: 9, origin: 'https://example.com' });
184
177
  assert.match(textOf(clear), /Cleared site data/);
185
178
  // Explicit origin/url must NOT be combined with use_active_tab: that would
186
179
  // send conflicting selectors to the bridge.
@@ -188,7 +181,7 @@ test('navigation/destructive tool builders pass through successful bridge respon
188
181
  assert.equal(calls.at(-1)?.params?.origin, 'https://example.com');
189
182
  });
190
183
 
191
- test('browser_clear_site_data defaults to the active tab only when no explicit target is given', async () => {
184
+ test('browser_clear_site_data rejects a missing tab even with an explicit URL', async () => {
192
185
  const calls: Array<{ type: string; params: any }> = [];
193
186
  const broker = createBrokerStub(async (type, params) => {
194
187
  calls.push({ type, params });
@@ -201,10 +194,11 @@ test('browser_clear_site_data defaults to the active tab only when no explicit t
201
194
  };
202
195
  });
203
196
 
204
- await createBrowserClearSiteDataTool(broker).execute('call-c1', {});
205
- assert.equal(calls.at(-1)?.params?.use_active_tab, true);
197
+ const rejected = await createBrowserClearSiteDataTool(broker).execute('call-c1', { url: 'https://example.com/path' });
198
+ assert.equal(rejected.details.ok, false);
199
+ assert.equal(calls.length, 0);
206
200
 
207
- await createBrowserClearSiteDataTool(broker).execute('call-c2', { url: 'https://example.com/path' });
201
+ await createBrowserClearSiteDataTool(broker).execute('call-c2', { tab_id: 9, url: 'https://example.com/path' });
208
202
  assert.equal(calls.at(-1)?.params?.use_active_tab, undefined);
209
203
  assert.equal(calls.at(-1)?.params?.url, 'https://example.com/path');
210
204
  });
@@ -240,7 +234,7 @@ test('navigation tools reject malformed success payloads without required fields
240
234
  const navBroker = createBrokerStub(async () => ({
241
235
  v: 1, kind: 'response', id: 'n', ok: true, data: { url: 'https://example.com' },
242
236
  }));
243
- const navResult = await createBrowserNavigateTool(navBroker).execute('call-n', { url: 'https://example.com' });
237
+ const navResult = await createBrowserNavigateTool(navBroker).execute('call-n', { tab_id: 9, url: 'https://example.com' });
244
238
  assert.equal(navResult.details.ok, false);
245
239
  assert.equal((navResult.details as any).error.code, 'E_PROTOCOL');
246
240
  assert.match(textOf(navResult), /browser_navigate failed/);
@@ -249,7 +243,7 @@ test('navigation tools reject malformed success payloads without required fields
249
243
  const clearBroker = createBrokerStub(async () => ({
250
244
  v: 1, kind: 'response', id: 'c', ok: true, data: { cleared: true },
251
245
  }));
252
- const clearResult = await createBrowserClearSiteDataTool(clearBroker).execute('call-c', { origin: 'https://example.com' });
246
+ const clearResult = await createBrowserClearSiteDataTool(clearBroker).execute('call-c', { tab_id: 9, origin: 'https://example.com' });
253
247
  assert.equal(clearResult.details.ok, false);
254
248
  assert.equal((clearResult.details as any).error.code, 'E_PROTOCOL');
255
249
  });
@@ -50,7 +50,7 @@ test('browser_get_console_logs tool forwards params and returns truncated previe
50
50
  assert.match(textOf(result), /Console log query returned 1 entry/);
51
51
  });
52
52
 
53
- test('browser_get_console_logs defaults to the active tab when no target is provided', async () => {
53
+ test('browser_get_console_logs rejects requests without an explicit tab', async () => {
54
54
  let call: any = null;
55
55
  const tool = createBrowserGetConsoleLogsTool(createBroker({
56
56
  async request(type: string, params: unknown) {
@@ -59,8 +59,9 @@ test('browser_get_console_logs defaults to the active tab when no target is prov
59
59
  },
60
60
  }));
61
61
 
62
- await tool.execute('call-1', { last: 5 });
63
- assert.deepEqual(call.params, { last: 5, use_active_tab: true });
62
+ const result = await tool.execute('call-1', { last: 5 });
63
+ assert.equal(result.details.ok, false);
64
+ assert.equal(call, null);
64
65
  });
65
66
 
66
67
  test('browser_get_network tool returns structured error results on bridge failure', async () => {
@@ -70,7 +71,7 @@ test('browser_get_network tool returns structured error results on bridge failur
70
71
  },
71
72
  }));
72
73
 
73
- const result = await tool.execute('call-1', { filter: { failed_only: true } });
74
+ const result = await tool.execute('call-1', { tab_id: 7, filter: { failed_only: true } });
74
75
  assert.equal(result.details.ok, false);
75
76
  assert.equal((result.details as any).error.code, 'E_BRIDGE_DISCONNECTED');
76
77
  assert.equal((result.details as any).error.message, 'socket dropped');
@@ -84,7 +85,7 @@ test('browser_get_console_logs tool returns structured error results on bridge f
84
85
  },
85
86
  }));
86
87
 
87
- const result = await tool.execute('call-1', { last: 5 });
88
+ const result = await tool.execute('call-1', { tab_id: 7, last: 5 });
88
89
  assert.equal(result.details.ok, false);
89
90
  assert.equal((result.details as any).error.code, 'E_BRIDGE_DISCONNECTED');
90
91
  assert.match(textOf(result), /browser_get_console_logs failed: socket dropped/);
@@ -93,8 +94,8 @@ test('browser_get_console_logs tool returns structured error results on bridge f
93
94
  test('buffered observability tool-definition builders expose both tools', () => {
94
95
  const definitions = createBufferedObservabilityToolDefinitions(createBroker());
95
96
  assert.deepEqual(Object.keys(definitions).sort(), ['browser_get_console_logs', 'browser_get_network']);
96
- assert.match(definitions.browser_get_network.description, /defaults to the active tab/i);
97
+ assert.match(definitions.browser_get_network.description, /tab_id/i);
97
98
  assert.match(definitions.browser_get_network.description, /Always pass filters/i);
98
- assert.match(definitions.browser_get_console_logs.description, /defaults to the active tab/i);
99
+ assert.match(definitions.browser_get_console_logs.description, /tab_id/i);
99
100
  assert.match(definitions.browser_get_console_logs.description, /Prefer passing filters/i);
100
101
  });
@@ -36,6 +36,17 @@ test('read-only tool family exports exactly the planned tool names', () => {
36
36
  ]);
37
37
  });
38
38
 
39
+ test('browser_get_dom_info rejects URL-only and URL-plus-tab reads without sending a bridge request', async () => {
40
+ const tools = createReadOnlyBrowserToolMap(createBrokerHarness(async () => assert.fail('must not contact bridge')));
41
+ for (const target of [{}, { tab_id: 7 }]) {
42
+ const result = await tools.get('browser_get_dom_info')!.execute('invalid-target', {
43
+ ...target, url: 'https://search.test/', selector: '.result',
44
+ });
45
+ assert.equal(result.details.ok, false);
46
+ assert.equal((result.details.error as any).code, 'E_INVALID_ARGS');
47
+ }
48
+ });
49
+
39
50
  test('browser_get_html truncates oversized HTML and spills the full output to a temp file', async () => {
40
51
  const tools = createReadOnlyBrowserToolMap(createBrokerHarness(async (type) => {
41
52
  assert.equal(type, 'browser_get_html');
@@ -51,7 +62,7 @@ test('browser_get_html truncates oversized HTML and spills the full output to a
51
62
  };
52
63
  }));
53
64
 
54
- const result = await tools.get('browser_get_html')!.execute('call-1', { selector: '#app' });
65
+ const result = await tools.get('browser_get_html')!.execute('call-1', { tab_id: 7, selector: '#app' });
55
66
  assert.equal(result.details.ok, true);
56
67
  assert.equal(result.details.truncated, true);
57
68
  assert.match(textOf(result), /Full output:/);
@@ -82,7 +93,7 @@ test('browser_get_screenshot returns screenshots as image content and never expo
82
93
  };
83
94
  }));
84
95
 
85
- const result = await tools.get('browser_get_screenshot')!.execute('call-1', {});
96
+ const result = await tools.get('browser_get_screenshot')!.execute('call-1', { tab_id: 7 });
86
97
  assert.equal(result.details.ok, true);
87
98
  assert.equal(result.details.imageAttached, true);
88
99
  assert.equal(result.details.spilledToFile, true);
@@ -103,7 +114,7 @@ test('browser_wait_for gives the bridge enough time to finish the requested wait
103
114
  const tools = createReadOnlyBrowserToolMap(createBrokerHarness(async (type, params, options) => {
104
115
  assert.equal(type, 'browser_wait_for');
105
116
  seenTimeout = options?.timeoutMs;
106
- assert.deepEqual(params, { selector: '#ready', timeout_ms: 40_000 });
117
+ assert.deepEqual(params, { tab_id: 7, selector: '#ready', timeout_ms: 40_000 });
107
118
  return {
108
119
  ok: true,
109
120
  id: 'req-3',
@@ -116,7 +127,7 @@ test('browser_wait_for gives the bridge enough time to finish the requested wait
116
127
  };
117
128
  }));
118
129
 
119
- const result = await tools.get('browser_wait_for')!.execute('call-1', { selector: '#ready', timeout_ms: 40_000 });
130
+ const result = await tools.get('browser_wait_for')!.execute('call-1', { tab_id: 7, selector: '#ready', timeout_ms: 40_000 });
120
131
  assert.equal(result.details.ok, true);
121
132
  assert.equal(seenTimeout, 41_500);
122
133
  assert.match(textOf(result), /matched/);
@@ -132,7 +143,7 @@ test('bridge transport failures become structured tool results', async () => {
132
143
  },
133
144
  } as any);
134
145
 
135
- const result = await tools.get('browser_get_performance_metrics')!.execute('call-1', {});
146
+ const result = await tools.get('browser_get_performance_metrics')!.execute('call-1', { tab_id: 7 });
136
147
  assert.equal(result.details.ok, false);
137
148
  assert.equal((result.details.error as any).code, 'E_TIMEOUT');
138
149
  assert.match(textOf(result), /failed: boom/);
@@ -148,7 +159,7 @@ test('plain broker timeout errors are surfaced as E_TIMEOUT instead of bridge di
148
159
  },
149
160
  } as any);
150
161
 
151
- const result = await tools.get('browser_get_html')!.execute('call-1', {});
162
+ const result = await tools.get('browser_get_html')!.execute('call-1', { tab_id: 7 });
152
163
  assert.equal(result.details.ok, false);
153
164
  assert.equal((result.details.error as any).code, 'E_TIMEOUT');
154
165
  });
@@ -163,7 +174,7 @@ test('browser_get_html rejects malformed success payloads without html/content',
163
174
  data: { url: 'https://example.com' },
164
175
  })));
165
176
 
166
- const result = await tools.get('browser_get_html')!.execute('call-1', {});
177
+ const result = await tools.get('browser_get_html')!.execute('call-1', { tab_id: 7 });
167
178
  assert.equal(result.details.ok, false);
168
179
  assert.equal((result.details.error as any).code, 'E_PROTOCOL');
169
180
  assert.match(textOf(result), /did not include html/i);
@@ -181,7 +192,7 @@ test('browser_get_screenshot rejects malformed success payloads without image da
181
192
  },
182
193
  })));
183
194
 
184
- const result = await tools.get('browser_get_screenshot')!.execute('call-1', {});
195
+ const result = await tools.get('browser_get_screenshot')!.execute('call-1', { tab_id: 7 });
185
196
  assert.equal(result.details.ok, false);
186
197
  assert.equal((result.details.error as any).code, 'E_INTERNAL');
187
198
  assert.match(textOf(result), /did not include image data/);
@@ -201,7 +212,7 @@ test('browser_get_performance_metrics uses a longer timeout when web vitals are
201
212
  };
202
213
  }));
203
214
 
204
- const result = await tools.get('browser_get_performance_metrics')!.execute('call-1', { include: ['web_vitals'] });
215
+ const result = await tools.get('browser_get_performance_metrics')!.execute('call-1', { tab_id: 7, include: ['web_vitals'] });
205
216
  assert.equal(result.details.ok, true);
206
217
  assert.equal(seenTimeout, 27_500);
207
218
  });
@@ -96,7 +96,7 @@ test('browser_run_task preserves a manual CAPTCHA pause without claiming complet
96
96
  });
97
97
  try {
98
98
  const tools = createToolHarness(broker);
99
- const result = await tools.get('browser_run_task').execute('manual-captcha', { task: 'Open the form' });
99
+ const result = await tools.get('browser_run_task').execute('manual-captcha', { tab_id: 7, task: 'Open the form' });
100
100
  assert.equal(result.details.ok, true);
101
101
  assert.equal(result.details.success, false);
102
102
  assert.equal(result.details.status, 'paused');
@@ -110,7 +110,7 @@ test('browser_run_task preserves a manual CAPTCHA pause without claiming complet
110
110
  }
111
111
  });
112
112
 
113
- test('browser_run_task happy path targets the active tab and records useful history', async () => {
113
+ test('browser_run_task happy path targets an explicit tab and records useful history', async () => {
114
114
  const { broker } = await createBroker();
115
115
  let receivedRequest: any;
116
116
  const socket = await connectBridge(broker, async (frame, ws) => {
@@ -135,7 +135,7 @@ test('browser_run_task happy path targets the active tab and records useful hist
135
135
  const tools = createToolHarness(broker);
136
136
 
137
137
  try {
138
- const runResult = await tools.get('browser_run_task').execute('call-1', { task: 'Open example.com' });
138
+ const runResult = await tools.get('browser_run_task').execute('call-1', { tab_id: 7, task: 'Open example.com' });
139
139
  assert.match(textOf(runResult), /completed/i);
140
140
  assert.match(textOf(runResult), /Success: yes/i);
141
141
  assert.match(textOf(runResult), /History summary:/i);
@@ -143,14 +143,14 @@ test('browser_run_task happy path targets the active tab and records useful hist
143
143
  assert.equal(runResult.details.success, true);
144
144
  assert.equal(runResult.details.status, 'done');
145
145
  assert.equal(runResult.details.historySummary.steps, 2);
146
- assert.equal(receivedRequest.use_active_tab, true);
147
- assert.equal(receivedRequest.tab_id, undefined);
146
+ assert.equal(receivedRequest.tab_id, 7);
147
+ assert.equal(receivedRequest.use_active_tab, undefined);
148
148
  const taskId = String(runResult.details.taskId);
149
149
 
150
150
  const historyResult = await tools.get('browser_get_task_history').execute('call-2', { taskId });
151
151
  assert.equal(historyResult.details.ok, true);
152
152
  assert.equal(historyResult.details.history.length, 2);
153
- assert.equal(historyResult.details.history[0].request.use_active_tab, true);
153
+ assert.equal(historyResult.details.history[0].request.tab_id, 7);
154
154
  assert.equal(historyResult.details.summary.status, 'done');
155
155
 
156
156
  const listResult = await tools.get('browser_list_tasks').execute('call-3', { limit: 10 });
@@ -226,10 +226,10 @@ test('concurrent browser_run_task attempts return E_BUSY without crashing the ca
226
226
  const tools = createToolHarness(broker);
227
227
 
228
228
  try {
229
- const firstRun = tools.get('browser_run_task').execute('call-1', { task: 'Task one' });
229
+ const firstRun = tools.get('browser_run_task').execute('call-1', { tab_id: 7, task: 'Task one' });
230
230
  await entered;
231
231
 
232
- const secondRun = await tools.get('browser_run_task').execute('call-2', { task: 'Task two' });
232
+ const secondRun = await tools.get('browser_run_task').execute('call-2', { tab_id: 7, task: 'Task two' });
233
233
  assert.equal(secondRun.details.ok, false);
234
234
  assert.equal(secondRun.details.error.code, 'E_BUSY');
235
235
  assert.match(textOf(secondRun), /rejected/i);
@@ -276,7 +276,7 @@ test('browser_run_task treats runtime error payloads as failures instead of succ
276
276
  const tools = createToolHarness(broker);
277
277
 
278
278
  try {
279
- const result = await tools.get('browser_run_task').execute('call-1', { task: 'Fail please' });
279
+ const result = await tools.get('browser_run_task').execute('call-1', { tab_id: 7, task: 'Fail please' });
280
280
  assert.equal(result.details.ok, false);
281
281
  assert.equal(result.details.status, 'error');
282
282
  assert.equal(result.details.error.code, 'E_RUNTIME');
@@ -319,7 +319,7 @@ test('browser_run_task rejects malformed success payloads without a recognized t
319
319
  const tools = createToolHarness(broker);
320
320
 
321
321
  try {
322
- const result = await tools.get('browser_run_task').execute('call-1', { task: 'Malformed payload' });
322
+ const result = await tools.get('browser_run_task').execute('call-1', { tab_id: 7, task: 'Malformed payload' });
323
323
  assert.equal(result.details.ok, false);
324
324
  assert.equal(result.details.status, 'error');
325
325
  assert.equal(result.details.error.code, 'E_PROTOCOL');
@@ -399,7 +399,7 @@ test('browser_run_task surfaces bridge disconnect as a structured error result',
399
399
  const tools = createToolHarness(broker);
400
400
 
401
401
  try {
402
- const result = await tools.get('browser_run_task').execute('call-1', { task: 'Disconnect me' });
402
+ const result = await tools.get('browser_run_task').execute('call-1', { tab_id: 7, task: 'Disconnect me' });
403
403
  assert.equal(result.details.ok, false);
404
404
  assert.equal(result.details.status, 'error');
405
405
  assert.equal(result.details.error.code, 'E_BRIDGE_DISCONNECTED');