oira666_pi-browser-agent 0.0.13 → 0.0.15

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.
@@ -8,7 +8,17 @@ import {
8
8
  type ResponseFrame,
9
9
  } from './protocol.ts';
10
10
  import { TaskStore } from './task-store.ts';
11
- import { BrowserAgentBroker, type BrokerLogger } from './server.ts';
11
+ import {
12
+ BrowserAgentBroker,
13
+ COLD_BRIDGE_WAIT_MS,
14
+ COLD_MEMO_MISS_THRESHOLD,
15
+ COLD_MEMO_TTL_MS,
16
+ DEFAULT_BRIDGE_WAIT_MS,
17
+ type BridgeStateEvent,
18
+ type BridgeStateListener,
19
+ type BrokerLogger,
20
+ type EnsureReadyOptions,
21
+ } from './server.ts';
12
22
 
13
23
  interface PendingRequest {
14
24
  resolve: (value: ResponseFrame) => void;
@@ -40,6 +50,17 @@ export class RemoteBrowserAgentBroker {
40
50
  private remoteProbe: ProbeResult | null = null;
41
51
  private promotedBroker: BrowserAgentBroker | null = null;
42
52
  private promotionPromise: Promise<BrowserAgentBroker | null> | null = null;
53
+ private healTimer: ReturnType<typeof setTimeout> | null = null;
54
+ private healAttempt = 0;
55
+ private stopped = false;
56
+ private bridgeStateListeners = new Set<BridgeStateListener>();
57
+ private promotionListeners = new Set<(broker: BrowserAgentBroker) => void>();
58
+ private unsubscribePromoted: (() => void) | null = null;
59
+ /** Consecutive full-budget waits that found no bridge, plus when we gave up.
60
+ * Without this every tool call on a secondary with Chrome closed burns the
61
+ * whole budget again. */
62
+ private coldBridgeMisses = 0;
63
+ private coldBridgeSince: number | null = null;
43
64
 
44
65
  constructor({
45
66
  host = '127.0.0.1',
@@ -63,6 +84,11 @@ export class RemoteBrowserAgentBroker {
63
84
  }
64
85
 
65
86
  async start(): Promise<void> {
87
+ // start() is also the resume path after SIGTSTP called stop(). Leaving
88
+ // `stopped` set there disabled background healing forever, so a single
89
+ // Ctrl+Z left the session with no recovery path at all.
90
+ this.stopped = false;
91
+ this.healAttempt = 0;
66
92
  this.startupError = null;
67
93
  await this.taskStore.init();
68
94
  await this.taskStore.gc();
@@ -87,9 +113,10 @@ export class RemoteBrowserAgentBroker {
87
113
  * for the socket-close handler: reconnect to the current primary, or (if
88
114
  * none is listening) compete to become the new primary. Idempotent and safe
89
115
  * to call concurrently — `promoteOrReconnect()` dedupes the bind race. */
90
- async ensureReady(): Promise<void> {
116
+ async ensureReady(options: EnsureReadyOptions = {}): Promise<void> {
117
+ if (this.stopped) return;
91
118
  if (this.promotedBroker) {
92
- await this.promotedBroker.ensureReady();
119
+ await this.promotedBroker.ensureReady(options);
93
120
  return;
94
121
  }
95
122
  try {
@@ -97,18 +124,149 @@ export class RemoteBrowserAgentBroker {
97
124
  this.remoteProbe = await this.probePrimary();
98
125
  this.startupError = null;
99
126
  } catch {
100
- await this.promoteOrReconnect();
127
+ const promoted = await this.promoteOrReconnect();
128
+ if (promoted) {
129
+ await promoted.ensureReady(options);
130
+ return;
131
+ }
132
+ }
133
+
134
+ // The primary is reachable but its Chrome bridge may be mid-reconnect.
135
+ // Poll the primary's probe for the same budget a local broker would wait,
136
+ // so a tool call arriving during a reconnect window succeeds instead of
137
+ // reporting a hard "connection is down".
138
+ await this.waitForRemoteBridge(options.waitForBridgeMs ?? this.defaultRemoteBridgeWaitMs());
139
+ }
140
+
141
+ /** Full budget only when the primary has actually seen a bridge at some point.
142
+ * If Chrome has never connected there is nothing to wait for, and stalling
143
+ * every tool call for the full budget would be pure latency. */
144
+ private defaultRemoteBridgeWaitMs(): number {
145
+ if (this.coldBridgeSince !== null && Date.now() - this.coldBridgeSince < COLD_MEMO_TTL_MS) {
146
+ return COLD_BRIDGE_WAIT_MS;
147
+ }
148
+ return this.remoteProbe?.bridgeEverConnected === false ? COLD_BRIDGE_WAIT_MS : DEFAULT_BRIDGE_WAIT_MS;
149
+ }
150
+
151
+ private async waitForRemoteBridge(timeoutMs: number): Promise<boolean> {
152
+ if (this.probeConnectivity().bridgeConnected) {
153
+ this.coldBridgeMisses = 0;
154
+ this.coldBridgeSince = null;
155
+ return true;
156
+ }
157
+ if (timeoutMs <= 0) return false;
158
+ const deadline = Date.now() + timeoutMs;
159
+ // Every sub-step below can block for up to ~1.5s, so the budget is
160
+ // re-checked before each of them. Checking only at the top of the loop let a
161
+ // final iteration overrun by several seconds, which is what turned an 8s
162
+ // budget into ~17s stalls on every single tool call.
163
+ while (Date.now() < deadline) {
164
+ const sleepMs = Math.min(250, deadline - Date.now());
165
+ if (sleepMs > 0) {
166
+ await new Promise((resolve) => setTimeout(resolve, sleepMs).unref?.());
167
+ }
168
+ if (this.stopped) return false;
169
+ if (Date.now() >= deadline) break;
170
+ try {
171
+ await this.ensureConnected();
172
+ if (Date.now() >= deadline) break;
173
+ this.remoteProbe = await this.probePrimary();
174
+ this.startupError = null;
175
+ if (this.remoteProbe.bridgeConnected) {
176
+ this.coldBridgeMisses = 0;
177
+ this.coldBridgeSince = null;
178
+ return true;
179
+ }
180
+ } catch {
181
+ if (Date.now() >= deadline) break;
182
+ const promoted = await this.promoteOrReconnect();
183
+ if (promoted) {
184
+ const found = await promoted.waitForBridge(Math.max(0, deadline - Date.now()));
185
+ this.recordBridgeWaitOutcome(found, timeoutMs);
186
+ return found;
187
+ }
188
+ }
189
+ }
190
+ const connected = this.probeConnectivity().bridgeConnected;
191
+ this.recordBridgeWaitOutcome(connected, timeoutMs);
192
+ return connected;
193
+ }
194
+
195
+ /** Remember that a full budget was spent without ever seeing a bridge, so the
196
+ * next calls fail fast on a short budget instead of stalling the agent for
197
+ * the full window on every request while Chrome is closed. */
198
+ private recordBridgeWaitOutcome(connected: boolean, budget: number): void {
199
+ if (connected) {
200
+ this.coldBridgeMisses = 0;
201
+ this.coldBridgeSince = null;
202
+ return;
203
+ }
204
+ if (budget < DEFAULT_BRIDGE_WAIT_MS) return;
205
+ this.coldBridgeMisses += 1;
206
+ if (this.coldBridgeMisses >= COLD_MEMO_MISS_THRESHOLD) {
207
+ this.coldBridgeSince = Date.now();
208
+ }
209
+ }
210
+
211
+ /** Subscribe to bridge connect/disconnect transitions, whether they come from
212
+ * a broker we promoted ourselves or from a `notify` push by the primary. */
213
+ addBridgeStateListener(listener: BridgeStateListener): () => void {
214
+ this.bridgeStateListeners.add(listener);
215
+ return () => {
216
+ this.bridgeStateListeners.delete(listener);
217
+ };
218
+ }
219
+
220
+ /** Fired when this secondary wins the bind race and becomes the primary, so
221
+ * the host process can republish instance discovery (which would otherwise
222
+ * keep pointing at the dead primary). */
223
+ addPromotionListener(listener: (broker: BrowserAgentBroker) => void): () => void {
224
+ this.promotionListeners.add(listener);
225
+ return () => {
226
+ this.promotionListeners.delete(listener);
227
+ };
228
+ }
229
+
230
+ private emitBridgeState(state: BridgeStateEvent): void {
231
+ for (const listener of [...this.bridgeStateListeners]) {
232
+ try {
233
+ listener(state);
234
+ } catch (error) {
235
+ this.logger.warn?.('[pi-browser-agent] bridge state listener failed', error);
236
+ }
101
237
  }
102
238
  }
103
239
 
104
240
  async stop(): Promise<void> {
241
+ this.stopped = true;
242
+ this.cancelHealTimer();
105
243
  this.rejectPendingRequests(new Error('E_BRIDGE_DISCONNECTED'));
244
+ const connecting = this.connectPromise;
106
245
  const socket = this.socket;
107
246
  this.socket = null;
108
- this.connectPromise = null;
109
247
  if (socket) {
110
248
  try { socket.close(); } catch { /* ignore */ }
111
249
  }
250
+ // A connect or promotion already in flight can otherwise publish a socket
251
+ // or listener after stop() returns. Their completion paths observe
252
+ // `stopped` and tear down instead of publishing.
253
+ if (connecting) {
254
+ try { await connecting; } catch { /* expected during shutdown */ }
255
+ }
256
+ this.connectPromise = null;
257
+ const promotion = this.promotionPromise;
258
+ if (promotion) {
259
+ try { await promotion; } catch { /* promotion failure is already logged */ }
260
+ }
261
+ const lateSocket = this.socket;
262
+ this.socket = null;
263
+ if (lateSocket) {
264
+ try { lateSocket.close(); } catch { /* ignore */ }
265
+ }
266
+ this.unsubscribePromoted?.();
267
+ this.unsubscribePromoted = null;
268
+ this.bridgeStateListeners.clear();
269
+ this.promotionListeners.clear();
112
270
  if (this.promotedBroker) {
113
271
  const broker = this.promotedBroker;
114
272
  this.promotedBroker = null;
@@ -117,6 +275,7 @@ export class RemoteBrowserAgentBroker {
117
275
  }
118
276
 
119
277
  async request(type: string, params: unknown, options: { timeoutMs?: number } = {}): Promise<ResponseFrame> {
278
+ if (this.stopped) throw new Error('E_BRIDGE_DISCONNECTED');
120
279
  if (this.promotedBroker) {
121
280
  return await this.promotedBroker.request(type, params, options);
122
281
  }
@@ -159,16 +318,23 @@ export class RemoteBrowserAgentBroker {
159
318
 
160
319
  probeConnectivity(): ProbeResult {
161
320
  if (this.promotedBroker) {
162
- return this.promotedBroker.probeConnectivity();
321
+ return { ...this.promotedBroker.probeConnectivity(), role: 'promoted' };
163
322
  }
164
323
  const primary = this.remoteProbe;
165
324
  if (primary) {
325
+ // A cached snapshot must never claim a live broker/bridge once our own
326
+ // socket to the primary is gone; otherwise tools happily send requests
327
+ // into a dead proxy and only fail on timeout, and callers cannot tell
328
+ // "healed" from "still using a stale snapshot".
329
+ const proxyAlive = !!this.socket && !this.startupError;
166
330
  return {
167
331
  ...primary,
168
- brokerReachable: !this.startupError && primary.brokerReachable,
169
- brokerListening: !this.startupError && primary.brokerListening,
332
+ brokerReachable: proxyAlive && primary.brokerReachable,
333
+ brokerListening: proxyAlive && primary.brokerListening,
334
+ bridgeConnected: proxyAlive && primary.bridgeConnected,
170
335
  startupError: this.startupError?.message || primary.startupError,
171
336
  url: this.url,
337
+ role: 'proxy',
172
338
  };
173
339
  }
174
340
  return {
@@ -178,6 +344,7 @@ export class RemoteBrowserAgentBroker {
178
344
  startupError: this.startupError?.message,
179
345
  url: this.url,
180
346
  bridgeSessionSerial: 0,
347
+ role: 'proxy',
181
348
  };
182
349
  }
183
350
 
@@ -211,16 +378,28 @@ export class RemoteBrowserAgentBroker {
211
378
  this.pendingRequests.delete(id);
212
379
  reject(new Error(`Port ${this.port} is busy, but it is not a pi-browser-agent broker`));
213
380
  }, Math.min(this.requestTimeoutMs, 1500));
381
+ timeout.unref?.();
214
382
  this.pendingRequests.set(id, { resolve, reject, timeout });
215
383
  });
216
384
  }
217
385
 
218
386
  private async ensureConnected(): Promise<void> {
387
+ if (this.stopped) throw new Error('Browser broker is stopped');
219
388
  if (this.socket?.readyState === WebSocket.OPEN) return;
220
389
  if (this.connectPromise) return await this.connectPromise;
221
390
 
222
- this.connectPromise = new Promise<void>((resolve, reject) => {
223
- const socket = new WebSocket(this.url);
391
+ // Construct the socket OUTSIDE the promise: a synchronous throw from the
392
+ // WebSocket constructor used to be captured into `connectPromise` after the
393
+ // executor's own `this.connectPromise = null` had already run, permanently
394
+ // caching a rejected promise so every later ensureConnected() failed.
395
+ let socket: WebSocket;
396
+ try {
397
+ socket = new WebSocket(this.url);
398
+ } catch (error) {
399
+ throw error instanceof Error ? error : new Error(String(error));
400
+ }
401
+
402
+ const pending = new Promise<void>((resolve, reject) => {
224
403
  let settled = false;
225
404
  const connectTimeout = setTimeout(() => {
226
405
  fail(new Error(`Port ${this.port} is busy, but it is not a pi-browser-agent broker`));
@@ -237,6 +416,10 @@ export class RemoteBrowserAgentBroker {
237
416
  };
238
417
 
239
418
  socket.once('open', () => {
419
+ if (this.stopped) {
420
+ fail(new Error('Browser broker is stopped'));
421
+ return;
422
+ }
240
423
  settled = true;
241
424
  clearTimeout(connectTimeout);
242
425
  this.socket = socket;
@@ -247,7 +430,7 @@ export class RemoteBrowserAgentBroker {
247
430
  if (this.socket === socket) {
248
431
  this.socket = null;
249
432
  this.rejectPendingRequests(new Error('E_BRIDGE_DISCONNECTED'));
250
- void this.promoteOrReconnect();
433
+ void this.healInBackground('primary broker socket closed');
251
434
  }
252
435
  });
253
436
  socket.on('error', (error) => {
@@ -255,7 +438,7 @@ export class RemoteBrowserAgentBroker {
255
438
  if (this.socket === socket) {
256
439
  this.socket = null;
257
440
  this.rejectPendingRequests(error instanceof Error ? error : new Error(String(error)));
258
- void this.promoteOrReconnect();
441
+ void this.healInBackground('primary broker socket error');
259
442
  }
260
443
  });
261
444
  resolve();
@@ -264,10 +447,58 @@ export class RemoteBrowserAgentBroker {
264
447
  socket.once('unexpected-response', () => fail(new Error(`Port ${this.port} is busy, but it is not a pi-browser-agent broker`)));
265
448
  });
266
449
 
450
+ // Belt and braces: never leave a rejected promise cached, whatever path the
451
+ // failure took.
452
+ this.connectPromise = pending.catch((error) => {
453
+ this.connectPromise = null;
454
+ throw error;
455
+ });
456
+
267
457
  return await this.connectPromise;
268
458
  }
269
459
 
460
+ /**
461
+ * Keep trying to reattach to (or become) a primary broker in the background.
462
+ *
463
+ * Without this, recovery only ever happened when an agent made a tool call:
464
+ * if the primary pi process died at 3am, every secondary sat disconnected
465
+ * until someone poked it, and the Chrome extension had no listener at all to
466
+ * reconnect to. The retry loop closes that hole so the port is re-owned within
467
+ * seconds of the primary disappearing, whether or not anyone is asking.
468
+ */
469
+ private async healInBackground(reason: string): Promise<void> {
470
+ if (this.stopped) return;
471
+ this.logger.warn?.('[pi-browser-agent] lost primary broker; healing', { reason });
472
+ const promoted = await this.promoteOrReconnect();
473
+ if (promoted || this.socket) {
474
+ this.healAttempt = 0;
475
+ this.cancelHealTimer();
476
+ return;
477
+ }
478
+ this.scheduleHeal();
479
+ }
480
+
481
+ private scheduleHeal(): void {
482
+ if (this.stopped || this.healTimer) return;
483
+ const delays = [500, 1_000, 2_000, 3_000, 5_000];
484
+ const delay = delays[Math.min(this.healAttempt, delays.length - 1)];
485
+ this.healAttempt += 1;
486
+ this.healTimer = setTimeout(() => {
487
+ this.healTimer = null;
488
+ void this.healInBackground('scheduled reconnect retry');
489
+ }, delay);
490
+ this.healTimer.unref?.();
491
+ }
492
+
493
+ private cancelHealTimer(): void {
494
+ if (this.healTimer) {
495
+ clearTimeout(this.healTimer);
496
+ this.healTimer = null;
497
+ }
498
+ }
499
+
270
500
  private async promoteOrReconnect(): Promise<BrowserAgentBroker | null> {
501
+ if (this.stopped) return null;
271
502
  if (this.promotedBroker) return this.promotedBroker;
272
503
  if (this.promotionPromise) return await this.promotionPromise;
273
504
 
@@ -285,10 +516,25 @@ export class RemoteBrowserAgentBroker {
285
516
  });
286
517
  try {
287
518
  await candidate.start();
519
+ if (this.stopped) {
520
+ await candidate.stop();
521
+ return null;
522
+ }
523
+ this.unsubscribePromoted?.();
524
+ this.unsubscribePromoted = candidate.addBridgeStateListener((state) => this.emitBridgeState(state));
288
525
  this.promotedBroker = candidate;
289
526
  this.remoteProbe = candidate.probeConnectivity();
290
527
  this.startupError = null;
528
+ this.healAttempt = 0;
529
+ this.cancelHealTimer();
291
530
  this.logger.info?.('[pi-browser-agent] promoted secondary broker to primary', { url: candidate.url });
531
+ for (const listener of [...this.promotionListeners]) {
532
+ try {
533
+ listener(candidate);
534
+ } catch (error) {
535
+ this.logger.warn?.('[pi-browser-agent] promotion listener failed', error);
536
+ }
537
+ }
292
538
  return candidate;
293
539
  } catch (error) {
294
540
  const code = (error as NodeJS.ErrnoException)?.code;
@@ -297,7 +543,8 @@ export class RemoteBrowserAgentBroker {
297
543
  return null;
298
544
  }
299
545
  // Someone else won the race. Reconnect to the new primary and refresh
300
- // our probe snapshot.
546
+ // our probe snapshot, unless shutdown won the race first.
547
+ if (this.stopped) return null;
301
548
  try {
302
549
  await this.ensureConnected();
303
550
  this.remoteProbe = await this.probePrimary();
@@ -322,6 +569,23 @@ export class RemoteBrowserAgentBroker {
322
569
  this.logger.warn?.('[pi-browser-agent] invalid primary proxy frame', error);
323
570
  return;
324
571
  }
572
+ // The primary pushes bridge transitions instead of making us poll, so a
573
+ // secondary session can tell its user the browser went away.
574
+ if (frame.kind === 'notify') {
575
+ if (frame.event !== 'bridge_state') return;
576
+ const payload = frame.payload as Partial<ProbeResult> | undefined;
577
+ if (payload && typeof payload === 'object') {
578
+ this.remoteProbe = { ...(this.remoteProbe ?? {} as ProbeResult), ...payload };
579
+ }
580
+ const probe = this.probeConnectivity();
581
+ if (probe.bridgeConnected) {
582
+ this.coldBridgeMisses = 0;
583
+ this.coldBridgeSince = null;
584
+ }
585
+ this.emitBridgeState({ connected: probe.bridgeConnected, probe });
586
+ return;
587
+ }
588
+
325
589
  if (frame.kind !== 'response') return;
326
590
  const pending = this.pendingRequests.get(frame.id);
327
591
  if (!pending) return;