oira666_pi-browser-agent 0.0.1 → 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 +1 -1
- package/src/broker/protocol.ts +1 -0
- package/src/broker/remote.ts +321 -0
- package/src/broker/server.ts +140 -34
- package/src/index.ts +74 -10
- package/src/util/instances.ts +102 -0
- package/tests/broker.test.ts +267 -6
- package/tests/index.test.ts +17 -0
- package/tests/instances.test.ts +80 -0
package/package.json
CHANGED
package/src/broker/protocol.ts
CHANGED
|
@@ -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
|
+
}
|
package/src/broker/server.ts
CHANGED
|
@@ -28,9 +28,22 @@ interface PendingRequest {
|
|
|
28
28
|
timeout: ReturnType<typeof setTimeout>;
|
|
29
29
|
}
|
|
30
30
|
|
|
31
|
+
function parsePositiveInt(value: string | undefined, fallback: number): number {
|
|
32
|
+
if (!value) return fallback;
|
|
33
|
+
const parsed = Number.parseInt(value, 10);
|
|
34
|
+
return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
|
|
35
|
+
}
|
|
36
|
+
|
|
31
37
|
export class BrowserAgentBroker {
|
|
32
38
|
readonly host: string;
|
|
33
|
-
|
|
39
|
+
/** Port the broker actually bound to. Equals `preferredPort` after a clean
|
|
40
|
+
* bind on the first try; otherwise the first free port in the range, or an
|
|
41
|
+
* OS-assigned ephemeral port if every candidate was busy. Updated by
|
|
42
|
+
* `start()` once the underlying server is listening. */
|
|
43
|
+
port: number;
|
|
44
|
+
readonly preferredPort: number;
|
|
45
|
+
readonly portRange: number;
|
|
46
|
+
readonly fallbackToEphemeral: boolean;
|
|
34
47
|
readonly logger: BrokerLogger;
|
|
35
48
|
readonly requestTimeoutMs: number;
|
|
36
49
|
readonly taskStore: TaskStore;
|
|
@@ -43,22 +56,35 @@ export class BrowserAgentBroker {
|
|
|
43
56
|
private shutdownError: Error | null = null;
|
|
44
57
|
private pingTimer: ReturnType<typeof setInterval> | null = null;
|
|
45
58
|
private pendingRequests = new Map<string, PendingRequest>();
|
|
59
|
+
private sockets = new Set<BridgeSocket>();
|
|
46
60
|
|
|
47
61
|
constructor({
|
|
48
62
|
host = process.env.PI_BA_HOST || '127.0.0.1',
|
|
49
|
-
port =
|
|
63
|
+
port = parsePositiveInt(process.env.PI_BA_PORT, 7878),
|
|
64
|
+
portRange = parsePositiveInt(process.env.PI_BA_PORT_RANGE, 20),
|
|
65
|
+
fallbackToEphemeral = process.env.PI_BA_NO_EPHEMERAL ? false : true,
|
|
50
66
|
logger = console,
|
|
51
67
|
requestTimeoutMs = 10_000,
|
|
52
68
|
taskStore,
|
|
53
69
|
}: {
|
|
54
70
|
host?: string;
|
|
55
71
|
port?: number;
|
|
72
|
+
/** Number of consecutive ports to try starting at `port` before falling
|
|
73
|
+
* back to an OS-assigned ephemeral port. Defaults to 20. Set to 1 to
|
|
74
|
+
* preserve the legacy single-port behaviour. */
|
|
75
|
+
portRange?: number;
|
|
76
|
+
/** If every port in the range is busy, bind to port 0 (OS-assigned).
|
|
77
|
+
* Defaults to true. Set `PI_BA_NO_EPHEMERAL=1` to disable. */
|
|
78
|
+
fallbackToEphemeral?: boolean;
|
|
56
79
|
logger?: BrokerLogger;
|
|
57
80
|
requestTimeoutMs?: number;
|
|
58
81
|
taskStore: TaskStore;
|
|
59
82
|
}) {
|
|
60
83
|
this.host = host;
|
|
84
|
+
this.preferredPort = port;
|
|
61
85
|
this.port = port;
|
|
86
|
+
this.portRange = Math.max(1, portRange);
|
|
87
|
+
this.fallbackToEphemeral = fallbackToEphemeral;
|
|
62
88
|
this.logger = logger;
|
|
63
89
|
this.requestTimeoutMs = requestTimeoutMs;
|
|
64
90
|
this.taskStore = taskStore;
|
|
@@ -78,35 +104,7 @@ export class BrowserAgentBroker {
|
|
|
78
104
|
try {
|
|
79
105
|
await this.taskStore.init();
|
|
80
106
|
await this.taskStore.gc();
|
|
81
|
-
await
|
|
82
|
-
const server = new WebSocketServer({ host: this.host, port: this.port });
|
|
83
|
-
|
|
84
|
-
const onError = (error: Error) => {
|
|
85
|
-
server.off('listening', onListening);
|
|
86
|
-
// Startup failed; do not publish the server as the broker's listener.
|
|
87
|
-
this.server = null;
|
|
88
|
-
try {
|
|
89
|
-
server.close();
|
|
90
|
-
} catch {
|
|
91
|
-
// ignore; server never finished binding
|
|
92
|
-
}
|
|
93
|
-
reject(error);
|
|
94
|
-
};
|
|
95
|
-
const onListening = () => {
|
|
96
|
-
server.off('error', onError);
|
|
97
|
-
this.server = server;
|
|
98
|
-
resolve();
|
|
99
|
-
};
|
|
100
|
-
|
|
101
|
-
server.once('error', onError);
|
|
102
|
-
server.once('listening', onListening);
|
|
103
|
-
server.on('connection', (socket: WebSocket) => {
|
|
104
|
-
void this.handleConnection(socket);
|
|
105
|
-
});
|
|
106
|
-
server.on('error', (error: Error) => {
|
|
107
|
-
this.logger.error?.('[pi-browser-agent] broker server error', error);
|
|
108
|
-
});
|
|
109
|
-
});
|
|
107
|
+
await this.bindWithFallback();
|
|
110
108
|
|
|
111
109
|
this.pingTimer = setInterval(() => {
|
|
112
110
|
const socket = this.bridgeSocket as BridgeSocket | null;
|
|
@@ -131,14 +129,89 @@ export class BrowserAgentBroker {
|
|
|
131
129
|
}
|
|
132
130
|
}, 25_000);
|
|
133
131
|
this.pingTimer.unref?.();
|
|
134
|
-
this.logger.info?.('[pi-browser-agent] broker listening', { url: this.url });
|
|
132
|
+
this.logger.info?.('[pi-browser-agent] broker listening', { url: this.url, preferredPort: this.preferredPort });
|
|
135
133
|
} catch (error) {
|
|
136
134
|
this.startupError = error instanceof Error ? error : new Error(String(error));
|
|
137
|
-
|
|
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
|
+
}
|
|
138
141
|
throw this.startupError;
|
|
139
142
|
}
|
|
140
143
|
}
|
|
141
144
|
|
|
145
|
+
/** Try to bind to the preferred port, walk up the configured range on
|
|
146
|
+
* EADDRINUSE, and finally fall back to an OS-assigned ephemeral port.
|
|
147
|
+
* Updates `this.port` to the actual bound port on success. */
|
|
148
|
+
private async bindWithFallback(): Promise<void> {
|
|
149
|
+
const candidates: number[] = [];
|
|
150
|
+
for (let i = 0; i < this.portRange; i += 1) {
|
|
151
|
+
candidates.push(this.preferredPort + i);
|
|
152
|
+
}
|
|
153
|
+
if (this.fallbackToEphemeral) {
|
|
154
|
+
candidates.push(0);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
let lastError: Error | null = null;
|
|
158
|
+
for (const candidate of candidates) {
|
|
159
|
+
try {
|
|
160
|
+
await this.tryBind(candidate);
|
|
161
|
+
return;
|
|
162
|
+
} catch (error) {
|
|
163
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
164
|
+
const code = (err as NodeJS.ErrnoException).code;
|
|
165
|
+
if (code === 'EADDRINUSE') {
|
|
166
|
+
lastError = err;
|
|
167
|
+
continue;
|
|
168
|
+
}
|
|
169
|
+
throw err;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
throw lastError ?? new Error('Failed to bind broker to any candidate port');
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
private async tryBind(candidate: number): Promise<void> {
|
|
176
|
+
await new Promise<void>((resolve, reject) => {
|
|
177
|
+
const server = new WebSocketServer({ host: this.host, port: candidate });
|
|
178
|
+
|
|
179
|
+
const onError = (error: Error) => {
|
|
180
|
+
server.off('listening', onListening);
|
|
181
|
+
this.server = null;
|
|
182
|
+
try {
|
|
183
|
+
server.close();
|
|
184
|
+
} catch {
|
|
185
|
+
// ignore; server never finished binding
|
|
186
|
+
}
|
|
187
|
+
reject(error);
|
|
188
|
+
};
|
|
189
|
+
const onListening = () => {
|
|
190
|
+
server.off('error', onError);
|
|
191
|
+
const address = server.address();
|
|
192
|
+
if (address && typeof address === 'object') {
|
|
193
|
+
this.port = address.port;
|
|
194
|
+
} else {
|
|
195
|
+
this.port = candidate;
|
|
196
|
+
}
|
|
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
|
+
});
|
|
204
|
+
resolve();
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
server.once('error', onError);
|
|
208
|
+
server.once('listening', onListening);
|
|
209
|
+
server.on('connection', (socket: WebSocket) => {
|
|
210
|
+
void this.handleConnection(socket);
|
|
211
|
+
});
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
|
|
142
215
|
async stop(): Promise<void> {
|
|
143
216
|
const closeErrors: Error[] = [];
|
|
144
217
|
|
|
@@ -149,6 +222,14 @@ export class BrowserAgentBroker {
|
|
|
149
222
|
|
|
150
223
|
this.rejectPendingRequests(new Error('E_BRIDGE_DISCONNECTED'));
|
|
151
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
|
+
|
|
152
233
|
if (this.bridgeSocket) {
|
|
153
234
|
try {
|
|
154
235
|
this.bridgeSocket.close();
|
|
@@ -165,7 +246,14 @@ export class BrowserAgentBroker {
|
|
|
165
246
|
this.server = null;
|
|
166
247
|
try {
|
|
167
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?.();
|
|
168
255
|
server.close((error) => {
|
|
256
|
+
clearTimeout(forceClose);
|
|
169
257
|
if (error) {
|
|
170
258
|
reject(error);
|
|
171
259
|
return;
|
|
@@ -232,12 +320,14 @@ export class BrowserAgentBroker {
|
|
|
232
320
|
startupError: this.startupError?.message,
|
|
233
321
|
url: this.url,
|
|
234
322
|
bridgeSessionSerial: this.bridgeSessionSerial,
|
|
323
|
+
supportsBrokerProxy: true,
|
|
235
324
|
};
|
|
236
325
|
}
|
|
237
326
|
|
|
238
327
|
private async handleConnection(socket: WebSocket): Promise<void> {
|
|
239
328
|
const bridgeSocket = socket as BridgeSocket;
|
|
240
329
|
bridgeSocket.isAlive = true;
|
|
330
|
+
this.sockets.add(bridgeSocket);
|
|
241
331
|
|
|
242
332
|
// Do NOT evict the current bridge here. A new accepted socket has not yet
|
|
243
333
|
// authenticated as a bridge session. We only replace the active bridge
|
|
@@ -253,6 +343,7 @@ export class BrowserAgentBroker {
|
|
|
253
343
|
});
|
|
254
344
|
|
|
255
345
|
bridgeSocket.on('close', () => {
|
|
346
|
+
this.sockets.delete(bridgeSocket);
|
|
256
347
|
this.failBridge(bridgeSocket, new Error('E_BRIDGE_DISCONNECTED'));
|
|
257
348
|
});
|
|
258
349
|
|
|
@@ -325,7 +416,22 @@ export class BrowserAgentBroker {
|
|
|
325
416
|
}
|
|
326
417
|
|
|
327
418
|
if (frame.kind === 'request') {
|
|
328
|
-
|
|
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
|
+
});
|
|
329
435
|
}
|
|
330
436
|
}
|
|
331
437
|
}
|
package/src/index.ts
CHANGED
|
@@ -1,16 +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';
|
|
7
|
+
import { listInstances, removeInstanceFile, writeInstanceFile } from './util/instances.ts';
|
|
6
8
|
import { registerAllTools, resetRegisteredBrowserTools } from './tools/_register.ts';
|
|
7
9
|
import { createBrowserAgentToolsTool, resetBrowserAgentToolState } from './tools/browser_agent_tools.ts';
|
|
8
10
|
|
|
9
|
-
|
|
10
|
-
|
|
11
|
+
type BrowserAgentBrokerLike = BrowserAgentBroker | RemoteBrowserAgentBroker;
|
|
12
|
+
|
|
13
|
+
let brokerSingleton: BrowserAgentBrokerLike | null = null;
|
|
14
|
+
let brokerStartup: Promise<BrowserAgentBrokerLike> | null = null;
|
|
11
15
|
let startupMessage: string | null = null;
|
|
12
16
|
|
|
13
|
-
export function getBroker():
|
|
17
|
+
export function getBroker(): BrowserAgentBrokerLike | null {
|
|
14
18
|
return brokerSingleton;
|
|
15
19
|
}
|
|
16
20
|
|
|
@@ -31,18 +35,71 @@ export async function resetForTests(): Promise<void> {
|
|
|
31
35
|
startupMessage = null;
|
|
32
36
|
}
|
|
33
37
|
|
|
34
|
-
async function createAndStartBroker(logger: Console): Promise<
|
|
38
|
+
async function createAndStartBroker(logger: Console): Promise<BrowserAgentBrokerLike> {
|
|
35
39
|
const tasksDir = await ensureStateDir('tasks');
|
|
36
|
-
const
|
|
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,
|
|
37
54
|
logger,
|
|
38
55
|
taskStore: new TaskStore({ dir: join(tasksDir) }),
|
|
39
56
|
});
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
57
|
+
|
|
58
|
+
try {
|
|
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;
|
|
74
|
+
} catch (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;
|
|
99
|
+
}
|
|
43
100
|
}
|
|
44
101
|
|
|
45
|
-
async function getOrCreateBroker(logger: Console = console): Promise<
|
|
102
|
+
async function getOrCreateBroker(logger: Console = console): Promise<BrowserAgentBrokerLike> {
|
|
46
103
|
// If an existing broker is healthy, reuse it.
|
|
47
104
|
if (brokerSingleton) {
|
|
48
105
|
const probe = brokerSingleton.probeConnectivity();
|
|
@@ -96,7 +153,7 @@ export default async function piBrowserAgentExtension(pi: {
|
|
|
96
153
|
}
|
|
97
154
|
} catch (error) {
|
|
98
155
|
startupMessage = error instanceof Error ? error.message : String(error);
|
|
99
|
-
ctx?.ui?.notify?.(`
|
|
156
|
+
ctx?.ui?.notify?.(`Browser agent unavailable: ${startupMessage}`, 'error');
|
|
100
157
|
// Install the meta-tool against a non-started fallback broker so the
|
|
101
158
|
// session still exposes a diagnostic surface. Do NOT publish this broker
|
|
102
159
|
// as the singleton — we want a real bind retry on the next session.
|
|
@@ -127,6 +184,13 @@ export default async function piBrowserAgentExtension(pi: {
|
|
|
127
184
|
} catch (error) {
|
|
128
185
|
const message = error instanceof Error ? error.message : String(error);
|
|
129
186
|
ctx?.ui?.notify?.(`pi-browser-agent shutdown failed: ${message}`, 'warning');
|
|
187
|
+
} finally {
|
|
188
|
+
try {
|
|
189
|
+
await removeInstanceFile(process.pid);
|
|
190
|
+
} catch (error) {
|
|
191
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
192
|
+
ctx?.ui?.notify?.(`pi-browser-agent instance cleanup failed: ${message}`, 'warning');
|
|
193
|
+
}
|
|
130
194
|
}
|
|
131
195
|
});
|
|
132
196
|
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { mkdir, readdir, readFile, unlink, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
|
|
4
|
+
import { ensureStateDir, getStateDir } from './paths.ts';
|
|
5
|
+
|
|
6
|
+
export interface InstanceRecord {
|
|
7
|
+
pid: number;
|
|
8
|
+
port: number;
|
|
9
|
+
host: string;
|
|
10
|
+
url: string;
|
|
11
|
+
cwd: string;
|
|
12
|
+
startedAt: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function instancesDir(): string {
|
|
16
|
+
return join(getStateDir(), 'instances');
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function instanceFilePath(pid: number): string {
|
|
20
|
+
return join(instancesDir(), `${pid}.json`);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export async function ensureInstancesDir(): Promise<string> {
|
|
24
|
+
return await ensureStateDir('instances');
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export async function writeInstanceFile(record: InstanceRecord): Promise<string> {
|
|
28
|
+
const dir = await ensureInstancesDir();
|
|
29
|
+
await mkdir(dir, { recursive: true });
|
|
30
|
+
const path = instanceFilePath(record.pid);
|
|
31
|
+
await writeFile(path, JSON.stringify(record, null, 2), 'utf8');
|
|
32
|
+
return path;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export async function removeInstanceFile(pid: number): Promise<void> {
|
|
36
|
+
try {
|
|
37
|
+
await unlink(instanceFilePath(pid));
|
|
38
|
+
} catch (error) {
|
|
39
|
+
const code = (error as NodeJS.ErrnoException)?.code;
|
|
40
|
+
if (code !== 'ENOENT') {
|
|
41
|
+
throw error;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function isProcessAlive(pid: number): boolean {
|
|
47
|
+
if (!Number.isFinite(pid) || pid <= 0) {
|
|
48
|
+
return false;
|
|
49
|
+
}
|
|
50
|
+
try {
|
|
51
|
+
// Signal 0 throws ESRCH if no such process; EPERM means it exists but we
|
|
52
|
+
// lack permission — also "alive" for our purposes.
|
|
53
|
+
process.kill(pid, 0);
|
|
54
|
+
return true;
|
|
55
|
+
} catch (error) {
|
|
56
|
+
const code = (error as NodeJS.ErrnoException)?.code;
|
|
57
|
+
return code === 'EPERM';
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export async function listInstances({ gcStale = true }: { gcStale?: boolean } = {}): Promise<InstanceRecord[]> {
|
|
62
|
+
const dir = instancesDir();
|
|
63
|
+
let entries: string[];
|
|
64
|
+
try {
|
|
65
|
+
entries = await readdir(dir);
|
|
66
|
+
} catch (error) {
|
|
67
|
+
const code = (error as NodeJS.ErrnoException)?.code;
|
|
68
|
+
if (code === 'ENOENT') {
|
|
69
|
+
return [];
|
|
70
|
+
}
|
|
71
|
+
throw error;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const records: InstanceRecord[] = [];
|
|
75
|
+
for (const entry of entries) {
|
|
76
|
+
if (!entry.endsWith('.json')) continue;
|
|
77
|
+
const path = join(dir, entry);
|
|
78
|
+
let record: InstanceRecord | null = null;
|
|
79
|
+
try {
|
|
80
|
+
const raw = await readFile(path, 'utf8');
|
|
81
|
+
record = JSON.parse(raw) as InstanceRecord;
|
|
82
|
+
} catch {
|
|
83
|
+
record = null;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
if (!record || typeof record.pid !== 'number' || typeof record.port !== 'number') {
|
|
87
|
+
if (gcStale) {
|
|
88
|
+
try { await unlink(path); } catch { /* ignore */ }
|
|
89
|
+
}
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
if (gcStale && !isProcessAlive(record.pid)) {
|
|
94
|
+
try { await unlink(path); } catch { /* ignore */ }
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
records.push(record);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
return records;
|
|
102
|
+
}
|
package/tests/broker.test.ts
CHANGED
|
@@ -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> {
|
|
@@ -31,11 +32,13 @@ async function getFreePort(): Promise<number> {
|
|
|
31
32
|
});
|
|
32
33
|
}
|
|
33
34
|
|
|
34
|
-
async function createBroker(port: number) {
|
|
35
|
+
async function createBroker(port: number, opts: { portRange?: number; fallbackToEphemeral?: boolean } = {}) {
|
|
35
36
|
const root = await mkdtemp(join(tmpdir(), 'pi-browser-agent-broker-'));
|
|
36
37
|
return new BrowserAgentBroker({
|
|
37
38
|
host: '127.0.0.1',
|
|
38
39
|
port,
|
|
40
|
+
portRange: opts.portRange ?? 1,
|
|
41
|
+
fallbackToEphemeral: opts.fallbackToEphemeral ?? false,
|
|
39
42
|
logger: { info() {}, warn() {}, error() {} },
|
|
40
43
|
taskStore: new TaskStore({ dir: join(root, 'tasks') }),
|
|
41
44
|
});
|
|
@@ -74,6 +77,212 @@ test('broker probe reports server-only and bridge-connected states', async () =>
|
|
|
74
77
|
await broker.stop();
|
|
75
78
|
});
|
|
76
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
|
+
|
|
77
286
|
test('broker request/response round-trips and bridge disconnect rejects in-flight requests', async () => {
|
|
78
287
|
const port = await getFreePort();
|
|
79
288
|
const broker = await createBroker(port);
|
|
@@ -221,16 +430,14 @@ test('request rejects immediately with E_BRIDGE_DISCONNECTED if the bridge was e
|
|
|
221
430
|
await broker.stop();
|
|
222
431
|
});
|
|
223
432
|
|
|
224
|
-
test('broker throws on startup failure and does not publish a non-listening server', async () => {
|
|
433
|
+
test('broker throws on startup failure and does not publish a non-listening server (range=1, no ephemeral)', async () => {
|
|
225
434
|
const port = await getFreePort();
|
|
226
435
|
const blocker = net.createServer();
|
|
227
436
|
await new Promise<void>((resolve, reject) => blocker.listen(port, '127.0.0.1', () => resolve()).once('error', reject));
|
|
228
437
|
|
|
229
|
-
const broker = await createBroker(port);
|
|
438
|
+
const broker = await createBroker(port, { portRange: 1, fallbackToEphemeral: false });
|
|
230
439
|
await assert.rejects(() => broker.start(), /EADDRINUSE|address already in use/i);
|
|
231
440
|
|
|
232
|
-
// The failed broker must NOT be left in a "listening" state; probe should
|
|
233
|
-
// reflect that the bind did not succeed and the startup error is recorded.
|
|
234
441
|
const probe = broker.probeConnectivity();
|
|
235
442
|
assert.equal(probe.brokerReachable, false);
|
|
236
443
|
assert.equal(probe.brokerListening, false);
|
|
@@ -239,3 +446,57 @@ test('broker throws on startup failure and does not publish a non-listening serv
|
|
|
239
446
|
await broker.stop();
|
|
240
447
|
await new Promise<void>((resolve, reject) => blocker.close((error) => (error ? reject(error) : resolve())));
|
|
241
448
|
});
|
|
449
|
+
|
|
450
|
+
test('broker walks port range past a busy preferred port and publishes the actual bound port', async () => {
|
|
451
|
+
const preferred = await getFreePort();
|
|
452
|
+
const blocker = net.createServer();
|
|
453
|
+
await new Promise<void>((resolve, reject) => blocker.listen(preferred, '127.0.0.1', () => resolve()).once('error', reject));
|
|
454
|
+
|
|
455
|
+
const broker = await createBroker(preferred, { portRange: 5, fallbackToEphemeral: false });
|
|
456
|
+
await broker.start();
|
|
457
|
+
|
|
458
|
+
assert.equal(broker.probeConnectivity().brokerListening, true);
|
|
459
|
+
assert.notEqual(broker.port, preferred);
|
|
460
|
+
assert.ok(broker.port > preferred && broker.port <= preferred + 4, `expected port within range, got ${broker.port}`);
|
|
461
|
+
assert.equal(broker.url, `ws://127.0.0.1:${broker.port}`);
|
|
462
|
+
|
|
463
|
+
await broker.stop();
|
|
464
|
+
await new Promise<void>((resolve, reject) => blocker.close((error) => (error ? reject(error) : resolve())));
|
|
465
|
+
});
|
|
466
|
+
|
|
467
|
+
test('two brokers can run concurrently with default port range without EADDRINUSE', async () => {
|
|
468
|
+
// This is the regression test for the multi-instance hard requirement:
|
|
469
|
+
// starting a second broker while the first holds the preferred port must
|
|
470
|
+
// succeed on a different port instead of throwing.
|
|
471
|
+
const preferred = await getFreePort();
|
|
472
|
+
|
|
473
|
+
const brokerA = await createBroker(preferred, { portRange: 10, fallbackToEphemeral: true });
|
|
474
|
+
await brokerA.start();
|
|
475
|
+
|
|
476
|
+
const brokerB = await createBroker(preferred, { portRange: 10, fallbackToEphemeral: true });
|
|
477
|
+
await brokerB.start();
|
|
478
|
+
|
|
479
|
+
assert.equal(brokerA.probeConnectivity().brokerListening, true);
|
|
480
|
+
assert.equal(brokerB.probeConnectivity().brokerListening, true);
|
|
481
|
+
assert.notEqual(brokerA.port, brokerB.port);
|
|
482
|
+
|
|
483
|
+
await brokerA.stop();
|
|
484
|
+
await brokerB.stop();
|
|
485
|
+
});
|
|
486
|
+
|
|
487
|
+
test('broker falls back to an ephemeral port when the entire range is busy', async () => {
|
|
488
|
+
const preferred = await getFreePort();
|
|
489
|
+
const blocker = net.createServer();
|
|
490
|
+
await new Promise<void>((resolve, reject) => blocker.listen(preferred, '127.0.0.1', () => resolve()).once('error', reject));
|
|
491
|
+
|
|
492
|
+
// portRange=1 means only `preferred` itself is tried before fallback.
|
|
493
|
+
const broker = await createBroker(preferred, { portRange: 1, fallbackToEphemeral: true });
|
|
494
|
+
await broker.start();
|
|
495
|
+
|
|
496
|
+
assert.equal(broker.probeConnectivity().brokerListening, true);
|
|
497
|
+
assert.notEqual(broker.port, preferred);
|
|
498
|
+
assert.ok(broker.port > 0);
|
|
499
|
+
|
|
500
|
+
await broker.stop();
|
|
501
|
+
await new Promise<void>((resolve, reject) => blocker.close((error) => (error ? reject(error) : resolve())));
|
|
502
|
+
});
|
package/tests/index.test.ts
CHANGED
|
@@ -87,12 +87,19 @@ test('extension eagerly registers the full browser_* suite at session start when
|
|
|
87
87
|
test('extension retries broker startup on a later session after a transient bind failure', async () => {
|
|
88
88
|
await resetForTests();
|
|
89
89
|
const originalPort = process.env.PI_BA_PORT;
|
|
90
|
+
const originalRange = process.env.PI_BA_PORT_RANGE;
|
|
91
|
+
const originalNoEph = process.env.PI_BA_NO_EPHEMERAL;
|
|
90
92
|
const blockedPort = await getFreePort();
|
|
91
93
|
const blocker = net.createServer();
|
|
92
94
|
|
|
93
95
|
try {
|
|
94
96
|
await new Promise<void>((resolve, reject) => blocker.listen(blockedPort, '127.0.0.1', () => resolve()).once('error', reject));
|
|
95
97
|
process.env.PI_BA_PORT = String(blockedPort);
|
|
98
|
+
// Force the legacy single-port-no-fallback behaviour so this test still
|
|
99
|
+
// exercises the "transient bind failure" path. With the default range +
|
|
100
|
+
// ephemeral fallback the broker would always succeed.
|
|
101
|
+
process.env.PI_BA_PORT_RANGE = '1';
|
|
102
|
+
process.env.PI_BA_NO_EPHEMERAL = '1';
|
|
96
103
|
|
|
97
104
|
const pi = createPiHarness();
|
|
98
105
|
await extension(pi as any);
|
|
@@ -120,6 +127,16 @@ test('extension retries broker startup on a later session after a transient bind
|
|
|
120
127
|
} else {
|
|
121
128
|
process.env.PI_BA_PORT = originalPort;
|
|
122
129
|
}
|
|
130
|
+
if (originalRange === undefined) {
|
|
131
|
+
delete process.env.PI_BA_PORT_RANGE;
|
|
132
|
+
} else {
|
|
133
|
+
process.env.PI_BA_PORT_RANGE = originalRange;
|
|
134
|
+
}
|
|
135
|
+
if (originalNoEph === undefined) {
|
|
136
|
+
delete process.env.PI_BA_NO_EPHEMERAL;
|
|
137
|
+
} else {
|
|
138
|
+
process.env.PI_BA_NO_EPHEMERAL = originalNoEph;
|
|
139
|
+
}
|
|
123
140
|
}
|
|
124
141
|
});
|
|
125
142
|
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { spawn } from 'node:child_process';
|
|
4
|
+
import { mkdtemp, readFile } from 'node:fs/promises';
|
|
5
|
+
import { tmpdir } from 'node:os';
|
|
6
|
+
import { join } from 'node:path';
|
|
7
|
+
|
|
8
|
+
import { listInstances, removeInstanceFile, writeInstanceFile } from '../src/util/instances.ts';
|
|
9
|
+
|
|
10
|
+
function setStateRoot(): { restore: () => void } {
|
|
11
|
+
const original = process.env.XDG_STATE_HOME;
|
|
12
|
+
return {
|
|
13
|
+
restore: () => {
|
|
14
|
+
if (original === undefined) delete process.env.XDG_STATE_HOME;
|
|
15
|
+
else process.env.XDG_STATE_HOME = original;
|
|
16
|
+
},
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
test('writeInstanceFile + listInstances round-trip and survive a process-alive check', async () => {
|
|
21
|
+
const root = await mkdtemp(join(tmpdir(), 'pi-ba-state-'));
|
|
22
|
+
const guard = setStateRoot();
|
|
23
|
+
process.env.XDG_STATE_HOME = root;
|
|
24
|
+
|
|
25
|
+
try {
|
|
26
|
+
const record = {
|
|
27
|
+
pid: process.pid,
|
|
28
|
+
port: 7878,
|
|
29
|
+
host: '127.0.0.1',
|
|
30
|
+
url: 'ws://127.0.0.1:7878',
|
|
31
|
+
cwd: process.cwd(),
|
|
32
|
+
startedAt: new Date().toISOString(),
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
const path = await writeInstanceFile(record);
|
|
36
|
+
const onDisk = JSON.parse(await readFile(path, 'utf8'));
|
|
37
|
+
assert.equal(onDisk.pid, process.pid);
|
|
38
|
+
assert.equal(onDisk.port, 7878);
|
|
39
|
+
|
|
40
|
+
const records = await listInstances();
|
|
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);
|
|
45
|
+
|
|
46
|
+
await removeInstanceFile(process.pid);
|
|
47
|
+
const afterRemove = await listInstances();
|
|
48
|
+
assert.equal(afterRemove.find((item) => item.pid === process.pid && item.port === 7878), undefined);
|
|
49
|
+
} finally {
|
|
50
|
+
guard.restore();
|
|
51
|
+
}
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
test('listInstances GCs files belonging to dead processes', async () => {
|
|
55
|
+
const root = await mkdtemp(join(tmpdir(), 'pi-ba-state-'));
|
|
56
|
+
const guard = setStateRoot();
|
|
57
|
+
process.env.XDG_STATE_HOME = root;
|
|
58
|
+
|
|
59
|
+
try {
|
|
60
|
+
// Spawn a short-lived child so we know the PID is dead by the time we
|
|
61
|
+
// probe it. We avoid race conditions by waiting for the close event.
|
|
62
|
+
const child = spawn(process.execPath, ['-e', 'process.exit(0)']);
|
|
63
|
+
const deadPid = child.pid!;
|
|
64
|
+
await new Promise<void>((resolve) => child.once('close', () => resolve()));
|
|
65
|
+
|
|
66
|
+
await writeInstanceFile({
|
|
67
|
+
pid: deadPid,
|
|
68
|
+
port: 7900,
|
|
69
|
+
host: '127.0.0.1',
|
|
70
|
+
url: `ws://127.0.0.1:7900`,
|
|
71
|
+
cwd: process.cwd(),
|
|
72
|
+
startedAt: new Date().toISOString(),
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
const records = await listInstances({ gcStale: true });
|
|
76
|
+
assert.equal(records.find((r) => r.pid === deadPid), undefined, 'stale record should have been GCd');
|
|
77
|
+
} finally {
|
|
78
|
+
guard.restore();
|
|
79
|
+
}
|
|
80
|
+
});
|