okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
66331f9bc
main
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 ) { 30if ( powershellFound ) return powershellFound ; 31if ( platform !== 'win32' ) return ( powershellFound = 'pwsh' ); 32try { if ( spawnSync ( 'where' , [ 'pwsh' ], { windowsHide :true , timeout :5000 }). status === 0 ) return ( powershellFound = 'pwsh' ); } catch { /* none */ } 33return ( 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 } = {}) { 42const windows = platform === 'win32' ; 43let choice = SHELLS . includes ( shell ) ?shell :'auto' ; 44if ( choice === 'auto' ) choice = windows ?( looksLikePowerShell ( command ) ?'powershell' :'cmd' ) :'sh' ; 45if ( choice === 'powershell' ) return { file :powershellExe ( platform ), args :[ '-NoProfile' , '-NonInteractive' , '-ExecutionPolicy' , 'Bypass' , '-Command' , command ], shell :false , name :'PowerShell' }; 46if ( choice === 'bash' ) return { file :'bash' , args :[ '-c' , command ], shell :false , name :'bash' }; 47if ( choice === 'sh' ) return windows ?{ file :'sh' , args :[ '-c' , command ], shell :false , name :'sh' } :{ file :command , args :[], shell :true , name :'sh' }; 48return { 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 ) { 53for ( const candidate of candidates ) { 54const text = typeof candidate === 'string' ?candidate . trim () :'' ; 55if ( ! text ) continue ; 56const expanded = text . replace ( / ^~ (? = $ | [ \\ / ]) / , homedir ()); 57try { 58if ( ! 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.` }; } 60return { cwd :expanded }; 61} 62return { cwd :homedir () }; 63} 64 65export const clampTimeoutSec = value => { 66const n = Number ( value ); 67return Number . isFinite ( n ) && n >= 1 ?Math . min ( Math . floor ( n ), MAX_TIMEOUT_SEC ) :DEFAULT_TIMEOUT_SEC ; 68}; 69 70function endTree ( child ) { 71endTreeNow ( 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 }) { 79return new Promise ( resolve => { 80const where = resolveCwd ( callCwd , cwd ); 81if ( where . error ) return resolve ({ ok :false , text :where . error }); 82const plan = planShell ( command , { shell, platform}); 83const limit = clampTimeoutSec ( timeoutSec ); 84let child ; 85try { 86child = 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 } ` }); } 88let text = '' , cut = false , timedOut = false ; 89const take = chunk => { if ( text . length < OUT_MAX + 1 ) text += chunk . toString (); else cut = true ; }; 90child . stdout . on ( 'data' , take ); child . stderr . on ( 'data' , take ); 91const timer = setTimeout (() => { timedOut = true ; endTree ( child ); }, limit * 1000 ); 92child . on ( 'error' , e => { clearTimeout ( timer ); resolve ({ ok :false , text :`The command could not start in ${ plan . name } : ${ e . message } ` }); }); 93child . on ( 'close' , code => { 94clearTimeout ( timer ); 95if ( text . length > OUT_MAX ) { cut = true ; text = text . slice ( 0 , OUT_MAX ); } 96const out = text . trim () + ( cut ?`\n\n(The output was cut after ${ OUT_MAX . toLocaleString ( 'en-US' )} characters.)` :'' ); 97if ( timedOut ) return resolve ({ ok :false , text :`The command was stopped after ${ limit } seconds. ${ out ? '\n' + out : '' } ` }); 98resolve ({ 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}