oira666_pi-browser-agent 0.0.13 → 0.0.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,28 +1,28 @@
1
- {
2
- "name": "oira666_pi-browser-agent",
3
- "version": "0.0.13",
4
- "private": false,
5
- "type": "module",
6
- "description": "Pi browser agent broker skeleton with lazy browser tool registration",
7
- "repository": {
8
- "type": "git",
9
- "url": "git+https://github.com/gee666/pi-browser-agent.git"
10
- },
11
- "pi": {
12
- "extensions": [
13
- "./src/index.ts"
14
- ]
15
- },
16
- "scripts": {
17
- "test": "node --test ./tests/*.test.ts ./tests/tools/*.test.ts"
18
- },
19
- "dependencies": {
20
- "@sinclair/typebox": "^0.34.41",
21
- "ws": "^8.18.3"
22
- },
23
- "devDependencies": {
24
- "@types/node": "^25.6.0",
25
- "@types/ws": "^8.18.1",
26
- "typescript": "^5.9.3"
27
- }
28
- }
1
+ {
2
+ "name": "oira666_pi-browser-agent",
3
+ "version": "0.0.14",
4
+ "private": false,
5
+ "type": "module",
6
+ "description": "Pi browser agent broker skeleton with lazy browser tool registration",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/gee666/pi-browser-agent.git"
10
+ },
11
+ "pi": {
12
+ "extensions": [
13
+ "./src/index.ts"
14
+ ]
15
+ },
16
+ "scripts": {
17
+ "test": "node --test ./tests/*.test.ts ./tests/tools/*.test.ts"
18
+ },
19
+ "dependencies": {
20
+ "@sinclair/typebox": "^0.34.41",
21
+ "ws": "^8.18.3"
22
+ },
23
+ "devDependencies": {
24
+ "@types/node": "^25.6.0",
25
+ "@types/ws": "^8.18.1",
26
+ "typescript": "^5.9.3"
27
+ }
28
+ }
@@ -0,0 +1,161 @@
1
+ import type { ProbeResult } from './protocol.ts';
2
+
3
+ /**
4
+ * Human + agent readable diagnostics for a down browser bridge.
5
+ *
6
+ * Design goal: when a browser_* tool has to fail with E_BRIDGE_DISCONNECTED,
7
+ * the agent must receive (a) exactly WHICH link of the chain is broken,
8
+ * (b) an ordered list of recovery actions it can perform ITSELF with tools it
9
+ * already has, and (c) an explicit instruction to tell the user what happened.
10
+ * Never return a bare "connection is down".
11
+ */
12
+
13
+ export type BridgeFailureKind =
14
+ | 'ok'
15
+ | 'broker_not_listening'
16
+ | 'broker_unreachable'
17
+ | 'bridge_never_connected'
18
+ | 'bridge_lost';
19
+
20
+ export interface BridgeDiagnostics {
21
+ kind: BridgeFailureKind;
22
+ /** One-line summary of the broken link. */
23
+ reason: string;
24
+ /** Ordered, agent-executable recovery steps. */
25
+ remediation: Array<{ step: number; action: string; how: string; automatic?: boolean }>;
26
+ /** What the agent must relay to the human. */
27
+ userMessage: string;
28
+ probe: ProbeResult;
29
+ }
30
+
31
+ const DEFAULT_URL = 'ws://127.0.0.1:7878';
32
+
33
+ function listenerCheckCommand(url: string): string {
34
+ const port = /:(\d+)/.exec(url || DEFAULT_URL)?.[1] ?? '7878';
35
+ if (process.platform === 'win32') {
36
+ return `netstat -ano | findstr :${port}`;
37
+ }
38
+ if (process.platform === 'darwin') {
39
+ return `lsof -nP -iTCP:${port} -sTCP:LISTEN`;
40
+ }
41
+ return `ss -ltnp | grep :${port} || lsof -nP -iTCP:${port} -sTCP:LISTEN`;
42
+ }
43
+
44
+ function chromeCheckCommand(): string {
45
+ if (process.platform === 'win32') {
46
+ return 'powershell -Command "Get-Process chrome -ErrorAction SilentlyContinue | Select-Object -First 1 Id,StartTime"';
47
+ }
48
+ return 'pgrep -a -f "Google Chrome|chrome" | head -5';
49
+ }
50
+
51
+ export function classifyBridgeFailure(probe: ProbeResult): BridgeFailureKind {
52
+ if (!probe.brokerReachable) return 'broker_unreachable';
53
+ if (!probe.brokerListening) return 'broker_not_listening';
54
+ if (probe.bridgeConnected) return 'ok';
55
+ return probe.bridgeEverConnected ? 'bridge_lost' : 'bridge_never_connected';
56
+ }
57
+
58
+ function describeState(probe: ProbeResult): string {
59
+ const bits: string[] = [];
60
+ bits.push(`broker=${probe.brokerListening ? `listening ${probe.url || DEFAULT_URL}` : 'not listening'}`);
61
+ bits.push(`role=${probe.role || 'unknown'}`);
62
+ bits.push(`bridge=${probe.bridgeConnected ? 'connected' : 'disconnected'}`);
63
+ if (probe.bridgeVersion) bits.push(`bridgeVersion=${probe.bridgeVersion}`);
64
+ if (probe.lastBridgeConnectedAt) bits.push(`lastConnected=${probe.lastBridgeConnectedAt}`);
65
+ if (probe.lastBridgeDisconnectedAt) bits.push(`lastDisconnected=${probe.lastBridgeDisconnectedAt}`);
66
+ if (probe.lastBridgeDisconnectReason) bits.push(`lastReason=${probe.lastBridgeDisconnectReason}`);
67
+ if (probe.startupError) bits.push(`startupError=${probe.startupError}`);
68
+ return bits.join(', ');
69
+ }
70
+
71
+ export function buildBridgeDiagnostics(probe: ProbeResult, options: { toolName?: string } = {}): BridgeDiagnostics {
72
+ const kind = classifyBridgeFailure(probe);
73
+ const url = probe.url || DEFAULT_URL;
74
+ const tool = options.toolName || 'the browser tool';
75
+
76
+ const reason = kind === 'broker_unreachable'
77
+ ? `The pi-browser-agent broker in this process could not be reached (${probe.startupError || 'unknown startup error'}).`
78
+ : kind === 'broker_not_listening'
79
+ ? `No pi-browser-agent broker is listening on ${url}${probe.startupError ? ` (${probe.startupError})` : ''}.`
80
+ : kind === 'bridge_never_connected'
81
+ ? `The broker is listening on ${url}, but the Chrome extension bridge has never connected in this session — Chrome is closed, the extension is disabled/unloaded, or its bridge URL list does not include ${url}.`
82
+ : `The broker is listening on ${url}, but the Chrome extension bridge dropped and has not come back${probe.lastBridgeDisconnectReason ? ` (last reason: ${probe.lastBridgeDisconnectReason})` : ''}.`;
83
+
84
+ const remediation: BridgeDiagnostics['remediation'] = [];
85
+ let step = 1;
86
+ const add = (action: string, how: string, automatic = false) => {
87
+ remediation.push({ step: step++, action, how, automatic });
88
+ };
89
+
90
+ add(
91
+ 'Already attempted automatically: lazy re-acquire + reconnect wait',
92
+ 'Every browser_* call re-binds/re-dials the broker and then waits for the extension to reconnect before failing. This error means that window elapsed.',
93
+ true,
94
+ );
95
+ add(
96
+ 'Re-probe and force another lazy re-establish',
97
+ 'Call activate_browser_agent_tools. It re-acquires the broker port (promoting this process to primary if the old primary died) and re-reads live bridge state.',
98
+ );
99
+ add(
100
+ `Retry ${tool} once after ~5 seconds`,
101
+ 'The Chrome extension reconnect backoff is capped at 5s, with a 30s chrome.alarms backstop. A single retry recovers most transient drops.',
102
+ );
103
+ if (kind === 'broker_not_listening' || kind === 'broker_unreachable') {
104
+ add(
105
+ 'Verify which process owns the broker port',
106
+ `Run: ${listenerCheckCommand(url)} — expect a LISTENING pi/node process. If a foreign process squats the port, set PI_BA_PORT to a free port in both pi and the extension options.`,
107
+ );
108
+ } else {
109
+ add(
110
+ 'Verify Chrome is actually running',
111
+ `Run: ${chromeCheckCommand()} — if there is no Chrome process, the bridge cannot exist. Ask the user to start Chrome.`,
112
+ );
113
+ add(
114
+ 'Confirm the socket at the OS level',
115
+ `Run: ${listenerCheckCommand(url)} — a healthy bridge shows the LISTENING socket plus one ESTABLISHED connection owned by chrome.exe/Chrome.`,
116
+ );
117
+ }
118
+ add(
119
+ 'Reload the extension service worker (only once the bridge is briefly back)',
120
+ 'browser_reload_extension restarts the extension worker and re-handshakes. It travels over the bridge itself, so it only helps after step 2/3 restored a connection.',
121
+ );
122
+ add(
123
+ 'Escalate to the user (do this — do not fail silently)',
124
+ 'Report the state summary below and ask them to open chrome://extensions, reload "Browser Agent", and check the extension options page: pi bridge enabled and the broker URL list includes ' + url + '.',
125
+ );
126
+
127
+ const userMessage = [
128
+ `Browser automation is unavailable: ${reason}`,
129
+ '',
130
+ `State: ${describeState(probe)}`,
131
+ '',
132
+ 'What you can do:',
133
+ ' 1. Open chrome://extensions and click the reload icon on "Browser Agent".',
134
+ ` 2. Open the extension options page and confirm the pi bridge is enabled and its broker URL list contains ${url}.`,
135
+ ' 3. If Chrome is not running, start it — the bridge lives inside the extension.',
136
+ ].join('\n');
137
+
138
+ return { kind, reason, remediation, userMessage, probe };
139
+ }
140
+
141
+ export function formatBridgeDiagnosticsText(diagnostics: BridgeDiagnostics): string {
142
+ const lines: string[] = [
143
+ `E_BRIDGE_DISCONNECTED — ${diagnostics.reason}`,
144
+ '',
145
+ `State: ${describeState(diagnostics.probe)}`,
146
+ '',
147
+ 'Self-service recovery (do these yourself, in order):',
148
+ ];
149
+ for (const item of diagnostics.remediation) {
150
+ lines.push(` ${item.step}. ${item.action}${item.automatic ? ' [already done]' : ''}`);
151
+ lines.push(` ${item.how}`);
152
+ }
153
+ lines.push('', 'Then TELL THE USER what happened, in your own words:', ...diagnostics.userMessage.split('\n').map((line) => ` ${line}`));
154
+ return lines.join('\n');
155
+ }
156
+
157
+ /** Convenience: build the full agent-facing text straight from a probe. */
158
+ export function formatBridgeFailure(probe: ProbeResult, toolName?: string): { text: string; diagnostics: BridgeDiagnostics } {
159
+ const diagnostics = buildBridgeDiagnostics(probe, { toolName });
160
+ return { text: formatBridgeDiagnosticsText(diagnostics), diagnostics };
161
+ }
@@ -0,0 +1,152 @@
1
+ import type { ProbeResult, ResponseFrame } from './protocol.ts';
2
+ import type { EnsureReadyOptions } from './server.ts';
3
+ import type { TaskStore } from './task-store.ts';
4
+
5
+ /** The slice of the broker API that the browser_* tools actually consume. */
6
+ export interface BrokerLike {
7
+ ensureReady?: (options?: EnsureReadyOptions) => Promise<void>;
8
+ probeConnectivity: () => ProbeResult;
9
+ request: (type: string, params: unknown, options?: { timeoutMs?: number }) => Promise<ResponseFrame>;
10
+ taskStore: TaskStore;
11
+ }
12
+
13
+ /**
14
+ * A broker handle that resolves its real backing broker lazily, on every call.
15
+ *
16
+ * Why this exists: pi reads the tool registry once at session_start, and any
17
+ * registerTool() after that is dropped. Previously the browser_* suite was only
18
+ * registered when the broker happened to be listening at session_start, so a pi
19
+ * instance started while the browser stack was down had NO browser tools for its
20
+ * entire lifetime — unrecoverable without restarting pi. And a session whose
21
+ * broker later died held a dead object forever.
22
+ *
23
+ * With this handle the tools are always registered and always re-resolve the
24
+ * broker at call time, so the integration heals itself whenever the browser
25
+ * comes back — no restart, no manual step.
26
+ */
27
+ export class LazyBrokerHandle implements BrokerLike {
28
+ private current: BrokerLike | null = null;
29
+ private lastError: string | undefined;
30
+ private resolving: Promise<BrokerLike | null> | null = null;
31
+ private disposed = false;
32
+ /** Last bridge session serial we actually observed. Reporting 0 while
33
+ * unresolved made browser_reload_extension's "serial must increase" wait
34
+ * never succeed, because the serial appeared to go N -> 0. */
35
+ private lastSeenBridgeSessionSerial = 0;
36
+
37
+ readonly taskStore: TaskStore;
38
+ private readonly resolveBroker: () => Promise<BrokerLike>;
39
+ private readonly url: string;
40
+
41
+ constructor(resolveBroker: () => Promise<BrokerLike>, taskStore: TaskStore, url?: string) {
42
+ this.resolveBroker = resolveBroker;
43
+ this.taskStore = taskStore;
44
+ this.url = url ?? `ws://${process.env.PI_BA_HOST || '127.0.0.1'}:${process.env.PI_BA_PORT || 7878}`;
45
+ }
46
+
47
+ /** Attach an already-resolved broker (the happy path at session_start). */
48
+ adopt(broker: BrokerLike): void {
49
+ if (this.disposed) return;
50
+ this.current = broker;
51
+ this.lastError = undefined;
52
+ }
53
+
54
+ /** Detach permanently. Tools captured this handle for the whole session, so
55
+ * without this a late tool call would happily re-start() the broker the
56
+ * session shutdown had just stopped — re-binding the port with nothing left
57
+ * to track or close it. */
58
+ dispose(): void {
59
+ this.disposed = true;
60
+ this.current = null;
61
+ this.resolving = null;
62
+ this.lastError = 'browser broker was shut down with this pi session';
63
+ }
64
+
65
+ get resolved(): BrokerLike | null {
66
+ return this.current;
67
+ }
68
+
69
+ private async resolve(): Promise<BrokerLike | null> {
70
+ if (this.disposed) return null;
71
+ if (this.current) return this.current;
72
+ if (this.resolving) return await this.resolving;
73
+
74
+ this.resolving = (async () => {
75
+ try {
76
+ const broker = await this.resolveBroker();
77
+ this.current = broker;
78
+ this.lastError = undefined;
79
+ return broker;
80
+ } catch (error) {
81
+ this.lastError = error instanceof Error ? error.message : String(error);
82
+ return null;
83
+ } finally {
84
+ this.resolving = null;
85
+ }
86
+ })();
87
+
88
+ return await this.resolving;
89
+ }
90
+
91
+ async ensureReady(options: EnsureReadyOptions = {}): Promise<void> {
92
+ if (this.disposed) return;
93
+ const broker = await this.resolve();
94
+ if (!broker) return;
95
+ try {
96
+ await broker.ensureReady?.(options);
97
+ } catch (error) {
98
+ this.lastError = error instanceof Error ? error.message : String(error);
99
+ }
100
+ // Only drop a broker that is structurally wrong for the current topology: a
101
+ // primary that cannot hold the port. Proxies and promoted brokers report
102
+ // brokerListening=false during every ordinary reconnect blip, and dropping
103
+ // them there orphaned a broker that kept its heal loop running and could
104
+ // still bind the port — two competing brokers in one process.
105
+ const probe = this.observe(broker.probeConnectivity());
106
+ if (probe.role === 'primary' && !probe.brokerListening) {
107
+ this.current = null;
108
+ }
109
+ }
110
+
111
+ probeConnectivity(): ProbeResult {
112
+ if (this.disposed) {
113
+ return {
114
+ brokerReachable: false,
115
+ brokerListening: false,
116
+ bridgeConnected: false,
117
+ startupError: 'browser broker was shut down with this pi session',
118
+ url: this.url,
119
+ bridgeSessionSerial: this.lastSeenBridgeSessionSerial,
120
+ };
121
+ }
122
+ if (this.current) {
123
+ return this.observe(this.current.probeConnectivity());
124
+ }
125
+ return {
126
+ brokerReachable: false,
127
+ brokerListening: false,
128
+ bridgeConnected: false,
129
+ startupError: this.lastError ?? 'browser broker has not been acquired in this process yet',
130
+ url: this.url,
131
+ bridgeSessionSerial: this.lastSeenBridgeSessionSerial,
132
+ };
133
+ }
134
+
135
+ private observe(probe: ProbeResult): ProbeResult {
136
+ if (typeof probe.bridgeSessionSerial === 'number') {
137
+ this.lastSeenBridgeSessionSerial = probe.bridgeSessionSerial;
138
+ }
139
+ return probe;
140
+ }
141
+
142
+ async request(type: string, params: unknown, options: { timeoutMs?: number } = {}): Promise<ResponseFrame> {
143
+ if (this.disposed) {
144
+ throw new Error('E_BRIDGE_DISCONNECTED');
145
+ }
146
+ const broker = await this.resolve();
147
+ if (!broker) {
148
+ throw new Error('E_BRIDGE_DISCONNECTED');
149
+ }
150
+ return await broker.request(type, params, options);
151
+ }
152
+ }
@@ -48,11 +48,22 @@ export const ResponseFrameSchema = Type.Object({
48
48
  error: Type.Optional(ErrorFrameSchema),
49
49
  });
50
50
 
51
+ /** Unsolicited server -> peer push. Used by the primary broker to tell peer pi
52
+ * processes that the Chrome bridge came or went, so a secondary session does
53
+ * not have to poll (and does not silently show a stale "connected" state). */
54
+ export const NotifyFrameSchema = Type.Object({
55
+ v: Type.Literal(PROTOCOL_VERSION),
56
+ kind: Type.Literal('notify'),
57
+ event: Type.String(),
58
+ payload: Type.Optional(Type.Unknown()),
59
+ });
60
+
51
61
  export const AnyIncomingFrameSchema = Type.Union([
52
62
  HelloFrameSchema,
53
63
  ProbeFrameSchema,
54
64
  RequestFrameSchema,
55
65
  ResponseFrameSchema,
66
+ NotifyFrameSchema,
56
67
  ]);
57
68
 
58
69
  export type HelloFrame = Static<typeof HelloFrameSchema>;
@@ -60,6 +71,7 @@ export type WelcomeFrame = Static<typeof WelcomeFrameSchema>;
60
71
  export type ProbeFrame = Static<typeof ProbeFrameSchema>;
61
72
  export type RequestFrame = Static<typeof RequestFrameSchema>;
62
73
  export type ResponseFrame = Static<typeof ResponseFrameSchema>;
74
+ export type NotifyFrame = Static<typeof NotifyFrameSchema>;
63
75
  export type IncomingFrame = Static<typeof AnyIncomingFrameSchema>;
64
76
 
65
77
  export interface ProbeResult {
@@ -72,6 +84,23 @@ export interface ProbeResult {
72
84
  url?: string;
73
85
  bridgeSessionSerial?: number;
74
86
  supportsBrokerProxy?: boolean;
87
+ /** Role of the broker object that produced this probe. Useful when telling a
88
+ * user/agent whether this pi process owns the Chrome bridge itself or
89
+ * proxies through another pi process. */
90
+ role?: 'primary' | 'promoted' | 'proxy';
91
+ /** PID of the process that owns the listener, when known. */
92
+ ownerPid?: number;
93
+ /** ISO timestamp of when the listener started accepting connections. */
94
+ listeningSince?: string;
95
+ /** True if a Chrome extension bridge has connected at least once to this
96
+ * listener. Distinguishes "Chrome never showed up" from "we lost it". */
97
+ bridgeEverConnected?: boolean;
98
+ /** ISO timestamp of the most recent successful bridge handshake. */
99
+ lastBridgeConnectedAt?: string;
100
+ /** ISO timestamp of the most recent bridge loss. */
101
+ lastBridgeDisconnectedAt?: string;
102
+ /** Why the bridge was last dropped (heartbeat timeout, socket close, ...). */
103
+ lastBridgeDisconnectReason?: string;
75
104
  }
76
105
 
77
106
  export function parseIncomingFrame(raw: string): IncomingFrame {
@@ -117,6 +146,15 @@ export function createResponseFrame(id: string, data: unknown): ResponseFrame {
117
146
  };
118
147
  }
119
148
 
149
+ export function createNotifyFrame(event: string, payload?: unknown): NotifyFrame {
150
+ return {
151
+ v: PROTOCOL_VERSION,
152
+ kind: 'notify',
153
+ event,
154
+ payload,
155
+ };
156
+ }
157
+
120
158
  export function createErrorResponseFrame(id: string, code: string, message: string, details?: unknown): ResponseFrame {
121
159
  return {
122
160
  v: PROTOCOL_VERSION,