oira666_pi-browser-agent 0.0.20 → 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 +1 -0
- package/EVERGREEN.md +60 -0
- package/README.md +1 -1
- package/package.json +5 -3
- package/src/broker/remote.ts +2 -2
- package/tests/integration/intent.test.ts +270 -0
- package/tests/pi-cli.e2e.ts +124 -229
- package/tests/remote-socket-errors.test.ts +69 -0
- package/tests/fixtures/lifecycle-observer.ts +0 -20
package/AGENTS.md
CHANGED
|
@@ -14,3 +14,4 @@
|
|
|
14
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
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
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
|
@@ -108,7 +108,7 @@ Run `npm ci --ignore-scripts` to install the locked development dependencies, th
|
|
|
108
108
|
|
|
109
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
110
|
|
|
111
|
-
|
|
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
112
|
|
|
113
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
114
|
|
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",
|
|
@@ -16,8 +16,10 @@
|
|
|
16
16
|
"scripts": {
|
|
17
17
|
"typecheck": "tsc --noEmit",
|
|
18
18
|
"pretest": "npm run typecheck",
|
|
19
|
-
"test": "node --test ./tests/*.test.ts ./tests/tools/*.test.ts",
|
|
20
|
-
"test:
|
|
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"
|
|
21
23
|
},
|
|
22
24
|
"dependencies": {
|
|
23
25
|
"ws": "^8.18.3"
|
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
|
|
@@ -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
|
+
});
|
package/tests/pi-cli.e2e.ts
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
import assert from 'node:assert/strict';
|
|
2
2
|
import { spawn } from 'node:child_process';
|
|
3
3
|
import { once } from 'node:events';
|
|
4
|
-
import {
|
|
5
|
-
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
|
|
4
|
+
import { copyFile, mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises';
|
|
6
5
|
import { createServer } from 'node:http';
|
|
7
6
|
import { createServer as createTcpServer } from 'node:net';
|
|
8
7
|
import path from 'node:path';
|
|
@@ -11,6 +10,7 @@ import { fileURLToPath } from 'node:url';
|
|
|
11
10
|
import WebSocket from 'ws';
|
|
12
11
|
|
|
13
12
|
const root = fileURLToPath(new URL('../', import.meta.url));
|
|
13
|
+
const piBin = process.env.EVERGREEN_PI_BIN || 'pi';
|
|
14
14
|
const names = ['activate_browser_agent_tools', 'browser_run_task', 'browser_get_task_history',
|
|
15
15
|
'browser_list_tasks', 'browser_get_screenshot', 'browser_get_html', 'browser_get_dom_info',
|
|
16
16
|
'browser_get_computed_styles', 'browser_get_console_logs', 'browser_get_network',
|
|
@@ -18,9 +18,6 @@ const names = ['activate_browser_agent_tools', 'browser_run_task', 'browser_get_
|
|
|
18
18
|
'browser_run_js', 'browser_create_tab', 'browser_list_tabs', 'browser_switch_tab',
|
|
19
19
|
'browser_close_tab', 'browser_navigate', 'browser_reload', 'browser_reload_extension',
|
|
20
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
21
|
type RecordValue = Record<string, unknown>;
|
|
25
22
|
function object(value: unknown): RecordValue {
|
|
26
23
|
assert.ok(value && typeof value === 'object' && !Array.isArray(value));
|
|
@@ -34,254 +31,152 @@ async function freePort() {
|
|
|
34
31
|
await new Promise<void>((resolve) => server.close(() => resolve()));
|
|
35
32
|
return address.port;
|
|
36
33
|
}
|
|
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');
|
|
34
|
+
async function workspace() {
|
|
42
35
|
await mkdir(path.join(root, 'tmp'), { recursive: true });
|
|
43
|
-
const dir = await mkdtemp(path.join(root, 'tmp/
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
const
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
let
|
|
57
|
-
|
|
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.
|
|
58
79
|
const endpoint = createServer(async (req, res) => {
|
|
59
80
|
let raw = '';
|
|
60
81
|
for await (const chunk of req) raw += chunk;
|
|
61
|
-
const body
|
|
82
|
+
const body = object(JSON.parse(raw));
|
|
62
83
|
requests.push(body);
|
|
63
|
-
|
|
64
|
-
|
|
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';
|
|
84
|
+
assert.ok(Array.isArray(body.messages));
|
|
85
|
+
const call = object(body.messages.at(-1)).role !== 'tool';
|
|
71
86
|
res.writeHead(200, { 'content-type': 'text/event-stream' });
|
|
72
|
-
const delta =
|
|
87
|
+
const delta = call ? { tool_calls: [{ index: 0, id: `eg_${requests.length}`,
|
|
73
88
|
type: 'function', function: { name: selectedTool, arguments: JSON.stringify(selectedParams) } }] }
|
|
74
|
-
: { content: '
|
|
75
|
-
const
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
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
|
+
}
|
|
81
97
|
res.end('data: [DONE]\n\n');
|
|
82
98
|
}).listen(0, '127.0.0.1');
|
|
83
99
|
await once(endpoint, 'listening');
|
|
84
100
|
const address = endpoint.address();
|
|
85
101
|
assert.ok(address && typeof address !== 'string');
|
|
86
|
-
await writeFile(path.join(
|
|
87
|
-
|
|
88
|
-
apiKey: '
|
|
89
|
-
contextWindow: 128000, maxTokens: 128 }] },
|
|
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 }] },
|
|
90
105
|
} }));
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
'
|
|
98
|
-
'
|
|
99
|
-
'
|
|
100
|
-
|
|
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');
|
|
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: [] })));
|
|
170
116
|
bridge.on('message', (raw) => {
|
|
171
117
|
const frame = object(JSON.parse(raw.toString()));
|
|
172
|
-
if (frame.kind
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
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
|
-
}
|
|
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' } }) }));
|
|
186
124
|
});
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
const
|
|
190
|
-
|
|
191
|
-
assert.
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
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');
|
|
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'));
|
|
254
135
|
selectedTool = 'browser_get_task_history';
|
|
255
|
-
selectedParams = { taskId };
|
|
256
|
-
await
|
|
257
|
-
assert.match(JSON.stringify(
|
|
258
|
-
|
|
259
|
-
requests.
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
assert.equal(row.suspend, Number(starts[0].suspend) - 1);
|
|
270
|
-
assert.equal(row.resume, Number(starts[0].resume) - 1);
|
|
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);
|
|
271
150
|
}
|
|
272
|
-
|
|
273
|
-
const
|
|
274
|
-
|
|
275
|
-
await exit;
|
|
276
|
-
assert.equal(child.exitCode, 0, stderr);
|
|
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')));
|
|
277
154
|
const probe = createTcpServer().listen(port, '127.0.0.1');
|
|
278
155
|
await once(probe, 'listening');
|
|
279
156
|
await new Promise<void>((resolve) => probe.close(() => resolve()));
|
|
280
157
|
} finally {
|
|
281
|
-
|
|
282
|
-
|
|
158
|
+
clearInterval(connect);
|
|
159
|
+
for (const bridge of bridges) bridge.terminate();
|
|
283
160
|
endpoint.closeAllConnections();
|
|
284
161
|
await new Promise<void>((resolve) => endpoint.close(() => resolve()));
|
|
285
162
|
await rm(dir, { recursive: true, force: true });
|
|
286
163
|
}
|
|
287
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,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
|
+
}
|
|
@@ -1,20 +0,0 @@
|
|
|
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
|
-
}
|