oira666_pi-browser-agent 0.0.28 → 0.0.29
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/README.md +7 -0
- package/package.json +1 -1
- package/src/broker/legacy-yield.ts +170 -0
- package/src/broker/protocol.ts +22 -0
- package/src/broker/remote.ts +206 -24
- package/src/broker/server.ts +105 -1
- package/src/broker/version.ts +23 -0
- package/src/index.ts +38 -0
- package/tests/fixtures/legacy-host.ts +22 -0
- package/tests/takeover.test.ts +238 -0
package/README.md
CHANGED
|
@@ -103,6 +103,13 @@ If another pi instance owns port `7878`, this session connects through it. If ac
|
|
|
103
103
|
|
|
104
104
|
The status line shows `browser: connected`, `browser: recovering`, or `browser: disconnected`. Transient disconnects and successful recovery do not produce notifications. After 60 seconds without a connection, the extension shows one short warning for that outage and continues retrying quietly. Broker logs and stack traces are not forwarded to the TUI. Use `activate_browser_agent_tools` for on-demand diagnostics.
|
|
105
105
|
|
|
106
|
+
## Which pi session hosts the browser bridge
|
|
107
|
+
|
|
108
|
+
Only one pi process hosts the Chrome bridge (port 7878); every other pi session proxies its browser calls through it.
|
|
109
|
+
|
|
110
|
+
- **`/browser:takeover`** makes the current session the host. The previous host is not killed: hosts running 0.0.29 or newer hand over cooperatively (they release the port, the taker binds it, then Chrome and the other proxies reconnect to the taker). Older hosts cannot be asked, so they are made to let go through Node's built-in inspector (`SIGUSR1`): only their listening socket and broker connections are closed, the session keeps running and becomes a proxy. Node prints "Debugger listening/attached/ending" in that session's terminal; that is the only visible side effect.
|
|
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
|
+
|
|
106
113
|
## WSL → Windows Chrome
|
|
107
114
|
|
|
108
115
|
Loopback usually works with modern WSL setups. If your Windows Chrome cannot reach the broker on `127.0.0.1`:
|
package/package.json
CHANGED
|
@@ -0,0 +1,170 @@
|
|
|
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
|
+
};
|
package/src/broker/protocol.ts
CHANGED
|
@@ -30,6 +30,18 @@ export const ProbeFrameSchema = Type.Object({
|
|
|
30
30
|
id: Type.Optional(Type.String()),
|
|
31
31
|
});
|
|
32
32
|
|
|
33
|
+
/** Peer -> primary: "hand the Chrome bridge over to me". `takeover_done` tells
|
|
34
|
+
* the yielding primary the taker has bound the port, so it may now close its
|
|
35
|
+
* connections (Chrome and other proxies then reconnect to the taker). */
|
|
36
|
+
export const TakeoverFrameSchema = Type.Object({
|
|
37
|
+
v: Type.Literal(PROTOCOL_VERSION),
|
|
38
|
+
kind: Type.Union([Type.Literal('takeover'), Type.Literal('takeover_done')]),
|
|
39
|
+
id: Type.String(),
|
|
40
|
+
pid: Type.Optional(Type.Number()),
|
|
41
|
+
version: Type.Optional(Type.String()),
|
|
42
|
+
reason: Type.Optional(Type.String()),
|
|
43
|
+
});
|
|
44
|
+
|
|
33
45
|
export const RequestFrameSchema = Type.Object({
|
|
34
46
|
v: Type.Literal(PROTOCOL_VERSION),
|
|
35
47
|
kind: Type.Literal('request'),
|
|
@@ -63,6 +75,7 @@ export const NotifyFrameSchema = Type.Object({
|
|
|
63
75
|
export const AnyIncomingFrameSchema = Type.Union([
|
|
64
76
|
HelloFrameSchema,
|
|
65
77
|
ProbeFrameSchema,
|
|
78
|
+
TakeoverFrameSchema,
|
|
66
79
|
RequestFrameSchema,
|
|
67
80
|
ResponseFrameSchema,
|
|
68
81
|
NotifyFrameSchema,
|
|
@@ -72,6 +85,7 @@ export type HelloFrame = Static<typeof HelloFrameSchema>;
|
|
|
72
85
|
export type WelcomeFrame = Static<typeof WelcomeFrameSchema>;
|
|
73
86
|
export type ProbeFrame = Static<typeof ProbeFrameSchema>;
|
|
74
87
|
export type RequestFrame = Static<typeof RequestFrameSchema>;
|
|
88
|
+
export type TakeoverFrame = Static<typeof TakeoverFrameSchema>;
|
|
75
89
|
export type ResponseFrame = Static<typeof ResponseFrameSchema>;
|
|
76
90
|
export type NotifyFrame = Static<typeof NotifyFrameSchema>;
|
|
77
91
|
export type IncomingFrame = Static<typeof AnyIncomingFrameSchema>;
|
|
@@ -103,6 +117,14 @@ export interface ProbeResult {
|
|
|
103
117
|
lastBridgeDisconnectedAt?: string;
|
|
104
118
|
/** Why the bridge was last dropped (heartbeat timeout, socket close, ...). */
|
|
105
119
|
lastBridgeDisconnectReason?: string;
|
|
120
|
+
/** Package version of the broker code that owns the listener. Absent on
|
|
121
|
+
* brokers older than 0.0.29, which therefore always count as oldest. */
|
|
122
|
+
brokerVersion?: string;
|
|
123
|
+
/** Primary understands the cooperative `takeover` frame. */
|
|
124
|
+
supportsTakeover?: boolean;
|
|
125
|
+
/** Primary got the bridge via an explicit /browser:takeover. Automatic
|
|
126
|
+
* newer-version takeovers leave such a host alone. */
|
|
127
|
+
hostedByCommand?: boolean;
|
|
106
128
|
}
|
|
107
129
|
|
|
108
130
|
export function parseIncomingFrame(raw: string): IncomingFrame {
|
package/src/broker/remote.ts
CHANGED
|
@@ -26,6 +26,21 @@ import {
|
|
|
26
26
|
throwIfAborted,
|
|
27
27
|
type BrokerRequestOptions,
|
|
28
28
|
} from './abort.ts';
|
|
29
|
+
import { BROKER_VERSION, compareVersions } from './version.ts';
|
|
30
|
+
import { yieldLegacyPrimary, type LegacyYield } from './legacy-yield.ts';
|
|
31
|
+
|
|
32
|
+
/** How long a taker keeps retrying the bind while the previous host lets go. */
|
|
33
|
+
const TAKEOVER_BIND_MS = 3_000;
|
|
34
|
+
/** Do not retry an automatic takeover of the same host more often than this. */
|
|
35
|
+
const AUTO_TAKEOVER_COOLDOWN_MS = 5 * 60_000;
|
|
36
|
+
|
|
37
|
+
export interface TakeoverResult {
|
|
38
|
+
/** already: we host. free: nobody hosted. cooperative: new host handed over.
|
|
39
|
+
* legacy: an old (< 0.0.29) host was made to let go via its inspector. */
|
|
40
|
+
mode: 'already' | 'free' | 'cooperative' | 'legacy';
|
|
41
|
+
previousPid?: number;
|
|
42
|
+
previousVersion?: string;
|
|
43
|
+
}
|
|
29
44
|
|
|
30
45
|
interface PendingRequest {
|
|
31
46
|
resolve: (value: ResponseFrame) => void;
|
|
@@ -69,6 +84,11 @@ export class RemoteBrowserAgentBroker {
|
|
|
69
84
|
* whole budget again. */
|
|
70
85
|
private coldBridgeMisses = 0;
|
|
71
86
|
private coldBridgeSince: number | null = null;
|
|
87
|
+
readonly version: string;
|
|
88
|
+
private readonly autoTakeover: boolean;
|
|
89
|
+
private readonly legacyYield: LegacyYield;
|
|
90
|
+
private takeoverPromise: Promise<TakeoverResult> | null = null;
|
|
91
|
+
private autoTakeoverAttempts = new Map<number, number>();
|
|
72
92
|
|
|
73
93
|
constructor({
|
|
74
94
|
host = '127.0.0.1',
|
|
@@ -76,7 +96,14 @@ export class RemoteBrowserAgentBroker {
|
|
|
76
96
|
logger = console,
|
|
77
97
|
requestTimeoutMs = 10_000,
|
|
78
98
|
taskStore,
|
|
99
|
+
version = BROKER_VERSION,
|
|
100
|
+
autoTakeover = !process.env.PI_BA_NO_AUTO_TAKEOVER,
|
|
101
|
+
legacyYield = yieldLegacyPrimary,
|
|
79
102
|
}: {
|
|
103
|
+
version?: string;
|
|
104
|
+
/** Newest code wins: take the bridge over from a host running older code. */
|
|
105
|
+
autoTakeover?: boolean;
|
|
106
|
+
legacyYield?: LegacyYield;
|
|
80
107
|
host?: string;
|
|
81
108
|
port?: number;
|
|
82
109
|
logger?: BrokerLogger;
|
|
@@ -89,6 +116,9 @@ export class RemoteBrowserAgentBroker {
|
|
|
89
116
|
this.logger = logger;
|
|
90
117
|
this.requestTimeoutMs = requestTimeoutMs;
|
|
91
118
|
this.taskStore = taskStore;
|
|
119
|
+
this.version = version;
|
|
120
|
+
this.autoTakeover = autoTakeover;
|
|
121
|
+
this.legacyYield = legacyYield;
|
|
92
122
|
}
|
|
93
123
|
|
|
94
124
|
async start(): Promise<void> {
|
|
@@ -406,7 +436,180 @@ export class RemoteBrowserAgentBroker {
|
|
|
406
436
|
throw new Error('E_BRIDGE_DISCONNECTED');
|
|
407
437
|
}
|
|
408
438
|
this.validatedSocket = socket;
|
|
409
|
-
|
|
439
|
+
const probe = data as ProbeResult;
|
|
440
|
+
setImmediate(() => this.maybeAutoTakeover(probe));
|
|
441
|
+
return probe;
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/** Mark the bridge we host as explicitly chosen (see /browser:takeover). */
|
|
445
|
+
markHostedByCommand(): void {
|
|
446
|
+
this.promotedBroker?.markHostedByCommand();
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
/**
|
|
450
|
+
* Make THIS process host the Chrome bridge, whoever hosts it now.
|
|
451
|
+
*
|
|
452
|
+
* New hosts (>= 0.0.29) hand over cooperatively: they release the port,
|
|
453
|
+
* we bind it, then they drop Chrome and their proxies, which reconnect to
|
|
454
|
+
* us. Older hosts cannot be asked, so they are made to let go through their
|
|
455
|
+
* Node inspector (see legacy-yield.ts). Nobody is killed or suspended.
|
|
456
|
+
*/
|
|
457
|
+
async takeover(options: { reason?: 'command' | 'auto' } = {}): Promise<TakeoverResult> {
|
|
458
|
+
if (this.stopped) throw new Error('Browser broker is stopped');
|
|
459
|
+
if (this.promotedBroker) {
|
|
460
|
+
if (options.reason !== 'auto') this.promotedBroker.markHostedByCommand();
|
|
461
|
+
return { mode: 'already' };
|
|
462
|
+
}
|
|
463
|
+
if (this.takeoverPromise) return await this.takeoverPromise;
|
|
464
|
+
const running = this.runTakeover(options.reason ?? 'command');
|
|
465
|
+
this.takeoverPromise = running;
|
|
466
|
+
try {
|
|
467
|
+
return await running;
|
|
468
|
+
} finally {
|
|
469
|
+
if (this.takeoverPromise === running) this.takeoverPromise = null;
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
private async runTakeover(reason: 'command' | 'auto'): Promise<TakeoverResult> {
|
|
474
|
+
let probe: ProbeResult;
|
|
475
|
+
try {
|
|
476
|
+
probe = await this.probePrimary();
|
|
477
|
+
} catch {
|
|
478
|
+
// Nobody usable hosts the bridge: simply compete for the free port.
|
|
479
|
+
const promoted = await this.promoteOrReconnect();
|
|
480
|
+
if (!promoted) throw new Error('Could not reach or replace the current browser broker');
|
|
481
|
+
if (reason === 'command') promoted.markHostedByCommand();
|
|
482
|
+
return { mode: 'free' };
|
|
483
|
+
}
|
|
484
|
+
const previousPid = probe.ownerPid;
|
|
485
|
+
const previousVersion = probe.brokerVersion;
|
|
486
|
+
|
|
487
|
+
const candidate = this.createCandidate();
|
|
488
|
+
let mode: TakeoverResult['mode'];
|
|
489
|
+
if (probe.supportsTakeover) {
|
|
490
|
+
const response = await this.sendTakeoverRequest(reason);
|
|
491
|
+
if (!response.ok) throw new Error(response.error?.message || 'The current host refused the takeover');
|
|
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';
|
|
514
|
+
}
|
|
515
|
+
if (this.stopped) {
|
|
516
|
+
await candidate.stop();
|
|
517
|
+
throw new Error('Browser broker is stopped');
|
|
518
|
+
}
|
|
519
|
+
if (reason === 'command') candidate.markHostedByCommand();
|
|
520
|
+
this.adoptPromoted(candidate);
|
|
521
|
+
this.logger.info?.('[pi-browser-agent] took over the browser bridge', { mode, previousPid, previousVersion, reason });
|
|
522
|
+
return { mode, previousPid, previousVersion };
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
/** Newest code wins: a proxy running newer code than the host takes over. */
|
|
526
|
+
private maybeAutoTakeover(probe: ProbeResult): void {
|
|
527
|
+
if (!this.autoTakeover || this.stopped || this.promotedBroker || this.takeoverPromise) return;
|
|
528
|
+
if (probe.hostedByCommand || !probe.ownerPid) return;
|
|
529
|
+
if (compareVersions(this.version, probe.brokerVersion) <= 0) return;
|
|
530
|
+
const last = this.autoTakeoverAttempts.get(probe.ownerPid) ?? 0;
|
|
531
|
+
if (Date.now() - last < AUTO_TAKEOVER_COOLDOWN_MS) return;
|
|
532
|
+
this.autoTakeoverAttempts.set(probe.ownerPid, Date.now());
|
|
533
|
+
this.logger.info?.('[pi-browser-agent] host runs older code; taking over the bridge', {
|
|
534
|
+
hostPid: probe.ownerPid, hostVersion: probe.brokerVersion ?? '< 0.0.29', ourVersion: this.version,
|
|
535
|
+
});
|
|
536
|
+
void this.takeover({ reason: 'auto' }).catch((error) => {
|
|
537
|
+
this.logger.warn?.('[pi-browser-agent] automatic takeover failed', error);
|
|
538
|
+
});
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
private createCandidate(): BrowserAgentBroker {
|
|
542
|
+
return new BrowserAgentBroker({
|
|
543
|
+
host: this.host,
|
|
544
|
+
port: this.port,
|
|
545
|
+
portRange: 1,
|
|
546
|
+
fallbackToEphemeral: false,
|
|
547
|
+
logger: this.logger,
|
|
548
|
+
requestTimeoutMs: this.requestTimeoutMs,
|
|
549
|
+
taskStore: this.taskStore,
|
|
550
|
+
version: this.version,
|
|
551
|
+
});
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
/** Retry the bind while the previous host is letting go of the port. */
|
|
555
|
+
private async bindCandidate(candidate: BrowserAgentBroker, timeoutMs = TAKEOVER_BIND_MS): Promise<boolean> {
|
|
556
|
+
const deadline = Date.now() + timeoutMs;
|
|
557
|
+
for (;;) {
|
|
558
|
+
try {
|
|
559
|
+
await candidate.start();
|
|
560
|
+
return true;
|
|
561
|
+
} catch (error) {
|
|
562
|
+
if ((error as NodeJS.ErrnoException)?.code !== 'EADDRINUSE') throw error;
|
|
563
|
+
if (this.stopped || Date.now() >= deadline) return false;
|
|
564
|
+
}
|
|
565
|
+
await new Promise((resolve) => setTimeout(resolve, 20));
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
private async sendTakeoverRequest(reason: string): Promise<ResponseFrame> {
|
|
570
|
+
await this.ensureConnected();
|
|
571
|
+
const socket = this.socket;
|
|
572
|
+
if (!socket || socket.readyState !== WebSocket.OPEN) throw new Error('E_BRIDGE_DISCONNECTED');
|
|
573
|
+
const id = randomUUID();
|
|
574
|
+
const response = new Promise<ResponseFrame>((resolve, reject) => {
|
|
575
|
+
const timeout = setTimeout(() => {
|
|
576
|
+
this.pendingRequests.delete(id);
|
|
577
|
+
reject(new Error('The current host did not answer the takeover request'));
|
|
578
|
+
}, 5_000);
|
|
579
|
+
timeout.unref?.();
|
|
580
|
+
this.pendingRequests.set(id, { resolve, reject, timeout });
|
|
581
|
+
});
|
|
582
|
+
socket.send(JSON.stringify({ v: 1, kind: 'takeover', id, pid: process.pid, version: this.version, reason }));
|
|
583
|
+
return await response;
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
/** Install a broker we bound ourselves as this process's primary. */
|
|
587
|
+
private adoptPromoted(candidate: BrowserAgentBroker): void {
|
|
588
|
+
this.unsubscribePromoted?.();
|
|
589
|
+
const offState = candidate.addBridgeStateListener((state) => this.emitBridgeState(state));
|
|
590
|
+
const offYield = candidate.addYieldListener(() => this.onPromotedYielded(candidate));
|
|
591
|
+
this.unsubscribePromoted = () => { offState(); offYield(); };
|
|
592
|
+
this.promotedBroker = candidate;
|
|
593
|
+
this.remoteProbe = candidate.probeConnectivity();
|
|
594
|
+
this.startupError = null;
|
|
595
|
+
this.healAttempt = 0;
|
|
596
|
+
this.cancelHealTimer();
|
|
597
|
+
for (const listener of [...this.promotionListeners]) {
|
|
598
|
+
try {
|
|
599
|
+
listener(candidate);
|
|
600
|
+
} catch (error) {
|
|
601
|
+
this.logger.warn?.('[pi-browser-agent] promotion listener failed', error);
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
/** Our promoted broker handed the bridge to a peer: go back to proxying. */
|
|
607
|
+
private onPromotedYielded(candidate: BrowserAgentBroker): void {
|
|
608
|
+
if (this.promotedBroker !== candidate) return;
|
|
609
|
+
this.unsubscribePromoted?.();
|
|
610
|
+
this.unsubscribePromoted = null;
|
|
611
|
+
this.promotedBroker = null;
|
|
612
|
+
void this.healInBackground('handed the browser bridge to another pi session');
|
|
410
613
|
}
|
|
411
614
|
|
|
412
615
|
private async sendControlRequest(kind: 'probe'): Promise<ResponseFrame> {
|
|
@@ -551,36 +754,15 @@ export class RemoteBrowserAgentBroker {
|
|
|
551
754
|
this.promotionPromise = (async () => {
|
|
552
755
|
// First try to become the new primary. If several remotes detect the
|
|
553
756
|
// disconnect at once, exactly one should win this bind race.
|
|
554
|
-
const candidate =
|
|
555
|
-
host: this.host,
|
|
556
|
-
port: this.port,
|
|
557
|
-
portRange: 1,
|
|
558
|
-
fallbackToEphemeral: false,
|
|
559
|
-
logger: this.logger,
|
|
560
|
-
requestTimeoutMs: this.requestTimeoutMs,
|
|
561
|
-
taskStore: this.taskStore,
|
|
562
|
-
});
|
|
757
|
+
const candidate = this.createCandidate();
|
|
563
758
|
try {
|
|
564
759
|
await candidate.start();
|
|
565
760
|
if (this.stopped) {
|
|
566
761
|
await candidate.stop();
|
|
567
762
|
return null;
|
|
568
763
|
}
|
|
569
|
-
this.
|
|
570
|
-
this.unsubscribePromoted = candidate.addBridgeStateListener((state) => this.emitBridgeState(state));
|
|
571
|
-
this.promotedBroker = candidate;
|
|
572
|
-
this.remoteProbe = candidate.probeConnectivity();
|
|
573
|
-
this.startupError = null;
|
|
574
|
-
this.healAttempt = 0;
|
|
575
|
-
this.cancelHealTimer();
|
|
764
|
+
this.adoptPromoted(candidate);
|
|
576
765
|
this.logger.info?.('[pi-browser-agent] promoted secondary broker to primary', { url: candidate.url });
|
|
577
|
-
for (const listener of [...this.promotionListeners]) {
|
|
578
|
-
try {
|
|
579
|
-
listener(candidate);
|
|
580
|
-
} catch (error) {
|
|
581
|
-
this.logger.warn?.('[pi-browser-agent] promotion listener failed', error);
|
|
582
|
-
}
|
|
583
|
-
}
|
|
584
766
|
return candidate;
|
|
585
767
|
} catch (error) {
|
|
586
768
|
const code = (error as NodeJS.ErrnoException)?.code;
|
package/src/broker/server.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
|
-
import { createServer } from 'node:http';
|
|
2
|
+
import { createServer, type Server as HttpServer } from 'node:http';
|
|
3
3
|
import type { Socket } from 'node:net';
|
|
4
4
|
import { WebSocketServer, type RawData, type WebSocket } from 'ws';
|
|
5
5
|
|
|
@@ -14,10 +14,12 @@ import {
|
|
|
14
14
|
createWelcomeFrame,
|
|
15
15
|
parseIncomingFrame,
|
|
16
16
|
type HelloFrame,
|
|
17
|
+
type TakeoverFrame,
|
|
17
18
|
type ProbeResult,
|
|
18
19
|
type ResponseFrame,
|
|
19
20
|
} from './protocol.ts';
|
|
20
21
|
import { TaskStore } from './task-store.ts';
|
|
22
|
+
import { BROKER_VERSION } from './version.ts';
|
|
21
23
|
import {
|
|
22
24
|
abortError,
|
|
23
25
|
onAbort,
|
|
@@ -69,6 +71,12 @@ export const COLD_MEMO_MISS_THRESHOLD = 2;
|
|
|
69
71
|
* comes back is picked up again quickly. */
|
|
70
72
|
export const COLD_MEMO_TTL_MS = 30_000;
|
|
71
73
|
|
|
74
|
+
/** A yielding primary refuses to rebind for this long, so its own recovery
|
|
75
|
+
* loop cannot grab the port back in the gap before the taker binds it. */
|
|
76
|
+
const TAKEOVER_WINDOW_MS = 10_000;
|
|
77
|
+
/** How long a yielding primary waits for the taker's `takeover_done`. */
|
|
78
|
+
const TAKEOVER_CONFIRM_MS = 5_000;
|
|
79
|
+
|
|
72
80
|
export interface BridgeStateEvent {
|
|
73
81
|
connected: boolean;
|
|
74
82
|
probe: ProbeResult;
|
|
@@ -96,6 +104,13 @@ export class BrowserAgentBroker {
|
|
|
96
104
|
readonly taskStore: TaskStore;
|
|
97
105
|
|
|
98
106
|
private server: WebSocketServer | null = null;
|
|
107
|
+
private httpServer: HttpServer | null = null;
|
|
108
|
+
readonly version: string;
|
|
109
|
+
private yieldingUntil = 0;
|
|
110
|
+
private takeoverInFlight = false;
|
|
111
|
+
private takeoverConfirm: { socket: WebSocket; id: string; finish: (ok: boolean) => void } | null = null;
|
|
112
|
+
private yieldListeners = new Set<() => void>();
|
|
113
|
+
private hostedByCommand = false;
|
|
99
114
|
private bridgeSocket: WebSocket | null = null;
|
|
100
115
|
private bridgeHello: HelloFrame | null = null;
|
|
101
116
|
private bridgeSessionSerial = 0;
|
|
@@ -136,7 +151,9 @@ export class BrowserAgentBroker {
|
|
|
136
151
|
logger = console,
|
|
137
152
|
requestTimeoutMs = 10_000,
|
|
138
153
|
taskStore,
|
|
154
|
+
version = BROKER_VERSION,
|
|
139
155
|
}: {
|
|
156
|
+
version?: string;
|
|
140
157
|
host?: string;
|
|
141
158
|
port?: number;
|
|
142
159
|
/** Number of consecutive ports to try starting at `port` before falling
|
|
@@ -158,6 +175,19 @@ export class BrowserAgentBroker {
|
|
|
158
175
|
this.logger = logger;
|
|
159
176
|
this.requestTimeoutMs = requestTimeoutMs;
|
|
160
177
|
this.taskStore = taskStore;
|
|
178
|
+
this.version = version;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** Fired after this broker handed the bridge to a peer via takeover. */
|
|
182
|
+
addYieldListener(listener: () => void): () => void {
|
|
183
|
+
this.yieldListeners.add(listener);
|
|
184
|
+
return () => { this.yieldListeners.delete(listener); };
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** This host was chosen explicitly (/browser:takeover); automatic
|
|
188
|
+
* newer-version takeovers leave it alone. */
|
|
189
|
+
markHostedByCommand(): void {
|
|
190
|
+
this.hostedByCommand = true;
|
|
161
191
|
}
|
|
162
192
|
|
|
163
193
|
get url(): string {
|
|
@@ -169,6 +199,10 @@ export class BrowserAgentBroker {
|
|
|
169
199
|
if (this.server) {
|
|
170
200
|
return;
|
|
171
201
|
}
|
|
202
|
+
if (Date.now() < this.yieldingUntil) {
|
|
203
|
+
// Handing the port to a peer: our own recovery must not grab it back.
|
|
204
|
+
throw Object.assign(new Error('Broker is handing the bridge over to another pi session'), { code: 'EADDRINUSE' });
|
|
205
|
+
}
|
|
172
206
|
|
|
173
207
|
this.startupError = null;
|
|
174
208
|
|
|
@@ -452,6 +486,7 @@ export class BrowserAgentBroker {
|
|
|
452
486
|
this.port = candidate;
|
|
453
487
|
}
|
|
454
488
|
this.server = server;
|
|
489
|
+
this.httpServer = httpServer;
|
|
455
490
|
// Only log post-listen server errors. Startup bind errors such as an
|
|
456
491
|
// expected EADDRINUSE fallback are handled by onError and should not
|
|
457
492
|
// be printed as scary broker failures.
|
|
@@ -619,6 +654,9 @@ export class BrowserAgentBroker {
|
|
|
619
654
|
url: this.url,
|
|
620
655
|
bridgeSessionSerial: this.bridgeSessionSerial,
|
|
621
656
|
supportsBrokerProxy: true,
|
|
657
|
+
brokerVersion: this.version,
|
|
658
|
+
supportsTakeover: true,
|
|
659
|
+
hostedByCommand: this.hostedByCommand || undefined,
|
|
622
660
|
role: 'primary',
|
|
623
661
|
ownerPid: process.pid,
|
|
624
662
|
listeningSince: this.listeningSince ? new Date(this.listeningSince).toISOString() : undefined,
|
|
@@ -662,6 +700,61 @@ export class BrowserAgentBroker {
|
|
|
662
700
|
});
|
|
663
701
|
}
|
|
664
702
|
|
|
703
|
+
/**
|
|
704
|
+
* Cooperative handover of the Chrome bridge to the peer on `socket`.
|
|
705
|
+
*
|
|
706
|
+
* The listening PORT is released first while every connection (Chrome
|
|
707
|
+
* bridge, other proxies) stays open, so no other peer notices anything and
|
|
708
|
+
* only the taker races for the port. Once the taker confirms it is bound we
|
|
709
|
+
* close everything; Chrome and the other proxies then reconnect to it. If
|
|
710
|
+
* the taker never confirms, we still close and our own recovery (or a peer)
|
|
711
|
+
* rebinds the port.
|
|
712
|
+
*/
|
|
713
|
+
private async handleTakeover(socket: WebSocket, frame: TakeoverFrame): Promise<void> {
|
|
714
|
+
if (this.takeoverInFlight || !this.server) {
|
|
715
|
+
socket.send(JSON.stringify(createErrorResponseFrame(frame.id, 'E_BUSY', this.server ? 'Another takeover is already in progress' : 'This broker is not hosting')));
|
|
716
|
+
return;
|
|
717
|
+
}
|
|
718
|
+
this.takeoverInFlight = true;
|
|
719
|
+
this.yieldingUntil = Date.now() + TAKEOVER_WINDOW_MS;
|
|
720
|
+
this.logger.info?.('[pi-browser-agent] handing the browser bridge over', { toPid: frame.pid, toVersion: frame.version, reason: frame.reason });
|
|
721
|
+
let confirmed = false;
|
|
722
|
+
try {
|
|
723
|
+
const done = new Promise<boolean>((resolve) => {
|
|
724
|
+
const onClose = () => finish(false);
|
|
725
|
+
const timer = setTimeout(() => finish(false), TAKEOVER_CONFIRM_MS);
|
|
726
|
+
timer.unref?.();
|
|
727
|
+
const finish = (ok: boolean) => {
|
|
728
|
+
clearTimeout(timer);
|
|
729
|
+
socket.off('close', onClose);
|
|
730
|
+
this.takeoverConfirm = null;
|
|
731
|
+
resolve(ok);
|
|
732
|
+
};
|
|
733
|
+
socket.once('close', onClose);
|
|
734
|
+
this.takeoverConfirm = { socket, id: frame.id, finish };
|
|
735
|
+
});
|
|
736
|
+
const http = this.httpServer;
|
|
737
|
+
// close() stops listening at once; its callback would wait for every
|
|
738
|
+
// live connection, so it is deliberately not awaited.
|
|
739
|
+
try { http?.close(); } catch { /* already closed */ }
|
|
740
|
+
socket.send(JSON.stringify(createResponseFrame(frame.id, { released: true, pid: process.pid, version: this.version })));
|
|
741
|
+
confirmed = await done;
|
|
742
|
+
} catch (error) {
|
|
743
|
+
this.logger.warn?.('[pi-browser-agent] takeover handling failed', error);
|
|
744
|
+
} finally {
|
|
745
|
+
try { await this.stop(); } catch { /* best effort */ }
|
|
746
|
+
this.httpServer = null;
|
|
747
|
+
this.hostedByCommand = false;
|
|
748
|
+
if (!confirmed) this.yieldingUntil = 0;
|
|
749
|
+
this.takeoverInFlight = false;
|
|
750
|
+
}
|
|
751
|
+
if (confirmed) {
|
|
752
|
+
for (const listener of [...this.yieldListeners]) {
|
|
753
|
+
try { listener(); } catch (error) { this.logger.warn?.('[pi-browser-agent] yield listener failed', error); }
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
|
|
665
758
|
private rejectPendingRequests(error: Error): void {
|
|
666
759
|
for (const [id, pending] of this.pendingRequests.entries()) {
|
|
667
760
|
clearTimeout(pending.timeout);
|
|
@@ -714,6 +807,17 @@ export class BrowserAgentBroker {
|
|
|
714
807
|
return;
|
|
715
808
|
}
|
|
716
809
|
|
|
810
|
+
if (frame.kind === 'takeover') {
|
|
811
|
+
void this.handleTakeover(socket, frame as TakeoverFrame);
|
|
812
|
+
return;
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
if (frame.kind === 'takeover_done') {
|
|
816
|
+
const confirm = this.takeoverConfirm;
|
|
817
|
+
if (confirm && confirm.socket === socket && confirm.id === frame.id) confirm.finish(true);
|
|
818
|
+
return;
|
|
819
|
+
}
|
|
820
|
+
|
|
717
821
|
if (frame.kind === 'probe') {
|
|
718
822
|
const id = frame.id || randomUUID();
|
|
719
823
|
socket.send(JSON.stringify(createResponseFrame(id, this.probeConnectivity())));
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
|
|
3
|
+
/** Version of the code running in THIS process. Brokers advertise it in their
|
|
4
|
+
* probe so peers can tell who runs the newest code (newest wins hosting). */
|
|
5
|
+
export const BROKER_VERSION: string = (() => {
|
|
6
|
+
try {
|
|
7
|
+
const pkg = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8'));
|
|
8
|
+
return typeof pkg.version === 'string' ? pkg.version : '0.0.0';
|
|
9
|
+
} catch {
|
|
10
|
+
return '0.0.0';
|
|
11
|
+
}
|
|
12
|
+
})();
|
|
13
|
+
|
|
14
|
+
/** Numeric dotted-version compare; missing/invalid versions sort as oldest. */
|
|
15
|
+
export function compareVersions(a: string | undefined, b: string | undefined): number {
|
|
16
|
+
const parse = (v: string | undefined) => (v ?? '0.0.0').split(/[.+-]/).slice(0, 3).map((part) => Number.parseInt(part, 10) || 0);
|
|
17
|
+
const left = parse(a);
|
|
18
|
+
const right = parse(b);
|
|
19
|
+
for (let i = 0; i < 3; i += 1) {
|
|
20
|
+
if (left[i] !== right[i]) return left[i] > right[i] ? 1 : -1;
|
|
21
|
+
}
|
|
22
|
+
return 0;
|
|
23
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -11,6 +11,7 @@ import { listInstances, removeInstanceFile, writeInstanceFile } from './util/ins
|
|
|
11
11
|
import { LazyBrokerHandle, type BrokerLike } from './broker/lazy.ts';
|
|
12
12
|
import { registerAllTools, resetRegisteredBrowserTools } from './tools/_register.ts';
|
|
13
13
|
import { createBrowserAgentToolsTool, resetBrowserAgentToolState } from './tools/browser_agent_tools.ts';
|
|
14
|
+
import { BROKER_VERSION } from './broker/version.ts';
|
|
14
15
|
|
|
15
16
|
type BrowserAgentBrokerLike = BrowserAgentBroker | RemoteBrowserAgentBroker;
|
|
16
17
|
type ExtensionUi = {
|
|
@@ -309,7 +310,44 @@ async function getOrCreateBroker(logger: BrokerLogger): Promise<BrowserAgentBrok
|
|
|
309
310
|
return await startup;
|
|
310
311
|
}
|
|
311
312
|
|
|
313
|
+
/**
|
|
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 (or,
|
|
316
|
+
* if it runs old code, is made to let go) and continues as a proxy.
|
|
317
|
+
*/
|
|
318
|
+
export async function takeoverBridgeHosting(logger: BrokerLogger = quietBrokerLogger): Promise<string> {
|
|
319
|
+
const existing = brokerSingleton;
|
|
320
|
+
const broker = existing && existing.probeConnectivity().brokerListening ? existing : await getOrCreateBroker(logger);
|
|
321
|
+
if (broker instanceof BrowserAgentBroker) {
|
|
322
|
+
broker.markHostedByCommand();
|
|
323
|
+
return `This pi session (pid ${process.pid}, v${BROKER_VERSION}) already hosts the browser bridge.`;
|
|
324
|
+
}
|
|
325
|
+
const result = await broker.takeover({ reason: 'command' });
|
|
326
|
+
if (result.mode === 'already') {
|
|
327
|
+
return `This pi session (pid ${process.pid}, v${BROKER_VERSION}) already hosts the browser bridge.`;
|
|
328
|
+
}
|
|
329
|
+
// Chrome reconnects on its own after the old host dropped it.
|
|
330
|
+
await broker.ensureReady({ waitForBridgeMs: 15_000 });
|
|
331
|
+
const connected = broker.probeConnectivity().bridgeConnected;
|
|
332
|
+
const from = result.previousPid
|
|
333
|
+
? ` from pid ${result.previousPid} (v${result.previousVersion ?? '< 0.0.29'}, ${result.mode} handover)`
|
|
334
|
+
: '';
|
|
335
|
+
return `This pi session (pid ${process.pid}, v${BROKER_VERSION}) now hosts the browser bridge${from}. `
|
|
336
|
+
+ (connected ? 'Chrome is connected.' : 'Chrome has not reconnected yet; it retries on its own within ~30 s.');
|
|
337
|
+
}
|
|
338
|
+
|
|
312
339
|
export default async function piBrowserAgentExtension(pi: ExtensionAPI) {
|
|
340
|
+
pi.registerCommand?.('browser:takeover', {
|
|
341
|
+
description: 'Host the Chrome browser bridge in this session (takes it over from whichever session hosts it now)',
|
|
342
|
+
handler: async (_args: string, ctx: any) => {
|
|
343
|
+
try {
|
|
344
|
+
ctx?.ui?.notify?.(await takeoverBridgeHosting(), 'info');
|
|
345
|
+
} catch (error) {
|
|
346
|
+
ctx?.ui?.notify?.(`Browser takeover failed: ${error instanceof Error ? error.message : String(error)}`, 'error');
|
|
347
|
+
}
|
|
348
|
+
},
|
|
349
|
+
});
|
|
350
|
+
|
|
313
351
|
const registerSessionTool = async (ctx?: ExtensionContextLike) => {
|
|
314
352
|
const sessionGeneration = ++sessionLifecycleGeneration;
|
|
315
353
|
for (const cleanup of [...sessionCleanups]) cleanup();
|
|
@@ -0,0 +1,22 @@
|
|
|
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);
|
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { spawn } from 'node:child_process';
|
|
4
|
+
import net from 'node:net';
|
|
5
|
+
import { mkdtemp } from 'node:fs/promises';
|
|
6
|
+
import { tmpdir } from 'node:os';
|
|
7
|
+
import { join } from 'node:path';
|
|
8
|
+
import { fileURLToPath } from 'node:url';
|
|
9
|
+
|
|
10
|
+
import WebSocket, { type RawData } from 'ws';
|
|
11
|
+
|
|
12
|
+
import { BrowserAgentBroker } from '../src/broker/server.ts';
|
|
13
|
+
import { RemoteBrowserAgentBroker } from '../src/broker/remote.ts';
|
|
14
|
+
import { TaskStore } from '../src/broker/task-store.ts';
|
|
15
|
+
import { yieldLegacyPrimary, type LegacyYield } from '../src/broker/legacy-yield.ts';
|
|
16
|
+
import { compareVersions } from '../src/broker/version.ts';
|
|
17
|
+
|
|
18
|
+
const quiet = { info() {}, warn() {}, error() {} };
|
|
19
|
+
|
|
20
|
+
async function freePort(): Promise<number> {
|
|
21
|
+
return await new Promise((resolve, reject) => {
|
|
22
|
+
const server = net.createServer();
|
|
23
|
+
server.listen(0, '127.0.0.1', () => {
|
|
24
|
+
const address = server.address();
|
|
25
|
+
if (!address || typeof address === 'string') return reject(new Error('no port'));
|
|
26
|
+
server.close(() => resolve(address.port));
|
|
27
|
+
});
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
async function store(): Promise<TaskStore> {
|
|
32
|
+
return new TaskStore({ dir: join(await mkdtemp(join(tmpdir(), 'takeover-')), 'tasks') });
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async function primary(port: number, version = '0.0.29'): Promise<BrowserAgentBroker> {
|
|
36
|
+
const broker = new BrowserAgentBroker({ host: '127.0.0.1', port, portRange: 1, fallbackToEphemeral: false, logger: quiet, taskStore: await store(), version });
|
|
37
|
+
await broker.start();
|
|
38
|
+
return broker;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async function remote(port: number, version = '0.0.29', extra: { autoTakeover?: boolean; legacyYield?: LegacyYield } = {}): Promise<RemoteBrowserAgentBroker> {
|
|
42
|
+
const broker = new RemoteBrowserAgentBroker({ host: '127.0.0.1', port, logger: quiet, taskStore: await store(), version, autoTakeover: extra.autoTakeover ?? false, ...(extra.legacyYield ? { legacyYield: extra.legacyYield } : {}) });
|
|
43
|
+
await broker.start();
|
|
44
|
+
return broker;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** A fake Chrome extension: answers every request, reconnects when dropped. */
|
|
48
|
+
function fakeChrome(port: number, label: string) {
|
|
49
|
+
const state = { connected: false, connections: 0, stopped: false, socket: null as WebSocket | null };
|
|
50
|
+
const connect = () => {
|
|
51
|
+
if (state.stopped) return;
|
|
52
|
+
const socket = new WebSocket(`ws://127.0.0.1:${port}`);
|
|
53
|
+
state.socket = socket;
|
|
54
|
+
socket.on('open', () => socket.send(JSON.stringify({ v: 1, kind: 'hello', extensionId: label, version: '1', capabilities: ['x'] })));
|
|
55
|
+
socket.on('message', (data: RawData) => {
|
|
56
|
+
const frame = JSON.parse(String(data));
|
|
57
|
+
if (frame.kind === 'welcome') { state.connected = true; state.connections += 1; }
|
|
58
|
+
if (frame.kind === 'request') socket.send(JSON.stringify({ v: 1, kind: 'response', id: frame.id, ok: true, data: { servedBy: label } }));
|
|
59
|
+
});
|
|
60
|
+
socket.on('close', () => { state.connected = false; setTimeout(connect, 50); });
|
|
61
|
+
socket.on('error', () => {});
|
|
62
|
+
};
|
|
63
|
+
connect();
|
|
64
|
+
return { state, stop: () => { state.stopped = true; state.socket?.close(); } };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async function waitFor(condition: () => boolean, timeoutMs = 5_000): Promise<void> {
|
|
68
|
+
const deadline = Date.now() + timeoutMs;
|
|
69
|
+
while (!condition()) {
|
|
70
|
+
if (Date.now() > deadline) throw new Error('condition not met in time');
|
|
71
|
+
await new Promise((resolve) => setTimeout(resolve, 20));
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
test('versions compare numerically and missing versions count as oldest', () => {
|
|
76
|
+
assert.equal(compareVersions('0.0.29', '0.0.28'), 1);
|
|
77
|
+
assert.equal(compareVersions('0.0.10', '0.0.9'), 1);
|
|
78
|
+
assert.equal(compareVersions('0.0.29', undefined), 1);
|
|
79
|
+
assert.equal(compareVersions('0.0.29', '0.0.29'), 0);
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
test('cooperative takeover: the taker hosts, Chrome and other proxies follow it', { timeout: 20_000 }, async () => {
|
|
83
|
+
const port = await freePort();
|
|
84
|
+
const host = await primary(port);
|
|
85
|
+
const chrome = fakeChrome(port, 'chrome');
|
|
86
|
+
await waitFor(() => host.probeConnectivity().bridgeConnected);
|
|
87
|
+
const bystander = await remote(port);
|
|
88
|
+
const taker = await remote(port);
|
|
89
|
+
|
|
90
|
+
const result = await taker.takeover({ reason: 'command' });
|
|
91
|
+
assert.equal(result.mode, 'cooperative');
|
|
92
|
+
assert.equal(taker.probeConnectivity().role, 'promoted');
|
|
93
|
+
assert.equal(taker.probeConnectivity().hostedByCommand, true);
|
|
94
|
+
assert.equal(host.probeConnectivity().brokerListening, false);
|
|
95
|
+
|
|
96
|
+
// Chrome reconnects to the new host and requests flow through it.
|
|
97
|
+
await waitFor(() => chrome.state.connections >= 2 && taker.probeConnectivity().bridgeConnected);
|
|
98
|
+
const viaTaker = await taker.request('x', {}, { timeoutMs: 2_000 });
|
|
99
|
+
assert.deepEqual(viaTaker.data, { servedBy: 'chrome' });
|
|
100
|
+
// The old host's own recovery cannot steal the port back.
|
|
101
|
+
await host.ensureReady({ waitForBridgeMs: 0 });
|
|
102
|
+
assert.equal(host.probeConnectivity().brokerListening, false);
|
|
103
|
+
// A bystander proxy heals onto the new host.
|
|
104
|
+
await bystander.ensureReady({ waitForBridgeMs: 3_000 });
|
|
105
|
+
const viaBystander = await bystander.request('x', {}, { timeoutMs: 2_000 });
|
|
106
|
+
assert.deepEqual(viaBystander.data, { servedBy: 'chrome' });
|
|
107
|
+
|
|
108
|
+
chrome.stop();
|
|
109
|
+
await bystander.stop();
|
|
110
|
+
await taker.stop();
|
|
111
|
+
await host.stop();
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
test('a promoted host that is taken over goes back to proxying', { timeout: 20_000 }, async () => {
|
|
115
|
+
const port = await freePort();
|
|
116
|
+
const host = await primary(port);
|
|
117
|
+
const chrome = fakeChrome(port, 'chrome');
|
|
118
|
+
await waitFor(() => host.probeConnectivity().bridgeConnected);
|
|
119
|
+
const first = await remote(port);
|
|
120
|
+
const second = await remote(port);
|
|
121
|
+
|
|
122
|
+
assert.equal((await first.takeover()).mode, 'cooperative');
|
|
123
|
+
await waitFor(() => first.probeConnectivity().bridgeConnected);
|
|
124
|
+
assert.equal((await second.takeover()).mode, 'cooperative');
|
|
125
|
+
await waitFor(() => second.probeConnectivity().bridgeConnected);
|
|
126
|
+
await waitFor(() => first.probeConnectivity().role === 'proxy' && first.probeConnectivity().bridgeConnected);
|
|
127
|
+
const response = await first.request('x', {}, { timeoutMs: 2_000 });
|
|
128
|
+
assert.deepEqual(response.data, { servedBy: 'chrome' });
|
|
129
|
+
|
|
130
|
+
chrome.stop();
|
|
131
|
+
await first.stop();
|
|
132
|
+
await second.stop();
|
|
133
|
+
await host.stop();
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
test('newest code wins: a newer proxy takes the bridge over automatically', { timeout: 20_000 }, async () => {
|
|
137
|
+
const port = await freePort();
|
|
138
|
+
const host = await primary(port, '0.0.28');
|
|
139
|
+
const chrome = fakeChrome(port, 'chrome');
|
|
140
|
+
await waitFor(() => host.probeConnectivity().bridgeConnected);
|
|
141
|
+
const older = await remote(port, '0.0.27', { autoTakeover: true });
|
|
142
|
+
const same = await remote(port, '0.0.28', { autoTakeover: true });
|
|
143
|
+
const newer = await remote(port, '0.0.29', { autoTakeover: true });
|
|
144
|
+
|
|
145
|
+
await waitFor(() => newer.probeConnectivity().role === 'promoted' && newer.probeConnectivity().bridgeConnected, 8_000);
|
|
146
|
+
assert.equal(newer.probeConnectivity().hostedByCommand, undefined);
|
|
147
|
+
for (const proxy of [older, same]) {
|
|
148
|
+
await proxy.ensureReady({ waitForBridgeMs: 3_000 });
|
|
149
|
+
assert.equal(proxy.probeConnectivity().role, 'proxy');
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
chrome.stop();
|
|
153
|
+
for (const broker of [older, same, newer]) await broker.stop();
|
|
154
|
+
await host.stop();
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
test('a host chosen with /browser:takeover is not taken over automatically', { timeout: 20_000 }, async () => {
|
|
158
|
+
const port = await freePort();
|
|
159
|
+
const host = await primary(port, '0.0.28');
|
|
160
|
+
host.markHostedByCommand();
|
|
161
|
+
const newer = await remote(port, '0.0.29', { autoTakeover: true });
|
|
162
|
+
await new Promise((resolve) => setTimeout(resolve, 500));
|
|
163
|
+
assert.equal(newer.probeConnectivity().role, 'proxy');
|
|
164
|
+
assert.equal(host.probeConnectivity().brokerListening, true);
|
|
165
|
+
await newer.stop();
|
|
166
|
+
await host.stop();
|
|
167
|
+
});
|
|
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
|
+
});
|