okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Trial2 merge f-0291-pr-nv (97b3d614f)1306424be

main
19.6 KiB317 linesraw
1/**
2 * Agent bridge, end to end against the real pinned Harness and a scripted worker.
3 *
4 * Needs the built Harness: set STRATA_HARNESS_DIR to a checkout built with `pnpm install` and
5 * `pnpm run build:artifacts`. Without it these tests skip, loudly, rather than pass.
6 *
7 * The model is scripted (tests/helpers/scripted-worker.mjs). What is real: the Harness process, its
8 * agent loop, its tool executor and approval gate, the gateway, the durable session, and the bridge.
9 * A scripted model proves the path; it does not prove a model chooses tools well.
10 */
11import test from 'node:test';
12import assert from 'node:assert/strict';
13import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, mkdirSync, statSync } from 'node:fs';
14import { tmpdir } from 'node:os';
15import { join } from 'node:path';
16import { createHash } from 'node:crypto';
17import { startScriptedWorker } from './helpers/scripted-worker.mjs';
18import { createAgentBridge } from '../server/agent/agent-bridge.mjs';
19import { resolveHarness } from '../server/agent/harness-runtime.mjs';
20
21const HARNESS = process.env.STRATA_HARNESS_DIR;
22const skip = !HARNESS || !resolveHarness({ env: process.env }).ok ? 'STRATA_HARNESS_DIR is not set to a built Harness' : false;
23
24function cleanup(dir) {
25  // The Harness's Windows sandbox adds access entries under the directories it works in, which can make a
26  // plain recursive delete fail with EPERM. Cleanup is best effort; a leftover temp dir is not a failure.
27  try { rmSync(dir, { recursive: true, force: true, maxRetries: 3 }); } catch { /* best effort */ }
28}
29
30const lines = file => readFileSync(file, 'utf8').split(/\r?\n/).filter(Boolean).length;
31
32async function rig(t, { connections = [], dataDir } = {}) {
33  const worker = await startScriptedWorker({});
34  const dir = dataDir ?? mkdtempSync(join(tmpdir(), 'strata-agent-'));
35  const ws = join(dir, 'ws'); mkdirSync(ws, { recursive: true });
36  const local = [{ id: 'inst-1', label: 'Scripted', baseUrl: worker.url, modelId: 'scripted-model', context: 32768 }];
37  const bridge = createAgentBridge({ dataDir: dir, localInstances: () => local, connections: () => connections, env: process.env, startTimeoutMs: 90_000 });
38  t.after(async () => { await bridge.close(); await worker.close(); if (!dataDir) cleanup(dir); });
39  const run = (chatId, message, opts = {}) => {
40    const frames = [];
41    const answerWith = opts.answer; // 'approve' | 'deny' | undefined
42    const promise = bridge.runTurn({
43      chatId, message, workspacePath: ws, choice: opts.choice ?? null, mode: opts.mode ?? null, history: opts.history ?? [],
44      onFrame: f => {
45        frames.push(f);
46        opts.onFrame?.(f);
47        if (answerWith && f.type === 'agent-tool' && f.tool.state === 'proposed') {
48          void bridge.approve({ chatId, callId: f.tool.id, decision: answerWith }).catch(e => frames.push({ type: 'test-error', message: e.message }));
49        }
50      },
51      signal: opts.signal,
52    });
53    return { frames, promise };
54  };
55  return { worker, bridge, dir, ws, run, local };
56}
57
58const states = (frames, id) => frames.filter(f => f.type === 'agent-tool' && (!id || f.tool.id === id)).map(f => f.tool.state);
59const text = frames => frames.filter(f => f.type === 'delta').map(f => f.text).join('');
60
61test('A01/A02 a turn streams reasoning and text, then finishes with usage', { skip }, async t => {
62  const r = await rig(t);
63  const { frames, promise } = r.run('chat-a01', 'SCRIPT:hello');
64  await promise;
65  assert.equal(frames[0].type, 'queued');
66  const start = frames.find(f => f.type === 'start');
67  assert.equal(start.agent, true); assert.equal(start.model, 'Scripted'); assert.equal(start.contextMax, 32768);
68  assert.match(frames.filter(f => f.type === 'reasoning').map(f => f.text).join(''), /Considering a greeting/);
69  assert.equal(text(frames), 'Hello from the scripted worker.');
70  const done = frames.at(-1);
71  assert.equal(done.type, 'done'); assert.equal(done.finishReason, 'stop'); assert.equal(done.usageSource, 'reported');
72  assert.ok(done.tokensIn > 0 && done.tokensOut > 0);
73  assert.equal(frames.filter(f => f.type === 'error').length, 0);
74  // The route is the declared local one, not a default the catalog would have chosen.
75  assert.ok(r.worker.requests.every(q => q.model === 'scripted-model'));
76});
77
78test('A03 a tool runs exactly once, in the Harness, after the user approves', { skip }, async t => {
79  const r = await rig(t);
80  const { frames, promise } = r.run('chat-a03', 'SCRIPT:tool marker.txt hi', { answer: 'approve' });
81  await promise;
82  const calls = frames.filter(f => f.type === 'agent-tool' && f.tool.state === 'running');
83  assert.ok(calls.length >= 1);
84  const id = frames.find(f => f.type === 'agent-tool').tool.id;
85  assert.deepEqual([...new Set(states(frames, id))], ['running', 'proposed', 'done']);
86  assert.equal(frames.filter(f => f.type === 'test-error').length, 0);
87  assert.equal(lines(join(r.ws, 'marker.txt')), 1, 'the marker must have exactly one line: the tool ran once');
88  const card = frames.filter(f => f.type === 'agent-tool').at(-1).tool;
89  assert.equal(card.scope, 'shell'); assert.match(card.preview, /marker\.txt/);
90  assert.equal(frames.at(-1).type, 'done');
91  // The worker only saw a transcript: it has no execution path, and it was asked twice (call, then result).
92  assert.equal(r.worker.requests.filter(q => q.toolNames.length).length, 2);
93  assert.match(text(frames), /Tool finished/);
94});
95
96test('A04 a denied tool never runs, and the agent is told', { skip }, async t => {
97  const r = await rig(t);
98  const { frames, promise } = r.run('chat-a04', 'SCRIPT:tool denied.txt nope', { answer: 'deny' });
99  await promise;
100  const id = frames.find(f => f.type === 'agent-tool').tool.id;
101  assert.deepEqual([...new Set(states(frames, id))], ['running', 'proposed', 'denied']);
102  assert.equal(existsSync(join(r.ws, 'denied.txt')), false, 'a denied tool must not run');
103  assert.equal(frames.at(-1).type, 'done', 'the turn still settles');
104  // The model got the denial back as a tool result it can read.
105  assert.match(text(frames), /reject|denied|Tool finished/i);
106});
107
108test('A05 Stop cancels exactly that chat, waits for the turn to end, and leaves other chats running', { skip }, async t => {
109  const r = await rig(t);
110  const slowA = r.run('chat-a05-a', 'SCRIPT:slow 400');
111  const slowB = r.run('chat-a05-b', 'SCRIPT:slow 60');
112  // wait until A is demonstrably live
113  for (let i = 0; i < 200 && slowA.frames.filter(f => f.type === 'delta').length < 3; i++) await new Promise(x => setTimeout(x, 50));
114  assert.ok(slowA.frames.filter(f => f.type === 'delta').length >= 3, 'the turn must be live before Stop, or the test proves nothing');
115  const stopped = await r.bridge.stop('chat-a05-a');
116  assert.equal(stopped.stopped, true); assert.equal(stopped.ended, 'aborted');
117  await slowA.promise;
118  assert.equal(slowA.frames.at(-1).finishReason, 'aborted'); assert.equal(slowA.frames.at(-1).cancelled, true);
119  assert.ok(slowA.frames.filter(f => f.type === 'delta').length < 400, 'the stream was cut short');
120  assert.ok(r.worker.aborted >= 1, 'the model request was cancelled at the worker');
121  assert.equal(r.bridge.isRunning('chat-a05-a'), false);
122  // B was not touched and runs to its end.
123  await slowB.promise;
124  assert.equal(slowB.frames.at(-1).finishReason, 'stop');
125  assert.equal(slowB.frames.filter(f => f.type === 'delta').length, 60);
126  // And A can be used again.
127  const again = r.run('chat-a05-a', 'SCRIPT:echo after stop'); await again.promise;
128  assert.equal(text(again.frames), 'after stop');
129});
130
131test('A05b Stop while an approval is pending denies it and ends the turn', { skip }, async t => {
132  const r = await rig(t);
133  const { frames, promise } = r.run('chat-a05b', 'SCRIPT:tool never.txt x');
134  for (let i = 0; i < 200 && !states(frames).includes('proposed'); i++) await new Promise(x => setTimeout(x, 50));
135  assert.ok(states(frames).includes('proposed'));
136  const stopped = await r.bridge.stop('chat-a05b');
137  assert.equal(stopped.stopped, true);
138  await promise;
139  assert.equal(existsSync(join(r.ws, 'never.txt')), false);
140  assert.equal(states(frames).at(-1), 'denied');
141  assert.equal(r.bridge.pendingFor('chat-a05b').length, 0);
142});
143
144test('A06 reopening a chat resumes its Harness session without replaying a tool', { skip }, async t => {
145  const dir = mkdtempSync(join(tmpdir(), 'strata-agent-resume-'));
146  t.after(() => cleanup(dir));
147  const first = await rig(t, { dataDir: dir });
148  const turn1 = first.run('chat-a06', 'SCRIPT:tool resume.txt once', { answer: 'approve' });
149  await turn1.promise;
150  const sessionId = first.bridge.sessionOf('chat-a06');
151  assert.ok(sessionId);
152  assert.equal(lines(join(first.ws, 'resume.txt')), 1);
153  await first.bridge.close();          // the host goes away; the Harness process with it
154
155  // A new host process over the same data directory.
156  const second = await rig(t, { dataDir: dir });
157  assert.equal(second.bridge.sessionOf('chat-a06'), sessionId, 'the chat keeps its session id');
158  const turn2 = second.run('chat-a06', 'SCRIPT:echo second turn');
159  await turn2.promise;
160  assert.equal(second.bridge.sessionOf('chat-a06'), sessionId);
161  assert.equal(text(turn2.frames), 'second turn');
162  assert.equal(turn2.frames.filter(f => f.type === 'agent-tool').length, 0, 'no tool card appears on resume');
163  assert.equal(lines(join(second.ws, 'resume.txt')), 1, 'the earlier tool effect was not replayed');
164  // The agent really carried the earlier conversation: its request holds the earlier turn too.
165  const resumed = second.worker.requests.find(q => q.toolNames.length);
166  assert.ok(resumed.messageCount > 5, `expected earlier messages in the request, saw ${resumed.messageCount}`);
167});
168
169test('A08 two chats run independently, each with its own session and approval', { skip }, async t => {
170  const r = await rig(t);
171  const a = r.run('chat-a08-a', 'SCRIPT:tool a.txt A');        // will wait on approval
172  for (let i = 0; i < 200 && !states(a.frames).includes('proposed'); i++) await new Promise(x => setTimeout(x, 50));
173  assert.ok(states(a.frames).includes('proposed'));
174  const b = r.run('chat-a08-b', 'SCRIPT:hello');
175  await b.promise;                                             // B finishes while A is parked on an approval
176  assert.equal(text(b.frames), 'Hello from the scripted worker.');
177  assert.equal(states(a.frames).at(-1), 'proposed', 'A is still waiting');
178  assert.notEqual(r.bridge.sessionOf('chat-a08-a'), r.bridge.sessionOf('chat-a08-b'));
179  assert.equal(r.bridge.pendingFor('chat-a08-b').length, 0);
180  assert.equal(r.bridge.pendingFor('chat-a08-a').length, 1);
181  assert.deepEqual(r.bridge.pendingAll().map(c => c.chatId), ['chat-a08-a'], 'the board lists every chat that waits, and only those');
182  const callId = a.frames.find(f => f.type === 'agent-tool').tool.id;
183  // An approval cannot be answered through the wrong chat.
184  await assert.rejects(r.bridge.approve({ chatId: 'chat-a08-b', callId, decision: 'approve' }), /no longer waiting/);
185  await r.bridge.approve({ chatId: 'chat-a08-a', callId, decision: 'approve' });
186  await a.promise;
187  assert.equal(states(a.frames).at(-1), 'done');
188  assert.equal(lines(join(r.ws, 'a.txt')), 1);
189});
190
191test('a second send to a chat that is mid-turn is refused', { skip }, async t => {
192  const r = await rig(t);
193  const first = r.run('chat-busy', 'SCRIPT:slow 80');
194  for (let i = 0; i < 100 && !first.frames.some(f => f.type === 'delta'); i++) await new Promise(x => setTimeout(x, 50));
195  await assert.rejects(r.run('chat-busy', 'SCRIPT:hello').promise, /still working/);
196  await first.promise;
197});
198
199test('an API connection becomes a route; its key reaches the model by reference and nowhere else', { skip }, async t => {
200  const secret = 'sk-test-SECRET-0123456789abcdef';
201  const dir = mkdtempSync(join(tmpdir(), 'strata-agent-keys-'));
202  t.after(() => cleanup(dir));
203  const apiWorker = await startScriptedWorker({ model: 'cloud-model' });
204  t.after(() => apiWorker.close());
205  const connections = [{ id: 'abcd1234-conn', name: 'Cloud test', baseUrl: apiWorker.url, protocol: 'openai-chat', apiKey: secret, models: [{ id: 'cloud-model', name: 'Cloud model', contextMax: 64000 }] }];
206  const r = await rig(t, { dataDir: dir, connections });
207  const frames = [];
208  await r.bridge.runTurn({ chatId: 'chat-api', message: 'SCRIPT:hello', workspacePath: r.ws, choice: { connectionId: 'abcd1234-conn', modelId: 'cloud-model' }, onFrame: f => frames.push(f) });
209  assert.equal(frames.find(f => f.type === 'start').remoteModel, true);
210  assert.equal(frames.find(f => f.type === 'start').model, 'Cloud model');
211  assert.equal(text(frames), 'Hello from the scripted worker.');
212  // The chat used the API worker, the local worker was never asked.
213  assert.ok(apiWorker.requests.length >= 1); assert.equal(r.worker.requests.length, 0);
214  const expected = createHash('sha256').update(`Bearer ${secret}`).digest('hex');
215  assert.ok(apiWorker.requests.every(q => q.authSha === expected), 'the key arrived as the bearer credential');
216  // A different chat on the local default is unaffected by the first chat's choice.
217  const local = []; await r.bridge.runTurn({ chatId: 'chat-local', message: 'SCRIPT:hello', workspacePath: r.ws, onFrame: f => local.push(f) });
218  assert.equal(local.find(f => f.type === 'start').remoteModel, false);
219  assert.ok(r.worker.requests.length >= 1);
220
221  // The shell tool the agent runs must not see the key.
222  // Bypass: the dump is a plain in-workspace write, which Manual would (rightly) make the person approve first.
223  const env = r.run('chat-api', 'SCRIPT:envdump envdump.txt', { choice: { connectionId: 'abcd1234-conn', modelId: 'cloud-model' }, mode: 'bypass' });
224  await env.promise;
225  assert.ok(existsSync(join(r.ws, 'envdump.txt')), 'the env dump tool must have run');
226  const dump = readFileSync(join(r.ws, 'envdump.txt'), 'utf8');
227  assert.match(dump, /^PATH=/im, 'the dump must really list the environment, or its silence about the key proves nothing');
228  assert.ok(!dump.includes(secret), 'the agent shell must not inherit the key');
229  // Nowhere on disk the host wrote: profile, logs, session map. (The compressed session store is checked by absence in frames.)
230  const stack = [join(dir, 'agent')];
231  while (stack.length) {
232    const p = stack.pop();
233    if (statSync(p).isDirectory()) { if (p.endsWith('home')) continue; for (const n of readdirSync(p)) stack.push(join(p, n)); continue; }
234    assert.ok(!readFileSync(p).includes(secret), `${p} must not contain the key`);
235  }
236  assert.ok(!JSON.stringify(frames).includes(secret) && !JSON.stringify(r.bridge.status()).includes(secret));
237});
238
239test('a missing or removed connection is a typed error, never another model', { skip }, async t => {
240  const r = await rig(t);
241  await assert.rejects(r.bridge.runTurn({ chatId: 'chat-gone', message: 'SCRIPT:hello', workspacePath: r.ws, choice: { connectionId: 'nope', modelId: 'm' }, onFrame: () => {} }), err => err.code === 'model-unavailable');
242  assert.equal(r.worker.requests.length, 0, 'nothing was sent to the local model instead');
243});
244
245test('A05c Stop pressed while the agent is still starting cancels the start, and nothing reaches the model', { skip }, async t => {
246  const r = await rig(t);
247  const { frames, promise } = r.run('chat-a05c', 'SCRIPT:slow 200');
248  await new Promise(x => setTimeout(x, 150));          // the Harness process takes about two seconds to boot
249  const stopped = await r.bridge.stop('chat-a05c');
250  assert.equal(stopped.stopped, true);
251  const result = await promise;
252  assert.equal(result.cancelled, true);
253  assert.equal(frames.at(-1).finishReason, 'aborted');
254  assert.equal(r.worker.requests.length, 0, 'the model was never asked');
255  // The chat is usable afterwards.
256  const again = r.run('chat-a05c', 'SCRIPT:echo fine'); await again.promise;
257  assert.equal(text(again.frames), 'fine');
258});
259
260test('a leftover agent from a host that died is stopped at the next start, and an unrelated PID is never touched', { skip }, async t => {
261  const { HarnessProcess, stopStaleAgent } = await import('../server/agent/harness-runtime.mjs');
262  const { buildProfile } = await import('../server/agent/profile.mjs');
263  const { writeFileSync } = await import('node:fs');
264  const { spawn } = await import('node:child_process');
265  const dir = mkdtempSync(join(tmpdir(), 'strata-stale-'));
266  t.after(() => cleanup(dir));
267  const profile = buildProfile({ local: [{ id: 'x', baseUrl: 'http://127.0.0.1:9/v1', modelId: 'm', context: 8192 }] });
268  const patchFile = join(dir, 'p.patch.yml'); writeFileSync(patchFile, profile.patch);
269  const pidFile = join(dir, 'harness.pid');
270  const hp = new HarnessProcess({ harness: resolveHarness({ env: process.env }), home: join(dir, 'home'), patchFile, cwd: join(dir, 'run'), env: profile.env, pidFile });
271  await hp.start({ timeoutMs: 90_000 });
272  const pid = hp.pid;
273  assert.ok(existsSync(pidFile), 'the agent records its PID');
274  // The host "dies": nothing calls stop(). The next start finds the record.
275  assert.equal(stopStaleAgent(pidFile), pid);
276  for (let i = 0; i < 50 && hp.exited === null; i++) await new Promise(x => setTimeout(x, 100));
277  assert.notEqual(hp.exited, null, 'the leftover agent was stopped');
278  assert.equal(existsSync(pidFile), false);
279
280  // A record that points at some other process must not kill it.
281  const bystander = spawn(process.execPath, ['-e', 'setTimeout(() => {}, 60000)'], { stdio: 'ignore' });
282  t.after(() => bystander.kill());
283  writeFileSync(pidFile, JSON.stringify({ pid: bystander.pid }));
284  assert.equal(stopStaleAgent(pidFile), null);
285  await new Promise(x => setTimeout(x, 300));
286  assert.equal(bystander.exitCode, null, 'an unrelated process is left alone');
287});
288
289const until = async (fn, ms = 30_000) => { const t0 = Date.now(); for (;;) { const v = fn(); if (v) return v; if (Date.now() - t0 > ms) return null; await new Promise(x => setTimeout(x, 50)); } };
290
291test('a question the agent asks the person waits for the person (#4244); a skip lets the model carry on and the turn does not hang', { skip }, async t => {
292  const r = await rig(t);
293  const { frames, promise } = r.run('chat-ask', 'SCRIPT:ask');
294  const asked = await until(() => frames.find(f => f.type === 'agent-question'));
295  assert.ok(asked, 'the question reaches the page as a frame');
296  assert.equal(asked.questions[0].id, 'q1'); assert.deepEqual(asked.questions[0].options.map(o => o.label), ['Red', 'Blue']);
297  await r.bridge.answerQuestion({ chatId: 'chat-ask', callId: asked.callId, skip: true });
298  const result = await Promise.race([promise, new Promise(x => setTimeout(() => x('hung'), 30_000))]);
299  assert.notEqual(result, 'hung', 'the turn must not wait forever once the question is skipped');
300  assert.equal(frames.at(-1).type, 'done');
301  assert.equal(frames.filter(f => f.type === 'agent-tool').at(-1).tool.name, 'ask_user_question');
302  assert.match(text(frames), /Tool finished/, 'the model got the result back and finished');
303});
304
305test('an answer to the question of the agent reaches the model as the tool result (#4244)', { skip }, async t => {
306  const r = await rig(t);
307  const { frames, promise } = r.run('chat-ask2', 'SCRIPT:ask');
308  const asked = await until(() => frames.find(f => f.type === 'agent-question'));
309  assert.ok(asked);
310  await assert.rejects(r.bridge.answerQuestion({ chatId: 'chat-ask2', callId: asked.callId, answers: [{ id: 'q1', selected: ['Green'] }] }), /Answer every question/, 'a label that was not offered is not an answer');
311  await r.bridge.answerQuestion({ chatId: 'chat-ask2', callId: asked.callId, answers: [{ id: 'q1', selected: ['Blue'] }] });
312  await promise;
313  const tool = frames.filter(f => f.type === 'agent-tool').at(-1).tool;
314  assert.notEqual(tool.state, 'error', 'the tool was answered, not declared unanswerable');
315  assert.match(JSON.stringify([...r.worker.requests].at(-1).raw), /Blue/, 'the model was told what the person chose');
316  await assert.rejects(r.bridge.answerQuestion({ chatId: 'chat-ask2', callId: asked.callId, skip: true }), /already answered/, 'an answer is final');
317});