oira666_pi-browser-agent 0.0.2 → 0.0.3

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.2",
3
+ "version": "0.0.3",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Pi browser agent broker skeleton with lazy browser tool registration",
@@ -71,6 +71,7 @@ export interface ProbeResult {
71
71
  startupError?: string;
72
72
  url?: string;
73
73
  bridgeSessionSerial?: number;
74
+ supportsBrokerProxy?: boolean;
74
75
  }
75
76
 
76
77
  export function parseIncomingFrame(raw: string): IncomingFrame {
@@ -0,0 +1,321 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import WebSocket, { type RawData } from 'ws';
3
+
4
+ import {
5
+ createErrorResponseFrame,
6
+ parseIncomingFrame,
7
+ type ProbeResult,
8
+ type ResponseFrame,
9
+ } from './protocol.ts';
10
+ import { TaskStore } from './task-store.ts';
11
+ import { BrowserAgentBroker, type BrokerLogger } from './server.ts';
12
+
13
+ interface PendingRequest {
14
+ resolve: (value: ResponseFrame) => void;
15
+ reject: (error: Error) => void;
16
+ timeout: ReturnType<typeof setTimeout>;
17
+ }
18
+
19
+ /**
20
+ * BrowserAgentBroker-compatible client for secondary pi processes.
21
+ *
22
+ * Only the primary broker owns the Chrome extension bridge (usually on 7878).
23
+ * Secondary pi processes should not require Chrome/MV3 to maintain extra
24
+ * WebSocket clients to fallback ports. Instead they proxy tool requests through
25
+ * the primary broker, which forwards them to its already-connected extension
26
+ * bridge.
27
+ */
28
+ export class RemoteBrowserAgentBroker {
29
+ readonly host: string;
30
+ readonly port: number;
31
+ readonly url: string;
32
+ readonly logger: BrokerLogger;
33
+ readonly requestTimeoutMs: number;
34
+ readonly taskStore: TaskStore;
35
+
36
+ private socket: WebSocket | null = null;
37
+ private connectPromise: Promise<void> | null = null;
38
+ private pendingRequests = new Map<string, PendingRequest>();
39
+ private startupError: Error | null = null;
40
+ private remoteProbe: ProbeResult | null = null;
41
+ private promotedBroker: BrowserAgentBroker | null = null;
42
+ private promotionPromise: Promise<BrowserAgentBroker | null> | null = null;
43
+
44
+ constructor({
45
+ host = '127.0.0.1',
46
+ port = 7878,
47
+ logger = console,
48
+ requestTimeoutMs = 10_000,
49
+ taskStore,
50
+ }: {
51
+ host?: string;
52
+ port?: number;
53
+ logger?: BrokerLogger;
54
+ requestTimeoutMs?: number;
55
+ taskStore: TaskStore;
56
+ }) {
57
+ this.host = host;
58
+ this.port = port;
59
+ this.url = `ws://${host}:${port}`;
60
+ this.logger = logger;
61
+ this.requestTimeoutMs = requestTimeoutMs;
62
+ this.taskStore = taskStore;
63
+ }
64
+
65
+ async start(): Promise<void> {
66
+ this.startupError = null;
67
+ await this.taskStore.init();
68
+ await this.taskStore.gc();
69
+ try {
70
+ await this.ensureConnected();
71
+ this.remoteProbe = await this.probePrimary();
72
+ this.logger.info?.('[pi-browser-agent] using primary broker proxy', { url: this.url });
73
+ } catch (error) {
74
+ this.startupError = error instanceof Error ? error : new Error(String(error));
75
+ const message = this.startupError.message;
76
+ if (message.includes('not a pi-browser-agent broker') || message.includes('old pi-browser-agent broker')) {
77
+ this.logger.warn?.(`[pi-browser-agent] ${message}`);
78
+ } else {
79
+ this.logger.error?.('[pi-browser-agent] primary broker proxy startup failed', this.startupError);
80
+ }
81
+ throw this.startupError;
82
+ }
83
+ }
84
+
85
+ async stop(): Promise<void> {
86
+ this.rejectPendingRequests(new Error('E_BRIDGE_DISCONNECTED'));
87
+ const socket = this.socket;
88
+ this.socket = null;
89
+ this.connectPromise = null;
90
+ if (socket) {
91
+ try { socket.close(); } catch { /* ignore */ }
92
+ }
93
+ if (this.promotedBroker) {
94
+ const broker = this.promotedBroker;
95
+ this.promotedBroker = null;
96
+ await broker.stop();
97
+ }
98
+ }
99
+
100
+ async request(type: string, params: unknown, options: { timeoutMs?: number } = {}): Promise<ResponseFrame> {
101
+ if (this.promotedBroker) {
102
+ return await this.promotedBroker.request(type, params, options);
103
+ }
104
+
105
+ try {
106
+ await this.ensureConnected();
107
+ } catch {
108
+ const promoted = await this.promoteOrReconnect();
109
+ if (promoted) return await promoted.request(type, params, options);
110
+ await this.ensureConnected();
111
+ }
112
+
113
+ const socket = this.socket;
114
+ if (!socket || socket.readyState !== WebSocket.OPEN) {
115
+ const promoted = await this.promoteOrReconnect();
116
+ if (promoted) return await promoted.request(type, params, options);
117
+ throw new Error('E_BRIDGE_DISCONNECTED');
118
+ }
119
+
120
+ const id = randomUUID();
121
+ const payload = JSON.stringify({ v: 1, kind: 'request', id, type, params });
122
+
123
+ return await new Promise<ResponseFrame>((resolve, reject) => {
124
+ const timeout = setTimeout(() => {
125
+ this.pendingRequests.delete(id);
126
+ reject(new Error(`Request timed out: ${type}`));
127
+ }, options.timeoutMs ?? this.requestTimeoutMs);
128
+ timeout.unref?.();
129
+
130
+ this.pendingRequests.set(id, { resolve, reject, timeout });
131
+ try {
132
+ socket.send(payload);
133
+ } catch (error) {
134
+ clearTimeout(timeout);
135
+ this.pendingRequests.delete(id);
136
+ reject(error instanceof Error ? error : new Error(String(error)));
137
+ }
138
+ });
139
+ }
140
+
141
+ probeConnectivity(): ProbeResult {
142
+ if (this.promotedBroker) {
143
+ return this.promotedBroker.probeConnectivity();
144
+ }
145
+ const primary = this.remoteProbe;
146
+ if (primary) {
147
+ return {
148
+ ...primary,
149
+ brokerReachable: !this.startupError && primary.brokerReachable,
150
+ brokerListening: !this.startupError && primary.brokerListening,
151
+ startupError: this.startupError?.message || primary.startupError,
152
+ url: this.url,
153
+ };
154
+ }
155
+ return {
156
+ brokerReachable: !this.startupError && !!this.socket,
157
+ brokerListening: !this.startupError && !!this.socket,
158
+ bridgeConnected: false,
159
+ startupError: this.startupError?.message,
160
+ url: this.url,
161
+ bridgeSessionSerial: 0,
162
+ };
163
+ }
164
+
165
+ private async probePrimary(): Promise<ProbeResult> {
166
+ const response = await this.sendControlRequest('probe');
167
+ if (!response.ok) {
168
+ throw new Error(response.error?.message || 'Primary broker probe failed');
169
+ }
170
+ const data = response.data as Partial<ProbeResult> | undefined;
171
+ if (!data || typeof data.brokerListening !== 'boolean' || typeof data.bridgeConnected !== 'boolean') {
172
+ throw new Error(`Port ${this.port} is busy, but it is not a pi-browser-agent broker`);
173
+ }
174
+ if (data.supportsBrokerProxy !== true) {
175
+ throw new Error(`Port ${this.port} has an old pi-browser-agent broker; restart the first pi instance`);
176
+ }
177
+ return data as ProbeResult;
178
+ }
179
+
180
+ private async sendControlRequest(kind: 'probe'): Promise<ResponseFrame> {
181
+ await this.ensureConnected();
182
+ const socket = this.socket;
183
+ if (!socket || socket.readyState !== WebSocket.OPEN) {
184
+ return createErrorResponseFrame(randomUUID(), 'E_BRIDGE_DISCONNECTED', 'Primary broker proxy is not connected');
185
+ }
186
+
187
+ const id = randomUUID();
188
+ socket.send(JSON.stringify({ v: 1, kind, id }));
189
+
190
+ return await new Promise<ResponseFrame>((resolve, reject) => {
191
+ const timeout = setTimeout(() => {
192
+ this.pendingRequests.delete(id);
193
+ reject(new Error(`Port ${this.port} is busy, but it is not a pi-browser-agent broker`));
194
+ }, Math.min(this.requestTimeoutMs, 1500));
195
+ this.pendingRequests.set(id, { resolve, reject, timeout });
196
+ });
197
+ }
198
+
199
+ private async ensureConnected(): Promise<void> {
200
+ if (this.socket?.readyState === WebSocket.OPEN) return;
201
+ if (this.connectPromise) return await this.connectPromise;
202
+
203
+ this.connectPromise = new Promise<void>((resolve, reject) => {
204
+ const socket = new WebSocket(this.url);
205
+ let settled = false;
206
+ const connectTimeout = setTimeout(() => {
207
+ fail(new Error(`Port ${this.port} is busy, but it is not a pi-browser-agent broker`));
208
+ }, Math.min(this.requestTimeoutMs, 1500));
209
+ connectTimeout.unref?.();
210
+
211
+ const fail = (error: Error) => {
212
+ if (settled) return;
213
+ settled = true;
214
+ clearTimeout(connectTimeout);
215
+ this.connectPromise = null;
216
+ try { socket.terminate(); } catch { try { socket.close(); } catch { /* ignore */ } }
217
+ reject(error);
218
+ };
219
+
220
+ socket.once('open', () => {
221
+ settled = true;
222
+ clearTimeout(connectTimeout);
223
+ this.socket = socket;
224
+ this.connectPromise = null;
225
+
226
+ socket.on('message', (buffer: RawData) => this.handleRawMessage(buffer.toString()));
227
+ socket.on('close', () => {
228
+ if (this.socket === socket) {
229
+ this.socket = null;
230
+ this.rejectPendingRequests(new Error('E_BRIDGE_DISCONNECTED'));
231
+ void this.promoteOrReconnect();
232
+ }
233
+ });
234
+ socket.on('error', (error) => {
235
+ this.logger.warn?.('[pi-browser-agent] primary broker proxy socket error', error);
236
+ if (this.socket === socket) {
237
+ this.socket = null;
238
+ this.rejectPendingRequests(error instanceof Error ? error : new Error(String(error)));
239
+ void this.promoteOrReconnect();
240
+ }
241
+ });
242
+ resolve();
243
+ });
244
+ socket.once('error', () => fail(new Error(`Port ${this.port} is busy, but it is not a pi-browser-agent broker`)));
245
+ socket.once('unexpected-response', () => fail(new Error(`Port ${this.port} is busy, but it is not a pi-browser-agent broker`)));
246
+ });
247
+
248
+ return await this.connectPromise;
249
+ }
250
+
251
+ private async promoteOrReconnect(): Promise<BrowserAgentBroker | null> {
252
+ if (this.promotedBroker) return this.promotedBroker;
253
+ if (this.promotionPromise) return await this.promotionPromise;
254
+
255
+ this.promotionPromise = (async () => {
256
+ // First try to become the new primary. If several remotes detect the
257
+ // disconnect at once, exactly one should win this bind race.
258
+ const candidate = new BrowserAgentBroker({
259
+ host: this.host,
260
+ port: this.port,
261
+ portRange: 1,
262
+ fallbackToEphemeral: false,
263
+ logger: this.logger,
264
+ requestTimeoutMs: this.requestTimeoutMs,
265
+ taskStore: this.taskStore,
266
+ });
267
+ try {
268
+ await candidate.start();
269
+ this.promotedBroker = candidate;
270
+ this.remoteProbe = candidate.probeConnectivity();
271
+ this.startupError = null;
272
+ this.logger.info?.('[pi-browser-agent] promoted secondary broker to primary', { url: candidate.url });
273
+ return candidate;
274
+ } catch (error) {
275
+ const code = (error as NodeJS.ErrnoException)?.code;
276
+ if (code !== 'EADDRINUSE') {
277
+ this.logger.warn?.('[pi-browser-agent] secondary broker promotion failed', error);
278
+ return null;
279
+ }
280
+ // Someone else won the race. Reconnect to the new primary and refresh
281
+ // our probe snapshot.
282
+ try {
283
+ await this.ensureConnected();
284
+ this.remoteProbe = await this.probePrimary();
285
+ this.startupError = null;
286
+ } catch (reconnectError) {
287
+ this.logger.warn?.('[pi-browser-agent] failed to reconnect to promoted primary broker', reconnectError);
288
+ }
289
+ return null;
290
+ } finally {
291
+ this.promotionPromise = null;
292
+ }
293
+ })();
294
+
295
+ return await this.promotionPromise;
296
+ }
297
+
298
+ private handleRawMessage(raw: string): void {
299
+ let frame;
300
+ try {
301
+ frame = parseIncomingFrame(raw);
302
+ } catch (error) {
303
+ this.logger.warn?.('[pi-browser-agent] invalid primary proxy frame', error);
304
+ return;
305
+ }
306
+ if (frame.kind !== 'response') return;
307
+ const pending = this.pendingRequests.get(frame.id);
308
+ if (!pending) return;
309
+ clearTimeout(pending.timeout);
310
+ this.pendingRequests.delete(frame.id);
311
+ pending.resolve(frame);
312
+ }
313
+
314
+ private rejectPendingRequests(error: Error): void {
315
+ for (const [id, pending] of this.pendingRequests.entries()) {
316
+ clearTimeout(pending.timeout);
317
+ pending.reject(error);
318
+ this.pendingRequests.delete(id);
319
+ }
320
+ }
321
+ }
@@ -56,6 +56,7 @@ export class BrowserAgentBroker {
56
56
  private shutdownError: Error | null = null;
57
57
  private pingTimer: ReturnType<typeof setInterval> | null = null;
58
58
  private pendingRequests = new Map<string, PendingRequest>();
59
+ private sockets = new Set<BridgeSocket>();
59
60
 
60
61
  constructor({
61
62
  host = process.env.PI_BA_HOST || '127.0.0.1',
@@ -131,7 +132,12 @@ export class BrowserAgentBroker {
131
132
  this.logger.info?.('[pi-browser-agent] broker listening', { url: this.url, preferredPort: this.preferredPort });
132
133
  } catch (error) {
133
134
  this.startupError = error instanceof Error ? error : new Error(String(error));
134
- this.logger.error?.('[pi-browser-agent] broker startup failed', this.startupError);
135
+ const code = (this.startupError as NodeJS.ErrnoException).code;
136
+ if (code === 'EADDRINUSE') {
137
+ this.logger.warn?.('[pi-browser-agent] primary broker port is busy', { port: this.preferredPort });
138
+ } else {
139
+ this.logger.error?.('[pi-browser-agent] broker startup failed', this.startupError);
140
+ }
135
141
  throw this.startupError;
136
142
  }
137
143
  }
@@ -157,7 +163,6 @@ export class BrowserAgentBroker {
157
163
  const err = error instanceof Error ? error : new Error(String(error));
158
164
  const code = (err as NodeJS.ErrnoException).code;
159
165
  if (code === 'EADDRINUSE') {
160
- this.logger.warn?.('[pi-browser-agent] port busy, trying next candidate', { tried: candidate });
161
166
  lastError = err;
162
167
  continue;
163
168
  }
@@ -190,6 +195,12 @@ export class BrowserAgentBroker {
190
195
  this.port = candidate;
191
196
  }
192
197
  this.server = server;
198
+ // Only log post-listen server errors. Startup bind errors such as an
199
+ // expected EADDRINUSE fallback are handled by onError and should not
200
+ // be printed as scary broker failures.
201
+ server.on('error', (error: Error) => {
202
+ this.logger.error?.('[pi-browser-agent] broker server error', error);
203
+ });
193
204
  resolve();
194
205
  };
195
206
 
@@ -198,9 +209,6 @@ export class BrowserAgentBroker {
198
209
  server.on('connection', (socket: WebSocket) => {
199
210
  void this.handleConnection(socket);
200
211
  });
201
- server.on('error', (error: Error) => {
202
- this.logger.error?.('[pi-browser-agent] broker server error', error);
203
- });
204
212
  });
205
213
  }
206
214
 
@@ -214,6 +222,14 @@ export class BrowserAgentBroker {
214
222
 
215
223
  this.rejectPendingRequests(new Error('E_BRIDGE_DISCONNECTED'));
216
224
 
225
+ for (const socket of this.sockets) {
226
+ try {
227
+ socket.close();
228
+ } catch (error) {
229
+ closeErrors.push(error instanceof Error ? error : new Error(String(error)));
230
+ }
231
+ }
232
+
217
233
  if (this.bridgeSocket) {
218
234
  try {
219
235
  this.bridgeSocket.close();
@@ -230,7 +246,14 @@ export class BrowserAgentBroker {
230
246
  this.server = null;
231
247
  try {
232
248
  await new Promise<void>((resolve, reject) => {
249
+ const forceClose = setTimeout(() => {
250
+ for (const socket of this.sockets) {
251
+ try { socket.terminate(); } catch { /* ignore */ }
252
+ }
253
+ }, 250);
254
+ forceClose.unref?.();
233
255
  server.close((error) => {
256
+ clearTimeout(forceClose);
234
257
  if (error) {
235
258
  reject(error);
236
259
  return;
@@ -297,12 +320,14 @@ export class BrowserAgentBroker {
297
320
  startupError: this.startupError?.message,
298
321
  url: this.url,
299
322
  bridgeSessionSerial: this.bridgeSessionSerial,
323
+ supportsBrokerProxy: true,
300
324
  };
301
325
  }
302
326
 
303
327
  private async handleConnection(socket: WebSocket): Promise<void> {
304
328
  const bridgeSocket = socket as BridgeSocket;
305
329
  bridgeSocket.isAlive = true;
330
+ this.sockets.add(bridgeSocket);
306
331
 
307
332
  // Do NOT evict the current bridge here. A new accepted socket has not yet
308
333
  // authenticated as a bridge session. We only replace the active bridge
@@ -318,6 +343,7 @@ export class BrowserAgentBroker {
318
343
  });
319
344
 
320
345
  bridgeSocket.on('close', () => {
346
+ this.sockets.delete(bridgeSocket);
321
347
  this.failBridge(bridgeSocket, new Error('E_BRIDGE_DISCONNECTED'));
322
348
  });
323
349
 
@@ -390,7 +416,22 @@ export class BrowserAgentBroker {
390
416
  }
391
417
 
392
418
  if (frame.kind === 'request') {
393
- socket.send(JSON.stringify(createErrorResponseFrame(frame.id, 'E_UNKNOWN_TYPE', `Unknown request type: ${frame.type}`)));
419
+ // Local peer brokers use request frames to proxy browser tool calls
420
+ // through the primary broker's single Chrome extension bridge. The
421
+ // extension itself does not send request frames to the broker, so this
422
+ // is safe and avoids requiring Chrome/MV3 to maintain one WebSocket per
423
+ // pi process.
424
+ void this.request(frame.type, frame.params)
425
+ .then((response) => {
426
+ socket.send(JSON.stringify({ ...response, id: frame.id }));
427
+ })
428
+ .catch((error) => {
429
+ socket.send(JSON.stringify(createErrorResponseFrame(
430
+ frame.id,
431
+ 'E_BRIDGE_DISCONNECTED',
432
+ error instanceof Error ? error.message : String(error),
433
+ )));
434
+ });
394
435
  }
395
436
  }
396
437
  }
package/src/index.ts CHANGED
@@ -1,17 +1,20 @@
1
1
  import { join } from 'node:path';
2
2
 
3
3
  import { BrowserAgentBroker } from './broker/server.ts';
4
+ import { RemoteBrowserAgentBroker } from './broker/remote.ts';
4
5
  import { TaskStore } from './broker/task-store.ts';
5
6
  import { ensureStateDir } from './util/paths.ts';
6
7
  import { listInstances, removeInstanceFile, writeInstanceFile } from './util/instances.ts';
7
8
  import { registerAllTools, resetRegisteredBrowserTools } from './tools/_register.ts';
8
9
  import { createBrowserAgentToolsTool, resetBrowserAgentToolState } from './tools/browser_agent_tools.ts';
9
10
 
10
- let brokerSingleton: BrowserAgentBroker | null = null;
11
- let brokerStartup: Promise<BrowserAgentBroker> | null = null;
11
+ type BrowserAgentBrokerLike = BrowserAgentBroker | RemoteBrowserAgentBroker;
12
+
13
+ let brokerSingleton: BrowserAgentBrokerLike | null = null;
14
+ let brokerStartup: Promise<BrowserAgentBrokerLike> | null = null;
12
15
  let startupMessage: string | null = null;
13
16
 
14
- export function getBroker(): BrowserAgentBroker | null {
17
+ export function getBroker(): BrowserAgentBrokerLike | null {
15
18
  return brokerSingleton;
16
19
  }
17
20
 
@@ -32,34 +35,71 @@ export async function resetForTests(): Promise<void> {
32
35
  startupMessage = null;
33
36
  }
34
37
 
35
- async function createAndStartBroker(logger: Console): Promise<BrowserAgentBroker> {
38
+ async function createAndStartBroker(logger: Console): Promise<BrowserAgentBrokerLike> {
36
39
  const tasksDir = await ensureStateDir('tasks');
37
- const broker = new BrowserAgentBroker({
40
+ const preferredPort = Number(process.env.PI_BA_PORT || 7878);
41
+ const host = process.env.PI_BA_HOST || '127.0.0.1';
42
+
43
+ // Robust multi-instance mode:
44
+ // - One primary process owns the broker listener on 7878 and receives the
45
+ // Chrome extension bridge.
46
+ // - Secondary pi processes that lose the 7878 bind race proxy requests
47
+ // through the primary broker instead of requiring Chrome to connect to
48
+ // their fallback ports (fragile under MV3 service-worker sleep/backoff).
49
+ const primaryBroker = new BrowserAgentBroker({
50
+ host,
51
+ port: preferredPort,
52
+ portRange: 1,
53
+ fallbackToEphemeral: false,
38
54
  logger,
39
55
  taskStore: new TaskStore({ dir: join(tasksDir) }),
40
56
  });
41
- // start() now throws on fatal startup failure. If we get here it bound successfully.
42
- await broker.start();
43
- // GC any stale instance files left behind by previous crashed runs, then
44
- // publish ourselves so the browser extension can discover us regardless of
45
- // which port we ended up on.
57
+
46
58
  try {
47
- await listInstances({ gcStale: true });
48
- await writeInstanceFile({
49
- pid: process.pid,
50
- port: broker.port,
51
- host: broker.host,
52
- url: broker.url,
53
- cwd: process.cwd(),
54
- startedAt: new Date().toISOString(),
55
- });
59
+ await primaryBroker.start();
60
+ try {
61
+ await listInstances({ gcStale: true });
62
+ await writeInstanceFile({
63
+ pid: process.pid,
64
+ port: primaryBroker.port,
65
+ host: primaryBroker.host,
66
+ url: primaryBroker.url,
67
+ cwd: process.cwd(),
68
+ startedAt: new Date().toISOString(),
69
+ });
70
+ } catch (error) {
71
+ logger.warn?.('[pi-browser-agent] failed to publish instance discovery file', error);
72
+ }
73
+ return primaryBroker;
56
74
  } catch (error) {
57
- logger.warn?.('[pi-browser-agent] failed to publish instance discovery file', error);
75
+ const code = (error as NodeJS.ErrnoException)?.code;
76
+ if (code !== 'EADDRINUSE' || process.env.PI_BA_NO_EPHEMERAL) {
77
+ throw error;
78
+ }
79
+
80
+ const remoteBroker = new RemoteBrowserAgentBroker({
81
+ host,
82
+ port: preferredPort,
83
+ logger,
84
+ taskStore: new TaskStore({ dir: join(tasksDir) }),
85
+ });
86
+ try {
87
+ await remoteBroker.start();
88
+ } catch (remoteError) {
89
+ const message = remoteError instanceof Error ? remoteError.message : String(remoteError);
90
+ if (message.includes('not a pi-browser-agent broker')) {
91
+ throw new Error(`Port ${preferredPort} is busy, but it is not pi-browser-agent`);
92
+ }
93
+ if (message.includes('old pi-browser-agent broker')) {
94
+ throw new Error(`Old browser broker on ${preferredPort}; restart the first pi instance`);
95
+ }
96
+ throw remoteError;
97
+ }
98
+ return remoteBroker;
58
99
  }
59
- return broker;
60
100
  }
61
101
 
62
- async function getOrCreateBroker(logger: Console = console): Promise<BrowserAgentBroker> {
102
+ async function getOrCreateBroker(logger: Console = console): Promise<BrowserAgentBrokerLike> {
63
103
  // If an existing broker is healthy, reuse it.
64
104
  if (brokerSingleton) {
65
105
  const probe = brokerSingleton.probeConnectivity();
@@ -113,7 +153,7 @@ export default async function piBrowserAgentExtension(pi: {
113
153
  }
114
154
  } catch (error) {
115
155
  startupMessage = error instanceof Error ? error.message : String(error);
116
- ctx?.ui?.notify?.(`pi-browser-agent startup failed: ${startupMessage}`, 'error');
156
+ ctx?.ui?.notify?.(`Browser agent unavailable: ${startupMessage}`, 'error');
117
157
  // Install the meta-tool against a non-started fallback broker so the
118
158
  // session still exposes a diagnostic surface. Do NOT publish this broker
119
159
  // as the singleton — we want a real bind retry on the next session.
@@ -5,9 +5,10 @@ import { mkdtemp } from 'node:fs/promises';
5
5
  import { tmpdir } from 'node:os';
6
6
  import { join } from 'node:path';
7
7
 
8
- import WebSocket, { type RawData } from 'ws';
8
+ import WebSocket, { WebSocketServer, type RawData } from 'ws';
9
9
 
10
10
  import { BrowserAgentBroker } from '../src/broker/server.ts';
11
+ import { RemoteBrowserAgentBroker } from '../src/broker/remote.ts';
11
12
  import { TaskStore } from '../src/broker/task-store.ts';
12
13
 
13
14
  async function getFreePort(): Promise<number> {
@@ -76,6 +77,212 @@ test('broker probe reports server-only and bridge-connected states', async () =>
76
77
  await broker.stop();
77
78
  });
78
79
 
80
+ test('remote broker proxies requests through the primary broker bridge', async () => {
81
+ const port = await getFreePort();
82
+ const primary = await createBroker(port);
83
+ await primary.start();
84
+
85
+ const bridge = new WebSocket(`ws://127.0.0.1:${port}`);
86
+ await new Promise<void>((resolve, reject) => {
87
+ bridge.once('error', reject);
88
+ bridge.once('open', () => {
89
+ bridge.send(JSON.stringify({
90
+ v: 1,
91
+ kind: 'hello',
92
+ extensionId: 'ext-remote-proxy-test',
93
+ version: '0.1.0',
94
+ capabilities: ['browser_list_tabs'],
95
+ }));
96
+ });
97
+ bridge.once('message', () => resolve());
98
+ });
99
+ bridge.on('message', (data: RawData) => {
100
+ const frame = JSON.parse(String(data));
101
+ if (frame.kind === 'request') {
102
+ bridge.send(JSON.stringify({
103
+ v: 1,
104
+ kind: 'response',
105
+ id: frame.id,
106
+ ok: true,
107
+ data: { proxied: true, type: frame.type, params: frame.params },
108
+ }));
109
+ }
110
+ });
111
+
112
+ const root = await mkdtemp(join(tmpdir(), 'pi-browser-agent-remote-'));
113
+ const remote = new RemoteBrowserAgentBroker({
114
+ host: '127.0.0.1',
115
+ port,
116
+ logger: { info() {}, warn() {}, error() {} },
117
+ taskStore: new TaskStore({ dir: join(root, 'tasks') }),
118
+ });
119
+ await remote.start();
120
+
121
+ const probe = remote.probeConnectivity();
122
+ assert.equal(probe.brokerListening, true);
123
+ assert.equal(probe.bridgeConnected, true);
124
+ assert.equal(probe.url, `ws://127.0.0.1:${port}`);
125
+
126
+ const response = await remote.request('browser_list_tabs', { activeOnly: false });
127
+ assert.equal(response.ok, true);
128
+ assert.equal(response.data?.proxied, true);
129
+ assert.equal(response.data?.type, 'browser_list_tabs');
130
+
131
+ await remote.stop();
132
+ bridge.close();
133
+ await primary.stop();
134
+ });
135
+
136
+ test('remote broker rejects a busy primary port that is not pi-browser-agent', async () => {
137
+ const port = await getFreePort();
138
+ const blocker = new WebSocketServer({ host: '127.0.0.1', port });
139
+ // Accept WebSocket connections but never respond to pi-browser-agent probe
140
+ // frames. This simulates a different websocket app owning the port.
141
+ blocker.on('connection', () => {});
142
+ await new Promise<void>((resolve) => blocker.once('listening', () => resolve()));
143
+
144
+ const root = await mkdtemp(join(tmpdir(), 'pi-browser-agent-not-broker-'));
145
+ const remote = new RemoteBrowserAgentBroker({
146
+ host: '127.0.0.1',
147
+ port,
148
+ logger: { info() {}, warn() {}, error() {} },
149
+ requestTimeoutMs: 500,
150
+ taskStore: new TaskStore({ dir: join(root, 'tasks') }),
151
+ });
152
+
153
+ await assert.rejects(() => remote.start(), /not a pi-browser-agent broker/i);
154
+ await remote.stop();
155
+ await new Promise<void>((resolve, reject) => blocker.close((error) => (error ? reject(error) : resolve())));
156
+ });
157
+
158
+ test('remote broker rejects an old pi-browser-agent primary without proxy support', async () => {
159
+ const port = await getFreePort();
160
+ const oldPrimary = new WebSocketServer({ host: '127.0.0.1', port });
161
+ oldPrimary.on('connection', (socket) => {
162
+ socket.on('message', (data) => {
163
+ const frame = JSON.parse(String(data));
164
+ if (frame.kind === 'probe') {
165
+ socket.send(JSON.stringify({
166
+ v: 1,
167
+ kind: 'response',
168
+ id: frame.id,
169
+ ok: true,
170
+ data: {
171
+ brokerReachable: true,
172
+ brokerListening: true,
173
+ bridgeConnected: true,
174
+ url: `ws://127.0.0.1:${port}`,
175
+ bridgeSessionSerial: 1,
176
+ },
177
+ }));
178
+ }
179
+ });
180
+ });
181
+ await new Promise<void>((resolve) => oldPrimary.once('listening', () => resolve()));
182
+
183
+ const root = await mkdtemp(join(tmpdir(), 'pi-browser-agent-old-primary-'));
184
+ const remote = new RemoteBrowserAgentBroker({
185
+ host: '127.0.0.1',
186
+ port,
187
+ logger: { info() {}, warn() {}, error() {} },
188
+ requestTimeoutMs: 500,
189
+ taskStore: new TaskStore({ dir: join(root, 'tasks') }),
190
+ });
191
+
192
+ await assert.rejects(() => remote.start(), /old pi-browser-agent broker/i);
193
+ await remote.stop();
194
+ await new Promise<void>((resolve, reject) => oldPrimary.close((error) => (error ? reject(error) : resolve())));
195
+ });
196
+
197
+ test('remote broker promotes itself when the primary broker exits', async () => {
198
+ const port = await getFreePort();
199
+ const primary = await createBroker(port);
200
+ await primary.start();
201
+
202
+ const root = await mkdtemp(join(tmpdir(), 'pi-browser-agent-promote-'));
203
+ const remote = new RemoteBrowserAgentBroker({
204
+ host: '127.0.0.1',
205
+ port,
206
+ logger: { info() {}, warn() {}, error() {} },
207
+ requestTimeoutMs: 2_000,
208
+ taskStore: new TaskStore({ dir: join(root, 'tasks') }),
209
+ });
210
+ await remote.start();
211
+ assert.equal(remote.probeConnectivity().brokerListening, true);
212
+
213
+ await primary.stop();
214
+
215
+ // Wait until the remote wins the bind race and becomes the new primary.
216
+ await new Promise<void>((resolve, reject) => {
217
+ const deadline = Date.now() + 3_000;
218
+ const tick = () => {
219
+ const probe = remote.probeConnectivity();
220
+ if (probe.brokerListening && probe.url === `ws://127.0.0.1:${port}` && probe.bridgeSessionSerial === 0) {
221
+ resolve();
222
+ return;
223
+ }
224
+ if (Date.now() > deadline) {
225
+ reject(new Error(`remote did not promote in time: ${JSON.stringify(probe)}`));
226
+ return;
227
+ }
228
+ setTimeout(tick, 25);
229
+ };
230
+ tick();
231
+ });
232
+
233
+ // Simulate Chrome reconnecting to the same stable URL (7878 in production).
234
+ const bridge = await new Promise<WebSocket>((resolve, reject) => {
235
+ const deadline = Date.now() + 3_000;
236
+ const tryConnect = () => {
237
+ const candidate = new WebSocket(`ws://127.0.0.1:${port}`);
238
+ let settled = false;
239
+ candidate.once('error', (error) => {
240
+ if (settled) return;
241
+ settled = true;
242
+ try { candidate.terminate(); } catch { /* ignore */ }
243
+ if (Date.now() > deadline) return reject(error);
244
+ setTimeout(tryConnect, 25);
245
+ });
246
+ candidate.once('open', () => {
247
+ if (settled) return;
248
+ settled = true;
249
+ candidate.send(JSON.stringify({
250
+ v: 1,
251
+ kind: 'hello',
252
+ extensionId: 'ext-promote-test',
253
+ version: '0.1.0',
254
+ capabilities: ['browser_list_tabs'],
255
+ }));
256
+ });
257
+ candidate.once('message', () => resolve(candidate));
258
+ };
259
+ tryConnect();
260
+ });
261
+ bridge.on('message', (data: RawData) => {
262
+ const frame = JSON.parse(String(data));
263
+ if (frame.kind === 'request') {
264
+ bridge.send(JSON.stringify({ v: 1, kind: 'response', id: frame.id, ok: true, data: { promoted: true } }));
265
+ }
266
+ });
267
+
268
+ await new Promise<void>((resolve, reject) => {
269
+ const deadline = Date.now() + 1_000;
270
+ const tick = () => {
271
+ if (remote.probeConnectivity().bridgeConnected) return resolve();
272
+ if (Date.now() > deadline) return reject(new Error('promoted broker bridge did not connect'));
273
+ setTimeout(tick, 25);
274
+ };
275
+ tick();
276
+ });
277
+
278
+ const response = await remote.request('browser_list_tabs', {});
279
+ assert.equal(response.ok, true);
280
+ assert.equal(response.data?.promoted, true);
281
+
282
+ bridge.close();
283
+ await remote.stop();
284
+ });
285
+
79
286
  test('broker request/response round-trips and bridge disconnect rejects in-flight requests', async () => {
80
287
  const port = await getFreePort();
81
288
  const broker = await createBroker(port);
@@ -38,12 +38,14 @@ test('writeInstanceFile + listInstances round-trip and survive a process-alive c
38
38
  assert.equal(onDisk.port, 7878);
39
39
 
40
40
  const records = await listInstances();
41
- assert.equal(records.length, 1);
42
- assert.equal(records[0].pid, process.pid);
43
- assert.equal(records[0].port, 7878);
41
+ const ownRecord = records.find((item) => item.pid === process.pid && item.port === 7878);
42
+ assert.ok(ownRecord, `expected to find own record in ${JSON.stringify(records)}`);
43
+ assert.equal(ownRecord.pid, process.pid);
44
+ assert.equal(ownRecord.port, 7878);
44
45
 
45
46
  await removeInstanceFile(process.pid);
46
- assert.equal((await listInstances()).length, 0);
47
+ const afterRemove = await listInstances();
48
+ assert.equal(afterRemove.find((item) => item.pid === process.pid && item.port === 7878), undefined);
47
49
  } finally {
48
50
  guard.restore();
49
51
  }