okami.mom/strata

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

Niko1221rc1 merge ds-coder (d6a5a7837)4fb068a8c

main
21.1 KiB287 linesraw
1/**
2 * The agent's tools in the app: the inventory, a tool from each family, and Manual mode's one approval card.
3 *
4 * Pure tests (the gate's rules, the preset list, the profile) always run. The rest need a built Harness
5 * (STRATA_HARNESS_DIR) and skip loudly without it. The model is scripted (tests/helpers/scripted-worker.mjs): what is real is
6 * the Harness, its tool executor, its sandbox, its approval service, the Strata gate plugin and the bridge.
7 */
8import test from 'node:test';
9import assert from 'node:assert/strict';
10import { existsSync, mkdtempSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
11import { tmpdir } from 'node:os';
12import { join } from 'node:path';
13import { startScriptedWorker } from './helpers/scripted-worker.mjs';
14import { createAgentBridge } from '../server/agent/agent-bridge.mjs';
15import { resolveHarness } from '../server/agent/harness-runtime.mjs';
16import { buildProfile, GATE_PLUGIN } from '../server/agent/profile.mjs';
17import { STANDARD_PLUGIN_IDS, REMOVED_PLUGIN_IDS, standardPreset } from '../server/agent/preset.mjs';
18import { isReadOnlyShell, manualDecision, maskQuotes, READ_ONLY_TOOLS } from '../server/agent/plugins/strata-gate.mjs';
19import { plainToolError, withPlain } from '../server/agent/events.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;
23const cleanup = dir => { try { rmSync(dir, { recursive: true, force: true, maxRetries: 3 }); } catch { /* the Harness sandbox leaves access entries; best effort */ } };
24const fwd = p => p.replaceAll('\\', '/');
25
26// ---------------------------------------------------------------------------------------------------------- pure
27
28test('the gate: only commands that provably just look are allowed without a question', () => {
29  for (const ok of ['Get-ChildItem', 'Get-ChildItem -Recurse src | Select-Object -First 5', 'git status', 'git log --oneline -5', 'git diff', 'cat notes.txt', 'ls -la', 'node --version', 'Get-Content a.txt | Select-String needle', 'git branch', 'git remote -v']) {
30    assert.equal(isReadOnlyShell(ok), true, ok);
31  }
32  for (const bad of ['', 'Set-Content a.txt x', 'echo hi > a.txt', 'Get-ChildItem; Remove-Item a.txt', 'rm -rf x', 'git commit -m x', 'git push', 'git branch -D x', 'git config user.name x', 'git remote add o u', 'curl http://x', 'Get-ChildItem | ForEach-Object { $_ }', 'Start-Process explorer.exe', 'explorer.exe C:/Users/x/Downloads', 'ii ~/Downloads', 'Invoke-Item $env:USERPROFILE/Downloads', 'start .', 'open .', 'xdg-open .', 'notepad a.txt', 'powershell -Command x', 'node script.js', 'python x.py', 'ls && rm a', 'find . -delete', 'echo $(whoami)', 'Invoke-WebRequest u', 'Start-Process x', 'New-Item a', 'cat a | tee b']) {
33    assert.equal(isReadOnlyShell(bad), false, bad);
34  }
35  assert.equal(isReadOnlyShell('x'.repeat(700)), false, 'a long command is never trusted');
36});
37
38test('the gate: quoted text is data, so an & ( ) ; { } in a quoted path does not make a look-only command ask (2026-10-22)', () => {
39  for (const ok of [
40    'Get-ChildItem "C:\\Users\\AI-Server\\Downloads\\GUI Q&A" | Select-Object -First 5 Name',
41    'Get-Content "C:\\Users\\AI-Server\\Downloads\\GUI Q&A\\a.txt"',
42    "Get-ChildItem 'C:\\Users\\x\\Notes (old) {draft}; v2'",
43    'Select-String -Path a.txt "a|b"',
44    'Select-String needle "C:\\x\\a & b.txt" | Measure-Object',
45    'git log --oneline "docs/Q&A.md"',
46    'cat "my file (1).txt"',
47    "Get-ChildItem 'it''s here'",
48  ]) assert.equal(isReadOnlyShell(ok), true, ok);
49  // Quoting does not hide anything that acts: outside the quotes the same characters still ask, and inside double quotes an expansion does.
50  for (const bad of [
51    'Get-ChildItem C:\\Q&A',
52    'Get-ChildItem "C:\\a" ; Remove-Item x',
53    'Get-ChildItem "C:\\a" & calc',
54    'Get-ChildItem "C:\\a" > out.txt',
55    'Get-ChildItem "$env:USERPROFILE"',
56    'Get-ChildItem "$(whoami)"',
57    'Get-ChildItem "a`b"',
58    "Get-ChildItem 'unterminated",
59    'Get-ChildItem "unterminated',
60    'git diff "--output=out.txt"',
61    'git diff --out"put"=out.txt',
62    'git diff --"output"=out.txt',
63    'Get-Content "a"b',
64    '"Remove-Item" x',
65    'Set-Content "a.txt" "x"',
66    'Get-ChildItem "a" | Remove-Item',
67    'curl "http://x"',
68  ]) assert.equal(isReadOnlyShell(bad), false, bad);
69  assert.equal(maskQuotes('Get-ChildItem "C:\\Q&A" | Select-Object Name'), 'Get-ChildItem "_" | Select-Object Name');
70  assert.equal(maskQuotes("echo 'a' \"b\""), 'echo "_" "_"');
71  assert.equal(maskQuotes('echo "$HOME"'), null);
72});
73
74test('the gate: every tool outside the read-only list asks, including unknown and connected ones', () => {
75  for (const name of READ_ONLY_TOOLS) assert.equal(manualDecision({ name, arguments: {} }), null, name);
76  for (const name of ['write', 'edit', 'job_kill', 'mcp__github__create_issue', 'something_new']) assert.equal(manualDecision({ name, arguments: {} })?.kind, 'ask', name);
77  assert.equal(manualDecision({ name: 'pwsh', arguments: { command: 'Get-ChildItem' } }), null);
78  assert.match(manualDecision({ name: 'pwsh', arguments: { command: 'Remove-Item x', description: 'Delete x' } }).reason, /Delete x/);
79  assert.match(manualDecision({ name: 'write', arguments: { file_path: 'C:/a/b.txt' } }).reason, /b\.txt/);
80  assert.equal(manualDecision({ name: 'pwsh', arguments: {} }).kind, 'ask', 'no command is not a read-only command');
81});
82
83test('the preset: our list is the Harness standard list minus exactly what the app replaces', () => {
84  const ids = standardPreset({ platform: 'win32' }).plugins.map(p => p.id);
85  assert.deepEqual(ids, STANDARD_PLUGIN_IDS.filter(id => !REMOVED_PLUGIN_IDS.includes(id) && id !== 'tool-bash'));
86  assert.ok(standardPreset({ platform: 'linux' }).plugins.some(p => p.id === 'tool-bash') && !standardPreset({ platform: 'linux' }).plugins.some(p => p.id === 'tool-pwsh'));
87  const web = standardPreset().plugins.find(p => p.id === 'tool-web').config;
88  assert.equal(web.fetch, true); assert.equal(web.search, false, 'the preset alone leaves search to the profile, which switches it on (DuckDuckGo needs no key)');
89  assert.equal(standardPreset({ search: true }).plugins.find(p => p.id === 'tool-web').config.search, true);
90  assert.ok(!ids.includes('tool-schedule'), 'Tasks is the only scheduler');
91});
92
93test('the profile loads the gate by path, sizes helper agents to the engine slots and keeps no secret', () => {
94  const p = buildProfile({ local: [{ id: 'a', baseUrl: 'http://127.0.0.1:1/v1', modelId: 'm', context: 32768, slots: 2, key: 'sekret-key-123' }] });
95  const entries = JSON.parse(p.patch.split('\n').slice(1).join('\n'));
96  assert.deepEqual(entries.find(e => e.insert)?.insert, [{ id: 'strata-gate', name: GATE_PLUGIN, config: { web: { provider: 'DuckDuckGo, or Bing when DuckDuckGo is busy', skipAsk: false } } }]);
97  assert.ok(existsSync(GATE_PLUGIN));
98  assert.equal(entries.find(e => e.id === 'subagent').config.maxActiveSubagents, 4, 'at least the 4 helpers; more only with more slots');
99  assert.equal(entries.find(e => e.id === 'preset-standard').config.plugins.some(x => x.id === 'tool-schedule'), false);
100  assert.ok(!p.patch.includes('sekret-key-123'));
101  const api = buildProfile({ local: [], connections: [{ id: 'c1', name: 'C', baseUrl: 'https://x/v1', protocol: 'openai-chat', models: [{ id: 'm' }] }] });
102  assert.equal(JSON.parse(api.patch.split('\n').slice(1).join('\n')).find(e => e.id === 'subagent').config.maxActiveSubagents, 8, 'API models take the Harness limit');
103});
104
105test('tool failures are said in plain words with the original text kept after them', () => {
106  assert.match(plainToolError('Error: URL hostname "127.0.0.1" resolves to a non-public IP address'), /web page could not be opened/);
107  assert.match(plainToolError('Error: invalid arguments: missing required property "files"'), /wrong way/);
108  assert.equal(plainToolError('something unusual'), null);
109  const text = withPlain('Error: web fetch failed: Error: getaddrinfo ENOTFOUND example.invalid');
110  assert.match(text, /^That web page could not be opened/);
111  assert.match(text, /Details: web fetch failed/);
112});
113
114// ------------------------------------------------------------------------------------------------- real Harness
115
116async function rig(t) {
117  const worker = await startScriptedWorker({});
118  const dir = mkdtempSync(join(tmpdir(), 'strata-tools-'));
119  const ws = join(dir, 'ws'); mkdirSync(ws, { recursive: true });
120  const local = [{ id: 'inst-1', label: 'Scripted', baseUrl: worker.url, modelId: 'scripted-model', context: 32768, slots: 4 }];
121  const bridge = createAgentBridge({ dataDir: dir, localInstances: () => local, connections: () => [], env: process.env, startTimeoutMs: 90_000 });
122  t.after(async () => { await bridge.close(); await worker.close(); cleanup(dir); });
123  const run = async (chatId, message, { mode = 'bypass', answer } = {}) => {
124    const frames = [];
125    await bridge.runTurn({
126      chatId, message, workspacePath: ws, mode,
127      onFrame: f => {
128        frames.push(f);
129        if (answer && f.type === 'agent-tool' && f.tool.state === 'proposed') void bridge.approve({ chatId, callId: f.tool.id, decision: answer }).catch(e => frames.push({ type: 'test-error', message: e.message }));
130      },
131    });
132    return frames;
133  };
134  const call = (chatId, tool, args, options) => run(chatId, `SCRIPT:call ${tool} ${JSON.stringify(args)}`, options);
135  return { worker, bridge, dir, ws, run, call };
136}
137const cards = frames => frames.filter(f => f.type === 'agent-tool').map(f => f.tool);
138const last = frames => cards(frames).at(-1);
139
140test('the agent is offered exactly these tools: everything useful including web search (no key needed), no scheduler, and the question tool the app can answer', { skip }, async (t) => {
141  const r = await rig(t);
142  await r.run('inv', 'SCRIPT:echo hi');
143  const offered = [...r.worker.requests].reverse().find(q => q.toolNames.length)?.toolNames.sort();
144  assert.deepEqual(offered, ['ask_user_question', 'create_goal', 'edit', 'get_goal', 'glob', 'grep', 'interrupt_agent', 'job_kill', 'job_list', 'job_output', 'list_agents', 'list_subagent_models', 'present', 'pwsh', 'read', 'read_image', 'send_message', 'skill', 'subagent', 'subagent_fork', 'todo_write', 'update_goal', 'web_fetch', 'web_search', 'workflow', 'working_directory', 'write'].sort());
145  assert.ok(!offered.some(n => n.startsWith('schedule_')) && offered.includes('web_search') && offered.includes('ask_user_question') && !offered.includes('exit_plan_mode'));
146});
147
148test('a tool from each family runs and shows a card the page can render', { skip }, async (t) => {
149  const r = await rig(t);
150  const file = join(r.ws, 'notes.txt');
151  writeFileSync(file, 'alpha\nneedle here\nomega\n');
152  const f = fwd(file);
153  // read-only family
154  assert.match(last(await r.call('fam-r', 'read', { file_path: f })).result, /needle here/);
155  assert.match(last(await r.call('fam-g', 'glob', { pattern: '*.txt' })).result, /notes\.txt/);
156  assert.match(last(await r.call('fam-s', 'grep', { pattern: 'needle' })).result, /Line 2/);
157  assert.equal(last(await r.call('fam-w', 'working_directory', {})).state, 'done');
158  assert.equal(last(await r.call('fam-j', 'job_list', {})).state, 'done');
159  // plan / list family
160  assert.equal(last(await r.call('fam-t', 'todo_write', { todos: [{ content: 'check the build', status: 'pending' }] })).state, 'done');
161  const goal = last(await r.call('fam-goal', 'create_goal', { objective: 'finish the notes' }));
162  assert.equal(goal.state, 'done'); assert.equal(goal.effect, 'Sets a goal to work towards.');
163  // write family (Bypass: no card asks)
164  const wrote = await r.call('fam-fs', 'write', { file_path: fwd(join(r.ws, 'new.txt')), content: 'made\n' });
165  assert.equal(last(wrote).state, 'done'); assert.equal(readFileSync(join(r.ws, 'new.txt'), 'utf8').trim(), 'made');
166  await r.call('fam-fs', 'read', { file_path: f });
167  const edited = await r.call('fam-fs', 'edit', { file_path: f, old_string: 'alpha', new_string: 'ALPHA' });
168  assert.equal(last(edited).state, 'done'); assert.match(readFileSync(file, 'utf8'), /^ALPHA/);
169  // shell family
170  assert.match(last(await r.call('fam-sh', 'pwsh', { command: 'Get-ChildItem', description: 'list files' })).result, /notes\.txt/);
171  // web family: offline, loopback is refused by the Harness itself; the failure is plain with Details after it
172  const web = last(await r.call('fam-web', 'web_fetch', { url: 'http://127.0.0.1:9/' }));
173  assert.equal(web.state, 'error'); assert.match(web.result, /^That web page could not be opened/); assert.match(web.result, /Details: /);
174  assert.equal(web.effect, 'Opens a web page.'); assert.equal(web.preview, 'http://127.0.0.1:9/');
175  // no card shows raw JSON as its explanation
176  for (const c of [last(await r.call('fam-t2', 'todo_write', { todos: [{ content: 'x', status: 'pending' }] }))]) assert.ok(!c.preview.startsWith('{'));
177});
178
179test('Manual: one change is one card. Nothing ran when it appeared, and no sandbox or PowerShell error was ever shown', { skip }, async (t) => {
180  const r = await rig(t);
181  const a = join(r.ws, 'a.txt'), b = join(r.ws, 'b.txt'), c = join(r.ws, 'c.txt');
182  // approve a file write
183  let frames = await r.call('man1', 'write', { file_path: fwd(a), content: 'hello\n' }, { mode: 'manual', answer: 'approve' });
184  assert.deepEqual(cards(frames).map(x => x.state), ['running', 'proposed', 'running', 'done']);
185  assert.equal(new Set(cards(frames).map(x => x.id)).size, 1, 'one card, updated in place');
186  assert.equal(readFileSync(a, 'utf8').trim(), 'hello');
187  // deny a file write
188  frames = await r.call('man2', 'write', { file_path: fwd(b), content: 'no\n' }, { mode: 'manual', answer: 'deny' });
189  assert.deepEqual(cards(frames).map(x => x.state), ['running', 'proposed', 'denied', 'denied']);
190  assert.equal(last(frames).result, 'Denied. Nothing ran.', 'the card says it in plain words, not the model-facing error');
191  assert.equal(existsSync(b), false);
192  // a shell command that changes things
193  frames = await r.call('man3', 'pwsh', { command: `Set-Content -Path '${c}' -Value x`, description: 'Make c.txt' }, { mode: 'manual', answer: 'approve' });
194  assert.deepEqual(cards(frames).map(x => x.state), ['running', 'proposed', 'running', 'done']);
195  assert.ok(existsSync(c));
196  // a shell command that only looks needs no question
197  frames = await r.call('man4', 'pwsh', { command: 'Get-ChildItem', description: 'List files' }, { mode: 'manual' });
198  assert.deepEqual(cards(frames).map(x => x.state), ['running', 'done']);
199  // nowhere in any of it does the person see the sandbox talking
200  const all = JSON.stringify([...cards(frames), ...cards(await r.call('man5', 'write', { file_path: fwd(join(r.ws, 'd.txt')), content: 'd' }, { mode: 'manual', answer: 'approve' }))]);
201  assert.ok(!/sandbox|Constrained|language mode|access denied/i.test(all), all.slice(0, 300));
202});
203
204test('Plan stays read-only and Bypass asks nothing', { skip }, async (t) => {
205  const r = await rig(t);
206  const p = join(r.ws, 'p.txt'), q = join(r.ws, 'q.txt');
207  const planned = await r.call('pl', 'write', { file_path: fwd(p), content: 'x' }, { mode: 'plan' });
208  assert.equal(existsSync(p), false);
209  assert.ok(!cards(planned).some(x => x.state === 'proposed'));
210  const free = await r.call('bp', 'write', { file_path: fwd(q), content: 'x' }, { mode: 'bypass' });
211  assert.equal(existsSync(q), true);
212  assert.ok(!cards(free).some(x => x.state === 'proposed'));
213});
214
215test('Manual refuses to start when the gate is not loaded (it would be an open sandbox that nobody asks about)', { skip }, async (t) => {
216  // A Harness started without the gate plugin (the bridge's `gate: false`).
217  const worker = await startScriptedWorker({});
218  const dir = mkdtempSync(join(tmpdir(), 'strata-nogate-'));
219  mkdirSync(join(dir, 'ws'), { recursive: true });
220  const local = [{ id: 'i', baseUrl: worker.url, modelId: 'scripted-model', context: 32768 }];
221  const bridge = createAgentBridge({ dataDir: dir, localInstances: () => local, connections: () => [], env: process.env, gate: false, startTimeoutMs: 90_000 });
222  t.after(async () => { await bridge.close(); await worker.close(); cleanup(dir); });
223  await assert.rejects(bridge.runTurn({ chatId: 'x', message: 'SCRIPT:echo hi', workspacePath: join(dir, 'ws'), mode: 'manual', onFrame: () => {} }), error => error.code === 'mode-unavailable' && /asks before changing/.test(error.message) && !/sandbox/i.test(error.message));
224});
225
226test('a tool server set up for the model is connected to the agent: its tools are offered, Manual asks before using them, and its secret never reaches a file', { skip }, async (t) => {
227  const worker = await startScriptedWorker({});
228  const dir = mkdtempSync(join(tmpdir(), 'strata-mcp-'));
229  const ws = join(dir, 'ws'); mkdirSync(ws, { recursive: true });
230  const mcpServers = { demo: { command: process.execPath, args: [fwd(join(import.meta.dirname, 'helpers', 'mini-mcp.mjs'))], env: { DEMO_TOKEN: 'tok-123456-secret' } }, off: { command: 'x', disabled: true } };
231  const local = [{ id: 'i', baseUrl: worker.url, modelId: 'scripted-model', context: 32768, slots: 2, mcpServers }];
232  const bridge = createAgentBridge({ dataDir: dir, localInstances: () => local, connections: () => [], env: process.env, startTimeoutMs: 90_000 });
233  t.after(async () => { await bridge.close(); await worker.close(); cleanup(dir); });
234  const frames = [];
235  await bridge.runTurn({ chatId: 'mcp-bypass', message: `SCRIPT:call mcp__demo__shout ${JSON.stringify({ text: 'hello' })}`, workspacePath: ws, mode: 'bypass', onFrame: f => frames.push(f) });
236  assert.ok([...worker.requests].reverse().find(q => q.toolNames.length).toolNames.includes('mcp__demo__shout'));
237  assert.ok(![...worker.requests].some(q => q.toolNames.some(n => n.startsWith('mcp__off'))), 'a disabled server is not connected');
238  const card = cards(frames).at(-1);
239  assert.equal(card.state, 'done'); assert.match(card.result, /HELLO\|token:set/, 'the secret reached the server through the environment');
240  assert.equal(card.scope, 'connected');
241  // Manual: a connected tool has unknown effects, so it asks first
242  const manual = [];
243  await bridge.runTurn({
244    chatId: 'mcp-manual', message: `SCRIPT:call mcp__demo__shout ${JSON.stringify({ text: 'ask me' })}`, workspacePath: ws, mode: 'manual',
245    onFrame: f => { manual.push(f); if (f.type === 'agent-tool' && f.tool.state === 'proposed') void bridge.approve({ chatId: 'mcp-manual', callId: f.tool.id, decision: 'approve' }); },
246  });
247  assert.deepEqual(cards(manual).map(c => c.state), ['running', 'proposed', 'running', 'done']);
248  assert.match(cards(manual)[1].effect, /Use the connected tool demo \/ shout/);
249  // the secret is in the environment of the agent only: never in the profile file
250  const files = JSON.stringify(readdirDeep(join(dir, 'agent')).filter(f => f.endsWith('.yml')).map(f => readFileSync(f, 'utf8')));
251  assert.ok(files.includes('process.env.STRATA_MCP_0_E_DEMO_TOKEN') && !files.includes('tok-123456-secret'));
252});
253
254function readdirDeep(dir) {
255  const out = [];
256  for (const e of readdirSync(dir, { withFileTypes: true })) { const p = join(dir, e.name); if (e.isDirectory()) out.push(...readdirDeep(p)); else out.push(p); }
257  return out;
258}
259
260test('the output budget is not the old 8192, and the Reasoning menu reaches the request (off sends enable_thinking false)', { skip }, async (t) => {
261  const worker = await startScriptedWorker({});
262  const dir = mkdtempSync(join(tmpdir(), 'strata-think-'));
263  const ws = join(dir, 'ws'); mkdirSync(ws, { recursive: true });
264  const local = [{ id: 'i', baseUrl: worker.url, modelId: 'scripted-model', context: 65536 }];
265  const bridge = createAgentBridge({ dataDir: dir, localInstances: () => local, connections: () => [], env: process.env, startTimeoutMs: 90_000 });
266  t.after(async () => { await bridge.close(); await worker.close(); cleanup(dir); });
267  const ask = async (chatId, thinking) => {
268    worker.requests.length = 0;
269    await bridge.runTurn({ chatId, message: 'SCRIPT:echo hi', workspacePath: ws, mode: 'bypass', thinking, onFrame: () => {} });
270    return worker.requests.find(r => r.toolNames.length).params;
271  };
272  const ctk = p => p.chat_template_kwargs ?? {};
273  const off = await ask('think-off', 'Off');
274  assert.equal(ctk(off).enable_thinking, false); assert.equal(ctk(off).reasoning_effort, undefined);
275  assert.equal(off.enable_thinking, undefined, 'a top-level enable_thinking is the field the Strata server ignores');
276  // The profile's budget (19,660 at 64K: what compaction sets aside for a reply) is the header the Harness reads; the request itself may produce half the window (AGENT-LOST).
277  assert.ok(off.max_completion_tokens === 32768, `ceiling ${off.max_completion_tokens} (half the window, at most 64K: never the old 8192, and a file written in one call is not cut at the 30 percent compaction reserves)`);
278  const high = await ask('think-high', 'High');
279  assert.equal(ctk(high).enable_thinking, true); assert.equal(ctk(high).reasoning_effort, 'high');
280  const low = await ask('think-low', 'Low');
281  assert.equal(ctk(low).enable_thinking, true); assert.equal(ctk(low).reasoning_effort, 'low');
282  const max = await ask('think-max', 'Max');
283  assert.equal(ctk(max).enable_thinking, true); assert.equal(ctk(max).reasoning_effort, 'high');
284  // the same chat switching its level between turns
285  assert.equal(ctk(await ask('think-off', 'High')).enable_thinking, true);
286  assert.equal(ctk(await ask('think-off', 'Off')).enable_thinking, false);
287});