oira666_pi-browser-agent 0.0.19 → 0.0.21
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 +17 -0
- package/EVERGREEN.md +60 -0
- package/README.md +16 -2
- package/package.json +11 -4
- package/src/broker/lazy.ts +3 -6
- package/src/broker/protocol.ts +2 -3
- package/src/broker/remote.ts +2 -2
- 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/integration/intent.test.ts +270 -0
- package/tests/native-result.test.ts +73 -0
- package/tests/pi-cli.e2e.ts +182 -0
- package/tests/pi-compatibility.test.ts +28 -0
- package/tests/remote-socket-errors.test.ts +69 -0
- package/tests/server-shutdown.test.ts +28 -0
package/AGENTS.md
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
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.
|
|
17
|
+
- Make it as simple as possible without losing reliability and quality. Ask yourself: is there a simpler, more natural solution?
|
package/EVERGREEN.md
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
## Summary
|
|
2
|
+
- Bridge Pi browser tools to Chrome's `browser-agent-ext`; do not synthesize input locally.
|
|
3
|
+
- Register the whole toolkit even when Chrome or broker startup is unavailable.
|
|
4
|
+
- Share one primary broker across Pi processes, recover quietly, and retain task history.
|
|
5
|
+
- Pi touchpoints: extension entry point, session lifecycle, tools/results and UI status.
|
|
6
|
+
- No internal or undocumented Pi APIs are used by runtime code.
|
|
7
|
+
- Main risks: bridge protocol drift, lifecycle races, model/tool schema changes and payload size.
|
|
8
|
+
|
|
9
|
+
## Intent
|
|
10
|
+
Provide browser automation and inspection from Pi without making every Pi process
|
|
11
|
+
own a Chrome connection. The primary forwards operations to the external browser
|
|
12
|
+
extension; secondaries proxy through it and can promote after it exits. Lazy tool
|
|
13
|
+
handles recover without requiring a session restart. Task history lives outside
|
|
14
|
+
Pi sessions so it remains inspectable after session or process replacement.
|
|
15
|
+
Disconnected startup must not hide tools or flood the TUI with logs.
|
|
16
|
+
|
|
17
|
+
## Pi integration (public APIs)
|
|
18
|
+
`package.json` loads `src/index.ts` through `pi.extensions`. Runtime imports the
|
|
19
|
+
public `ExtensionAPI` and `ToolDefinition` types from the package root.
|
|
20
|
+
`pi.on('session_start')` registers tools and acquires the broker;
|
|
21
|
+
`session_shutdown` releases sockets, timers, handles and signal listeners.
|
|
22
|
+
`pi.registerTool` uses TypeBox parameters, execute's AbortSignal, text/image
|
|
23
|
+
content, persisted details, outputSchema, structuredContent and isError.
|
|
24
|
+
`ctx.ui.setStatus` and `notify` report connectivity with delayed outage warnings.
|
|
25
|
+
The host TypeBox peer dependency must remain compatible with Pi's validator.
|
|
26
|
+
## Internal Pi APIs
|
|
27
|
+
None in runtime code: no deep imports, private fields or undocumented Pi hooks.
|
|
28
|
+
The compatibility test uses the exported `discoverAndLoadExtensions` loader.
|
|
29
|
+
POSIX suspend/resume handlers and the WebSocket protocol are extension-owned,
|
|
30
|
+
not Pi APIs. Historical commits mentioning internal image shapes now correspond
|
|
31
|
+
to Pi's public image content contract.
|
|
32
|
+
|
|
33
|
+
## Weak points
|
|
34
|
+
Chrome/MV3 connection lifetime, hello/probe/proxy compatibility and primary
|
|
35
|
+
promotion are external boundaries. Shutdown, suspend and reload can race startup.
|
|
36
|
+
Image/text limits, spilled files and JSON normalization must preserve usable output.
|
|
37
|
+
Real Chrome/input-backend behavior is not covered by the automated bridge fixture.
|
|
38
|
+
CLI E2E uses stdin-ignored JSON runs, not interactive reload/compaction or RPC abort;
|
|
39
|
+
unit/lifecycle tests cover those underlying broker cancellation and teardown paths.
|
|
40
|
+
Live E2E needs credentials for EVERGREEN_E2E_MODEL and may fail on provider outages.
|
|
41
|
+
|
|
42
|
+
## Tests
|
|
43
|
+
`npm run test:evergreen` runs typechecking, unit, integration and E2E checks.
|
|
44
|
+
Existing unit suites cover readiness/recovery, cancellation, health warnings,
|
|
45
|
+
promotion, shutdown races, schemas, screenshot output and truncation.
|
|
46
|
+
`tests/integration/intent.test.ts` protects task execution through the real proxy,
|
|
47
|
+
primary and bridge chain, failure classification and history after store restart.
|
|
48
|
+
`tests/pi-cli.e2e.ts` runs EVERGREEN_PI_BIN (fallback: pi on PATH), stdin ignored.
|
|
49
|
+
A local SSE fixture checks all declarations in provider-bound requests, actual
|
|
50
|
+
bridge task execution, result/error persistence, cross-process history and cleanup.
|
|
51
|
+
A live EVERGREEN_E2E_MODEL call must discover and execute browser_list_tasks even
|
|
52
|
+
without Chrome. Settings/state are isolated; provider credentials are reused.
|
|
53
|
+
These tests protect available tools, working forwarding and durable inspection,
|
|
54
|
+
not merely individual helper outputs. Tested against latest Pi 1.4.0.
|
|
55
|
+
|
|
56
|
+
## Relevant changelog topics
|
|
57
|
+
Watch extension lifecycle/reload, tool registration and execution signatures,
|
|
58
|
+
AbortSignal propagation, TypeBox validation, text/image result formats,
|
|
59
|
+
outputSchema/structuredContent/isError, session serialization, UI status APIs,
|
|
60
|
+
CLI JSON events, provider transport and SDK extension loading.
|
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
|
+
Run `EVERGREEN_E2E_MODEL=provider/model npm run test:evergreen` for typechecking, unit, integration and E2E checks. E2E runs the globally installed `$EVERGREEN_PI_BIN` (or `pi` on PATH), with stdin ignored and isolated settings/state. A deterministic local SSE endpoint and WebSocket bridge fixture check full tool declarations, task forwarding, error classification, session persistence, history across process restarts and listener cleanup. A live call using `$EVERGREEN_E2E_MODEL` checks model discovery and use of local browser history without Chrome; it uses your provider credentials and incurs model usage. Integration tests exercise task tools through the primary/secondary broker chain. These tests do not replace a live Chrome check; see [EVERGREEN.md](EVERGREEN.md) for scope and weak points.
|
|
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.21",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "Pi browser agent broker skeleton with lazy browser tool registration",
|
|
@@ -14,18 +14,25 @@
|
|
|
14
14
|
]
|
|
15
15
|
},
|
|
16
16
|
"scripts": {
|
|
17
|
-
"
|
|
17
|
+
"typecheck": "tsc --noEmit",
|
|
18
|
+
"pretest": "npm run typecheck",
|
|
19
|
+
"test": "node --test --test-concurrency=1 ./tests/*.test.ts ./tests/tools/*.test.ts",
|
|
20
|
+
"test:integration": "node --test ./tests/integration/*.test.ts",
|
|
21
|
+
"test:e2e": "node --test ./tests/pi-cli.e2e.ts",
|
|
22
|
+
"test:evergreen": "npm test && npm run test:integration && npm run test:e2e"
|
|
18
23
|
},
|
|
19
24
|
"dependencies": {
|
|
20
25
|
"ws": "^8.18.3"
|
|
21
26
|
},
|
|
22
27
|
"peerDependencies": {
|
|
23
|
-
"@
|
|
28
|
+
"@earendil-works/pi-coding-agent": ">=1.4.0",
|
|
29
|
+
"typebox": "*"
|
|
24
30
|
},
|
|
25
31
|
"devDependencies": {
|
|
26
|
-
"@
|
|
32
|
+
"@earendil-works/pi-coding-agent": "1.4.0",
|
|
27
33
|
"@types/node": "^25.6.0",
|
|
28
34
|
"@types/ws": "^8.18.1",
|
|
35
|
+
"typebox": "^1.3.27",
|
|
29
36
|
"typescript": "^5.9.3"
|
|
30
37
|
}
|
|
31
38
|
}
|
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/remote.ts
CHANGED
|
@@ -485,8 +485,8 @@ export class RemoteBrowserAgentBroker {
|
|
|
485
485
|
});
|
|
486
486
|
resolve();
|
|
487
487
|
});
|
|
488
|
-
|
|
489
|
-
socket.
|
|
488
|
+
// A failed handshake can emit more errors while terminate() drains the transport.
|
|
489
|
+
socket.on('error', () => fail(new Error(`Port ${this.port} is busy, but it is not a pi-browser-agent broker`)));
|
|
490
490
|
});
|
|
491
491
|
|
|
492
492
|
// Belt and braces: never leave a rejected promise cached, whatever path the
|
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,270 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { once } from 'node:events';
|
|
3
|
+
import { mkdtemp, rm } from 'node:fs/promises';
|
|
4
|
+
import net from 'node:net';
|
|
5
|
+
import { tmpdir } from 'node:os';
|
|
6
|
+
import { join } from 'node:path';
|
|
7
|
+
import test from 'node:test';
|
|
8
|
+
|
|
9
|
+
import WebSocket from 'ws';
|
|
10
|
+
import { Value } from 'typebox/value';
|
|
11
|
+
|
|
12
|
+
import { RemoteBrowserAgentBroker } from '../../src/broker/remote.ts';
|
|
13
|
+
import { BrowserAgentBroker, type EnsureReadyOptions } from '../../src/broker/server.ts';
|
|
14
|
+
import type { BrokerRequestOptions } from '../../src/broker/abort.ts';
|
|
15
|
+
import {
|
|
16
|
+
parseIncomingFrame,
|
|
17
|
+
WelcomeFrameSchema,
|
|
18
|
+
type ResponseFrame,
|
|
19
|
+
} from '../../src/broker/protocol.ts';
|
|
20
|
+
import { TaskStore } from '../../src/broker/task-store.ts';
|
|
21
|
+
import {
|
|
22
|
+
createBrowserGetTaskHistoryTool,
|
|
23
|
+
createBrowserListTasksTool,
|
|
24
|
+
createBrowserRunTaskTool,
|
|
25
|
+
} from '../../src/tools/browser_task_tools.ts';
|
|
26
|
+
|
|
27
|
+
const logger = { info() {}, warn() {}, error() {} };
|
|
28
|
+
|
|
29
|
+
// Tool factories require the nominal primary class, although they only use this
|
|
30
|
+
// public surface. Delegate it to the real secondary without a type assertion.
|
|
31
|
+
class SecondaryToolBroker extends BrowserAgentBroker {
|
|
32
|
+
private readonly secondary: RemoteBrowserAgentBroker;
|
|
33
|
+
|
|
34
|
+
constructor(secondary: RemoteBrowserAgentBroker) {
|
|
35
|
+
super({ taskStore: secondary.taskStore, logger });
|
|
36
|
+
this.secondary = secondary;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
override ensureReady(options?: EnsureReadyOptions) {
|
|
40
|
+
return this.secondary.ensureReady(options);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
override probeConnectivity() {
|
|
44
|
+
return this.secondary.probeConnectivity();
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
override request(type: string, params: unknown, options?: BrokerRequestOptions) {
|
|
48
|
+
return this.secondary.request(type, params, options);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
53
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function record(value: unknown): Record<string, unknown> {
|
|
57
|
+
assert.ok(isRecord(value));
|
|
58
|
+
return value;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function records(value: unknown): Record<string, unknown>[] {
|
|
62
|
+
assert.ok(Array.isArray(value));
|
|
63
|
+
return value.map((entry: unknown) => record(entry));
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
async function freePort(): Promise<number> {
|
|
67
|
+
const server = net.createServer();
|
|
68
|
+
server.listen(0, '127.0.0.1');
|
|
69
|
+
await once(server, 'listening');
|
|
70
|
+
const address = server.address();
|
|
71
|
+
assert.ok(address && typeof address !== 'string');
|
|
72
|
+
await new Promise<void>((resolve, reject) => {
|
|
73
|
+
server.close((error) => error ? reject(error) : resolve());
|
|
74
|
+
});
|
|
75
|
+
return address.port;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
interface Scenario {
|
|
79
|
+
task: string;
|
|
80
|
+
params: { tab_id?: number; use_active_tab?: boolean; debugMode?: boolean; timeoutMs: number };
|
|
81
|
+
target: { tab_id: number } | { use_active_tab: boolean };
|
|
82
|
+
reply: Pick<ResponseFrame, 'ok' | 'data' | 'error'>;
|
|
83
|
+
status: string;
|
|
84
|
+
code?: string;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const scenarios: Scenario[] = [
|
|
88
|
+
{
|
|
89
|
+
task: 'Read the active page',
|
|
90
|
+
params: { timeoutMs: 2_000 },
|
|
91
|
+
target: { use_active_tab: true },
|
|
92
|
+
reply: {
|
|
93
|
+
ok: true,
|
|
94
|
+
data: { status: 'done', message: 'Read page', historySummary: { steps: 1, text: '1. Read page' } },
|
|
95
|
+
},
|
|
96
|
+
status: 'done',
|
|
97
|
+
},
|
|
98
|
+
{
|
|
99
|
+
task: 'Fail on the selected tab',
|
|
100
|
+
params: { tab_id: 42, use_active_tab: true, debugMode: true, timeoutMs: 3_000 },
|
|
101
|
+
target: { tab_id: 42 },
|
|
102
|
+
reply: { ok: true, data: { status: 'error', error: { code: 'E_RUNTIME', message: 'Model failed' } } },
|
|
103
|
+
status: 'error',
|
|
104
|
+
code: 'E_RUNTIME',
|
|
105
|
+
},
|
|
106
|
+
{
|
|
107
|
+
task: 'Reject a busy task',
|
|
108
|
+
params: { use_active_tab: false, timeoutMs: 2_000 },
|
|
109
|
+
target: { use_active_tab: false },
|
|
110
|
+
reply: { ok: false, error: { code: 'E_BUSY', message: 'Already running' } },
|
|
111
|
+
status: 'rejected',
|
|
112
|
+
code: 'E_BUSY',
|
|
113
|
+
},
|
|
114
|
+
{
|
|
115
|
+
task: 'Reject a malformed success',
|
|
116
|
+
params: { timeoutMs: 2_000 },
|
|
117
|
+
target: { use_active_tab: true },
|
|
118
|
+
reply: { ok: true, data: {} },
|
|
119
|
+
status: 'error',
|
|
120
|
+
code: 'E_PROTOCOL',
|
|
121
|
+
},
|
|
122
|
+
{
|
|
123
|
+
task: 'Report a bridge failure',
|
|
124
|
+
params: { timeoutMs: 2_000 },
|
|
125
|
+
target: { use_active_tab: true },
|
|
126
|
+
reply: { ok: false, error: { code: 'E_EXTENSION', message: 'Browser action failed' } },
|
|
127
|
+
status: 'error',
|
|
128
|
+
code: 'E_EXTENSION',
|
|
129
|
+
},
|
|
130
|
+
];
|
|
131
|
+
|
|
132
|
+
test('secondary task tools forward through the primary bridge and retain history after restart', { timeout: 20_000 }, async (t) => {
|
|
133
|
+
const port = await freePort();
|
|
134
|
+
const root = await mkdtemp(join(tmpdir(), 'pi-browser-intent-'));
|
|
135
|
+
const primaryDir = join(root, 'primary');
|
|
136
|
+
const secondaryDir = join(root, 'secondary');
|
|
137
|
+
const options = { host: '127.0.0.1', port, logger, requestTimeoutMs: 4_000 };
|
|
138
|
+
let primary = new BrowserAgentBroker({ ...options, taskStore: new TaskStore({ dir: primaryDir }) });
|
|
139
|
+
let secondary = new RemoteBrowserAgentBroker({ ...options, taskStore: new TaskStore({ dir: secondaryDir }) });
|
|
140
|
+
let bridge: WebSocket | undefined;
|
|
141
|
+
t.after(async () => {
|
|
142
|
+
try {
|
|
143
|
+
await secondary.stop();
|
|
144
|
+
} finally {
|
|
145
|
+
bridge?.terminate();
|
|
146
|
+
try {
|
|
147
|
+
await primary.stop();
|
|
148
|
+
} finally {
|
|
149
|
+
await rm(root, { recursive: true, force: true });
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
await primary.start();
|
|
155
|
+
assert.equal(primary.port, port);
|
|
156
|
+
bridge = new WebSocket(primary.url);
|
|
157
|
+
await once(bridge, 'open');
|
|
158
|
+
const welcome = once(bridge, 'message');
|
|
159
|
+
bridge.send(JSON.stringify({
|
|
160
|
+
v: 1, kind: 'hello', extensionId: 'intent-fixture', version: '1.0.0', capabilities: ['browser_run_task'],
|
|
161
|
+
}));
|
|
162
|
+
const [welcomeData] = await welcome;
|
|
163
|
+
const welcomeFrame: unknown = JSON.parse(String(welcomeData));
|
|
164
|
+
assert.ok(Value.Check(WelcomeFrameSchema, welcomeFrame));
|
|
165
|
+
|
|
166
|
+
const received: Record<string, unknown>[] = [];
|
|
167
|
+
const fixtureErrors: unknown[] = [];
|
|
168
|
+
const fixtureSocket = bridge;
|
|
169
|
+
bridge.on('message', (raw) => {
|
|
170
|
+
try {
|
|
171
|
+
const frame = parseIncomingFrame(String(raw));
|
|
172
|
+
assert.equal(frame.kind, 'request');
|
|
173
|
+
assert.ok(frame.kind === 'request');
|
|
174
|
+
assert.equal(frame.type, 'browser_run_task');
|
|
175
|
+
const params = record(frame.params);
|
|
176
|
+
const scenario = scenarios[received.length];
|
|
177
|
+
assert.ok(scenario, 'unexpected extra bridge request');
|
|
178
|
+
received.push(params);
|
|
179
|
+
const response: ResponseFrame = { v: 1, kind: 'response', id: frame.id, ...scenario.reply };
|
|
180
|
+
fixtureSocket.send(JSON.stringify(response));
|
|
181
|
+
} catch (error) {
|
|
182
|
+
fixtureErrors.push(error);
|
|
183
|
+
fixtureSocket.close();
|
|
184
|
+
}
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
await secondary.start();
|
|
188
|
+
assert.equal(secondary.probeConnectivity().role, 'proxy');
|
|
189
|
+
assert.equal(secondary.probeConnectivity().bridgeConnected, true);
|
|
190
|
+
const tools = new SecondaryToolBroker(secondary);
|
|
191
|
+
const run = createBrowserRunTaskTool(tools);
|
|
192
|
+
const saved: Array<{ taskId: string; scenario: Scenario; history: unknown }> = [];
|
|
193
|
+
|
|
194
|
+
for (const scenario of scenarios) {
|
|
195
|
+
const result = await run.execute('intent-run', { task: scenario.task, ...scenario.params });
|
|
196
|
+
assert.deepEqual(fixtureErrors, []);
|
|
197
|
+
const { taskId } = result.details;
|
|
198
|
+
assert.equal(typeof taskId, 'string');
|
|
199
|
+
assert.ok(typeof taskId === 'string');
|
|
200
|
+
assert.equal(result.details.ok, !scenario.code);
|
|
201
|
+
assert.equal(result.details.success, scenario.status === 'done');
|
|
202
|
+
assert.equal(result.details.status, scenario.status);
|
|
203
|
+
assert.match(result.content[0].text, scenario.status === 'done' ? /Success: yes/ : /Success: no/);
|
|
204
|
+
if (scenario.code) {
|
|
205
|
+
assert.equal(record(result.details.error).code, scenario.code);
|
|
206
|
+
} else {
|
|
207
|
+
assert.deepEqual(result.details.historySummary, record(scenario.reply.data).historySummary);
|
|
208
|
+
assert.match(result.content[0].text, /History summary:\n1\. Read page/);
|
|
209
|
+
}
|
|
210
|
+
const expectedRequest = {
|
|
211
|
+
taskId, task: scenario.task, debugMode: scenario.params.debugMode ?? false, ...scenario.target,
|
|
212
|
+
};
|
|
213
|
+
assert.deepEqual(received.at(-1), expectedRequest);
|
|
214
|
+
const history = records(result.details.history);
|
|
215
|
+
assert.equal(history.length, 2);
|
|
216
|
+
assert.equal(history[0].kind, 'task_started');
|
|
217
|
+
assert.equal(history[0].status, 'running');
|
|
218
|
+
assert.equal(history[0].taskId, taskId);
|
|
219
|
+
assert.equal(typeof history[0].startedAt, 'number');
|
|
220
|
+
assert.deepEqual(history[0].request, { ...expectedRequest, timeoutMs: scenario.params.timeoutMs });
|
|
221
|
+
assert.equal(history[1].kind, 'task_finished');
|
|
222
|
+
assert.equal(history[1].taskId, taskId);
|
|
223
|
+
assert.equal(history[1].status, scenario.status);
|
|
224
|
+
assert.equal(typeof history[1].endedAt, 'number');
|
|
225
|
+
if (scenario.code) assert.equal(record(history[1].error).code, scenario.code);
|
|
226
|
+
else assert.deepEqual(history[1].result, scenario.reply.data);
|
|
227
|
+
saved.push({ taskId, scenario, history });
|
|
228
|
+
}
|
|
229
|
+
assert.equal(received.length, scenarios.length);
|
|
230
|
+
assert.deepEqual(await primary.taskStore.list(), [], 'history belongs to the calling secondary');
|
|
231
|
+
|
|
232
|
+
await secondary.stop();
|
|
233
|
+
bridge.terminate();
|
|
234
|
+
await primary.stop();
|
|
235
|
+
primary = new BrowserAgentBroker({ ...options, taskStore: new TaskStore({ dir: primaryDir }) });
|
|
236
|
+
secondary = new RemoteBrowserAgentBroker({ ...options, taskStore: new TaskStore({ dir: secondaryDir }) });
|
|
237
|
+
await primary.start();
|
|
238
|
+
await secondary.start();
|
|
239
|
+
assert.equal(secondary.probeConnectivity().role, 'proxy');
|
|
240
|
+
assert.equal(secondary.probeConnectivity().bridgeConnected, false);
|
|
241
|
+
const freshTools = new SecondaryToolBroker(secondary);
|
|
242
|
+
const historyTool = createBrowserGetTaskHistoryTool(freshTools);
|
|
243
|
+
const listTool = createBrowserListTasksTool(freshTools);
|
|
244
|
+
for (const { taskId, scenario, history } of saved) {
|
|
245
|
+
const loaded = await historyTool.execute('intent-history', { taskId });
|
|
246
|
+
assert.equal(loaded.details.ok, true);
|
|
247
|
+
assert.deepEqual(loaded.details.history, history);
|
|
248
|
+
const summary = record(loaded.details.summary);
|
|
249
|
+
assert.equal(summary.taskId, taskId);
|
|
250
|
+
assert.equal(summary.task, scenario.task);
|
|
251
|
+
assert.equal(summary.status, scenario.status);
|
|
252
|
+
assert.equal(summary.events, 2);
|
|
253
|
+
if (scenario.code) assert.equal(record(summary.error).code, scenario.code);
|
|
254
|
+
else assert.deepEqual(summary.result, scenario.reply.data);
|
|
255
|
+
}
|
|
256
|
+
const listed = await listTool.execute('intent-list', { limit: 20 });
|
|
257
|
+
assert.equal(listed.details.ok, true);
|
|
258
|
+
const tasks = records(listed.details.tasks);
|
|
259
|
+
assert.equal(tasks.length, saved.length);
|
|
260
|
+
for (const { taskId, scenario } of saved) {
|
|
261
|
+
const summary = tasks.find((entry) => entry.taskId === taskId);
|
|
262
|
+
assert.ok(summary);
|
|
263
|
+
assert.equal(summary.task, scenario.task);
|
|
264
|
+
assert.equal(summary.status, scenario.status);
|
|
265
|
+
}
|
|
266
|
+
const filtered = await listTool.execute('intent-filter', { status: 'done', limit: 20 });
|
|
267
|
+
assert.equal(filtered.details.ok, true);
|
|
268
|
+
assert.deepEqual(records(filtered.details.tasks).map((entry) => entry.taskId), [saved[0].taskId]);
|
|
269
|
+
assert.equal(received.length, scenarios.length, 'history tools must not call the bridge');
|
|
270
|
+
});
|
|
@@ -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,182 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { spawn } from 'node:child_process';
|
|
3
|
+
import { once } from 'node:events';
|
|
4
|
+
import { copyFile, mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises';
|
|
5
|
+
import { createServer } from 'node:http';
|
|
6
|
+
import { createServer as createTcpServer } from 'node:net';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import test from 'node:test';
|
|
9
|
+
import { fileURLToPath } from 'node:url';
|
|
10
|
+
import WebSocket from 'ws';
|
|
11
|
+
|
|
12
|
+
const root = fileURLToPath(new URL('../', import.meta.url));
|
|
13
|
+
const piBin = process.env.EVERGREEN_PI_BIN || 'pi';
|
|
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
|
+
type RecordValue = Record<string, unknown>;
|
|
22
|
+
function object(value: unknown): RecordValue {
|
|
23
|
+
assert.ok(value && typeof value === 'object' && !Array.isArray(value));
|
|
24
|
+
return value as RecordValue;
|
|
25
|
+
}
|
|
26
|
+
async function freePort() {
|
|
27
|
+
const server = createTcpServer().listen(0, '127.0.0.1');
|
|
28
|
+
await once(server, 'listening');
|
|
29
|
+
const address = server.address();
|
|
30
|
+
assert.ok(address && typeof address !== 'string');
|
|
31
|
+
await new Promise<void>((resolve) => server.close(() => resolve()));
|
|
32
|
+
return address.port;
|
|
33
|
+
}
|
|
34
|
+
async function workspace() {
|
|
35
|
+
await mkdir(path.join(root, 'tmp'), { recursive: true });
|
|
36
|
+
const dir = await mkdtemp(path.join(root, 'tmp/evergreen-'));
|
|
37
|
+
await mkdir(path.join(dir, 'agent'));
|
|
38
|
+
return dir;
|
|
39
|
+
}
|
|
40
|
+
async function runPi(dir: string, port: number, model: string, prompt: string, extra: string[] = []) {
|
|
41
|
+
const child = spawn(piBin, ['--mode', 'json', '--offline', '--no-extensions', '--no-mcp',
|
|
42
|
+
'--no-skills', '--no-prompt-templates', '--no-context-files', '--no-builtin-tools',
|
|
43
|
+
'--model', model, '--session-dir', path.join(dir, 'sessions'),
|
|
44
|
+
'-e', path.join(root, 'src/index.ts'), ...extra, prompt], {
|
|
45
|
+
cwd: dir, env: { ...process.env, PI_CODING_AGENT_DIR: path.join(dir, 'agent'),
|
|
46
|
+
PI_TELEMETRY: '0', XDG_STATE_HOME: dir, PI_BA_PORT: String(port) },
|
|
47
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
48
|
+
});
|
|
49
|
+
let stdout = '', stderr = '';
|
|
50
|
+
child.stdout.on('data', (chunk) => { stdout += chunk; });
|
|
51
|
+
child.stderr.on('data', (chunk) => { stderr += chunk; });
|
|
52
|
+
const timer = setTimeout(() => child.kill('SIGKILL'), 120_000);
|
|
53
|
+
try {
|
|
54
|
+
const [code] = await once(child, 'exit');
|
|
55
|
+
assert.equal(code, 0, `${stderr}\n${stdout}`);
|
|
56
|
+
return stdout.trim().split('\n').map((line) => object(JSON.parse(line)));
|
|
57
|
+
} finally {
|
|
58
|
+
clearTimeout(timer);
|
|
59
|
+
if (child.exitCode === null) child.kill('SIGKILL');
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
function toolEnd(events: RecordValue[], name: string) {
|
|
63
|
+
const event = events.find((item) => item.type === 'tool_execution_end' && item.toolName === name);
|
|
64
|
+
assert.ok(event, `Pi must actually execute ${name}: ${JSON.stringify(events)}`);
|
|
65
|
+
return event;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
test('global Pi declares all tools offline, forwards tasks, persists history across processes and classifies bridge failures',
|
|
69
|
+
{ timeout: 180_000 }, async () => {
|
|
70
|
+
const dir = await workspace();
|
|
71
|
+
const port = await freePort();
|
|
72
|
+
const requests: RecordValue[] = [];
|
|
73
|
+
let selectedTool = 'browser_run_task';
|
|
74
|
+
let selectedParams: RecordValue = { task: 'EVERGREEN_TASK_INTENT' };
|
|
75
|
+
let bridgeFailure = false;
|
|
76
|
+
const bridges = new Set<WebSocket>();
|
|
77
|
+
// A local transport fixture makes declaration/result assertions deterministic;
|
|
78
|
+
// the second test below uses EVERGREEN_E2E_MODEL with real credentials.
|
|
79
|
+
const endpoint = createServer(async (req, res) => {
|
|
80
|
+
let raw = '';
|
|
81
|
+
for await (const chunk of req) raw += chunk;
|
|
82
|
+
const body = object(JSON.parse(raw));
|
|
83
|
+
requests.push(body);
|
|
84
|
+
assert.ok(Array.isArray(body.messages));
|
|
85
|
+
const call = object(body.messages.at(-1)).role !== 'tool';
|
|
86
|
+
res.writeHead(200, { 'content-type': 'text/event-stream' });
|
|
87
|
+
const delta = call ? { tool_calls: [{ index: 0, id: `eg_${requests.length}`,
|
|
88
|
+
type: 'function', function: { name: selectedTool, arguments: JSON.stringify(selectedParams) } }] }
|
|
89
|
+
: { content: 'EVERGREEN_COMPLETE' };
|
|
90
|
+
for (const [change, finish] of [[{ role: 'assistant', ...delta }, null],
|
|
91
|
+
[{}, call ? 'tool_calls' : 'stop']]) {
|
|
92
|
+
res.write(`data: ${JSON.stringify({ id: 'eg', object: 'chat.completion.chunk',
|
|
93
|
+
model: 'evergreen-fixture', created: 1,
|
|
94
|
+
choices: [{ index: 0, delta: change, finish_reason: finish }],
|
|
95
|
+
usage: { prompt_tokens: 20, completion_tokens: 5, total_tokens: 25 } })}\n\n`);
|
|
96
|
+
}
|
|
97
|
+
res.end('data: [DONE]\n\n');
|
|
98
|
+
}).listen(0, '127.0.0.1');
|
|
99
|
+
await once(endpoint, 'listening');
|
|
100
|
+
const address = endpoint.address();
|
|
101
|
+
assert.ok(address && typeof address !== 'string');
|
|
102
|
+
await writeFile(path.join(dir, 'agent/models.json'), JSON.stringify({ providers: {
|
|
103
|
+
evergreen: { baseUrl: `http://127.0.0.1:${address.port}/v1`, api: 'openai-completions',
|
|
104
|
+
apiKey: 'local-fixture', models: [{ id: 'evergreen-fixture', contextWindow: 128000, maxTokens: 128 }] },
|
|
105
|
+
} }));
|
|
106
|
+
let connecting = false;
|
|
107
|
+
const connect = setInterval(() => {
|
|
108
|
+
if (connecting) return;
|
|
109
|
+
connecting = true;
|
|
110
|
+
const bridge = new WebSocket(`ws://127.0.0.1:${port}`);
|
|
111
|
+
bridges.add(bridge);
|
|
112
|
+
bridge.on('error', () => {});
|
|
113
|
+
bridge.on('close', () => { bridges.delete(bridge); connecting = false; });
|
|
114
|
+
bridge.on('open', () => bridge.send(JSON.stringify({ v: 1, kind: 'hello',
|
|
115
|
+
extensionId: 'evergreen', version: '1', capabilities: [] })));
|
|
116
|
+
bridge.on('message', (raw) => {
|
|
117
|
+
const frame = object(JSON.parse(raw.toString()));
|
|
118
|
+
if (frame.kind !== 'request') return;
|
|
119
|
+
assert.equal(frame.type, 'browser_run_task');
|
|
120
|
+
assert.equal(object(frame.params).task, 'EVERGREEN_TASK_INTENT');
|
|
121
|
+
bridge.send(JSON.stringify({ v: 1, kind: 'response', id: frame.id, ok: !bridgeFailure,
|
|
122
|
+
...(bridgeFailure ? { error: { code: 'E_RUNTIME', message: 'EVERGREEN_BRIDGE_FAILURE' } }
|
|
123
|
+
: { data: { status: 'done', message: 'EVERGREEN_BRIDGE_RESULT' } }) }));
|
|
124
|
+
});
|
|
125
|
+
}, 40);
|
|
126
|
+
try {
|
|
127
|
+
const events = await runPi(dir, port, 'evergreen/evergreen-fixture', 'Run the browser task.');
|
|
128
|
+
const completed = toolEnd(events, 'browser_run_task');
|
|
129
|
+
assert.equal(completed.isError, false);
|
|
130
|
+
const result = object(completed.result);
|
|
131
|
+
const details = object(result.details);
|
|
132
|
+
assert.equal(details.success, true);
|
|
133
|
+
assert.deepEqual(result.structuredContent, details);
|
|
134
|
+
assert.ok(JSON.stringify(requests.at(-1)).includes('EVERGREEN_BRIDGE_RESULT'));
|
|
135
|
+
selectedTool = 'browser_get_task_history';
|
|
136
|
+
selectedParams = { taskId: details.taskId };
|
|
137
|
+
const history = await runPi(dir, port, 'evergreen/evergreen-fixture', 'Read the stored task.');
|
|
138
|
+
assert.match(JSON.stringify(toolEnd(history, selectedTool)), /EVERGREEN_TASK_INTENT/);
|
|
139
|
+
assert.match(JSON.stringify(toolEnd(history, selectedTool)), /EVERGREEN_BRIDGE_RESULT/);
|
|
140
|
+
assert.match(JSON.stringify(requests.at(-1)), /Loaded 2 history event/);
|
|
141
|
+
selectedTool = 'browser_run_task';
|
|
142
|
+
selectedParams = { task: 'EVERGREEN_TASK_INTENT' };
|
|
143
|
+
bridgeFailure = true;
|
|
144
|
+
const failed = toolEnd(await runPi(dir, port, 'evergreen/evergreen-fixture', 'Run the task.'), selectedTool);
|
|
145
|
+
assert.equal(failed.isError, true);
|
|
146
|
+
assert.match(JSON.stringify(failed), /EVERGREEN_BRIDGE_FAILURE/);
|
|
147
|
+
for (const request of requests) {
|
|
148
|
+
assert.ok(Array.isArray(request.tools));
|
|
149
|
+
assert.deepEqual(request.tools.map((tool) => object(object(tool).function).name).sort(), names);
|
|
150
|
+
}
|
|
151
|
+
const sessions = await readdir(path.join(dir, 'sessions'));
|
|
152
|
+
const persisted = await Promise.all(sessions.map((file) => readFile(path.join(dir, 'sessions', file), 'utf8')));
|
|
153
|
+
assert.ok(persisted.some((text) => text.includes('EVERGREEN_BRIDGE_FAILURE') && text.includes('"isError":true')));
|
|
154
|
+
const probe = createTcpServer().listen(port, '127.0.0.1');
|
|
155
|
+
await once(probe, 'listening');
|
|
156
|
+
await new Promise<void>((resolve) => probe.close(() => resolve()));
|
|
157
|
+
} finally {
|
|
158
|
+
clearInterval(connect);
|
|
159
|
+
for (const bridge of bridges) bridge.terminate();
|
|
160
|
+
endpoint.closeAllConnections();
|
|
161
|
+
await new Promise<void>((resolve) => endpoint.close(() => resolve()));
|
|
162
|
+
await rm(dir, { recursive: true, force: true });
|
|
163
|
+
}
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
test('live Evergreen model discovers and uses browser history without Chrome', { timeout: 150_000 }, async () => {
|
|
167
|
+
const model = process.env.EVERGREEN_E2E_MODEL;
|
|
168
|
+
assert.ok(model, 'Set EVERGREEN_E2E_MODEL to the provider/model used for live E2E');
|
|
169
|
+
const dir = await workspace();
|
|
170
|
+
try {
|
|
171
|
+
// Isolate settings/extensions/state, but retain the user's provider credentials.
|
|
172
|
+
const agent = process.env.PI_CODING_AGENT_DIR || path.join(process.env.HOME || '', '.pi/agent');
|
|
173
|
+
try { await copyFile(path.join(agent, 'auth.json'), path.join(dir, 'agent/auth.json')); }
|
|
174
|
+
catch (error) { if (!(error instanceof Error && 'code' in error && error.code === 'ENOENT')) throw error; }
|
|
175
|
+
const events = await runPi(dir, await freePort(), model,
|
|
176
|
+
'Call browser_list_tasks exactly once to inspect local browser task history. Do not call any other tools. Then briefly report whether the list is empty.');
|
|
177
|
+
assert.equal(toolEnd(events, 'browser_list_tasks').isError, false);
|
|
178
|
+
assert.ok(events.some((event) => event.type === 'agent_end'));
|
|
179
|
+
} finally {
|
|
180
|
+
await rm(dir, { recursive: true, force: true });
|
|
181
|
+
}
|
|
182
|
+
});
|
|
@@ -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,69 @@
|
|
|
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:http';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
import test from 'node:test';
|
|
7
|
+
import WebSocket from 'ws';
|
|
8
|
+
import { RemoteBrowserAgentBroker } from '../src/broker/remote.ts';
|
|
9
|
+
import { BrowserAgentBroker } from '../src/broker/server.ts';
|
|
10
|
+
import { TaskStore } from '../src/broker/task-store.ts';
|
|
11
|
+
|
|
12
|
+
for (const failure of ['handshake rejection', 'connection timeout']) {
|
|
13
|
+
test(`a proxy handles repeated socket errors after ${failure} and can reconnect`, { timeout: 10_000 }, async (t) => {
|
|
14
|
+
await mkdir(join(process.cwd(), 'tmp'), { recursive: true });
|
|
15
|
+
const root = await mkdtemp(join(process.cwd(), 'tmp', 'proxy-errors-'));
|
|
16
|
+
const server = createServer((_request, response) => {
|
|
17
|
+
if (failure === 'handshake rejection') {
|
|
18
|
+
response.writeHead(503);
|
|
19
|
+
response.end();
|
|
20
|
+
}
|
|
21
|
+
}).listen(0, '127.0.0.1');
|
|
22
|
+
await once(server, 'listening');
|
|
23
|
+
const address = server.address();
|
|
24
|
+
assert.ok(address && typeof address !== 'string');
|
|
25
|
+
const options = { host: '127.0.0.1', port: address.port, logger: { info() {}, warn() {}, error() {} } };
|
|
26
|
+
const remote = new RemoteBrowserAgentBroker({
|
|
27
|
+
...options, requestTimeoutMs: 100,
|
|
28
|
+
taskStore: new TaskStore({ dir: join(root, 'remote') }),
|
|
29
|
+
});
|
|
30
|
+
const primary = new BrowserAgentBroker({
|
|
31
|
+
...options, portRange: 1, fallbackToEphemeral: false,
|
|
32
|
+
taskStore: new TaskStore({ dir: join(root, 'primary') }),
|
|
33
|
+
});
|
|
34
|
+
let failedSocket: WebSocket | undefined;
|
|
35
|
+
let closed: Promise<void> | undefined;
|
|
36
|
+
const terminate = WebSocket.prototype.terminate;
|
|
37
|
+
t.mock.method(WebSocket.prototype, 'terminate', function (this: WebSocket) {
|
|
38
|
+
failedSocket = this;
|
|
39
|
+
closed = new Promise<void>((resolve) => this.once('close', () => resolve()));
|
|
40
|
+
terminate.call(this);
|
|
41
|
+
});
|
|
42
|
+
try {
|
|
43
|
+
await assert.rejects(remote.start(), /not a pi-browser-agent broker/);
|
|
44
|
+
assert.ok(failedSocket, 'the failed connection must be terminated');
|
|
45
|
+
const retired = failedSocket;
|
|
46
|
+
await closed;
|
|
47
|
+
// Bun can emit another transport error after the first error/termination.
|
|
48
|
+
assert.doesNotThrow(() => retired.emit('error', new Error('late transport error')));
|
|
49
|
+
assert.doesNotThrow(() => retired.emit('error', new Error('another transport error')));
|
|
50
|
+
|
|
51
|
+
server.closeAllConnections();
|
|
52
|
+
await new Promise<void>((resolve) => server.close(() => resolve()));
|
|
53
|
+
await primary.start();
|
|
54
|
+
await remote.start();
|
|
55
|
+
assert.equal(remote.probeConnectivity().brokerListening, true);
|
|
56
|
+
assert.equal(remote.probeConnectivity().role, 'proxy');
|
|
57
|
+
assert.doesNotThrow(() => retired.emit('error', new Error('error after replacement')));
|
|
58
|
+
assert.equal(remote.probeConnectivity().brokerListening, true, 'an old socket cannot disrupt its replacement');
|
|
59
|
+
await remote.stop();
|
|
60
|
+
assert.doesNotThrow(() => retired.emit('error', new Error('error after shutdown')));
|
|
61
|
+
} finally {
|
|
62
|
+
await remote.stop();
|
|
63
|
+
await primary.stop();
|
|
64
|
+
server.closeAllConnections();
|
|
65
|
+
await new Promise<void>((resolve) => server.close(() => resolve()));
|
|
66
|
+
await rm(root, { recursive: true, force: true });
|
|
67
|
+
}
|
|
68
|
+
});
|
|
69
|
+
}
|
|
@@ -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
|
+
});
|