oira666_pi-browser-agent 0.0.18 → 0.0.19

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.18",
3
+ "version": "0.0.19",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Pi browser agent broker skeleton with lazy browser tool registration",
@@ -0,0 +1,107 @@
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,12 +1,13 @@
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';
4
5
 
5
6
  /** The slice of the broker API that the browser_* tools actually consume. */
6
7
  export interface BrokerLike {
7
8
  ensureReady?: (options?: EnsureReadyOptions) => Promise<void>;
8
9
  probeConnectivity: () => ProbeResult;
9
- request: (type: string, params: unknown, options?: { timeoutMs?: number }) => Promise<ResponseFrame>;
10
+ request: (type: string, params: unknown, options?: BrokerRequestOptions) => Promise<ResponseFrame>;
10
11
  taskStore: TaskStore;
11
12
  }
12
13
 
@@ -139,7 +140,7 @@ export class LazyBrokerHandle implements BrokerLike {
139
140
  return probe;
140
141
  }
141
142
 
142
- async request(type: string, params: unknown, options: { timeoutMs?: number } = {}): Promise<ResponseFrame> {
143
+ async request(type: string, params: unknown, options: BrokerRequestOptions = {}): Promise<ResponseFrame> {
143
144
  if (this.disposed) {
144
145
  throw new Error('E_BRIDGE_DISCONNECTED');
145
146
  }
@@ -19,6 +19,13 @@ 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';
22
29
 
23
30
  interface PendingRequest {
24
31
  resolve: (value: ResponseFrame) => void;
@@ -136,7 +143,7 @@ export class RemoteBrowserAgentBroker {
136
143
  // Poll the primary's probe for the same budget a local broker would wait,
137
144
  // so a tool call arriving during a reconnect window succeeds instead of
138
145
  // reporting a hard "connection is down".
139
- await this.waitForRemoteBridge(options.waitForBridgeMs ?? this.defaultRemoteBridgeWaitMs());
146
+ await this.waitForRemoteBridge(options.waitForBridgeMs ?? this.defaultRemoteBridgeWaitMs(), options.signal);
140
147
  }
141
148
 
142
149
  /** Full budget only when the primary has actually seen a bridge at some point.
@@ -149,13 +156,13 @@ export class RemoteBrowserAgentBroker {
149
156
  return this.remoteProbe?.bridgeEverConnected === false ? COLD_BRIDGE_WAIT_MS : DEFAULT_BRIDGE_WAIT_MS;
150
157
  }
151
158
 
152
- private async waitForRemoteBridge(timeoutMs: number): Promise<boolean> {
159
+ private async waitForRemoteBridge(timeoutMs: number, signal?: AbortSignal): Promise<boolean> {
153
160
  if (this.probeConnectivity().bridgeConnected) {
154
161
  this.coldBridgeMisses = 0;
155
162
  this.coldBridgeSince = null;
156
163
  return true;
157
164
  }
158
- if (timeoutMs <= 0) return false;
165
+ if (timeoutMs <= 0 || signal?.aborted) return false;
159
166
  const deadline = Date.now() + timeoutMs;
160
167
  // Every sub-step below can block for up to ~1.5s, so the budget is
161
168
  // re-checked before each of them. Checking only at the top of the loop let a
@@ -164,9 +171,10 @@ export class RemoteBrowserAgentBroker {
164
171
  while (Date.now() < deadline) {
165
172
  const sleepMs = Math.min(250, deadline - Date.now());
166
173
  if (sleepMs > 0) {
167
- await new Promise((resolve) => setTimeout(resolve, sleepMs).unref?.());
174
+ // Wakes immediately on Escape instead of finishing the tick.
175
+ await sleepUnlessAborted(sleepMs, signal);
168
176
  }
169
- if (this.stopped) return false;
177
+ if (this.stopped || signal?.aborted) return false;
170
178
  if (Date.now() >= deadline) break;
171
179
  try {
172
180
  await this.ensureConnected();
@@ -182,14 +190,15 @@ export class RemoteBrowserAgentBroker {
182
190
  if (Date.now() >= deadline) break;
183
191
  const promoted = await this.promoteOrReconnect();
184
192
  if (promoted) {
185
- const found = await promoted.waitForBridge(Math.max(0, deadline - Date.now()));
186
- this.recordBridgeWaitOutcome(found, timeoutMs);
193
+ const found = await promoted.waitForBridge(Math.max(0, deadline - Date.now()), signal);
194
+ if (!signal?.aborted) this.recordBridgeWaitOutcome(found, timeoutMs);
187
195
  return found;
188
196
  }
189
197
  }
190
198
  }
191
199
  const connected = this.probeConnectivity().bridgeConnected;
192
- this.recordBridgeWaitOutcome(connected, timeoutMs);
200
+ // A budget cut short by Escape is not evidence that the browser is cold.
201
+ if (!signal?.aborted) this.recordBridgeWaitOutcome(connected, timeoutMs);
193
202
  return connected;
194
203
  }
195
204
 
@@ -280,8 +289,9 @@ export class RemoteBrowserAgentBroker {
280
289
  }
281
290
  }
282
291
 
283
- async request(type: string, params: unknown, options: { timeoutMs?: number } = {}): Promise<ResponseFrame> {
292
+ async request(type: string, params: unknown, options: BrokerRequestOptions = {}): Promise<ResponseFrame> {
284
293
  if (this.stopped) throw new Error('E_BRIDGE_DISCONNECTED');
294
+ throwIfAborted(options.signal, type);
285
295
  if (this.promotedBroker) {
286
296
  return await this.promotedBroker.request(type, params, options);
287
297
  }
@@ -305,19 +315,34 @@ export class RemoteBrowserAgentBroker {
305
315
  const payload = JSON.stringify({ v: 1, kind: 'request', id, type, params });
306
316
 
307
317
  return await new Promise<ResponseFrame>((resolve, reject) => {
308
- const timeout = setTimeout(() => {
318
+ let releaseAbort = () => {};
319
+ const settle = (fn: () => void) => {
309
320
  this.pendingRequests.delete(id);
310
- reject(new Error(`Request timed out: ${type}`));
321
+ clearTimeout(timeout);
322
+ releaseAbort();
323
+ fn();
324
+ };
325
+
326
+ const timeout = setTimeout(() => {
327
+ settle(() => reject(new Error(`Request timed out: ${type}`)));
311
328
  }, options.timeoutMs ?? this.requestTimeoutMs);
312
329
  timeout.unref?.();
313
330
 
314
- this.pendingRequests.set(id, { resolve, reject, timeout });
331
+ this.pendingRequests.set(id, {
332
+ resolve: (frame) => settle(() => resolve(frame)),
333
+ reject: (error) => settle(() => reject(error)),
334
+ timeout,
335
+ });
336
+
337
+ releaseAbort = onAbort(options.signal, () => {
338
+ settle(() => reject(abortError(type, options.signal)));
339
+ });
340
+ if (options.signal?.aborted) return;
341
+
315
342
  try {
316
343
  socket.send(payload);
317
344
  } catch (error) {
318
- clearTimeout(timeout);
319
- this.pendingRequests.delete(id);
320
- reject(error instanceof Error ? error : new Error(String(error)));
345
+ settle(() => reject(error instanceof Error ? error : new Error(String(error))));
321
346
  }
322
347
  });
323
348
  }
@@ -16,6 +16,13 @@ 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';
19
26
 
20
27
  export interface BrokerLogger {
21
28
  info?: (...args: unknown[]) => void;
@@ -67,7 +74,7 @@ export interface BridgeStateEvent {
67
74
 
68
75
  export type BridgeStateListener = (state: BridgeStateEvent) => void;
69
76
 
70
- export interface EnsureReadyOptions {
77
+ export interface EnsureReadyOptions extends AbortableOptions {
71
78
  /** Override the bridge wait budget. 0 disables waiting entirely. */
72
79
  waitForBridgeMs?: number;
73
80
  }
@@ -258,8 +265,12 @@ export class BrowserAgentBroker {
258
265
  // failing a tool call that arrived mid-reconnect. This is what makes the
259
266
  // integration self-healing from the agent's point of view.
260
267
  const budget = this.resolveBridgeWaitMs(options);
261
- const connected = await this.waitForBridge(budget);
262
- this.recordBridgeWaitOutcome(connected, budget);
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
+ }
263
274
  }
264
275
 
265
276
  /** Remember that the full budget was burned without a bridge showing up, so
@@ -308,23 +319,29 @@ export class BrowserAgentBroker {
308
319
  /** Resolve as soon as a Chrome extension bridge is connected, or after
309
320
  * `timeoutMs`. Never rejects — callers decide what to do with a still-absent
310
321
  * bridge. */
311
- async waitForBridge(timeoutMs: number): Promise<boolean> {
322
+ async waitForBridge(timeoutMs: number, signal?: AbortSignal): Promise<boolean> {
312
323
  if (this.bridgeSocket && this.bridgeHello) return true;
324
+ if (signal?.aborted) return false;
313
325
  if (!this.server || timeoutMs <= 0) return false;
314
326
 
315
327
  return await new Promise<boolean>((resolve) => {
316
328
  let settled = false;
329
+ let releaseAbort = () => {};
317
330
  const finish = (value: boolean) => {
318
331
  if (settled) return;
319
332
  settled = true;
320
333
  this.bridgeWaiters.delete(waiter);
321
334
  clearTimeout(timer);
335
+ releaseAbort();
322
336
  resolve(value);
323
337
  };
324
338
  const waiter = (connected: boolean) => finish(connected);
325
339
  const timer = setTimeout(() => finish(!!this.bridgeSocket && !!this.bridgeHello), timeoutMs);
326
340
  timer.unref?.();
327
341
  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));
328
345
  });
329
346
  }
330
347
 
@@ -510,7 +527,10 @@ export class BrowserAgentBroker {
510
527
  });
511
528
  }
512
529
 
513
- async request(type: string, params: unknown, options: { timeoutMs?: number } = {}): Promise<ResponseFrame> {
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
+
514
534
  const socket = this.bridgeSocket;
515
535
  if (!socket || !this.bridgeHello) {
516
536
  throw new Error('E_BRIDGE_DISCONNECTED');
@@ -520,29 +540,45 @@ export class BrowserAgentBroker {
520
540
  const payload = JSON.stringify({ v: 1, kind: 'request', id, type, params });
521
541
 
522
542
  return await new Promise<ResponseFrame>((resolve, reject) => {
523
- const timeout = setTimeout(() => {
543
+ let releaseAbort = () => {};
544
+ const settle = (fn: () => void) => {
524
545
  this.pendingRequests.delete(id);
525
- reject(new Error(`Request timed out: ${type}`));
546
+ clearTimeout(timeout);
547
+ releaseAbort();
548
+ fn();
549
+ };
550
+
551
+ const timeout = setTimeout(() => {
552
+ settle(() => reject(new Error(`Request timed out: ${type}`)));
526
553
  }, options.timeoutMs ?? this.requestTimeoutMs);
527
554
  timeout.unref?.();
528
555
 
529
- this.pendingRequests.set(id, { resolve, reject, timeout });
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;
530
570
 
531
571
  // If the bridge went away between our validation and send, reject fast
532
572
  // so callers get a direct disconnect error instead of waiting for a timeout.
533
573
  if (this.bridgeSocket !== socket) {
534
- clearTimeout(timeout);
535
- this.pendingRequests.delete(id);
536
- reject(new Error('E_BRIDGE_DISCONNECTED'));
574
+ settle(() => reject(new Error('E_BRIDGE_DISCONNECTED')));
537
575
  return;
538
576
  }
539
577
 
540
578
  try {
541
579
  socket.send(payload);
542
580
  } catch (error) {
543
- clearTimeout(timeout);
544
- this.pendingRequests.delete(id);
545
- reject(error instanceof Error ? error : new Error(String(error)));
581
+ settle(() => reject(error instanceof Error ? error : new Error(String(error))));
546
582
  }
547
583
  });
548
584
  }
@@ -2,6 +2,7 @@ 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';
5
6
  import { getPlaceholderBrowserToolSpecs } from './_register.ts';
6
7
 
7
8
  export function resetBrowserAgentToolState(): void {
@@ -45,13 +46,21 @@ export function createBrowserAgentToolsTool(
45
46
  '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.',
46
47
  promptSnippet: 'Diagnose and repair the browser integration for this session.',
47
48
  parameters: Type.Object({}),
48
- async execute(_toolCallId: string, _params: Record<string, unknown>) {
49
+ async execute(_toolCallId: string, _params: Record<string, unknown>, signal?: AbortSignal) {
49
50
  // Lazily (re)acquire the broker so a killed primary is replaced on demand
50
51
  // when someone actually asks for the browser tools. Only do this for the
51
52
  // lifecycle-managed singleton — never for the throwaway fallback broker,
52
53
  // 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.
53
56
  if (managed) {
54
- await broker.ensureReady?.();
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
+ };
55
64
  }
56
65
  const probe = broker.probeConnectivity();
57
66
  if (!probe.brokerReachable || !probe.brokerListening || !probe.bridgeConnected) {
@@ -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 { abortError, isAbortError, sleepUnlessAborted } from '../broker/abort.ts';
7
8
 
8
9
  interface ToolResult {
9
10
  content: Array<{ type: 'text'; text: string }>;
@@ -36,18 +37,22 @@ async function brokerToolRequest(
36
37
  type: string,
37
38
  params: unknown,
38
39
  timeoutMs: number,
40
+ signal?: AbortSignal,
39
41
  ): Promise<{ ok: true; data: unknown } | { ok: false; error: { code: string; message: string; details?: unknown } }> {
40
42
  try {
43
+ // Cancellation can arrive before we touch the broker at all.
44
+ if (signal?.aborted) throw abortError(type, signal);
41
45
  // Lazily (re)acquire the broker (and wait out the extension's reconnect
42
46
  // window) so a killed primary or a bounced service worker is healed on
43
47
  // demand instead of failing the call.
44
- await broker.ensureReady?.();
48
+ await broker.ensureReady?.({ signal });
49
+ if (signal?.aborted) throw abortError(type, signal);
45
50
  const probe = broker.probeConnectivity();
46
51
  if (!probe.brokerListening || !probe.bridgeConnected) {
47
52
  const { text, diagnostics } = formatBridgeFailure(probe, type);
48
53
  return { ok: false, error: { code: 'E_BRIDGE_DISCONNECTED', message: text, details: { probe, diagnostics } } };
49
54
  }
50
- const response = await broker.request(type, params, { timeoutMs });
55
+ const response = await broker.request(type, params, { timeoutMs, signal });
51
56
  if (!response.ok) {
52
57
  return {
53
58
  ok: false,
@@ -64,6 +69,15 @@ async function brokerToolRequest(
64
69
  }
65
70
  }
66
71
 
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
+
67
81
  async function formatPayload(payload: unknown, ext: 'txt' | 'json' = 'json') {
68
82
  const serialized = typeof payload === 'string' ? payload : JSON.stringify(payload, null, 2);
69
83
  return await truncateAndSpill(serialized, ext);
@@ -162,11 +176,17 @@ function validateSuccessPayload(name: string, data: any): { code: string; messag
162
176
  return null;
163
177
  }
164
178
 
165
- async function waitForBridgeSessionChange(broker: BrowserAgentBroker, beforeProbe: ProbeResult, timeoutMs: number): Promise<ProbeResult> {
179
+ async function waitForBridgeSessionChange(
180
+ broker: BrowserAgentBroker,
181
+ beforeProbe: ProbeResult,
182
+ timeoutMs: number,
183
+ signal?: AbortSignal,
184
+ ): Promise<ProbeResult> {
166
185
  const deadline = Date.now() + timeoutMs;
167
186
  let lastProbe = broker.probeConnectivity();
168
187
 
169
188
  while (Date.now() < deadline) {
189
+ if (signal?.aborted) throw abortError('browser_reload_extension', signal);
170
190
  lastProbe = broker.probeConnectivity();
171
191
  if (
172
192
  lastProbe.bridgeConnected
@@ -176,7 +196,7 @@ async function waitForBridgeSessionChange(broker: BrowserAgentBroker, beforeProb
176
196
  ) {
177
197
  return lastProbe;
178
198
  }
179
- await new Promise((resolve) => setTimeout(resolve, 100));
199
+ await sleepUnlessAborted(100, signal);
180
200
  }
181
201
 
182
202
  throw {
@@ -203,7 +223,14 @@ function createRequestTool(options: {
203
223
  description: createToolDescription(options.description),
204
224
  promptSnippet: options.promptSnippet,
205
225
  parameters: options.parameters,
206
- async execute(_toolCallId: string, params: Record<string, unknown>): Promise<ToolResult> {
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> {
207
234
  const requestParams = options.name === 'browser_clear_site_data'
208
235
  ? withClearSiteDataTarget(params)
209
236
  : [
@@ -215,10 +242,17 @@ function createRequestTool(options: {
215
242
  ? withDefaultActiveTabTarget(params)
216
243
  : params;
217
244
 
218
- const outcome = await brokerToolRequest(broker, options.name, requestParams, options.timeoutFromParams(requestParams));
245
+ const outcome = await brokerToolRequest(
246
+ broker,
247
+ options.name,
248
+ requestParams,
249
+ options.timeoutFromParams(requestParams),
250
+ signal,
251
+ );
219
252
  if (!outcome.ok) {
220
- return textResult(`${options.name} failed: ${outcome.error.message}`, {
253
+ return textResult(formatFailureText(options.name, outcome.error), {
221
254
  ok: false,
255
+ cancelled: outcome.error.code === 'E_ABORTED' || undefined,
222
256
  error: outcome.error,
223
257
  request: requestParams,
224
258
  });
@@ -432,13 +466,18 @@ export function createBrowserReloadExtensionTool(broker: BrowserAgentBroker) {
432
466
  description: createToolDescription(browserReloadExtensionDefinition.description),
433
467
  promptSnippet: browserReloadExtensionDefinition.promptSnippet,
434
468
  parameters: browserReloadExtensionDefinition.parameters,
435
- async execute(_toolCallId: string, params: { timeout_ms?: number }): Promise<ToolResult> {
469
+ async execute(
470
+ _toolCallId: string,
471
+ params: { timeout_ms?: number },
472
+ signal?: AbortSignal,
473
+ ): Promise<ToolResult> {
436
474
  const timeoutMs = Number(params.timeout_ms ?? 15_000);
437
475
  const beforeProbe = broker.probeConnectivity();
438
- const outcome = await brokerToolRequest(broker, 'browser_reload_extension', params, timeoutMs);
476
+ const outcome = await brokerToolRequest(broker, 'browser_reload_extension', params, timeoutMs, signal);
439
477
  if (!outcome.ok) {
440
- return textResult('browser_reload_extension failed: ' + outcome.error.message, {
478
+ return textResult(formatFailureText('browser_reload_extension', outcome.error), {
441
479
  ok: false,
480
+ cancelled: outcome.error.code === 'E_ABORTED' || undefined,
442
481
  error: outcome.error,
443
482
  request: params,
444
483
  probeBefore: beforeProbe,
@@ -446,7 +485,7 @@ export function createBrowserReloadExtensionTool(broker: BrowserAgentBroker) {
446
485
  }
447
486
 
448
487
  try {
449
- const afterProbe = await waitForBridgeSessionChange(broker, beforeProbe, timeoutMs);
488
+ const afterProbe = await waitForBridgeSessionChange(broker, beforeProbe, timeoutMs, signal);
450
489
  const data = { ...(outcome.data as Record<string, unknown>), reconnected: true };
451
490
  const protocolError = validateSuccessPayload('browser_reload_extension', data);
452
491
  if (protocolError) {
@@ -471,8 +510,9 @@ export function createBrowserReloadExtensionTool(broker: BrowserAgentBroker) {
471
510
  });
472
511
  } catch (error) {
473
512
  const errorInfo = errorInfoFromUnknown(error);
474
- return textResult('browser_reload_extension failed: ' + errorInfo.message, {
513
+ return textResult(formatFailureText('browser_reload_extension', errorInfo), {
475
514
  ok: false,
515
+ cancelled: isAbortError(error) || undefined,
476
516
  error: errorInfo,
477
517
  request: params,
478
518
  result: outcome.data,
@@ -5,9 +5,11 @@ import {
5
5
  coerceError,
6
6
  defaultTimeoutMs,
7
7
  formatJsonResult,
8
+ formatToolFailureText,
8
9
  requestBridge,
9
10
  textResult,
10
11
  } from './read_only/common.ts';
12
+ import { isAbortError } from '../broker/abort.ts';
11
13
  import type { ToolResult } from './read_only/common.ts';
12
14
 
13
15
  function withDefaultActiveTabTarget(params: Record<string, unknown>) {
@@ -58,11 +60,16 @@ export function createBrowserGetConsoleLogsTool(broker: BrowserAgentBroker) {
58
60
  include_stack: Type.Optional(Type.Boolean()),
59
61
  timeout_ms: Type.Optional(Type.Number({ minimum: 1, maximum: 60_000 })),
60
62
  }),
61
- async execute(_toolCallId: string, params: Record<string, unknown>): Promise<ToolResult> {
63
+ async execute(
64
+ _toolCallId: string,
65
+ params: Record<string, unknown>,
66
+ signal?: AbortSignal,
67
+ ): Promise<ToolResult> {
62
68
  const requestParams = withDefaultActiveTabTarget(params);
63
69
  try {
64
70
  const { data } = await requestBridge<Record<string, unknown>>(broker, 'browser_get_console_logs', requestParams, {
65
71
  timeoutMs: Number(requestParams.timeout_ms || defaultTimeoutMs('browser_get_console_logs')),
72
+ signal,
66
73
  });
67
74
 
68
75
  const rendered = await formatJsonResult('Browser console logs', data, 'json');
@@ -80,8 +87,9 @@ export function createBrowserGetConsoleLogsTool(broker: BrowserAgentBroker) {
80
87
  return textResult(consoleLogText(details), details);
81
88
  } catch (error) {
82
89
  const info = coerceError(error);
83
- return textResult(`browser_get_console_logs failed: ${info.message}`, {
90
+ return textResult(formatToolFailureText('browser_get_console_logs', info), {
84
91
  ok: false,
92
+ cancelled: isAbortError(error) || undefined,
85
93
  error: { code: info.code, message: info.message, details: info.details },
86
94
  });
87
95
  }
@@ -124,11 +132,16 @@ export function createBrowserGetNetworkTool(broker: BrowserAgentBroker) {
124
132
  include_timing: Type.Optional(Type.Boolean()),
125
133
  timeout_ms: Type.Optional(Type.Number({ minimum: 1, maximum: 60_000 })),
126
134
  }),
127
- async execute(_toolCallId: string, params: Record<string, unknown>): Promise<ToolResult> {
135
+ async execute(
136
+ _toolCallId: string,
137
+ params: Record<string, unknown>,
138
+ signal?: AbortSignal,
139
+ ): Promise<ToolResult> {
128
140
  const requestParams = withDefaultActiveTabTarget(params);
129
141
  try {
130
142
  const { data } = await requestBridge<Record<string, unknown>>(broker, 'browser_get_network', requestParams, {
131
143
  timeoutMs: Number(requestParams.timeout_ms || defaultTimeoutMs('browser_get_network')),
144
+ signal,
132
145
  });
133
146
 
134
147
  const rendered = await formatJsonResult('Browser network activity', data, 'json');
@@ -146,8 +159,9 @@ export function createBrowserGetNetworkTool(broker: BrowserAgentBroker) {
146
159
  return textResult(networkText(details), details);
147
160
  } catch (error) {
148
161
  const info = coerceError(error);
149
- return textResult(`browser_get_network failed: ${info.message}`, {
162
+ return textResult(formatToolFailureText('browser_get_network', info), {
150
163
  ok: false,
164
+ cancelled: isAbortError(error) || undefined,
151
165
  error: { code: info.code, message: info.message, details: info.details },
152
166
  });
153
167
  }
@@ -6,6 +6,7 @@ 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';
9
10
 
10
11
  interface ToolResult {
11
12
  content: Array<{ type: 'text'; text: string }>;
@@ -206,10 +207,20 @@ export function createBrowserRunTaskTool(broker: BrowserAgentBroker) {
206
207
  async execute(
207
208
  _toolCallId: string,
208
209
  params: { task: string; tab_id?: number; use_active_tab?: boolean; debugMode?: boolean; timeoutMs?: number },
210
+ signal?: AbortSignal,
209
211
  ): Promise<ToolResult> {
210
212
  // Lazily (re)acquire the broker so a killed primary is replaced on demand,
211
213
  // and wait out the extension's reconnect window before deciding we are down.
212
- await broker.ensureReady?.();
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
+ }
213
224
  const probe = broker.probeConnectivity();
214
225
 
215
226
  // Fail fast with actionable diagnostics rather than recording a task that
@@ -251,25 +262,37 @@ export function createBrowserRunTaskTool(broker: BrowserAgentBroker) {
251
262
  response = await broker.request(
252
263
  'browser_run_task',
253
264
  request,
254
- { timeoutMs: params.timeoutMs ?? 5 * 60 * 1000 },
265
+ { timeoutMs: params.timeoutMs ?? 5 * 60 * 1000, signal },
255
266
  );
256
267
  } catch (error) {
257
268
  const errorInfo = errorInfoFromUnknown(error);
258
- const history = await finishRecordedTask(broker, taskId, '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, {
259
276
  error: errorInfo,
260
277
  bridge: { connected: broker.probeConnectivity().bridgeConnected },
261
278
  });
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
- });
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
+ );
273
296
  }
274
297
 
275
298
  if (!response.ok) {
@@ -10,6 +10,7 @@ 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';
13
14
 
14
15
  const SCREENSHOT_TEMP_DIR = join(tmpdir(), 'pi-browser-agent', 'screenshots');
15
16
  const SCREENSHOT_TEMP_MAX_AGE_MS = 24 * 60 * 60 * 1000;
@@ -30,7 +31,8 @@ export interface ReadOnlyToolDefinition<TParams = Record<string, unknown>> {
30
31
  description: string;
31
32
  promptSnippet: string;
32
33
  parameters: TSchema;
33
- execute: (toolCallId: string, params: TParams) => Promise<ToolResult>;
34
+ /** `signal` is pi's per-tool-call cancellation handle (Escape). */
35
+ execute: (toolCallId: string, params: TParams, signal?: AbortSignal) => Promise<ToolResult>;
34
36
  }
35
37
 
36
38
  export class BrowserReadOnlyToolError extends Error {
@@ -89,6 +91,15 @@ export function coerceError(error: unknown, fallbackCode = 'E_INTERNAL'): Browse
89
91
  return new BrowserReadOnlyToolError(normalizedCode, message);
90
92
  }
91
93
 
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
+
92
103
  export function ensureBridgeConnected(broker: BrowserAgentBroker, toolName?: string): void {
93
104
  const probe = broker.probeConnectivity();
94
105
  if (probe.brokerListening && probe.bridgeConnected) {
@@ -104,13 +115,17 @@ export async function requestBridge<TData>(
104
115
  broker: BrowserAgentBroker,
105
116
  type: string,
106
117
  params: unknown,
107
- options: { timeoutMs?: number } = {},
118
+ options: BrokerRequestOptions = {},
108
119
  ): Promise<{ response: ResponseFrame; data: TData }> {
120
+ const { signal } = options;
121
+ if (signal?.aborted) throw coerceError(abortError(type, signal));
109
122
  // Lazily (re)acquire the broker before the readiness check so a killed
110
123
  // primary is replaced (or reconnected to) on this request instead of failing.
111
124
  // ensureReady() also absorbs the extension's reconnect window, so a call that
112
- // lands mid-reconnect waits instead of failing.
113
- await broker.ensureReady?.();
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));
114
129
  ensureBridgeConnected(broker, type);
115
130
 
116
131
  let response: ResponseFrame;
@@ -3,6 +3,7 @@ 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';
6
7
  import {
7
8
  BrowserReadOnlyToolError,
8
9
  type ReadOnlyToolDefinition,
@@ -10,6 +11,7 @@ import {
10
11
  defaultTimeoutMs,
11
12
  formatJsonResult,
12
13
  formatTextResult,
14
+ formatToolFailureText,
13
15
  imageResult,
14
16
  inferFileExtensionFromMime,
15
17
  normalizeScreenshotPayload,
@@ -57,10 +59,11 @@ function createJsonReadOnlyTool<TParams>(
57
59
  description: config.description,
58
60
  promptSnippet: config.promptSnippet,
59
61
  parameters: config.parameters,
60
- async execute(_toolCallId: string, params: TParams) {
62
+ async execute(_toolCallId: string, params: TParams, signal?: AbortSignal) {
61
63
  try {
62
64
  const { data, response } = await requestBridge<any>(broker, config.name, params, {
63
65
  timeoutMs: config.timeoutMs ? config.timeoutMs(params) : defaultTimeoutMs(config.name),
66
+ signal,
64
67
  });
65
68
  const normalized = config.normalizeData ? config.normalizeData(data) : data;
66
69
  const formatted = await formatJsonResult(config.title(normalized, params), normalized);
@@ -74,8 +77,9 @@ function createJsonReadOnlyTool<TParams>(
74
77
  });
75
78
  } catch (error) {
76
79
  const info = coerceError(error);
77
- return textResult(`${config.label} failed: ${info.message}`, {
80
+ return textResult(formatToolFailureText(config.label, info), {
78
81
  ok: false,
82
+ cancelled: isAbortError(error) || undefined,
79
83
  requestType: config.name,
80
84
  error: { code: info.code, message: info.message, details: info.details },
81
85
  });
@@ -117,10 +121,11 @@ function createScreenshotTool(broker: BrowserAgentBroker): ReadOnlyToolDefinitio
117
121
  quality: Type.Optional(Type.Number({ minimum: 0, maximum: 1 })),
118
122
  max_width: Type.Optional(Type.Number({ minimum: 1 })),
119
123
  }),
120
- async execute(_toolCallId: string, params: any) {
124
+ async execute(_toolCallId: string, params: any, signal?: AbortSignal) {
121
125
  try {
122
126
  const { data, response } = await requestBridge<any>(broker, 'browser_get_screenshot', params, {
123
127
  timeoutMs: defaultTimeoutMs('browser_get_screenshot'),
128
+ signal,
124
129
  });
125
130
  const normalized = normalizeScreenshotPayload(data);
126
131
  let path = normalized.path;
@@ -165,8 +170,9 @@ function createScreenshotTool(broker: BrowserAgentBroker): ReadOnlyToolDefinitio
165
170
  return textResult(text, details);
166
171
  } catch (error) {
167
172
  const info = coerceError(error);
168
- return textResult(`browser_get_screenshot failed: ${info.message}`, {
173
+ return textResult(formatToolFailureText('browser_get_screenshot', info), {
169
174
  ok: false,
175
+ cancelled: isAbortError(error) || undefined,
170
176
  requestType: 'browser_get_screenshot',
171
177
  error: { code: info.code, message: info.message, details: info.details },
172
178
  });
@@ -193,10 +199,11 @@ function createHtmlTool(broker: BrowserAgentBroker): ReadOnlyToolDefinition<any>
193
199
  strip: Type.Optional(includeType(['script', 'style', 'comments'])),
194
200
  max_bytes: Type.Optional(Type.Number({ minimum: 1 })),
195
201
  }),
196
- async execute(_toolCallId: string, params: any) {
202
+ async execute(_toolCallId: string, params: any, signal?: AbortSignal) {
197
203
  try {
198
204
  const { data, response } = await requestBridge<any>(broker, 'browser_get_html', params, {
199
205
  timeoutMs: defaultTimeoutMs('browser_get_html'),
206
+ signal,
200
207
  });
201
208
  if (typeof data?.html !== 'string' && typeof data?.content !== 'string') {
202
209
  throw new BrowserReadOnlyToolError(
@@ -217,8 +224,9 @@ function createHtmlTool(broker: BrowserAgentBroker): ReadOnlyToolDefinition<any>
217
224
  });
218
225
  } catch (error) {
219
226
  const info = coerceError(error);
220
- return textResult(`browser_get_html failed: ${info.message}`, {
227
+ return textResult(formatToolFailureText('browser_get_html', info), {
221
228
  ok: false,
229
+ cancelled: isAbortError(error) || undefined,
222
230
  requestType: 'browser_get_html',
223
231
  error: { code: info.code, message: info.message, details: info.details },
224
232
  });
@@ -0,0 +1,243 @@
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
+ });