oira666_pi-browser-agent 0.0.29 → 0.0.31
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/EVERGREEN.md +6 -4
- package/README.md +2 -2
- package/package.json +2 -2
- package/src/broker/protocol.ts +1 -4
- package/src/broker/remote.ts +15 -39
- package/src/broker/server.ts +0 -1
- package/src/index.ts +3 -3
- package/tests/takeover.test.ts +2 -76
- package/src/broker/legacy-yield.ts +0 -170
- package/tests/fixtures/legacy-host.ts +0 -22
package/EVERGREEN.md
CHANGED
|
@@ -18,7 +18,8 @@ Disconnected startup must not hide tools or flood the TUI with logs.
|
|
|
18
18
|
`package.json` loads `src/index.ts` through `pi.extensions`. Runtime imports the
|
|
19
19
|
public `ExtensionAPI` and `ToolDefinition` types from the package root.
|
|
20
20
|
`pi.on('session_start')` registers tools and acquires the broker;
|
|
21
|
-
`session_shutdown` releases sockets, timers, handles and signal listeners.
|
|
21
|
+
`session_shutdown` releases sockets, timers, handles and signal listeners. Pi 1.8.0
|
|
22
|
+
also emits it on terminal loss without SIGHUP, allowing up to five seconds for cleanup.
|
|
22
23
|
`pi.registerTool` uses TypeBox parameters, execute's AbortSignal, text/image
|
|
23
24
|
content, persisted details, outputSchema, structuredContent and isError.
|
|
24
25
|
`ctx.ui.setStatus` and `notify` report connectivity with delayed outage warnings.
|
|
@@ -37,8 +38,9 @@ Chrome/MV3 connection lifetime, hello/probe/proxy compatibility and primary
|
|
|
37
38
|
promotion are external boundaries. Shutdown, suspend and reload can race startup.
|
|
38
39
|
Image/text limits, spilled files and JSON normalization must preserve usable output.
|
|
39
40
|
Real Chrome/input-backend behavior is not covered by the automated bridge fixture.
|
|
40
|
-
CLI E2E uses stdin-ignored JSON runs, not interactive
|
|
41
|
-
|
|
41
|
+
CLI E2E uses stdin-ignored JSON runs, not interactive terminal loss,
|
|
42
|
+
reload/compaction or RPC abort. Unit tests cover the broker cancellation and
|
|
43
|
+
teardown paths, but do not exercise Pi's terminal-loss detection.
|
|
42
44
|
Live E2E needs credentials for EVERGREEN_E2E_MODEL and may fail on provider outages.
|
|
43
45
|
|
|
44
46
|
## Tests
|
|
@@ -53,7 +55,7 @@ bridge task execution, result/error persistence, cross-process history and clean
|
|
|
53
55
|
A live EVERGREEN_E2E_MODEL call must discover and execute browser_list_tasks even
|
|
54
56
|
without Chrome. Settings/state are isolated; provider credentials are reused.
|
|
55
57
|
These tests protect available tools, working forwarding and durable inspection,
|
|
56
|
-
not merely individual helper outputs. Tested against Pi 1.
|
|
58
|
+
not merely individual helper outputs. Tested against Pi 1.8.0.
|
|
57
59
|
Pi's non-strict OpenAI fallback supports the unconstrained JSON values in
|
|
58
60
|
browser_run_js.args; keep them unconstrained. Session startup/reload uses the
|
|
59
61
|
existing teardown and reacquisition path. No custom renderers consume cached TUI arrays.
|
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# pi-browser-agent
|
|
2
2
|
|
|
3
|
-
Tested against Pi 1.
|
|
3
|
+
Tested against Pi 1.8.0
|
|
4
4
|
|
|
5
5
|
`pi-browser-agent` is a pi extension that starts a local WebSocket broker and registers a browser-driving tool suite for `browser-agent-ext`.
|
|
6
6
|
|
|
@@ -107,7 +107,7 @@ The status line shows `browser: connected`, `browser: recovering`, or `browser:
|
|
|
107
107
|
|
|
108
108
|
Only one pi process hosts the Chrome bridge (port 7878); every other pi session proxies its browser calls through it.
|
|
109
109
|
|
|
110
|
-
- **`/browser:takeover`** makes the current session the host. The previous host is not killed:
|
|
110
|
+
- **`/browser:takeover`** makes the current session the host. The previous host is not killed: it is asked to hand over, releases the port, the taker binds it, then Chrome and the other proxies reconnect to the taker. The previous session keeps running as a proxy.
|
|
111
111
|
- **Newest code wins.** A proxy running a newer version than the host takes the bridge over automatically, the same way, so after an update the fleet converges on the newest code whoever won the port race. A host chosen with `/browser:takeover` is left alone. Set `PI_BA_NO_AUTO_TAKEOVER=1` to disable automatic takeovers in a session.
|
|
112
112
|
|
|
113
113
|
## WSL → Windows Chrome
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "oira666_pi-browser-agent",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.31",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "Pi browser agent broker skeleton with lazy browser tool registration",
|
|
@@ -29,7 +29,7 @@
|
|
|
29
29
|
"typebox": "*"
|
|
30
30
|
},
|
|
31
31
|
"devDependencies": {
|
|
32
|
-
"@earendil-works/pi-coding-agent": "1.
|
|
32
|
+
"@earendil-works/pi-coding-agent": "1.8.0",
|
|
33
33
|
"@types/node": "^26.6.5",
|
|
34
34
|
"@types/ws": "^8.18.2",
|
|
35
35
|
"typebox": "^1.4.3",
|
package/src/broker/protocol.ts
CHANGED
|
@@ -117,11 +117,8 @@ export interface ProbeResult {
|
|
|
117
117
|
lastBridgeDisconnectedAt?: string;
|
|
118
118
|
/** Why the bridge was last dropped (heartbeat timeout, socket close, ...). */
|
|
119
119
|
lastBridgeDisconnectReason?: string;
|
|
120
|
-
/** Package version of the broker code that owns the listener.
|
|
121
|
-
* brokers older than 0.0.29, which therefore always count as oldest. */
|
|
120
|
+
/** Package version of the broker code that owns the listener. */
|
|
122
121
|
brokerVersion?: string;
|
|
123
|
-
/** Primary understands the cooperative `takeover` frame. */
|
|
124
|
-
supportsTakeover?: boolean;
|
|
125
122
|
/** Primary got the bridge via an explicit /browser:takeover. Automatic
|
|
126
123
|
* newer-version takeovers leave such a host alone. */
|
|
127
124
|
hostedByCommand?: boolean;
|
package/src/broker/remote.ts
CHANGED
|
@@ -27,7 +27,6 @@ import {
|
|
|
27
27
|
type BrokerRequestOptions,
|
|
28
28
|
} from './abort.ts';
|
|
29
29
|
import { BROKER_VERSION, compareVersions } from './version.ts';
|
|
30
|
-
import { yieldLegacyPrimary, type LegacyYield } from './legacy-yield.ts';
|
|
31
30
|
|
|
32
31
|
/** How long a taker keeps retrying the bind while the previous host lets go. */
|
|
33
32
|
const TAKEOVER_BIND_MS = 3_000;
|
|
@@ -35,9 +34,8 @@ const TAKEOVER_BIND_MS = 3_000;
|
|
|
35
34
|
const AUTO_TAKEOVER_COOLDOWN_MS = 5 * 60_000;
|
|
36
35
|
|
|
37
36
|
export interface TakeoverResult {
|
|
38
|
-
/** already: we host. free: nobody hosted. cooperative:
|
|
39
|
-
|
|
40
|
-
mode: 'already' | 'free' | 'cooperative' | 'legacy';
|
|
37
|
+
/** already: we host. free: nobody hosted. cooperative: the host handed over. */
|
|
38
|
+
mode: 'already' | 'free' | 'cooperative';
|
|
41
39
|
previousPid?: number;
|
|
42
40
|
previousVersion?: string;
|
|
43
41
|
}
|
|
@@ -86,7 +84,6 @@ export class RemoteBrowserAgentBroker {
|
|
|
86
84
|
private coldBridgeSince: number | null = null;
|
|
87
85
|
readonly version: string;
|
|
88
86
|
private readonly autoTakeover: boolean;
|
|
89
|
-
private readonly legacyYield: LegacyYield;
|
|
90
87
|
private takeoverPromise: Promise<TakeoverResult> | null = null;
|
|
91
88
|
private autoTakeoverAttempts = new Map<number, number>();
|
|
92
89
|
|
|
@@ -98,12 +95,10 @@ export class RemoteBrowserAgentBroker {
|
|
|
98
95
|
taskStore,
|
|
99
96
|
version = BROKER_VERSION,
|
|
100
97
|
autoTakeover = !process.env.PI_BA_NO_AUTO_TAKEOVER,
|
|
101
|
-
legacyYield = yieldLegacyPrimary,
|
|
102
98
|
}: {
|
|
103
99
|
version?: string;
|
|
104
100
|
/** Newest code wins: take the bridge over from a host running older code. */
|
|
105
101
|
autoTakeover?: boolean;
|
|
106
|
-
legacyYield?: LegacyYield;
|
|
107
102
|
host?: string;
|
|
108
103
|
port?: number;
|
|
109
104
|
logger?: BrokerLogger;
|
|
@@ -118,7 +113,6 @@ export class RemoteBrowserAgentBroker {
|
|
|
118
113
|
this.taskStore = taskStore;
|
|
119
114
|
this.version = version;
|
|
120
115
|
this.autoTakeover = autoTakeover;
|
|
121
|
-
this.legacyYield = legacyYield;
|
|
122
116
|
}
|
|
123
117
|
|
|
124
118
|
async start(): Promise<void> {
|
|
@@ -449,10 +443,9 @@ export class RemoteBrowserAgentBroker {
|
|
|
449
443
|
/**
|
|
450
444
|
* Make THIS process host the Chrome bridge, whoever hosts it now.
|
|
451
445
|
*
|
|
452
|
-
*
|
|
453
|
-
*
|
|
454
|
-
*
|
|
455
|
-
* Node inspector (see legacy-yield.ts). Nobody is killed or suspended.
|
|
446
|
+
* The host hands over cooperatively: it releases the port, we bind it,
|
|
447
|
+
* then it drops Chrome and its proxies, which reconnect to us. Nobody is
|
|
448
|
+
* killed or suspended.
|
|
456
449
|
*/
|
|
457
450
|
async takeover(options: { reason?: 'command' | 'auto' } = {}): Promise<TakeoverResult> {
|
|
458
451
|
if (this.stopped) throw new Error('Browser broker is stopped');
|
|
@@ -485,33 +478,16 @@ export class RemoteBrowserAgentBroker {
|
|
|
485
478
|
const previousVersion = probe.brokerVersion;
|
|
486
479
|
|
|
487
480
|
const candidate = this.createCandidate();
|
|
488
|
-
|
|
489
|
-
if (
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
if (!await this.bindCandidate(candidate)) {
|
|
493
|
-
throw new Error('The port did not become free in time; the previous host will recover it');
|
|
494
|
-
}
|
|
495
|
-
try {
|
|
496
|
-
this.socket?.send(JSON.stringify({ v: 1, kind: 'takeover_done', id: response.id }));
|
|
497
|
-
} catch { /* the host closes on its own after a timeout */ }
|
|
498
|
-
this.closeSocket();
|
|
499
|
-
mode = 'cooperative';
|
|
500
|
-
} else {
|
|
501
|
-
if (!previousPid) throw new Error('The current host is too old to report its pid; restart that pi session');
|
|
502
|
-
const bound = await this.legacyYield({
|
|
503
|
-
pid: previousPid,
|
|
504
|
-
port: this.port,
|
|
505
|
-
bind: () => this.bindCandidate(candidate),
|
|
506
|
-
// Our own proxy socket is one of the connections about to be dropped;
|
|
507
|
-
// detach it first so its close does not trigger a heal/promotion race.
|
|
508
|
-
beforeDrop: () => this.closeSocket(),
|
|
509
|
-
logger: this.logger,
|
|
510
|
-
});
|
|
511
|
-
if (!bound) throw new Error('The port did not become free in time; the previous host will recover it');
|
|
512
|
-
this.closeSocket();
|
|
513
|
-
mode = 'legacy';
|
|
481
|
+
const response = await this.sendTakeoverRequest(reason);
|
|
482
|
+
if (!response.ok) throw new Error(response.error?.message || 'The current host refused the takeover');
|
|
483
|
+
if (!await this.bindCandidate(candidate)) {
|
|
484
|
+
throw new Error('The port did not become free in time; the previous host will recover it');
|
|
514
485
|
}
|
|
486
|
+
try {
|
|
487
|
+
this.socket?.send(JSON.stringify({ v: 1, kind: 'takeover_done', id: response.id }));
|
|
488
|
+
} catch { /* the host closes on its own after a timeout */ }
|
|
489
|
+
this.closeSocket();
|
|
490
|
+
const mode = 'cooperative';
|
|
515
491
|
if (this.stopped) {
|
|
516
492
|
await candidate.stop();
|
|
517
493
|
throw new Error('Browser broker is stopped');
|
|
@@ -531,7 +507,7 @@ export class RemoteBrowserAgentBroker {
|
|
|
531
507
|
if (Date.now() - last < AUTO_TAKEOVER_COOLDOWN_MS) return;
|
|
532
508
|
this.autoTakeoverAttempts.set(probe.ownerPid, Date.now());
|
|
533
509
|
this.logger.info?.('[pi-browser-agent] host runs older code; taking over the bridge', {
|
|
534
|
-
hostPid: probe.ownerPid, hostVersion: probe.brokerVersion
|
|
510
|
+
hostPid: probe.ownerPid, hostVersion: probe.brokerVersion, ourVersion: this.version,
|
|
535
511
|
});
|
|
536
512
|
void this.takeover({ reason: 'auto' }).catch((error) => {
|
|
537
513
|
this.logger.warn?.('[pi-browser-agent] automatic takeover failed', error);
|
package/src/broker/server.ts
CHANGED
|
@@ -655,7 +655,6 @@ export class BrowserAgentBroker {
|
|
|
655
655
|
bridgeSessionSerial: this.bridgeSessionSerial,
|
|
656
656
|
supportsBrokerProxy: true,
|
|
657
657
|
brokerVersion: this.version,
|
|
658
|
-
supportsTakeover: true,
|
|
659
658
|
hostedByCommand: this.hostedByCommand || undefined,
|
|
660
659
|
role: 'primary',
|
|
661
660
|
ownerPid: process.pid,
|
package/src/index.ts
CHANGED
|
@@ -312,8 +312,8 @@ async function getOrCreateBroker(logger: BrokerLogger): Promise<BrowserAgentBrok
|
|
|
312
312
|
|
|
313
313
|
/**
|
|
314
314
|
* /browser:takeover — make THIS pi session host the Chrome browser bridge,
|
|
315
|
-
* whoever hosts it now. The previous host is not killed: it hands over
|
|
316
|
-
*
|
|
315
|
+
* whoever hosts it now. The previous host is not killed: it hands over and
|
|
316
|
+
* continues as a proxy.
|
|
317
317
|
*/
|
|
318
318
|
export async function takeoverBridgeHosting(logger: BrokerLogger = quietBrokerLogger): Promise<string> {
|
|
319
319
|
const existing = brokerSingleton;
|
|
@@ -330,7 +330,7 @@ export async function takeoverBridgeHosting(logger: BrokerLogger = quietBrokerLo
|
|
|
330
330
|
await broker.ensureReady({ waitForBridgeMs: 15_000 });
|
|
331
331
|
const connected = broker.probeConnectivity().bridgeConnected;
|
|
332
332
|
const from = result.previousPid
|
|
333
|
-
? ` from pid ${result.previousPid} (v${result.previousVersion ?? '
|
|
333
|
+
? ` from pid ${result.previousPid} (v${result.previousVersion ?? 'unknown'})`
|
|
334
334
|
: '';
|
|
335
335
|
return `This pi session (pid ${process.pid}, v${BROKER_VERSION}) now hosts the browser bridge${from}. `
|
|
336
336
|
+ (connected ? 'Chrome is connected.' : 'Chrome has not reconnected yet; it retries on its own within ~30 s.');
|
package/tests/takeover.test.ts
CHANGED
|
@@ -1,18 +1,15 @@
|
|
|
1
1
|
import test from 'node:test';
|
|
2
2
|
import assert from 'node:assert/strict';
|
|
3
|
-
import { spawn } from 'node:child_process';
|
|
4
3
|
import net from 'node:net';
|
|
5
4
|
import { mkdtemp } from 'node:fs/promises';
|
|
6
5
|
import { tmpdir } from 'node:os';
|
|
7
6
|
import { join } from 'node:path';
|
|
8
|
-
import { fileURLToPath } from 'node:url';
|
|
9
7
|
|
|
10
8
|
import WebSocket, { type RawData } from 'ws';
|
|
11
9
|
|
|
12
10
|
import { BrowserAgentBroker } from '../src/broker/server.ts';
|
|
13
11
|
import { RemoteBrowserAgentBroker } from '../src/broker/remote.ts';
|
|
14
12
|
import { TaskStore } from '../src/broker/task-store.ts';
|
|
15
|
-
import { yieldLegacyPrimary, type LegacyYield } from '../src/broker/legacy-yield.ts';
|
|
16
13
|
import { compareVersions } from '../src/broker/version.ts';
|
|
17
14
|
|
|
18
15
|
const quiet = { info() {}, warn() {}, error() {} };
|
|
@@ -38,8 +35,8 @@ async function primary(port: number, version = '0.0.29'): Promise<BrowserAgentBr
|
|
|
38
35
|
return broker;
|
|
39
36
|
}
|
|
40
37
|
|
|
41
|
-
async function remote(port: number, version = '0.0.29', extra: { autoTakeover?: boolean
|
|
42
|
-
const broker = new RemoteBrowserAgentBroker({ host: '127.0.0.1', port, logger: quiet, taskStore: await store(), version, autoTakeover: extra.autoTakeover ?? false
|
|
38
|
+
async function remote(port: number, version = '0.0.29', extra: { autoTakeover?: boolean } = {}): Promise<RemoteBrowserAgentBroker> {
|
|
39
|
+
const broker = new RemoteBrowserAgentBroker({ host: '127.0.0.1', port, logger: quiet, taskStore: await store(), version, autoTakeover: extra.autoTakeover ?? false });
|
|
43
40
|
await broker.start();
|
|
44
41
|
return broker;
|
|
45
42
|
}
|
|
@@ -165,74 +162,3 @@ test('a host chosen with /browser:takeover is not taken over automatically', { t
|
|
|
165
162
|
await newer.stop();
|
|
166
163
|
await host.stop();
|
|
167
164
|
});
|
|
168
|
-
|
|
169
|
-
test('legacy hosts without takeover support are made to let go via legacyYield', { timeout: 20_000 }, async () => {
|
|
170
|
-
const port = await freePort();
|
|
171
|
-
const host = await primary(port);
|
|
172
|
-
// Pretend to be a pre-0.0.29 broker.
|
|
173
|
-
const realProbe = host.probeConnectivity.bind(host);
|
|
174
|
-
host.probeConnectivity = () => {
|
|
175
|
-
const { supportsTakeover: _s, brokerVersion: _v, ...rest } = realProbe();
|
|
176
|
-
return rest;
|
|
177
|
-
};
|
|
178
|
-
const chrome = fakeChrome(port, 'chrome');
|
|
179
|
-
await waitFor(() => realProbe().bridgeConnected);
|
|
180
|
-
let calledWith: any;
|
|
181
|
-
const legacyYield: LegacyYield = async (options) => {
|
|
182
|
-
calledWith = options;
|
|
183
|
-
(host as any).httpServer.close();
|
|
184
|
-
const bound = await options.bind();
|
|
185
|
-
await options.beforeDrop?.();
|
|
186
|
-
await host.stop();
|
|
187
|
-
return bound;
|
|
188
|
-
};
|
|
189
|
-
const taker = await remote(port, '0.0.29', { legacyYield });
|
|
190
|
-
const result = await taker.takeover();
|
|
191
|
-
assert.equal(result.mode, 'legacy');
|
|
192
|
-
assert.equal(calledWith.pid, process.pid);
|
|
193
|
-
assert.equal(calledWith.port, port);
|
|
194
|
-
await waitFor(() => taker.probeConnectivity().bridgeConnected);
|
|
195
|
-
chrome.stop();
|
|
196
|
-
await taker.stop();
|
|
197
|
-
});
|
|
198
|
-
|
|
199
|
-
test('legacy yield really frees the port of another live process without killing it', { timeout: 30_000 }, async (t) => {
|
|
200
|
-
const inspectorBusy = await fetch('http://127.0.0.1:9229/json/list').then(() => true).catch(() => false);
|
|
201
|
-
if (inspectorBusy) {
|
|
202
|
-
t.skip('inspector port 9229 is in use');
|
|
203
|
-
return;
|
|
204
|
-
}
|
|
205
|
-
process.env.XDG_STATE_HOME = await mkdtemp(join(tmpdir(), 'takeover-state-'));
|
|
206
|
-
const port = await freePort();
|
|
207
|
-
const fixture = fileURLToPath(new URL('./fixtures/legacy-host.ts', import.meta.url));
|
|
208
|
-
const child = spawn(process.execPath, [fixture, String(port)], { stdio: ['ignore', 'pipe', 'pipe'] });
|
|
209
|
-
let out = '';
|
|
210
|
-
child.stdout.on('data', (chunk) => { out += chunk; });
|
|
211
|
-
try {
|
|
212
|
-
await waitFor(() => out.includes('ready'), 10_000);
|
|
213
|
-
const ours = await primary(port).catch(() => null);
|
|
214
|
-
assert.equal(ours, null, 'port must be busy before the takeover');
|
|
215
|
-
const mine = new BrowserAgentBroker({ host: '127.0.0.1', port, portRange: 1, fallbackToEphemeral: false, logger: quiet, taskStore: await store() });
|
|
216
|
-
const bound = await yieldLegacyPrimary({
|
|
217
|
-
pid: child.pid!,
|
|
218
|
-
port,
|
|
219
|
-
bind: async () => {
|
|
220
|
-
const deadline = Date.now() + 3_000;
|
|
221
|
-
for (;;) {
|
|
222
|
-
try { await mine.start(); return true; } catch { if (Date.now() > deadline) return false; }
|
|
223
|
-
await new Promise((resolve) => setTimeout(resolve, 20));
|
|
224
|
-
}
|
|
225
|
-
},
|
|
226
|
-
});
|
|
227
|
-
assert.equal(bound, true);
|
|
228
|
-
assert.equal(mine.probeConnectivity().brokerListening, true);
|
|
229
|
-
await waitFor(() => out.includes('bridge closed'), 5_000);
|
|
230
|
-
assert.equal(child.exitCode, null, 'the previous host must still be running');
|
|
231
|
-
// The inspector is closed again afterwards.
|
|
232
|
-
await new Promise((resolve) => setTimeout(resolve, 300));
|
|
233
|
-
assert.equal(await fetch('http://127.0.0.1:9229/json/list').then(() => true).catch(() => false), false);
|
|
234
|
-
await mine.stop();
|
|
235
|
-
} finally {
|
|
236
|
-
child.kill();
|
|
237
|
-
}
|
|
238
|
-
});
|
|
@@ -1,170 +0,0 @@
|
|
|
1
|
-
import { open, rm, stat } from 'node:fs/promises';
|
|
2
|
-
import { join } from 'node:path';
|
|
3
|
-
import WebSocket from 'ws';
|
|
4
|
-
|
|
5
|
-
import { ensureStateDir } from '../util/paths.ts';
|
|
6
|
-
import type { BrokerLogger } from './server.ts';
|
|
7
|
-
|
|
8
|
-
/**
|
|
9
|
-
* Make a broker that predates the cooperative `takeover` frame (< 0.0.29)
|
|
10
|
-
* give up the Chrome bridge WITHOUT killing or suspending its pi session.
|
|
11
|
-
*
|
|
12
|
-
* Old code cannot be asked politely, and suspending it (SIGTSTP) is not an
|
|
13
|
-
* option: pi stops its whole process group on SIGTSTP, which hands the
|
|
14
|
-
* terminal back to the shell and leaves that session stuck in the background.
|
|
15
|
-
*
|
|
16
|
-
* Instead we open Node's built-in inspector in the target (SIGUSR1, standard
|
|
17
|
-
* Node behaviour), close ONLY its listening socket on the broker port, bind
|
|
18
|
-
* the port ourselves, then destroy its remaining broker connections (Chrome
|
|
19
|
-
* bridge and proxies) so they reconnect to us. The target keeps running; its
|
|
20
|
-
* own recovery loop finds the port taken and turns into a proxy. The inspector
|
|
21
|
-
* is closed again afterwards. Node prints "Debugger listening/attached/ending"
|
|
22
|
-
* in the target's terminal; that is the only visible side effect.
|
|
23
|
-
*/
|
|
24
|
-
export interface LegacyYieldOptions {
|
|
25
|
-
pid: number;
|
|
26
|
-
port: number;
|
|
27
|
-
/** Bind the port in this process; resolves true once bound. */
|
|
28
|
-
bind: () => Promise<boolean>;
|
|
29
|
-
/** Runs after we are bound, before the target's connections are dropped. */
|
|
30
|
-
beforeDrop?: () => void | Promise<void>;
|
|
31
|
-
logger?: BrokerLogger;
|
|
32
|
-
inspectorPort?: number;
|
|
33
|
-
timeoutMs?: number;
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
export type LegacyYield = (options: LegacyYieldOptions) => Promise<boolean>;
|
|
37
|
-
|
|
38
|
-
const LOCK_STALE_MS = 30_000;
|
|
39
|
-
|
|
40
|
-
async function acquireLock(pid: number): Promise<() => Promise<void>> {
|
|
41
|
-
const path = join(await ensureStateDir('locks'), `legacy-takeover-${pid}.lock`);
|
|
42
|
-
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
43
|
-
try {
|
|
44
|
-
const handle = await open(path, 'wx');
|
|
45
|
-
await handle.writeFile(String(process.pid));
|
|
46
|
-
await handle.close();
|
|
47
|
-
return async () => { await rm(path, { force: true }); };
|
|
48
|
-
} catch (error) {
|
|
49
|
-
if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;
|
|
50
|
-
const info = await stat(path).catch(() => null);
|
|
51
|
-
if (info && Date.now() - info.mtimeMs > LOCK_STALE_MS) {
|
|
52
|
-
await rm(path, { force: true });
|
|
53
|
-
continue;
|
|
54
|
-
}
|
|
55
|
-
throw new Error(`Another pi session is already taking over the bridge from pid ${pid}`);
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
throw new Error(`Could not lock the takeover of pid ${pid}`);
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
class InspectorSession {
|
|
62
|
-
private nextId = 0;
|
|
63
|
-
private pending = new Map<number, (frame: any) => void>();
|
|
64
|
-
private readonly socket: WebSocket;
|
|
65
|
-
|
|
66
|
-
constructor(socket: WebSocket) {
|
|
67
|
-
this.socket = socket;
|
|
68
|
-
socket.on('message', (data) => {
|
|
69
|
-
let frame: any;
|
|
70
|
-
try { frame = JSON.parse(String(data)); } catch { return; }
|
|
71
|
-
const resolve = this.pending.get(frame.id);
|
|
72
|
-
if (resolve) {
|
|
73
|
-
this.pending.delete(frame.id);
|
|
74
|
-
resolve(frame);
|
|
75
|
-
}
|
|
76
|
-
});
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
static async connect(url: string, timeoutMs: number): Promise<InspectorSession> {
|
|
80
|
-
const socket = new WebSocket(url);
|
|
81
|
-
await new Promise<void>((resolve, reject) => {
|
|
82
|
-
const timer = setTimeout(() => reject(new Error('Inspector connection timed out')), timeoutMs);
|
|
83
|
-
socket.once('open', () => { clearTimeout(timer); resolve(); });
|
|
84
|
-
socket.once('error', (error) => { clearTimeout(timer); reject(error); });
|
|
85
|
-
});
|
|
86
|
-
return new InspectorSession(socket);
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
async evaluate(expression: string, timeoutMs = 3_000): Promise<unknown> {
|
|
90
|
-
const id = ++this.nextId;
|
|
91
|
-
const frame = await new Promise<any>((resolve, reject) => {
|
|
92
|
-
const timer = setTimeout(() => { this.pending.delete(id); reject(new Error('Inspector evaluation timed out')); }, timeoutMs);
|
|
93
|
-
this.pending.set(id, (value) => { clearTimeout(timer); resolve(value); });
|
|
94
|
-
this.socket.send(JSON.stringify({ id, method: 'Runtime.evaluate', params: { expression, returnByValue: true } }));
|
|
95
|
-
});
|
|
96
|
-
if (frame.error) throw new Error(frame.error.message || 'Inspector evaluation failed');
|
|
97
|
-
if (frame.result?.exceptionDetails) throw new Error(frame.result.exceptionDetails.text || 'Inspector evaluation threw');
|
|
98
|
-
return frame.result?.result?.value;
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
/** inspector.close() in the target blocks until every session detaches, so
|
|
102
|
-
* schedule it there and detach right away instead of awaiting it. */
|
|
103
|
-
closeTargetInspector(): void {
|
|
104
|
-
try {
|
|
105
|
-
this.socket.send(JSON.stringify({
|
|
106
|
-
id: ++this.nextId,
|
|
107
|
-
method: 'Runtime.evaluate',
|
|
108
|
-
params: { expression: "setTimeout(() => { try { process.getBuiltinModule('node:inspector').close(); } catch {} }, 50), 1" },
|
|
109
|
-
}));
|
|
110
|
-
} catch { /* ignore */ }
|
|
111
|
-
setTimeout(() => { try { this.socket.close(); } catch { /* ignore */ } }, 20);
|
|
112
|
-
}
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
async function listTargets(inspectorPort: number): Promise<Array<{ webSocketDebuggerUrl?: string }>> {
|
|
116
|
-
const response = await fetch(`http://127.0.0.1:${inspectorPort}/json/list`);
|
|
117
|
-
return await response.json() as Array<{ webSocketDebuggerUrl?: string }>;
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
export const yieldLegacyPrimary: LegacyYield = async ({
|
|
121
|
-
pid,
|
|
122
|
-
port,
|
|
123
|
-
bind,
|
|
124
|
-
beforeDrop,
|
|
125
|
-
logger,
|
|
126
|
-
inspectorPort = 9229,
|
|
127
|
-
timeoutMs = 3_000,
|
|
128
|
-
}) => {
|
|
129
|
-
if (!Number.isInteger(pid) || pid <= 0 || pid === process.pid) throw new Error('Invalid broker owner pid');
|
|
130
|
-
if (!Number.isInteger(port) || port <= 0) throw new Error('Invalid broker port');
|
|
131
|
-
const release = await acquireLock(pid);
|
|
132
|
-
let session: InspectorSession | null = null;
|
|
133
|
-
try {
|
|
134
|
-
process.kill(pid, 'SIGUSR1');
|
|
135
|
-
const deadline = Date.now() + timeoutMs;
|
|
136
|
-
let targets: Array<{ webSocketDebuggerUrl?: string }> = [];
|
|
137
|
-
while (Date.now() < deadline) {
|
|
138
|
-
try {
|
|
139
|
-
targets = await listTargets(inspectorPort);
|
|
140
|
-
if (targets.length) break;
|
|
141
|
-
} catch { /* inspector not up yet */ }
|
|
142
|
-
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
143
|
-
}
|
|
144
|
-
for (const target of targets) {
|
|
145
|
-
if (!target.webSocketDebuggerUrl) continue;
|
|
146
|
-
const candidate = await InspectorSession.connect(target.webSocketDebuggerUrl, timeoutMs).catch(() => null);
|
|
147
|
-
if (!candidate) continue;
|
|
148
|
-
// The inspector port is shared: make sure this really is the broker owner.
|
|
149
|
-
if (await candidate.evaluate('process.pid').catch(() => null) === pid) {
|
|
150
|
-
session = candidate;
|
|
151
|
-
break;
|
|
152
|
-
}
|
|
153
|
-
candidate.closeTargetInspector();
|
|
154
|
-
}
|
|
155
|
-
if (!session) throw new Error(`Could not open the inspector of pid ${pid} (inspector port ${inspectorPort} busy or disabled)`);
|
|
156
|
-
|
|
157
|
-
const closed = await session.evaluate(`(() => { let n = 0; for (const h of process._getActiveHandles()) { try { const a = typeof h.address === 'function' ? h.address() : null; if (h.listening && a && a.port === ${port}) { h.close(); n += 1; } } catch {} } return n; })()`);
|
|
158
|
-
logger?.info?.('[pi-browser-agent] closed legacy broker listener', { pid, closed });
|
|
159
|
-
const bound = await bind();
|
|
160
|
-
if (bound) {
|
|
161
|
-
await beforeDrop?.();
|
|
162
|
-
const dropped = await session.evaluate(`(() => { let n = 0; for (const h of process._getActiveHandles()) { if (h && h.localPort === ${port} && typeof h.destroy === 'function') { try { h.destroy(); n += 1; } catch {} } } return n; })()`);
|
|
163
|
-
logger?.info?.('[pi-browser-agent] dropped legacy broker connections', { pid, dropped });
|
|
164
|
-
}
|
|
165
|
-
return bound;
|
|
166
|
-
} finally {
|
|
167
|
-
session?.closeTargetInspector();
|
|
168
|
-
await release().catch(() => {});
|
|
169
|
-
}
|
|
170
|
-
};
|
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
// Child process standing in for an old pi session that hosts the bridge.
|
|
2
|
-
import { mkdtemp } from 'node:fs/promises';
|
|
3
|
-
import { tmpdir } from 'node:os';
|
|
4
|
-
import { join } from 'node:path';
|
|
5
|
-
import WebSocket from 'ws';
|
|
6
|
-
|
|
7
|
-
import { BrowserAgentBroker } from '../../src/broker/server.ts';
|
|
8
|
-
import { TaskStore } from '../../src/broker/task-store.ts';
|
|
9
|
-
|
|
10
|
-
const port = Number(process.argv[2]);
|
|
11
|
-
const root = await mkdtemp(join(tmpdir(), 'legacy-host-'));
|
|
12
|
-
const broker = new BrowserAgentBroker({
|
|
13
|
-
host: '127.0.0.1', port, portRange: 1, fallbackToEphemeral: false,
|
|
14
|
-
logger: { info() {}, warn() {}, error() {} },
|
|
15
|
-
taskStore: new TaskStore({ dir: join(root, 'tasks') }),
|
|
16
|
-
});
|
|
17
|
-
await broker.start();
|
|
18
|
-
const bridge = new WebSocket(`ws://127.0.0.1:${port}`);
|
|
19
|
-
bridge.on('open', () => bridge.send(JSON.stringify({ v: 1, kind: 'hello', extensionId: 'ext', version: '1', capabilities: [] })));
|
|
20
|
-
bridge.on('message', () => process.stdout.write('ready\n'));
|
|
21
|
-
bridge.on('close', () => process.stdout.write('bridge closed\n'));
|
|
22
|
-
setInterval(() => {}, 1_000);
|