oira666_pi-browser-agent 0.0.19 → 0.0.20
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/AGENTS.md +16 -0
- package/README.md +16 -2
- package/package.json +9 -4
- package/src/broker/lazy.ts +3 -6
- package/src/broker/protocol.ts +2 -3
- package/src/broker/server.ts +26 -1
- package/src/index.ts +23 -20
- package/src/tools/_register.ts +9 -20
- package/src/tools/browser_agent_tools.ts +3 -2
- package/src/tools/browser_js_navigation_tools.ts +1 -1
- package/src/tools/browser_observability_tools.ts +1 -1
- package/src/tools/browser_task_tools.ts +1 -1
- package/src/tools/native-result.ts +31 -0
- package/src/tools/read_only/common.ts +1 -1
- package/src/tools/read_only/index.ts +1 -1
- package/tests/fixtures/lifecycle-observer.ts +20 -0
- package/tests/native-result.test.ts +73 -0
- package/tests/pi-cli.e2e.ts +287 -0
- package/tests/pi-compatibility.test.ts +28 -0
- package/tests/server-shutdown.test.ts +28 -0
package/AGENTS.md
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
# Working preferences
|
|
2
|
+
|
|
3
|
+
- Treat models as senior architects. Keep prompts task-specific, with my explicit preferences rather than generic advice or repeated global instructions.
|
|
4
|
+
- Pull the latest changes from `origin` before starting work. Commit and push each finished piece as soon as it is ready; I work across multiple machines.
|
|
5
|
+
- Test only against the latest Pi release. On every release, update the README line `Tested against Pi <version>` to the version actually tested and keep any supported-Pi metadata in `package.json` current.
|
|
6
|
+
|
|
7
|
+
## Code quality bar
|
|
8
|
+
|
|
9
|
+
- Remove dead code, unused imports, and unused dependencies. Wire intended functionality into the application instead of leaving disconnected code.
|
|
10
|
+
- Keep module responsibilities and dependency boundaries clear. Follow existing project conventions and use TypeScript libraries and frameworks as intended.
|
|
11
|
+
- Avoid duplicated logic and unnecessary abstractions. Prefer simple, consistent solutions over one-off patterns.
|
|
12
|
+
- Fix root causes, not symptoms. Avoid brittle workarounds. Make deployment-specific values and operational settings configurable, and never hardcode secrets.
|
|
13
|
+
- Use strict TypeScript and types that model valid application states. Validate external data at runtime. Do not bypass type safety with `any`, unsafe assertions, or suppressed type errors.
|
|
14
|
+
- Keep functions and classes focused. Split files by responsibility before they exceed 350 lines. Exceed this limit only when splitting would clearly hurt readability or cohesion, and explain why.
|
|
15
|
+
- Remove stale or irrelevant comments and docs. Keep useful ones accurate, short, clear, and human-friendly. Explain non-obvious decisions rather than restating code. Apply the unslop and write-prompts skills when available.
|
|
16
|
+
- Add or update tests for changed behavior. Run the project's available type checks, lint checks, and relevant tests before considering work complete.
|
package/README.md
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
# pi-browser-agent
|
|
2
2
|
|
|
3
|
+
Tested against Pi 1.4.0
|
|
4
|
+
|
|
3
5
|
`pi-browser-agent` is a pi extension that starts a local WebSocket broker and registers a browser-driving tool suite for `browser-agent-ext`.
|
|
4
6
|
|
|
5
7
|
## What it does
|
|
6
8
|
|
|
7
9
|
- starts a loopback-only broker on `ws://127.0.0.1:7878` by default
|
|
8
|
-
- registers the full `browser_*` tool suite at session start
|
|
10
|
+
- registers the full `browser_*` tool suite at session start, even while the broker or bridge is unavailable
|
|
9
11
|
- exposes `activate_browser_agent_tools` as a self-check / status tool
|
|
10
12
|
- forwards tool calls to `browser-agent-ext`
|
|
11
13
|
- keeps browser-task history on disk for local inspection
|
|
@@ -41,7 +43,7 @@ For the current in-repo state, use the local-checkout form above.
|
|
|
41
43
|
|
|
42
44
|
## First use in a pi session
|
|
43
45
|
|
|
44
|
-
All `browser_*` tools are registered at session start
|
|
46
|
+
All `browser_*` tools are registered at session start independently of broker availability. `activate_browser_agent_tools` remains available as a self-check / status tool:
|
|
45
47
|
|
|
46
48
|
```text
|
|
47
49
|
activate_browser_agent_tools
|
|
@@ -62,11 +64,13 @@ The full toolkit registered for the session is:
|
|
|
62
64
|
- `browser_get_performance_metrics`
|
|
63
65
|
- `browser_evaluate_js`
|
|
64
66
|
- `browser_run_js`
|
|
67
|
+
- `browser_create_tab`
|
|
65
68
|
- `browser_list_tabs`
|
|
66
69
|
- `browser_switch_tab`
|
|
67
70
|
- `browser_close_tab`
|
|
68
71
|
- `browser_navigate`
|
|
69
72
|
- `browser_reload`
|
|
73
|
+
- `browser_reload_extension`
|
|
70
74
|
- `browser_wait_for`
|
|
71
75
|
- `browser_clear_site_data`
|
|
72
76
|
|
|
@@ -98,6 +102,16 @@ Example:
|
|
|
98
102
|
PI_BA_HOST=0.0.0.0 pi
|
|
99
103
|
```
|
|
100
104
|
|
|
105
|
+
## Development and release checks
|
|
106
|
+
|
|
107
|
+
Run `npm ci --ignore-scripts` to install the locked development dependencies, then `npm test` to typecheck and run the suite. The Pi SDK development dependency is pinned to the tested release; tests do not update the manifest or lockfile.
|
|
108
|
+
|
|
109
|
+
The tests include SDK extension loading, local broker lifecycle checks, and browser-tool protocol tests. `npm run typecheck` checks the currently installed dependencies. Registered tools retain their text/image output and persisted details, and additionally expose JSON-normalized details through Pi's `outputSchema`/`structuredContent` APIs. Failed browser operations set `isError: true` so Pi and programmatic callers can distinguish failures without parsing text.
|
|
110
|
+
|
|
111
|
+
Also run `PI_EVERGREEN_PI_BIN=/absolute/path/to/global/pi npm run test:e2e`. This explicitly loads the local extension into that real Pi CLI, using an isolated agent directory, a deterministic local OpenAI-compatible SSE endpoint and a WebSocket bridge fixture (no credentials or model charges). It checks actual outbound requests, tool execution, retry/abort recovery, compaction, reload with a connected bridge, persistent task history, session replacement and cleanup. Linux also exercises real suspend/resume. `PI_EVERGREEN_E2E_PROVIDER`, `PI_EVERGREEN_E2E_MODEL` and `PI_EVERGREEN_E2E_REASONING` select the test model identity (defaults: `openai`, `gpt-6-luna`, `medium`). These tests do not replace a live Chrome end-to-end check.
|
|
112
|
+
|
|
113
|
+
Before every release, update the tested-against line above to the actual Pi version that passed the checks, and keep the supported Pi peer range in `package.json` accurate. See `AGENTS.md` for the release and code quality rules.
|
|
114
|
+
|
|
101
115
|
## Notes
|
|
102
116
|
|
|
103
117
|
- The broker never synthesizes browser input. Browser actions still go through the extension runtime and its configured input backend.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "oira666_pi-browser-agent",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.20",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "Pi browser agent broker skeleton with lazy browser tool registration",
|
|
@@ -14,18 +14,23 @@
|
|
|
14
14
|
]
|
|
15
15
|
},
|
|
16
16
|
"scripts": {
|
|
17
|
-
"
|
|
17
|
+
"typecheck": "tsc --noEmit",
|
|
18
|
+
"pretest": "npm run typecheck",
|
|
19
|
+
"test": "node --test ./tests/*.test.ts ./tests/tools/*.test.ts",
|
|
20
|
+
"test:e2e": "node --test ./tests/pi-cli.e2e.ts"
|
|
18
21
|
},
|
|
19
22
|
"dependencies": {
|
|
20
23
|
"ws": "^8.18.3"
|
|
21
24
|
},
|
|
22
25
|
"peerDependencies": {
|
|
23
|
-
"@
|
|
26
|
+
"@earendil-works/pi-coding-agent": ">=1.4.0",
|
|
27
|
+
"typebox": "*"
|
|
24
28
|
},
|
|
25
29
|
"devDependencies": {
|
|
26
|
-
"@
|
|
30
|
+
"@earendil-works/pi-coding-agent": "1.4.0",
|
|
27
31
|
"@types/node": "^25.6.0",
|
|
28
32
|
"@types/ws": "^8.18.1",
|
|
33
|
+
"typebox": "^1.3.27",
|
|
29
34
|
"typescript": "^5.9.3"
|
|
30
35
|
}
|
|
31
36
|
}
|
package/src/broker/lazy.ts
CHANGED
|
@@ -14,12 +14,9 @@ export interface BrokerLike {
|
|
|
14
14
|
/**
|
|
15
15
|
* A broker handle that resolves its real backing broker lazily, on every call.
|
|
16
16
|
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
* instance started while the browser stack was down had NO browser tools for its
|
|
21
|
-
* entire lifetime — unrecoverable without restarting pi. And a session whose
|
|
22
|
-
* broker later died held a dead object forever.
|
|
17
|
+
* Registering tools independently of broker availability keeps them visible
|
|
18
|
+
* while Chrome is offline. Resolving at call time also avoids holding a dead
|
|
19
|
+
* broker after a disconnect or primary-process failover.
|
|
23
20
|
*
|
|
24
21
|
* With this handle the tools are always registered and always re-resolve the
|
|
25
22
|
* broker at call time, so the integration heals itself whenever the browser
|
package/src/broker/protocol.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import { Type } from '
|
|
2
|
-
import
|
|
3
|
-
import { Value } from '@sinclair/typebox/value';
|
|
1
|
+
import { Type, type Static } from 'typebox';
|
|
2
|
+
import { Value } from 'typebox/value';
|
|
4
3
|
|
|
5
4
|
export const PROTOCOL_VERSION = 1;
|
|
6
5
|
|
package/src/broker/server.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { createServer } from 'node:http';
|
|
3
|
+
import type { Socket } from 'node:net';
|
|
2
4
|
import { WebSocketServer, type RawData, type WebSocket } from 'ws';
|
|
3
5
|
|
|
4
6
|
interface BridgeSocket extends WebSocket {
|
|
@@ -102,6 +104,7 @@ export class BrowserAgentBroker {
|
|
|
102
104
|
private pingTimer: ReturnType<typeof setInterval> | null = null;
|
|
103
105
|
private pendingRequests = new Map<string, PendingRequest>();
|
|
104
106
|
private sockets = new Set<BridgeSocket>();
|
|
107
|
+
private transports = new Set<Socket>();
|
|
105
108
|
private listeningSince: number | null = null;
|
|
106
109
|
private bridgeEverConnected = false;
|
|
107
110
|
private lastBridgeConnectedAt: number | null = null;
|
|
@@ -419,7 +422,16 @@ export class BrowserAgentBroker {
|
|
|
419
422
|
|
|
420
423
|
private async tryBind(candidate: number): Promise<void> {
|
|
421
424
|
await new Promise<void>((resolve, reject) => {
|
|
422
|
-
const
|
|
425
|
+
const httpServer = createServer((_request, response) => {
|
|
426
|
+
response.writeHead(426, { 'Content-Type': 'text/plain' });
|
|
427
|
+
response.end('Upgrade Required');
|
|
428
|
+
});
|
|
429
|
+
httpServer.on('connection', (socket) => {
|
|
430
|
+
this.transports.add(socket);
|
|
431
|
+
socket.once('close', () => this.transports.delete(socket));
|
|
432
|
+
});
|
|
433
|
+
const server = new WebSocketServer({ server: httpServer });
|
|
434
|
+
server.once('close', () => httpServer.close());
|
|
423
435
|
|
|
424
436
|
const onError = (error: Error) => {
|
|
425
437
|
server.off('listening', onListening);
|
|
@@ -454,6 +466,7 @@ export class BrowserAgentBroker {
|
|
|
454
466
|
server.on('connection', (socket: WebSocket) => {
|
|
455
467
|
void this.handleConnection(socket);
|
|
456
468
|
});
|
|
469
|
+
httpServer.listen(candidate, this.host);
|
|
457
470
|
});
|
|
458
471
|
}
|
|
459
472
|
|
|
@@ -473,6 +486,13 @@ export class BrowserAgentBroker {
|
|
|
473
486
|
this.notifyBridgeWaiters(false);
|
|
474
487
|
this.bridgeStateListeners.clear();
|
|
475
488
|
|
|
489
|
+
// Finish upgraded connections before closing the listener. The packaged
|
|
490
|
+
// Pi runtime can otherwise leave ws's HTTP close callback pending forever,
|
|
491
|
+
// even after all clients have completed their closing handshakes.
|
|
492
|
+
const closingSockets = [...this.sockets].map((socket) => new Promise<void>((resolve) => {
|
|
493
|
+
const timeout = setTimeout(() => socket.terminate(), 250);
|
|
494
|
+
socket.once('close', () => { clearTimeout(timeout); resolve(); });
|
|
495
|
+
}));
|
|
476
496
|
for (const socket of this.sockets) {
|
|
477
497
|
try {
|
|
478
498
|
socket.close();
|
|
@@ -492,6 +512,11 @@ export class BrowserAgentBroker {
|
|
|
492
512
|
}
|
|
493
513
|
}
|
|
494
514
|
|
|
515
|
+
await Promise.all(closingSockets);
|
|
516
|
+
// Explicitly retire upgraded TCP transports too; a completed WebSocket
|
|
517
|
+
// handshake need not mean the host HTTP server has released its connection.
|
|
518
|
+
for (const socket of this.transports) socket.destroy();
|
|
519
|
+
this.transports.clear();
|
|
495
520
|
this.listeningSince = null;
|
|
496
521
|
|
|
497
522
|
if (this.server) {
|
package/src/index.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { join } from 'node:path';
|
|
2
|
+
import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
|
|
3
|
+
import { withNativeResult } from './tools/native-result.ts';
|
|
2
4
|
|
|
3
5
|
import { BrowserAgentBroker, type BrokerLogger } from './broker/server.ts';
|
|
4
6
|
import { RemoteBrowserAgentBroker } from './broker/remote.ts';
|
|
@@ -41,6 +43,7 @@ export function getStartupMessage(): string | null {
|
|
|
41
43
|
}
|
|
42
44
|
|
|
43
45
|
export async function resetForTests(): Promise<void> {
|
|
46
|
+
removeSignalHandlers?.();
|
|
44
47
|
brokerShuttingDown = true;
|
|
45
48
|
brokerLifecycleGeneration += 1;
|
|
46
49
|
sessionLifecycleGeneration += 1;
|
|
@@ -137,7 +140,7 @@ async function createAndStartBroker(logger: BrokerLogger): Promise<BrowserAgentB
|
|
|
137
140
|
}
|
|
138
141
|
}
|
|
139
142
|
|
|
140
|
-
let
|
|
143
|
+
let removeSignalHandlers: (() => void) | null = null;
|
|
141
144
|
let suspending = false;
|
|
142
145
|
let resumeGeneration = 0;
|
|
143
146
|
|
|
@@ -154,12 +157,10 @@ let resumeGeneration = 0;
|
|
|
154
157
|
* process like the default Ctrl+Z). On SIGCONT we re-acquire the broker.
|
|
155
158
|
*/
|
|
156
159
|
function installSuspendResumeHandlers(): void {
|
|
157
|
-
if (
|
|
160
|
+
if (removeSignalHandlers) return;
|
|
158
161
|
// SIGTSTP/SIGCONT are POSIX-only; nothing to do on Windows.
|
|
159
162
|
if (process.platform === 'win32') return;
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
process.on('SIGTSTP', () => {
|
|
163
|
+
const onSuspend = () => {
|
|
163
164
|
if (suspending) return;
|
|
164
165
|
suspending = true;
|
|
165
166
|
brokerShuttingDown = true;
|
|
@@ -184,9 +185,9 @@ function installSuspendResumeHandlers(): void {
|
|
|
184
185
|
try { process.kill(process.pid, 'SIGSTOP'); } catch { /* ignore */ }
|
|
185
186
|
}
|
|
186
187
|
})();
|
|
187
|
-
}
|
|
188
|
+
};
|
|
188
189
|
|
|
189
|
-
|
|
190
|
+
const onResume = () => {
|
|
190
191
|
if (!suspending) return;
|
|
191
192
|
suspending = false;
|
|
192
193
|
resumeGeneration += 1;
|
|
@@ -216,7 +217,15 @@ function installSuspendResumeHandlers(): void {
|
|
|
216
217
|
// re-resolves the lazy handle; the health reporter owns any warning.
|
|
217
218
|
}
|
|
218
219
|
})();
|
|
219
|
-
}
|
|
220
|
+
};
|
|
221
|
+
process.on('SIGTSTP', onSuspend);
|
|
222
|
+
process.on('SIGCONT', onResume);
|
|
223
|
+
removeSignalHandlers = () => {
|
|
224
|
+
process.off('SIGTSTP', onSuspend);
|
|
225
|
+
process.off('SIGCONT', onResume);
|
|
226
|
+
removeSignalHandlers = null;
|
|
227
|
+
suspending = false;
|
|
228
|
+
};
|
|
220
229
|
}
|
|
221
230
|
|
|
222
231
|
/** Republish instance discovery when a secondary wins the bind race. Without
|
|
@@ -300,10 +309,7 @@ async function getOrCreateBroker(logger: BrokerLogger): Promise<BrowserAgentBrok
|
|
|
300
309
|
return await startup;
|
|
301
310
|
}
|
|
302
311
|
|
|
303
|
-
export default async function piBrowserAgentExtension(pi: {
|
|
304
|
-
on: (event: string, handler: (_event: unknown, ctx?: ExtensionContextLike) => Promise<void> | void) => void;
|
|
305
|
-
registerTool: (tool: any) => void;
|
|
306
|
-
}) {
|
|
312
|
+
export default async function piBrowserAgentExtension(pi: ExtensionAPI) {
|
|
307
313
|
const registerSessionTool = async (ctx?: ExtensionContextLike) => {
|
|
308
314
|
const sessionGeneration = ++sessionLifecycleGeneration;
|
|
309
315
|
for (const cleanup of [...sessionCleanups]) cleanup();
|
|
@@ -326,9 +332,8 @@ export default async function piBrowserAgentExtension(pi: {
|
|
|
326
332
|
attachedBroker = broker;
|
|
327
333
|
};
|
|
328
334
|
|
|
329
|
-
//
|
|
330
|
-
//
|
|
331
|
-
// suite, backed by a lazy handle that re-acquires the broker on every tool
|
|
335
|
+
// Register the full browser_* suite independently of bridge availability,
|
|
336
|
+
// backed by a lazy handle that re-acquires the broker on every tool
|
|
332
337
|
// call. That way a session started while Chrome/the broker was down still
|
|
333
338
|
// gets working tools the moment the browser comes back, with no restart.
|
|
334
339
|
// The handle's task store is used directly by the task tools, so it must be
|
|
@@ -386,7 +391,7 @@ export default async function piBrowserAgentExtension(pi: {
|
|
|
386
391
|
attachedBroker = null;
|
|
387
392
|
});
|
|
388
393
|
|
|
389
|
-
pi.registerTool(createBrowserAgentToolsTool(pi, handle as any));
|
|
394
|
+
pi.registerTool(withNativeResult(createBrowserAgentToolsTool(pi, handle as any)));
|
|
390
395
|
registerAllTools(pi, { broker: handle as any });
|
|
391
396
|
|
|
392
397
|
// Best-effort eager acquisition so the session starts out connected and the
|
|
@@ -403,15 +408,13 @@ export default async function piBrowserAgentExtension(pi: {
|
|
|
403
408
|
observeHealth();
|
|
404
409
|
};
|
|
405
410
|
|
|
406
|
-
// Install once per process so Ctrl+Z releases the broker port instead of
|
|
407
|
-
// freezing it while still bound.
|
|
408
|
-
installSuspendResumeHandlers();
|
|
409
|
-
|
|
410
411
|
pi.on('session_start', async (_event, ctx) => {
|
|
412
|
+
installSuspendResumeHandlers();
|
|
411
413
|
await registerSessionTool(ctx);
|
|
412
414
|
});
|
|
413
415
|
|
|
414
416
|
pi.on('session_shutdown', async (_event, ctx) => {
|
|
417
|
+
removeSignalHandlers?.();
|
|
415
418
|
brokerShuttingDown = true;
|
|
416
419
|
brokerLifecycleGeneration += 1;
|
|
417
420
|
sessionLifecycleGeneration += 1;
|
package/src/tools/_register.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { ExtensionAPI, ToolDefinition } from '@earendil-works/pi-coding-agent';
|
|
2
|
+
import type { TSchema } from 'typebox';
|
|
3
|
+
import { withNativeResult } from './native-result.ts';
|
|
2
4
|
|
|
3
5
|
import type { BrowserAgentBroker } from '../broker/server.ts';
|
|
4
6
|
import {
|
|
@@ -49,9 +51,9 @@ export function getPlaceholderBrowserToolSpecs(): Array<{ name: string; descript
|
|
|
49
51
|
return PLACEHOLDER_TOOL_SPECS.map(([name, description]) => ({ name, description }));
|
|
50
52
|
}
|
|
51
53
|
|
|
52
|
-
export function registerAllTools(pi:
|
|
54
|
+
export function registerAllTools(pi: Pick<ExtensionAPI, 'registerTool'>, { broker }: { broker: BrowserAgentBroker }) {
|
|
53
55
|
const newlyRegistered: string[] = [];
|
|
54
|
-
const realTools = new Map<string,
|
|
56
|
+
const realTools = new Map<string, ToolDefinition<TSchema, Record<string, unknown>>>([
|
|
55
57
|
['browser_run_task', createBrowserRunTaskTool(broker)],
|
|
56
58
|
['browser_get_task_history', createBrowserGetTaskHistoryTool(broker)],
|
|
57
59
|
['browser_list_tasks', createBrowserListTasksTool(broker)],
|
|
@@ -60,27 +62,14 @@ export function registerAllTools(pi: { registerTool: (tool: any) => void }, { br
|
|
|
60
62
|
...createBrowserJsNavigationToolFamily(broker).map((tool) => [tool.name, tool] as const),
|
|
61
63
|
]);
|
|
62
64
|
|
|
63
|
-
for (const [name
|
|
65
|
+
for (const [name] of PLACEHOLDER_TOOL_SPECS) {
|
|
64
66
|
if (registeredToolNames.has(name)) {
|
|
65
67
|
continue;
|
|
66
68
|
}
|
|
67
69
|
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
label: name,
|
|
72
|
-
description: `${description} This tool was expected to be registered but no implementation was found.`,
|
|
73
|
-
promptSnippet: description,
|
|
74
|
-
parameters: Type.Object({}, { additionalProperties: true }),
|
|
75
|
-
async execute() {
|
|
76
|
-
const probe = broker.probeConnectivity();
|
|
77
|
-
return {
|
|
78
|
-
content: [{ type: 'text', text: `${name} is unavailable because its implementation was not registered.` }],
|
|
79
|
-
details: { probe, ok: false, error: { code: 'E_INTERNAL', message: `${name} implementation missing` } },
|
|
80
|
-
};
|
|
81
|
-
},
|
|
82
|
-
},
|
|
83
|
-
);
|
|
70
|
+
const tool = realTools.get(name);
|
|
71
|
+
if (!tool) throw new Error(`${name} implementation missing`);
|
|
72
|
+
pi.registerTool(withNativeResult(tool));
|
|
84
73
|
|
|
85
74
|
registeredToolNames.add(name);
|
|
86
75
|
newlyRegistered.push(name);
|
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
import { Type } from '
|
|
1
|
+
import { Type } from 'typebox';
|
|
2
2
|
|
|
3
3
|
import type { BrowserAgentBroker } from '../broker/server.ts';
|
|
4
4
|
import { formatBridgeFailure } from '../broker/diagnostics.ts';
|
|
5
5
|
import { ABORT_ERROR_CODE } from '../broker/abort.ts';
|
|
6
6
|
import { getPlaceholderBrowserToolSpecs } from './_register.ts';
|
|
7
|
+
import type { ToolResult } from './read_only/common.ts';
|
|
7
8
|
|
|
8
9
|
export function resetBrowserAgentToolState(): void {
|
|
9
10
|
// No-op retained for API compatibility. Browser tool registration is now
|
|
@@ -46,7 +47,7 @@ export function createBrowserAgentToolsTool(
|
|
|
46
47
|
'Diagnose and repair the browser integration. Forces a lazy re-acquire of the broker port (promoting this pi process to primary if the previous owner died) and waits for the Chrome extension bridge to reconnect. Call this whenever a browser_* tool reports E_BRIDGE_DISCONNECTED; it returns the full connectivity state plus recovery steps.',
|
|
47
48
|
promptSnippet: 'Diagnose and repair the browser integration for this session.',
|
|
48
49
|
parameters: Type.Object({}),
|
|
49
|
-
async execute(_toolCallId: string, _params: Record<string, unknown>, signal?: AbortSignal) {
|
|
50
|
+
async execute(_toolCallId: string, _params: Record<string, unknown>, signal?: AbortSignal): Promise<ToolResult> {
|
|
50
51
|
// Lazily (re)acquire the broker so a killed primary is replaced on demand
|
|
51
52
|
// when someone actually asks for the browser tools. Only do this for the
|
|
52
53
|
// lifecycle-managed singleton — never for the throwaway fallback broker,
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { ToolDefinition } from '@earendil-works/pi-coding-agent';
|
|
2
|
+
import { Type, type TSchema } from 'typebox';
|
|
3
|
+
|
|
4
|
+
type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue };
|
|
5
|
+
|
|
6
|
+
function isJsonValue(value: unknown): value is JsonValue {
|
|
7
|
+
if (value === null || typeof value === 'string' || typeof value === 'boolean') return true;
|
|
8
|
+
if (typeof value === 'number') return Number.isFinite(value);
|
|
9
|
+
if (Array.isArray(value)) return value.every(isJsonValue);
|
|
10
|
+
return typeof value === 'object' && Object.values(value).every(isJsonValue);
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Keep legacy rendering/history intact while exposing the same data to SDK callers. */
|
|
14
|
+
export function withNativeResult<TParams extends TSchema>(tool: ToolDefinition<TParams, Record<string, unknown>>): ToolDefinition<TParams, Record<string, unknown>> {
|
|
15
|
+
return {
|
|
16
|
+
...tool,
|
|
17
|
+
outputSchema: Type.Object({}, { additionalProperties: true }),
|
|
18
|
+
async execute(...args) {
|
|
19
|
+
const result = await tool.execute(...args);
|
|
20
|
+
// Details already cross a JSON session boundary. Normalize optional undefined
|
|
21
|
+
// fields exactly as persistence does, without mutating the original details.
|
|
22
|
+
const structuredContent: unknown = JSON.parse(JSON.stringify(result.details));
|
|
23
|
+
if (!isJsonValue(structuredContent)) throw new TypeError('Browser result is not JSON data');
|
|
24
|
+
return {
|
|
25
|
+
...result,
|
|
26
|
+
structuredContent,
|
|
27
|
+
isError: result.isError === true || result.details.ok === false || result.details.success === false,
|
|
28
|
+
};
|
|
29
|
+
},
|
|
30
|
+
};
|
|
31
|
+
}
|
|
@@ -4,7 +4,7 @@ import { mkdir, readdir, rm, stat, writeFile } from 'node:fs/promises';
|
|
|
4
4
|
import { tmpdir } from 'node:os';
|
|
5
5
|
import { join } from 'node:path';
|
|
6
6
|
|
|
7
|
-
import type { TSchema } from '
|
|
7
|
+
import type { TSchema } from 'typebox';
|
|
8
8
|
|
|
9
9
|
import type { BrowserAgentBroker } from '../../broker/server.ts';
|
|
10
10
|
import type { ResponseFrame } from '../../broker/protocol.ts';
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { appendFileSync } from 'node:fs';
|
|
2
|
+
import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
|
|
3
|
+
|
|
4
|
+
export default function observer(pi: ExtensionAPI) {
|
|
5
|
+
const record = (event: string) => {
|
|
6
|
+
appendFileSync(process.env.BA_AUDIT_LOG!, JSON.stringify({
|
|
7
|
+
event,
|
|
8
|
+
suspend: process.listenerCount('SIGTSTP'),
|
|
9
|
+
resume: process.listenerCount('SIGCONT'),
|
|
10
|
+
tools: pi.getAllTools().map((tool) => tool.name)
|
|
11
|
+
.filter((name) => name.startsWith('browser_') || name === 'activate_browser_agent_tools').sort(),
|
|
12
|
+
}) + '\n');
|
|
13
|
+
};
|
|
14
|
+
pi.on('session_start', () => record('start'));
|
|
15
|
+
pi.on('session_shutdown', () => record('shutdown'));
|
|
16
|
+
pi.registerCommand('audit-reload', {
|
|
17
|
+
description: 'Reload the real extension runtime for the compatibility test',
|
|
18
|
+
handler: async (_args, ctx) => { await ctx.reload(); },
|
|
19
|
+
});
|
|
20
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import test from 'node:test';
|
|
3
|
+
import { Type, type TSchema } from 'typebox';
|
|
4
|
+
import { mkdtemp, rm } from 'node:fs/promises';
|
|
5
|
+
import { tmpdir } from 'node:os';
|
|
6
|
+
import { join } from 'node:path';
|
|
7
|
+
import { TaskStore } from '../src/broker/task-store.ts';
|
|
8
|
+
import { Value } from 'typebox/value';
|
|
9
|
+
import { withNativeResult } from '../src/tools/native-result.ts';
|
|
10
|
+
import { registerAllTools, resetRegisteredBrowserTools } from '../src/tools/_register.ts';
|
|
11
|
+
import { BrowserAgentBroker } from '../src/broker/server.ts';
|
|
12
|
+
|
|
13
|
+
for (const details of [
|
|
14
|
+
{ ok: true, tabs: [{ id: 17 }], optional: undefined },
|
|
15
|
+
{ ok: false, error: { code: 'E_BRIDGE_DISCONNECTED', message: 'offline' } },
|
|
16
|
+
{ ok: true, success: false, status: 'rejected' },
|
|
17
|
+
{ success: true, status: 'done', history: [{ type: 'started' }, { type: 'finished' }] },
|
|
18
|
+
]) {
|
|
19
|
+
test(`native result preserves content/details and reports ${JSON.stringify(details)}`, async () => {
|
|
20
|
+
const content = [{ type: 'text' as const, text: 'legacy output' },
|
|
21
|
+
{ type: 'image' as const, data: 'c2VudGluZWw=', mimeType: 'image/png' }];
|
|
22
|
+
const tool = withNativeResult({ name: 'sentinel', label: 'sentinel', description: 'sentinel',
|
|
23
|
+
parameters: Type.Object({}), async execute() { return { content, details }; } });
|
|
24
|
+
// execute's context is unused by this fixture, just like existing browser builders.
|
|
25
|
+
const result = await Reflect.apply(tool.execute, undefined, ['call', {}, undefined]);
|
|
26
|
+
assert.equal(result.content, content);
|
|
27
|
+
assert.equal(result.details, details);
|
|
28
|
+
assert.deepEqual(result.structuredContent, JSON.parse(JSON.stringify(details)));
|
|
29
|
+
assert.equal(result.isError, details.ok === false || details.success === false);
|
|
30
|
+
assert.ok(tool.outputSchema && Value.Check(tool.outputSchema, result.structuredContent));
|
|
31
|
+
assert.equal(Object.hasOwn(details, 'optional'), Object.hasOwn(result.details, 'optional'));
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
test('native result forwards cancellation, updates and context and preserves explicit errors', async () => {
|
|
36
|
+
let received: unknown[] = [];
|
|
37
|
+
const tool = withNativeResult({ name: 'forward', label: 'forward', description: 'forward',
|
|
38
|
+
parameters: Type.Object({}), async execute(...args) {
|
|
39
|
+
received = args;
|
|
40
|
+
return { content: [{ type: 'text', text: 'error' }], details: {}, isError: true };
|
|
41
|
+
} });
|
|
42
|
+
const controller = new AbortController();
|
|
43
|
+
const update = () => {};
|
|
44
|
+
const context = { sentinel: 'context' };
|
|
45
|
+
const args = ['call', {}, controller.signal, update, context];
|
|
46
|
+
const result = await Reflect.apply(tool.execute, undefined, args);
|
|
47
|
+
assert.deepEqual(received, args);
|
|
48
|
+
assert.equal(result.isError, true);
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
test('every registered browser implementation declares native output and preserves offline diagnostics', async () => {
|
|
52
|
+
resetRegisteredBrowserTools();
|
|
53
|
+
const tools: { name: string; outputSchema?: TSchema; execute: unknown }[] = [];
|
|
54
|
+
const dir = await mkdtemp(join(tmpdir(), 'ba-native-result-'));
|
|
55
|
+
const broker = new BrowserAgentBroker({ port: 0, taskStore: new TaskStore({ dir }) });
|
|
56
|
+
try {
|
|
57
|
+
registerAllTools({ registerTool(tool) { tools.push(tool); } }, { broker });
|
|
58
|
+
assert.equal(tools.length, 22);
|
|
59
|
+
assert.ok(tools.every((tool) => tool.outputSchema), 'no family may miss the registration adapter');
|
|
60
|
+
for (const name of ['browser_list_tabs', 'browser_get_html', 'browser_get_console_logs', 'browser_run_task']) {
|
|
61
|
+
const tool = tools.find((item) => item.name === name);
|
|
62
|
+
assert.ok(tool && typeof tool.execute === 'function');
|
|
63
|
+
const result = await Reflect.apply(tool.execute, undefined, ['call', { task: 'sentinel' }, undefined]);
|
|
64
|
+
assert.equal(result.isError, true, name);
|
|
65
|
+
assert.deepEqual(result.structuredContent, JSON.parse(JSON.stringify(result.details)), name);
|
|
66
|
+
assert.match(JSON.stringify(result.content), /bridge|broker/i);
|
|
67
|
+
}
|
|
68
|
+
} finally {
|
|
69
|
+
await broker.stop();
|
|
70
|
+
resetRegisteredBrowserTools();
|
|
71
|
+
await rm(dir, { recursive: true, force: true });
|
|
72
|
+
}
|
|
73
|
+
});
|
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { spawn } from 'node:child_process';
|
|
3
|
+
import { once } from 'node:events';
|
|
4
|
+
import { readFileSync } from 'node:fs';
|
|
5
|
+
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
|
|
6
|
+
import { createServer } from 'node:http';
|
|
7
|
+
import { createServer as createTcpServer } from 'node:net';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import test from 'node:test';
|
|
10
|
+
import { fileURLToPath } from 'node:url';
|
|
11
|
+
import WebSocket from 'ws';
|
|
12
|
+
|
|
13
|
+
const root = fileURLToPath(new URL('../', import.meta.url));
|
|
14
|
+
const names = ['activate_browser_agent_tools', 'browser_run_task', 'browser_get_task_history',
|
|
15
|
+
'browser_list_tasks', 'browser_get_screenshot', 'browser_get_html', 'browser_get_dom_info',
|
|
16
|
+
'browser_get_computed_styles', 'browser_get_console_logs', 'browser_get_network',
|
|
17
|
+
'browser_get_accessibility_tree', 'browser_get_performance_metrics', 'browser_evaluate_js',
|
|
18
|
+
'browser_run_js', 'browser_create_tab', 'browser_list_tabs', 'browser_switch_tab',
|
|
19
|
+
'browser_close_tab', 'browser_navigate', 'browser_reload', 'browser_reload_extension',
|
|
20
|
+
'browser_wait_for', 'browser_clear_site_data'].sort();
|
|
21
|
+
|
|
22
|
+
type WireRequest = { model: string; tools?: { function: { name: string } }[];
|
|
23
|
+
messages: { role: string; content?: unknown }[] };
|
|
24
|
+
type RecordValue = Record<string, unknown>;
|
|
25
|
+
function object(value: unknown): RecordValue {
|
|
26
|
+
assert.ok(value && typeof value === 'object' && !Array.isArray(value));
|
|
27
|
+
return value as RecordValue;
|
|
28
|
+
}
|
|
29
|
+
async function freePort() {
|
|
30
|
+
const server = createTcpServer().listen(0, '127.0.0.1');
|
|
31
|
+
await once(server, 'listening');
|
|
32
|
+
const address = server.address();
|
|
33
|
+
assert.ok(address && typeof address !== 'string');
|
|
34
|
+
await new Promise<void>((resolve) => server.close(() => resolve()));
|
|
35
|
+
return address.port;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
test('real Pi CLI preserves browser declarations, execution, history and cleanup across turns, compaction and reload',
|
|
39
|
+
{ timeout: 90_000 }, async () => {
|
|
40
|
+
const piBin = process.env.PI_EVERGREEN_PI_BIN;
|
|
41
|
+
assert.ok(piBin, 'PI_EVERGREEN_PI_BIN must identify the installed global Pi executable');
|
|
42
|
+
await mkdir(path.join(root, 'tmp'), { recursive: true });
|
|
43
|
+
const dir = await mkdtemp(path.join(root, 'tmp/cli-audit-'));
|
|
44
|
+
const agent = path.join(dir, 'agent');
|
|
45
|
+
await mkdir(agent);
|
|
46
|
+
const provider = process.env.PI_EVERGREEN_E2E_PROVIDER ?? 'openai';
|
|
47
|
+
const model = process.env.PI_EVERGREEN_E2E_MODEL ?? 'gpt-6-luna';
|
|
48
|
+
const reasoning = process.env.PI_EVERGREEN_E2E_REASONING ?? 'medium';
|
|
49
|
+
// No live intelligence is needed: use Pi's real OpenAI transport against a
|
|
50
|
+
// local SSE endpoint. The captured bytes are actual provider-bound requests.
|
|
51
|
+
const requests: WireRequest[] = [];
|
|
52
|
+
let selectedTool = 'browser_list_tasks';
|
|
53
|
+
let selectedParams: RecordValue = {};
|
|
54
|
+
let failNextRequest = false;
|
|
55
|
+
let holdBridgeResponse = false;
|
|
56
|
+
let rejectBridgeResponse = false;
|
|
57
|
+
let bridgeCalls = 0;
|
|
58
|
+
const endpoint = createServer(async (req, res) => {
|
|
59
|
+
let raw = '';
|
|
60
|
+
for await (const chunk of req) raw += chunk;
|
|
61
|
+
const body: WireRequest = JSON.parse(raw);
|
|
62
|
+
requests.push(body);
|
|
63
|
+
if (failNextRequest) {
|
|
64
|
+
failNextRequest = false;
|
|
65
|
+
res.writeHead(503, { 'content-type': 'application/json' });
|
|
66
|
+
res.end(JSON.stringify({ error: { message: 'AUDIT_RETRY_SENTINEL', type: 'server_error' } }));
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
const tool = body.tools?.some((item) => item.function.name === selectedTool)
|
|
70
|
+
&& body.messages.at(-1)?.role !== 'tool';
|
|
71
|
+
res.writeHead(200, { 'content-type': 'text/event-stream' });
|
|
72
|
+
const delta = tool ? { tool_calls: [{ index: 0, id: `audit_${requests.length}`,
|
|
73
|
+
type: 'function', function: { name: selectedTool, arguments: JSON.stringify(selectedParams) } }] }
|
|
74
|
+
: { content: 'AUDIT_SUMMARY: browser tools remain available.' };
|
|
75
|
+
const chunk = (data: unknown) => res.write(`data: ${JSON.stringify(data)}\n\n`);
|
|
76
|
+
chunk({ id: 'audit', object: 'chat.completion.chunk', model, created: 1,
|
|
77
|
+
choices: [{ index: 0, delta: { role: 'assistant', ...delta }, finish_reason: null }] });
|
|
78
|
+
chunk({ id: 'audit', object: 'chat.completion.chunk', model, created: 1,
|
|
79
|
+
choices: [{ index: 0, delta: {}, finish_reason: tool ? 'tool_calls' : 'stop' }],
|
|
80
|
+
usage: { prompt_tokens: 20, completion_tokens: 5, total_tokens: 25 } });
|
|
81
|
+
res.end('data: [DONE]\n\n');
|
|
82
|
+
}).listen(0, '127.0.0.1');
|
|
83
|
+
await once(endpoint, 'listening');
|
|
84
|
+
const address = endpoint.address();
|
|
85
|
+
assert.ok(address && typeof address !== 'string');
|
|
86
|
+
await writeFile(path.join(agent, 'models.json'), JSON.stringify({ providers: {
|
|
87
|
+
[provider]: { baseUrl: `http://127.0.0.1:${address.port}/v1`, api: 'openai-completions',
|
|
88
|
+
apiKey: 'harmless-local-sentinel', models: [{ id: model, reasoning: true,
|
|
89
|
+
contextWindow: 128000, maxTokens: 128 }] },
|
|
90
|
+
} }));
|
|
91
|
+
await writeFile(path.join(agent, 'settings.json'), JSON.stringify({
|
|
92
|
+
compaction: { keepRecentTokens: 1 }, retry: { enabled: true, maxRetries: 1, baseDelayMs: 1 },
|
|
93
|
+
}));
|
|
94
|
+
const port = await freePort();
|
|
95
|
+
const auditLog = path.join(dir, 'lifecycle.jsonl');
|
|
96
|
+
const child = spawn(piBin, ['--mode', 'rpc', '--offline', '--no-extensions', '--no-mcp',
|
|
97
|
+
'--no-skills', '--no-prompt-templates', '--no-context-files', '--no-builtin-tools',
|
|
98
|
+
'--provider', provider, '--model', model, '--thinking', reasoning,
|
|
99
|
+
'--session-dir', path.join(dir, 'sessions'), '-e', path.join(root, 'src/index.ts'),
|
|
100
|
+
'-e', path.join(root, 'tests/fixtures/lifecycle-observer.ts')], {
|
|
101
|
+
cwd: root, env: { PATH: process.env.PATH, HOME: dir, PI_CODING_AGENT_DIR: agent,
|
|
102
|
+
PI_OFFLINE: '1', PI_TELEMETRY: '0', XDG_STATE_HOME: dir,
|
|
103
|
+
PI_BA_PORT: String(port), BA_AUDIT_LOG: auditLog },
|
|
104
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
105
|
+
});
|
|
106
|
+
const events: RecordValue[] = [];
|
|
107
|
+
let stderr = '', buffer = '';
|
|
108
|
+
child.stderr.on('data', (chunk) => { stderr += chunk; });
|
|
109
|
+
child.stdout.on('data', (chunk) => {
|
|
110
|
+
buffer += chunk;
|
|
111
|
+
let end: number;
|
|
112
|
+
while ((end = buffer.indexOf('\n')) >= 0) {
|
|
113
|
+
const line = buffer.slice(0, end); buffer = buffer.slice(end + 1);
|
|
114
|
+
if (line.trim()) events.push(object(JSON.parse(line)));
|
|
115
|
+
}
|
|
116
|
+
});
|
|
117
|
+
let bridge: WebSocket | undefined;
|
|
118
|
+
async function waitFor(predicate: () => boolean) {
|
|
119
|
+
const deadline = Date.now() + 20_000;
|
|
120
|
+
while (!predicate()) {
|
|
121
|
+
assert.equal(child.exitCode, null, stderr);
|
|
122
|
+
assert.ok(Date.now() < deadline, `CLI timeout: ${stderr}\n${JSON.stringify(events.slice(-4))}`);
|
|
123
|
+
await new Promise((resolve) => setTimeout(resolve, 20));
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
let sequence = 0;
|
|
127
|
+
async function command(type: string, fields: RecordValue = {}) {
|
|
128
|
+
const id = String(++sequence);
|
|
129
|
+
child.stdin.write(JSON.stringify({ type, id, ...fields }) + '\n');
|
|
130
|
+
await waitFor(() => events.some((event) => event.id === id));
|
|
131
|
+
const response = events.find((event) => event.id === id)!;
|
|
132
|
+
assert.equal(response.success, true, JSON.stringify(response));
|
|
133
|
+
return object(response.data ?? {});
|
|
134
|
+
}
|
|
135
|
+
async function prompt(message: string) {
|
|
136
|
+
const start = events.length;
|
|
137
|
+
const firstRequest = requests.length;
|
|
138
|
+
await command('prompt', { message });
|
|
139
|
+
await waitFor(() => events.slice(start).some((event) => event.type === 'agent_settled'));
|
|
140
|
+
const outbound = requests.slice(firstRequest);
|
|
141
|
+
assert.ok(outbound.length >= 2, 'each prompt must execute a browser tool and send its result');
|
|
142
|
+
outbound.forEach(declarations);
|
|
143
|
+
}
|
|
144
|
+
const declarations = (body: WireRequest) => {
|
|
145
|
+
assert.deepEqual(body.tools?.map((item) => item.function.name).sort(), names);
|
|
146
|
+
assert.equal(body.model, model);
|
|
147
|
+
};
|
|
148
|
+
try {
|
|
149
|
+
await command('get_state');
|
|
150
|
+
await prompt('AUDIT_FIRST: list stored browser tasks.');
|
|
151
|
+
assert.ok(requests.length >= 2, 'must observe tool call and follow-up HTTP requests');
|
|
152
|
+
requests.forEach(declarations);
|
|
153
|
+
// Negative control proves the assertion rejects a missing browser tool.
|
|
154
|
+
assert.throws(() => declarations({ ...requests[0], tools: requests[0].tools?.slice(1) }));
|
|
155
|
+
assert.ok(JSON.stringify(requests.at(-1)).includes('AUDIT_FIRST'));
|
|
156
|
+
if (process.platform === 'linux') {
|
|
157
|
+
// Pi and this extension both participate in job control. Verify the real
|
|
158
|
+
// process stops only after releasing the listener, then reacquires it.
|
|
159
|
+
child.kill('SIGTSTP');
|
|
160
|
+
await waitFor(() => /^State:\s+T/m.test(readFileSync(`/proc/${child.pid}/status`, 'utf8')));
|
|
161
|
+
const released = createTcpServer().listen(port, '127.0.0.1');
|
|
162
|
+
await once(released, 'listening');
|
|
163
|
+
await new Promise<void>((resolve) => released.close(() => resolve()));
|
|
164
|
+
child.kill('SIGCONT');
|
|
165
|
+
await command('get_state');
|
|
166
|
+
}
|
|
167
|
+
selectedTool = 'browser_list_tabs';
|
|
168
|
+
bridge = new WebSocket(`ws://127.0.0.1:${port}`);
|
|
169
|
+
await once(bridge, 'open');
|
|
170
|
+
bridge.on('message', (raw) => {
|
|
171
|
+
const frame = object(JSON.parse(raw.toString()));
|
|
172
|
+
if (frame.kind === 'request') {
|
|
173
|
+
assert.ok(frame.type === 'browser_list_tabs' || frame.type === 'browser_run_task');
|
|
174
|
+
bridgeCalls += 1;
|
|
175
|
+
if (holdBridgeResponse) return;
|
|
176
|
+
if (rejectBridgeResponse) {
|
|
177
|
+
bridge!.send(JSON.stringify({ v: 1, kind: 'response', id: frame.id, ok: false,
|
|
178
|
+
error: { code: 'E_RUNTIME', message: 'BRIDGE_FAILURE_SENTINEL' } }));
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
bridge!.send(JSON.stringify({ v: 1, kind: 'response', id: frame.id, ok: true,
|
|
182
|
+
data: frame.type === 'browser_run_task'
|
|
183
|
+
? { status: 'done', message: 'TASK_SENTINEL' }
|
|
184
|
+
: { tabs: [{ id: 17, title: 'BRIDGE_SENTINEL', url: 'https://example.invalid' }] } }));
|
|
185
|
+
}
|
|
186
|
+
});
|
|
187
|
+
bridge.send(JSON.stringify({ v: 1, kind: 'hello', extensionId: 'audit', version: '1', capabilities: [] }));
|
|
188
|
+
failNextRequest = true;
|
|
189
|
+
const retryStart = requests.length;
|
|
190
|
+
await prompt('AUDIT_SECOND: list browser tabs.');
|
|
191
|
+
assert.ok(requests.length >= retryStart + 3, '503 must cause a real provider retry before tool execution');
|
|
192
|
+
assert.ok(events.some((event) => event.type === 'auto_retry_start'), 'Pi must report the retry');
|
|
193
|
+
assert.ok(JSON.stringify(requests.at(-1)).includes('BRIDGE_SENTINEL'), 'bridge result must reach real next request');
|
|
194
|
+
const beforeFailure = events.length;
|
|
195
|
+
rejectBridgeResponse = true;
|
|
196
|
+
await prompt('AUDIT_BRIDGE_FAILURE');
|
|
197
|
+
const failed = events.slice(beforeFailure).find((event) => event.type === 'tool_execution_end');
|
|
198
|
+
assert.ok(failed);
|
|
199
|
+
assert.equal(failed.isError, true, 'Pi must classify returned bridge failures as errors');
|
|
200
|
+
const failedResult = object(failed.result);
|
|
201
|
+
assert.deepEqual(failedResult.structuredContent, failedResult.details);
|
|
202
|
+
assert.match(JSON.stringify(requests.at(-1)), /BRIDGE_FAILURE_SENTINEL/);
|
|
203
|
+
rejectBridgeResponse = false;
|
|
204
|
+
// Cancellation must reach execute's third argument, unwind the pending
|
|
205
|
+
// bridge request, persist a cancelled tool result and permit another turn.
|
|
206
|
+
holdBridgeResponse = true;
|
|
207
|
+
const beforeAbort = events.length;
|
|
208
|
+
const beforeBridge = bridgeCalls;
|
|
209
|
+
await command('prompt', { message: 'AUDIT_ABORT: list browser tabs.' });
|
|
210
|
+
await waitFor(() => bridgeCalls > beforeBridge);
|
|
211
|
+
await command('abort');
|
|
212
|
+
await waitFor(() => events.slice(beforeAbort).some((event) => event.type === 'agent_settled'));
|
|
213
|
+
const abortedResult = events.slice(beforeAbort).find((event) => event.type === 'tool_execution_end');
|
|
214
|
+
assert.ok(abortedResult, 'real Pi execution must finish on cancellation');
|
|
215
|
+
assert.match(JSON.stringify(abortedResult), /cancel|abort/i);
|
|
216
|
+
holdBridgeResponse = false;
|
|
217
|
+
await prompt('AUDIT_RECOVER_AFTER_ABORT');
|
|
218
|
+
assert.ok(JSON.stringify(requests.at(-1)).includes('BRIDGE_SENTINEL'));
|
|
219
|
+
selectedTool = 'browser_run_task';
|
|
220
|
+
selectedParams = { task: 'TASK_INTENT_SENTINEL' };
|
|
221
|
+
const beforeTask = events.length;
|
|
222
|
+
await prompt('AUDIT_RUN_TASK');
|
|
223
|
+
const taskEnd = events.slice(beforeTask).find((event) => event.type === 'tool_execution_end');
|
|
224
|
+
const taskDetails = object(object(taskEnd?.result).details);
|
|
225
|
+
assert.equal(taskDetails.success, true);
|
|
226
|
+
assert.equal(taskDetails.status, 'done');
|
|
227
|
+
assert.equal(taskEnd?.isError, false);
|
|
228
|
+
assert.deepEqual(object(taskEnd?.result).structuredContent, taskDetails,
|
|
229
|
+
'native structured results must retain task history without replacing legacy details');
|
|
230
|
+
const taskId = taskDetails.taskId;
|
|
231
|
+
assert.equal(typeof taskId, 'string');
|
|
232
|
+
selectedTool = 'browser_list_tabs';
|
|
233
|
+
selectedParams = {};
|
|
234
|
+
const state = await command('get_state');
|
|
235
|
+
const session = await readFile(String(state.sessionFile), 'utf8');
|
|
236
|
+
assert.match(session, /BRIDGE_SENTINEL/);
|
|
237
|
+
assert.match(session, /browser_list_tasks/);
|
|
238
|
+
const persisted = session.trim().split('\n').map((line) => object(JSON.parse(line)));
|
|
239
|
+
const failedMessage = persisted.map((entry) => entry.message).find((message) =>
|
|
240
|
+
message && typeof message === 'object' && 'role' in message && message.role === 'toolResult'
|
|
241
|
+
&& JSON.stringify(message).includes('BRIDGE_FAILURE_SENTINEL'));
|
|
242
|
+
assert.ok(failedMessage, 'error content and legacy details must survive session serialization');
|
|
243
|
+
assert.equal(object(failedMessage).isError, true);
|
|
244
|
+
assert.deepEqual(object(failedMessage).details, failedResult.details);
|
|
245
|
+
await command('compact', { customInstructions: 'Keep audit sentinels.' });
|
|
246
|
+
await prompt('AUDIT_AFTER_COMPACTION');
|
|
247
|
+
// Reload must work on its own: a subsequent new_session could otherwise
|
|
248
|
+
// conceal a broken replacement tool closure or missing declarations.
|
|
249
|
+
await command('prompt', { message: '/audit-reload' });
|
|
250
|
+
selectedTool = 'browser_list_tasks';
|
|
251
|
+
await prompt('AUDIT_AFTER_RELOAD');
|
|
252
|
+
await command('get_state');
|
|
253
|
+
await command('new_session');
|
|
254
|
+
selectedTool = 'browser_get_task_history';
|
|
255
|
+
selectedParams = { taskId };
|
|
256
|
+
await prompt('AUDIT_NEW_SESSION');
|
|
257
|
+
assert.match(JSON.stringify(requests.at(-1)), /Loaded 2 history event/,
|
|
258
|
+
'browser task history must survive compaction, reload and new_session');
|
|
259
|
+
requests.filter((body) => body.tools?.length).forEach(declarations);
|
|
260
|
+
const lifecycle = (await readFile(auditLog, 'utf8')).trim().split('\n').map((line) => object(JSON.parse(line)));
|
|
261
|
+
const starts = lifecycle.filter((row) => row.event === 'start');
|
|
262
|
+
assert.ok(starts.length >= 3, 'initial, reload and new-session startup must run');
|
|
263
|
+
for (const row of starts) {
|
|
264
|
+
assert.equal(row.suspend, starts[0].suspend, 'reload must not accumulate SIGTSTP handlers');
|
|
265
|
+
assert.equal(row.resume, starts[0].resume, 'reload must not accumulate SIGCONT handlers');
|
|
266
|
+
assert.deepEqual(row.tools, names);
|
|
267
|
+
}
|
|
268
|
+
for (const row of lifecycle.filter((row) => row.event === 'shutdown')) {
|
|
269
|
+
assert.equal(row.suspend, Number(starts[0].suspend) - 1);
|
|
270
|
+
assert.equal(row.resume, Number(starts[0].resume) - 1);
|
|
271
|
+
}
|
|
272
|
+
bridge.close();
|
|
273
|
+
const exit = once(child, 'exit');
|
|
274
|
+
child.stdin.end();
|
|
275
|
+
await exit;
|
|
276
|
+
assert.equal(child.exitCode, 0, stderr);
|
|
277
|
+
const probe = createTcpServer().listen(port, '127.0.0.1');
|
|
278
|
+
await once(probe, 'listening');
|
|
279
|
+
await new Promise<void>((resolve) => probe.close(() => resolve()));
|
|
280
|
+
} finally {
|
|
281
|
+
bridge?.terminate();
|
|
282
|
+
if (child.exitCode === null) child.kill('SIGKILL');
|
|
283
|
+
endpoint.closeAllConnections();
|
|
284
|
+
await new Promise<void>((resolve) => endpoint.close(() => resolve()));
|
|
285
|
+
await rm(dir, { recursive: true, force: true });
|
|
286
|
+
}
|
|
287
|
+
});
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { mkdir, mkdtemp, rm } from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import test from 'node:test';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { discoverAndLoadExtensions, VERSION } from '@earendil-works/pi-coding-agent';
|
|
7
|
+
|
|
8
|
+
const root = fileURLToPath(new URL('../', import.meta.url));
|
|
9
|
+
|
|
10
|
+
test('the installed Pi host loads the browser extension and registers its lifecycle handlers', async () => {
|
|
11
|
+
const tempRoot = path.join(root, 'tmp');
|
|
12
|
+
await mkdir(tempRoot, { recursive: true });
|
|
13
|
+
const agentDir = await mkdtemp(path.join(tempRoot, 'pi-compatibility-'));
|
|
14
|
+
try {
|
|
15
|
+
const result = await discoverAndLoadExtensions(
|
|
16
|
+
[path.join(root, 'src/index.ts')],
|
|
17
|
+
root,
|
|
18
|
+
agentDir,
|
|
19
|
+
);
|
|
20
|
+
assert.deepEqual(result.errors, [], `Pi ${VERSION} must load the extension without errors`);
|
|
21
|
+
assert.equal(result.extensions.length, 1);
|
|
22
|
+
const extension = result.extensions[0];
|
|
23
|
+
assert.equal(extension.handlers.get('session_start')?.length, 1);
|
|
24
|
+
assert.equal(extension.handlers.get('session_shutdown')?.length, 1);
|
|
25
|
+
} finally {
|
|
26
|
+
await rm(agentDir, { recursive: true, force: true });
|
|
27
|
+
}
|
|
28
|
+
});
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { once } from 'node:events';
|
|
3
|
+
import { mkdir, mkdtemp, rm } from 'node:fs/promises';
|
|
4
|
+
import { createServer } from 'node:net';
|
|
5
|
+
import test from 'node:test';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
import { BrowserAgentBroker } from '../src/broker/server.ts';
|
|
8
|
+
import { TaskStore } from '../src/broker/task-store.ts';
|
|
9
|
+
|
|
10
|
+
test('broker rejects non-WebSocket HTTP requests and releases keep-alive transports on shutdown',
|
|
11
|
+
{ timeout: 5_000 }, async () => {
|
|
12
|
+
await mkdir(new URL('../tmp/', import.meta.url), { recursive: true });
|
|
13
|
+
const dir = await mkdtemp(fileURLToPath(new URL('../tmp/http-shutdown-', import.meta.url)));
|
|
14
|
+
const broker = new BrowserAgentBroker({ port: 0, taskStore: new TaskStore({ dir }) });
|
|
15
|
+
try {
|
|
16
|
+
await broker.start();
|
|
17
|
+
const response = await fetch(`http://127.0.0.1:${broker.port}`);
|
|
18
|
+
assert.equal(response.status, 426);
|
|
19
|
+
assert.equal(await response.text(), 'Upgrade Required');
|
|
20
|
+
await broker.stop();
|
|
21
|
+
const replacement = createServer().listen(broker.port, '127.0.0.1');
|
|
22
|
+
await once(replacement, 'listening');
|
|
23
|
+
await new Promise<void>((resolve) => replacement.close(() => resolve()));
|
|
24
|
+
} finally {
|
|
25
|
+
await broker.stop();
|
|
26
|
+
await rm(dir, { recursive: true, force: true });
|
|
27
|
+
}
|
|
28
|
+
});
|