oira666_pi-browser-agent 0.0.28 → 0.0.30
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/protocol.ts +19 -0
- package/src/broker/remote.ts +182 -24
- package/src/broker/server.ts +104 -1
- package/src/broker/version.ts +23 -0
- package/src/index.ts +38 -0
- package/tests/takeover.test.ts +164 -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: 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
|
+
- **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
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,11 @@ 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. */
|
|
121
|
+
brokerVersion?: string;
|
|
122
|
+
/** Primary got the bridge via an explicit /browser:takeover. Automatic
|
|
123
|
+
* newer-version takeovers leave such a host alone. */
|
|
124
|
+
hostedByCommand?: boolean;
|
|
106
125
|
}
|
|
107
126
|
|
|
108
127
|
export function parseIncomingFrame(raw: string): IncomingFrame {
|
package/src/broker/remote.ts
CHANGED
|
@@ -26,6 +26,19 @@ import {
|
|
|
26
26
|
throwIfAborted,
|
|
27
27
|
type BrokerRequestOptions,
|
|
28
28
|
} from './abort.ts';
|
|
29
|
+
import { BROKER_VERSION, compareVersions } from './version.ts';
|
|
30
|
+
|
|
31
|
+
/** How long a taker keeps retrying the bind while the previous host lets go. */
|
|
32
|
+
const TAKEOVER_BIND_MS = 3_000;
|
|
33
|
+
/** Do not retry an automatic takeover of the same host more often than this. */
|
|
34
|
+
const AUTO_TAKEOVER_COOLDOWN_MS = 5 * 60_000;
|
|
35
|
+
|
|
36
|
+
export interface TakeoverResult {
|
|
37
|
+
/** already: we host. free: nobody hosted. cooperative: the host handed over. */
|
|
38
|
+
mode: 'already' | 'free' | 'cooperative';
|
|
39
|
+
previousPid?: number;
|
|
40
|
+
previousVersion?: string;
|
|
41
|
+
}
|
|
29
42
|
|
|
30
43
|
interface PendingRequest {
|
|
31
44
|
resolve: (value: ResponseFrame) => void;
|
|
@@ -69,6 +82,10 @@ export class RemoteBrowserAgentBroker {
|
|
|
69
82
|
* whole budget again. */
|
|
70
83
|
private coldBridgeMisses = 0;
|
|
71
84
|
private coldBridgeSince: number | null = null;
|
|
85
|
+
readonly version: string;
|
|
86
|
+
private readonly autoTakeover: boolean;
|
|
87
|
+
private takeoverPromise: Promise<TakeoverResult> | null = null;
|
|
88
|
+
private autoTakeoverAttempts = new Map<number, number>();
|
|
72
89
|
|
|
73
90
|
constructor({
|
|
74
91
|
host = '127.0.0.1',
|
|
@@ -76,7 +93,12 @@ export class RemoteBrowserAgentBroker {
|
|
|
76
93
|
logger = console,
|
|
77
94
|
requestTimeoutMs = 10_000,
|
|
78
95
|
taskStore,
|
|
96
|
+
version = BROKER_VERSION,
|
|
97
|
+
autoTakeover = !process.env.PI_BA_NO_AUTO_TAKEOVER,
|
|
79
98
|
}: {
|
|
99
|
+
version?: string;
|
|
100
|
+
/** Newest code wins: take the bridge over from a host running older code. */
|
|
101
|
+
autoTakeover?: boolean;
|
|
80
102
|
host?: string;
|
|
81
103
|
port?: number;
|
|
82
104
|
logger?: BrokerLogger;
|
|
@@ -89,6 +111,8 @@ export class RemoteBrowserAgentBroker {
|
|
|
89
111
|
this.logger = logger;
|
|
90
112
|
this.requestTimeoutMs = requestTimeoutMs;
|
|
91
113
|
this.taskStore = taskStore;
|
|
114
|
+
this.version = version;
|
|
115
|
+
this.autoTakeover = autoTakeover;
|
|
92
116
|
}
|
|
93
117
|
|
|
94
118
|
async start(): Promise<void> {
|
|
@@ -406,7 +430,162 @@ export class RemoteBrowserAgentBroker {
|
|
|
406
430
|
throw new Error('E_BRIDGE_DISCONNECTED');
|
|
407
431
|
}
|
|
408
432
|
this.validatedSocket = socket;
|
|
409
|
-
|
|
433
|
+
const probe = data as ProbeResult;
|
|
434
|
+
setImmediate(() => this.maybeAutoTakeover(probe));
|
|
435
|
+
return probe;
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/** Mark the bridge we host as explicitly chosen (see /browser:takeover). */
|
|
439
|
+
markHostedByCommand(): void {
|
|
440
|
+
this.promotedBroker?.markHostedByCommand();
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
/**
|
|
444
|
+
* Make THIS process host the Chrome bridge, whoever hosts it now.
|
|
445
|
+
*
|
|
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.
|
|
449
|
+
*/
|
|
450
|
+
async takeover(options: { reason?: 'command' | 'auto' } = {}): Promise<TakeoverResult> {
|
|
451
|
+
if (this.stopped) throw new Error('Browser broker is stopped');
|
|
452
|
+
if (this.promotedBroker) {
|
|
453
|
+
if (options.reason !== 'auto') this.promotedBroker.markHostedByCommand();
|
|
454
|
+
return { mode: 'already' };
|
|
455
|
+
}
|
|
456
|
+
if (this.takeoverPromise) return await this.takeoverPromise;
|
|
457
|
+
const running = this.runTakeover(options.reason ?? 'command');
|
|
458
|
+
this.takeoverPromise = running;
|
|
459
|
+
try {
|
|
460
|
+
return await running;
|
|
461
|
+
} finally {
|
|
462
|
+
if (this.takeoverPromise === running) this.takeoverPromise = null;
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
private async runTakeover(reason: 'command' | 'auto'): Promise<TakeoverResult> {
|
|
467
|
+
let probe: ProbeResult;
|
|
468
|
+
try {
|
|
469
|
+
probe = await this.probePrimary();
|
|
470
|
+
} catch {
|
|
471
|
+
// Nobody usable hosts the bridge: simply compete for the free port.
|
|
472
|
+
const promoted = await this.promoteOrReconnect();
|
|
473
|
+
if (!promoted) throw new Error('Could not reach or replace the current browser broker');
|
|
474
|
+
if (reason === 'command') promoted.markHostedByCommand();
|
|
475
|
+
return { mode: 'free' };
|
|
476
|
+
}
|
|
477
|
+
const previousPid = probe.ownerPid;
|
|
478
|
+
const previousVersion = probe.brokerVersion;
|
|
479
|
+
|
|
480
|
+
const candidate = this.createCandidate();
|
|
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');
|
|
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';
|
|
491
|
+
if (this.stopped) {
|
|
492
|
+
await candidate.stop();
|
|
493
|
+
throw new Error('Browser broker is stopped');
|
|
494
|
+
}
|
|
495
|
+
if (reason === 'command') candidate.markHostedByCommand();
|
|
496
|
+
this.adoptPromoted(candidate);
|
|
497
|
+
this.logger.info?.('[pi-browser-agent] took over the browser bridge', { mode, previousPid, previousVersion, reason });
|
|
498
|
+
return { mode, previousPid, previousVersion };
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
/** Newest code wins: a proxy running newer code than the host takes over. */
|
|
502
|
+
private maybeAutoTakeover(probe: ProbeResult): void {
|
|
503
|
+
if (!this.autoTakeover || this.stopped || this.promotedBroker || this.takeoverPromise) return;
|
|
504
|
+
if (probe.hostedByCommand || !probe.ownerPid) return;
|
|
505
|
+
if (compareVersions(this.version, probe.brokerVersion) <= 0) return;
|
|
506
|
+
const last = this.autoTakeoverAttempts.get(probe.ownerPid) ?? 0;
|
|
507
|
+
if (Date.now() - last < AUTO_TAKEOVER_COOLDOWN_MS) return;
|
|
508
|
+
this.autoTakeoverAttempts.set(probe.ownerPid, Date.now());
|
|
509
|
+
this.logger.info?.('[pi-browser-agent] host runs older code; taking over the bridge', {
|
|
510
|
+
hostPid: probe.ownerPid, hostVersion: probe.brokerVersion, ourVersion: this.version,
|
|
511
|
+
});
|
|
512
|
+
void this.takeover({ reason: 'auto' }).catch((error) => {
|
|
513
|
+
this.logger.warn?.('[pi-browser-agent] automatic takeover failed', error);
|
|
514
|
+
});
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
private createCandidate(): BrowserAgentBroker {
|
|
518
|
+
return new BrowserAgentBroker({
|
|
519
|
+
host: this.host,
|
|
520
|
+
port: this.port,
|
|
521
|
+
portRange: 1,
|
|
522
|
+
fallbackToEphemeral: false,
|
|
523
|
+
logger: this.logger,
|
|
524
|
+
requestTimeoutMs: this.requestTimeoutMs,
|
|
525
|
+
taskStore: this.taskStore,
|
|
526
|
+
version: this.version,
|
|
527
|
+
});
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
/** Retry the bind while the previous host is letting go of the port. */
|
|
531
|
+
private async bindCandidate(candidate: BrowserAgentBroker, timeoutMs = TAKEOVER_BIND_MS): Promise<boolean> {
|
|
532
|
+
const deadline = Date.now() + timeoutMs;
|
|
533
|
+
for (;;) {
|
|
534
|
+
try {
|
|
535
|
+
await candidate.start();
|
|
536
|
+
return true;
|
|
537
|
+
} catch (error) {
|
|
538
|
+
if ((error as NodeJS.ErrnoException)?.code !== 'EADDRINUSE') throw error;
|
|
539
|
+
if (this.stopped || Date.now() >= deadline) return false;
|
|
540
|
+
}
|
|
541
|
+
await new Promise((resolve) => setTimeout(resolve, 20));
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
private async sendTakeoverRequest(reason: string): Promise<ResponseFrame> {
|
|
546
|
+
await this.ensureConnected();
|
|
547
|
+
const socket = this.socket;
|
|
548
|
+
if (!socket || socket.readyState !== WebSocket.OPEN) throw new Error('E_BRIDGE_DISCONNECTED');
|
|
549
|
+
const id = randomUUID();
|
|
550
|
+
const response = new Promise<ResponseFrame>((resolve, reject) => {
|
|
551
|
+
const timeout = setTimeout(() => {
|
|
552
|
+
this.pendingRequests.delete(id);
|
|
553
|
+
reject(new Error('The current host did not answer the takeover request'));
|
|
554
|
+
}, 5_000);
|
|
555
|
+
timeout.unref?.();
|
|
556
|
+
this.pendingRequests.set(id, { resolve, reject, timeout });
|
|
557
|
+
});
|
|
558
|
+
socket.send(JSON.stringify({ v: 1, kind: 'takeover', id, pid: process.pid, version: this.version, reason }));
|
|
559
|
+
return await response;
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
/** Install a broker we bound ourselves as this process's primary. */
|
|
563
|
+
private adoptPromoted(candidate: BrowserAgentBroker): void {
|
|
564
|
+
this.unsubscribePromoted?.();
|
|
565
|
+
const offState = candidate.addBridgeStateListener((state) => this.emitBridgeState(state));
|
|
566
|
+
const offYield = candidate.addYieldListener(() => this.onPromotedYielded(candidate));
|
|
567
|
+
this.unsubscribePromoted = () => { offState(); offYield(); };
|
|
568
|
+
this.promotedBroker = candidate;
|
|
569
|
+
this.remoteProbe = candidate.probeConnectivity();
|
|
570
|
+
this.startupError = null;
|
|
571
|
+
this.healAttempt = 0;
|
|
572
|
+
this.cancelHealTimer();
|
|
573
|
+
for (const listener of [...this.promotionListeners]) {
|
|
574
|
+
try {
|
|
575
|
+
listener(candidate);
|
|
576
|
+
} catch (error) {
|
|
577
|
+
this.logger.warn?.('[pi-browser-agent] promotion listener failed', error);
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
/** Our promoted broker handed the bridge to a peer: go back to proxying. */
|
|
583
|
+
private onPromotedYielded(candidate: BrowserAgentBroker): void {
|
|
584
|
+
if (this.promotedBroker !== candidate) return;
|
|
585
|
+
this.unsubscribePromoted?.();
|
|
586
|
+
this.unsubscribePromoted = null;
|
|
587
|
+
this.promotedBroker = null;
|
|
588
|
+
void this.healInBackground('handed the browser bridge to another pi session');
|
|
410
589
|
}
|
|
411
590
|
|
|
412
591
|
private async sendControlRequest(kind: 'probe'): Promise<ResponseFrame> {
|
|
@@ -551,36 +730,15 @@ export class RemoteBrowserAgentBroker {
|
|
|
551
730
|
this.promotionPromise = (async () => {
|
|
552
731
|
// First try to become the new primary. If several remotes detect the
|
|
553
732
|
// 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
|
-
});
|
|
733
|
+
const candidate = this.createCandidate();
|
|
563
734
|
try {
|
|
564
735
|
await candidate.start();
|
|
565
736
|
if (this.stopped) {
|
|
566
737
|
await candidate.stop();
|
|
567
738
|
return null;
|
|
568
739
|
}
|
|
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();
|
|
740
|
+
this.adoptPromoted(candidate);
|
|
576
741
|
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
742
|
return candidate;
|
|
585
743
|
} catch (error) {
|
|
586
744
|
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,8 @@ export class BrowserAgentBroker {
|
|
|
619
654
|
url: this.url,
|
|
620
655
|
bridgeSessionSerial: this.bridgeSessionSerial,
|
|
621
656
|
supportsBrokerProxy: true,
|
|
657
|
+
brokerVersion: this.version,
|
|
658
|
+
hostedByCommand: this.hostedByCommand || undefined,
|
|
622
659
|
role: 'primary',
|
|
623
660
|
ownerPid: process.pid,
|
|
624
661
|
listeningSince: this.listeningSince ? new Date(this.listeningSince).toISOString() : undefined,
|
|
@@ -662,6 +699,61 @@ export class BrowserAgentBroker {
|
|
|
662
699
|
});
|
|
663
700
|
}
|
|
664
701
|
|
|
702
|
+
/**
|
|
703
|
+
* Cooperative handover of the Chrome bridge to the peer on `socket`.
|
|
704
|
+
*
|
|
705
|
+
* The listening PORT is released first while every connection (Chrome
|
|
706
|
+
* bridge, other proxies) stays open, so no other peer notices anything and
|
|
707
|
+
* only the taker races for the port. Once the taker confirms it is bound we
|
|
708
|
+
* close everything; Chrome and the other proxies then reconnect to it. If
|
|
709
|
+
* the taker never confirms, we still close and our own recovery (or a peer)
|
|
710
|
+
* rebinds the port.
|
|
711
|
+
*/
|
|
712
|
+
private async handleTakeover(socket: WebSocket, frame: TakeoverFrame): Promise<void> {
|
|
713
|
+
if (this.takeoverInFlight || !this.server) {
|
|
714
|
+
socket.send(JSON.stringify(createErrorResponseFrame(frame.id, 'E_BUSY', this.server ? 'Another takeover is already in progress' : 'This broker is not hosting')));
|
|
715
|
+
return;
|
|
716
|
+
}
|
|
717
|
+
this.takeoverInFlight = true;
|
|
718
|
+
this.yieldingUntil = Date.now() + TAKEOVER_WINDOW_MS;
|
|
719
|
+
this.logger.info?.('[pi-browser-agent] handing the browser bridge over', { toPid: frame.pid, toVersion: frame.version, reason: frame.reason });
|
|
720
|
+
let confirmed = false;
|
|
721
|
+
try {
|
|
722
|
+
const done = new Promise<boolean>((resolve) => {
|
|
723
|
+
const onClose = () => finish(false);
|
|
724
|
+
const timer = setTimeout(() => finish(false), TAKEOVER_CONFIRM_MS);
|
|
725
|
+
timer.unref?.();
|
|
726
|
+
const finish = (ok: boolean) => {
|
|
727
|
+
clearTimeout(timer);
|
|
728
|
+
socket.off('close', onClose);
|
|
729
|
+
this.takeoverConfirm = null;
|
|
730
|
+
resolve(ok);
|
|
731
|
+
};
|
|
732
|
+
socket.once('close', onClose);
|
|
733
|
+
this.takeoverConfirm = { socket, id: frame.id, finish };
|
|
734
|
+
});
|
|
735
|
+
const http = this.httpServer;
|
|
736
|
+
// close() stops listening at once; its callback would wait for every
|
|
737
|
+
// live connection, so it is deliberately not awaited.
|
|
738
|
+
try { http?.close(); } catch { /* already closed */ }
|
|
739
|
+
socket.send(JSON.stringify(createResponseFrame(frame.id, { released: true, pid: process.pid, version: this.version })));
|
|
740
|
+
confirmed = await done;
|
|
741
|
+
} catch (error) {
|
|
742
|
+
this.logger.warn?.('[pi-browser-agent] takeover handling failed', error);
|
|
743
|
+
} finally {
|
|
744
|
+
try { await this.stop(); } catch { /* best effort */ }
|
|
745
|
+
this.httpServer = null;
|
|
746
|
+
this.hostedByCommand = false;
|
|
747
|
+
if (!confirmed) this.yieldingUntil = 0;
|
|
748
|
+
this.takeoverInFlight = false;
|
|
749
|
+
}
|
|
750
|
+
if (confirmed) {
|
|
751
|
+
for (const listener of [...this.yieldListeners]) {
|
|
752
|
+
try { listener(); } catch (error) { this.logger.warn?.('[pi-browser-agent] yield listener failed', error); }
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
|
|
665
757
|
private rejectPendingRequests(error: Error): void {
|
|
666
758
|
for (const [id, pending] of this.pendingRequests.entries()) {
|
|
667
759
|
clearTimeout(pending.timeout);
|
|
@@ -714,6 +806,17 @@ export class BrowserAgentBroker {
|
|
|
714
806
|
return;
|
|
715
807
|
}
|
|
716
808
|
|
|
809
|
+
if (frame.kind === 'takeover') {
|
|
810
|
+
void this.handleTakeover(socket, frame as TakeoverFrame);
|
|
811
|
+
return;
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
if (frame.kind === 'takeover_done') {
|
|
815
|
+
const confirm = this.takeoverConfirm;
|
|
816
|
+
if (confirm && confirm.socket === socket && confirm.id === frame.id) confirm.finish(true);
|
|
817
|
+
return;
|
|
818
|
+
}
|
|
819
|
+
|
|
717
820
|
if (frame.kind === 'probe') {
|
|
718
821
|
const id = frame.id || randomUUID();
|
|
719
822
|
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 and
|
|
316
|
+
* 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 ?? 'unknown'})`
|
|
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,164 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import net from 'node:net';
|
|
4
|
+
import { mkdtemp } from 'node:fs/promises';
|
|
5
|
+
import { tmpdir } from 'node:os';
|
|
6
|
+
import { join } from 'node:path';
|
|
7
|
+
|
|
8
|
+
import WebSocket, { type RawData } from 'ws';
|
|
9
|
+
|
|
10
|
+
import { BrowserAgentBroker } from '../src/broker/server.ts';
|
|
11
|
+
import { RemoteBrowserAgentBroker } from '../src/broker/remote.ts';
|
|
12
|
+
import { TaskStore } from '../src/broker/task-store.ts';
|
|
13
|
+
import { compareVersions } from '../src/broker/version.ts';
|
|
14
|
+
|
|
15
|
+
const quiet = { info() {}, warn() {}, error() {} };
|
|
16
|
+
|
|
17
|
+
async function freePort(): Promise<number> {
|
|
18
|
+
return await new Promise((resolve, reject) => {
|
|
19
|
+
const server = net.createServer();
|
|
20
|
+
server.listen(0, '127.0.0.1', () => {
|
|
21
|
+
const address = server.address();
|
|
22
|
+
if (!address || typeof address === 'string') return reject(new Error('no port'));
|
|
23
|
+
server.close(() => resolve(address.port));
|
|
24
|
+
});
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async function store(): Promise<TaskStore> {
|
|
29
|
+
return new TaskStore({ dir: join(await mkdtemp(join(tmpdir(), 'takeover-')), 'tasks') });
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async function primary(port: number, version = '0.0.29'): Promise<BrowserAgentBroker> {
|
|
33
|
+
const broker = new BrowserAgentBroker({ host: '127.0.0.1', port, portRange: 1, fallbackToEphemeral: false, logger: quiet, taskStore: await store(), version });
|
|
34
|
+
await broker.start();
|
|
35
|
+
return broker;
|
|
36
|
+
}
|
|
37
|
+
|
|
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 });
|
|
40
|
+
await broker.start();
|
|
41
|
+
return broker;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** A fake Chrome extension: answers every request, reconnects when dropped. */
|
|
45
|
+
function fakeChrome(port: number, label: string) {
|
|
46
|
+
const state = { connected: false, connections: 0, stopped: false, socket: null as WebSocket | null };
|
|
47
|
+
const connect = () => {
|
|
48
|
+
if (state.stopped) return;
|
|
49
|
+
const socket = new WebSocket(`ws://127.0.0.1:${port}`);
|
|
50
|
+
state.socket = socket;
|
|
51
|
+
socket.on('open', () => socket.send(JSON.stringify({ v: 1, kind: 'hello', extensionId: label, version: '1', capabilities: ['x'] })));
|
|
52
|
+
socket.on('message', (data: RawData) => {
|
|
53
|
+
const frame = JSON.parse(String(data));
|
|
54
|
+
if (frame.kind === 'welcome') { state.connected = true; state.connections += 1; }
|
|
55
|
+
if (frame.kind === 'request') socket.send(JSON.stringify({ v: 1, kind: 'response', id: frame.id, ok: true, data: { servedBy: label } }));
|
|
56
|
+
});
|
|
57
|
+
socket.on('close', () => { state.connected = false; setTimeout(connect, 50); });
|
|
58
|
+
socket.on('error', () => {});
|
|
59
|
+
};
|
|
60
|
+
connect();
|
|
61
|
+
return { state, stop: () => { state.stopped = true; state.socket?.close(); } };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function waitFor(condition: () => boolean, timeoutMs = 5_000): Promise<void> {
|
|
65
|
+
const deadline = Date.now() + timeoutMs;
|
|
66
|
+
while (!condition()) {
|
|
67
|
+
if (Date.now() > deadline) throw new Error('condition not met in time');
|
|
68
|
+
await new Promise((resolve) => setTimeout(resolve, 20));
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
test('versions compare numerically and missing versions count as oldest', () => {
|
|
73
|
+
assert.equal(compareVersions('0.0.29', '0.0.28'), 1);
|
|
74
|
+
assert.equal(compareVersions('0.0.10', '0.0.9'), 1);
|
|
75
|
+
assert.equal(compareVersions('0.0.29', undefined), 1);
|
|
76
|
+
assert.equal(compareVersions('0.0.29', '0.0.29'), 0);
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
test('cooperative takeover: the taker hosts, Chrome and other proxies follow it', { timeout: 20_000 }, async () => {
|
|
80
|
+
const port = await freePort();
|
|
81
|
+
const host = await primary(port);
|
|
82
|
+
const chrome = fakeChrome(port, 'chrome');
|
|
83
|
+
await waitFor(() => host.probeConnectivity().bridgeConnected);
|
|
84
|
+
const bystander = await remote(port);
|
|
85
|
+
const taker = await remote(port);
|
|
86
|
+
|
|
87
|
+
const result = await taker.takeover({ reason: 'command' });
|
|
88
|
+
assert.equal(result.mode, 'cooperative');
|
|
89
|
+
assert.equal(taker.probeConnectivity().role, 'promoted');
|
|
90
|
+
assert.equal(taker.probeConnectivity().hostedByCommand, true);
|
|
91
|
+
assert.equal(host.probeConnectivity().brokerListening, false);
|
|
92
|
+
|
|
93
|
+
// Chrome reconnects to the new host and requests flow through it.
|
|
94
|
+
await waitFor(() => chrome.state.connections >= 2 && taker.probeConnectivity().bridgeConnected);
|
|
95
|
+
const viaTaker = await taker.request('x', {}, { timeoutMs: 2_000 });
|
|
96
|
+
assert.deepEqual(viaTaker.data, { servedBy: 'chrome' });
|
|
97
|
+
// The old host's own recovery cannot steal the port back.
|
|
98
|
+
await host.ensureReady({ waitForBridgeMs: 0 });
|
|
99
|
+
assert.equal(host.probeConnectivity().brokerListening, false);
|
|
100
|
+
// A bystander proxy heals onto the new host.
|
|
101
|
+
await bystander.ensureReady({ waitForBridgeMs: 3_000 });
|
|
102
|
+
const viaBystander = await bystander.request('x', {}, { timeoutMs: 2_000 });
|
|
103
|
+
assert.deepEqual(viaBystander.data, { servedBy: 'chrome' });
|
|
104
|
+
|
|
105
|
+
chrome.stop();
|
|
106
|
+
await bystander.stop();
|
|
107
|
+
await taker.stop();
|
|
108
|
+
await host.stop();
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
test('a promoted host that is taken over goes back to proxying', { timeout: 20_000 }, async () => {
|
|
112
|
+
const port = await freePort();
|
|
113
|
+
const host = await primary(port);
|
|
114
|
+
const chrome = fakeChrome(port, 'chrome');
|
|
115
|
+
await waitFor(() => host.probeConnectivity().bridgeConnected);
|
|
116
|
+
const first = await remote(port);
|
|
117
|
+
const second = await remote(port);
|
|
118
|
+
|
|
119
|
+
assert.equal((await first.takeover()).mode, 'cooperative');
|
|
120
|
+
await waitFor(() => first.probeConnectivity().bridgeConnected);
|
|
121
|
+
assert.equal((await second.takeover()).mode, 'cooperative');
|
|
122
|
+
await waitFor(() => second.probeConnectivity().bridgeConnected);
|
|
123
|
+
await waitFor(() => first.probeConnectivity().role === 'proxy' && first.probeConnectivity().bridgeConnected);
|
|
124
|
+
const response = await first.request('x', {}, { timeoutMs: 2_000 });
|
|
125
|
+
assert.deepEqual(response.data, { servedBy: 'chrome' });
|
|
126
|
+
|
|
127
|
+
chrome.stop();
|
|
128
|
+
await first.stop();
|
|
129
|
+
await second.stop();
|
|
130
|
+
await host.stop();
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
test('newest code wins: a newer proxy takes the bridge over automatically', { timeout: 20_000 }, async () => {
|
|
134
|
+
const port = await freePort();
|
|
135
|
+
const host = await primary(port, '0.0.28');
|
|
136
|
+
const chrome = fakeChrome(port, 'chrome');
|
|
137
|
+
await waitFor(() => host.probeConnectivity().bridgeConnected);
|
|
138
|
+
const older = await remote(port, '0.0.27', { autoTakeover: true });
|
|
139
|
+
const same = await remote(port, '0.0.28', { autoTakeover: true });
|
|
140
|
+
const newer = await remote(port, '0.0.29', { autoTakeover: true });
|
|
141
|
+
|
|
142
|
+
await waitFor(() => newer.probeConnectivity().role === 'promoted' && newer.probeConnectivity().bridgeConnected, 8_000);
|
|
143
|
+
assert.equal(newer.probeConnectivity().hostedByCommand, undefined);
|
|
144
|
+
for (const proxy of [older, same]) {
|
|
145
|
+
await proxy.ensureReady({ waitForBridgeMs: 3_000 });
|
|
146
|
+
assert.equal(proxy.probeConnectivity().role, 'proxy');
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
chrome.stop();
|
|
150
|
+
for (const broker of [older, same, newer]) await broker.stop();
|
|
151
|
+
await host.stop();
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
test('a host chosen with /browser:takeover is not taken over automatically', { timeout: 20_000 }, async () => {
|
|
155
|
+
const port = await freePort();
|
|
156
|
+
const host = await primary(port, '0.0.28');
|
|
157
|
+
host.markHostedByCommand();
|
|
158
|
+
const newer = await remote(port, '0.0.29', { autoTakeover: true });
|
|
159
|
+
await new Promise((resolve) => setTimeout(resolve, 500));
|
|
160
|
+
assert.equal(newer.probeConnectivity().role, 'proxy');
|
|
161
|
+
assert.equal(host.probeConnectivity().brokerListening, true);
|
|
162
|
+
await newer.stop();
|
|
163
|
+
await host.stop();
|
|
164
|
+
});
|