Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

agent: custom command tools run in the right shell and folder, with a time the tool can raise (T7)

Niko1221a71fd347584a
diff --git a/apps/host/server/agent/custom-command-run.mjs b/apps/host/server/agent/custom-command-run.mjs
new file mode 100644
index 000000000..5543b38fb
--- /dev/null
+++ b/apps/host/server/agent/custom-command-run.mjs
@@ -0,0 +1,103 @@
+/**
+ * Runs the command of a command tool the person wrote (Settings -> Tools). Split from custom-tools-mcp.mjs so it can be tested.
+ *
+ * T7 (tools and images review, 2026-10-22). It used to run every command with `shell: true` (cmd.exe on Windows, so `Get-Content x` failed with
+ * "not recognized"), in whatever folder the host happened to run in (so `python tools/foo.py` could not find its file), and ended it after two
+ * minutes with 20,000 characters of output, silently cut.
+ *
+ * shell 'auto' (default): PowerShell for a Windows command that reads as PowerShell (Get-Content, Start-Process, $env:X, $(...)), cmd.exe for
+ * any other Windows command (so every command that worked keeps working), /bin/sh elsewhere. 'cmd', 'powershell', 'bash' and 'sh' name one.
+ * cwd the folder to run in: the tool's own, or the one the assistant names in the call (it knows the chat's folder); else the person's home.
+ * timeoutSec the time allowed, 1 to 3600 (default 120). A command that runs over is ended together with the programs it started.
+ */
+import { spawn, spawnSync } from 'node:child_process';
+import { existsSync, statSync } from 'node:fs';
+import { homedir } from 'node:os';
+
+export const DEFAULT_TIMEOUT_SEC = 120;
+export const MAX_TIMEOUT_SEC = 3600;
+export const OUT_MAX = 20000;
+export const SHELLS = ['auto', 'cmd', 'powershell', 'bash', 'sh'];
+
+/** A Windows command that is PowerShell and would fail in cmd.exe. */
+const POWERSHELL_LOOKS = /(^|[\s;|(&])[A-Z][A-Za-z]+-[A-Z][A-Za-z]+\b|\$\w|\$\(|\$env:|@\(|\|\s*(?:%|\?)\s*\{/;
+export const looksLikePowerShell = command => POWERSHELL_LOOKS.test(String(command ?? ''));
+
+let powershellFound;
+/** pwsh when it is installed (PowerShell 7), else the Windows PowerShell every Windows has. */
+function powershellExe(platform) {
+ if (powershellFound) return powershellFound;
+ if (platform !== 'win32') return (powershellFound = 'pwsh');
+ try { if (spawnSync('where', ['pwsh'], { windowsHide: true, timeout: 5000 }).status === 0) return (powershellFound = 'pwsh'); } catch { /* none */ }
+ return (powershellFound = 'powershell.exe');
+}
+
+/**
+ * -> { file, args, shell } for spawn: which program runs `command`.
+ * @param {string} command
+ * @param {{shell?: string, platform?: string}} [options]
+ */
+export function planShell(command, { shell = 'auto', platform = process.platform } = {}) {
+ const windows = platform === 'win32';
+ let choice = SHELLS.includes(shell) ? shell : 'auto';
+ if (choice === 'auto') choice = windows ? (looksLikePowerShell(command) ? 'powershell' : 'cmd') : 'sh';
+ if (choice === 'powershell') return { file: powershellExe(platform), args: ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', command], shell: false, name: 'PowerShell' };
+ if (choice === 'bash') return { file: 'bash', args: ['-c', command], shell: false, name: 'bash' };
+ if (choice === 'sh') return windows ? { file: 'sh', args: ['-c', command], shell: false, name: 'sh' } : { file: command, args: [], shell: true, name: 'sh' };
+ return { file: command, args: [], shell: true, name: windows ? 'cmd.exe' : 'sh' }; // cmd: spawn's shell:true is cmd.exe on Windows
+}
+
+/** The folder a command runs in: -> { cwd } or { error } with a plain sentence. */
+export function resolveCwd(...candidates) {
+ for (const candidate of candidates) {
+ const text = typeof candidate === 'string' ? candidate.trim() : '';
+ if (!text) continue;
+ const expanded = text.replace(/^~(?=$|[\\/])/, homedir());
+ try {
+ if (!existsSync(expanded) || !statSync(expanded).isDirectory()) return { error: `The folder “${text}” does not exist, so the command was not run.` };
+ } catch { return { error: `The folder “${text}” could not be opened, so the command was not run.` }; }
+ return { cwd: expanded };
+ }
+ return { cwd: homedir() };
+}
+
+export const clampTimeoutSec = value => {
+ const n = Number(value);
+ return Number.isFinite(n) && n >= 1 ? Math.min(Math.floor(n), MAX_TIMEOUT_SEC) : DEFAULT_TIMEOUT_SEC;
+};
+
+function endTree(child) {
+ try {
+ if (process.platform === 'win32' && child.pid) spawnSync('taskkill', ['/PID', String(child.pid), '/T', '/F'], { windowsHide: true, timeout: 10000 });
+ else child.kill('SIGKILL');
+ } catch { /* gone */ }
+}
+
+/**
+ * @param {{command: string, input?: string, cwd?: string, callCwd?: string, shell?: string, timeoutSec?: number, platform?: string}} job
+ * @returns {Promise<{ok: boolean, text: string}>}
+ */
+export function runCommand({ command, input = '', cwd, callCwd, shell = 'auto', timeoutSec, platform = process.platform }) {
+ return new Promise(resolve => {
+ const where = resolveCwd(callCwd, cwd);
+ if (where.error) return resolve({ ok: false, text: where.error });
+ const plan = planShell(command, { shell, platform });
+ const limit = clampTimeoutSec(timeoutSec);
+ let child;
+ try {
+ child = spawn(plan.file, plan.args, { shell: plan.shell, windowsHide: true, cwd: where.cwd, env: { ...process.env, STRATA_INPUT: String(input ?? '') }, stdio: ['ignore', 'pipe', 'pipe'] });
+ } catch (e) { return resolve({ ok: false, text: `The command could not start in ${plan.name}: ${e.message}` }); }
+ let text = '', cut = false, timedOut = false;
+ const take = chunk => { if (text.length < OUT_MAX + 1) text += chunk.toString(); else cut = true; };
+ child.stdout.on('data', take); child.stderr.on('data', take);
+ const timer = setTimeout(() => { timedOut = true; endTree(child); }, limit * 1000);
+ child.on('error', e => { clearTimeout(timer); resolve({ ok: false, text: `The command could not start in ${plan.name}: ${e.message}` }); });
+ child.on('close', code => {
+ clearTimeout(timer);
+ if (text.length > OUT_MAX) { cut = true; text = text.slice(0, OUT_MAX); }
+ const out = text.trim() + (cut ? `\n\n(The output was cut after ${OUT_MAX.toLocaleString('en-US')} characters.)` : '');
+ if (timedOut) return resolve({ ok: false, text: `The command was stopped after ${limit} seconds.${out ? '\n' + out : ''}` });
+ resolve({ ok: code === 0, text: out || (code === 0 ? 'The command finished without any error. It printed nothing.' : `The command failed (exit code ${code}) and printed nothing.`) });
+ });
+ });
+}
diff --git a/apps/host/server/agent/custom-tools-mcp.mjs b/apps/host/server/agent/custom-tools-mcp.mjs
index 93cb40f6f..99a97f3d0 100644
--- a/apps/host/server/agent/custom-tools-mcp.mjs
+++ b/apps/host/server/agent/custom-tools-mcp.mjs
@@ -8,49 +8,35 @@
* It speaks the Model Context Protocol over stdio (newline-delimited JSON-RPC), the transport the Harness's MCP client uses for a program
* it starts. The file is re-read on every request, so a change in Settings is seen without restarting anything. The assistant's text for
* a command tool reaches the command in the STRATA_INPUT environment variable (never spliced into the command line, so it cannot add
- * commands of its own). A command gets 2 minutes and 20,000 characters of output.
+ * commands of its own). A command runs in the shell that suits it (PowerShell for a Windows command that reads as PowerShell, cmd.exe for
+ * the rest, sh elsewhere), in its own folder or the one the assistant names, gets 2 minutes unless its tool allows more (up to an hour) and
+ * 20,000 characters of output (custom-command-run.mjs).
*/
-import { spawn } from 'node:child_process';
import { readFileSync } from 'node:fs';
import { createInterface } from 'node:readline';
+import { runCommand } from './custom-command-run.mjs';
const [mode, file] = process.argv.slice(2);
if (!['instructions', 'commands'].includes(mode) || !file) { console.error('usage: custom-tools-mcp.mjs instructions|commands <tools.json>'); process.exit(2); }
const load = () => { try { return JSON.parse(readFileSync(file, 'utf8'))[mode] ?? {}; } catch { return {}; } };
-const OUT_MAX = 20000;
-const TIME_MS = 120000;
const schema = mode === 'commands'
- ? { type: 'object', properties: { input: { type: 'string', description: 'Text to give the command (optional).' } }, additionalProperties: false }
+ ? { type: 'object', properties: {
+ input: { type: 'string', description: 'Text to give the command (optional).' },
+ cwd: { type: 'string', description: 'The folder to run the command in (optional). Give the working folder of this chat when the command uses relative paths.' },
+ }, additionalProperties: false }
: { type: 'object', properties: {}, additionalProperties: false };
function listTools() {
return Object.entries(load()).map(([name, t]) => ({ name, description: String(t.description ?? ''), inputSchema: schema, annotations: mode === 'instructions' ? { readOnlyHint: true } : {} }));
}
-function runCommand(command, input) {
- return new Promise(resolve => {
- const child = spawn(command, { shell: true, windowsHide: true, env: { ...process.env, STRATA_INPUT: String(input ?? '') }, stdio: ['ignore', 'pipe', 'pipe'] });
- let text = '';
- const take = chunk => { if (text.length < OUT_MAX) text += chunk.toString(); };
- child.stdout.on('data', take); child.stderr.on('data', take);
- const timer = setTimeout(() => { try { child.kill(); } catch { /* gone */ } }, TIME_MS);
- child.on('error', e => { clearTimeout(timer); resolve({ ok: false, text: `The command could not start: ${e.message}` }); });
- child.on('close', (code, signal) => {
- clearTimeout(timer);
- const out = text.slice(0, OUT_MAX).trim();
- if (signal) resolve({ ok: false, text: `The command was stopped after ${TIME_MS / 1000} seconds.${out ? '\n' + out : ''}` });
- else resolve({ ok: code === 0, text: out || (code === 0 ? 'The command finished without any error. It printed nothing.' : `The command failed (exit code ${code}) and printed nothing.`) });
- });
- });
-}
-
async function call(name, args) {
const t = load()[name];
if (!t) return { isError: true, content: [{ type: 'text', text: 'That tool is no longer available.' }] };
if (mode === 'instructions') return { content: [{ type: 'text', text: String(t.text ?? '') }] };
- const r = await runCommand(String(t.command ?? ''), args?.input);
+ const r = await runCommand({ command: String(t.command ?? ''), input: args?.input, callCwd: args?.cwd, cwd: t.cwd, shell: t.shell, timeoutSec: t.timeoutSec });
return { isError: !r.ok, content: [{ type: 'text', text: r.text }] };
}
diff --git a/apps/host/server/agent/tools-settings.mjs b/apps/host/server/agent/tools-settings.mjs
index 4a919e307..0adba80ce 100644
--- a/apps/host/server/agent/tools-settings.mjs
+++ b/apps/host/server/agent/tools-settings.mjs
@@ -13,6 +13,7 @@
import { mkdirSync, renameSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { GROUP_IDS, TOOL_GROUPS } from './tools-catalog.mjs';
+import { SHELLS, clampTimeoutSec } from './custom-command-run.mjs';
export const SEARCH_PROVIDERS = ['builtin', 'exa', 'perplexity', 'deepseek'];
const KINDS = ['instructions', 'command', 'server'];
@@ -38,6 +39,8 @@ function normalize(raw) {
id: String(t.id), name: String(t.name), about: clean(t.about, 300), kind: t.kind, enabled: t.enabled !== false,
instructions: clean(t.instructions, 20000), command: clean(t.command, 2000), address: clean(t.address, 2000),
args: (Array.isArray(t.args) ? t.args : []).slice(0, 50).map(a => clean(a, 1000)),
+ // a command tool's folder, shell and time allowed (custom-command-run.mjs); '' / 'auto' / 120 when not set
+ cwd: clean(t.cwd, 1000).trim(), shell: SHELLS.includes(t.shell) ? t.shell : 'auto', timeoutSec: clampTimeoutSec(t.timeoutSec),
})),
};
}
@@ -49,7 +52,7 @@ function validateCustom(body, existing) {
if (!about) throw new Error('Say what the tool does, in a sentence. The assistant reads this to decide when to use it.');
const kind = body?.kind;
if (!KINDS.includes(kind)) throw new Error('Choose how the tool works.');
- const out = { name, about, kind, instructions: '', command: '', address: '', args: [] };
+ const out = { name, about, kind, instructions: '', command: '', address: '', args: [], cwd: '', shell: 'auto', timeoutSec: clampTimeoutSec(undefined) };
if (kind === 'instructions') {
out.instructions = clean(body.instructions, 20000).trim();
if (!out.instructions) throw new Error('Write the instructions the assistant should follow when it uses this tool.');
@@ -57,6 +60,14 @@ function validateCustom(body, existing) {
out.command = clean(body.command, 2000).trim();
if (!out.command) throw new Error('Enter the command to run.');
if (/[\r\n]/.test(out.command)) throw new Error('Put the command on one line.');
+ // The edit form of Settings does not send these three: an edit keeps what the tool had.
+ const before = existing.find(t => t.id === body.id && t.kind === 'command');
+ out.cwd = body.cwd !== undefined ? clean(body.cwd, 1000).trim() : before?.cwd ?? '';
+ if (/[\r\n]/.test(out.cwd)) throw new Error('Put the folder on one line.');
+ if (body.shell !== undefined && !SHELLS.includes(body.shell)) throw new Error('Choose how the command runs: automatic, cmd, PowerShell, bash or sh.');
+ out.shell = body.shell !== undefined ? body.shell : before?.shell ?? 'auto';
+ if (body.timeoutSec !== undefined && !(Number(body.timeoutSec) >= 1 && Number(body.timeoutSec) <= 3600)) throw new Error('Give the time allowed in seconds, from 1 to 3600.');
+ out.timeoutSec = body.timeoutSec !== undefined ? clampTimeoutSec(body.timeoutSec) : before?.timeoutSec ?? clampTimeoutSec(undefined);
} else {
out.address = clean(body.address, 2000).trim();
if (!out.address) throw new Error('Enter the tool server’s web address, or the program that starts it.');
@@ -91,7 +102,7 @@ export function createAgentTools({ read, write, dataDir, browser = () => ({ foun
for (const t of s.custom.filter(t => t.enabled)) {
const key = t.id;
if (t.kind === 'instructions') instructions[key] = { description: t.about, text: t.instructions };
- else if (t.kind === 'command') commands[key] = { description: t.about, command: t.command };
+ else if (t.kind === 'command') commands[key] = { description: t.about, command: t.command, cwd: t.cwd, shell: t.shell, timeoutSec: t.timeoutSec };
}
mkdirSync(join(dataDir, 'agent'), { recursive: true });
const tmp = `${filePath}.tmp`;
@@ -115,6 +126,7 @@ export function createAgentTools({ read, write, dataDir, browser = () => ({ foun
id: t.id, name: t.name, about: t.about, kind: t.kind, enabled: t.enabled,
summary: t.kind === 'instructions' ? t.instructions.slice(0, 80) : t.kind === 'command' ? t.command : t.address,
instructions: t.instructions, command: t.command, address: t.address, args: t.args,
+ ...(t.kind === 'command' ? { cwd: t.cwd, shell: t.shell, timeoutSec: t.timeoutSec } : {}),
})),
};
}
diff --git a/apps/host/tests/custom-command-tools.test.mjs b/apps/host/tests/custom-command-tools.test.mjs
new file mode 100644
index 000000000..95c447d53
--- /dev/null
+++ b/apps/host/tests/custom-command-tools.test.mjs
@@ -0,0 +1,144 @@
+// 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
+// limit the person can raise. These tests run real commands; they use only what every machine has (node).
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { mkdtempSync, mkdirSync, rmSync, writeFileSync, realpathSync } from 'node:fs';
+import { tmpdir, homedir } from 'node:os';
+import { join } from 'node:path';
+import { spawn } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
+import { createAgentTools } from '../server/agent/tools-settings.mjs';
+import { runCommand, planShell, looksLikePowerShell, resolveCwd, clampTimeoutSec, DEFAULT_TIMEOUT_SEC } from '../server/agent/custom-command-run.mjs';
+
+const SERVER = fileURLToPath(new URL('../server/agent/custom-tools-mcp.mjs', import.meta.url));
+const node = JSON.stringify(process.execPath);
+const WIN = process.platform === 'win32';
+
+test('a Windows command that reads as PowerShell goes to PowerShell, the rest to cmd.exe, and a named shell is honoured', () => {
+ for (const c of ['Get-Content notes.txt', 'Start-Process notepad', 'Get-ChildItem | Where-Object { $_.Length -gt 1 }', '$env:HOME', 'echo $(Get-Date)'])
+ assert.ok(looksLikePowerShell(c), c);
+ for (const c of ['dir', 'type notes.txt', 'python tools\\foo.py --x', 'npm run build && echo done', 'echo %PATH%', 'git status'])
+ assert.ok(!looksLikePowerShell(c), c);
+ const ps = planShell('Get-Content x', { platform: 'win32' });
+ assert.match(ps.file, /^(pwsh|powershell\.exe)$/);
+ assert.deepEqual(ps.args.slice(0, 5), ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command']);
+ assert.equal(ps.args.at(-1), 'Get-Content x');
+ assert.deepEqual(planShell('dir', { platform: 'win32' }), { file: 'dir', args: [], shell: true, name: 'cmd.exe' });
+ assert.equal(planShell('dir', { platform: 'win32', shell: 'powershell' }).args.at(-1), 'dir');
+ assert.equal(planShell('Get-Content x', { platform: 'win32', shell: 'cmd' }).shell, true);
+ assert.deepEqual(planShell('ls -la', { platform: 'linux' }), { file: 'ls -la', args: [], shell: true, name: 'sh' });
+ assert.deepEqual(planShell('ls | wc -l', { platform: 'linux', shell: 'bash' }), { file: 'bash', args: ['-c', 'ls | wc -l'], shell: false, name: 'bash' });
+ assert.equal(planShell('Get-Content x', { platform: 'linux' }).name, 'sh', 'on Linux and macOS a PowerShell-looking command is not rerouted');
+});
+
+test('the time allowed is 2 minutes unless the tool says more, at most an hour', () => {
+ assert.equal(DEFAULT_TIMEOUT_SEC, 120);
+ assert.equal(clampTimeoutSec(undefined), 120);
+ assert.equal(clampTimeoutSec(600), 600);
+ assert.equal(clampTimeoutSec(99999), 3600);
+ assert.equal(clampTimeoutSec(0), 120);
+ assert.equal(clampTimeoutSec('abc'), 120);
+});
+
+test('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 () => {
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'strata-cmd-')));
+ const other = join(dir, 'other'); mkdirSync(other);
+ try {
+ const pwd = `${node} -e "console.log(process.cwd())"`;
+ const here = await runCommand({ command: pwd, cwd: dir });
+ assert.equal(realpathSync(here.text), dir);
+ const named = await runCommand({ command: pwd, cwd: dir, callCwd: other });
+ assert.equal(realpathSync(named.text), other, 'the folder named in the call wins');
+ const home = await runCommand({ command: pwd });
+ assert.equal(realpathSync(home.text), realpathSync(homedir()));
+ const gone = await runCommand({ command: pwd, cwd: join(dir, 'nope') });
+ assert.equal(gone.ok, false);
+ assert.match(gone.text, /does not exist, so the command was not run/);
+ assert.deepEqual(resolveCwd(''), { cwd: homedir() });
+ } finally { rmSync(dir, { recursive: true, force: true }); }
+});
+
+test('a relative path in the command finds its file in the tool\'s folder', async () => {
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'strata-cmd-')));
+ try {
+ mkdirSync(join(dir, 'tools'));
+ writeFileSync(join(dir, 'tools', 'foo.js'), 'console.log("from foo " + (process.env.STRATA_INPUT || ""));');
+ const r = await runCommand({ command: `${node} tools/foo.js`, cwd: dir, input: 'hello' });
+ assert.deepEqual([r.ok, r.text], [true, 'from foo hello']);
+ } finally { rmSync(dir, { recursive: true, force: true }); }
+});
+
+test('a command over the limit is ended and says so; output over the cap says it was cut', async () => {
+ const slow = await runCommand({ command: `${node} -e "setTimeout(()=>{}, 30000)"`, timeoutSec: 1 });
+ assert.equal(slow.ok, false);
+ assert.match(slow.text, /stopped after 1 seconds/);
+ const big = await runCommand({ command: `${node} -e "process.stdout.write('x'.repeat(50000))"` });
+ assert.equal(big.ok, true);
+ assert.match(big.text, /\(The output was cut after 20,000 characters\.\)$/);
+ assert.ok(big.text.length < 20100);
+});
+
+test('PowerShell commands run on Windows (Get-ChildItem, $env:)', { skip: !WIN && 'PowerShell is checked on Windows' }, async () => {
+ const r = await runCommand({ command: 'Write-Output ("a" + $env:STRATA_INPUT)', input: 'b' });
+ assert.deepEqual([r.ok, r.text], [true, 'ab']);
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'strata-cmd-')));
+ try {
+ writeFileSync(join(dir, 'note.txt'), 'hi');
+ const read = await runCommand({ command: 'Get-Content note.txt', cwd: dir });
+ assert.deepEqual([read.ok, read.text], [true, 'hi']);
+ } finally { rmSync(dir, { recursive: true, force: true }); }
+});
+
+test('Settings keeps a command tool\'s folder, shell and time, validates them, and an edit that does not send them keeps them', () => {
+ let stored;
+ const dir = mkdtempSync(join(tmpdir(), 'strata-cmdset-'));
+ try {
+ const tools = createAgentTools({ read: () => stored, write: v => { stored = v; }, dataDir: dir });
+ tools.addCustom({ name: 'Build', about: 'Builds the project.', kind: 'command', command: 'npm run build', cwd: 'C:\\work\\app', shell: 'cmd', timeoutSec: 900 });
+ let tool = tools.view().custom[0];
+ assert.deepEqual([tool.cwd, tool.shell, tool.timeoutSec], ['C:\\work\\app', 'cmd', 900]);
+ tools.editCustom(tool.id, { name: 'Build', about: 'Builds the project, quickly.', kind: 'command', command: 'npm run build' }); // the form sends none of the three
+ tool = tools.view().custom[0];
+ assert.deepEqual([tool.about, tool.cwd, tool.shell, tool.timeoutSec], ['Builds the project, quickly.', 'C:\\work\\app', 'cmd', 900]);
+ assert.throws(() => tools.editCustom(tool.id, { name: 'Build', about: 'x', kind: 'command', command: 'npm run build', timeoutSec: 99999 }), /1 to 3600/);
+ assert.throws(() => tools.editCustom(tool.id, { name: 'Build', about: 'x', kind: 'command', command: 'npm run build', shell: 'fish' }), /Choose how the command runs/);
+ tools.addCustom({ name: 'Plain', about: 'Plain.', kind: 'command', command: 'echo hi' });
+ const plain = tools.view().custom[1];
+ assert.deepEqual([plain.cwd, plain.shell, plain.timeoutSec], ['', 'auto', 120]);
+ // the tool server's file carries them
+ const file = JSON.parse(require_read(tools.filePath));
+ assert.deepEqual(file.commands.build, { description: 'Builds the project, quickly.', command: 'npm run build', cwd: 'C:\\work\\app', shell: 'cmd', timeoutSec: 900 });
+ } finally { rmSync(dir, { recursive: true, force: true }); }
+});
+
+import { readFileSync } from 'node:fs';
+const require_read = file => readFileSync(file, 'utf8');
+
+test('the tool server over stdio: the call may name a folder, and the tool\'s own settings apply', async () => {
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'strata-cmdsrv-')));
+ const work = join(dir, 'work'); mkdirSync(work);
+ const file = join(dir, 'tools.json');
+ writeFileSync(file, JSON.stringify({ commands: {
+ where: { description: 'Prints its folder.', command: `${node} -e "console.log(process.cwd())"` },
+ pinned: { description: 'Runs in work.', command: `${node} -e "console.log(process.cwd())"`, cwd: work },
+ } }));
+ const child = spawn(process.execPath, [SERVER, 'commands', file], { stdio: ['pipe', 'pipe', 'inherit'] });
+ const lines = []; let buffer = '';
+ 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); } });
+ const ask = async (id, method, params) => {
+ child.stdin.write(JSON.stringify({ jsonrpc: '2.0', id, method, params }) + '\n');
+ 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)); }
+ throw new Error('no answer');
+ };
+ try {
+ const listed = await ask(1, 'tools/list', {});
+ assert.ok(listed.tools.every(t => t.inputSchema.properties.cwd?.type === 'string'), 'the optional folder is offered');
+ const pinned = await ask(2, 'tools/call', { name: 'pinned', arguments: {} });
+ assert.equal(realpathSync(pinned.content[0].text), work);
+ const named = await ask(3, 'tools/call', { name: 'where', arguments: { cwd: dir } });
+ assert.equal(realpathSync(named.content[0].text), dir);
+ const missing = await ask(4, 'tools/call', { name: 'where', arguments: { cwd: join(dir, 'nope') } });
+ assert.equal(missing.isError, true);
+ assert.match(missing.content[0].text, /does not exist/);
+ } finally { child.kill(); rmSync(dir, { recursive: true, force: true }); }
+});