oira666_pi-browser-agent 0.0.1
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/LICENSE +201 -0
- package/README.md +101 -0
- package/package.json +28 -0
- package/src/broker/protocol.ts +127 -0
- package/src/broker/server.ts +331 -0
- package/src/broker/task-store.ts +192 -0
- package/src/index.ts +132 -0
- package/src/tools/_register.ts +89 -0
- package/src/tools/browser_agent_tools.ts +72 -0
- package/src/tools/browser_js_navigation_tools.ts +458 -0
- package/src/tools/browser_observability_tools.ts +167 -0
- package/src/tools/browser_task_tools.ts +383 -0
- package/src/tools/read_only/common.ts +173 -0
- package/src/tools/read_only/index.ts +312 -0
- package/src/util/paths.ts +19 -0
- package/src/util/truncate.ts +34 -0
- package/tests/broker.test.ts +241 -0
- package/tests/index.test.ts +153 -0
- package/tests/protocol.test.ts +48 -0
- package/tests/task-store.test.ts +35 -0
- package/tests/tools/browser-js-navigation-tools.test.ts +223 -0
- package/tests/tools/browser-observability-tools.test.ts +100 -0
- package/tests/tools/browser-read-only-tools.test.ts +225 -0
- package/tests/tools/browser-task-tools.test.ts +348 -0
- package/tests/tools/meta-tool.test.ts +110 -0
- package/tsconfig.json +15 -0
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { WebSocketServer, type RawData, type WebSocket } from 'ws';
|
|
3
|
+
|
|
4
|
+
interface BridgeSocket extends WebSocket {
|
|
5
|
+
isAlive?: boolean;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
import {
|
|
9
|
+
createErrorResponseFrame,
|
|
10
|
+
createResponseFrame,
|
|
11
|
+
createWelcomeFrame,
|
|
12
|
+
parseIncomingFrame,
|
|
13
|
+
type HelloFrame,
|
|
14
|
+
type ProbeResult,
|
|
15
|
+
type ResponseFrame,
|
|
16
|
+
} from './protocol.ts';
|
|
17
|
+
import { TaskStore } from './task-store.ts';
|
|
18
|
+
|
|
19
|
+
export interface BrokerLogger {
|
|
20
|
+
info?: (...args: unknown[]) => void;
|
|
21
|
+
warn?: (...args: unknown[]) => void;
|
|
22
|
+
error?: (...args: unknown[]) => void;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
interface PendingRequest {
|
|
26
|
+
resolve: (value: ResponseFrame) => void;
|
|
27
|
+
reject: (error: Error) => void;
|
|
28
|
+
timeout: ReturnType<typeof setTimeout>;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export class BrowserAgentBroker {
|
|
32
|
+
readonly host: string;
|
|
33
|
+
readonly port: number;
|
|
34
|
+
readonly logger: BrokerLogger;
|
|
35
|
+
readonly requestTimeoutMs: number;
|
|
36
|
+
readonly taskStore: TaskStore;
|
|
37
|
+
|
|
38
|
+
private server: WebSocketServer | null = null;
|
|
39
|
+
private bridgeSocket: WebSocket | null = null;
|
|
40
|
+
private bridgeHello: HelloFrame | null = null;
|
|
41
|
+
private bridgeSessionSerial = 0;
|
|
42
|
+
private startupError: Error | null = null;
|
|
43
|
+
private shutdownError: Error | null = null;
|
|
44
|
+
private pingTimer: ReturnType<typeof setInterval> | null = null;
|
|
45
|
+
private pendingRequests = new Map<string, PendingRequest>();
|
|
46
|
+
|
|
47
|
+
constructor({
|
|
48
|
+
host = process.env.PI_BA_HOST || '127.0.0.1',
|
|
49
|
+
port = Number(process.env.PI_BA_PORT || 7878),
|
|
50
|
+
logger = console,
|
|
51
|
+
requestTimeoutMs = 10_000,
|
|
52
|
+
taskStore,
|
|
53
|
+
}: {
|
|
54
|
+
host?: string;
|
|
55
|
+
port?: number;
|
|
56
|
+
logger?: BrokerLogger;
|
|
57
|
+
requestTimeoutMs?: number;
|
|
58
|
+
taskStore: TaskStore;
|
|
59
|
+
}) {
|
|
60
|
+
this.host = host;
|
|
61
|
+
this.port = port;
|
|
62
|
+
this.logger = logger;
|
|
63
|
+
this.requestTimeoutMs = requestTimeoutMs;
|
|
64
|
+
this.taskStore = taskStore;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
get url(): string {
|
|
68
|
+
return `ws://${this.host}:${this.port}`;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async start(): Promise<void> {
|
|
72
|
+
if (this.server) {
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
this.startupError = null;
|
|
77
|
+
|
|
78
|
+
try {
|
|
79
|
+
await this.taskStore.init();
|
|
80
|
+
await this.taskStore.gc();
|
|
81
|
+
await new Promise<void>((resolve, reject) => {
|
|
82
|
+
const server = new WebSocketServer({ host: this.host, port: this.port });
|
|
83
|
+
|
|
84
|
+
const onError = (error: Error) => {
|
|
85
|
+
server.off('listening', onListening);
|
|
86
|
+
// Startup failed; do not publish the server as the broker's listener.
|
|
87
|
+
this.server = null;
|
|
88
|
+
try {
|
|
89
|
+
server.close();
|
|
90
|
+
} catch {
|
|
91
|
+
// ignore; server never finished binding
|
|
92
|
+
}
|
|
93
|
+
reject(error);
|
|
94
|
+
};
|
|
95
|
+
const onListening = () => {
|
|
96
|
+
server.off('error', onError);
|
|
97
|
+
this.server = server;
|
|
98
|
+
resolve();
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
server.once('error', onError);
|
|
102
|
+
server.once('listening', onListening);
|
|
103
|
+
server.on('connection', (socket: WebSocket) => {
|
|
104
|
+
void this.handleConnection(socket);
|
|
105
|
+
});
|
|
106
|
+
server.on('error', (error: Error) => {
|
|
107
|
+
this.logger.error?.('[pi-browser-agent] broker server error', error);
|
|
108
|
+
});
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
this.pingTimer = setInterval(() => {
|
|
112
|
+
const socket = this.bridgeSocket as BridgeSocket | null;
|
|
113
|
+
if (!socket) {
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
if (socket.isAlive === false) {
|
|
117
|
+
this.logger.warn?.('[pi-browser-agent] bridge heartbeat timed out');
|
|
118
|
+
this.failBridge(socket, new Error('E_BRIDGE_DISCONNECTED'));
|
|
119
|
+
try {
|
|
120
|
+
socket.terminate();
|
|
121
|
+
} catch (error) {
|
|
122
|
+
this.logger.warn?.('[pi-browser-agent] failed to terminate stale bridge socket', error);
|
|
123
|
+
}
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
socket.isAlive = false;
|
|
127
|
+
try {
|
|
128
|
+
socket.ping();
|
|
129
|
+
} catch (error) {
|
|
130
|
+
this.logger.warn?.('[pi-browser-agent] ping failed', error);
|
|
131
|
+
}
|
|
132
|
+
}, 25_000);
|
|
133
|
+
this.pingTimer.unref?.();
|
|
134
|
+
this.logger.info?.('[pi-browser-agent] broker listening', { url: this.url });
|
|
135
|
+
} catch (error) {
|
|
136
|
+
this.startupError = error instanceof Error ? error : new Error(String(error));
|
|
137
|
+
this.logger.error?.('[pi-browser-agent] broker startup failed', this.startupError);
|
|
138
|
+
throw this.startupError;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
async stop(): Promise<void> {
|
|
143
|
+
const closeErrors: Error[] = [];
|
|
144
|
+
|
|
145
|
+
if (this.pingTimer) {
|
|
146
|
+
clearInterval(this.pingTimer);
|
|
147
|
+
this.pingTimer = null;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
this.rejectPendingRequests(new Error('E_BRIDGE_DISCONNECTED'));
|
|
151
|
+
|
|
152
|
+
if (this.bridgeSocket) {
|
|
153
|
+
try {
|
|
154
|
+
this.bridgeSocket.close();
|
|
155
|
+
} catch (error) {
|
|
156
|
+
closeErrors.push(error instanceof Error ? error : new Error(String(error)));
|
|
157
|
+
} finally {
|
|
158
|
+
this.bridgeSocket = null;
|
|
159
|
+
this.bridgeHello = null;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
if (this.server) {
|
|
164
|
+
const server = this.server;
|
|
165
|
+
this.server = null;
|
|
166
|
+
try {
|
|
167
|
+
await new Promise<void>((resolve, reject) => {
|
|
168
|
+
server.close((error) => {
|
|
169
|
+
if (error) {
|
|
170
|
+
reject(error);
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
resolve();
|
|
174
|
+
});
|
|
175
|
+
});
|
|
176
|
+
} catch (error) {
|
|
177
|
+
closeErrors.push(error instanceof Error ? error : new Error(String(error)));
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
if (closeErrors.length > 0) {
|
|
182
|
+
this.shutdownError = closeErrors[0];
|
|
183
|
+
this.logger.error?.('[pi-browser-agent] broker shutdown failed', this.shutdownError);
|
|
184
|
+
throw new AggregateError(closeErrors, 'Broker shutdown failed');
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
async request(type: string, params: unknown, options: { timeoutMs?: number } = {}): Promise<ResponseFrame> {
|
|
189
|
+
const socket = this.bridgeSocket;
|
|
190
|
+
if (!socket || !this.bridgeHello) {
|
|
191
|
+
throw new Error('E_BRIDGE_DISCONNECTED');
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
const id = randomUUID();
|
|
195
|
+
const payload = JSON.stringify({ v: 1, kind: 'request', id, type, params });
|
|
196
|
+
|
|
197
|
+
return await new Promise<ResponseFrame>((resolve, reject) => {
|
|
198
|
+
const timeout = setTimeout(() => {
|
|
199
|
+
this.pendingRequests.delete(id);
|
|
200
|
+
reject(new Error(`Request timed out: ${type}`));
|
|
201
|
+
}, options.timeoutMs ?? this.requestTimeoutMs);
|
|
202
|
+
timeout.unref?.();
|
|
203
|
+
|
|
204
|
+
this.pendingRequests.set(id, { resolve, reject, timeout });
|
|
205
|
+
|
|
206
|
+
// If the bridge went away between our validation and send, reject fast
|
|
207
|
+
// so callers get a direct disconnect error instead of waiting for a timeout.
|
|
208
|
+
if (this.bridgeSocket !== socket) {
|
|
209
|
+
clearTimeout(timeout);
|
|
210
|
+
this.pendingRequests.delete(id);
|
|
211
|
+
reject(new Error('E_BRIDGE_DISCONNECTED'));
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
try {
|
|
216
|
+
socket.send(payload);
|
|
217
|
+
} catch (error) {
|
|
218
|
+
clearTimeout(timeout);
|
|
219
|
+
this.pendingRequests.delete(id);
|
|
220
|
+
reject(error instanceof Error ? error : new Error(String(error)));
|
|
221
|
+
}
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
probeConnectivity(): ProbeResult {
|
|
226
|
+
return {
|
|
227
|
+
brokerReachable: !this.startupError,
|
|
228
|
+
brokerListening: !!this.server && !this.startupError,
|
|
229
|
+
bridgeConnected: !!this.bridgeSocket && !!this.bridgeHello,
|
|
230
|
+
bridgeVersion: this.bridgeHello?.version,
|
|
231
|
+
capabilities: this.bridgeHello?.capabilities,
|
|
232
|
+
startupError: this.startupError?.message,
|
|
233
|
+
url: this.url,
|
|
234
|
+
bridgeSessionSerial: this.bridgeSessionSerial,
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
private async handleConnection(socket: WebSocket): Promise<void> {
|
|
239
|
+
const bridgeSocket = socket as BridgeSocket;
|
|
240
|
+
bridgeSocket.isAlive = true;
|
|
241
|
+
|
|
242
|
+
// Do NOT evict the current bridge here. A new accepted socket has not yet
|
|
243
|
+
// authenticated as a bridge session. We only replace the active bridge
|
|
244
|
+
// once this socket sends a valid `hello` frame (see handleRawMessage).
|
|
245
|
+
|
|
246
|
+
bridgeSocket.on('pong', () => {
|
|
247
|
+
bridgeSocket.isAlive = true;
|
|
248
|
+
});
|
|
249
|
+
|
|
250
|
+
bridgeSocket.on('error', (error: Error) => {
|
|
251
|
+
this.logger.warn?.('[pi-browser-agent] bridge socket error', error);
|
|
252
|
+
this.failBridge(bridgeSocket, error);
|
|
253
|
+
});
|
|
254
|
+
|
|
255
|
+
bridgeSocket.on('close', () => {
|
|
256
|
+
this.failBridge(bridgeSocket, new Error('E_BRIDGE_DISCONNECTED'));
|
|
257
|
+
});
|
|
258
|
+
|
|
259
|
+
bridgeSocket.on('message', (buffer: RawData) => {
|
|
260
|
+
try {
|
|
261
|
+
this.handleRawMessage(bridgeSocket, buffer.toString());
|
|
262
|
+
} catch (error) {
|
|
263
|
+
this.logger.warn?.('[pi-browser-agent] invalid bridge frame', error);
|
|
264
|
+
}
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
private rejectPendingRequests(error: Error): void {
|
|
269
|
+
for (const [id, pending] of this.pendingRequests.entries()) {
|
|
270
|
+
clearTimeout(pending.timeout);
|
|
271
|
+
pending.reject(error);
|
|
272
|
+
this.pendingRequests.delete(id);
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
private failBridge(socket: BridgeSocket, error: Error): void {
|
|
277
|
+
if (this.bridgeSocket !== socket) {
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
this.bridgeSocket = null;
|
|
281
|
+
this.bridgeHello = null;
|
|
282
|
+
this.rejectPendingRequests(error);
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
private handleRawMessage(socket: WebSocket, raw: string): void {
|
|
286
|
+
const frame = parseIncomingFrame(raw);
|
|
287
|
+
|
|
288
|
+
if (frame.kind === 'hello') {
|
|
289
|
+
// Promote this socket to the active bridge. Capture the previous one in
|
|
290
|
+
// a local so we can close it explicitly after state has been swapped.
|
|
291
|
+
const previous = this.bridgeSocket as BridgeSocket | null;
|
|
292
|
+
const isHandoff = previous !== null && previous !== socket;
|
|
293
|
+
|
|
294
|
+
this.bridgeSocket = socket;
|
|
295
|
+
this.bridgeHello = frame;
|
|
296
|
+
this.bridgeSessionSerial += 1;
|
|
297
|
+
socket.send(JSON.stringify(createWelcomeFrame('0.0.0')));
|
|
298
|
+
|
|
299
|
+
if (isHandoff && previous) {
|
|
300
|
+
this.rejectPendingRequests(new Error('E_BRIDGE_DISCONNECTED'));
|
|
301
|
+
try {
|
|
302
|
+
previous.close(1012, 'Superseded by a newer bridge connection');
|
|
303
|
+
} catch (error) {
|
|
304
|
+
this.logger.warn?.('[pi-browser-agent] failed to close stale bridge socket', error);
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
return;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
if (frame.kind === 'probe') {
|
|
311
|
+
const id = frame.id || randomUUID();
|
|
312
|
+
socket.send(JSON.stringify(createResponseFrame(id, this.probeConnectivity())));
|
|
313
|
+
return;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
if (frame.kind === 'response') {
|
|
317
|
+
const pending = this.pendingRequests.get(frame.id);
|
|
318
|
+
if (!pending) {
|
|
319
|
+
return;
|
|
320
|
+
}
|
|
321
|
+
clearTimeout(pending.timeout);
|
|
322
|
+
this.pendingRequests.delete(frame.id);
|
|
323
|
+
pending.resolve(frame);
|
|
324
|
+
return;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
if (frame.kind === 'request') {
|
|
328
|
+
socket.send(JSON.stringify(createErrorResponseFrame(frame.id, 'E_UNKNOWN_TYPE', `Unknown request type: ${frame.type}`)));
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
}
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import { mkdir, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
|
|
4
|
+
export interface TaskStoreEntry {
|
|
5
|
+
kind: string;
|
|
6
|
+
taskId?: string;
|
|
7
|
+
status?: string;
|
|
8
|
+
startedAt?: number;
|
|
9
|
+
endedAt?: number;
|
|
10
|
+
[key: string]: unknown;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface TaskSummary {
|
|
14
|
+
taskId: string;
|
|
15
|
+
status: string;
|
|
16
|
+
startedAt?: number;
|
|
17
|
+
endedAt?: number;
|
|
18
|
+
task?: string;
|
|
19
|
+
result?: unknown;
|
|
20
|
+
error?: unknown;
|
|
21
|
+
events?: number;
|
|
22
|
+
path: string;
|
|
23
|
+
corrupted?: boolean;
|
|
24
|
+
corruptionError?: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export class TaskCorruptionError extends Error {
|
|
28
|
+
readonly taskId: string;
|
|
29
|
+
readonly path: string;
|
|
30
|
+
readonly cause: unknown;
|
|
31
|
+
constructor(taskId: string, path: string, cause: unknown) {
|
|
32
|
+
const reason = cause instanceof Error ? cause.message : String(cause);
|
|
33
|
+
super(`Task history for ${taskId} is corrupted: ${reason}`);
|
|
34
|
+
this.name = 'TaskCorruptionError';
|
|
35
|
+
this.taskId = taskId;
|
|
36
|
+
this.path = path;
|
|
37
|
+
this.cause = cause;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function assertValidTaskId(taskId: string): void {
|
|
42
|
+
if (!/^[A-Za-z0-9_-]+$/.test(taskId)) {
|
|
43
|
+
throw new Error(`Invalid task id: ${taskId}`);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function normalizeTaskStatus(status?: string): string {
|
|
48
|
+
switch (String(status || '').toLowerCase()) {
|
|
49
|
+
case 'done':
|
|
50
|
+
case 'completed':
|
|
51
|
+
return 'completed';
|
|
52
|
+
case 'stopped':
|
|
53
|
+
case 'cancelled':
|
|
54
|
+
case 'canceled':
|
|
55
|
+
return 'stopped';
|
|
56
|
+
case 'error':
|
|
57
|
+
case 'failed':
|
|
58
|
+
return 'error';
|
|
59
|
+
default:
|
|
60
|
+
return status || 'unknown';
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export class TaskStore {
|
|
65
|
+
readonly dir: string;
|
|
66
|
+
readonly ttlMs: number;
|
|
67
|
+
readonly now: () => number;
|
|
68
|
+
|
|
69
|
+
constructor({ dir, ttlMs = 7 * 24 * 60 * 60 * 1000, now = () => Date.now() }: { dir: string; ttlMs?: number; now?: () => number }) {
|
|
70
|
+
this.dir = dir;
|
|
71
|
+
this.ttlMs = ttlMs;
|
|
72
|
+
this.now = now;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async init(): Promise<void> {
|
|
76
|
+
await mkdir(this.dir, { recursive: true });
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
private getTaskPath(taskId: string): string {
|
|
80
|
+
assertValidTaskId(taskId);
|
|
81
|
+
return join(this.dir, `${taskId}.jsonl`);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
async append(taskId: string, entry: TaskStoreEntry): Promise<string> {
|
|
85
|
+
await this.init();
|
|
86
|
+
const path = this.getTaskPath(taskId);
|
|
87
|
+
const line = `${JSON.stringify(entry)}\n`;
|
|
88
|
+
await writeFile(path, line, { encoding: 'utf8', flag: 'a' });
|
|
89
|
+
return path;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async read(taskId: string): Promise<TaskStoreEntry[]> {
|
|
93
|
+
const path = this.getTaskPath(taskId);
|
|
94
|
+
const contents = await readFile(path, 'utf8');
|
|
95
|
+
const entries: TaskStoreEntry[] = [];
|
|
96
|
+
const lines = contents.split('\n');
|
|
97
|
+
for (let index = 0; index < lines.length; index += 1) {
|
|
98
|
+
const line = lines[index]?.trim();
|
|
99
|
+
if (!line) continue;
|
|
100
|
+
try {
|
|
101
|
+
entries.push(JSON.parse(line) as TaskStoreEntry);
|
|
102
|
+
} catch (error) {
|
|
103
|
+
throw new TaskCorruptionError(taskId, path, error);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return entries;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
async list(options: { limit?: number; status?: string } = {}): Promise<TaskSummary[]> {
|
|
110
|
+
await this.init();
|
|
111
|
+
const limit = options.limit ?? 50;
|
|
112
|
+
const names = (await readdir(this.dir)).filter((name) => name.endsWith('.jsonl'));
|
|
113
|
+
const items = await Promise.all(
|
|
114
|
+
names.map(async (name) => {
|
|
115
|
+
const path = join(this.dir, name);
|
|
116
|
+
const taskId = name.slice(0, -'.jsonl'.length);
|
|
117
|
+
const stats = await stat(path);
|
|
118
|
+
// Isolate per-file corruption: a single bad task file must not prevent
|
|
119
|
+
// the rest of the list from being returned. Surface a corruption marker
|
|
120
|
+
// on the affected entry instead.
|
|
121
|
+
try {
|
|
122
|
+
const entries = await this.read(taskId);
|
|
123
|
+
const first = entries[0] ?? {};
|
|
124
|
+
const last = entries[entries.length - 1] ?? {};
|
|
125
|
+
const summary: TaskSummary = {
|
|
126
|
+
taskId: String(first.taskId ?? taskId),
|
|
127
|
+
status: String(last.status ?? first.status ?? 'unknown'),
|
|
128
|
+
startedAt: typeof first.startedAt === 'number' ? first.startedAt : undefined,
|
|
129
|
+
endedAt: typeof last.endedAt === 'number' ? last.endedAt : undefined,
|
|
130
|
+
task: typeof first.task === 'string' ? first.task : undefined,
|
|
131
|
+
result: last.result,
|
|
132
|
+
error: last.error,
|
|
133
|
+
events: entries.length,
|
|
134
|
+
path,
|
|
135
|
+
};
|
|
136
|
+
return { summary, mtimeMs: stats.mtimeMs };
|
|
137
|
+
} catch (error) {
|
|
138
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
139
|
+
const summary: TaskSummary = {
|
|
140
|
+
taskId,
|
|
141
|
+
status: 'corrupted',
|
|
142
|
+
path,
|
|
143
|
+
corrupted: true,
|
|
144
|
+
corruptionError: reason,
|
|
145
|
+
};
|
|
146
|
+
return { summary, mtimeMs: stats.mtimeMs };
|
|
147
|
+
}
|
|
148
|
+
}),
|
|
149
|
+
);
|
|
150
|
+
|
|
151
|
+
return items
|
|
152
|
+
.sort((a, b) => b.mtimeMs - a.mtimeMs)
|
|
153
|
+
.map((item) => item.summary)
|
|
154
|
+
.filter((summary) => {
|
|
155
|
+
if (!options.status) return true;
|
|
156
|
+
const wanted = normalizeTaskStatus(options.status);
|
|
157
|
+
return normalizeTaskStatus(summary.status) === wanted;
|
|
158
|
+
})
|
|
159
|
+
.slice(0, limit);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
async gc(): Promise<string[]> {
|
|
163
|
+
await this.init();
|
|
164
|
+
const cutoff = this.now() - this.ttlMs;
|
|
165
|
+
const names = (await readdir(this.dir)).filter((name) => name.endsWith('.jsonl'));
|
|
166
|
+
const removed: string[] = [];
|
|
167
|
+
|
|
168
|
+
await Promise.all(
|
|
169
|
+
names.map(async (name) => {
|
|
170
|
+
const taskId = name.slice(0, -'.jsonl'.length);
|
|
171
|
+
const path = join(this.dir, name);
|
|
172
|
+
const entries = await this.read(taskId).catch(() => [] as TaskStoreEntry[]);
|
|
173
|
+
const first = entries[0] ?? {};
|
|
174
|
+
const last = entries[entries.length - 1] ?? {};
|
|
175
|
+
const candidateTime =
|
|
176
|
+
typeof last.endedAt === 'number'
|
|
177
|
+
? last.endedAt
|
|
178
|
+
: typeof first.startedAt === 'number'
|
|
179
|
+
? first.startedAt
|
|
180
|
+
: (await stat(path)).mtimeMs;
|
|
181
|
+
|
|
182
|
+
if (candidateTime >= cutoff) {
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
await rm(path, { force: true });
|
|
186
|
+
removed.push(path);
|
|
187
|
+
}),
|
|
188
|
+
);
|
|
189
|
+
|
|
190
|
+
return removed;
|
|
191
|
+
}
|
|
192
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { join } from 'node:path';
|
|
2
|
+
|
|
3
|
+
import { BrowserAgentBroker } from './broker/server.ts';
|
|
4
|
+
import { TaskStore } from './broker/task-store.ts';
|
|
5
|
+
import { ensureStateDir } from './util/paths.ts';
|
|
6
|
+
import { registerAllTools, resetRegisteredBrowserTools } from './tools/_register.ts';
|
|
7
|
+
import { createBrowserAgentToolsTool, resetBrowserAgentToolState } from './tools/browser_agent_tools.ts';
|
|
8
|
+
|
|
9
|
+
let brokerSingleton: BrowserAgentBroker | null = null;
|
|
10
|
+
let brokerStartup: Promise<BrowserAgentBroker> | null = null;
|
|
11
|
+
let startupMessage: string | null = null;
|
|
12
|
+
|
|
13
|
+
export function getBroker(): BrowserAgentBroker | null {
|
|
14
|
+
return brokerSingleton;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function getStartupMessage(): string | null {
|
|
18
|
+
return startupMessage;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export async function resetForTests(): Promise<void> {
|
|
22
|
+
if (brokerSingleton) {
|
|
23
|
+
try {
|
|
24
|
+
await brokerSingleton.stop();
|
|
25
|
+
} catch {
|
|
26
|
+
// ignore in tests; callers are resetting state intentionally
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
brokerSingleton = null;
|
|
30
|
+
brokerStartup = null;
|
|
31
|
+
startupMessage = null;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async function createAndStartBroker(logger: Console): Promise<BrowserAgentBroker> {
|
|
35
|
+
const tasksDir = await ensureStateDir('tasks');
|
|
36
|
+
const broker = new BrowserAgentBroker({
|
|
37
|
+
logger,
|
|
38
|
+
taskStore: new TaskStore({ dir: join(tasksDir) }),
|
|
39
|
+
});
|
|
40
|
+
// start() now throws on fatal startup failure. If we get here it bound successfully.
|
|
41
|
+
await broker.start();
|
|
42
|
+
return broker;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async function getOrCreateBroker(logger: Console = console): Promise<BrowserAgentBroker> {
|
|
46
|
+
// If an existing broker is healthy, reuse it.
|
|
47
|
+
if (brokerSingleton) {
|
|
48
|
+
const probe = brokerSingleton.probeConnectivity();
|
|
49
|
+
if (probe.brokerListening) {
|
|
50
|
+
return brokerSingleton;
|
|
51
|
+
}
|
|
52
|
+
// Non-listening singleton (e.g. after a prior failure). Drop it and retry.
|
|
53
|
+
brokerSingleton = null;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// Serialize startup: at most one in-flight start attempt at a time.
|
|
57
|
+
if (brokerStartup) {
|
|
58
|
+
return await brokerStartup;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
brokerStartup = (async () => {
|
|
62
|
+
try {
|
|
63
|
+
const broker = await createAndStartBroker(logger);
|
|
64
|
+
// Only publish a broker as the singleton after a successful bind.
|
|
65
|
+
brokerSingleton = broker;
|
|
66
|
+
return broker;
|
|
67
|
+
} finally {
|
|
68
|
+
// Clear the in-flight promise so subsequent starts can retry on failure.
|
|
69
|
+
brokerStartup = null;
|
|
70
|
+
}
|
|
71
|
+
})();
|
|
72
|
+
|
|
73
|
+
return await brokerStartup;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export default async function piBrowserAgentExtension(pi: {
|
|
77
|
+
on: (event: string, handler: (_event: unknown, ctx?: { ui?: { notify?: (message: string, type?: string) => void } }) => Promise<void> | void) => void;
|
|
78
|
+
registerTool: (tool: any) => void;
|
|
79
|
+
}) {
|
|
80
|
+
const registerSessionTool = async (ctx?: { ui?: { notify?: (message: string, type?: string) => void } }) => {
|
|
81
|
+
resetBrowserAgentToolState();
|
|
82
|
+
resetRegisteredBrowserTools();
|
|
83
|
+
|
|
84
|
+
try {
|
|
85
|
+
const broker = await getOrCreateBroker();
|
|
86
|
+
startupMessage = null;
|
|
87
|
+
pi.registerTool(createBrowserAgentToolsTool(pi, broker));
|
|
88
|
+
// pi reads the tool registry at session_start; any later registerTool()
|
|
89
|
+
// calls (e.g. from a meta-tool invocation) are dropped. Register the
|
|
90
|
+
// full browser_* suite eagerly whenever the broker is listening. The
|
|
91
|
+
// tools themselves probe the bridge at call time and return structured
|
|
92
|
+
// errors if the Chrome extension bridge is disconnected.
|
|
93
|
+
const probe = broker.probeConnectivity();
|
|
94
|
+
if (probe.brokerListening) {
|
|
95
|
+
registerAllTools(pi, { broker });
|
|
96
|
+
}
|
|
97
|
+
} catch (error) {
|
|
98
|
+
startupMessage = error instanceof Error ? error.message : String(error);
|
|
99
|
+
ctx?.ui?.notify?.(`pi-browser-agent startup failed: ${startupMessage}`, 'error');
|
|
100
|
+
// Install the meta-tool against a non-started fallback broker so the
|
|
101
|
+
// session still exposes a diagnostic surface. Do NOT publish this broker
|
|
102
|
+
// as the singleton — we want a real bind retry on the next session.
|
|
103
|
+
const fallbackBroker = new BrowserAgentBroker({
|
|
104
|
+
taskStore: new TaskStore({ dir: join(await ensureStateDir('tasks')) }),
|
|
105
|
+
});
|
|
106
|
+
pi.registerTool(createBrowserAgentToolsTool(pi, fallbackBroker));
|
|
107
|
+
// Intentionally do NOT call registerAllTools here: the fallback broker
|
|
108
|
+
// is not listening, so the full suite would have no working backend.
|
|
109
|
+
}
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
pi.on('session_start', async (_event, ctx) => {
|
|
113
|
+
await registerSessionTool(ctx);
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
pi.on('session_shutdown', async (_event, ctx) => {
|
|
117
|
+
brokerStartup = null;
|
|
118
|
+
if (!brokerSingleton) {
|
|
119
|
+
startupMessage = null;
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
const broker = brokerSingleton;
|
|
123
|
+
brokerSingleton = null;
|
|
124
|
+
startupMessage = null;
|
|
125
|
+
try {
|
|
126
|
+
await broker.stop();
|
|
127
|
+
} catch (error) {
|
|
128
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
129
|
+
ctx?.ui?.notify?.(`pi-browser-agent shutdown failed: ${message}`, 'warning');
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
}
|