oira666_pi-browser-agent 0.0.13 → 0.0.14

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,9 @@ 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> {
91
117
  if (this.promotedBroker) {
92
- await this.promotedBroker.ensureReady();
118
+ await this.promotedBroker.ensureReady(options);
93
119
  return;
94
120
  }
95
121
  try {
@@ -97,11 +123,122 @@ export class RemoteBrowserAgentBroker {
97
123
  this.remoteProbe = await this.probePrimary();
98
124
  this.startupError = null;
99
125
  } catch {
100
- await this.promoteOrReconnect();
126
+ const promoted = await this.promoteOrReconnect();
127
+ if (promoted) {
128
+ await promoted.ensureReady(options);
129
+ return;
130
+ }
131
+ }
132
+
133
+ // The primary is reachable but its Chrome bridge may be mid-reconnect.
134
+ // Poll the primary's probe for the same budget a local broker would wait,
135
+ // so a tool call arriving during a reconnect window succeeds instead of
136
+ // reporting a hard "connection is down".
137
+ await this.waitForRemoteBridge(options.waitForBridgeMs ?? this.defaultRemoteBridgeWaitMs());
138
+ }
139
+
140
+ /** Full budget only when the primary has actually seen a bridge at some point.
141
+ * If Chrome has never connected there is nothing to wait for, and stalling
142
+ * every tool call for the full budget would be pure latency. */
143
+ private defaultRemoteBridgeWaitMs(): number {
144
+ if (this.coldBridgeSince !== null && Date.now() - this.coldBridgeSince < COLD_MEMO_TTL_MS) {
145
+ return COLD_BRIDGE_WAIT_MS;
146
+ }
147
+ return this.remoteProbe?.bridgeEverConnected === false ? COLD_BRIDGE_WAIT_MS : DEFAULT_BRIDGE_WAIT_MS;
148
+ }
149
+
150
+ private async waitForRemoteBridge(timeoutMs: number): Promise<boolean> {
151
+ if (this.probeConnectivity().bridgeConnected) {
152
+ this.coldBridgeMisses = 0;
153
+ this.coldBridgeSince = null;
154
+ return true;
155
+ }
156
+ if (timeoutMs <= 0) return false;
157
+ const deadline = Date.now() + timeoutMs;
158
+ // Every sub-step below can block for up to ~1.5s, so the budget is
159
+ // re-checked before each of them. Checking only at the top of the loop let a
160
+ // final iteration overrun by several seconds, which is what turned an 8s
161
+ // budget into ~17s stalls on every single tool call.
162
+ while (Date.now() < deadline) {
163
+ const sleepMs = Math.min(250, deadline - Date.now());
164
+ if (sleepMs > 0) {
165
+ await new Promise((resolve) => setTimeout(resolve, sleepMs).unref?.());
166
+ }
167
+ if (this.stopped) return false;
168
+ if (Date.now() >= deadline) break;
169
+ try {
170
+ await this.ensureConnected();
171
+ if (Date.now() >= deadline) break;
172
+ this.remoteProbe = await this.probePrimary();
173
+ this.startupError = null;
174
+ if (this.remoteProbe.bridgeConnected) {
175
+ this.coldBridgeMisses = 0;
176
+ this.coldBridgeSince = null;
177
+ return true;
178
+ }
179
+ } catch {
180
+ if (Date.now() >= deadline) break;
181
+ const promoted = await this.promoteOrReconnect();
182
+ if (promoted) {
183
+ const found = await promoted.waitForBridge(Math.max(0, deadline - Date.now()));
184
+ this.recordBridgeWaitOutcome(found, timeoutMs);
185
+ return found;
186
+ }
187
+ }
188
+ }
189
+ const connected = this.probeConnectivity().bridgeConnected;
190
+ this.recordBridgeWaitOutcome(connected, timeoutMs);
191
+ return connected;
192
+ }
193
+
194
+ /** Remember that a full budget was spent without ever seeing a bridge, so the
195
+ * next calls fail fast on a short budget instead of stalling the agent for
196
+ * the full window on every request while Chrome is closed. */
197
+ private recordBridgeWaitOutcome(connected: boolean, budget: number): void {
198
+ if (connected) {
199
+ this.coldBridgeMisses = 0;
200
+ this.coldBridgeSince = null;
201
+ return;
202
+ }
203
+ if (budget < DEFAULT_BRIDGE_WAIT_MS) return;
204
+ this.coldBridgeMisses += 1;
205
+ if (this.coldBridgeMisses >= COLD_MEMO_MISS_THRESHOLD) {
206
+ this.coldBridgeSince = Date.now();
207
+ }
208
+ }
209
+
210
+ /** Subscribe to bridge connect/disconnect transitions, whether they come from
211
+ * a broker we promoted ourselves or from a `notify` push by the primary. */
212
+ addBridgeStateListener(listener: BridgeStateListener): () => void {
213
+ this.bridgeStateListeners.add(listener);
214
+ return () => {
215
+ this.bridgeStateListeners.delete(listener);
216
+ };
217
+ }
218
+
219
+ /** Fired when this secondary wins the bind race and becomes the primary, so
220
+ * the host process can republish instance discovery (which would otherwise
221
+ * keep pointing at the dead primary). */
222
+ addPromotionListener(listener: (broker: BrowserAgentBroker) => void): () => void {
223
+ this.promotionListeners.add(listener);
224
+ return () => {
225
+ this.promotionListeners.delete(listener);
226
+ };
227
+ }
228
+
229
+ private emitBridgeState(state: BridgeStateEvent): void {
230
+ for (const listener of [...this.bridgeStateListeners]) {
231
+ try {
232
+ listener(state);
233
+ } catch (error) {
234
+ this.logger.warn?.('[pi-browser-agent] bridge state listener failed', error);
235
+ }
101
236
  }
102
237
  }
103
238
 
104
239
  async stop(): Promise<void> {
240
+ this.stopped = true;
241
+ this.cancelHealTimer();
105
242
  this.rejectPendingRequests(new Error('E_BRIDGE_DISCONNECTED'));
106
243
  const socket = this.socket;
107
244
  this.socket = null;
@@ -109,6 +246,10 @@ export class RemoteBrowserAgentBroker {
109
246
  if (socket) {
110
247
  try { socket.close(); } catch { /* ignore */ }
111
248
  }
249
+ this.unsubscribePromoted?.();
250
+ this.unsubscribePromoted = null;
251
+ this.bridgeStateListeners.clear();
252
+ this.promotionListeners.clear();
112
253
  if (this.promotedBroker) {
113
254
  const broker = this.promotedBroker;
114
255
  this.promotedBroker = null;
@@ -159,16 +300,23 @@ export class RemoteBrowserAgentBroker {
159
300
 
160
301
  probeConnectivity(): ProbeResult {
161
302
  if (this.promotedBroker) {
162
- return this.promotedBroker.probeConnectivity();
303
+ return { ...this.promotedBroker.probeConnectivity(), role: 'promoted' };
163
304
  }
164
305
  const primary = this.remoteProbe;
165
306
  if (primary) {
307
+ // A cached snapshot must never claim a live broker/bridge once our own
308
+ // socket to the primary is gone; otherwise tools happily send requests
309
+ // into a dead proxy and only fail on timeout, and callers cannot tell
310
+ // "healed" from "still using a stale snapshot".
311
+ const proxyAlive = !!this.socket && !this.startupError;
166
312
  return {
167
313
  ...primary,
168
- brokerReachable: !this.startupError && primary.brokerReachable,
169
- brokerListening: !this.startupError && primary.brokerListening,
314
+ brokerReachable: proxyAlive && primary.brokerReachable,
315
+ brokerListening: proxyAlive && primary.brokerListening,
316
+ bridgeConnected: proxyAlive && primary.bridgeConnected,
170
317
  startupError: this.startupError?.message || primary.startupError,
171
318
  url: this.url,
319
+ role: 'proxy',
172
320
  };
173
321
  }
174
322
  return {
@@ -178,6 +326,7 @@ export class RemoteBrowserAgentBroker {
178
326
  startupError: this.startupError?.message,
179
327
  url: this.url,
180
328
  bridgeSessionSerial: 0,
329
+ role: 'proxy',
181
330
  };
182
331
  }
183
332
 
@@ -211,6 +360,7 @@ export class RemoteBrowserAgentBroker {
211
360
  this.pendingRequests.delete(id);
212
361
  reject(new Error(`Port ${this.port} is busy, but it is not a pi-browser-agent broker`));
213
362
  }, Math.min(this.requestTimeoutMs, 1500));
363
+ timeout.unref?.();
214
364
  this.pendingRequests.set(id, { resolve, reject, timeout });
215
365
  });
216
366
  }
@@ -219,8 +369,18 @@ export class RemoteBrowserAgentBroker {
219
369
  if (this.socket?.readyState === WebSocket.OPEN) return;
220
370
  if (this.connectPromise) return await this.connectPromise;
221
371
 
222
- this.connectPromise = new Promise<void>((resolve, reject) => {
223
- const socket = new WebSocket(this.url);
372
+ // Construct the socket OUTSIDE the promise: a synchronous throw from the
373
+ // WebSocket constructor used to be captured into `connectPromise` after the
374
+ // executor's own `this.connectPromise = null` had already run, permanently
375
+ // caching a rejected promise so every later ensureConnected() failed.
376
+ let socket: WebSocket;
377
+ try {
378
+ socket = new WebSocket(this.url);
379
+ } catch (error) {
380
+ throw error instanceof Error ? error : new Error(String(error));
381
+ }
382
+
383
+ const pending = new Promise<void>((resolve, reject) => {
224
384
  let settled = false;
225
385
  const connectTimeout = setTimeout(() => {
226
386
  fail(new Error(`Port ${this.port} is busy, but it is not a pi-browser-agent broker`));
@@ -247,7 +407,7 @@ export class RemoteBrowserAgentBroker {
247
407
  if (this.socket === socket) {
248
408
  this.socket = null;
249
409
  this.rejectPendingRequests(new Error('E_BRIDGE_DISCONNECTED'));
250
- void this.promoteOrReconnect();
410
+ void this.healInBackground('primary broker socket closed');
251
411
  }
252
412
  });
253
413
  socket.on('error', (error) => {
@@ -255,7 +415,7 @@ export class RemoteBrowserAgentBroker {
255
415
  if (this.socket === socket) {
256
416
  this.socket = null;
257
417
  this.rejectPendingRequests(error instanceof Error ? error : new Error(String(error)));
258
- void this.promoteOrReconnect();
418
+ void this.healInBackground('primary broker socket error');
259
419
  }
260
420
  });
261
421
  resolve();
@@ -264,9 +424,56 @@ export class RemoteBrowserAgentBroker {
264
424
  socket.once('unexpected-response', () => fail(new Error(`Port ${this.port} is busy, but it is not a pi-browser-agent broker`)));
265
425
  });
266
426
 
427
+ // Belt and braces: never leave a rejected promise cached, whatever path the
428
+ // failure took.
429
+ this.connectPromise = pending.catch((error) => {
430
+ this.connectPromise = null;
431
+ throw error;
432
+ });
433
+
267
434
  return await this.connectPromise;
268
435
  }
269
436
 
437
+ /**
438
+ * Keep trying to reattach to (or become) a primary broker in the background.
439
+ *
440
+ * Without this, recovery only ever happened when an agent made a tool call:
441
+ * if the primary pi process died at 3am, every secondary sat disconnected
442
+ * until someone poked it, and the Chrome extension had no listener at all to
443
+ * reconnect to. The retry loop closes that hole so the port is re-owned within
444
+ * seconds of the primary disappearing, whether or not anyone is asking.
445
+ */
446
+ private async healInBackground(reason: string): Promise<void> {
447
+ if (this.stopped) return;
448
+ this.logger.warn?.('[pi-browser-agent] lost primary broker; healing', { reason });
449
+ const promoted = await this.promoteOrReconnect();
450
+ if (promoted || this.socket) {
451
+ this.healAttempt = 0;
452
+ this.cancelHealTimer();
453
+ return;
454
+ }
455
+ this.scheduleHeal();
456
+ }
457
+
458
+ private scheduleHeal(): void {
459
+ if (this.stopped || this.healTimer) return;
460
+ const delays = [500, 1_000, 2_000, 3_000, 5_000];
461
+ const delay = delays[Math.min(this.healAttempt, delays.length - 1)];
462
+ this.healAttempt += 1;
463
+ this.healTimer = setTimeout(() => {
464
+ this.healTimer = null;
465
+ void this.healInBackground('scheduled reconnect retry');
466
+ }, delay);
467
+ this.healTimer.unref?.();
468
+ }
469
+
470
+ private cancelHealTimer(): void {
471
+ if (this.healTimer) {
472
+ clearTimeout(this.healTimer);
473
+ this.healTimer = null;
474
+ }
475
+ }
476
+
270
477
  private async promoteOrReconnect(): Promise<BrowserAgentBroker | null> {
271
478
  if (this.promotedBroker) return this.promotedBroker;
272
479
  if (this.promotionPromise) return await this.promotionPromise;
@@ -285,10 +492,21 @@ export class RemoteBrowserAgentBroker {
285
492
  });
286
493
  try {
287
494
  await candidate.start();
495
+ this.unsubscribePromoted?.();
496
+ this.unsubscribePromoted = candidate.addBridgeStateListener((state) => this.emitBridgeState(state));
288
497
  this.promotedBroker = candidate;
289
498
  this.remoteProbe = candidate.probeConnectivity();
290
499
  this.startupError = null;
500
+ this.healAttempt = 0;
501
+ this.cancelHealTimer();
291
502
  this.logger.info?.('[pi-browser-agent] promoted secondary broker to primary', { url: candidate.url });
503
+ for (const listener of [...this.promotionListeners]) {
504
+ try {
505
+ listener(candidate);
506
+ } catch (error) {
507
+ this.logger.warn?.('[pi-browser-agent] promotion listener failed', error);
508
+ }
509
+ }
292
510
  return candidate;
293
511
  } catch (error) {
294
512
  const code = (error as NodeJS.ErrnoException)?.code;
@@ -322,6 +540,23 @@ export class RemoteBrowserAgentBroker {
322
540
  this.logger.warn?.('[pi-browser-agent] invalid primary proxy frame', error);
323
541
  return;
324
542
  }
543
+ // The primary pushes bridge transitions instead of making us poll, so a
544
+ // secondary session can tell its user the browser went away.
545
+ if (frame.kind === 'notify') {
546
+ if (frame.event !== 'bridge_state') return;
547
+ const payload = frame.payload as Partial<ProbeResult> | undefined;
548
+ if (payload && typeof payload === 'object') {
549
+ this.remoteProbe = { ...(this.remoteProbe ?? {} as ProbeResult), ...payload };
550
+ }
551
+ const probe = this.probeConnectivity();
552
+ if (probe.bridgeConnected) {
553
+ this.coldBridgeMisses = 0;
554
+ this.coldBridgeSince = null;
555
+ }
556
+ this.emitBridgeState({ connected: probe.bridgeConnected, probe });
557
+ return;
558
+ }
559
+
325
560
  if (frame.kind !== 'response') return;
326
561
  const pending = this.pendingRequests.get(frame.id);
327
562
  if (!pending) return;