oira666_pi-browser-agent 0.0.16 → 0.0.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -78,7 +78,11 @@ Environment variables:
78
78
  - `PI_BA_PORT` — broker port, default `7878`
79
79
  - `PI_BA_TASK_TTL_DAYS` — task-history retention
80
80
 
81
- If port `7878` is busy, the broker fails fast and asks you to set `PI_BA_PORT`.
81
+ If another pi instance owns port `7878`, this session connects through it. If acquisition fails, the extension retries in the background.
82
+
83
+ ## Connection status
84
+
85
+ The status line shows `browser: connected`, `browser: recovering`, or `browser: disconnected`. Transient disconnects and successful recovery do not produce notifications. After 60 seconds without a connection, the extension shows one short warning for that outage and continues retrying quietly. Broker logs and stack traces are not forwarded to the TUI. Use `activate_browser_agent_tools` for on-demand diagnostics.
82
86
 
83
87
  ## WSL → Windows Chrome
84
88
 
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.18",
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"
@@ -0,0 +1,59 @@
1
+ import type { BrokerLogger } from './server.ts';
2
+
3
+ export type BrowserHealthUi = {
4
+ notify?: (message: string, type?: 'info' | 'warning' | 'error') => void;
5
+ setStatus?: (key: string, text: string | undefined) => void;
6
+ };
7
+
8
+ // Broker logs describe individual attempts, not the outcome of recovery. Never
9
+ // forward them (or Error objects) into pi's notifications or runtime console.
10
+ export const quietBrokerLogger: BrokerLogger = { info() {}, warn() {}, error() {} };
11
+ export const RECOVERY_GRACE_MS = 60_000;
12
+
13
+ /** One reporter per session, retained across broker replacements. */
14
+ export class BrowserHealthReporter {
15
+ private disconnectedSince: number | null = null;
16
+ private warned = false;
17
+ private status: string | undefined;
18
+ private disposed = false;
19
+
20
+ private readonly ui?: BrowserHealthUi;
21
+
22
+ constructor(ui?: BrowserHealthUi) {
23
+ this.ui = ui;
24
+ }
25
+
26
+ observe(connected: boolean, now = Date.now()): void {
27
+ if (this.disposed) return;
28
+ if (connected) {
29
+ this.disconnectedSince = null;
30
+ this.warned = false;
31
+ this.setStatus('browser: connected');
32
+ return;
33
+ }
34
+ this.disconnectedSince ??= now;
35
+ const expired = now - this.disconnectedSince >= RECOVERY_GRACE_MS;
36
+ this.setStatus(expired ? 'browser: disconnected' : 'browser: recovering');
37
+ if (expired && !this.warned) {
38
+ this.warned = true;
39
+ this.ui?.notify?.('Browser unavailable. Check Chrome and the Browser Agent extension; retrying quietly.', 'warning');
40
+ }
41
+ }
42
+
43
+ /** Time spent suspended is not a failed recovery attempt. Keep the warning
44
+ * latch, but give an unfinished recovery a fresh grace period on resume. */
45
+ resume(): void {
46
+ this.disconnectedSince = null;
47
+ }
48
+
49
+ dispose(): void {
50
+ this.disposed = true;
51
+ this.ui?.setStatus?.('browser-bridge', undefined);
52
+ }
53
+
54
+ private setStatus(status: string): void {
55
+ if (this.status === status) return;
56
+ this.status = status;
57
+ this.ui?.setStatus?.('browser-bridge', status);
58
+ }
59
+ }
@@ -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;
@@ -51,6 +44,7 @@ export class RemoteBrowserAgentBroker {
51
44
  readonly taskStore: TaskStore;
52
45
 
53
46
  private socket: WebSocket | null = null;
47
+ private validatedSocket: WebSocket | null = null;
54
48
  private connectPromise: Promise<void> | null = null;
55
49
  private pendingRequests = new Map<string, PendingRequest>();
56
50
  private startupError: Error | null = null;
@@ -142,7 +136,7 @@ export class RemoteBrowserAgentBroker {
142
136
  // Poll the primary's probe for the same budget a local broker would wait,
143
137
  // so a tool call arriving during a reconnect window succeeds instead of
144
138
  // reporting a hard "connection is down".
145
- await this.waitForRemoteBridge(options.waitForBridgeMs ?? this.defaultRemoteBridgeWaitMs(), options.signal);
139
+ await this.waitForRemoteBridge(options.waitForBridgeMs ?? this.defaultRemoteBridgeWaitMs());
146
140
  }
147
141
 
148
142
  /** Full budget only when the primary has actually seen a bridge at some point.
@@ -155,13 +149,13 @@ export class RemoteBrowserAgentBroker {
155
149
  return this.remoteProbe?.bridgeEverConnected === false ? COLD_BRIDGE_WAIT_MS : DEFAULT_BRIDGE_WAIT_MS;
156
150
  }
157
151
 
158
- private async waitForRemoteBridge(timeoutMs: number, signal?: AbortSignal): Promise<boolean> {
152
+ private async waitForRemoteBridge(timeoutMs: number): Promise<boolean> {
159
153
  if (this.probeConnectivity().bridgeConnected) {
160
154
  this.coldBridgeMisses = 0;
161
155
  this.coldBridgeSince = null;
162
156
  return true;
163
157
  }
164
- if (timeoutMs <= 0 || signal?.aborted) return false;
158
+ if (timeoutMs <= 0) return false;
165
159
  const deadline = Date.now() + timeoutMs;
166
160
  // Every sub-step below can block for up to ~1.5s, so the budget is
167
161
  // re-checked before each of them. Checking only at the top of the loop let a
@@ -170,10 +164,9 @@ export class RemoteBrowserAgentBroker {
170
164
  while (Date.now() < deadline) {
171
165
  const sleepMs = Math.min(250, deadline - Date.now());
172
166
  if (sleepMs > 0) {
173
- // Wakes immediately on Escape instead of finishing the tick.
174
- await sleepUnlessAborted(sleepMs, signal);
167
+ await new Promise((resolve) => setTimeout(resolve, sleepMs).unref?.());
175
168
  }
176
- if (this.stopped || signal?.aborted) return false;
169
+ if (this.stopped) return false;
177
170
  if (Date.now() >= deadline) break;
178
171
  try {
179
172
  await this.ensureConnected();
@@ -189,15 +182,14 @@ export class RemoteBrowserAgentBroker {
189
182
  if (Date.now() >= deadline) break;
190
183
  const promoted = await this.promoteOrReconnect();
191
184
  if (promoted) {
192
- const found = await promoted.waitForBridge(Math.max(0, deadline - Date.now()), signal);
193
- if (!signal?.aborted) this.recordBridgeWaitOutcome(found, timeoutMs);
185
+ const found = await promoted.waitForBridge(Math.max(0, deadline - Date.now()));
186
+ this.recordBridgeWaitOutcome(found, timeoutMs);
194
187
  return found;
195
188
  }
196
189
  }
197
190
  }
198
191
  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);
192
+ this.recordBridgeWaitOutcome(connected, timeoutMs);
201
193
  return connected;
202
194
  }
203
195
 
@@ -246,16 +238,24 @@ export class RemoteBrowserAgentBroker {
246
238
  }
247
239
  }
248
240
 
241
+ private closeSocket(terminate = false): void {
242
+ const socket = this.socket;
243
+ this.socket = null;
244
+ this.validatedSocket = null;
245
+ if (socket) {
246
+ try {
247
+ if (terminate) socket.terminate();
248
+ else socket.close();
249
+ } catch { /* ignore */ }
250
+ }
251
+ }
252
+
249
253
  async stop(): Promise<void> {
250
254
  this.stopped = true;
251
255
  this.cancelHealTimer();
252
256
  this.rejectPendingRequests(new Error('E_BRIDGE_DISCONNECTED'));
253
257
  const connecting = this.connectPromise;
254
- const socket = this.socket;
255
- this.socket = null;
256
- if (socket) {
257
- try { socket.close(); } catch { /* ignore */ }
258
- }
258
+ this.closeSocket();
259
259
  // A connect or promotion already in flight can otherwise publish a socket
260
260
  // or listener after stop() returns. Their completion paths observe
261
261
  // `stopped` and tear down instead of publishing.
@@ -267,11 +267,8 @@ export class RemoteBrowserAgentBroker {
267
267
  if (promotion) {
268
268
  try { await promotion; } catch { /* promotion failure is already logged */ }
269
269
  }
270
- const lateSocket = this.socket;
271
- this.socket = null;
272
- if (lateSocket) {
273
- try { lateSocket.close(); } catch { /* ignore */ }
274
- }
270
+ // Read the socket again after async work, which may have replaced it.
271
+ this.closeSocket();
275
272
  this.unsubscribePromoted?.();
276
273
  this.unsubscribePromoted = null;
277
274
  this.bridgeStateListeners.clear();
@@ -283,9 +280,8 @@ export class RemoteBrowserAgentBroker {
283
280
  }
284
281
  }
285
282
 
286
- async request(type: string, params: unknown, options: BrokerRequestOptions = {}): Promise<ResponseFrame> {
283
+ async request(type: string, params: unknown, options: { timeoutMs?: number } = {}): Promise<ResponseFrame> {
287
284
  if (this.stopped) throw new Error('E_BRIDGE_DISCONNECTED');
288
- throwIfAborted(options.signal, type);
289
285
  if (this.promotedBroker) {
290
286
  return await this.promotedBroker.request(type, params, options);
291
287
  }
@@ -309,34 +305,19 @@ export class RemoteBrowserAgentBroker {
309
305
  const payload = JSON.stringify({ v: 1, kind: 'request', id, type, params });
310
306
 
311
307
  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
308
  const timeout = setTimeout(() => {
321
- settle(() => reject(new Error(`Request timed out: ${type}`)));
309
+ this.pendingRequests.delete(id);
310
+ reject(new Error(`Request timed out: ${type}`));
322
311
  }, options.timeoutMs ?? this.requestTimeoutMs);
323
312
  timeout.unref?.();
324
313
 
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
-
314
+ this.pendingRequests.set(id, { resolve, reject, timeout });
336
315
  try {
337
316
  socket.send(payload);
338
317
  } catch (error) {
339
- settle(() => reject(error instanceof Error ? error : new Error(String(error))));
318
+ clearTimeout(timeout);
319
+ this.pendingRequests.delete(id);
320
+ reject(error instanceof Error ? error : new Error(String(error)));
340
321
  }
341
322
  });
342
323
  }
@@ -351,7 +332,7 @@ export class RemoteBrowserAgentBroker {
351
332
  // socket to the primary is gone; otherwise tools happily send requests
352
333
  // into a dead proxy and only fail on timeout, and callers cannot tell
353
334
  // "healed" from "still using a stale snapshot".
354
- const proxyAlive = !!this.socket && !this.startupError;
335
+ const proxyAlive = this.hasValidatedConnection();
355
336
  return {
356
337
  ...primary,
357
338
  brokerReachable: proxyAlive && primary.brokerReachable,
@@ -363,8 +344,8 @@ export class RemoteBrowserAgentBroker {
363
344
  };
364
345
  }
365
346
  return {
366
- brokerReachable: !this.startupError && !!this.socket,
367
- brokerListening: !this.startupError && !!this.socket,
347
+ brokerReachable: this.hasValidatedConnection(),
348
+ brokerListening: this.hasValidatedConnection(),
368
349
  bridgeConnected: false,
369
350
  startupError: this.startupError?.message,
370
351
  url: this.url,
@@ -373,7 +354,14 @@ export class RemoteBrowserAgentBroker {
373
354
  };
374
355
  }
375
356
 
357
+ private hasValidatedConnection(): boolean {
358
+ return !!this.socket && this.socket === this.validatedSocket
359
+ && this.socket.readyState === WebSocket.OPEN && !this.startupError;
360
+ }
361
+
376
362
  private async probePrimary(): Promise<ProbeResult> {
363
+ await this.ensureConnected();
364
+ const socket = this.socket;
377
365
  const response = await this.sendControlRequest('probe');
378
366
  if (!response.ok) {
379
367
  throw new Error(response.error?.message || 'Primary broker probe failed');
@@ -385,6 +373,10 @@ export class RemoteBrowserAgentBroker {
385
373
  if (data.supportsBrokerProxy !== true) {
386
374
  throw new Error(`Port ${this.port} has an old pi-browser-agent broker; restart the first pi instance`);
387
375
  }
376
+ if (this.stopped || this.socket !== socket || socket?.readyState !== WebSocket.OPEN) {
377
+ throw new Error('E_BRIDGE_DISCONNECTED');
378
+ }
379
+ this.validatedSocket = socket;
388
380
  return data as ProbeResult;
389
381
  }
390
382
 
@@ -495,7 +487,7 @@ export class RemoteBrowserAgentBroker {
495
487
  if (this.stopped) return;
496
488
  this.logger.warn?.('[pi-browser-agent] lost primary broker; healing', { reason });
497
489
  const promoted = await this.promoteOrReconnect();
498
- if (promoted || this.socket) {
490
+ if (promoted || this.hasValidatedConnection()) {
499
491
  this.healAttempt = 0;
500
492
  this.cancelHealTimer();
501
493
  return;
@@ -575,6 +567,12 @@ export class RemoteBrowserAgentBroker {
575
567
  this.remoteProbe = await this.probePrimary();
576
568
  this.startupError = null;
577
569
  } catch (reconnectError) {
570
+ this.startupError = reconnectError instanceof Error ? reconnectError : new Error(String(reconnectError));
571
+ // A WebSocket handshake alone does not identify a broker. Discard
572
+ // failed probes immediately rather than waiting for a close handshake.
573
+ this.closeSocket(true);
574
+ this.rejectPendingRequests(this.startupError);
575
+ this.scheduleHeal();
578
576
  this.logger.warn?.('[pi-browser-agent] failed to reconnect to promoted primary broker', reconnectError);
579
577
  }
580
578
  return null;
@@ -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
  }