okami.mom/strata

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

Niko1221Merge f-0213-life (final 576d06553) into f-0213-int66331f9bc

main
6.1 KiB101 linesraw
1/**
2 * Runs the command of a command tool the person wrote (Settings -> Tools). Split from custom-tools-mcp.mjs so it can be tested.
3 *
4 * 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
5 * "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
6 * minutes with 20,000 characters of output, silently cut.
7 *
8 *   shell      'auto' (default): PowerShell for a Windows command that reads as PowerShell (Get-Content, Start-Process, $env:X, $(...)), cmd.exe for
9 *              any other Windows command (so every command that worked keeps working), /bin/sh elsewhere. 'cmd', 'powershell', 'bash' and 'sh' name one.
10 *   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.
11 *   timeoutSec the time allowed, 1 to 3600 (default 120). A command that runs over is ended together with the programs it started.
12 */
13import { spawn, spawnSync } from 'node:child_process';
14import { endTree as endTreeNow, ownGroup } from '../process-tree.mjs';
15import { existsSync, statSync } from 'node:fs';
16import { homedir } from 'node:os';
17
18export const DEFAULT_TIMEOUT_SEC = 120;
19export const MAX_TIMEOUT_SEC = 3600;
20export const OUT_MAX = 20000;
21export const SHELLS = ['auto', 'cmd', 'powershell', 'bash', 'sh'];
22
23/** A Windows command that is PowerShell and would fail in cmd.exe. */
24const POWERSHELL_LOOKS = /(^|[\s;|(&])[A-Z][A-Za-z]+-[A-Z][A-Za-z]+\b|\$\w|\$\(|\$env:|@\(|\|\s*(?:%|\?)\s*\{/;
25export const looksLikePowerShell = command => POWERSHELL_LOOKS.test(String(command ?? ''));
26
27let powershellFound;
28/** pwsh when it is installed (PowerShell 7), else the Windows PowerShell every Windows has. */
29function powershellExe(platform) {
30  if (powershellFound) return powershellFound;
31  if (platform !== 'win32') return (powershellFound = 'pwsh');
32  try { if (spawnSync('where', ['pwsh'], { windowsHide: true, timeout: 5000 }).status === 0) return (powershellFound = 'pwsh'); } catch { /* none */ }
33  return (powershellFound = 'powershell.exe');
34}
35
36/**
37 * -> { file, args, shell } for spawn: which program runs `command`.
38 * @param {string} command
39 * @param {{shell?: string, platform?: string}} [options]
40 */
41export function planShell(command, { shell = 'auto', platform = process.platform } = {}) {
42  const windows = platform === 'win32';
43  let choice = SHELLS.includes(shell) ? shell : 'auto';
44  if (choice === 'auto') choice = windows ? (looksLikePowerShell(command) ? 'powershell' : 'cmd') : 'sh';
45  if (choice === 'powershell') return { file: powershellExe(platform), args: ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', command], shell: false, name: 'PowerShell' };
46  if (choice === 'bash') return { file: 'bash', args: ['-c', command], shell: false, name: 'bash' };
47  if (choice === 'sh') return windows ? { file: 'sh', args: ['-c', command], shell: false, name: 'sh' } : { file: command, args: [], shell: true, name: 'sh' };
48  return { file: command, args: [], shell: true, name: windows ? 'cmd.exe' : 'sh' };       // cmd: spawn's shell:true is cmd.exe on Windows
49}
50
51/** The folder a command runs in: -> { cwd } or { error } with a plain sentence. */
52export function resolveCwd(...candidates) {
53  for (const candidate of candidates) {
54    const text = typeof candidate === 'string' ? candidate.trim() : '';
55    if (!text) continue;
56    const expanded = text.replace(/^~(?=$|[\\/])/, homedir());
57    try {
58      if (!existsSync(expanded) || !statSync(expanded).isDirectory()) return { error: `The folder “${text}” does not exist, so the command was not run.` };
59    } catch { return { error: `The folder “${text}” could not be opened, so the command was not run.` }; }
60    return { cwd: expanded };
61  }
62  return { cwd: homedir() };
63}
64
65export const clampTimeoutSec = value => {
66  const n = Number(value);
67  return Number.isFinite(n) && n >= 1 ? Math.min(Math.floor(n), MAX_TIMEOUT_SEC) : DEFAULT_TIMEOUT_SEC;
68};
69
70function endTree(child) {
71  endTreeNow(child, 'SIGKILL');    // the command's whole process group on Linux and macOS (it is started as its own group below), taskkill /T on Windows
72}
73
74/**
75 * @param {{command: string, input?: string, cwd?: string, callCwd?: string, shell?: string, timeoutSec?: number, platform?: string}} job
76 * @returns {Promise<{ok: boolean, text: string}>}
77 */
78export function runCommand({ command, input = '', cwd, callCwd, shell = 'auto', timeoutSec, platform = process.platform }) {
79  return new Promise(resolve => {
80    const where = resolveCwd(callCwd, cwd);
81    if (where.error) return resolve({ ok: false, text: where.error });
82    const plan = planShell(command, { shell, platform });
83    const limit = clampTimeoutSec(timeoutSec);
84    let child;
85    try {
86      child = spawn(plan.file, plan.args, { shell: plan.shell, windowsHide: true, detached: ownGroup(), cwd: where.cwd, env: { ...process.env, STRATA_INPUT: String(input ?? '') }, stdio: ['ignore', 'pipe', 'pipe'] });
87    } catch (e) { return resolve({ ok: false, text: `The command could not start in ${plan.name}: ${e.message}` }); }
88    let text = '', cut = false, timedOut = false;
89    const take = chunk => { if (text.length < OUT_MAX + 1) text += chunk.toString(); else cut = true; };
90    child.stdout.on('data', take); child.stderr.on('data', take);
91    const timer = setTimeout(() => { timedOut = true; endTree(child); }, limit * 1000);
92    child.on('error', e => { clearTimeout(timer); resolve({ ok: false, text: `The command could not start in ${plan.name}: ${e.message}` }); });
93    child.on('close', code => {
94      clearTimeout(timer);
95      if (text.length > OUT_MAX) { cut = true; text = text.slice(0, OUT_MAX); }
96      const out = text.trim() + (cut ? `\n\n(The output was cut after ${OUT_MAX.toLocaleString('en-US')} characters.)` : '');
97      if (timedOut) return resolve({ ok: false, text: `The command was stopped after ${limit} seconds.${out ? '\n' + out : ''}` });
98      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.`) });
99    });
100  });
101}