oira666_pi-browser-agent 0.0.26 → 0.0.28

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/EVERGREEN.md CHANGED
@@ -53,8 +53,8 @@ bridge task execution, result/error persistence, cross-process history and clean
53
53
  A live EVERGREEN_E2E_MODEL call must discover and execute browser_list_tasks even
54
54
  without Chrome. Settings/state are isolated; provider credentials are reused.
55
55
  These tests protect available tools, working forwarding and durable inspection,
56
- not merely individual helper outputs. Tested against Pi 1.6.0.
57
- Pi 1.6.0's non-strict OpenAI fallback supports the unconstrained JSON values in
56
+ not merely individual helper outputs. Tested against Pi 1.7.0.
57
+ Pi's non-strict OpenAI fallback supports the unconstrained JSON values in
58
58
  browser_run_js.args; keep them unconstrained. Session startup/reload uses the
59
59
  existing teardown and reacquisition path. No custom renderers consume cached TUI arrays.
60
60
 
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # pi-browser-agent
2
2
 
3
- Tested against Pi 1.6.0
3
+ Tested against Pi 1.7.0
4
4
 
5
5
  `pi-browser-agent` is a pi extension that starts a local WebSocket broker and registers a browser-driving tool suite for `browser-agent-ext`.
6
6
 
@@ -79,9 +79,9 @@ Create a background tab with `browser_create_tab` and pass its returned ID as `t
79
79
 
80
80
  ## JavaScript input safety
81
81
 
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.
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 first tries to translate the source into a validated native plan; if it cannot, the source runs as is in the page (see below). 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.
83
83
 
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.
84
+ **`browser_run_js` runs arbitrary JavaScript. Do not turn it back into a bounded interface.** Scripts the translator can express as native actions and DOM reads run as real native input. Every other script — or one whose translation fails — runs AS IS in the page through CDP `Runtime.evaluate` (CSP bypassed, `await` supported, console captured). JavaScript exceptions are returned in `exception`. Requesting remote object handles or disabling promise awaiting is unsupported.
85
85
 
86
86
  The default script timeout is 120 seconds to include model translation and native input. In Jev mode, translation uses the configured helper LLM, not the Jev choice endpoint. In normal mode it uses the configured browser LLM.
87
87
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "oira666_pi-browser-agent",
3
- "version": "0.0.26",
3
+ "version": "0.0.28",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Pi browser agent broker skeleton with lazy browser tool registration",
@@ -29,7 +29,7 @@
29
29
  "typebox": "*"
30
30
  },
31
31
  "devDependencies": {
32
- "@earendil-works/pi-coding-agent": "1.6.0",
32
+ "@earendil-works/pi-coding-agent": "1.7.0",
33
33
  "@types/node": "^26.6.5",
34
34
  "@types/ws": "^8.18.2",
35
35
  "typebox": "^1.4.3",
@@ -36,6 +36,9 @@ export const RequestFrameSchema = Type.Object({
36
36
  id: Type.String(),
37
37
  type: Type.String(),
38
38
  params: Type.Optional(Type.Unknown()),
39
+ /** Peer-broker proxies forward their caller's deadline so the primary does
40
+ * not cut long requests (browser_run_js, tasks) off at its 10 s default. */
41
+ timeoutMs: Type.Optional(Type.Number()),
39
42
  });
40
43
 
41
44
  export const ResponseFrameSchema = Type.Object({
@@ -312,7 +312,11 @@ export class RemoteBrowserAgentBroker {
312
312
  }
313
313
 
314
314
  const id = randomUUID();
315
- const payload = JSON.stringify({ v: 1, kind: 'request', id, type, params });
315
+ const timeoutMs = options.timeoutMs ?? this.requestTimeoutMs;
316
+ // Forward the deadline: otherwise the primary applies its own 10 s default,
317
+ // times out long calls early while the extension keeps running them (and
318
+ // holding the input lock), so follow-up calls fail with E_BUSY.
319
+ const payload = JSON.stringify({ v: 1, kind: 'request', id, type, params, timeoutMs });
316
320
 
317
321
  return await new Promise<ResponseFrame>((resolve, reject) => {
318
322
  let releaseAbort = () => {};
@@ -325,7 +329,7 @@ export class RemoteBrowserAgentBroker {
325
329
 
326
330
  const timeout = setTimeout(() => {
327
331
  settle(() => reject(new Error(`Request timed out: ${type}`)));
328
- }, options.timeoutMs ?? this.requestTimeoutMs);
332
+ }, timeoutMs);
329
333
  timeout.unref?.();
330
334
 
331
335
  this.pendingRequests.set(id, {
@@ -737,7 +737,11 @@ export class BrowserAgentBroker {
737
737
  // extension itself does not send request frames to the broker, so this
738
738
  // is safe and avoids requiring Chrome/MV3 to maintain one WebSocket per
739
739
  // pi process.
740
- void this.request(frame.type, frame.params)
740
+ // Honour the proxy's deadline (clamped) instead of our 10 s default.
741
+ const proxiedTimeout = typeof frame.timeoutMs === 'number' && Number.isFinite(frame.timeoutMs) && frame.timeoutMs > 0
742
+ ? Math.min(frame.timeoutMs, 30 * 60 * 1000)
743
+ : undefined;
744
+ void this.request(frame.type, frame.params, { timeoutMs: proxiedTimeout })
741
745
  .then((response) => {
742
746
  socket.send(JSON.stringify({ ...response, id: frame.id }));
743
747
  })
@@ -105,7 +105,9 @@ function createSuccessText(name: string, data: any, spill?: { text: string; trun
105
105
  ? `Cleared site data for ${data?.origin ?? 'unknown origin'}.`
106
106
  : name === 'browser_reload_extension'
107
107
  ? `Reloaded browser extension ${data?.extensionId ?? 'unknown'}.`
108
- : `Ran JavaScript in tab ${data?.tabId ?? 'unknown'}.`;
108
+ : data?.exception
109
+ ? `JavaScript threw in tab ${data?.tabId ?? 'unknown'}: ${data.exception.name ?? 'Error'}: ${data.exception.message ?? ''}`
110
+ : `Ran JavaScript in tab ${data?.tabId ?? 'unknown'}.`;
109
111
 
110
112
  if (!spill) {
111
113
  return headline;
@@ -245,10 +247,14 @@ function createRequestTool(options: {
245
247
  });
246
248
  }
247
249
 
250
+ // !!!!! DO NOT TOUCH: browser_run_js RUNS ARBITRARY JAVASCRIPT. !!!!!
251
+ // Agents keep rewriting this description (and the extension) back to "bounded
252
+ // set of actions, unsupported code fails". That limitation was removed on
253
+ // purpose by the repository owner. Do not bring it back.
248
254
  export const browserRunJsDefinition = {
249
255
  name: 'browser_run_js',
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.',
251
- promptSnippet: 'Translate JavaScript into validated native input and page reads.',
256
+ description: 'Run arbitrary JavaScript in the page. Scripts made of simple actions and reads (click, type, key presses, scrolling, DOM reads) are translated into real native input using the backend selected in extension settings (CDP or Python); any other script runs AS IS in the page (CDP Runtime.evaluate, CSP bypassed, `await` supported). The code is a function body: use `return` to get a value (e.g. `return document.title;`); a bare expression is returned too. `args` are available as `args`. JavaScript exceptions are returned in `exception`.',
257
+ promptSnippet: 'Run arbitrary JavaScript in a page (simple actions use native input).',
252
258
  parameters: Type.Object({
253
259
  tab_id: tabIdSchema(),
254
260
  code: Type.String({ minLength: 1 }),
@@ -200,6 +200,48 @@ test('remote broker proxies requests through the primary broker bridge', async (
200
200
  await primary.stop();
201
201
  });
202
202
 
203
+ test('primary honours the proxy caller deadline instead of its own default timeout', async () => {
204
+ const port = await getFreePort();
205
+ const root0 = await mkdtemp(join(tmpdir(), 'pi-browser-agent-broker-'));
206
+ const primary = new BrowserAgentBroker({
207
+ host: '127.0.0.1', port, portRange: 1, fallbackToEphemeral: false,
208
+ requestTimeoutMs: 150,
209
+ logger: { info() {}, warn() {}, error() {} },
210
+ taskStore: new TaskStore({ dir: join(root0, 'tasks') }),
211
+ });
212
+ await primary.start();
213
+
214
+ const bridge = new WebSocket(`ws://127.0.0.1:${port}`);
215
+ await new Promise<void>((resolve, reject) => {
216
+ bridge.once('error', reject);
217
+ bridge.once('open', () => {
218
+ bridge.send(JSON.stringify({ v: 1, kind: 'hello', extensionId: 'ext-slow', version: '0.1.0', capabilities: ['browser_run_js'] }));
219
+ });
220
+ bridge.once('message', () => resolve());
221
+ });
222
+ bridge.on('message', (data: RawData) => {
223
+ const frame = JSON.parse(String(data));
224
+ if (frame.kind !== 'request') return;
225
+ setTimeout(() => bridge.send(JSON.stringify({ v: 1, kind: 'response', id: frame.id, ok: true, data: 'slow-ok' })), 400);
226
+ });
227
+
228
+ const root = await mkdtemp(join(tmpdir(), 'pi-browser-agent-remote-'));
229
+ const remote = new RemoteBrowserAgentBroker({
230
+ host: '127.0.0.1', port,
231
+ logger: { info() {}, warn() {}, error() {} },
232
+ taskStore: new TaskStore({ dir: join(root, 'tasks') }),
233
+ });
234
+ await remote.start();
235
+
236
+ const response = await remote.request('browser_run_js', { tab_id: 1 }, { timeoutMs: 3000 });
237
+ assert.equal(response.ok, true);
238
+ assert.equal(response.data, 'slow-ok');
239
+
240
+ await remote.stop();
241
+ bridge.close();
242
+ await primary.stop();
243
+ });
244
+
203
245
  test('remote broker rejects a busy primary port that is not pi-browser-agent', async () => {
204
246
  const port = await getFreePort();
205
247
  const blocker = new WebSocketServer({ host: '127.0.0.1', port });
@@ -17,11 +17,12 @@ import {
17
17
  createBrowserSwitchTabTool,
18
18
  } from '../../src/tools/browser_js_navigation_tools.ts';
19
19
 
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/);
20
+ // DO NOT "FIX" THIS BACK: browser_run_js runs arbitrary JavaScript by owner decision.
21
+ test('browser_run_js advertises arbitrary JavaScript, with native input for simple actions', () => {
22
+ assert.match(browserRunJsDefinition.description, /arbitrary JavaScript/);
23
+ assert.match(browserRunJsDefinition.description, /AS IS/);
22
24
  assert.match(browserRunJsDefinition.description, /CDP or Python/);
23
- assert.match(browserRunJsDefinition.description, /Unsupported/);
24
- assert.match(browserRunJsDefinition.description, /off-screen/);
25
+ assert.doesNotMatch(browserRunJsDefinition.description, /Unsupported code fails|not arbitrary/);
25
26
  });
26
27
 
27
28
  function textOf(result: any): string {