@wonderwhy-er/desktop-commander
Version:
MCP server for terminal operations and file editing
965 lines • 51.5 kB
JavaScript
import { getShellType, programName } from './shell.js';
import { requireCompleteArguments } from './command-reading.js';
/** tmux's commands that start the program after their options (tmux new-session -d sudo ls), by name and alias */
const TMUX_NEW_SESSION = { letters: 'cefFnstxy', flags: 'AdDEPX' };
const TMUX_NEW_WINDOW = { letters: 'ceFnt', flags: 'abdEkPS' };
const TMUX_SPLIT_WINDOW = { letters: 'BceFlmpRsStT', flags: 'bdEfhIkPvWZ' };
const TMUX_RESPAWN = { letters: 'cet', flags: 'Ek' };
const TMUX_COMMANDS = new Map([
['new-session', TMUX_NEW_SESSION], ['new', TMUX_NEW_SESSION],
['new-window', TMUX_NEW_WINDOW], ['neww', TMUX_NEW_WINDOW],
['split-window', TMUX_SPLIT_WINDOW], ['splitw', TMUX_SPLIT_WINDOW],
['respawn-pane', TMUX_RESPAWN], ['respawnp', TMUX_RESPAWN], ['respawn-window', TMUX_RESPAWN], ['respawnw', TMUX_RESPAWN],
]);
/** find's words that take the next one as their value, GNU's and BSD's: -newerXY is each of -newerat … -newertt */
const FIND_VALUES = [
'amin', 'anewer', 'atime', 'Bmin', 'Bnewer', 'Btime', 'cmin', 'cnewer', 'context', 'ctime', 'D', 'f', 'files0-from', 'flags', 'fls',
'fprint', 'fprint0', 'fprintf', 'fstype', 'gid', 'group', 'ilname', 'iname', 'inum', 'ipath', 'iregex', 'iwholename', 'links', 'lname',
'maxdepth', 'mindepth', 'mmin', 'mtime', 'name', 'newer', 'path', 'perm', 'printf', 'regex', 'regextype', 'samefile', 'size', 'type', 'uid',
'used', 'user', 'wholename', 'xattrname', 'xtype', ...[...'aBcmt'].flatMap((x) => [...'aBcmt'].map((y) => `newer${x}${y}`)),
].map((name) => `-${name}`);
/**
* tmux's commands that run a shell-command, read for its text (see
* TEXT_PROGRAMS): those in TMUX_COMMANDS, and display-popup (popup)
*/
const TMUX_POPUP = { letters: 'bcdehsStTwxy', flags: 'BCEkN' };
const TMUX_TEXT_COMMANDS = new Map([...TMUX_COMMANDS, ['display-popup', TMUX_POPUP], ['popup', TMUX_POPUP]]
.map(([name, rules]) => [name, { ...rules, textOperands: 0, textEnds: [';'] }]));
/**
* The wrappers that are programs, with their options from each one's manual
* or --help: GNU's, BSD's and macOS's where there are several (and Windows'
* sudo), util-linux's, systemd's, OpenBSD's doas, polkit's pkexec, and the
* usage text of busybox, wsl, gsudo and psexec
*/
const PROGRAMS = new Map([
['env', {
letters: 'uCPLUa', flags: 'i0v', long: ['unset', 'chdir', 'argv0'],
longFlags: ['ignore-environment', 'null', 'debug', 'block-signal', 'default-signal', 'ignore-signal', 'list-signal-handling', 'help', 'version'],
assignments: true, texts: { letters: 'S', long: ['split-string'] },
}],
['nohup', { longFlags: ['help', 'version'] }],
['xargs', {
letters: 'adEIJLnPRSs', attachedLetters: 'eil', flags: '0oprtx',
long: ['arg-file', 'delimiter', 'max-args', 'max-chars', 'max-lines', 'max-procs', 'process-slot-var'],
longFlags: ['null', 'eof', 'replace', 'open-tty', 'interactive', 'no-run-if-empty', 'show-limits', 'verbose', 'exit', 'help', 'version'],
}],
['timeout', {
letters: 'ks', flags: 'fpv', long: ['kill-after', 'signal'], longFlags: ['foreground', 'preserve-status', 'verbose', 'help', 'version'],
before: 1, noProgramWords: ['/t', '/nobreak'],
}],
['nice', { letters: 'n', attachedLetters: '0123456789', long: ['adjustment'], longFlags: ['help', 'version'] }],
['stdbuf', { letters: 'ioe', long: ['input', 'output', 'error'], longFlags: ['help', 'version'] }],
['setsid', { flags: 'cfwhV', longFlags: ['ctty', 'fork', 'wait', 'help', 'version'] }],
['chroot', { letters: 'Ggu', flags: 'n', long: ['groups', 'userspec'], longFlags: ['skip-chdir', 'help', 'version'], before: 1 }],
['sudo', {
letters: 'aCcDghpRrTtUu', flags: 'ABbEeHiKklNnPSsVv',
long: ['auth-type', 'chdir', 'chroot', 'close-from', 'command-timeout', 'group', 'host', 'login-class', 'other-user', 'prompt', 'role', 'type', 'user'],
longFlags: [
'askpass', 'bell', 'background', 'preserve-env', 'edit', 'set-home', 'help', 'login', 'remove-timestamp', 'reset-timestamp', 'list',
'no-update', 'non-interactive', 'preserve-groups', 'stdin', 'shell', 'version', 'validate', 'new-window', 'disable-input', 'inline',
],
assignments: true,
}],
['doas', { letters: 'au', flags: 'ns', noProgram: 'CL' }],
['pkexec', { long: ['user'], longFlags: ['keep-cwd', 'disable-internal-agent', 'help', 'version'] }],
['busybox', { noProgramWords: ['--list', '--list-full', '--install', '--show', '--help'] }],
['wsl', { letters: 'du', flags: 'e', long: ['cd', 'distribution', 'distribution-id', 'user', 'shell-type'], longFlags: ['exec', 'system'] }],
['nsenter', {
letters: 'tNGS', attachedLetters: 'muinpUCTrwW', flags: 'aeFZchV', long: ['target', 'net-socket', 'setgid', 'setuid'],
longFlags: [
'all', 'mount', 'uts', 'ipc', 'net', 'pid', 'user', 'user-parent', 'cgroup', 'time', 'keep-caps', 'preserve-credentials', 'root',
'wd', 'wdns', 'env', 'no-fork', 'follow-context', 'join-cgroup', 'help', 'version',
],
}],
['unshare', {
letters: 'lRwSG', attachedLetters: 'imnpuUCT', flags: 'frchV',
long: [
'load-interp', 'map-user', 'map-users', 'map-group', 'map-groups', 'owner', 'propagation', 'setgroups', 'root', 'wd', 'setuid',
'setgid', 'monotonic', 'boottime', 'whitelist-env',
],
longFlags: [
'ipc', 'mount', 'net', 'pid', 'uts', 'user', 'cgroup', 'time', 'fork', 'forward-signals', 'keep-caps', 'kill-child', 'mount-proc',
'mount-binfmt', 'map-auto', 'map-subids', 'map-root-user', 'map-current-user', 'clear-env', 'help', 'version',
],
}],
['ionice', { letters: 'cn', flags: 'thV', long: ['class', 'classdata'], longFlags: ['ignore', 'help', 'version'], noProgram: 'pPu', noProgramLong: ['pid', 'pgid', 'uid'] }],
['taskset', { flags: 'achV', longFlags: ['all-tasks', 'cpu-list', 'help', 'version'], noProgram: 'p', noProgramLong: ['pid'], before: 1 }],
['chrt', {
letters: 'TPDUX', flags: 'ofrbideGORavhV', long: ['sched-runtime', 'sched-period', 'sched-deadline', 'clamp-min', 'clamp-max'],
longFlags: ['other', 'fifo', 'rr', 'batch', 'idle', 'deadline', 'ext', 'reclaim-grub', 'deadline-overrun', 'reset-on-fork', 'all-tasks', 'verbose', 'help', 'version'],
noProgram: 'mp', noProgramLong: ['max', 'pid'], before: 1, beforeOptional: true,
}],
['numactl', {
letters: 'iwmNCpP', flags: 'alb',
long: ['interleave', 'weighted-interleave', 'membind', 'cpunodebind', 'physcpubind', 'preferred', 'preferred-many', 'offset', 'shmmode', 'length'],
longFlags: ['all', 'localalloc', 'balancing', 'cpu-compress', 'huge', 'strict', 'touch', 'dump', 'dump-nodes'],
noProgram: 'sH', noProgramLong: ['show', 'hardware', 'version', 'shm', 'shmid', 'file'],
}],
['prlimit', {
letters: 'o', attachedLetters: 'cdefilmnqrstuvxy', flags: 'hV', long: ['output'],
longFlags: [
'noheadings', 'raw', 'verbose', 'help', 'version', 'core', 'data', 'nice', 'fsize', 'sigpending', 'memlock', 'rss', 'nofile',
'msgqueue', 'rtprio', 'stack', 'cpu', 'nproc', 'as', 'locks', 'rttime',
],
noProgram: 'p', noProgramLong: ['pid'],
}],
['setpriv', {
flags: 'hV',
long: [
'groups', 'inh-caps', 'ambient-caps', 'bounding-set', 'rgid', 'egid', 'regid', 'ruid', 'euid', 'reuid', 'securebits', 'pdeathsig',
'ptracer', 'selinux-label', 'apparmor-profile', 'landlock-access', 'landlock-rule', 'seccomp-filter',
],
longFlags: ['clear-groups', 'keep-groups', 'init-groups', 'nnp', 'no-new-privs', 'reset-env', 'help', 'version'],
noProgram: 'd', noProgramLong: ['dump', 'list-caps'],
}],
['capsh', { equalsOnly: true, programOptions: { long: ['shell'], default: 'bash' } }],
['cpulimit', {
letters: 'lcs', flags: 'bfqkmrvzh', long: ['limit', 'cpu', 'signal'],
longFlags: ['background', 'foreground', 'quiet', 'kill', 'monitor-forks', 'restore', 'verbose', 'lazy', 'help'],
noProgram: 'peP', noProgramLong: ['pid', 'exe', 'path'],
}],
['systemd-run', {
letters: 'upEHMC', flags: 'rdRtTPSqvGh',
long: [
'unit', 'property', 'description', 'slice', 'expand-environment', 'service-type', 'uid', 'gid', 'nice', 'working-directory',
'root-directory', 'setenv', 'output', 'on-active', 'on-boot', 'on-startup', 'on-unit-active', 'on-unit-inactive', 'on-calendar',
'path-property', 'socket-property', 'timer-property', 'job-mode', 'background', 'host', 'machine', 'capsule', 'json',
],
longFlags: [
'scope', 'slice-inherit', 'remain-after-exit', 'send-sighup', 'same-dir', 'same-root-dir', 'pty', 'pty-late', 'pipe', 'shell',
'quiet', 'verbose', 'on-clock-change', 'on-timezone-change', 'no-block', 'wait', 'collect', 'ignore-failure', 'user', 'system',
'no-ask-password', 'help', 'version', 'no-pager',
],
}],
['run0', {
letters: 'ugD', flags: 'kKinh',
long: [
'unit', 'property', 'description', 'slice', 'user', 'group', 'nice', 'chdir', 'setenv', 'background', 'shell-prompt-prefix',
'lightweight', 'area', 'machine',
],
longFlags: [
'slice-inherit', 'reset-timestamp', 'remove-timestamp', 'via-shell', 'pty', 'pty-late', 'pipe', 'empower', 'same-root-dir',
'non-interactive', 'no-ask-password', 'help', 'version',
],
noProgram: 'v', noProgramLong: ['validate'],
}],
['strace', {
letters: 'eEpubIPaoOsSUX', flags: 'DfcCdhiknNqrtTvVwxyYzZAF',
long: [
'env', 'attach', 'user', 'argv0', 'detach-on', 'interruptible', 'syscall-limit', 'trace', 'trace-fds', 'signal', 'status',
'trace-path', 'columns', 'abbrev', 'verbose', 'raw', 'read', 'write', 'silent', 'silence', 'kvm', 'namespace',
'stack-trace-frame-limit', 'output', 'color', 'string-limit', 'const-print-style', 'summary-syscall-overhead', 'summary-sort-by',
'summary-columns', 'inject', 'fault',
],
longFlags: [
'daemonize', 'follow-forks', 'output-separately', 'kill-on-exit', 'successful-only', 'failed-only', 'quiet', 'decode-fds',
'decode-pids', 'pidns-translation', 'instruction-pointer', 'syscall-number', 'arg-names', 'stack-trace', 'output-append-mode',
'relative-timestamps', 'absolute-timestamps', 'timestamps', 'syscall-times', 'no-abbrev', 'strings-in-hex', 'summary-only',
'summary', 'summary-wall-clock', 'debug', 'help', 'seccomp-bpf', 'tips', 'version', 'always-show-pid', 'secontext',
],
}],
['ltrace', {
letters: 'aAdDeFlnopsuwx', flags: 'bcCfhiLrStTV', long: ['align', 'max-depth', 'debug', 'config', 'library', 'indent', 'output', 'where'],
longFlags: ['no-signals', 'demangle', 'help', 'version'],
}],
['time', { letters: 'fo', flags: 'paqvV', long: ['format', 'output'], longFlags: ['portability', 'append', 'verbose', 'quiet', 'help', 'version'] }],
['firejail', {
equalsOnly: true, flags: 'c', noProgram: '?',
noProgramLong: [
'list', 'tree', 'top', 'netstats', 'nettrace', 'icmptrace', 'dnstrace', 'snitrace', 'version', 'help', 'debug-caps',
'debug-errnos', 'debug-syscalls', 'debug-syscalls32', 'debug-protocols', 'shutdown', 'bandwidth', 'ids-init', 'ids-check', 'ls',
'get', 'put', 'cat',
],
}],
['bwrap', {
long: [
'args', 'userns', 'userns2', 'pidns', 'uid', 'gid', 'hostname', 'chdir', 'unsetenv', 'lock-file', 'sync-fd', 'perms', 'size',
'remount-ro', 'proc', 'dev', 'tmpfs', 'mqueue', 'dir', 'seccomp', 'add-seccomp-fd', 'exec-label', 'file-label', 'block-fd',
'userns-block-fd', 'info-fd', 'json-status-fd', 'cap-add', 'cap-drop',
],
longPairs: [
'setenv', 'bind', 'bind-try', 'dev-bind', 'dev-bind-try', 'ro-bind', 'ro-bind-try', 'file', 'bind-data', 'ro-bind-data', 'symlink',
'chmod',
],
longFlags: [
'help', 'version', 'unshare-user', 'unshare-user-try', 'unshare-ipc', 'unshare-pid', 'unshare-net', 'unshare-uts',
'unshare-cgroup', 'unshare-cgroup-try', 'unshare-all', 'share-net', 'disable-userns', 'assert-userns-disabled', 'clearenv',
'new-session', 'die-with-parent', 'as-pid-1',
],
}],
['unbuffer', { flags: 'p' }],
['rlwrap', {
letters: 'bCDefgHlMOPqsStwz', attachedLetters: 'aAmp', flags: 'cEhiInNorRUvW',
long: [
'break-chars', 'command-name', 'history-no-dupes', 'extra-char-after-completion', 'file', 'forget-matching', 'history-filename',
'logfile', 'multi-line-ext', 'only-cook', 'pre-given', 'quote-characters', 'histsize', 'substitute-prompt', 'set-term-name',
'wait-before-prompt', 'filter',
],
longFlags: [
'always-readline', 'ansi-colour-aware', 'complete-filenames', 'always-echo', 'help', 'case-insensitive', 'pass-sigint-as-sigterm',
'multi-line', 'no-warnings', 'no-children', 'one-shot', 'prompt-colour', 'remember', 'renice', 'mirror-arguments', 'version', 'polling',
],
}],
['chpst', { letters: 'uUbe/nlLmdopfct', flags: 'vVP012' }],
['setuidgid', { before: 1 }],
['start-stop-daemon', {
letters: 'pnugsRcrdONPIk', flags: 'StoqbCmv',
long: [
'pid', 'ppid', 'pidfile', 'name', 'user', 'group', 'signal', 'retry', 'chuid', 'chroot', 'chdir', 'notify-timeout', 'output',
'nicelevel', 'procsched', 'iosched', 'umask',
],
longFlags: ['start', 'test', 'oknodo', 'quiet', 'background', 'notify-await', 'no-close', 'make-pidfile', 'remove-pidfile', 'verbose'],
noProgram: 'KTHV', noProgramLong: ['stop', 'status', 'help', 'version'], programOptions: { letters: 'xa', long: ['exec', 'startas'] },
}],
['caffeinate', { letters: 'tw', flags: 'dimsu' }],
['arch', { wordOptions: true, long: ['arch', 'd', 'e'], longFlags: ['32', '64', 'i386', 'x86_64', 'x86_64h', 'arm64', 'arm64e', 'c', 'h'] }],
['sandbox-exec', { letters: 'fnpD' }],
['find', { programAfter: { words: ['-exec', '-execdir', '-ok', '-okdir'], ends: [';', '+'], values: FIND_VALUES } }],
['parallel', {
letters: 'aCdEIjJnNPsLS', attachedLetters: 'eil', flags: '0kmqrtuvXx',
long: [
'arg-file', 'arg-file-sep', 'arg-sep', 'basefile', 'bf', 'basenamereplace', 'bnr', 'basenameextensionreplace', 'bner', 'bin', 'block',
'block-size', 'block-timeout', 'bt', 'colsep', 'combineexec', 'compress-program', 'decompress-program', 'delay', 'delimiter',
'dirnamereplace', 'dnr', 'env', 'extensionreplace', 'er', 'filter', 'group-by', 'halt', 'halt-on-error', 'header', 'jobs',
'max-procs', 'joblog', 'jl', 'limit', 'load', 'match', 'max-args', 'max-chars', 'max-replace-args', 'memfree', 'memsuspend',
'milestone', 'minversion', 'nice', 'parens', 'process-slot-var', 'profile', 'recend', 'recstart', 'results', 'res', 'retries',
'return', 'rpl', 'rsync-opts', 'sshlogin', 'sshloginfile', 'tagstring', 'timeout', 'tmpdir', 'workdir', 'wd',
],
longFlags: [
'eof', 'max-lines', 'keep-order', 'tag', 'dry-run', 'pipe', 'group', 'ungroup', 'line-buffer', 'progress', 'eta', 'bar', 'verbose',
'null', 'quote', 'no-run-if-empty', 'shuf', 'tty', 'xargs', 'cleanup', 'transfer', 'help', 'version',
],
}],
['xterm', {
wordOptions: true, plus: true,
long: [
'b', 'bcf', 'bcn', 'bd', 'bg', 'bw', 'cc', 'class', 'cr', 'display', 'en', 'fa', 'fb', 'fc', 'fd', 'fg', 'fi', 'fn', 'font', 'fs', 'fw',
'fwb', 'fx', 'geometry', 'hc', 'into', 'kt', 'lcc', 'lf', 'mc', 'ms', 'n', 'name', 'nb', 'pf', 'selbg', 'selfg', 'sh', 'sl', 'ti',
'title', 'tm', 'tn', 'T', 'w', 'xrm', 'ziconbeep', 'baudrate',
],
longFlags: [
'e', 'ah', 'aw', 'bc', 'cb', 'cjk_width', 'cm', 'cn', 'cu', 'dc', 'fbb', 'fbx', 'fullscreen', 'hf', 'hm', 'hold', 'ie', 'im', 'itc',
'j', 'k8', 'l', 'lc', 'leftbar', 'ls', 'maximized', 'mb', 'mesg', 'mk_width', 'nul', 'pc', 'pob', 'rightbar', 'rv', 'rvc', 'rw', 's',
'samename', 'sb', 'sf', 'si', 'sk', 'sm', 'sp', 't', 'tb', 'toolbar', 'u8', 'ulc', 'ulit', 'ut', 'vb', 'wc', 'wf', 'iconic',
'reverse', 'help', 'version',
],
}],
['tmux', { letters: 'cfLST', flags: '2CDhlNuVv', subcommands: TMUX_COMMANDS }],
['screen', { letters: 'cehpsStT', flags: 'aAdDfiLlmOPqRU', noProgram: 'rxXQv', noProgramWords: ['-ls', '-list', '-wipe'] }],
['gsudo', {
letters: 'ui', flags: 'nwskd', long: ['user', 'integrity', 'loglevel', 'chdir'],
longFlags: ['new', 'wait', 'keepShell', 'keepWindow', 'system', 'ti', 'direct', 'loadProfile', 'debug', 'copyns', 'copyev'],
}],
['psexec', {
wordOptions: true, long: ['u', 'p', 'n', 'r', 'w', 'a', 'g'],
longFlags: [
's', 'e', 'h', 'l', 'x', 'c', 'f', 'v', 'd', 'accepteula', 'nobanner', 'low', 'belownormal', 'abovenormal', 'high', 'realtime',
'background',
],
remote: ['\\\\', '@'],
}],
]);
/** The POSIX shells' own commands that start a program */
const POSIX_SHELL_COMMANDS = new Map([
['exec', { letters: 'a', flags: 'cl' }],
['command', { flags: 'p', noProgram: 'vV' }],
]);
/** fish's commands that start the command after them */
const FISH_COMMANDS = new Map([
['and', {}],
['or', {}],
['not', {}],
]);
/**
* How a POSIX shell reads its own options, for shellRuns(): bash's, from bash
* 5.3's --help and bash(1), for every shell but fish (sh, dash, zsh and ksh
* have the same -c, -s, -o and +o), and fish's, from fish(1). bash's -c makes
* the first word after the options the command text, and its other words are
* the command's $0, $1 and so on; fish's -c and -C (--init-command) take the
* command text as their value, and fish runs -C's before the rest.
*/
const BASH_OPTIONS = {
letters: 'oO', flags: 'abcefhiklmnprstuvxBCDEHPT', long: ['init-file', 'rcfile'],
longFlags: [
'debug', 'debugger', 'dump-po-strings', 'dump-strings', 'help', 'login', 'noediting', 'noprofile', 'norc', 'posix',
'pretty-print', 'protected', 'restricted', 'verbose', 'version', 'wordexp',
],
plus: true, groupValues: 'words', operandRoles: { c: 'text', s: 'arguments' },
};
const FISH_OPTIONS = {
letters: 'dfop', flags: 'hilnNPv', long: ['debug', 'debug-output', 'features', 'profile', 'profile-startup'],
longFlags: ['help', 'interactive', 'login', 'no-config', 'no-execute', 'print-debug-categories', 'print-rusage-self', 'private', 'version'],
texts: { letters: 'cC', long: ['command', 'init-command'] }, optionsAfterTexts: true,
operandRoles: { c: 'arguments', command: 'arguments' },
};
/**
* The programs that run one command text in a shell, as bash -c does, with
* the shell that reads it: shellRuns() gives their texts to the check. Their
* options are from their --help on Debian 12 (util-linux's su, runuser,
* script and flock, procps' watch, sg from login) and from Windows' runas /? help;
* wsl's, tmux's and parallel's are their rows in PROGRAMS, and display-popup's
* are from OpenBSD's tmux(1).
* - su, runuser and script run the text of -c (--command) in the user's
* shell, and -c can come after the user or the file too; runuser -u runs
* the program after the user directly, without reading it as a shell text;
* - sg runs its command with sh -c, given with -c or not, after its group;
* - flock runs -c's text with sh -c, or the program after the lock file;
* - watch runs its words with sh -c;
* - runas runs its quoted command line, which is read as cmd reads one;
* - wsl without --exec gives its words to the Linux shell as one command line;
* - tmux runs -c's text in the user's shell, and the shell-command of new,
* split-window, respawn-pane, display-popup and the like with sh -c when it
* is one word (tmux new 'sudo ls'), the program after their options otherwise;
* - parallel runs its command line with a shell, once for each argument after
* :::, and without a command each of those arguments is a command.
*/
const TEXT_PROGRAMS = new Map([
['su', { shell: 'sh', rules: {
letters: 'gGsw', flags: 'flmpP', long: ['group', 'supp-group', 'shell', 'whitelist-environment'],
longFlags: ['fast', 'login', 'preserve-environment', 'pty', 'help', 'version'],
texts: { letters: 'c', long: ['command', 'session-command'] },
optionsAfterTexts: true, permute: true, shellArgumentsAfter: 1,
} }],
['runuser', { shell: 'sh', rules: {
letters: 'gGswu', flags: 'flmpP', long: ['group', 'supp-group', 'shell', 'whitelist-environment', 'user'],
longFlags: ['fast', 'login', 'preserve-environment', 'pty', 'help', 'version'],
texts: { letters: 'c', long: ['command', 'session-command'] },
optionsAfterTexts: true, permute: true, shellArgumentsAfter: 1,
operandRoles: { u: 'program', user: 'program' },
} }],
['sg', { shell: 'sh', rules: { texts: { letters: 'c', long: [] }, optionsAfterTexts: true, permute: true, textOperands: 1 } }],
['script', { shell: 'sh', rules: {
letters: 'IOBTmEo', attachedLetters: 't', flags: 'aefq',
long: ['log-in', 'log-out', 'log-io', 'log-timing', 'logging-format', 'echo', 'output-limit'],
longFlags: ['timing', 'append', 'return', 'flush', 'force', 'quiet', 'help', 'version'],
texts: { letters: 'c', long: ['command'] }, optionsAfterTexts: true, permute: true,
} }],
['flock', { shell: 'sh', rules: {
letters: 'wE', flags: 'sxunoF', long: ['timeout', 'conflict-exit-code'],
longFlags: ['shared', 'exclusive', 'unlock', 'nonblock', 'close', 'no-fork', 'verbose', 'help', 'version'],
texts: { letters: 'c', long: ['command'] }, optionsAfterTexts: true, permute: true, textOperands: 1,
} }],
['watch', { shell: 'sh', rules: {
letters: 'qn', attachedLetters: 'd', flags: 'bcegptwx', long: ['equexit', 'interval'],
longFlags: ['beep', 'color', 'differences', 'errexit', 'chgexit', 'precise', 'no-title', 'no-wrap', 'exec', 'help', 'version'],
textOperands: 0,
} }],
['runas', { shell: 'cmd', rules: { slash: true, textOperands: 0 } }],
['wsl', { shell: 'sh', rules: { ...PROGRAMS.get('wsl'), textOperands: 0, operandRoles: { e: 'arguments', exec: 'arguments' } } }],
['tmux', { shell: 'sh', rules: { ...PROGRAMS.get('tmux'), texts: { letters: 'c', long: [] }, subcommands: TMUX_TEXT_COMMANDS, separator: ';' } }],
['parallel', { shell: 'sh', rules: {
...PROGRAMS.get('parallel'), textOperands: 0, textEnds: [':::', ':::+', '::::', '::::+'], commandArguments: [':::', ':::+'],
commandFiles: ['::::', '::::+'],
} }],
]);
/**
* The programs that run one command text in the shell they were started
* from, as eval does: gsudo 'net user' runs net there (gsudo's README).
* sameShellTexts() gives their texts to the check.
*/
const SAME_SHELL_PROGRAMS = new Map([
['gsudo', { ...PROGRAMS.get('gsudo'), textOperands: 0 }],
]);
/** cmd's start switches that take the next word as their value (/D also takes it in the same word: /Dpath) */
const CMD_START_VALUE_SWITCHES = ['/d', '/node', '/affinity', '/machine'];
/**
* The commands that run in `shell`: each of `commands`, followed by the
* programs that the wrappers among them start (for env sudo ls: env, then
* sudo). A started program has its wrapper's start.
*/
export function withStartedPrograms(commands, shell) {
const running = [];
// Each program once: readings of nested wrappers reach the same one many ways (find . -exec find . -exec … echo
// finds each level's program from every level before it), and another copy adds no answer
const seen = new Set();
const add = (command) => {
if (command.nameAtRunTime)
requireCompleteArguments(command);
const key = JSON.stringify([command.start, command.words, command.written, command.argumentError]);
if (seen.has(key))
return;
seen.add(key);
running.push(command);
if (command.nameAtRunTime)
return;
for (const { words, written, wordTexts, argumentError } of startedPrograms(command, shell)) {
add({ name: words[0] ?? written[0], words, written, wordTexts, start: command.start,
nameAtRunTime: words[0] === null, ...(argumentError === undefined ? {} : { argumentError }) });
}
};
commands.forEach(add);
return running;
}
/** The programs a command starts when it is a wrapper: none for any other command */
function startedPrograms(command, shell) {
const shellType = getShellType(shell);
const name = programName(command.name, shellType);
const { words, written, wordTexts } = command;
const from = (at) => ({ words: words.slice(at), written: written.slice(at),
wordTexts: wordTexts.slice(at),
...(command.argumentError === undefined ? {} : { argumentError: command.argumentError }) });
// runuser -u starts the program and its arguments directly, without a shell's text parsing.
if (name === 'runuser') {
requireCompleteArguments(command);
const readings = readOptions(words, TEXT_PROGRAMS.get(name).rules);
return readings.programs.flatMap(({ at }) => at === undefined ? [] : [from(at)]);
}
const posix = PROGRAMS.get(name)
?? (shellType === 'posix' ? POSIX_SHELL_COMMANDS.get(name) : undefined)
?? (programName(shell, shellType) === 'fish' ? FISH_COMMANDS.get(name) : undefined);
if (posix) {
requireCompleteArguments(command);
return posixPrograms(command, posix);
}
// Its own arguments are in -ArgumentList, a text the check doesn't read, so a program Start-Process starts has only its name
if (shellType === 'powershell' && name === 'start-process') {
requireCompleteArguments(command);
return (command.filePaths ?? []).map(({ word, written }) => ({
words: [word], written: [written], wordTexts: [word ?? written],
...(command.argumentError === undefined ? {} : { argumentError: command.argumentError }),
}));
}
if (shellType === 'cmd' && name === 'start') {
requireCompleteArguments(command);
return cmdStartProgramsAt(command).map(from);
}
if (shellType === 'cmd' && name === 'call') {
requireCompleteArguments(command);
return words.length > 1 ? [from(1)] : [];
}
return [];
}
/**
* The programs a POSIX wrapper starts: its words from each place the program
* can be. env -S puts the words of its text in its own place and reads them as
* env's words, followed by the words after the text (env -S ls sudo runs ls).
*/
function posixPrograms({ words, written, wordTexts, argumentError }, rules) {
// Windows' timeout /t 5 only waits, and GNU's timeout stops with an error at /t, which is no duration
const first = words[1];
if (first && rules.noProgramWords?.includes(first.toLowerCase()))
return [];
const from = (i, end = words.length) => ({ words: words.slice(i, end),
written: written.slice(i, end), wordTexts: wordTexts.slice(i, end),
...(argumentError === undefined ? {} : { argumentError }) });
const after = rules.programAfter;
if (after) {
// find -exec sudo rm {} ;: each program runs from the word after -exec up to ;. A word known only at run time
// where -exec could be may be -exec (find . $ACT sudo {} ;), or -exec and its program, known only at run time;
// a value (find -name "$NAME") and a word in an -exec's command (-exec grep "$PATTERN" {} ;) are neither
const programs = [];
let commandEnd = 0;
for (let i = 1; i < words.length; i++) {
const word = words[i];
if (word !== null && !after.words.includes(word)) {
if (i >= commandEnd && after.values.includes(word))
i++;
continue;
}
if (word === null && i < commandEnd)
continue;
const end = words.findIndex((next, j) => j > i && next !== null && after.ends.includes(next));
const stop = end === -1 ? words.length : end;
if (word === null)
programs.push(from(i, stop));
else
commandEnd = Math.max(commandEnd, stop);
if (stop > i + 1)
programs.push(from(i + 1, stop));
}
return programs;
}
const { operands, texts, programs: named } = readOptions(words, rules);
if (rules.programOptions) {
// The program an option names, or the one that runs without it, takes the words after -- as its arguments
const end = words.indexOf('--');
const args = end === -1 ? words.length : end + 1;
const fallback = rules.programOptions.default;
const runs = named.length > 0 ? named : end !== -1 && fallback ? [{ program: fallback }] : [];
return runs.map(({ program, at }) => ({
words: [program, ...words.slice(args)],
written: [at === undefined ? program ?? '' : written[at], ...written.slice(args)],
wordTexts: [at === undefined ? program ?? '' : wordTexts[at], ...wordTexts.slice(args)],
...(argumentError === undefined ? {} : { argumentError }),
}));
}
// psexec \\server sudo ls runs sudo on another computer
const remote = (i) => words.slice(1, i + 1).some((word) => rules.remote?.some((start) => word?.startsWith(start)));
const at = new Set();
for (let i of operands) {
// After the options: the NAME=VALUE settings, then the words before the program, which chrt may leave out. A word
// known only at run time whose = is only in an expansion may be no setting but the program (env "${TOOL:=sudo}")
while (rules.assignments && i < words.length && (words[i] ?? written[i]).includes('=')) {
if (words[i] === null && !hasWrittenEquals(written[i]) && !remote(i))
at.add(i);
i++;
}
if (rules.beforeOptional && i < words.length)
at.add(i);
i += rules.before ?? 0;
if (i < words.length && !remote(i))
at.add(i);
}
// A command of the program's own, such as tmux new-session, reads its words by its own rules
const programs = [...at].flatMap((i) => {
const subcommand = subcommandOf(words[i], rules);
return subcommand ? posixPrograms(from(i), subcommand) : [from(i)];
});
// A wrapper's command text is more of its own words, split as env splits -S's: env is the one wrapper with one.
// One known only at run time is read on as a word known only at run time (see readOptions)
return [...programs, ...texts.flatMap(({ text, after }) => {
if (text === null)
return [];
const split = envSplitWords(text);
return posixPrograms({
words: [words[0], ...split.words, ...words.slice(after)],
written: [written[0], ...split.written, ...written.slice(after)],
wordTexts: [wordTexts[0], ...split.wordTexts, ...wordTexts.slice(after)],
...(argumentError === undefined ? {} : { argumentError }),
}, rules);
})];
}
/**
* Whether a word as written has an = outside its expansions ($X, ${…}, $(…), `…`, cmd's %X%), so that its value
* has one whatever they give: env "FOO=$BAR" sets FOO
*/
function hasWrittenEquals(written) {
let depth = 0;
for (let i = 0; i < written.length; i++) {
const char = written[i];
if (char === '\\') {
i++;
if (depth === 0 && written[i] === '=')
return true;
}
else if (char === "'" && depth === 0) {
const close = written.indexOf("'", i + 1);
if (close === -1)
return false;
if (written.slice(i + 1, close).includes('='))
return true;
i = close;
}
else if (char === '`' || (char === '%' && depth === 0)) {
const close = written.indexOf(char, i + 1);
if (close !== -1)
i = close;
}
else if (char === '$' && (written[i + 1] === '{' || written[i + 1] === '(')) {
depth++;
i++;
}
else if (depth > 0 && (char === '{' || char === '(')) {
depth++;
}
else if (depth > 0 && (char === '}' || char === ')')) {
depth--;
}
else if (char === '=' && depth === 0) {
return true;
}
}
return false;
}
/** How a POSIX shell, by its name in POSIX_SHELLS, reads its own options (see BASH_OPTIONS) */
export function shellOptionReadings(program, words) {
return readOptions(words, program === 'fish' ? FISH_OPTIONS : BASH_OPTIONS);
}
/**
* For a program that runs one command text in a shell (see TEXT_PROGRAMS): its
* options read in every way, and the shell that reads its texts. Undefined for
* any other program.
*/
export function textProgramReadings(program, words, inspection = {}) {
const found = TEXT_PROGRAMS.get(program);
if (!found)
return undefined;
requireCompleteArguments(inspection);
const readings = readOptions(words, found.rules);
// A command of the program's own reads its words by its own rules (tmux new 'sudo ls'), and so does each one
// after a separator (tmux new -d \; new-window 'sudo ls')
const first = Math.min(words.length, ...readings.operands);
const separated = words.flatMap((word, j) => (j > first && word !== null && word === found.rules.separator ? [j + 1] : []));
for (const at of new Set([...readings.operands, ...separated])) {
const subcommand = subcommandOf(words[at], found.rules);
if (!subcommand)
continue;
const own = readOptions(words.slice(at), subcommand);
readings.hidden || (readings.hidden = own.hidden);
readings.texts.push(...own.texts.map((text) => ({
...text, after: text.after + at, ...(text.at === undefined ? {} : { at: text.at + at }), ...(text.to === undefined ? {} : { to: text.to + at }),
})));
}
const argumentsAfter = found.rules.shellArgumentsAfter;
const argumentsAt = argumentsAfter === undefined ? {} : {
arguments: [...new Set(readings.operands)].sort((a, b) => a - b).slice(argumentsAfter),
};
return { readings, shell: found.shell, ...argumentsAt };
}
/** For a program that runs one command text in the shell it was started from (see SAME_SHELL_PROGRAMS): its options read in every way */
export function sameShellProgramReadings(program, words, inspection = {}) {
const rules = SAME_SHELL_PROGRAMS.get(program);
if (!rules)
return undefined;
requireCompleteArguments(inspection);
return readOptions(words, rules);
}
/**
* Reads a program's options by its rules, in every way they can be read: an
* option the rules don't list, and a word known only at run time, may take the
* next word as its value or not, though not a word that is an option itself.
* A wrapper's command text known only at run time (env -S "$CMD") is read on
* as a word known only at run time. For a shell, each reading also knows what
* the words after its options are (bash -c makes the first one the text).
*/
function readOptions(words, rules) {
const readings = { operands: [], texts: [], programs: [], hidden: false };
const read = new Set();
const isOption = (word) => typeof word === 'string' && (word.startsWith('-') || (rules.plus === true && word.length > 1 && word.startsWith('+'))
|| (rules.slash === true && word.length > 1 && word.startsWith('/')));
// A word after the options, the `count`th of them, by what the options before it made it. True when the
// options can go on after it (permute)
const operand = (i, role, count) => {
if (role === 'text') {
if (i < words.length)
readings.texts.push({ text: words[i], at: i, after: i + 1 });
return false;
}
if (role === 'program') {
if (i < words.length)
readings.programs.push({ program: words[i], at: i });
return false;
}
if (role === 'arguments')
return false;
if (count === rules.textOperands) {
// The text goes on to the end, or to a word that ends it (parallel's :::)
const end = (from) => {
const found = words.findIndex((word, j) => j >= from && word !== null && rules.textEnds?.includes(word));
return found === -1 ? words.length : found;
};
const to = end(i);
if (to > i) {
const text = words.slice(i, to);
readings.texts.push({ text: text.includes(null) ? null : text.join(' '), at: i, to, after: to });
return false;
}
// With no text before them, each argument after parallel's ::: is a command of its own, and those in a ::::
// file or in its input, when it is given no arguments, can't be seen
words.forEach((word, j) => {
if (j < i || word === null || !rules.commandArguments?.includes(word))
return;
for (let k = j + 1; k < end(j + 1); k++)
readings.texts.push({ text: words[k], at: k, after: k + 1 });
});
const after = words.slice(i).filter((word) => word !== null);
if (rules.commandFiles && (after.some((word) => rules.commandFiles?.includes(word)) || !after.some((word) => rules.textEnds?.includes(word)))) {
readings.hidden = true;
}
return false;
}
readings.operands.push(i);
return rules.permute === true;
};
const readFrom = (i, role, count = 0) => {
const key = `${i} ${role ?? ''} ${count}`;
if (read.has(key))
return;
read.add(key);
const word = words[i];
if (word === null) {
// An option with or without a value, or the first word after them
if (operand(i, role, count))
readFrom(i + 1, role, count + 1);
readFrom(i + 1, role, count);
const next = words[i + 1];
if (isOption(next))
return;
readFrom(i + 2, role, count);
// Or an option that gives the command text: its value (fish $X 'sudo ls', su $OPTS 'sudo ls'), or the first
// word after the options (bash $X 'sudo ls')
if (next !== undefined && rules.texts) {
readings.texts.push({ text: next, at: i + 1, after: i + 2 });
if (rules.optionsAfterTexts)
readFrom(i + 2, role, count);
}
if (Object.values(rules.operandRoles ?? {}).includes('text'))
readFrom(i + 1, 'text', count);
if (Object.values(rules.operandRoles ?? {}).includes('program'))
readFrom(i + 1, 'program', count);
return;
}
if (!isOption(word)) {
if (word !== undefined && operand(i, role, count))
readFrom(i + 1, role, count + 1);
else if (word === undefined)
operand(i, role, count);
return;
}
if (word === '--') {
// Every word after -- is one after the options
for (let j = i + 1, n = count; operand(j, role, n) && j < words.length; j++, n++)
;
return;
}
for (const reading of optionReadings(word, rules)) {
if (reading === null)
continue;
// A value the rules don't know of isn't a word that is an option itself
if (reading.uncertain && reading.next > 0 && isOption(words[i + reading.next]))
continue;
const next = reading.role === 'text' || role === 'text' ? 'text' : reading.role ?? role;
if (reading.program !== undefined) {
const at = reading.next === 1 ? i + 1 : undefined;
const program = at === undefined ? reading.program : words[at];
if (program !== undefined)
readings.programs.push({ program, at });
readFrom(i + 1 + reading.next, next, count);
continue;
}
if (reading.text === undefined) {
readFrom(i + 1 + reading.next, next, count);
continue;
}
const at = reading.next === 1 ? i + 1 : undefined;
const text = at === undefined ? reading.text : words[at];
if (text === undefined)
continue;
readings.texts.push({ text, at, after: i + 1 + reading.next });
if (rules.optionsAfterTexts)
readFrom(i + 1 + reading.next, next, count);
else if (text === null)
readFrom(i + 1, role, count);
}
};
readFrom(1);
return readings;
}
/**
* The ways to read an option word, null for one with which no program runs.
* An option that takes a value takes the rest of the word (-uroot,
* --user=root), or the next word when the rest is empty. One the rules don't
* list may take a value or not, so it has both readings. A lone - is an
* option too: env's -i.
*/
function optionReadings(option, rules) {
// A switch keeps its value in its own word (runas /user:admin)
if (rules.slash && option.startsWith('/'))
return [{ next: 0 }];
let long;
if (option.startsWith('--'))
long = option.slice(2);
else if (rules.wordOptions)
long = option.slice(1);
if (long !== undefined) {
const equals = long.indexOf('=');
const name = longOption(equals === -1 ? long : long.slice(0, equals), rules);
if (name !== undefined && rules.noProgramLong?.includes(name))
return [null];
const isText = name !== undefined && rules.texts?.long.includes(name);
const isProgram = name !== undefined && rules.programOptions?.long.includes(name);
const role = name === undefined ? undefined : rules.operandRoles?.[name];
const value = long.slice(equals + 1);
if (equals !== -1) {
if (isText)
return [{ next: 0, text: value, role }];
if (isProgram)
return [{ next: 0, program: value }];
return [{ next: 0, role }];
}
if (rules.equalsOnly)
return [{ next: 0, role }];
if (name === undefined)
return [{ next: 0 }, { next: 1, uncertain: true }];
if (isText)
return [{ next: 1, text: '', role }];
if (isProgram)
return [{ next: 1, program: '' }];
if (rules.longPairs?.includes(name))
return [{ next: 2, role }];
if (rules.long?.includes(name))
return [{ next: 1, role }];
return [{ next: 0, role }];
}
if (rules.groupValues === 'words')
return groupWordReadings(option, rules);
const readings = [];
let role;
for (let i = 1; i < option.length; i++) {
const letter = option[i];
role = role === 'text' ? role : rules.operandRoles?.[letter] ?? role;
const value = i === option.length - 1 ? { next: 1, role } : { next: 0, role };
if (rules.noProgram?.includes(letter))
return [...readings, null];
if (rules.texts?.letters.includes(letter))
return [...readings, { ...value, text: option.slice(i + 1) }];
if (rules.programOptions?.letters?.includes(letter))
return [...readings, { ...value, program: option.slice(i + 1) }];
if (rules.attachedLetters?.includes(letter))
return [...readings, { next: 0, role }];
if (rules.letters?.includes(letter))
return [...readings, value];
// An option the rules don't list may take a value, and the next letters read on as if it takes none
if (!rules.flags?.includes(letter))
readings.push({ ...value, uncertain: true });
}
return [...readings, { next: 0, role }];
}
/**
* The ways to read a group of letters as bash reads it: each letter that
* takes a value takes one of the words after the group, in order (bash -euo
* pipefail deploy.sh), and one the rules don't list may take one too.
*/
function groupWordReadings(option, rules) {
let values = 0;
let unlisted = 0;
let role;
for (const letter of option.slice(1)) {
if (rules.noProgram?.includes(letter))
return [null];
role = role === 'text' ? role : rules.operandRoles?.[letter] ?? role;
if (rules.letters?.includes(letter))
values++;
else if (!rules.flags?.includes(letter))
unlisted++;
}
return Array.from({ length: unlisted + 1 }, (_, taken) => ({
next: values + taken, role, ...(taken > 0 ? { uncertain: true } : {}),
}));
}
/** The long option a name means: the one it names, or the only one it shortens */
function longOption(name, rules) {
const long = [
...rules.long ?? [], ...rules.longPairs ?? [], ...rules.longFlags ?? [], ...rules.noProgramLong ?? [],
...rules.texts?.long ?? [], ...rules.programOptions?.long ?? [],
];
if (long.includes(name))
return name;
// firejail and capsh know their long options only in full
if (rules.equalsOnly)
return undefined;
const shortened = long.filter((known) => known.startsWith(name));
return shortened.length === 1 ? shortened[0] : undefined;
}
/** The command of the program's own that a word names: the one it names, or the one it shortens (tmux new-s) */
function subcommandOf(word, rules) {
if (!word || !rules.subcommands)
return undefined;
const named = rules.subcommands.get(word);
if (named)
return named;
const shortened = new Set([...rules.subcommands].filter(([name]) => name.startsWith(word)).map(([, subcommand]) => subcommand));
return shortened.size === 1 ? [...shortened][0] : undefined;
}
/** What a backslash escape in env -S's text gives, besides the character after the backslash */
const ENV_ESCAPES = { f: '\f', n: '\n', r: '\r', t: '\t', v: '\v', _: ' ' };
/**
* The words env makes of -S's text, as GNU's and BSD's env split it: spaces,
* tabs and \_ between words; '…' and "…" keep a word together, and in '…'
* only \\ and \' are escapes; a backslash escape gives its character (\t a
* tab, \_ a space inside "…"), and \c ends the text; a # that starts a word
* starts a comment; and env fills in ${NAME} at run time, so its word is known
* only then. Where env would stop with an error, nothing runs, so the text is
* read as well as it can be.
*/
function envSplitWords(text) {
const split = { words: [], written: [], wordTexts: [] };
// The word being read: undefined between words, null when known only at run time
let word;
// Its text, with ${NAME} as written
let wordText = '';
let start = 0;
let quote = '';
const add = (chars, at, asText = chars ?? '') => {
if (word === undefined) {
word = '';
wordText = '';
start = at;
}
word = word === null || chars === null ? null : word + chars;
wordText += asText;
};
const end = (at) => {
if (word === undefined)
return;
split.words.push(word);
split.written.push(text.slice(start, at));
split.wordTexts.push(wordText);
word = undefined;
};
for (let i = 0; i < text.length; i++) {
const char = text[i];
if (quote === "'") {
if (char === "'")
quote = '';
else if (char === '\\' && (text[i + 1] === '\\' || text[i + 1] === "'"))
add(text[++i], i - 1);
else
add(char, i);
continue;
}
if (char === '\\') {
const escaped = text[++i];
if (escaped === undefined || escaped === 'c') {
end(i - 1);
return split;
}
if (escaped === '_' && !quote)
end(i - 1);
else
add(ENV_ESCAPES[escaped] ?? escaped, i - 1);
continue;
}
if (char === quote) {
quote = '';
continue;
}
if (!quote && (char === '"' || char === "'")) {
quote = char;
add('', i);
continue;
}
const close = char === '$' && text[i + 1] === '{' ? text.indexOf('}', i) : -1;
if (close !== -1) {
add(null, i, text.slice(i, close + 1));
i = close;
continue;
}
if (!quote && ' \t\n\v\f\r'.includes(char)) {
end(i);
continue;
}
// A comment, to the end of the text
if (!quote && char === '#' && word === undefined)
break;
add(char, i);
}
end(text.length);
return split;
}
/**
* Where the program cmd's start starts can be: after its switches and its
* window title, the first word in quotes. A word with %VAR% in it may be a
* switch or the program: it counts, and so does the next word.
*/
function cmdStartProgramsAt({ words, written }) {
const at = [];
let title = false;
for (let i = 1; i < words.length; i++) {
const word = words[i];
if (!title && written[i].startsWith('"')) {
title = true;
continue;
}
if (word?.startsWith('/')) {
if (CMD_START_VALUE_SWITCHES.includes(word.toLowerCase()))
i++;
continue;
}
at.push(i);
if (word !== null)
break;
}
return at;
}