oira666_pi-browser-agent 0.0.16 → 0.0.17

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "oira666_pi-browser-agent",
3
- "version": "0.0.16",
3
+ "version": "0.0.17",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Pi browser agent broker skeleton with lazy browser tool registration",
@@ -17,10 +17,13 @@
17
17
  "test": "node --test ./tests/*.test.ts ./tests/tools/*.test.ts"
18
18
  },
19
19
  "dependencies": {
20
- "@sinclair/typebox": "^0.34.41",
21
20
  "ws": "^8.18.3"
22
21
  },
22
+ "peerDependencies": {
23
+ "@sinclair/typebox": "*"
24
+ },
23
25
  "devDependencies": {
26
+ "@sinclair/typebox": "^0.34.41",
24
27
  "@types/node": "^25.6.0",
25
28
  "@types/ws": "^8.18.1",
26
29
  "typescript": "^5.9.3"
@@ -1,13 +1,12 @@
1
1
  import type { ProbeResult, ResponseFrame } from './protocol.ts';
2
2
  import type { EnsureReadyOptions } from './server.ts';
3
3
  import type { TaskStore } from './task-store.ts';
4
- import type { BrokerRequestOptions } from './abort.ts';
5
4
 
6
5
  /** The slice of the broker API that the browser_* tools actually consume. */
7
6
  export interface BrokerLike {
8
7
  ensureReady?: (options?: EnsureReadyOptions) => Promise<void>;
9
8
  probeConnectivity: () => ProbeResult;
10
- request: (type: string, params: unknown, options?: BrokerRequestOptions) => Promise<ResponseFrame>;
9
+ request: (type: string, params: unknown, options?: { timeoutMs?: number }) => Promise<ResponseFrame>;
11
10
  taskStore: TaskStore;
12
11
  }
13
12
 
@@ -140,7 +139,7 @@ export class LazyBrokerHandle implements BrokerLike {
140
139
  return probe;
141
140
  }
142
141
 
143
- async request(type: string, params: unknown, options: BrokerRequestOptions = {}): Promise<ResponseFrame> {
142
+ async request(type: string, params: unknown, options: { timeoutMs?: number } = {}): Promise<ResponseFrame> {
144
143
  if (this.disposed) {
145
144
  throw new Error('E_BRIDGE_DISCONNECTED');
146
145
  }
@@ -19,13 +19,6 @@ import {
19
19
  type BrokerLogger,
20
20
  type EnsureReadyOptions,
21
21
  } from './server.ts';
22
- import {
23
- abortError,
24
- onAbort,
25
- sleepUnlessAborted,
26
- throwIfAborted,
27
- type BrokerRequestOptions,
28
- } from './abort.ts';
29
22
 
30
23
  interface PendingRequest {
31
24
  resolve: (value: ResponseFrame) => void;
@@ -142,7 +135,7 @@ export class RemoteBrowserAgentBroker {
142
135
  // Poll the primary's probe for the same budget a local broker would wait,
143
136
  // so a tool call arriving during a reconnect window succeeds instead of
144
137
  // reporting a hard "connection is down".
145
- await this.waitForRemoteBridge(options.waitForBridgeMs ?? this.defaultRemoteBridgeWaitMs(), options.signal);
138
+ await this.waitForRemoteBridge(options.waitForBridgeMs ?? this.defaultRemoteBridgeWaitMs());
146
139
  }
147
140
 
148
141
  /** Full budget only when the primary has actually seen a bridge at some point.
@@ -155,13 +148,13 @@ export class RemoteBrowserAgentBroker {
155
148
  return this.remoteProbe?.bridgeEverConnected === false ? COLD_BRIDGE_WAIT_MS : DEFAULT_BRIDGE_WAIT_MS;
156
149
  }
157
150
 
158
- private async waitForRemoteBridge(timeoutMs: number, signal?: AbortSignal): Promise<boolean> {
151
+ private async waitForRemoteBridge(timeoutMs: number): Promise<boolean> {
159
152
  if (this.probeConnectivity().bridgeConnected) {
160
153
  this.coldBridgeMisses = 0;
161
154
  this.coldBridgeSince = null;
162
155
  return true;
163
156
  }
164
- if (timeoutMs <= 0 || signal?.aborted) return false;
157
+ if (timeoutMs <= 0) return false;
165
158
  const deadline = Date.now() + timeoutMs;
166
159
  // Every sub-step below can block for up to ~1.5s, so the budget is
167
160
  // re-checked before each of them. Checking only at the top of the loop let a
@@ -170,10 +163,9 @@ export class RemoteBrowserAgentBroker {
170
163
  while (Date.now() < deadline) {
171
164
  const sleepMs = Math.min(250, deadline - Date.now());
172
165
  if (sleepMs > 0) {
173
- // Wakes immediately on Escape instead of finishing the tick.
174
- await sleepUnlessAborted(sleepMs, signal);
166
+ await new Promise((resolve) => setTimeout(resolve, sleepMs).unref?.());
175
167
  }
176
- if (this.stopped || signal?.aborted) return false;
168
+ if (this.stopped) return false;
177
169
  if (Date.now() >= deadline) break;
178
170
  try {
179
171
  await this.ensureConnected();
@@ -189,15 +181,14 @@ export class RemoteBrowserAgentBroker {
189
181
  if (Date.now() >= deadline) break;
190
182
  const promoted = await this.promoteOrReconnect();
191
183
  if (promoted) {
192
- const found = await promoted.waitForBridge(Math.max(0, deadline - Date.now()), signal);
193
- if (!signal?.aborted) this.recordBridgeWaitOutcome(found, timeoutMs);
184
+ const found = await promoted.waitForBridge(Math.max(0, deadline - Date.now()));
185
+ this.recordBridgeWaitOutcome(found, timeoutMs);
194
186
  return found;
195
187
  }
196
188
  }
197
189
  }
198
190
  const connected = this.probeConnectivity().bridgeConnected;
199
- // A budget cut short by Escape is not evidence that the browser is cold.
200
- if (!signal?.aborted) this.recordBridgeWaitOutcome(connected, timeoutMs);
191
+ this.recordBridgeWaitOutcome(connected, timeoutMs);
201
192
  return connected;
202
193
  }
203
194
 
@@ -246,16 +237,20 @@ export class RemoteBrowserAgentBroker {
246
237
  }
247
238
  }
248
239
 
249
- async stop(): Promise<void> {
250
- this.stopped = true;
251
- this.cancelHealTimer();
252
- this.rejectPendingRequests(new Error('E_BRIDGE_DISCONNECTED'));
253
- const connecting = this.connectPromise;
240
+ private closeSocket(): void {
254
241
  const socket = this.socket;
255
242
  this.socket = null;
256
243
  if (socket) {
257
244
  try { socket.close(); } catch { /* ignore */ }
258
245
  }
246
+ }
247
+
248
+ async stop(): Promise<void> {
249
+ this.stopped = true;
250
+ this.cancelHealTimer();
251
+ this.rejectPendingRequests(new Error('E_BRIDGE_DISCONNECTED'));
252
+ const connecting = this.connectPromise;
253
+ this.closeSocket();
259
254
  // A connect or promotion already in flight can otherwise publish a socket
260
255
  // or listener after stop() returns. Their completion paths observe
261
256
  // `stopped` and tear down instead of publishing.
@@ -267,11 +262,8 @@ export class RemoteBrowserAgentBroker {
267
262
  if (promotion) {
268
263
  try { await promotion; } catch { /* promotion failure is already logged */ }
269
264
  }
270
- const lateSocket = this.socket;
271
- this.socket = null;
272
- if (lateSocket) {
273
- try { lateSocket.close(); } catch { /* ignore */ }
274
- }
265
+ // Read the socket again after async work, which may have replaced it.
266
+ this.closeSocket();
275
267
  this.unsubscribePromoted?.();
276
268
  this.unsubscribePromoted = null;
277
269
  this.bridgeStateListeners.clear();
@@ -283,9 +275,8 @@ export class RemoteBrowserAgentBroker {
283
275
  }
284
276
  }
285
277
 
286
- async request(type: string, params: unknown, options: BrokerRequestOptions = {}): Promise<ResponseFrame> {
278
+ async request(type: string, params: unknown, options: { timeoutMs?: number } = {}): Promise<ResponseFrame> {
287
279
  if (this.stopped) throw new Error('E_BRIDGE_DISCONNECTED');
288
- throwIfAborted(options.signal, type);
289
280
  if (this.promotedBroker) {
290
281
  return await this.promotedBroker.request(type, params, options);
291
282
  }
@@ -309,34 +300,19 @@ export class RemoteBrowserAgentBroker {
309
300
  const payload = JSON.stringify({ v: 1, kind: 'request', id, type, params });
310
301
 
311
302
  return await new Promise<ResponseFrame>((resolve, reject) => {
312
- let releaseAbort = () => {};
313
- const settle = (fn: () => void) => {
314
- this.pendingRequests.delete(id);
315
- clearTimeout(timeout);
316
- releaseAbort();
317
- fn();
318
- };
319
-
320
303
  const timeout = setTimeout(() => {
321
- settle(() => reject(new Error(`Request timed out: ${type}`)));
304
+ this.pendingRequests.delete(id);
305
+ reject(new Error(`Request timed out: ${type}`));
322
306
  }, options.timeoutMs ?? this.requestTimeoutMs);
323
307
  timeout.unref?.();
324
308
 
325
- this.pendingRequests.set(id, {
326
- resolve: (frame) => settle(() => resolve(frame)),
327
- reject: (error) => settle(() => reject(error)),
328
- timeout,
329
- });
330
-
331
- releaseAbort = onAbort(options.signal, () => {
332
- settle(() => reject(abortError(type, options.signal)));
333
- });
334
- if (options.signal?.aborted) return;
335
-
309
+ this.pendingRequests.set(id, { resolve, reject, timeout });
336
310
  try {
337
311
  socket.send(payload);
338
312
  } catch (error) {
339
- settle(() => reject(error instanceof Error ? error : new Error(String(error))));
313
+ clearTimeout(timeout);
314
+ this.pendingRequests.delete(id);
315
+ reject(error instanceof Error ? error : new Error(String(error)));
340
316
  }
341
317
  });
342
318
  }
@@ -16,13 +16,6 @@ import {
16
16
  type ResponseFrame,
17
17
  } from './protocol.ts';
18
18
  import { TaskStore } from './task-store.ts';
19
- import {
20
- abortError,
21
- onAbort,
22
- throwIfAborted,
23
- type BrokerRequestOptions,
24
- type AbortableOptions,
25
- } from './abort.ts';
26
19
 
27
20
  export interface BrokerLogger {
28
21
  info?: (...args: unknown[]) => void;
@@ -74,7 +67,7 @@ export interface BridgeStateEvent {
74
67
 
75
68
  export type BridgeStateListener = (state: BridgeStateEvent) => void;
76
69
 
77
- export interface EnsureReadyOptions extends AbortableOptions {
70
+ export interface EnsureReadyOptions {
78
71
  /** Override the bridge wait budget. 0 disables waiting entirely. */
79
72
  waitForBridgeMs?: number;
80
73
  }
@@ -265,12 +258,8 @@ export class BrowserAgentBroker {
265
258
  // failing a tool call that arrived mid-reconnect. This is what makes the
266
259
  // integration self-healing from the agent's point of view.
267
260
  const budget = this.resolveBridgeWaitMs(options);
268
- const connected = await this.waitForBridge(budget, options.signal);
269
- // A wait cut short by Escape says nothing about whether the browser is
270
- // cold, so it must not feed the cold-bridge memo.
271
- if (!options.signal?.aborted) {
272
- this.recordBridgeWaitOutcome(connected, budget);
273
- }
261
+ const connected = await this.waitForBridge(budget);
262
+ this.recordBridgeWaitOutcome(connected, budget);
274
263
  }
275
264
 
276
265
  /** Remember that the full budget was burned without a bridge showing up, so
@@ -319,29 +308,23 @@ export class BrowserAgentBroker {
319
308
  /** Resolve as soon as a Chrome extension bridge is connected, or after
320
309
  * `timeoutMs`. Never rejects — callers decide what to do with a still-absent
321
310
  * bridge. */
322
- async waitForBridge(timeoutMs: number, signal?: AbortSignal): Promise<boolean> {
311
+ async waitForBridge(timeoutMs: number): Promise<boolean> {
323
312
  if (this.bridgeSocket && this.bridgeHello) return true;
324
- if (signal?.aborted) return false;
325
313
  if (!this.server || timeoutMs <= 0) return false;
326
314
 
327
315
  return await new Promise<boolean>((resolve) => {
328
316
  let settled = false;
329
- let releaseAbort = () => {};
330
317
  const finish = (value: boolean) => {
331
318
  if (settled) return;
332
319
  settled = true;
333
320
  this.bridgeWaiters.delete(waiter);
334
321
  clearTimeout(timer);
335
- releaseAbort();
336
322
  resolve(value);
337
323
  };
338
324
  const waiter = (connected: boolean) => finish(connected);
339
325
  const timer = setTimeout(() => finish(!!this.bridgeSocket && !!this.bridgeHello), timeoutMs);
340
326
  timer.unref?.();
341
327
  this.bridgeWaiters.add(waiter);
342
- // Waiting out an 8s reconnect window is the other place Escape used to
343
- // hang, before any request is even sent.
344
- releaseAbort = onAbort(signal, () => finish(false));
345
328
  });
346
329
  }
347
330
 
@@ -527,10 +510,7 @@ export class BrowserAgentBroker {
527
510
  });
528
511
  }
529
512
 
530
- async request(type: string, params: unknown, options: BrokerRequestOptions = {}): Promise<ResponseFrame> {
531
- // Never open a request for a caller that has already cancelled.
532
- throwIfAborted(options.signal, type);
533
-
513
+ async request(type: string, params: unknown, options: { timeoutMs?: number } = {}): Promise<ResponseFrame> {
534
514
  const socket = this.bridgeSocket;
535
515
  if (!socket || !this.bridgeHello) {
536
516
  throw new Error('E_BRIDGE_DISCONNECTED');
@@ -540,45 +520,29 @@ export class BrowserAgentBroker {
540
520
  const payload = JSON.stringify({ v: 1, kind: 'request', id, type, params });
541
521
 
542
522
  return await new Promise<ResponseFrame>((resolve, reject) => {
543
- let releaseAbort = () => {};
544
- const settle = (fn: () => void) => {
545
- this.pendingRequests.delete(id);
546
- clearTimeout(timeout);
547
- releaseAbort();
548
- fn();
549
- };
550
-
551
523
  const timeout = setTimeout(() => {
552
- settle(() => reject(new Error(`Request timed out: ${type}`)));
524
+ this.pendingRequests.delete(id);
525
+ reject(new Error(`Request timed out: ${type}`));
553
526
  }, options.timeoutMs ?? this.requestTimeoutMs);
554
527
  timeout.unref?.();
555
528
 
556
- this.pendingRequests.set(id, {
557
- resolve: (frame) => settle(() => resolve(frame)),
558
- reject: (error) => settle(() => reject(error)),
559
- timeout,
560
- });
561
-
562
- // Escape (or any other cancellation) hands pi back control immediately.
563
- // The bridge has no cancel frame yet, so the in-flight browser work still
564
- // finishes; we just stop waiting for it and drop the pending entry so a
565
- // late response is ignored instead of resolving a dead promise.
566
- releaseAbort = onAbort(options.signal, () => {
567
- settle(() => reject(abortError(type, options.signal)));
568
- });
569
- if (options.signal?.aborted) return;
529
+ this.pendingRequests.set(id, { resolve, reject, timeout });
570
530
 
571
531
  // If the bridge went away between our validation and send, reject fast
572
532
  // so callers get a direct disconnect error instead of waiting for a timeout.
573
533
  if (this.bridgeSocket !== socket) {
574
- settle(() => reject(new Error('E_BRIDGE_DISCONNECTED')));
534
+ clearTimeout(timeout);
535
+ this.pendingRequests.delete(id);
536
+ reject(new Error('E_BRIDGE_DISCONNECTED'));
575
537
  return;
576
538
  }
577
539
 
578
540
  try {
579
541
  socket.send(payload);
580
542
  } catch (error) {
581
- settle(() => reject(error instanceof Error ? error : new Error(String(error))));
543
+ clearTimeout(timeout);
544
+ this.pendingRequests.delete(id);
545
+ reject(error instanceof Error ? error : new Error(String(error)));
582
546
  }
583
547
  });
584
548
  }
@@ -2,7 +2,6 @@ import { Type } from '@sinclair/typebox';
2
2
 
3
3
  import type { BrowserAgentBroker } from '../broker/server.ts';
4
4
  import { formatBridgeFailure } from '../broker/diagnostics.ts';
5
- import { ABORT_ERROR_CODE } from '../broker/abort.ts';
6
5
  import { getPlaceholderBrowserToolSpecs } from './_register.ts';
7
6
 
8
7
  export function resetBrowserAgentToolState(): void {
@@ -46,21 +45,13 @@ export function createBrowserAgentToolsTool(
46
45
  'Diagnose and repair the browser integration. Forces a lazy re-acquire of the broker port (promoting this pi process to primary if the previous owner died) and waits for the Chrome extension bridge to reconnect. Call this whenever a browser_* tool reports E_BRIDGE_DISCONNECTED; it returns the full connectivity state plus recovery steps.',
47
46
  promptSnippet: 'Diagnose and repair the browser integration for this session.',
48
47
  parameters: Type.Object({}),
49
- async execute(_toolCallId: string, _params: Record<string, unknown>, signal?: AbortSignal) {
48
+ async execute(_toolCallId: string, _params: Record<string, unknown>) {
50
49
  // Lazily (re)acquire the broker so a killed primary is replaced on demand
51
50
  // when someone actually asks for the browser tools. Only do this for the
52
51
  // lifecycle-managed singleton — never for the throwaway fallback broker,
53
52
  // which is not tracked for shutdown and must not leak a listener.
54
- // This call waits out the bridge reconnect window, so it must honour
55
- // Escape too.
56
53
  if (managed) {
57
- await broker.ensureReady?.({ signal });
58
- }
59
- if (signal?.aborted) {
60
- return {
61
- content: [{ type: 'text', text: 'activate_browser_agent_tools cancelled before completing.' }],
62
- details: { ok: false, cancelled: true, error: { code: ABORT_ERROR_CODE, message: 'Request cancelled' } },
63
- };
54
+ await broker.ensureReady?.();
64
55
  }
65
56
  const probe = broker.probeConnectivity();
66
57
  if (!probe.brokerReachable || !probe.brokerListening || !probe.bridgeConnected) {
@@ -4,7 +4,6 @@ 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 { abortError, isAbortError, sleepUnlessAborted } from '../broker/abort.ts';
8
7
 
9
8
  interface ToolResult {
10
9
  content: Array<{ type: 'text'; text: string }>;
@@ -37,22 +36,18 @@ async function brokerToolRequest(
37
36
  type: string,
38
37
  params: unknown,
39
38
  timeoutMs: number,
40
- signal?: AbortSignal,
41
39
  ): Promise<{ ok: true; data: unknown } | { ok: false; error: { code: string; message: string; details?: unknown } }> {
42
40
  try {
43
- // Cancellation can arrive before we touch the broker at all.
44
- if (signal?.aborted) throw abortError(type, signal);
45
41
  // Lazily (re)acquire the broker (and wait out the extension's reconnect
46
42
  // window) so a killed primary or a bounced service worker is healed on
47
43
  // demand instead of failing the call.
48
- await broker.ensureReady?.({ signal });
49
- if (signal?.aborted) throw abortError(type, signal);
44
+ await broker.ensureReady?.();
50
45
  const probe = broker.probeConnectivity();
51
46
  if (!probe.brokerListening || !probe.bridgeConnected) {
52
47
  const { text, diagnostics } = formatBridgeFailure(probe, type);
53
48
  return { ok: false, error: { code: 'E_BRIDGE_DISCONNECTED', message: text, details: { probe, diagnostics } } };
54
49
  }
55
- const response = await broker.request(type, params, { timeoutMs, signal });
50
+ const response = await broker.request(type, params, { timeoutMs });
56
51
  if (!response.ok) {
57
52
  return {
58
53
  ok: false,
@@ -69,15 +64,6 @@ async function brokerToolRequest(
69
64
  }
70
65
  }
71
66
 
72
- /** Cancellation is a normal outcome, not a malfunction — say so plainly so the
73
- * agent does not start diagnosing a broken browser after the user hit Escape. */
74
- function formatFailureText(name: string, error: { code: string; message: string }): string {
75
- if (error.code === 'E_ABORTED') {
76
- return `${name} cancelled: ${error.message}`;
77
- }
78
- return `${name} failed: ${error.message}`;
79
- }
80
-
81
67
  async function formatPayload(payload: unknown, ext: 'txt' | 'json' = 'json') {
82
68
  const serialized = typeof payload === 'string' ? payload : JSON.stringify(payload, null, 2);
83
69
  return await truncateAndSpill(serialized, ext);
@@ -176,17 +162,11 @@ function validateSuccessPayload(name: string, data: any): { code: string; messag
176
162
  return null;
177
163
  }
178
164
 
179
- async function waitForBridgeSessionChange(
180
- broker: BrowserAgentBroker,
181
- beforeProbe: ProbeResult,
182
- timeoutMs: number,
183
- signal?: AbortSignal,
184
- ): Promise<ProbeResult> {
165
+ async function waitForBridgeSessionChange(broker: BrowserAgentBroker, beforeProbe: ProbeResult, timeoutMs: number): Promise<ProbeResult> {
185
166
  const deadline = Date.now() + timeoutMs;
186
167
  let lastProbe = broker.probeConnectivity();
187
168
 
188
169
  while (Date.now() < deadline) {
189
- if (signal?.aborted) throw abortError('browser_reload_extension', signal);
190
170
  lastProbe = broker.probeConnectivity();
191
171
  if (
192
172
  lastProbe.bridgeConnected
@@ -196,7 +176,7 @@ async function waitForBridgeSessionChange(
196
176
  ) {
197
177
  return lastProbe;
198
178
  }
199
- await sleepUnlessAborted(100, signal);
179
+ await new Promise((resolve) => setTimeout(resolve, 100));
200
180
  }
201
181
 
202
182
  throw {
@@ -223,14 +203,7 @@ function createRequestTool(options: {
223
203
  description: createToolDescription(options.description),
224
204
  promptSnippet: options.promptSnippet,
225
205
  parameters: options.parameters,
226
- // `signal` is pi's cancellation handle (Escape). Accepting it here is what
227
- // lets an aborted call return at once instead of blocking until the
228
- // per-tool timeout (15s eval / 30s run_js / navigation budgets) expires.
229
- async execute(
230
- _toolCallId: string,
231
- params: Record<string, unknown>,
232
- signal?: AbortSignal,
233
- ): Promise<ToolResult> {
206
+ async execute(_toolCallId: string, params: Record<string, unknown>): Promise<ToolResult> {
234
207
  const requestParams = options.name === 'browser_clear_site_data'
235
208
  ? withClearSiteDataTarget(params)
236
209
  : [
@@ -242,17 +215,10 @@ function createRequestTool(options: {
242
215
  ? withDefaultActiveTabTarget(params)
243
216
  : params;
244
217
 
245
- const outcome = await brokerToolRequest(
246
- broker,
247
- options.name,
248
- requestParams,
249
- options.timeoutFromParams(requestParams),
250
- signal,
251
- );
218
+ const outcome = await brokerToolRequest(broker, options.name, requestParams, options.timeoutFromParams(requestParams));
252
219
  if (!outcome.ok) {
253
- return textResult(formatFailureText(options.name, outcome.error), {
220
+ return textResult(`${options.name} failed: ${outcome.error.message}`, {
254
221
  ok: false,
255
- cancelled: outcome.error.code === 'E_ABORTED' || undefined,
256
222
  error: outcome.error,
257
223
  request: requestParams,
258
224
  });
@@ -466,18 +432,13 @@ export function createBrowserReloadExtensionTool(broker: BrowserAgentBroker) {
466
432
  description: createToolDescription(browserReloadExtensionDefinition.description),
467
433
  promptSnippet: browserReloadExtensionDefinition.promptSnippet,
468
434
  parameters: browserReloadExtensionDefinition.parameters,
469
- async execute(
470
- _toolCallId: string,
471
- params: { timeout_ms?: number },
472
- signal?: AbortSignal,
473
- ): Promise<ToolResult> {
435
+ async execute(_toolCallId: string, params: { timeout_ms?: number }): Promise<ToolResult> {
474
436
  const timeoutMs = Number(params.timeout_ms ?? 15_000);
475
437
  const beforeProbe = broker.probeConnectivity();
476
- const outcome = await brokerToolRequest(broker, 'browser_reload_extension', params, timeoutMs, signal);
438
+ const outcome = await brokerToolRequest(broker, 'browser_reload_extension', params, timeoutMs);
477
439
  if (!outcome.ok) {
478
- return textResult(formatFailureText('browser_reload_extension', outcome.error), {
440
+ return textResult('browser_reload_extension failed: ' + outcome.error.message, {
479
441
  ok: false,
480
- cancelled: outcome.error.code === 'E_ABORTED' || undefined,
481
442
  error: outcome.error,
482
443
  request: params,
483
444
  probeBefore: beforeProbe,
@@ -485,7 +446,7 @@ export function createBrowserReloadExtensionTool(broker: BrowserAgentBroker) {
485
446
  }
486
447
 
487
448
  try {
488
- const afterProbe = await waitForBridgeSessionChange(broker, beforeProbe, timeoutMs, signal);
449
+ const afterProbe = await waitForBridgeSessionChange(broker, beforeProbe, timeoutMs);
489
450
  const data = { ...(outcome.data as Record<string, unknown>), reconnected: true };
490
451
  const protocolError = validateSuccessPayload('browser_reload_extension', data);
491
452
  if (protocolError) {
@@ -510,9 +471,8 @@ export function createBrowserReloadExtensionTool(broker: BrowserAgentBroker) {
510
471
  });
511
472
  } catch (error) {
512
473
  const errorInfo = errorInfoFromUnknown(error);
513
- return textResult(formatFailureText('browser_reload_extension', errorInfo), {
474
+ return textResult('browser_reload_extension failed: ' + errorInfo.message, {
514
475
  ok: false,
515
- cancelled: isAbortError(error) || undefined,
516
476
  error: errorInfo,
517
477
  request: params,
518
478
  result: outcome.data,
@@ -5,11 +5,9 @@ import {
5
5
  coerceError,
6
6
  defaultTimeoutMs,
7
7
  formatJsonResult,
8
- formatToolFailureText,
9
8
  requestBridge,
10
9
  textResult,
11
10
  } from './read_only/common.ts';
12
- import { isAbortError } from '../broker/abort.ts';
13
11
  import type { ToolResult } from './read_only/common.ts';
14
12
 
15
13
  function withDefaultActiveTabTarget(params: Record<string, unknown>) {
@@ -60,16 +58,11 @@ export function createBrowserGetConsoleLogsTool(broker: BrowserAgentBroker) {
60
58
  include_stack: Type.Optional(Type.Boolean()),
61
59
  timeout_ms: Type.Optional(Type.Number({ minimum: 1, maximum: 60_000 })),
62
60
  }),
63
- async execute(
64
- _toolCallId: string,
65
- params: Record<string, unknown>,
66
- signal?: AbortSignal,
67
- ): Promise<ToolResult> {
61
+ async execute(_toolCallId: string, params: Record<string, unknown>): Promise<ToolResult> {
68
62
  const requestParams = withDefaultActiveTabTarget(params);
69
63
  try {
70
64
  const { data } = await requestBridge<Record<string, unknown>>(broker, 'browser_get_console_logs', requestParams, {
71
65
  timeoutMs: Number(requestParams.timeout_ms || defaultTimeoutMs('browser_get_console_logs')),
72
- signal,
73
66
  });
74
67
 
75
68
  const rendered = await formatJsonResult('Browser console logs', data, 'json');
@@ -87,9 +80,8 @@ export function createBrowserGetConsoleLogsTool(broker: BrowserAgentBroker) {
87
80
  return textResult(consoleLogText(details), details);
88
81
  } catch (error) {
89
82
  const info = coerceError(error);
90
- return textResult(formatToolFailureText('browser_get_console_logs', info), {
83
+ return textResult(`browser_get_console_logs failed: ${info.message}`, {
91
84
  ok: false,
92
- cancelled: isAbortError(error) || undefined,
93
85
  error: { code: info.code, message: info.message, details: info.details },
94
86
  });
95
87
  }
@@ -132,16 +124,11 @@ export function createBrowserGetNetworkTool(broker: BrowserAgentBroker) {
132
124
  include_timing: Type.Optional(Type.Boolean()),
133
125
  timeout_ms: Type.Optional(Type.Number({ minimum: 1, maximum: 60_000 })),
134
126
  }),
135
- async execute(
136
- _toolCallId: string,
137
- params: Record<string, unknown>,
138
- signal?: AbortSignal,
139
- ): Promise<ToolResult> {
127
+ async execute(_toolCallId: string, params: Record<string, unknown>): Promise<ToolResult> {
140
128
  const requestParams = withDefaultActiveTabTarget(params);
141
129
  try {
142
130
  const { data } = await requestBridge<Record<string, unknown>>(broker, 'browser_get_network', requestParams, {
143
131
  timeoutMs: Number(requestParams.timeout_ms || defaultTimeoutMs('browser_get_network')),
144
- signal,
145
132
  });
146
133
 
147
134
  const rendered = await formatJsonResult('Browser network activity', data, 'json');
@@ -159,9 +146,8 @@ export function createBrowserGetNetworkTool(broker: BrowserAgentBroker) {
159
146
  return textResult(networkText(details), details);
160
147
  } catch (error) {
161
148
  const info = coerceError(error);
162
- return textResult(formatToolFailureText('browser_get_network', info), {
149
+ return textResult(`browser_get_network failed: ${info.message}`, {
163
150
  ok: false,
164
- cancelled: isAbortError(error) || undefined,
165
151
  error: { code: info.code, message: info.message, details: info.details },
166
152
  });
167
153
  }
@@ -6,7 +6,6 @@ import type { BrowserAgentBroker } from '../broker/server.ts';
6
6
  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
- import { ABORT_ERROR_CODE, isAbortError } from '../broker/abort.ts';
10
9
 
11
10
  interface ToolResult {
12
11
  content: Array<{ type: 'text'; text: string }>;
@@ -207,20 +206,10 @@ export function createBrowserRunTaskTool(broker: BrowserAgentBroker) {
207
206
  async execute(
208
207
  _toolCallId: string,
209
208
  params: { task: string; tab_id?: number; use_active_tab?: boolean; debugMode?: boolean; timeoutMs?: number },
210
- signal?: AbortSignal,
211
209
  ): Promise<ToolResult> {
212
210
  // Lazily (re)acquire the broker so a killed primary is replaced on demand,
213
211
  // and wait out the extension's reconnect window before deciding we are down.
214
- await broker.ensureReady?.({ signal });
215
- if (signal?.aborted) {
216
- return textResult('browser_run_task cancelled before the task was started.', {
217
- ok: false,
218
- success: false,
219
- cancelled: true,
220
- status: 'cancelled',
221
- error: { code: ABORT_ERROR_CODE, message: 'Request cancelled' },
222
- });
223
- }
212
+ await broker.ensureReady?.();
224
213
  const probe = broker.probeConnectivity();
225
214
 
226
215
  // Fail fast with actionable diagnostics rather than recording a task that
@@ -262,37 +251,25 @@ export function createBrowserRunTaskTool(broker: BrowserAgentBroker) {
262
251
  response = await broker.request(
263
252
  'browser_run_task',
264
253
  request,
265
- { timeoutMs: params.timeoutMs ?? 5 * 60 * 1000, signal },
254
+ { timeoutMs: params.timeoutMs ?? 5 * 60 * 1000 },
266
255
  );
267
256
  } catch (error) {
268
257
  const errorInfo = errorInfoFromUnknown(error);
269
- // Escape on a task used to hold pi for the full 5-minute budget. We now
270
- // stop waiting immediately; the browser-side run is still in flight, so
271
- // the recorded status says cancelled rather than failed and the task id
272
- // remains queryable via browser_get_task_history.
273
- const cancelled = isAbortError(error);
274
- const status = cancelled ? 'cancelled' : 'error';
275
- const history = await finishRecordedTask(broker, taskId, status, {
258
+ const history = await finishRecordedTask(broker, taskId, 'error', {
276
259
  error: errorInfo,
277
260
  bridge: { connected: broker.probeConnectivity().bridgeConnected },
278
261
  });
279
- return textResult(
280
- cancelled
281
- ? `Browser task ${taskId} cancelled: pi stopped waiting for it. The browser may still be running it; check browser_get_task_history for the outcome.`
282
- : formatResponseText(taskId, 'error', errorInfo.message),
283
- {
284
- ok: false,
285
- success: false,
286
- cancelled: cancelled || undefined,
287
- taskId,
288
- status,
289
- error: errorInfo,
290
- probe,
291
- history,
292
- summary: summarizeHistory(taskId, history),
293
- historySummary: null,
294
- },
295
- );
262
+ return textResult(formatResponseText(taskId, 'error', errorInfo.message), {
263
+ ok: false,
264
+ success: false,
265
+ taskId,
266
+ status: 'error',
267
+ error: errorInfo,
268
+ probe,
269
+ history,
270
+ summary: summarizeHistory(taskId, history),
271
+ historySummary: null,
272
+ });
296
273
  }
297
274
 
298
275
  if (!response.ok) {
@@ -10,7 +10,6 @@ import type { BrowserAgentBroker } from '../../broker/server.ts';
10
10
  import type { ResponseFrame } from '../../broker/protocol.ts';
11
11
  import { formatBridgeFailure } from '../../broker/diagnostics.ts';
12
12
  import { truncateAndSpill } from '../../util/truncate.ts';
13
- import { abortError, isAbortError, type BrokerRequestOptions } from '../../broker/abort.ts';
14
13
 
15
14
  const SCREENSHOT_TEMP_DIR = join(tmpdir(), 'pi-browser-agent', 'screenshots');
16
15
  const SCREENSHOT_TEMP_MAX_AGE_MS = 24 * 60 * 60 * 1000;
@@ -31,8 +30,7 @@ export interface ReadOnlyToolDefinition<TParams = Record<string, unknown>> {
31
30
  description: string;
32
31
  promptSnippet: string;
33
32
  parameters: TSchema;
34
- /** `signal` is pi's per-tool-call cancellation handle (Escape). */
35
- execute: (toolCallId: string, params: TParams, signal?: AbortSignal) => Promise<ToolResult>;
33
+ execute: (toolCallId: string, params: TParams) => Promise<ToolResult>;
36
34
  }
37
35
 
38
36
  export class BrowserReadOnlyToolError extends Error {
@@ -91,15 +89,6 @@ export function coerceError(error: unknown, fallbackCode = 'E_INTERNAL'): Browse
91
89
  return new BrowserReadOnlyToolError(normalizedCode, message);
92
90
  }
93
91
 
94
- /** Cancellation is a user action, not a failure: label it accordingly so the
95
- * agent does not chase a browser problem that does not exist. */
96
- export function formatToolFailureText(label: string, error: { code: string; message: string }): string {
97
- if (isAbortError(error)) {
98
- return `${label} cancelled: ${error.message}`;
99
- }
100
- return `${label} failed: ${error.message}`;
101
- }
102
-
103
92
  export function ensureBridgeConnected(broker: BrowserAgentBroker, toolName?: string): void {
104
93
  const probe = broker.probeConnectivity();
105
94
  if (probe.brokerListening && probe.bridgeConnected) {
@@ -115,17 +104,13 @@ export async function requestBridge<TData>(
115
104
  broker: BrowserAgentBroker,
116
105
  type: string,
117
106
  params: unknown,
118
- options: BrokerRequestOptions = {},
107
+ options: { timeoutMs?: number } = {},
119
108
  ): Promise<{ response: ResponseFrame; data: TData }> {
120
- const { signal } = options;
121
- if (signal?.aborted) throw coerceError(abortError(type, signal));
122
109
  // Lazily (re)acquire the broker before the readiness check so a killed
123
110
  // primary is replaced (or reconnected to) on this request instead of failing.
124
111
  // ensureReady() also absorbs the extension's reconnect window, so a call that
125
- // lands mid-reconnect waits instead of failing. Passing the signal keeps that
126
- // wait interruptible, so Escape is not swallowed by the reconnect budget.
127
- await broker.ensureReady?.({ signal });
128
- if (signal?.aborted) throw coerceError(abortError(type, signal));
112
+ // lands mid-reconnect waits instead of failing.
113
+ await broker.ensureReady?.();
129
114
  ensureBridgeConnected(broker, type);
130
115
 
131
116
  let response: ResponseFrame;
@@ -3,7 +3,6 @@ import { readFile } from 'node:fs/promises';
3
3
  import { Type } from '@sinclair/typebox';
4
4
 
5
5
  import type { BrowserAgentBroker } from '../../broker/server.ts';
6
- import { isAbortError } from '../../broker/abort.ts';
7
6
  import {
8
7
  BrowserReadOnlyToolError,
9
8
  type ReadOnlyToolDefinition,
@@ -11,7 +10,6 @@ import {
11
10
  defaultTimeoutMs,
12
11
  formatJsonResult,
13
12
  formatTextResult,
14
- formatToolFailureText,
15
13
  imageResult,
16
14
  inferFileExtensionFromMime,
17
15
  normalizeScreenshotPayload,
@@ -59,11 +57,10 @@ function createJsonReadOnlyTool<TParams>(
59
57
  description: config.description,
60
58
  promptSnippet: config.promptSnippet,
61
59
  parameters: config.parameters,
62
- async execute(_toolCallId: string, params: TParams, signal?: AbortSignal) {
60
+ async execute(_toolCallId: string, params: TParams) {
63
61
  try {
64
62
  const { data, response } = await requestBridge<any>(broker, config.name, params, {
65
63
  timeoutMs: config.timeoutMs ? config.timeoutMs(params) : defaultTimeoutMs(config.name),
66
- signal,
67
64
  });
68
65
  const normalized = config.normalizeData ? config.normalizeData(data) : data;
69
66
  const formatted = await formatJsonResult(config.title(normalized, params), normalized);
@@ -77,9 +74,8 @@ function createJsonReadOnlyTool<TParams>(
77
74
  });
78
75
  } catch (error) {
79
76
  const info = coerceError(error);
80
- return textResult(formatToolFailureText(config.label, info), {
77
+ return textResult(`${config.label} failed: ${info.message}`, {
81
78
  ok: false,
82
- cancelled: isAbortError(error) || undefined,
83
79
  requestType: config.name,
84
80
  error: { code: info.code, message: info.message, details: info.details },
85
81
  });
@@ -121,11 +117,10 @@ function createScreenshotTool(broker: BrowserAgentBroker): ReadOnlyToolDefinitio
121
117
  quality: Type.Optional(Type.Number({ minimum: 0, maximum: 1 })),
122
118
  max_width: Type.Optional(Type.Number({ minimum: 1 })),
123
119
  }),
124
- async execute(_toolCallId: string, params: any, signal?: AbortSignal) {
120
+ async execute(_toolCallId: string, params: any) {
125
121
  try {
126
122
  const { data, response } = await requestBridge<any>(broker, 'browser_get_screenshot', params, {
127
123
  timeoutMs: defaultTimeoutMs('browser_get_screenshot'),
128
- signal,
129
124
  });
130
125
  const normalized = normalizeScreenshotPayload(data);
131
126
  let path = normalized.path;
@@ -170,9 +165,8 @@ function createScreenshotTool(broker: BrowserAgentBroker): ReadOnlyToolDefinitio
170
165
  return textResult(text, details);
171
166
  } catch (error) {
172
167
  const info = coerceError(error);
173
- return textResult(formatToolFailureText('browser_get_screenshot', info), {
168
+ return textResult(`browser_get_screenshot failed: ${info.message}`, {
174
169
  ok: false,
175
- cancelled: isAbortError(error) || undefined,
176
170
  requestType: 'browser_get_screenshot',
177
171
  error: { code: info.code, message: info.message, details: info.details },
178
172
  });
@@ -199,11 +193,10 @@ function createHtmlTool(broker: BrowserAgentBroker): ReadOnlyToolDefinition<any>
199
193
  strip: Type.Optional(includeType(['script', 'style', 'comments'])),
200
194
  max_bytes: Type.Optional(Type.Number({ minimum: 1 })),
201
195
  }),
202
- async execute(_toolCallId: string, params: any, signal?: AbortSignal) {
196
+ async execute(_toolCallId: string, params: any) {
203
197
  try {
204
198
  const { data, response } = await requestBridge<any>(broker, 'browser_get_html', params, {
205
199
  timeoutMs: defaultTimeoutMs('browser_get_html'),
206
- signal,
207
200
  });
208
201
  if (typeof data?.html !== 'string' && typeof data?.content !== 'string') {
209
202
  throw new BrowserReadOnlyToolError(
@@ -224,9 +217,8 @@ function createHtmlTool(broker: BrowserAgentBroker): ReadOnlyToolDefinition<any>
224
217
  });
225
218
  } catch (error) {
226
219
  const info = coerceError(error);
227
- return textResult(formatToolFailureText('browser_get_html', info), {
220
+ return textResult(`browser_get_html failed: ${info.message}`, {
228
221
  ok: false,
229
- cancelled: isAbortError(error) || undefined,
230
222
  requestType: 'browser_get_html',
231
223
  error: { code: info.code, message: info.message, details: info.details },
232
224
  });
@@ -189,8 +189,11 @@ test('remote broker proxies requests through the primary broker bridge', async (
189
189
 
190
190
  const response = await remote.request('browser_list_tabs', { activeOnly: false });
191
191
  assert.equal(response.ok, true);
192
- assert.equal(response.data?.proxied, true);
193
- assert.equal(response.data?.type, 'browser_list_tabs');
192
+ assert.deepEqual(response.data, {
193
+ proxied: true,
194
+ type: 'browser_list_tabs',
195
+ params: { activeOnly: false },
196
+ });
194
197
 
195
198
  await remote.stop();
196
199
  bridge.close();
@@ -341,7 +344,7 @@ test('remote broker promotes itself when the primary broker exits', async () =>
341
344
 
342
345
  const response = await remote.request('browser_list_tabs', {});
343
346
  assert.equal(response.ok, true);
344
- assert.equal(response.data?.promoted, true);
347
+ assert.deepEqual(response.data, { promoted: true });
345
348
 
346
349
  bridge.close();
347
350
  await remote.stop();
@@ -478,7 +481,7 @@ test('with many secondaries, exactly one promotes when the primary stops and all
478
481
  const results = await Promise.all(remotes.map((r) => r.request('browser_list_tabs', {})));
479
482
  for (const response of results) {
480
483
  assert.equal(response.ok, true);
481
- assert.equal(response.data?.served, true);
484
+ assert.deepEqual(response.data, { served: true });
482
485
  }
483
486
 
484
487
  bridge.close();
@@ -871,6 +874,44 @@ test('ensureReady() rebind leaves exactly one heartbeat interval running', async
871
874
  }
872
875
  });
873
876
 
877
+ test('remote stop() rejects a pending proxy request and does not reconnect', async () => {
878
+ const port = await getFreePort();
879
+ const primary = await createBroker(port);
880
+ await primary.start();
881
+ const bridge = await connectBridge(port, 'ext-stop-proxy');
882
+
883
+ const root = await mkdtemp(join(tmpdir(), 'pi-browser-agent-stop-proxy-'));
884
+ const remote = new RemoteBrowserAgentBroker({
885
+ host: '127.0.0.1',
886
+ port,
887
+ logger: { info() {}, warn() {}, error() {} },
888
+ requestTimeoutMs: 2_000,
889
+ taskStore: new TaskStore({ dir: join(root, 'tasks') }),
890
+ });
891
+
892
+ try {
893
+ await remote.start();
894
+ const received = new Promise<void>((resolve) => bridge.once('message', () => resolve()));
895
+ const rejected = assert.rejects(
896
+ remote.request('browser_list_tabs', {}),
897
+ /E_BRIDGE_DISCONNECTED/,
898
+ );
899
+ await received;
900
+ await remote.stop();
901
+ await rejected;
902
+
903
+ await remote.ensureReady({ waitForBridgeMs: 0 });
904
+ assert.equal(remote.probeConnectivity().brokerListening, false);
905
+ assert.equal(remote.probeConnectivity().bridgeConnected, false);
906
+ await assert.rejects(() => remote.request('browser_list_tabs', {}), /E_BRIDGE_DISCONNECTED/);
907
+ assert.equal(primary.probeConnectivity().brokerListening, true);
908
+ } finally {
909
+ bridge.close();
910
+ await remote.stop();
911
+ await primary.stop();
912
+ }
913
+ });
914
+
874
915
  test('remote stop() awaits an in-flight promotion and prevents a late bind', async () => {
875
916
  const port = await getFreePort();
876
917
  const primary = await createBroker(port);
@@ -175,7 +175,8 @@ test('browser_run_task forwards an explicit tab_id instead of selecting the acti
175
175
  test('concurrent browser_run_task attempts return E_BUSY without crashing the caller', async () => {
176
176
  const { broker } = await createBroker();
177
177
  let activeRunId: string | null = null;
178
- let activeSocket: WebSocket | null = null;
178
+ let requestEntered!: () => void;
179
+ const entered = new Promise<void>((resolve) => { requestEntered = resolve; });
179
180
 
180
181
  const socket = await connectBridge(broker, async (frame, ws) => {
181
182
  if (frame.type !== 'browser_run_task') return;
@@ -194,13 +195,13 @@ test('concurrent browser_run_task attempts return E_BUSY without crashing the ca
194
195
  }
195
196
 
196
197
  activeRunId = frame.id;
197
- activeSocket = ws;
198
+ requestEntered();
198
199
  });
199
200
  const tools = createToolHarness(broker);
200
201
 
201
202
  try {
202
203
  const firstRun = tools.get('browser_run_task').execute('call-1', { task: 'Task one' });
203
- await new Promise((resolve) => setTimeout(resolve, 50));
204
+ await entered;
204
205
 
205
206
  const secondRun = await tools.get('browser_run_task').execute('call-2', { task: 'Task two' });
206
207
  assert.equal(secondRun.details.ok, false);
@@ -208,7 +209,7 @@ test('concurrent browser_run_task attempts return E_BUSY without crashing the ca
208
209
  assert.match(textOf(secondRun), /rejected/i);
209
210
 
210
211
  assert.ok(activeRunId);
211
- activeSocket?.send(JSON.stringify({
212
+ socket.send(JSON.stringify({
212
213
  v: 1,
213
214
  kind: 'response',
214
215
  id: activeRunId,
@@ -120,5 +120,6 @@ test('meta-tool reports ready status when broker + bridge are healthy and remain
120
120
  assert.equal(probes, 3);
121
121
  assert.ok(Array.isArray(first.details.registeredTools));
122
122
  assert.ok(first.details.registeredTools.includes('browser_run_task'));
123
+ assert.ok(Array.isArray(third.details.registeredTools));
123
124
  assert.ok(third.details.registeredTools.includes('browser_run_task'));
124
125
  });
@@ -1,107 +0,0 @@
1
- /**
2
- * Cooperative cancellation for broker requests.
3
- *
4
- * pi hands every tool an `AbortSignal` (see `execute(toolCallId, params,
5
- * signal, ...)` in pi's extension API) and fires it when the user presses
6
- * Escape. Before this module nothing in this package listened to that signal,
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
9
- * and longer for navigation waits. Escape looked like it did nothing.
10
- *
11
- * Everything here is host-side only: it releases pi immediately and drops the
12
- * pending request entry. Work already started inside the page keeps running
13
- * until the bridge grows a real cancel frame.
14
- */
15
-
16
- export const ABORT_ERROR_CODE = 'E_ABORTED';
17
-
18
- export interface AbortableOptions {
19
- /** Fired by pi when the user cancels the tool call (Escape). */
20
- signal?: AbortSignal;
21
- }
22
-
23
- export interface BrokerRequestOptions extends AbortableOptions {
24
- timeoutMs?: number;
25
- }
26
-
27
- /** Error surfaced to callers when a request is cancelled. Carries the same
28
- * `code`/`message` shape the tool layer already uses for protocol errors. */
29
- export class BrokerAbortError extends Error {
30
- readonly code = ABORT_ERROR_CODE;
31
- readonly details?: unknown;
32
-
33
- constructor(message = 'Request cancelled', details?: unknown) {
34
- super(message);
35
- this.name = 'BrokerAbortError';
36
- this.details = details;
37
- }
38
- }
39
-
40
- /** True for our own abort error and for the DOMException `AbortError` that
41
- * `AbortSignal.throwIfAborted()` / stdlib APIs raise. */
42
- export function isAbortError(error: unknown): boolean {
43
- if (!error || typeof error !== 'object') return false;
44
- const candidate = error as { code?: unknown; name?: unknown };
45
- return candidate.code === ABORT_ERROR_CODE || candidate.name === 'AbortError';
46
- }
47
-
48
- function describeReason(signal: AbortSignal | undefined): string | undefined {
49
- const reason = signal?.reason as unknown;
50
- if (reason === undefined || reason === null) return undefined;
51
- if (typeof reason === 'string') return reason;
52
- if (reason instanceof Error) return reason.message;
53
- return undefined;
54
- }
55
-
56
- export function abortError(context: string, signal?: AbortSignal): BrokerAbortError {
57
- const reason = describeReason(signal);
58
- return new BrokerAbortError(
59
- reason ? `${context} was cancelled: ${reason}` : `${context} was cancelled`,
60
- );
61
- }
62
-
63
- /** Reject immediately when the caller is already gone, so we never open a
64
- * socket request for a tool call pi has stopped waiting for. */
65
- export function throwIfAborted(signal: AbortSignal | undefined, context: string): void {
66
- if (signal?.aborted) {
67
- throw abortError(context, signal);
68
- }
69
- }
70
-
71
- /**
72
- * Attach an abort listener and return a disposer. Always call the disposer once
73
- * the awaited work settles: a listener left on a long-lived session signal
74
- * keeps the closure (and its promise) alive for the rest of the session.
75
- */
76
- export function onAbort(signal: AbortSignal | undefined, listener: () => void): () => void {
77
- if (!signal) return () => {};
78
- if (signal.aborted) {
79
- listener();
80
- return () => {};
81
- }
82
- signal.addEventListener('abort', listener, { once: true });
83
- return () => signal.removeEventListener('abort', listener);
84
- }
85
-
86
- /**
87
- * Sleep that wakes early on abort. Returns `false` when it was cut short, so
88
- * polling loops can exit instead of burning their full budget after Escape.
89
- */
90
- export async function sleepUnlessAborted(ms: number, signal?: AbortSignal): Promise<boolean> {
91
- if (signal?.aborted) return false;
92
- if (ms <= 0) return !signal?.aborted;
93
-
94
- return await new Promise<boolean>((resolve) => {
95
- let settled = false;
96
- const finish = (completed: boolean) => {
97
- if (settled) return;
98
- settled = true;
99
- clearTimeout(timer);
100
- release();
101
- resolve(completed);
102
- };
103
- const timer = setTimeout(() => finish(true), ms);
104
- timer.unref?.();
105
- const release = onAbort(signal, () => finish(false));
106
- });
107
- }
@@ -1,243 +0,0 @@
1
- import test from 'node:test';
2
- import assert from 'node:assert/strict';
3
- import net from 'node:net';
4
- import { mkdtemp } from 'node:fs/promises';
5
- import { tmpdir } from 'node:os';
6
- import { join } from 'node:path';
7
-
8
- import WebSocket from 'ws';
9
-
10
- import { BrowserAgentBroker } from '../src/broker/server.ts';
11
- import { TaskStore } from '../src/broker/task-store.ts';
12
- import { ABORT_ERROR_CODE, isAbortError, sleepUnlessAborted } from '../src/broker/abort.ts';
13
- import { createBrowserEvaluateJsTool } from '../src/tools/browser_js_navigation_tools.ts';
14
- import { createReadOnlyBrowserTools } from '../src/tools/read_only/index.ts';
15
- import type { ResponseFrame } from '../src/broker/protocol.ts';
16
-
17
- /**
18
- * Regression tests for Escape / tool-call cancellation.
19
- *
20
- * Before this, every browser_* tool ignored the AbortSignal pi passes as the
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
23
- * for browser_run_task). Each test below asserts we now settle promptly and
24
- * report the cancellation as such instead of as a browser failure.
25
- */
26
-
27
- async function getFreePort(): Promise<number> {
28
- return await new Promise((resolve, reject) => {
29
- const server = net.createServer();
30
- server.listen(0, '127.0.0.1', () => {
31
- const address = server.address();
32
- if (!address || typeof address === 'string') {
33
- reject(new Error('Unable to allocate a free port'));
34
- return;
35
- }
36
- const { port } = address;
37
- server.close((error) => (error ? reject(error) : resolve(port)));
38
- });
39
- });
40
- }
41
-
42
- /** Connects a fake extension bridge that accepts requests and never answers,
43
- * which is exactly the shape of a long-running in-page evaluation. */
44
- async function connectSilentBridge(port: number): Promise<WebSocket> {
45
- return await new Promise<WebSocket>((resolve, reject) => {
46
- const socket = new WebSocket(`ws://127.0.0.1:${port}`);
47
- socket.once('error', reject);
48
- socket.once('open', () => socket.send(JSON.stringify({
49
- v: 1,
50
- kind: 'hello',
51
- extensionId: 'ext-abort-test',
52
- version: '0.1.0',
53
- capabilities: ['browser_evaluate_js', 'browser_get_html'],
54
- })));
55
- socket.once('message', () => resolve(socket));
56
- });
57
- }
58
-
59
- function textOf(result: any): string {
60
- return result.content[0]?.text || '';
61
- }
62
-
63
- async function createBroker(port: number): Promise<BrowserAgentBroker> {
64
- const root = await mkdtemp(join(tmpdir(), 'pi-ba-abort-'));
65
- return new BrowserAgentBroker({
66
- host: '127.0.0.1',
67
- port,
68
- portRange: 1,
69
- fallbackToEphemeral: false,
70
- logger: { info() {}, warn() {}, error() {} },
71
- taskStore: new TaskStore({ dir: join(root, 'tasks') }),
72
- } as any);
73
- }
74
-
75
- test('broker.request rejects immediately when the caller aborts mid-flight', async () => {
76
- const port = await getFreePort();
77
- const broker = await createBroker(port);
78
- await broker.start();
79
- const bridge = await connectSilentBridge(port);
80
-
81
- try {
82
- const controller = new AbortController();
83
- const startedAt = Date.now();
84
- // A 30s timeout stands in for browser_run_js: without abort support the
85
- // promise below could only settle after those 30 seconds.
86
- const pending = broker.request('browser_evaluate_js', { expression: 'while(true){}' }, {
87
- timeoutMs: 30_000,
88
- signal: controller.signal,
89
- });
90
- setTimeout(() => controller.abort(), 20);
91
-
92
- const error = await pending.then(() => null, (reason) => reason);
93
- const elapsed = Date.now() - startedAt;
94
-
95
- assert.ok(error, 'request should reject when aborted');
96
- assert.equal(error.code, ABORT_ERROR_CODE);
97
- assert.ok(isAbortError(error));
98
- assert.ok(elapsed < 2_000, `expected a prompt rejection, took ${elapsed}ms`);
99
- } finally {
100
- bridge.close();
101
- await broker.stop();
102
- }
103
- });
104
-
105
- test('broker.request refuses to send a request that is already cancelled', async () => {
106
- const port = await getFreePort();
107
- const broker = await createBroker(port);
108
- await broker.start();
109
- const bridge = await connectSilentBridge(port);
110
- const received: unknown[] = [];
111
- bridge.on('message', (raw) => received.push(JSON.parse(String(raw))));
112
-
113
- try {
114
- const controller = new AbortController();
115
- controller.abort();
116
-
117
- const error = await broker
118
- .request('browser_evaluate_js', { expression: '1' }, { signal: controller.signal })
119
- .then(() => null, (reason) => reason);
120
-
121
- assert.ok(error);
122
- assert.equal(error.code, ABORT_ERROR_CODE);
123
- await new Promise((resolve) => setTimeout(resolve, 50));
124
- assert.equal(received.length, 0, 'no frame should reach the bridge for an already-cancelled call');
125
- } finally {
126
- bridge.close();
127
- await broker.stop();
128
- }
129
- });
130
-
131
- test('waitForBridge stops waiting when the tool call is cancelled', async () => {
132
- const port = await getFreePort();
133
- const broker = await createBroker(port);
134
- await broker.start();
135
-
136
- try {
137
- const controller = new AbortController();
138
- const startedAt = Date.now();
139
- // No bridge ever connects, so this would otherwise burn the whole budget.
140
- const pending = broker.waitForBridge(10_000, controller.signal);
141
- setTimeout(() => controller.abort(), 20);
142
-
143
- const connected = await pending;
144
- const elapsed = Date.now() - startedAt;
145
-
146
- assert.equal(connected, false);
147
- assert.ok(elapsed < 2_000, `expected an early return, took ${elapsed}ms`);
148
- } finally {
149
- await broker.stop();
150
- }
151
- });
152
-
153
- test('browser_evaluate_js reports cancellation instead of a browser failure', async () => {
154
- let capturedSignal: AbortSignal | undefined;
155
- const broker = {
156
- async ensureReady(options: { signal?: AbortSignal } = {}) {
157
- capturedSignal = options.signal;
158
- },
159
- probeConnectivity() {
160
- return {
161
- brokerReachable: true,
162
- brokerListening: true,
163
- bridgeConnected: true,
164
- url: 'ws://127.0.0.1:7878',
165
- bridgeSessionSerial: 1,
166
- };
167
- },
168
- async request(_type: string, _params: unknown, options: { signal?: AbortSignal } = {}): Promise<ResponseFrame> {
169
- return await new Promise((_resolve, reject) => {
170
- options.signal?.addEventListener('abort', () => {
171
- const error: any = new Error('browser_evaluate_js was cancelled');
172
- error.code = ABORT_ERROR_CODE;
173
- reject(error);
174
- });
175
- });
176
- },
177
- } as any;
178
-
179
- const tool = createBrowserEvaluateJsTool(broker);
180
- const controller = new AbortController();
181
- const pending = tool.execute('call-1', { expression: 'document.title' }, controller.signal);
182
- setTimeout(() => controller.abort(), 20);
183
-
184
- const result: any = await pending;
185
-
186
- // The signal must reach ensureReady too: that is the 8s bridge-reconnect
187
- // wait, which used to swallow Escape before any request was even sent.
188
- assert.ok(capturedSignal, 'ensureReady should receive the abort signal');
189
- assert.equal(result.details.ok, false);
190
- assert.equal(result.details.cancelled, true);
191
- assert.equal(result.details.error.code, ABORT_ERROR_CODE);
192
- assert.match(textOf(result), /cancelled/i);
193
- assert.doesNotMatch(textOf(result), /failed/i);
194
- });
195
-
196
- test('read-only tools forward the abort signal and label cancellation', async () => {
197
- const broker = {
198
- async ensureReady() {},
199
- probeConnectivity() {
200
- return {
201
- brokerReachable: true,
202
- brokerListening: true,
203
- bridgeConnected: true,
204
- url: 'ws://127.0.0.1:7878',
205
- bridgeSessionSerial: 1,
206
- };
207
- },
208
- async request(_type: string, _params: unknown, options: { signal?: AbortSignal } = {}): Promise<ResponseFrame> {
209
- return await new Promise((_resolve, reject) => {
210
- options.signal?.addEventListener('abort', () => {
211
- const error: any = new Error('cancelled');
212
- error.code = ABORT_ERROR_CODE;
213
- reject(error);
214
- });
215
- });
216
- },
217
- } as any;
218
-
219
- const htmlTool = createReadOnlyBrowserTools(broker).find((tool) => tool.name === 'browser_get_html');
220
- assert.ok(htmlTool);
221
-
222
- const controller = new AbortController();
223
- const pending = htmlTool.execute('call-2', { url: 'https://example.com' }, controller.signal);
224
- setTimeout(() => controller.abort(), 20);
225
-
226
- const result: any = await pending;
227
- assert.equal(result.details.ok, false);
228
- assert.equal(result.details.cancelled, true);
229
- assert.equal(result.details.error.code, ABORT_ERROR_CODE);
230
- assert.match(textOf(result), /cancelled/i);
231
- });
232
-
233
- test('sleepUnlessAborted wakes early and reports that it was cut short', async () => {
234
- const controller = new AbortController();
235
- const startedAt = Date.now();
236
- setTimeout(() => controller.abort(), 20);
237
-
238
- const completed = await sleepUnlessAborted(5_000, controller.signal);
239
-
240
- assert.equal(completed, false);
241
- assert.ok(Date.now() - startedAt < 2_000);
242
- assert.equal(await sleepUnlessAborted(1, undefined), true);
243
- });