oira666_pi-browser-agent 0.0.18 → 0.0.20

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/AGENTS.md ADDED
@@ -0,0 +1,16 @@
1
+ # Working preferences
2
+
3
+ - Treat models as senior architects. Keep prompts task-specific, with my explicit preferences rather than generic advice or repeated global instructions.
4
+ - Pull the latest changes from `origin` before starting work. Commit and push each finished piece as soon as it is ready; I work across multiple machines.
5
+ - Test only against the latest Pi release. On every release, update the README line `Tested against Pi <version>` to the version actually tested and keep any supported-Pi metadata in `package.json` current.
6
+
7
+ ## Code quality bar
8
+
9
+ - Remove dead code, unused imports, and unused dependencies. Wire intended functionality into the application instead of leaving disconnected code.
10
+ - Keep module responsibilities and dependency boundaries clear. Follow existing project conventions and use TypeScript libraries and frameworks as intended.
11
+ - Avoid duplicated logic and unnecessary abstractions. Prefer simple, consistent solutions over one-off patterns.
12
+ - Fix root causes, not symptoms. Avoid brittle workarounds. Make deployment-specific values and operational settings configurable, and never hardcode secrets.
13
+ - Use strict TypeScript and types that model valid application states. Validate external data at runtime. Do not bypass type safety with `any`, unsafe assertions, or suppressed type errors.
14
+ - Keep functions and classes focused. Split files by responsibility before they exceed 350 lines. Exceed this limit only when splitting would clearly hurt readability or cohesion, and explain why.
15
+ - Remove stale or irrelevant comments and docs. Keep useful ones accurate, short, clear, and human-friendly. Explain non-obvious decisions rather than restating code. Apply the unslop and write-prompts skills when available.
16
+ - Add or update tests for changed behavior. Run the project's available type checks, lint checks, and relevant tests before considering work complete.
package/README.md CHANGED
@@ -1,11 +1,13 @@
1
1
  # pi-browser-agent
2
2
 
3
+ Tested against Pi 1.4.0
4
+
3
5
  `pi-browser-agent` is a pi extension that starts a local WebSocket broker and registers a browser-driving tool suite for `browser-agent-ext`.
4
6
 
5
7
  ## What it does
6
8
 
7
9
  - starts a loopback-only broker on `ws://127.0.0.1:7878` by default
8
- - registers the full `browser_*` tool suite at session start when the broker starts listening
10
+ - registers the full `browser_*` tool suite at session start, even while the broker or bridge is unavailable
9
11
  - exposes `activate_browser_agent_tools` as a self-check / status tool
10
12
  - forwards tool calls to `browser-agent-ext`
11
13
  - keeps browser-task history on disk for local inspection
@@ -41,7 +43,7 @@ For the current in-repo state, use the local-checkout form above.
41
43
 
42
44
  ## First use in a pi session
43
45
 
44
- All `browser_*` tools are registered at session start when the broker starts listening. `activate_browser_agent_tools` remains available as a self-check / status tool:
46
+ All `browser_*` tools are registered at session start independently of broker availability. `activate_browser_agent_tools` remains available as a self-check / status tool:
45
47
 
46
48
  ```text
47
49
  activate_browser_agent_tools
@@ -62,11 +64,13 @@ The full toolkit registered for the session is:
62
64
  - `browser_get_performance_metrics`
63
65
  - `browser_evaluate_js`
64
66
  - `browser_run_js`
67
+ - `browser_create_tab`
65
68
  - `browser_list_tabs`
66
69
  - `browser_switch_tab`
67
70
  - `browser_close_tab`
68
71
  - `browser_navigate`
69
72
  - `browser_reload`
73
+ - `browser_reload_extension`
70
74
  - `browser_wait_for`
71
75
  - `browser_clear_site_data`
72
76
 
@@ -98,6 +102,16 @@ Example:
98
102
  PI_BA_HOST=0.0.0.0 pi
99
103
  ```
100
104
 
105
+ ## Development and release checks
106
+
107
+ Run `npm ci --ignore-scripts` to install the locked development dependencies, then `npm test` to typecheck and run the suite. The Pi SDK development dependency is pinned to the tested release; tests do not update the manifest or lockfile.
108
+
109
+ The tests include SDK extension loading, local broker lifecycle checks, and browser-tool protocol tests. `npm run typecheck` checks the currently installed dependencies. Registered tools retain their text/image output and persisted details, and additionally expose JSON-normalized details through Pi's `outputSchema`/`structuredContent` APIs. Failed browser operations set `isError: true` so Pi and programmatic callers can distinguish failures without parsing text.
110
+
111
+ Also run `PI_EVERGREEN_PI_BIN=/absolute/path/to/global/pi npm run test:e2e`. This explicitly loads the local extension into that real Pi CLI, using an isolated agent directory, a deterministic local OpenAI-compatible SSE endpoint and a WebSocket bridge fixture (no credentials or model charges). It checks actual outbound requests, tool execution, retry/abort recovery, compaction, reload with a connected bridge, persistent task history, session replacement and cleanup. Linux also exercises real suspend/resume. `PI_EVERGREEN_E2E_PROVIDER`, `PI_EVERGREEN_E2E_MODEL` and `PI_EVERGREEN_E2E_REASONING` select the test model identity (defaults: `openai`, `gpt-6-luna`, `medium`). These tests do not replace a live Chrome end-to-end check.
112
+
113
+ Before every release, update the tested-against line above to the actual Pi version that passed the checks, and keep the supported Pi peer range in `package.json` accurate. See `AGENTS.md` for the release and code quality rules.
114
+
101
115
  ## Notes
102
116
 
103
117
  - The broker never synthesizes browser input. Browser actions still go through the extension runtime and its configured input backend.
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.20",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Pi browser agent broker skeleton with lazy browser tool registration",
@@ -14,18 +14,23 @@
14
14
  ]
15
15
  },
16
16
  "scripts": {
17
- "test": "node --test ./tests/*.test.ts ./tests/tools/*.test.ts"
17
+ "typecheck": "tsc --noEmit",
18
+ "pretest": "npm run typecheck",
19
+ "test": "node --test ./tests/*.test.ts ./tests/tools/*.test.ts",
20
+ "test:e2e": "node --test ./tests/pi-cli.e2e.ts"
18
21
  },
19
22
  "dependencies": {
20
23
  "ws": "^8.18.3"
21
24
  },
22
25
  "peerDependencies": {
23
- "@sinclair/typebox": "*"
26
+ "@earendil-works/pi-coding-agent": ">=1.4.0",
27
+ "typebox": "*"
24
28
  },
25
29
  "devDependencies": {
26
- "@sinclair/typebox": "^0.34.41",
30
+ "@earendil-works/pi-coding-agent": "1.4.0",
27
31
  "@types/node": "^25.6.0",
28
32
  "@types/ws": "^8.18.1",
33
+ "typebox": "^1.3.27",
29
34
  "typescript": "^5.9.3"
30
35
  }
31
36
  }
@@ -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,24 +1,22 @@
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
 
13
14
  /**
14
15
  * A broker handle that resolves its real backing broker lazily, on every call.
15
16
  *
16
- * Why this exists: pi reads the tool registry once at session_start, and any
17
- * registerTool() after that is dropped. Previously the browser_* suite was only
18
- * registered when the broker happened to be listening at session_start, so a pi
19
- * instance started while the browser stack was down had NO browser tools for its
20
- * entire lifetime — unrecoverable without restarting pi. And a session whose
21
- * broker later died held a dead object forever.
17
+ * Registering tools independently of broker availability keeps them visible
18
+ * while Chrome is offline. Resolving at call time also avoids holding a dead
19
+ * broker after a disconnect or primary-process failover.
22
20
  *
23
21
  * With this handle the tools are always registered and always re-resolve the
24
22
  * broker at call time, so the integration heals itself whenever the browser
@@ -139,7 +137,7 @@ export class LazyBrokerHandle implements BrokerLike {
139
137
  return probe;
140
138
  }
141
139
 
142
- async request(type: string, params: unknown, options: { timeoutMs?: number } = {}): Promise<ResponseFrame> {
140
+ async request(type: string, params: unknown, options: BrokerRequestOptions = {}): Promise<ResponseFrame> {
143
141
  if (this.disposed) {
144
142
  throw new Error('E_BRIDGE_DISCONNECTED');
145
143
  }
@@ -1,6 +1,5 @@
1
- import { Type } from '@sinclair/typebox';
2
- import type { Static } from '@sinclair/typebox';
3
- import { Value } from '@sinclair/typebox/value';
1
+ import { Type, type Static } from 'typebox';
2
+ import { Value } from 'typebox/value';
4
3
 
5
4
  export const PROTOCOL_VERSION = 1;
6
5
 
@@ -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
  }
@@ -1,4 +1,6 @@
1
1
  import { randomUUID } from 'node:crypto';
2
+ import { createServer } from 'node:http';
3
+ import type { Socket } from 'node:net';
2
4
  import { WebSocketServer, type RawData, type WebSocket } from 'ws';
3
5
 
4
6
  interface BridgeSocket extends WebSocket {
@@ -16,6 +18,13 @@ import {
16
18
  type ResponseFrame,
17
19
  } from './protocol.ts';
18
20
  import { TaskStore } from './task-store.ts';
21
+ import {
22
+ abortError,
23
+ onAbort,
24
+ throwIfAborted,
25
+ type BrokerRequestOptions,
26
+ type AbortableOptions,
27
+ } from './abort.ts';
19
28
 
20
29
  export interface BrokerLogger {
21
30
  info?: (...args: unknown[]) => void;
@@ -67,7 +76,7 @@ export interface BridgeStateEvent {
67
76
 
68
77
  export type BridgeStateListener = (state: BridgeStateEvent) => void;
69
78
 
70
- export interface EnsureReadyOptions {
79
+ export interface EnsureReadyOptions extends AbortableOptions {
71
80
  /** Override the bridge wait budget. 0 disables waiting entirely. */
72
81
  waitForBridgeMs?: number;
73
82
  }
@@ -95,6 +104,7 @@ export class BrowserAgentBroker {
95
104
  private pingTimer: ReturnType<typeof setInterval> | null = null;
96
105
  private pendingRequests = new Map<string, PendingRequest>();
97
106
  private sockets = new Set<BridgeSocket>();
107
+ private transports = new Set<Socket>();
98
108
  private listeningSince: number | null = null;
99
109
  private bridgeEverConnected = false;
100
110
  private lastBridgeConnectedAt: number | null = null;
@@ -258,8 +268,12 @@ export class BrowserAgentBroker {
258
268
  // failing a tool call that arrived mid-reconnect. This is what makes the
259
269
  // integration self-healing from the agent's point of view.
260
270
  const budget = this.resolveBridgeWaitMs(options);
261
- const connected = await this.waitForBridge(budget);
262
- this.recordBridgeWaitOutcome(connected, budget);
271
+ const connected = await this.waitForBridge(budget, options.signal);
272
+ // A wait cut short by Escape says nothing about whether the browser is
273
+ // cold, so it must not feed the cold-bridge memo.
274
+ if (!options.signal?.aborted) {
275
+ this.recordBridgeWaitOutcome(connected, budget);
276
+ }
263
277
  }
264
278
 
265
279
  /** Remember that the full budget was burned without a bridge showing up, so
@@ -308,23 +322,29 @@ export class BrowserAgentBroker {
308
322
  /** Resolve as soon as a Chrome extension bridge is connected, or after
309
323
  * `timeoutMs`. Never rejects — callers decide what to do with a still-absent
310
324
  * bridge. */
311
- async waitForBridge(timeoutMs: number): Promise<boolean> {
325
+ async waitForBridge(timeoutMs: number, signal?: AbortSignal): Promise<boolean> {
312
326
  if (this.bridgeSocket && this.bridgeHello) return true;
327
+ if (signal?.aborted) return false;
313
328
  if (!this.server || timeoutMs <= 0) return false;
314
329
 
315
330
  return await new Promise<boolean>((resolve) => {
316
331
  let settled = false;
332
+ let releaseAbort = () => {};
317
333
  const finish = (value: boolean) => {
318
334
  if (settled) return;
319
335
  settled = true;
320
336
  this.bridgeWaiters.delete(waiter);
321
337
  clearTimeout(timer);
338
+ releaseAbort();
322
339
  resolve(value);
323
340
  };
324
341
  const waiter = (connected: boolean) => finish(connected);
325
342
  const timer = setTimeout(() => finish(!!this.bridgeSocket && !!this.bridgeHello), timeoutMs);
326
343
  timer.unref?.();
327
344
  this.bridgeWaiters.add(waiter);
345
+ // Waiting out an 8s reconnect window is the other place Escape used to
346
+ // hang, before any request is even sent.
347
+ releaseAbort = onAbort(signal, () => finish(false));
328
348
  });
329
349
  }
330
350
 
@@ -402,7 +422,16 @@ export class BrowserAgentBroker {
402
422
 
403
423
  private async tryBind(candidate: number): Promise<void> {
404
424
  await new Promise<void>((resolve, reject) => {
405
- const server = new WebSocketServer({ host: this.host, port: candidate });
425
+ const httpServer = createServer((_request, response) => {
426
+ response.writeHead(426, { 'Content-Type': 'text/plain' });
427
+ response.end('Upgrade Required');
428
+ });
429
+ httpServer.on('connection', (socket) => {
430
+ this.transports.add(socket);
431
+ socket.once('close', () => this.transports.delete(socket));
432
+ });
433
+ const server = new WebSocketServer({ server: httpServer });
434
+ server.once('close', () => httpServer.close());
406
435
 
407
436
  const onError = (error: Error) => {
408
437
  server.off('listening', onListening);
@@ -437,6 +466,7 @@ export class BrowserAgentBroker {
437
466
  server.on('connection', (socket: WebSocket) => {
438
467
  void this.handleConnection(socket);
439
468
  });
469
+ httpServer.listen(candidate, this.host);
440
470
  });
441
471
  }
442
472
 
@@ -456,6 +486,13 @@ export class BrowserAgentBroker {
456
486
  this.notifyBridgeWaiters(false);
457
487
  this.bridgeStateListeners.clear();
458
488
 
489
+ // Finish upgraded connections before closing the listener. The packaged
490
+ // Pi runtime can otherwise leave ws's HTTP close callback pending forever,
491
+ // even after all clients have completed their closing handshakes.
492
+ const closingSockets = [...this.sockets].map((socket) => new Promise<void>((resolve) => {
493
+ const timeout = setTimeout(() => socket.terminate(), 250);
494
+ socket.once('close', () => { clearTimeout(timeout); resolve(); });
495
+ }));
459
496
  for (const socket of this.sockets) {
460
497
  try {
461
498
  socket.close();
@@ -475,6 +512,11 @@ export class BrowserAgentBroker {
475
512
  }
476
513
  }
477
514
 
515
+ await Promise.all(closingSockets);
516
+ // Explicitly retire upgraded TCP transports too; a completed WebSocket
517
+ // handshake need not mean the host HTTP server has released its connection.
518
+ for (const socket of this.transports) socket.destroy();
519
+ this.transports.clear();
478
520
  this.listeningSince = null;
479
521
 
480
522
  if (this.server) {
@@ -510,7 +552,10 @@ export class BrowserAgentBroker {
510
552
  });
511
553
  }
512
554
 
513
- async request(type: string, params: unknown, options: { timeoutMs?: number } = {}): Promise<ResponseFrame> {
555
+ async request(type: string, params: unknown, options: BrokerRequestOptions = {}): Promise<ResponseFrame> {
556
+ // Never open a request for a caller that has already cancelled.
557
+ throwIfAborted(options.signal, type);
558
+
514
559
  const socket = this.bridgeSocket;
515
560
  if (!socket || !this.bridgeHello) {
516
561
  throw new Error('E_BRIDGE_DISCONNECTED');
@@ -520,29 +565,45 @@ export class BrowserAgentBroker {
520
565
  const payload = JSON.stringify({ v: 1, kind: 'request', id, type, params });
521
566
 
522
567
  return await new Promise<ResponseFrame>((resolve, reject) => {
523
- const timeout = setTimeout(() => {
568
+ let releaseAbort = () => {};
569
+ const settle = (fn: () => void) => {
524
570
  this.pendingRequests.delete(id);
525
- reject(new Error(`Request timed out: ${type}`));
571
+ clearTimeout(timeout);
572
+ releaseAbort();
573
+ fn();
574
+ };
575
+
576
+ const timeout = setTimeout(() => {
577
+ settle(() => reject(new Error(`Request timed out: ${type}`)));
526
578
  }, options.timeoutMs ?? this.requestTimeoutMs);
527
579
  timeout.unref?.();
528
580
 
529
- this.pendingRequests.set(id, { resolve, reject, timeout });
581
+ this.pendingRequests.set(id, {
582
+ resolve: (frame) => settle(() => resolve(frame)),
583
+ reject: (error) => settle(() => reject(error)),
584
+ timeout,
585
+ });
586
+
587
+ // Escape (or any other cancellation) hands pi back control immediately.
588
+ // The bridge has no cancel frame yet, so the in-flight browser work still
589
+ // finishes; we just stop waiting for it and drop the pending entry so a
590
+ // late response is ignored instead of resolving a dead promise.
591
+ releaseAbort = onAbort(options.signal, () => {
592
+ settle(() => reject(abortError(type, options.signal)));
593
+ });
594
+ if (options.signal?.aborted) return;
530
595
 
531
596
  // If the bridge went away between our validation and send, reject fast
532
597
  // so callers get a direct disconnect error instead of waiting for a timeout.
533
598
  if (this.bridgeSocket !== socket) {
534
- clearTimeout(timeout);
535
- this.pendingRequests.delete(id);
536
- reject(new Error('E_BRIDGE_DISCONNECTED'));
599
+ settle(() => reject(new Error('E_BRIDGE_DISCONNECTED')));
537
600
  return;
538
601
  }
539
602
 
540
603
  try {
541
604
  socket.send(payload);
542
605
  } catch (error) {
543
- clearTimeout(timeout);
544
- this.pendingRequests.delete(id);
545
- reject(error instanceof Error ? error : new Error(String(error)));
606
+ settle(() => reject(error instanceof Error ? error : new Error(String(error))));
546
607
  }
547
608
  });
548
609
  }