okami.mom/strata

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

Niko1221Merge f-023-int into f-023-guifcb0c2d0e

main
9.3 KiB144 linesraw
1// T7 (tools and images review, 2026-10-22): a custom command tool runs in the shell that suits it, in the folder it needs, and with a time
2// limit the person can raise. These tests run real commands; they use only what every machine has (node).
3import test from 'node:test';
4import assert from 'node:assert/strict';
5import { mkdtempSync, mkdirSync, rmSync, writeFileSync, realpathSync } from 'node:fs';
6import { tmpdir, homedir } from 'node:os';
7import { join } from 'node:path';
8import { spawn } from 'node:child_process';
9import { fileURLToPath } from 'node:url';
10import { createAgentTools } from '../server/agent/tools-settings.mjs';
11import { runCommand, planShell, looksLikePowerShell, resolveCwd, clampTimeoutSec, DEFAULT_TIMEOUT_SEC } from '../server/agent/custom-command-run.mjs';
12
13const SERVER = fileURLToPath(new URL('../server/agent/custom-tools-mcp.mjs', import.meta.url));
14const node = JSON.stringify(process.execPath);
15const WIN = process.platform === 'win32';
16
17test('a Windows command that reads as PowerShell goes to PowerShell, the rest to cmd.exe, and a named shell is honoured', () => {
18  for (const c of ['Get-Content notes.txt', 'Start-Process notepad', 'Get-ChildItem | Where-Object { $_.Length -gt 1 }', '$env:HOME', 'echo $(Get-Date)'])
19    assert.ok(looksLikePowerShell(c), c);
20  for (const c of ['dir', 'type notes.txt', 'python tools\\foo.py --x', 'npm run build && echo done', 'echo %PATH%', 'git status'])
21    assert.ok(!looksLikePowerShell(c), c);
22  const ps = planShell('Get-Content x', { platform: 'win32' });
23  assert.match(ps.file, /^(pwsh|powershell\.exe)$/);
24  assert.deepEqual(ps.args.slice(0, 5), ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command']);
25  assert.equal(ps.args.at(-1), 'Get-Content x');
26  assert.deepEqual(planShell('dir', { platform: 'win32' }), { file: 'dir', args: [], shell: true, name: 'cmd.exe' });
27  assert.equal(planShell('dir', { platform: 'win32', shell: 'powershell' }).args.at(-1), 'dir');
28  assert.equal(planShell('Get-Content x', { platform: 'win32', shell: 'cmd' }).shell, true);
29  assert.deepEqual(planShell('ls -la', { platform: 'linux' }), { file: 'ls -la', args: [], shell: true, name: 'sh' });
30  assert.deepEqual(planShell('ls | wc -l', { platform: 'linux', shell: 'bash' }), { file: 'bash', args: ['-c', 'ls | wc -l'], shell: false, name: 'bash' });
31  assert.equal(planShell('Get-Content x', { platform: 'linux' }).name, 'sh', 'on Linux and macOS a PowerShell-looking command is not rerouted');
32});
33
34test('the time allowed is 2 minutes unless the tool says more, at most an hour', () => {
35  assert.equal(DEFAULT_TIMEOUT_SEC, 120);
36  assert.equal(clampTimeoutSec(undefined), 120);
37  assert.equal(clampTimeoutSec(600), 600);
38  assert.equal(clampTimeoutSec(99999), 3600);
39  assert.equal(clampTimeoutSec(0), 120);
40  assert.equal(clampTimeoutSec('abc'), 120);
41});
42
43test('a command runs in the folder the call names, then the tool\'s, then the home folder; a missing folder is a plain refusal', async () => {
44  const dir = realpathSync(mkdtempSync(join(tmpdir(), 'strata-cmd-')));
45  const other = join(dir, 'other'); mkdirSync(other);
46  try {
47    const pwd = `${node} -e "console.log(process.cwd())"`;
48    const here = await runCommand({ command: pwd, cwd: dir });
49    assert.equal(realpathSync(here.text), dir);
50    const named = await runCommand({ command: pwd, cwd: dir, callCwd: other });
51    assert.equal(realpathSync(named.text), other, 'the folder named in the call wins');
52    const home = await runCommand({ command: pwd });
53    assert.equal(realpathSync(home.text), realpathSync(homedir()));
54    const gone = await runCommand({ command: pwd, cwd: join(dir, 'nope') });
55    assert.equal(gone.ok, false);
56    assert.match(gone.text, /does not exist, so the command was not run/);
57    assert.deepEqual(resolveCwd(''), { cwd: homedir() });
58  } finally { rmSync(dir, { recursive: true, force: true }); }
59});
60
61test('a relative path in the command finds its file in the tool\'s folder', async () => {
62  const dir = realpathSync(mkdtempSync(join(tmpdir(), 'strata-cmd-')));
63  try {
64    mkdirSync(join(dir, 'tools'));
65    writeFileSync(join(dir, 'tools', 'foo.js'), 'console.log("from foo " + (process.env.STRATA_INPUT || ""));');
66    const r = await runCommand({ command: `${node} tools/foo.js`, cwd: dir, input: 'hello' });
67    assert.deepEqual([r.ok, r.text], [true, 'from foo hello']);
68  } finally { rmSync(dir, { recursive: true, force: true }); }
69});
70
71test('a command over the limit is ended and says so; output over the cap says it was cut', async () => {
72  const slow = await runCommand({ command: `${node} -e "setTimeout(()=>{}, 30000)"`, timeoutSec: 1 });
73  assert.equal(slow.ok, false);
74  assert.match(slow.text, /stopped after 1 seconds/);
75  const big = await runCommand({ command: `${node} -e "process.stdout.write('x'.repeat(50000))"` });
76  assert.equal(big.ok, true);
77  assert.match(big.text, /\(The output was cut after 20,000 characters\.\)$/);
78  assert.ok(big.text.length < 20100);
79});
80
81test('PowerShell commands run on Windows (Get-ChildItem, $env:)', { skip: !WIN && 'PowerShell is checked on Windows' }, async () => {
82  const r = await runCommand({ command: 'Write-Output ("a" + $env:STRATA_INPUT)', input: 'b' });
83  assert.deepEqual([r.ok, r.text], [true, 'ab']);
84  const dir = realpathSync(mkdtempSync(join(tmpdir(), 'strata-cmd-')));
85  try {
86    writeFileSync(join(dir, 'note.txt'), 'hi');
87    const read = await runCommand({ command: 'Get-Content note.txt', cwd: dir });
88    assert.deepEqual([read.ok, read.text], [true, 'hi']);
89  } finally { rmSync(dir, { recursive: true, force: true }); }
90});
91
92test('Settings keeps a command tool\'s folder, shell and time, validates them, and an edit that does not send them keeps them', () => {
93  let stored;
94  const dir = mkdtempSync(join(tmpdir(), 'strata-cmdset-'));
95  try {
96    const tools = createAgentTools({ read: () => stored, write: v => { stored = v; }, dataDir: dir });
97    tools.addCustom({ name: 'Build', about: 'Builds the project.', kind: 'command', command: 'npm run build', cwd: 'C:\\work\\app', shell: 'cmd', timeoutSec: 900 });
98    let tool = tools.view().custom[0];
99    assert.deepEqual([tool.cwd, tool.shell, tool.timeoutSec], ['C:\\work\\app', 'cmd', 900]);
100    tools.editCustom(tool.id, { name: 'Build', about: 'Builds the project, quickly.', kind: 'command', command: 'npm run build' });   // the form sends none of the three
101    tool = tools.view().custom[0];
102    assert.deepEqual([tool.about, tool.cwd, tool.shell, tool.timeoutSec], ['Builds the project, quickly.', 'C:\\work\\app', 'cmd', 900]);
103    assert.throws(() => tools.editCustom(tool.id, { name: 'Build', about: 'x', kind: 'command', command: 'npm run build', timeoutSec: 99999 }), /1 to 3600/);
104    assert.throws(() => tools.editCustom(tool.id, { name: 'Build', about: 'x', kind: 'command', command: 'npm run build', shell: 'fish' }), /Choose how the command runs/);
105    tools.addCustom({ name: 'Plain', about: 'Plain.', kind: 'command', command: 'echo hi' });
106    const plain = tools.view().custom[1];
107    assert.deepEqual([plain.cwd, plain.shell, plain.timeoutSec], ['', 'auto', 120]);
108    // the tool server's file carries them
109    const file = JSON.parse(require_read(tools.filePath));
110    assert.deepEqual(file.commands.build, { description: 'Builds the project, quickly.', command: 'npm run build', cwd: 'C:\\work\\app', shell: 'cmd', timeoutSec: 900 });
111  } finally { rmSync(dir, { recursive: true, force: true }); }
112});
113
114import { readFileSync } from 'node:fs';
115const require_read = file => readFileSync(file, 'utf8');
116
117test('the tool server over stdio: the call may name a folder, and the tool\'s own settings apply', async () => {
118  const dir = realpathSync(mkdtempSync(join(tmpdir(), 'strata-cmdsrv-')));
119  const work = join(dir, 'work'); mkdirSync(work);
120  const file = join(dir, 'tools.json');
121  writeFileSync(file, JSON.stringify({ commands: {
122    where: { description: 'Prints its folder.', command: `${node} -e "console.log(process.cwd())"` },
123    pinned: { description: 'Runs in work.', command: `${node} -e "console.log(process.cwd())"`, cwd: work },
124  } }));
125  const child = spawn(process.execPath, [SERVER, 'commands', file], { stdio: ['pipe', 'pipe', 'inherit'] });
126  const lines = []; let buffer = '';
127  child.stdout.on('data', d => { buffer += d; let i; while ((i = buffer.indexOf('\n')) >= 0) { lines.push(JSON.parse(buffer.slice(0, i))); buffer = buffer.slice(i + 1); } });
128  const ask = async (id, method, params) => {
129    child.stdin.write(JSON.stringify({ jsonrpc: '2.0', id, method, params }) + '\n');
130    for (let n = 0; n < 200; n++) { const hit = lines.find(l => l.id === id); if (hit) return hit.result; await new Promise(r => setTimeout(r, 25)); }
131    throw new Error('no answer');
132  };
133  try {
134    const listed = await ask(1, 'tools/list', {});
135    assert.ok(listed.tools.every(t => t.inputSchema.properties.cwd?.type === 'string'), 'the optional folder is offered');
136    const pinned = await ask(2, 'tools/call', { name: 'pinned', arguments: {} });
137    assert.equal(realpathSync(pinned.content[0].text), work);
138    const named = await ask(3, 'tools/call', { name: 'where', arguments: { cwd: dir } });
139    assert.equal(realpathSync(named.content[0].text), dir);
140    const missing = await ask(4, 'tools/call', { name: 'where', arguments: { cwd: join(dir, 'nope') } });
141    assert.equal(missing.isError, true);
142    assert.match(missing.content[0].text, /does not exist/);
143  } finally { child.kill(); rmSync(dir, { recursive: true, force: true }); }
144});