oira666_pi-browser-agent 0.0.17 → 0.0.19
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 +5 -1
- package/package.json +1 -1
- package/src/broker/abort.ts +107 -0
- package/src/broker/health-reporter.ts +59 -0
- package/src/broker/lazy.ts +3 -2
- package/src/broker/remote.ts +68 -21
- package/src/broker/server.ts +50 -14
- package/src/index.ts +58 -95
- package/src/tools/browser_agent_tools.ts +11 -2
- package/src/tools/browser_js_navigation_tools.ts +52 -12
- package/src/tools/browser_observability_tools.ts +18 -4
- package/src/tools/browser_task_tools.ts +37 -14
- package/src/tools/read_only/common.ts +19 -4
- package/src/tools/read_only/index.ts +14 -6
- package/tests/abort.test.ts +243 -0
- package/tests/broker.test.ts +59 -1
- package/tests/health-reporter.test.ts +76 -0
- package/tests/index.test.ts +65 -7
package/README.md
CHANGED
|
@@ -78,7 +78,11 @@ Environment variables:
|
|
|
78
78
|
- `PI_BA_PORT` — broker port, default `7878`
|
|
79
79
|
- `PI_BA_TASK_TTL_DAYS` — task-history retention
|
|
80
80
|
|
|
81
|
-
If port `7878
|
|
81
|
+
If another pi instance owns port `7878`, this session connects through it. If acquisition fails, the extension retries in the background.
|
|
82
|
+
|
|
83
|
+
## Connection status
|
|
84
|
+
|
|
85
|
+
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.
|
|
82
86
|
|
|
83
87
|
## WSL → Windows Chrome
|
|
84
88
|
|
package/package.json
CHANGED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cooperative cancellation for broker requests.
|
|
3
|
+
*
|
|
4
|
+
* pi hands every tool an `AbortSignal` (see `execute(toolCallId, params,
|
|
5
|
+
* signal, ...)` in pi's extension API) and fires it when the user presses
|
|
6
|
+
* Escape. Before this module nothing in this package listened to that signal,
|
|
7
|
+
* so an aborted call stayed pending inside `broker.request()` until its own
|
|
8
|
+
* timeout expired — up to 15s for browser_evaluate_js, 30s for browser_run_js
|
|
9
|
+
* and longer for navigation waits. Escape looked like it did nothing.
|
|
10
|
+
*
|
|
11
|
+
* Everything here is host-side only: it releases pi immediately and drops the
|
|
12
|
+
* pending request entry. Work already started inside the page keeps running
|
|
13
|
+
* until the bridge grows a real cancel frame.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
export const ABORT_ERROR_CODE = 'E_ABORTED';
|
|
17
|
+
|
|
18
|
+
export interface AbortableOptions {
|
|
19
|
+
/** Fired by pi when the user cancels the tool call (Escape). */
|
|
20
|
+
signal?: AbortSignal;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface BrokerRequestOptions extends AbortableOptions {
|
|
24
|
+
timeoutMs?: number;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Error surfaced to callers when a request is cancelled. Carries the same
|
|
28
|
+
* `code`/`message` shape the tool layer already uses for protocol errors. */
|
|
29
|
+
export class BrokerAbortError extends Error {
|
|
30
|
+
readonly code = ABORT_ERROR_CODE;
|
|
31
|
+
readonly details?: unknown;
|
|
32
|
+
|
|
33
|
+
constructor(message = 'Request cancelled', details?: unknown) {
|
|
34
|
+
super(message);
|
|
35
|
+
this.name = 'BrokerAbortError';
|
|
36
|
+
this.details = details;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** True for our own abort error and for the DOMException `AbortError` that
|
|
41
|
+
* `AbortSignal.throwIfAborted()` / stdlib APIs raise. */
|
|
42
|
+
export function isAbortError(error: unknown): boolean {
|
|
43
|
+
if (!error || typeof error !== 'object') return false;
|
|
44
|
+
const candidate = error as { code?: unknown; name?: unknown };
|
|
45
|
+
return candidate.code === ABORT_ERROR_CODE || candidate.name === 'AbortError';
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function describeReason(signal: AbortSignal | undefined): string | undefined {
|
|
49
|
+
const reason = signal?.reason as unknown;
|
|
50
|
+
if (reason === undefined || reason === null) return undefined;
|
|
51
|
+
if (typeof reason === 'string') return reason;
|
|
52
|
+
if (reason instanceof Error) return reason.message;
|
|
53
|
+
return undefined;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function abortError(context: string, signal?: AbortSignal): BrokerAbortError {
|
|
57
|
+
const reason = describeReason(signal);
|
|
58
|
+
return new BrokerAbortError(
|
|
59
|
+
reason ? `${context} was cancelled: ${reason}` : `${context} was cancelled`,
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Reject immediately when the caller is already gone, so we never open a
|
|
64
|
+
* socket request for a tool call pi has stopped waiting for. */
|
|
65
|
+
export function throwIfAborted(signal: AbortSignal | undefined, context: string): void {
|
|
66
|
+
if (signal?.aborted) {
|
|
67
|
+
throw abortError(context, signal);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Attach an abort listener and return a disposer. Always call the disposer once
|
|
73
|
+
* the awaited work settles: a listener left on a long-lived session signal
|
|
74
|
+
* keeps the closure (and its promise) alive for the rest of the session.
|
|
75
|
+
*/
|
|
76
|
+
export function onAbort(signal: AbortSignal | undefined, listener: () => void): () => void {
|
|
77
|
+
if (!signal) return () => {};
|
|
78
|
+
if (signal.aborted) {
|
|
79
|
+
listener();
|
|
80
|
+
return () => {};
|
|
81
|
+
}
|
|
82
|
+
signal.addEventListener('abort', listener, { once: true });
|
|
83
|
+
return () => signal.removeEventListener('abort', listener);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Sleep that wakes early on abort. Returns `false` when it was cut short, so
|
|
88
|
+
* polling loops can exit instead of burning their full budget after Escape.
|
|
89
|
+
*/
|
|
90
|
+
export async function sleepUnlessAborted(ms: number, signal?: AbortSignal): Promise<boolean> {
|
|
91
|
+
if (signal?.aborted) return false;
|
|
92
|
+
if (ms <= 0) return !signal?.aborted;
|
|
93
|
+
|
|
94
|
+
return await new Promise<boolean>((resolve) => {
|
|
95
|
+
let settled = false;
|
|
96
|
+
const finish = (completed: boolean) => {
|
|
97
|
+
if (settled) return;
|
|
98
|
+
settled = true;
|
|
99
|
+
clearTimeout(timer);
|
|
100
|
+
release();
|
|
101
|
+
resolve(completed);
|
|
102
|
+
};
|
|
103
|
+
const timer = setTimeout(() => finish(true), ms);
|
|
104
|
+
timer.unref?.();
|
|
105
|
+
const release = onAbort(signal, () => finish(false));
|
|
106
|
+
});
|
|
107
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import type { BrokerLogger } from './server.ts';
|
|
2
|
+
|
|
3
|
+
export type BrowserHealthUi = {
|
|
4
|
+
notify?: (message: string, type?: 'info' | 'warning' | 'error') => void;
|
|
5
|
+
setStatus?: (key: string, text: string | undefined) => void;
|
|
6
|
+
};
|
|
7
|
+
|
|
8
|
+
// Broker logs describe individual attempts, not the outcome of recovery. Never
|
|
9
|
+
// forward them (or Error objects) into pi's notifications or runtime console.
|
|
10
|
+
export const quietBrokerLogger: BrokerLogger = { info() {}, warn() {}, error() {} };
|
|
11
|
+
export const RECOVERY_GRACE_MS = 60_000;
|
|
12
|
+
|
|
13
|
+
/** One reporter per session, retained across broker replacements. */
|
|
14
|
+
export class BrowserHealthReporter {
|
|
15
|
+
private disconnectedSince: number | null = null;
|
|
16
|
+
private warned = false;
|
|
17
|
+
private status: string | undefined;
|
|
18
|
+
private disposed = false;
|
|
19
|
+
|
|
20
|
+
private readonly ui?: BrowserHealthUi;
|
|
21
|
+
|
|
22
|
+
constructor(ui?: BrowserHealthUi) {
|
|
23
|
+
this.ui = ui;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
observe(connected: boolean, now = Date.now()): void {
|
|
27
|
+
if (this.disposed) return;
|
|
28
|
+
if (connected) {
|
|
29
|
+
this.disconnectedSince = null;
|
|
30
|
+
this.warned = false;
|
|
31
|
+
this.setStatus('browser: connected');
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
this.disconnectedSince ??= now;
|
|
35
|
+
const expired = now - this.disconnectedSince >= RECOVERY_GRACE_MS;
|
|
36
|
+
this.setStatus(expired ? 'browser: disconnected' : 'browser: recovering');
|
|
37
|
+
if (expired && !this.warned) {
|
|
38
|
+
this.warned = true;
|
|
39
|
+
this.ui?.notify?.('Browser unavailable. Check Chrome and the Browser Agent extension; retrying quietly.', 'warning');
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Time spent suspended is not a failed recovery attempt. Keep the warning
|
|
44
|
+
* latch, but give an unfinished recovery a fresh grace period on resume. */
|
|
45
|
+
resume(): void {
|
|
46
|
+
this.disconnectedSince = null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
dispose(): void {
|
|
50
|
+
this.disposed = true;
|
|
51
|
+
this.ui?.setStatus?.('browser-bridge', undefined);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
private setStatus(status: string): void {
|
|
55
|
+
if (this.status === status) return;
|
|
56
|
+
this.status = status;
|
|
57
|
+
this.ui?.setStatus?.('browser-bridge', status);
|
|
58
|
+
}
|
|
59
|
+
}
|
package/src/broker/lazy.ts
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
import type { ProbeResult, ResponseFrame } from './protocol.ts';
|
|
2
2
|
import type { EnsureReadyOptions } from './server.ts';
|
|
3
3
|
import type { TaskStore } from './task-store.ts';
|
|
4
|
+
import type { BrokerRequestOptions } from './abort.ts';
|
|
4
5
|
|
|
5
6
|
/** The slice of the broker API that the browser_* tools actually consume. */
|
|
6
7
|
export interface BrokerLike {
|
|
7
8
|
ensureReady?: (options?: EnsureReadyOptions) => Promise<void>;
|
|
8
9
|
probeConnectivity: () => ProbeResult;
|
|
9
|
-
request: (type: string, params: unknown, options?:
|
|
10
|
+
request: (type: string, params: unknown, options?: BrokerRequestOptions) => Promise<ResponseFrame>;
|
|
10
11
|
taskStore: TaskStore;
|
|
11
12
|
}
|
|
12
13
|
|
|
@@ -139,7 +140,7 @@ export class LazyBrokerHandle implements BrokerLike {
|
|
|
139
140
|
return probe;
|
|
140
141
|
}
|
|
141
142
|
|
|
142
|
-
async request(type: string, params: unknown, options:
|
|
143
|
+
async request(type: string, params: unknown, options: BrokerRequestOptions = {}): Promise<ResponseFrame> {
|
|
143
144
|
if (this.disposed) {
|
|
144
145
|
throw new Error('E_BRIDGE_DISCONNECTED');
|
|
145
146
|
}
|
package/src/broker/remote.ts
CHANGED
|
@@ -19,6 +19,13 @@ import {
|
|
|
19
19
|
type BrokerLogger,
|
|
20
20
|
type EnsureReadyOptions,
|
|
21
21
|
} from './server.ts';
|
|
22
|
+
import {
|
|
23
|
+
abortError,
|
|
24
|
+
onAbort,
|
|
25
|
+
sleepUnlessAborted,
|
|
26
|
+
throwIfAborted,
|
|
27
|
+
type BrokerRequestOptions,
|
|
28
|
+
} from './abort.ts';
|
|
22
29
|
|
|
23
30
|
interface PendingRequest {
|
|
24
31
|
resolve: (value: ResponseFrame) => void;
|
|
@@ -44,6 +51,7 @@ export class RemoteBrowserAgentBroker {
|
|
|
44
51
|
readonly taskStore: TaskStore;
|
|
45
52
|
|
|
46
53
|
private socket: WebSocket | null = null;
|
|
54
|
+
private validatedSocket: WebSocket | null = null;
|
|
47
55
|
private connectPromise: Promise<void> | null = null;
|
|
48
56
|
private pendingRequests = new Map<string, PendingRequest>();
|
|
49
57
|
private startupError: Error | null = null;
|
|
@@ -135,7 +143,7 @@ export class RemoteBrowserAgentBroker {
|
|
|
135
143
|
// Poll the primary's probe for the same budget a local broker would wait,
|
|
136
144
|
// so a tool call arriving during a reconnect window succeeds instead of
|
|
137
145
|
// reporting a hard "connection is down".
|
|
138
|
-
await this.waitForRemoteBridge(options.waitForBridgeMs ?? this.defaultRemoteBridgeWaitMs());
|
|
146
|
+
await this.waitForRemoteBridge(options.waitForBridgeMs ?? this.defaultRemoteBridgeWaitMs(), options.signal);
|
|
139
147
|
}
|
|
140
148
|
|
|
141
149
|
/** Full budget only when the primary has actually seen a bridge at some point.
|
|
@@ -148,13 +156,13 @@ export class RemoteBrowserAgentBroker {
|
|
|
148
156
|
return this.remoteProbe?.bridgeEverConnected === false ? COLD_BRIDGE_WAIT_MS : DEFAULT_BRIDGE_WAIT_MS;
|
|
149
157
|
}
|
|
150
158
|
|
|
151
|
-
private async waitForRemoteBridge(timeoutMs: number): Promise<boolean> {
|
|
159
|
+
private async waitForRemoteBridge(timeoutMs: number, signal?: AbortSignal): Promise<boolean> {
|
|
152
160
|
if (this.probeConnectivity().bridgeConnected) {
|
|
153
161
|
this.coldBridgeMisses = 0;
|
|
154
162
|
this.coldBridgeSince = null;
|
|
155
163
|
return true;
|
|
156
164
|
}
|
|
157
|
-
if (timeoutMs <= 0) return false;
|
|
165
|
+
if (timeoutMs <= 0 || signal?.aborted) return false;
|
|
158
166
|
const deadline = Date.now() + timeoutMs;
|
|
159
167
|
// Every sub-step below can block for up to ~1.5s, so the budget is
|
|
160
168
|
// re-checked before each of them. Checking only at the top of the loop let a
|
|
@@ -163,9 +171,10 @@ export class RemoteBrowserAgentBroker {
|
|
|
163
171
|
while (Date.now() < deadline) {
|
|
164
172
|
const sleepMs = Math.min(250, deadline - Date.now());
|
|
165
173
|
if (sleepMs > 0) {
|
|
166
|
-
|
|
174
|
+
// Wakes immediately on Escape instead of finishing the tick.
|
|
175
|
+
await sleepUnlessAborted(sleepMs, signal);
|
|
167
176
|
}
|
|
168
|
-
if (this.stopped) return false;
|
|
177
|
+
if (this.stopped || signal?.aborted) return false;
|
|
169
178
|
if (Date.now() >= deadline) break;
|
|
170
179
|
try {
|
|
171
180
|
await this.ensureConnected();
|
|
@@ -181,14 +190,15 @@ export class RemoteBrowserAgentBroker {
|
|
|
181
190
|
if (Date.now() >= deadline) break;
|
|
182
191
|
const promoted = await this.promoteOrReconnect();
|
|
183
192
|
if (promoted) {
|
|
184
|
-
const found = await promoted.waitForBridge(Math.max(0, deadline - Date.now()));
|
|
185
|
-
this.recordBridgeWaitOutcome(found, timeoutMs);
|
|
193
|
+
const found = await promoted.waitForBridge(Math.max(0, deadline - Date.now()), signal);
|
|
194
|
+
if (!signal?.aborted) this.recordBridgeWaitOutcome(found, timeoutMs);
|
|
186
195
|
return found;
|
|
187
196
|
}
|
|
188
197
|
}
|
|
189
198
|
}
|
|
190
199
|
const connected = this.probeConnectivity().bridgeConnected;
|
|
191
|
-
|
|
200
|
+
// A budget cut short by Escape is not evidence that the browser is cold.
|
|
201
|
+
if (!signal?.aborted) this.recordBridgeWaitOutcome(connected, timeoutMs);
|
|
192
202
|
return connected;
|
|
193
203
|
}
|
|
194
204
|
|
|
@@ -237,11 +247,15 @@ export class RemoteBrowserAgentBroker {
|
|
|
237
247
|
}
|
|
238
248
|
}
|
|
239
249
|
|
|
240
|
-
private closeSocket(): void {
|
|
250
|
+
private closeSocket(terminate = false): void {
|
|
241
251
|
const socket = this.socket;
|
|
242
252
|
this.socket = null;
|
|
253
|
+
this.validatedSocket = null;
|
|
243
254
|
if (socket) {
|
|
244
|
-
try {
|
|
255
|
+
try {
|
|
256
|
+
if (terminate) socket.terminate();
|
|
257
|
+
else socket.close();
|
|
258
|
+
} catch { /* ignore */ }
|
|
245
259
|
}
|
|
246
260
|
}
|
|
247
261
|
|
|
@@ -275,8 +289,9 @@ export class RemoteBrowserAgentBroker {
|
|
|
275
289
|
}
|
|
276
290
|
}
|
|
277
291
|
|
|
278
|
-
async request(type: string, params: unknown, options:
|
|
292
|
+
async request(type: string, params: unknown, options: BrokerRequestOptions = {}): Promise<ResponseFrame> {
|
|
279
293
|
if (this.stopped) throw new Error('E_BRIDGE_DISCONNECTED');
|
|
294
|
+
throwIfAborted(options.signal, type);
|
|
280
295
|
if (this.promotedBroker) {
|
|
281
296
|
return await this.promotedBroker.request(type, params, options);
|
|
282
297
|
}
|
|
@@ -300,19 +315,34 @@ export class RemoteBrowserAgentBroker {
|
|
|
300
315
|
const payload = JSON.stringify({ v: 1, kind: 'request', id, type, params });
|
|
301
316
|
|
|
302
317
|
return await new Promise<ResponseFrame>((resolve, reject) => {
|
|
303
|
-
|
|
318
|
+
let releaseAbort = () => {};
|
|
319
|
+
const settle = (fn: () => void) => {
|
|
304
320
|
this.pendingRequests.delete(id);
|
|
305
|
-
|
|
321
|
+
clearTimeout(timeout);
|
|
322
|
+
releaseAbort();
|
|
323
|
+
fn();
|
|
324
|
+
};
|
|
325
|
+
|
|
326
|
+
const timeout = setTimeout(() => {
|
|
327
|
+
settle(() => reject(new Error(`Request timed out: ${type}`)));
|
|
306
328
|
}, options.timeoutMs ?? this.requestTimeoutMs);
|
|
307
329
|
timeout.unref?.();
|
|
308
330
|
|
|
309
|
-
this.pendingRequests.set(id, {
|
|
331
|
+
this.pendingRequests.set(id, {
|
|
332
|
+
resolve: (frame) => settle(() => resolve(frame)),
|
|
333
|
+
reject: (error) => settle(() => reject(error)),
|
|
334
|
+
timeout,
|
|
335
|
+
});
|
|
336
|
+
|
|
337
|
+
releaseAbort = onAbort(options.signal, () => {
|
|
338
|
+
settle(() => reject(abortError(type, options.signal)));
|
|
339
|
+
});
|
|
340
|
+
if (options.signal?.aborted) return;
|
|
341
|
+
|
|
310
342
|
try {
|
|
311
343
|
socket.send(payload);
|
|
312
344
|
} catch (error) {
|
|
313
|
-
|
|
314
|
-
this.pendingRequests.delete(id);
|
|
315
|
-
reject(error instanceof Error ? error : new Error(String(error)));
|
|
345
|
+
settle(() => reject(error instanceof Error ? error : new Error(String(error))));
|
|
316
346
|
}
|
|
317
347
|
});
|
|
318
348
|
}
|
|
@@ -327,7 +357,7 @@ export class RemoteBrowserAgentBroker {
|
|
|
327
357
|
// socket to the primary is gone; otherwise tools happily send requests
|
|
328
358
|
// into a dead proxy and only fail on timeout, and callers cannot tell
|
|
329
359
|
// "healed" from "still using a stale snapshot".
|
|
330
|
-
const proxyAlive =
|
|
360
|
+
const proxyAlive = this.hasValidatedConnection();
|
|
331
361
|
return {
|
|
332
362
|
...primary,
|
|
333
363
|
brokerReachable: proxyAlive && primary.brokerReachable,
|
|
@@ -339,8 +369,8 @@ export class RemoteBrowserAgentBroker {
|
|
|
339
369
|
};
|
|
340
370
|
}
|
|
341
371
|
return {
|
|
342
|
-
brokerReachable:
|
|
343
|
-
brokerListening:
|
|
372
|
+
brokerReachable: this.hasValidatedConnection(),
|
|
373
|
+
brokerListening: this.hasValidatedConnection(),
|
|
344
374
|
bridgeConnected: false,
|
|
345
375
|
startupError: this.startupError?.message,
|
|
346
376
|
url: this.url,
|
|
@@ -349,7 +379,14 @@ export class RemoteBrowserAgentBroker {
|
|
|
349
379
|
};
|
|
350
380
|
}
|
|
351
381
|
|
|
382
|
+
private hasValidatedConnection(): boolean {
|
|
383
|
+
return !!this.socket && this.socket === this.validatedSocket
|
|
384
|
+
&& this.socket.readyState === WebSocket.OPEN && !this.startupError;
|
|
385
|
+
}
|
|
386
|
+
|
|
352
387
|
private async probePrimary(): Promise<ProbeResult> {
|
|
388
|
+
await this.ensureConnected();
|
|
389
|
+
const socket = this.socket;
|
|
353
390
|
const response = await this.sendControlRequest('probe');
|
|
354
391
|
if (!response.ok) {
|
|
355
392
|
throw new Error(response.error?.message || 'Primary broker probe failed');
|
|
@@ -361,6 +398,10 @@ export class RemoteBrowserAgentBroker {
|
|
|
361
398
|
if (data.supportsBrokerProxy !== true) {
|
|
362
399
|
throw new Error(`Port ${this.port} has an old pi-browser-agent broker; restart the first pi instance`);
|
|
363
400
|
}
|
|
401
|
+
if (this.stopped || this.socket !== socket || socket?.readyState !== WebSocket.OPEN) {
|
|
402
|
+
throw new Error('E_BRIDGE_DISCONNECTED');
|
|
403
|
+
}
|
|
404
|
+
this.validatedSocket = socket;
|
|
364
405
|
return data as ProbeResult;
|
|
365
406
|
}
|
|
366
407
|
|
|
@@ -471,7 +512,7 @@ export class RemoteBrowserAgentBroker {
|
|
|
471
512
|
if (this.stopped) return;
|
|
472
513
|
this.logger.warn?.('[pi-browser-agent] lost primary broker; healing', { reason });
|
|
473
514
|
const promoted = await this.promoteOrReconnect();
|
|
474
|
-
if (promoted || this.
|
|
515
|
+
if (promoted || this.hasValidatedConnection()) {
|
|
475
516
|
this.healAttempt = 0;
|
|
476
517
|
this.cancelHealTimer();
|
|
477
518
|
return;
|
|
@@ -551,6 +592,12 @@ export class RemoteBrowserAgentBroker {
|
|
|
551
592
|
this.remoteProbe = await this.probePrimary();
|
|
552
593
|
this.startupError = null;
|
|
553
594
|
} catch (reconnectError) {
|
|
595
|
+
this.startupError = reconnectError instanceof Error ? reconnectError : new Error(String(reconnectError));
|
|
596
|
+
// A WebSocket handshake alone does not identify a broker. Discard
|
|
597
|
+
// failed probes immediately rather than waiting for a close handshake.
|
|
598
|
+
this.closeSocket(true);
|
|
599
|
+
this.rejectPendingRequests(this.startupError);
|
|
600
|
+
this.scheduleHeal();
|
|
554
601
|
this.logger.warn?.('[pi-browser-agent] failed to reconnect to promoted primary broker', reconnectError);
|
|
555
602
|
}
|
|
556
603
|
return null;
|
package/src/broker/server.ts
CHANGED
|
@@ -16,6 +16,13 @@ import {
|
|
|
16
16
|
type ResponseFrame,
|
|
17
17
|
} from './protocol.ts';
|
|
18
18
|
import { TaskStore } from './task-store.ts';
|
|
19
|
+
import {
|
|
20
|
+
abortError,
|
|
21
|
+
onAbort,
|
|
22
|
+
throwIfAborted,
|
|
23
|
+
type BrokerRequestOptions,
|
|
24
|
+
type AbortableOptions,
|
|
25
|
+
} from './abort.ts';
|
|
19
26
|
|
|
20
27
|
export interface BrokerLogger {
|
|
21
28
|
info?: (...args: unknown[]) => void;
|
|
@@ -67,7 +74,7 @@ export interface BridgeStateEvent {
|
|
|
67
74
|
|
|
68
75
|
export type BridgeStateListener = (state: BridgeStateEvent) => void;
|
|
69
76
|
|
|
70
|
-
export interface EnsureReadyOptions {
|
|
77
|
+
export interface EnsureReadyOptions extends AbortableOptions {
|
|
71
78
|
/** Override the bridge wait budget. 0 disables waiting entirely. */
|
|
72
79
|
waitForBridgeMs?: number;
|
|
73
80
|
}
|
|
@@ -258,8 +265,12 @@ export class BrowserAgentBroker {
|
|
|
258
265
|
// failing a tool call that arrived mid-reconnect. This is what makes the
|
|
259
266
|
// integration self-healing from the agent's point of view.
|
|
260
267
|
const budget = this.resolveBridgeWaitMs(options);
|
|
261
|
-
const connected = await this.waitForBridge(budget);
|
|
262
|
-
|
|
268
|
+
const connected = await this.waitForBridge(budget, options.signal);
|
|
269
|
+
// A wait cut short by Escape says nothing about whether the browser is
|
|
270
|
+
// cold, so it must not feed the cold-bridge memo.
|
|
271
|
+
if (!options.signal?.aborted) {
|
|
272
|
+
this.recordBridgeWaitOutcome(connected, budget);
|
|
273
|
+
}
|
|
263
274
|
}
|
|
264
275
|
|
|
265
276
|
/** Remember that the full budget was burned without a bridge showing up, so
|
|
@@ -308,23 +319,29 @@ export class BrowserAgentBroker {
|
|
|
308
319
|
/** Resolve as soon as a Chrome extension bridge is connected, or after
|
|
309
320
|
* `timeoutMs`. Never rejects — callers decide what to do with a still-absent
|
|
310
321
|
* bridge. */
|
|
311
|
-
async waitForBridge(timeoutMs: number): Promise<boolean> {
|
|
322
|
+
async waitForBridge(timeoutMs: number, signal?: AbortSignal): Promise<boolean> {
|
|
312
323
|
if (this.bridgeSocket && this.bridgeHello) return true;
|
|
324
|
+
if (signal?.aborted) return false;
|
|
313
325
|
if (!this.server || timeoutMs <= 0) return false;
|
|
314
326
|
|
|
315
327
|
return await new Promise<boolean>((resolve) => {
|
|
316
328
|
let settled = false;
|
|
329
|
+
let releaseAbort = () => {};
|
|
317
330
|
const finish = (value: boolean) => {
|
|
318
331
|
if (settled) return;
|
|
319
332
|
settled = true;
|
|
320
333
|
this.bridgeWaiters.delete(waiter);
|
|
321
334
|
clearTimeout(timer);
|
|
335
|
+
releaseAbort();
|
|
322
336
|
resolve(value);
|
|
323
337
|
};
|
|
324
338
|
const waiter = (connected: boolean) => finish(connected);
|
|
325
339
|
const timer = setTimeout(() => finish(!!this.bridgeSocket && !!this.bridgeHello), timeoutMs);
|
|
326
340
|
timer.unref?.();
|
|
327
341
|
this.bridgeWaiters.add(waiter);
|
|
342
|
+
// Waiting out an 8s reconnect window is the other place Escape used to
|
|
343
|
+
// hang, before any request is even sent.
|
|
344
|
+
releaseAbort = onAbort(signal, () => finish(false));
|
|
328
345
|
});
|
|
329
346
|
}
|
|
330
347
|
|
|
@@ -510,7 +527,10 @@ export class BrowserAgentBroker {
|
|
|
510
527
|
});
|
|
511
528
|
}
|
|
512
529
|
|
|
513
|
-
async request(type: string, params: unknown, options:
|
|
530
|
+
async request(type: string, params: unknown, options: BrokerRequestOptions = {}): Promise<ResponseFrame> {
|
|
531
|
+
// Never open a request for a caller that has already cancelled.
|
|
532
|
+
throwIfAborted(options.signal, type);
|
|
533
|
+
|
|
514
534
|
const socket = this.bridgeSocket;
|
|
515
535
|
if (!socket || !this.bridgeHello) {
|
|
516
536
|
throw new Error('E_BRIDGE_DISCONNECTED');
|
|
@@ -520,29 +540,45 @@ export class BrowserAgentBroker {
|
|
|
520
540
|
const payload = JSON.stringify({ v: 1, kind: 'request', id, type, params });
|
|
521
541
|
|
|
522
542
|
return await new Promise<ResponseFrame>((resolve, reject) => {
|
|
523
|
-
|
|
543
|
+
let releaseAbort = () => {};
|
|
544
|
+
const settle = (fn: () => void) => {
|
|
524
545
|
this.pendingRequests.delete(id);
|
|
525
|
-
|
|
546
|
+
clearTimeout(timeout);
|
|
547
|
+
releaseAbort();
|
|
548
|
+
fn();
|
|
549
|
+
};
|
|
550
|
+
|
|
551
|
+
const timeout = setTimeout(() => {
|
|
552
|
+
settle(() => reject(new Error(`Request timed out: ${type}`)));
|
|
526
553
|
}, options.timeoutMs ?? this.requestTimeoutMs);
|
|
527
554
|
timeout.unref?.();
|
|
528
555
|
|
|
529
|
-
this.pendingRequests.set(id, {
|
|
556
|
+
this.pendingRequests.set(id, {
|
|
557
|
+
resolve: (frame) => settle(() => resolve(frame)),
|
|
558
|
+
reject: (error) => settle(() => reject(error)),
|
|
559
|
+
timeout,
|
|
560
|
+
});
|
|
561
|
+
|
|
562
|
+
// Escape (or any other cancellation) hands pi back control immediately.
|
|
563
|
+
// The bridge has no cancel frame yet, so the in-flight browser work still
|
|
564
|
+
// finishes; we just stop waiting for it and drop the pending entry so a
|
|
565
|
+
// late response is ignored instead of resolving a dead promise.
|
|
566
|
+
releaseAbort = onAbort(options.signal, () => {
|
|
567
|
+
settle(() => reject(abortError(type, options.signal)));
|
|
568
|
+
});
|
|
569
|
+
if (options.signal?.aborted) return;
|
|
530
570
|
|
|
531
571
|
// If the bridge went away between our validation and send, reject fast
|
|
532
572
|
// so callers get a direct disconnect error instead of waiting for a timeout.
|
|
533
573
|
if (this.bridgeSocket !== socket) {
|
|
534
|
-
|
|
535
|
-
this.pendingRequests.delete(id);
|
|
536
|
-
reject(new Error('E_BRIDGE_DISCONNECTED'));
|
|
574
|
+
settle(() => reject(new Error('E_BRIDGE_DISCONNECTED')));
|
|
537
575
|
return;
|
|
538
576
|
}
|
|
539
577
|
|
|
540
578
|
try {
|
|
541
579
|
socket.send(payload);
|
|
542
580
|
} catch (error) {
|
|
543
|
-
|
|
544
|
-
this.pendingRequests.delete(id);
|
|
545
|
-
reject(error instanceof Error ? error : new Error(String(error)));
|
|
581
|
+
settle(() => reject(error instanceof Error ? error : new Error(String(error))));
|
|
546
582
|
}
|
|
547
583
|
});
|
|
548
584
|
}
|