oira666_pi-browser-agent 0.0.12 → 0.0.13
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/LICENSE +201 -201
- package/README.md +101 -101
- package/package.json +28 -28
- package/src/broker/protocol.ts +128 -128
- package/src/broker/remote.ts +340 -321
- package/src/broker/server.ts +454 -436
- package/src/broker/task-store.ts +192 -192
- package/src/index.ts +1 -1
- package/src/tools/_register.ts +90 -90
- package/src/tools/browser_agent_tools.ts +83 -72
- package/src/tools/browser_js_navigation_tools.ts +491 -489
- package/src/tools/browser_observability_tools.ts +163 -163
- package/src/tools/browser_task_tools.ts +399 -383
- package/src/tools/read_only/common.ts +235 -232
- package/src/tools/read_only/index.ts +344 -344
- package/src/util/instances.ts +102 -102
- package/src/util/paths.ts +19 -19
- package/src/util/truncate.ts +34 -34
- package/tests/broker.test.ts +35 -0
- package/tests/index.test.ts +215 -215
- package/tests/instances.test.ts +80 -80
- package/tests/protocol.test.ts +48 -48
- package/tests/task-store.test.ts +35 -35
- package/tests/tools/browser-js-navigation-tools.test.ts +251 -251
- package/tests/tools/browser-observability-tools.test.ts +100 -100
- package/tests/tools/browser-read-only-tools.test.ts +229 -229
- package/tests/tools/browser-task-tools.test.ts +387 -348
- package/tests/tools/meta-tool.test.ts +110 -110
- package/tsconfig.json +15 -15
package/src/broker/remote.ts
CHANGED
|
@@ -1,321 +1,340 @@
|
|
|
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
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
await
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
private async
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
this.
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
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
|
+
/** Lazily ensure a primary broker is reachable on demand. Tools call this at
|
|
86
|
+
* the start of every request so a killed primary is replaced without waiting
|
|
87
|
+
* for the socket-close handler: reconnect to the current primary, or (if
|
|
88
|
+
* none is listening) compete to become the new primary. Idempotent and safe
|
|
89
|
+
* to call concurrently — `promoteOrReconnect()` dedupes the bind race. */
|
|
90
|
+
async ensureReady(): Promise<void> {
|
|
91
|
+
if (this.promotedBroker) {
|
|
92
|
+
await this.promotedBroker.ensureReady();
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
try {
|
|
96
|
+
await this.ensureConnected();
|
|
97
|
+
this.remoteProbe = await this.probePrimary();
|
|
98
|
+
this.startupError = null;
|
|
99
|
+
} catch {
|
|
100
|
+
await this.promoteOrReconnect();
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async stop(): Promise<void> {
|
|
105
|
+
this.rejectPendingRequests(new Error('E_BRIDGE_DISCONNECTED'));
|
|
106
|
+
const socket = this.socket;
|
|
107
|
+
this.socket = null;
|
|
108
|
+
this.connectPromise = null;
|
|
109
|
+
if (socket) {
|
|
110
|
+
try { socket.close(); } catch { /* ignore */ }
|
|
111
|
+
}
|
|
112
|
+
if (this.promotedBroker) {
|
|
113
|
+
const broker = this.promotedBroker;
|
|
114
|
+
this.promotedBroker = null;
|
|
115
|
+
await broker.stop();
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
async request(type: string, params: unknown, options: { timeoutMs?: number } = {}): Promise<ResponseFrame> {
|
|
120
|
+
if (this.promotedBroker) {
|
|
121
|
+
return await this.promotedBroker.request(type, params, options);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
try {
|
|
125
|
+
await this.ensureConnected();
|
|
126
|
+
} catch {
|
|
127
|
+
const promoted = await this.promoteOrReconnect();
|
|
128
|
+
if (promoted) return await promoted.request(type, params, options);
|
|
129
|
+
await this.ensureConnected();
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const socket = this.socket;
|
|
133
|
+
if (!socket || socket.readyState !== WebSocket.OPEN) {
|
|
134
|
+
const promoted = await this.promoteOrReconnect();
|
|
135
|
+
if (promoted) return await promoted.request(type, params, options);
|
|
136
|
+
throw new Error('E_BRIDGE_DISCONNECTED');
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const id = randomUUID();
|
|
140
|
+
const payload = JSON.stringify({ v: 1, kind: 'request', id, type, params });
|
|
141
|
+
|
|
142
|
+
return await new Promise<ResponseFrame>((resolve, reject) => {
|
|
143
|
+
const timeout = setTimeout(() => {
|
|
144
|
+
this.pendingRequests.delete(id);
|
|
145
|
+
reject(new Error(`Request timed out: ${type}`));
|
|
146
|
+
}, options.timeoutMs ?? this.requestTimeoutMs);
|
|
147
|
+
timeout.unref?.();
|
|
148
|
+
|
|
149
|
+
this.pendingRequests.set(id, { resolve, reject, timeout });
|
|
150
|
+
try {
|
|
151
|
+
socket.send(payload);
|
|
152
|
+
} catch (error) {
|
|
153
|
+
clearTimeout(timeout);
|
|
154
|
+
this.pendingRequests.delete(id);
|
|
155
|
+
reject(error instanceof Error ? error : new Error(String(error)));
|
|
156
|
+
}
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
probeConnectivity(): ProbeResult {
|
|
161
|
+
if (this.promotedBroker) {
|
|
162
|
+
return this.promotedBroker.probeConnectivity();
|
|
163
|
+
}
|
|
164
|
+
const primary = this.remoteProbe;
|
|
165
|
+
if (primary) {
|
|
166
|
+
return {
|
|
167
|
+
...primary,
|
|
168
|
+
brokerReachable: !this.startupError && primary.brokerReachable,
|
|
169
|
+
brokerListening: !this.startupError && primary.brokerListening,
|
|
170
|
+
startupError: this.startupError?.message || primary.startupError,
|
|
171
|
+
url: this.url,
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
return {
|
|
175
|
+
brokerReachable: !this.startupError && !!this.socket,
|
|
176
|
+
brokerListening: !this.startupError && !!this.socket,
|
|
177
|
+
bridgeConnected: false,
|
|
178
|
+
startupError: this.startupError?.message,
|
|
179
|
+
url: this.url,
|
|
180
|
+
bridgeSessionSerial: 0,
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
private async probePrimary(): Promise<ProbeResult> {
|
|
185
|
+
const response = await this.sendControlRequest('probe');
|
|
186
|
+
if (!response.ok) {
|
|
187
|
+
throw new Error(response.error?.message || 'Primary broker probe failed');
|
|
188
|
+
}
|
|
189
|
+
const data = response.data as Partial<ProbeResult> | undefined;
|
|
190
|
+
if (!data || typeof data.brokerListening !== 'boolean' || typeof data.bridgeConnected !== 'boolean') {
|
|
191
|
+
throw new Error(`Port ${this.port} is busy, but it is not a pi-browser-agent broker`);
|
|
192
|
+
}
|
|
193
|
+
if (data.supportsBrokerProxy !== true) {
|
|
194
|
+
throw new Error(`Port ${this.port} has an old pi-browser-agent broker; restart the first pi instance`);
|
|
195
|
+
}
|
|
196
|
+
return data as ProbeResult;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
private async sendControlRequest(kind: 'probe'): Promise<ResponseFrame> {
|
|
200
|
+
await this.ensureConnected();
|
|
201
|
+
const socket = this.socket;
|
|
202
|
+
if (!socket || socket.readyState !== WebSocket.OPEN) {
|
|
203
|
+
return createErrorResponseFrame(randomUUID(), 'E_BRIDGE_DISCONNECTED', 'Primary broker proxy is not connected');
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
const id = randomUUID();
|
|
207
|
+
socket.send(JSON.stringify({ v: 1, kind, id }));
|
|
208
|
+
|
|
209
|
+
return await new Promise<ResponseFrame>((resolve, reject) => {
|
|
210
|
+
const timeout = setTimeout(() => {
|
|
211
|
+
this.pendingRequests.delete(id);
|
|
212
|
+
reject(new Error(`Port ${this.port} is busy, but it is not a pi-browser-agent broker`));
|
|
213
|
+
}, Math.min(this.requestTimeoutMs, 1500));
|
|
214
|
+
this.pendingRequests.set(id, { resolve, reject, timeout });
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
private async ensureConnected(): Promise<void> {
|
|
219
|
+
if (this.socket?.readyState === WebSocket.OPEN) return;
|
|
220
|
+
if (this.connectPromise) return await this.connectPromise;
|
|
221
|
+
|
|
222
|
+
this.connectPromise = new Promise<void>((resolve, reject) => {
|
|
223
|
+
const socket = new WebSocket(this.url);
|
|
224
|
+
let settled = false;
|
|
225
|
+
const connectTimeout = setTimeout(() => {
|
|
226
|
+
fail(new Error(`Port ${this.port} is busy, but it is not a pi-browser-agent broker`));
|
|
227
|
+
}, Math.min(this.requestTimeoutMs, 1500));
|
|
228
|
+
connectTimeout.unref?.();
|
|
229
|
+
|
|
230
|
+
const fail = (error: Error) => {
|
|
231
|
+
if (settled) return;
|
|
232
|
+
settled = true;
|
|
233
|
+
clearTimeout(connectTimeout);
|
|
234
|
+
this.connectPromise = null;
|
|
235
|
+
try { socket.terminate(); } catch { try { socket.close(); } catch { /* ignore */ } }
|
|
236
|
+
reject(error);
|
|
237
|
+
};
|
|
238
|
+
|
|
239
|
+
socket.once('open', () => {
|
|
240
|
+
settled = true;
|
|
241
|
+
clearTimeout(connectTimeout);
|
|
242
|
+
this.socket = socket;
|
|
243
|
+
this.connectPromise = null;
|
|
244
|
+
|
|
245
|
+
socket.on('message', (buffer: RawData) => this.handleRawMessage(buffer.toString()));
|
|
246
|
+
socket.on('close', () => {
|
|
247
|
+
if (this.socket === socket) {
|
|
248
|
+
this.socket = null;
|
|
249
|
+
this.rejectPendingRequests(new Error('E_BRIDGE_DISCONNECTED'));
|
|
250
|
+
void this.promoteOrReconnect();
|
|
251
|
+
}
|
|
252
|
+
});
|
|
253
|
+
socket.on('error', (error) => {
|
|
254
|
+
this.logger.warn?.('[pi-browser-agent] primary broker proxy socket error', error);
|
|
255
|
+
if (this.socket === socket) {
|
|
256
|
+
this.socket = null;
|
|
257
|
+
this.rejectPendingRequests(error instanceof Error ? error : new Error(String(error)));
|
|
258
|
+
void this.promoteOrReconnect();
|
|
259
|
+
}
|
|
260
|
+
});
|
|
261
|
+
resolve();
|
|
262
|
+
});
|
|
263
|
+
socket.once('error', () => fail(new Error(`Port ${this.port} is busy, but it is not a pi-browser-agent broker`)));
|
|
264
|
+
socket.once('unexpected-response', () => fail(new Error(`Port ${this.port} is busy, but it is not a pi-browser-agent broker`)));
|
|
265
|
+
});
|
|
266
|
+
|
|
267
|
+
return await this.connectPromise;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
private async promoteOrReconnect(): Promise<BrowserAgentBroker | null> {
|
|
271
|
+
if (this.promotedBroker) return this.promotedBroker;
|
|
272
|
+
if (this.promotionPromise) return await this.promotionPromise;
|
|
273
|
+
|
|
274
|
+
this.promotionPromise = (async () => {
|
|
275
|
+
// First try to become the new primary. If several remotes detect the
|
|
276
|
+
// disconnect at once, exactly one should win this bind race.
|
|
277
|
+
const candidate = new BrowserAgentBroker({
|
|
278
|
+
host: this.host,
|
|
279
|
+
port: this.port,
|
|
280
|
+
portRange: 1,
|
|
281
|
+
fallbackToEphemeral: false,
|
|
282
|
+
logger: this.logger,
|
|
283
|
+
requestTimeoutMs: this.requestTimeoutMs,
|
|
284
|
+
taskStore: this.taskStore,
|
|
285
|
+
});
|
|
286
|
+
try {
|
|
287
|
+
await candidate.start();
|
|
288
|
+
this.promotedBroker = candidate;
|
|
289
|
+
this.remoteProbe = candidate.probeConnectivity();
|
|
290
|
+
this.startupError = null;
|
|
291
|
+
this.logger.info?.('[pi-browser-agent] promoted secondary broker to primary', { url: candidate.url });
|
|
292
|
+
return candidate;
|
|
293
|
+
} catch (error) {
|
|
294
|
+
const code = (error as NodeJS.ErrnoException)?.code;
|
|
295
|
+
if (code !== 'EADDRINUSE') {
|
|
296
|
+
this.logger.warn?.('[pi-browser-agent] secondary broker promotion failed', error);
|
|
297
|
+
return null;
|
|
298
|
+
}
|
|
299
|
+
// Someone else won the race. Reconnect to the new primary and refresh
|
|
300
|
+
// our probe snapshot.
|
|
301
|
+
try {
|
|
302
|
+
await this.ensureConnected();
|
|
303
|
+
this.remoteProbe = await this.probePrimary();
|
|
304
|
+
this.startupError = null;
|
|
305
|
+
} catch (reconnectError) {
|
|
306
|
+
this.logger.warn?.('[pi-browser-agent] failed to reconnect to promoted primary broker', reconnectError);
|
|
307
|
+
}
|
|
308
|
+
return null;
|
|
309
|
+
} finally {
|
|
310
|
+
this.promotionPromise = null;
|
|
311
|
+
}
|
|
312
|
+
})();
|
|
313
|
+
|
|
314
|
+
return await this.promotionPromise;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
private handleRawMessage(raw: string): void {
|
|
318
|
+
let frame;
|
|
319
|
+
try {
|
|
320
|
+
frame = parseIncomingFrame(raw);
|
|
321
|
+
} catch (error) {
|
|
322
|
+
this.logger.warn?.('[pi-browser-agent] invalid primary proxy frame', error);
|
|
323
|
+
return;
|
|
324
|
+
}
|
|
325
|
+
if (frame.kind !== 'response') return;
|
|
326
|
+
const pending = this.pendingRequests.get(frame.id);
|
|
327
|
+
if (!pending) return;
|
|
328
|
+
clearTimeout(pending.timeout);
|
|
329
|
+
this.pendingRequests.delete(frame.id);
|
|
330
|
+
pending.resolve(frame);
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
private rejectPendingRequests(error: Error): void {
|
|
334
|
+
for (const [id, pending] of this.pendingRequests.entries()) {
|
|
335
|
+
clearTimeout(pending.timeout);
|
|
336
|
+
pending.reject(error);
|
|
337
|
+
this.pendingRequests.delete(id);
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
}
|