@kirkchinese/harness-forge 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/README.md +4 -0
  2. package/docs/DETAIL.zh.md +47 -0
  3. package/lib/agents/presets.d.ts +7 -0
  4. package/lib/agents/presets.js +11 -1
  5. package/lib/agents/profiles.js +3 -2
  6. package/lib/agents/row.js +3 -1
  7. package/lib/client/paths.d.ts +12 -0
  8. package/lib/client/paths.js +68 -0
  9. package/lib/client/typert.d.ts +12 -1
  10. package/lib/client/typert.js +54 -6
  11. package/lib/client.js +1593 -270
  12. package/lib/commands/row.js +1 -1
  13. package/lib/context/instructions.js +5 -5
  14. package/lib/dsh/host.d.ts +3 -0
  15. package/lib/dsh/host.js +3 -0
  16. package/lib/forge/contract.d.ts +42 -2
  17. package/lib/forge/contract.js +3 -1
  18. package/lib/forge/follow.d.ts +30 -0
  19. package/lib/forge/follow.js +73 -0
  20. package/lib/forge/ledger.d.ts +70 -7
  21. package/lib/forge/ledger.js +314 -42
  22. package/lib/forge/projects.d.ts +5 -2
  23. package/lib/forge/projects.js +23 -16
  24. package/lib/forge/remote/archive.d.ts +65 -0
  25. package/lib/forge/remote/archive.js +565 -0
  26. package/lib/forge/remote/code-parts.d.ts +18 -0
  27. package/lib/forge/remote/code-parts.js +76 -0
  28. package/lib/forge/remote/fetch.d.ts +265 -0
  29. package/lib/forge/remote/fetch.js +1133 -0
  30. package/lib/forge/remote/service.d.ts +256 -0
  31. package/lib/forge/remote/service.js +868 -0
  32. package/lib/forge/service.d.ts +19 -9
  33. package/lib/forge/service.js +47 -31
  34. package/lib/forge/settings.d.ts +5 -3
  35. package/lib/forge/settings.js +11 -4
  36. package/lib/forge/state.d.ts +60 -0
  37. package/lib/forge/state.js +174 -58
  38. package/lib/hooks/broker/engine.js +2 -8
  39. package/lib/hooks/broker/session-events.d.ts +5 -0
  40. package/lib/hooks/broker/session-events.js +12 -3
  41. package/lib/hooks/broker/types.d.ts +7 -5
  42. package/lib/hooks/condition.d.ts +78 -2
  43. package/lib/hooks/condition.js +494 -73
  44. package/lib/hooks/config.d.ts +1 -1
  45. package/lib/hooks/config.js +4 -0
  46. package/lib/hooks/glob.d.ts +41 -0
  47. package/lib/hooks/glob.js +114 -0
  48. package/lib/hooks/permissions.d.ts +8 -3
  49. package/lib/hooks/permissions.js +119 -26
  50. package/lib/hooks/powershell-aliases.d.ts +19 -0
  51. package/lib/hooks/powershell-aliases.js +58 -0
  52. package/lib/hooks/process.d.ts +17 -0
  53. package/lib/hooks/process.js +156 -1
  54. package/lib/hooks/row.js +2 -0
  55. package/lib/hooks/runner.d.ts +17 -4
  56. package/lib/hooks/runner.js +42 -13
  57. package/lib/hooks/shell-commands.d.ts +10 -1
  58. package/lib/hooks/shell-commands.js +74 -10
  59. package/lib/hooks/shell.d.ts +3 -2
  60. package/lib/hooks/shell.js +5 -2
  61. package/lib/hooks/vocabulary.js +3 -1
  62. package/lib/mcp/catalog.d.ts +5 -2
  63. package/lib/mcp/catalog.js +18 -10
  64. package/lib/mcp/mount.d.ts +40 -2
  65. package/lib/mcp/mount.js +131 -31
  66. package/lib/mcp/policy.d.ts +42 -0
  67. package/lib/mcp/policy.js +43 -0
  68. package/lib/mcp/remote.js +5 -15
  69. package/lib/mcp/row.js +111 -17
  70. package/lib/mods/loader.js +4 -0
  71. package/lib/mods/service/turns.d.ts +8 -7
  72. package/lib/mods/service/turns.js +10 -35
  73. package/lib/opencode/bun.js +14 -2
  74. package/lib/opencode/row.d.ts +14 -1
  75. package/lib/opencode/row.js +38 -20
  76. package/lib/opencode/runtime/server.js +2 -1
  77. package/lib/porting/adapter-paths.d.ts +13 -0
  78. package/lib/porting/adapter-paths.js +120 -0
  79. package/lib/porting/port-gap.d.ts +10 -4
  80. package/lib/porting/port-gap.js +43 -7
  81. package/lib/porting/prompt.js +9 -7
  82. package/lib/porting/row.js +7 -5
  83. package/lib/porting/verify-port.d.ts +3 -10
  84. package/lib/porting/verify-port.js +12 -34
  85. package/lib/sessions/chat-import.d.ts +48 -0
  86. package/lib/sessions/chat-import.js +44 -0
  87. package/lib/sessions/claude.d.ts +16 -10
  88. package/lib/sessions/claude.js +76 -55
  89. package/lib/sessions/codex-discover.d.ts +34 -0
  90. package/lib/sessions/codex-discover.js +205 -0
  91. package/lib/sessions/codex-meta.d.ts +63 -0
  92. package/lib/sessions/codex-meta.js +148 -0
  93. package/lib/sessions/codex-text.d.ts +9 -0
  94. package/lib/sessions/codex-text.js +44 -0
  95. package/lib/sessions/codex.d.ts +34 -22
  96. package/lib/sessions/codex.js +150 -183
  97. package/lib/sessions/opencode.d.ts +15 -9
  98. package/lib/sessions/opencode.js +77 -58
  99. package/lib/sessions/persist.d.ts +162 -0
  100. package/lib/sessions/persist.js +377 -0
  101. package/lib/sessions/row.d.ts +2 -1
  102. package/lib/sessions/row.js +75 -9
  103. package/lib/sessions/turns.d.ts +31 -0
  104. package/lib/sessions/turns.js +63 -0
  105. package/lib/sessions/zstd.d.ts +15 -0
  106. package/lib/sessions/zstd.js +152 -0
  107. package/lib/shared/render.d.ts +30 -1
  108. package/lib/shared/render.js +813 -48
  109. package/lib/skills/provider.d.ts +2 -0
  110. package/lib/skills/provider.js +8 -2
  111. package/lib/skills/row.js +1 -1
  112. package/lib/workbench/adapter-coverage.d.ts +20 -2
  113. package/lib/workbench/adapter-coverage.js +46 -7
  114. package/lib/workbench/overview.d.ts +77 -27
  115. package/lib/workbench/overview.js +99 -12
  116. package/lib/workbench/remote.d.ts +64 -21
  117. package/lib/workbench/remote.js +181 -42
  118. package/lib/workbench/settings.d.ts +5 -1
  119. package/lib/workbench/settings.js +6 -2
  120. package/lib/workbench/workbench.d.ts +34 -4
  121. package/lib/workbench/workbench.js +147 -46
  122. package/locale/zh.json +2 -1
  123. package/package.json +3 -2
  124. package/lib/forge/marketplace-install.d.ts +0 -3
  125. package/lib/forge/marketplace-install.js +0 -64
@@ -17,7 +17,10 @@
17
17
  import { readFileSync, statSync } from 'node:fs';
18
18
  import { homedir } from 'node:os';
19
19
  import { basename, isAbsolute, join, resolve } from 'node:path';
20
- import { isInside, realOrLexical, workspaceRootOf } from '@kirkchinese/harness-forge-core';
20
+ import { isInside, linksReachNewShare, reachesNewShare, realOrLexical, stripTrailing, workspaceRootOf } from '@kirkchinese/harness-forge-core';
21
+ import { redirectFiles } from '../hooks/condition.js';
22
+ import { powershellCommand } from '../hooks/powershell-aliases.js';
23
+ import { powershellAmpersand } from '../hooks/shell-commands.js';
21
24
  /** What stands in place of a shell line that did not run. */
22
25
  function shellNote(reason) {
23
26
  return `[Harness Forge: this shell command was not run: ${reason}]`;
@@ -28,16 +31,76 @@ const FILE_LIMIT = 256 * 1024;
28
31
  const PLACEHOLDER = /\\\$|\$\{(CLAUDE_SKILL_DIR|CLAUDE_PROJECT_DIR|CLAUDE_SESSION_ID|CLAUDE_PLUGIN_ROOT|CLAUDE_PLUGIN_DATA)\}|\$ARGUMENTS\[(\d+)\]|\$ARGUMENTS\b|\$(\d+)|\$([A-Za-z_][A-Za-z0-9_-]*)/gu;
29
32
  /** Split a body into prose and shell lines, as written: a fenced ```! block, or an inline !`cmd` at line start or after whitespace. */
30
33
  function segmentsOf(body) {
34
+ // A scan in one pass: the equivalent pattern reads to the end of the body from every unclosed fence.
31
35
  const segments = [];
36
+ const breaks = /[\n\r\u2028\u2029]/u;
37
+ const lineStart = (at) => at === 0 || breaks.test(body[at - 1] ?? '');
32
38
  let cursor = 0;
33
- for (const match of body.matchAll(/^```!\s*\r?\n([\s\S]*?)\r?\n```[ \t]*$|(^|\s)!`([^`\n]+)`/gmu)) {
34
- segments.push({ kind: 'text', text: body.slice(cursor, match.index) });
35
- segments.push(match[1] !== undefined ? { kind: 'shell', command: match[1], lead: '' } : { kind: 'shell', command: match[3] ?? '', lead: match[2] ?? '' });
36
- cursor = (match.index ?? 0) + match[0].length;
39
+ /** Fences cannot close at or after this index (a search from there found no closing line). */
40
+ let unclosedFrom = body.length + 1;
41
+ let tick = -1;
42
+ let newline = -1;
43
+ const take = (at, end, segment) => {
44
+ segments.push({ kind: 'text', text: body.slice(cursor, at) }, segment);
45
+ cursor = end;
46
+ return end;
47
+ };
48
+ for (let at = 0; at < body.length;) {
49
+ if (lineStart(at) && body.startsWith('```!', at)) {
50
+ const fence = fenceAt(body, at, unclosedFrom);
51
+ if (fence !== undefined && 'unclosedFrom' in fence)
52
+ unclosedFrom = fence.unclosedFrom;
53
+ else if (fence !== undefined) {
54
+ at = take(at, fence.end, { kind: 'shell', command: fence.command, lead: '' });
55
+ continue;
56
+ }
57
+ }
58
+ const bang = lineStart(at) && body[at] === '!' ? at : /\s/u.test(body[at] ?? '') && body[at + 1] === '!' ? at + 1 : -1;
59
+ if (bang !== -1 && body[bang + 1] === '`') {
60
+ if (tick < bang + 2)
61
+ tick = body.indexOf('`', bang + 2);
62
+ if (newline < bang + 2)
63
+ newline = body.indexOf('\n', bang + 2);
64
+ if (tick > bang + 2 && (newline === -1 || tick < newline)) {
65
+ at = take(at, tick + 1, { kind: 'shell', command: body.slice(bang + 2, tick), lead: body.slice(at, bang) });
66
+ continue;
67
+ }
68
+ }
69
+ at++;
37
70
  }
38
71
  segments.push({ kind: 'text', text: body.slice(cursor) });
39
72
  return segments;
40
73
  }
74
+ /**
75
+ * The fenced ```` ```! ```` block opening at `at`: the opener line, its body,
76
+ * and a closing line of three backticks and blanks.
77
+ */
78
+ function fenceAt(body, at, unclosedFrom) {
79
+ let index = at + 4;
80
+ while (body[index] === ' ' || body[index] === '\t')
81
+ index++;
82
+ if (body[index] === '\r')
83
+ index++;
84
+ if (body[index] !== '\n')
85
+ return undefined;
86
+ const start = index + 1;
87
+ if (start - 1 >= unclosedFrom)
88
+ return undefined;
89
+ for (let search = start - 1;;) {
90
+ const close = body.indexOf('\n```', search);
91
+ if (close === -1)
92
+ return { unclosedFrom: start - 1 };
93
+ let end = close + 4;
94
+ while (body[end] === ' ' || body[end] === '\t')
95
+ end++;
96
+ if (end === body.length || /[\n\r\u2028\u2029]/u.test(body[end] ?? '')) {
97
+ // The body ends before the `\r?\n` of the closing line, whose own line break stays outside the fence.
98
+ if (close >= start)
99
+ return { command: body.slice(start, close > start && body[close - 1] === '\r' ? close - 1 : close), end };
100
+ }
101
+ search = close + 1;
102
+ }
103
+ }
41
104
  /** Render one body. */
42
105
  export async function renderBody(body, context) {
43
106
  const args = splitArguments(context.rawArguments);
@@ -77,17 +140,9 @@ export async function renderBody(body, context) {
77
140
  const segments = segmentsOf(body);
78
141
  const references = segments.flatMap(segment => segment.kind === 'text' ? fileReferences(segment.text, context) : []);
79
142
  const kind = context.shellKind === 'powershell' ? 'powershell' : context.shell.defaultKind;
80
- let commands = 0;
81
- let text = '';
82
- for (const segment of segments) {
83
- if (segment.kind === 'text') {
84
- text += substituteText(segment.text);
85
- continue;
86
- }
87
- if (context.refuseShell !== undefined) {
88
- text += segment.lead + shellNote(context.refuseShell);
89
- continue;
90
- }
143
+ const lines = segments.map((segment) => {
144
+ if (segment.kind === 'text' || context.refuseShell !== undefined)
145
+ return undefined;
91
146
  const values = {};
92
147
  const line = shellCommand(segment.command, kind, (match, variable, indexed, short, name) => {
93
148
  const value = valueOf(match, variable, indexed, short, name);
@@ -97,12 +152,31 @@ export async function renderBody(body, context) {
97
152
  values[key] = value;
98
153
  return key;
99
154
  });
100
- if ('refused' in line) {
101
- text += segment.lead + shellNote(`${line.refused}, where Harness Forge cannot pass it safely`);
155
+ if ('refused' in line)
156
+ return { refused: `${line.refused}, where Harness Forge cannot pass it safely` };
157
+ if (line.operands.some(key => values[key]?.startsWith('-') === true))
158
+ return { refused: 'a value starts with "-" where the program would read it as an option' };
159
+ return { line, values };
160
+ });
161
+ const runs = lines.flatMap(entry => entry !== undefined && 'line' in entry ? [entry.line] : []);
162
+ // The lines that run, in order, as one sequence; each line's constructs are its own.
163
+ const bodySteps = runs.flatMap((line, at) => line.steps.map(step => ({ ...step, groups: step.groups.map(group => `${String(at)}:${group}`) })));
164
+ const bodyRefused = runs.some(line => line.chosen) && writesThenRuns(bodySteps) ? WRITE_THEN_RUN : undefined;
165
+ let commands = 0;
166
+ let text = '';
167
+ for (const [at, segment] of segments.entries()) {
168
+ if (segment.kind === 'text') {
169
+ text += substituteText(segment.text);
170
+ continue;
171
+ }
172
+ const entry = lines[at];
173
+ const refused = context.refuseShell ?? (entry === undefined ? undefined : 'refused' in entry ? entry.refused : bodyRefused);
174
+ if (refused !== undefined || entry === undefined || !('line' in entry)) {
175
+ text += segment.lead + shellNote(refused ?? '');
102
176
  continue;
103
177
  }
104
178
  commands += 1;
105
- text += segment.lead + await execute(line.command, kind, values, context);
179
+ text += segment.lead + await execute(entry.line.command, kind, entry.values, context);
106
180
  }
107
181
  const withArguments = !consumed && context.rawArguments.trim().length > 0
108
182
  ? `${text.trimEnd()}\n\nARGUMENTS: ${context.rawArguments.trim()}`
@@ -210,35 +284,490 @@ const WHERE = {
210
284
  const BASH_PREFIXES = new Set(['if', 'then', 'else', 'elif', 'do', 'while', 'until', '!', '{', '}', 'fi', 'done', 'esac']);
211
285
  /** bash builtins and keywords: none may take a value, apart from those in `argumentOf`. */
212
286
  const BASH_BUILTINS = new Set(['.', ':', '[', 'alias', 'bg', 'bind', 'break', 'builtin', 'caller', 'case', 'cd', 'command', 'compgen', 'complete', 'compopt', 'continue', 'coproc', 'declare', 'dirs', 'disown', 'echo', 'enable', 'eval', 'exec', 'exit', 'export', 'false', 'fc', 'fg', 'for', 'function', 'getopts', 'hash', 'help', 'history', 'jobs', 'kill', 'let', 'local', 'logout', 'mapfile', 'popd', 'printf', 'pushd', 'pwd', 'read', 'readarray', 'readonly', 'return', 'select', 'set', 'shift', 'shopt', 'source', 'suspend', 'test', 'time', 'times', 'trap', 'true', 'type', 'typeset', 'ulimit', 'umask', 'unalias', 'unset', 'wait']);
213
- /** Programs that run a command or code they are given. */
214
- const RUNNERS = new Set(['env', 'sudo', 'doas', 'su', 'xargs', 'nohup', 'nice', 'ionice', 'timeout', 'stdbuf', 'setsid', 'chroot', 'unshare', 'nsenter', 'flock', 'watch', 'strace', 'ltrace', 'parallel', 'ssh', 'sed', 'awk', 'gawk', 'mawk', 'nawk', 'sh', 'bash', 'dash', 'zsh', 'ksh', 'mksh', 'fish', 'csh', 'tcsh', 'busybox', 'pwsh', 'powershell', 'cmd', 'python', 'python2', 'python3', 'perl', 'ruby', 'node', 'deno', 'bun', 'php', 'lua', 'tclsh', 'expect', 'script']);
215
- /** PowerShell commands (and aliases) that run, load or define code they are given. */
216
- const POWERSHELL_RUNNERS = new Set(['.', 'iex', 'invoke-expression', 'icm', 'invoke-command', 'saps', 'start', 'start-process', 'sajb', 'start-job', 'start-threadjob', 'ii', 'invoke-item', 'add-type', 'nmo', 'new-module', 'ipmo', 'import-module', 'foreach-object', 'where-object', 'sv', 'set-variable', 'nv', 'new-variable', 'si', 'set-item', 'ni', 'new-item']);
287
+ /**
288
+ * Programs whose purpose is to run a command, code, package, container, task or
289
+ * file named by their arguments: no value anywhere on their line. Interpreters
290
+ * and shells are recognised by {@link FAMILIES} however they are spelled; the
291
+ * ones repeated here are only the exact names.
292
+ */
293
+ /**
294
+ * Wrappers that run the command given after their options, with other rights,
295
+ * limits, timing or environment. Those in {@link WRAPPERS} are resolved to the
296
+ * command they run where a line is checked for a program that reads code or
297
+ * runs a package manager; any other one counts as both.
298
+ */
299
+ const WRAPPING_RUNNERS = new Set(['env', 'sudo', 'doas', 'su', 'runuser', 'pkexec', 'sg', 'nohup', 'nice', 'ionice', 'chrt', 'taskset', 'numactl', 'cpulimit', 'prlimit', 'setpriv', 'timeout', 'time', 'chronic', 'stdbuf', 'unbuffer', 'rlwrap', 'setsid', 'chroot', 'unshare', 'nsenter', 'flock', 'fakeroot', 'faketime', 'firejail', 'bwrap', 'systemd-run', 'dbus-run-session', 'xvfb-run', 'caffeinate', 'strace', 'ltrace', 'valgrind', 'gdb', 'lldb', 'script', 'expect']);
300
+ const RUNNERS = new Set([
301
+ ...WRAPPING_RUNNERS,
302
+ // Watchers and benchmark tools that run a command again and again.
303
+ 'watch', 'watchexec', 'entr', 'nodemon', 'hyperfine',
304
+ // Programs that build commands from their arguments or input, or run them elsewhere.
305
+ 'xargs', 'parallel', 'ssh',
306
+ // Text tools with a programming language of their own.
307
+ 'sed', 'awk', 'gawk', 'mawk', 'nawk',
308
+ // JavaScript package and TypeScript runners: they run a package or file they are given. (`npm`, `pnpm`, `yarn`: see PACKAGE_MANAGERS.)
309
+ 'npx', 'pnpx', 'bunx', 'corepack', 'tsx', 'ts-node', 'ts-node-esm', 'vite-node', 'esno',
310
+ // Python package runners.
311
+ 'uvx',
312
+ // Build and task runners: a value picks the makefile, the target or a variable a recipe expands.
313
+ 'make', 'gmake', 'bmake', 'just', 'task',
314
+ // Build tools, test and task runners that run the project's build files, scripts or tasks, named by their arguments.
315
+ 'mvn', 'mvnw', 'gradle', 'gradlew', 'ant', 'sbt', 'rake', 'ninja', 'bazel', 'bazelisk', 'scons', 'meson', 'cmake', 'ctest', 'dotnet', 'msbuild', 'tox', 'nox', 'grunt', 'gulp', 'nx', 'turbo', 'lerna',
316
+ // Tool version managers: they run the tool a version or an argument picks.
317
+ 'mise', 'asdf', 'volta', 'nvm', 'fnm', 'pyenv', 'rbenv', 'nodenv',
318
+ // Interpreters and shells by exact name (FAMILIES covers every spelling).
319
+ 'sh', 'bash', 'dash', 'zsh', 'ksh', 'mksh', 'fish', 'csh', 'tcsh', 'busybox', 'pwsh', 'powershell', 'cmd', 'python', 'python2', 'python3', 'perl', 'ruby', 'node', 'deno', 'bun', 'php', 'lua', 'tclsh',
320
+ ]);
321
+ /** Docker's (and Podman's and nerdctl's) subcommands that list or inspect containers, images, volumes and networks. */
322
+ const CONTAINER_QUERIES = [
323
+ 'ps', 'images', 'logs', 'inspect', 'top', 'port', 'stats', 'history', 'version', 'info', 'search',
324
+ 'container ls', 'container list', 'container ps', 'container inspect', 'container logs', 'container top', 'container port', 'container stats',
325
+ 'image ls', 'image list', 'image inspect', 'image history', 'volume ls', 'volume inspect', 'network ls', 'network inspect',
326
+ ];
327
+ /**
328
+ * Package managers and container or cluster tools, with the only subcommands
329
+ * in which they take a value: each lists packages, metadata, containers or
330
+ * resources and runs no package, lifecycle or build script, project task,
331
+ * container or plugin named by its arguments (checked against each tool's
332
+ * reference below). A subcommand of more than one word is written with
333
+ * blanks. Every other subcommand (`install`, `add`, `run`, `exec`, `test`,
334
+ * `build`, `x`, `dlx`, a script name …), a missing or dynamic one, and options
335
+ * before it refuse a value anywhere on the line; in an allowed subcommand the
336
+ * value must be an operand (see `packageOperand`).
337
+ */
338
+ const PACKAGE_MANAGERS = {
339
+ // https://docs.npmjs.com/cli/commands (with aliases). Not `docs`, `bugs`, `repo`, `home` or `help`: they start the
340
+ // configured browser or viewer, on a URL the package's metadata chooses.
341
+ npm: ['view', 'info', 'show', 'v', 'search', 'find', 's', 'se', 'ls', 'list', 'la', 'll', 'outdated', 'explain', 'why'],
342
+ // https://pnpm.io/cli/list, /cli/why, /cli/outdated. Any other word may run the project script of that name.
343
+ pnpm: ['list', 'ls', 'll', 'la', 'why', 'outdated'],
344
+ // https://yarnpkg.com/cli/info, /cli/why (also Yarn 1). Yarn 2+ runs a script or binary for any unknown word, `list` included.
345
+ yarn: ['info', 'why'],
346
+ // Bun is a JavaScript runtime as well (see FAMILIES): no subcommand takes a value.
347
+ bun: [],
348
+ // https://docs.astral.sh/uv/reference/cli/#uv-pip: these read the installed environment and build nothing.
349
+ uv: ['pip show', 'pip list', 'pip freeze', 'pip tree'],
350
+ // https://pip.pypa.io/en/stable/cli/: these read installed metadata; `download`, `wheel` and `install` may build.
351
+ pip: ['show', 'list', 'freeze', 'check'],
352
+ // https://pipx.pypa.io/stable/docs/
353
+ pipx: ['list'],
354
+ // https://python-poetry.org/docs/cli/
355
+ poetry: ['show', 'search'],
356
+ // https://doc.rust-lang.org/cargo/commands/: these read the registry or the lock file and run no build script.
357
+ cargo: ['search', 'tree', 'info'],
358
+ // https://pkg.go.dev/cmd/go: `go version FILE` reads a binary without running it.
359
+ go: ['doc', 'list', 'version'],
360
+ // https://guides.rubygems.org/command-reference/
361
+ gem: ['list', 'search', 'info', 'contents', 'dependency'],
362
+ // https://bundler.io/man/bundle-list.1.html, /bundle-info.1.html
363
+ bundle: ['list', 'info'],
364
+ // https://getcomposer.org/doc/03-cli.md
365
+ composer: ['show', 'info', 'search', 'depends', 'why', 'prohibits', 'why-not', 'outdated', 'licenses'],
366
+ // https://docs.docker.com/reference/cli/docker/ (Podman and nerdctl follow it): listing and inspecting only.
367
+ docker: CONTAINER_QUERIES,
368
+ podman: CONTAINER_QUERIES,
369
+ nerdctl: CONTAINER_QUERIES,
370
+ // https://kubernetes.io/docs/reference/kubectl/: reading resources only; an unknown word runs a `kubectl-*` plugin.
371
+ kubectl: ['get', 'describe', 'logs', 'explain', 'version', 'api-resources', 'api-versions', 'top', 'config view'],
372
+ // https://docs.conda.io/projects/conda/en/stable/commands/index.html
373
+ conda: ['list', 'search', 'info'],
374
+ mamba: ['list', 'search', 'info'],
375
+ micromamba: ['list', 'search', 'info'],
376
+ // Homebrew evaluates a formula's Ruby code (tapping its repository first) to describe it; PDM, Hatch, Rye and
377
+ // pixi run project scripts by name: none takes a value.
378
+ brew: [],
379
+ pdm: [],
380
+ hatch: [],
381
+ rye: [],
382
+ pixi: [],
383
+ // https://manpages.debian.org/apt-cache, /apt: queries of the package lists.
384
+ 'apt-cache': ['show', 'search', 'policy', 'depends', 'rdepends', 'showpkg'],
385
+ apt: ['show', 'search', 'list', 'policy'],
386
+ 'apt-get': [],
387
+ // https://dnf.readthedocs.io/en/latest/command_ref.html
388
+ dnf: ['info', 'list', 'search'],
389
+ yum: ['info', 'list', 'search'],
390
+ // Their queries are options (`pacman -Q`), which no value may follow.
391
+ pacman: [],
392
+ apk: [],
393
+ zypper: [],
394
+ };
395
+ /**
396
+ * The wrappers resolved to the command they run. Any other option, a combined
397
+ * one (`-cl`) or a dynamic word makes the wrapper unresolvable, and an
398
+ * unresolvable wrapper (as every other one in {@link RUNNERS}, `sudo` and the
399
+ * like) counts as a program that reads code and runs packages.
400
+ */
401
+ const WRAPPERS = {
402
+ // https://www.gnu.org/software/bash/manual/bash.html#Bash-Builtins: `command [-pVv] command [arguments]`
403
+ // (`-v`/`-V` only describe, so they are left unresolved), `builtin [shell-builtin [args]]`,
404
+ // `exec [-cl] [-a name] [command [arguments]]`.
405
+ command: { flags: ['-p'], valued: [], builtin: true },
406
+ builtin: { flags: [], valued: [], builtin: true },
407
+ exec: { flags: ['-c', '-l'], valued: ['-a'], builtin: true },
408
+ // https://www.gnu.org/software/coreutils/manual/html_node/env-invocation.html (`-S` splits a string: unresolved).
409
+ env: { flags: ['-', '-i', '--ignore-environment', '-0', '--null', '-v', '--debug'], valued: ['-u', '--unset', '-C', '--chdir', '-a', '--argv0'], assignments: true },
410
+ // https://www.gnu.org/software/coreutils/manual/html_node/nice-invocation.html, /nohup-invocation.html,
411
+ // /timeout-invocation.html and /stdbuf-invocation.html.
412
+ nice: { flags: [], valued: ['-n', '--adjustment'] },
413
+ nohup: { flags: [], valued: [] },
414
+ timeout: { flags: ['--preserve-status', '--foreground', '-v', '--verbose'], valued: ['-s', '--signal', '-k', '--kill-after'], operands: 1 },
415
+ stdbuf: { flags: [], valued: ['-i', '--input', '-o', '--output', '-e', '--error'] },
416
+ // bash's `time [-p]` (https://www.gnu.org/software/bash/manual/bash.html#Pipelines) and GNU time
417
+ // (https://www.gnu.org/software/time/manual/time.html#Invoking-time).
418
+ time: { flags: ['-p', '--portability', '-a', '--append', '-q', '--quiet', '-v', '--verbose'], valued: ['-f', '--format', '-o', '--output'] },
419
+ // util-linux setsid(1): https://man7.org/linux/man-pages/man1/setsid.1.html
420
+ setsid: { flags: ['-c', '--ctty', '-f', '--fork', '-w', '--wait'], valued: [] },
421
+ };
422
+ /** `sed` and `awk`: the program is an argument; it comes from a stream only through `-f` (`--file`, gawk's `-E`/`--exec`). */
423
+ const PROGRAM_FILE_OPTION = /^(?:-[fE]|--file|--exec)(?:=?(.*))?$/u;
424
+ /** A path that names standard input, or a process substitution. */
425
+ const STDIN_PATH = /^(?:-|\/dev\/stdin|\/dev\/fd\/0|\/proc\/self\/fd\/0|<\()$/u;
426
+ /** PowerShell runners whose script block is fixed and whose pipeline input is data. */
427
+ const POWERSHELL_PIPELINE_BLOCKS = new Set(['foreach-object', 'where-object']);
428
+ /** PowerShell cmdlets that run, load or define code they are given; an alias is read as its cmdlet (see `programName`). */
429
+ const POWERSHELL_RUNNERS = new Set(['.', 'invoke-expression', 'invoke-command', 'start-process', 'start-job', 'start-threadjob', 'invoke-item', 'add-type', 'new-module', 'import-module', 'foreach-object', 'where-object', 'set-variable', 'new-variable', 'set-item', 'new-item', 'invoke-history']);
217
430
  /** A `test` / `[` operator whose operand stays a plain string or file name (not `-v`, `-a`, `-o`, `!`). */
218
431
  const TEST_OPERATOR = /^(?:-[bcdefghknprsStuwxzGLNO]|-(?:eq|ne|lt|le|gt|ge|nt|ot|ef)|==?|!=)$/u;
219
432
  /** A line that defines a function or alias, whose body may run its arguments. */
220
433
  const DEFINES = { bash: /\bfunction\s|[\w.:-]\s*\(\s*\)|\balias\b/u, powershell: /\b(?:function|filter|workflow)\s|\b(?:set|new)-alias\b|\b(?:sal|nal)\b|\b(?:function|alias):/iu };
434
+ /** Path variables the host sets: never user or model input. */
435
+ const HOST_VARIABLE = /\$\{(?:CLAUDE_SKILL_DIR|CLAUDE_PROJECT_DIR|CLAUDE_PLUGIN_ROOT|CLAUDE_PLUGIN_DATA)\}/gu;
436
+ const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*(?:\[[^\]]*\])?\+?=/u;
437
+ /**
438
+ * A word that stays exactly one word: plain characters and quotes around
439
+ * text that expands nothing, with host path variables anywhere in it. No
440
+ * `$`, glob, brace or splat that could make it vanish or split.
441
+ */
442
+ function fixedWord(word) {
443
+ return /^(?:[\w./:+%=~-]|"[^"$`\\]*"|'[^']*')+$/u.test(word.replace(HOST_VARIABLE, ''));
444
+ }
445
+ /** A word as the shell reads it, without its quotes (and, in bash, its escapes). */
446
+ function unquote(word, kind = 'bash') {
447
+ return word.replace(kind === 'bash' ? /["'\\]/gu : /["'`]/gu, '');
448
+ }
449
+ /** A program's file name as a rule knows it: base name, lower case, no Windows executable extension. */
450
+ function programName(word, kind) {
451
+ const plain = unquote(word, kind);
452
+ // A bare PowerShell name may be an alias: read it as its cmdlet, through every alias PowerShell defines anywhere.
453
+ if (kind === 'powershell' && /^[^/\\.]+$/u.test(plain))
454
+ return powershellCommand(plain, 'all');
455
+ return basename(kind === 'powershell' ? plain.replace(/\\/gu, '/') : plain).toLowerCase().replace(/\.(?:exe|cmd|bat|com)$/u, '');
456
+ }
457
+ const NO_OPTIONS = { options: [] };
458
+ const INTERPRETERS = {
459
+ // https://nodejs.org/api/cli.html#synopsis: `node [options] [V8 options] [<program-entry-point> | -e "script" | -] [--] [arguments]`;
460
+ // `node inspect …` starts the debugger. The options listed take no value and load no code.
461
+ node: { options: ['--no-warnings', '--no-deprecation', '--enable-source-maps', '--trace-warnings', '--trace-uncaught'], notScript: ['inspect'] },
462
+ // https://docs.python.org/3/using/cmdline.html#interface-options: the script "terminates the list of options consumed by the
463
+ // interpreter, all consecutive arguments will end up in sys.argv". The options listed take no value; PyPy takes CPython's.
464
+ python: { options: ['-B', '-E', '-I', '-P', '-q', '-s', '-S', '-u'] },
465
+ // https://www.gnu.org/software/bash/manual/bash.html#Invoking-Bash, https://pubs.opengroup.org/onlinepubs/9799919799/utilities/sh.html
466
+ // and https://zsh.sourceforge.io/Doc/Release/Invocation.html: the first argument after the options names the script and the
467
+ // rest become its positional parameters. No options: `-s`, `-c`, `-i`, `-o` and the like change what runs.
468
+ bash: NO_OPTIONS,
469
+ sh: NO_OPTIONS,
470
+ zsh: NO_OPTIONS,
471
+ // https://perldoc.perl.org/perlrun#SYNOPSIS and https://docs.ruby-lang.org/en/master/ruby/options_md.html: the words after the
472
+ // program file are its @ARGV / ARGV. No options, so `-s` (which reads them as switches) cannot occur.
473
+ perl: NO_OPTIONS,
474
+ ruby: NO_OPTIONS,
475
+ };
221
476
  /**
222
- * Whether a value may stand in the word being read after `words` (the words
223
- * of the current simple command so far): only as an argument of a command
224
- * named by a plain word, not as the command itself or an assignment, and not
225
- * of a builtin or program that runs, evaluates or names what it is given.
477
+ * Every interpreter, script host and shell, by root name, and the family it
478
+ * belongs to. Only the families in {@link INTERPRETERS} take a value, in their
479
+ * verified form; every other family takes none anywhere on its line (`java`
480
+ * runs the class or `-jar` it is given, the rest run code or files likewise).
226
481
  */
227
- function argumentOf(words, kind) {
228
- const at = words.findIndex(word => kind === 'powershell' || !/^[A-Za-z_][A-Za-z0-9_]*(?:\[[^\]]*\])?\+?=/u.test(word));
482
+ const FAMILIES = {
483
+ python: 'python', py: 'python', pypy: 'python',
484
+ node: 'node', nodejs: 'node', bun: 'bun', deno: 'deno',
485
+ perl: 'perl', ruby: 'ruby', irb: 'irb',
486
+ php: 'php', lua: 'lua', luajit: 'luajit', rscript: 'r', r: 'r', osascript: 'osascript', tclsh: 'tclsh', wish: 'wish',
487
+ jshell: 'jshell', jrunscript: 'jrunscript', groovy: 'groovy', java: 'java',
488
+ awk: 'awk', gawk: 'awk', mawk: 'awk', nawk: 'awk',
489
+ bash: 'bash', sh: 'sh', zsh: 'zsh', dash: 'dash', ksh: 'ksh', mksh: 'mksh', fish: 'fish', csh: 'csh', tcsh: 'tcsh', ash: 'ash', busybox: 'busybox',
490
+ pwsh: 'pwsh', powershell: 'powershell', cmd: 'cmd', wscript: 'wscript', cscript: 'cscript', mshta: 'mshta',
491
+ // Windows programs that start a shell or run the command, file or library they are given.
492
+ wsl: 'wsl', wt: 'wt', runas: 'runas', rundll32: 'rundll32', regsvr32: 'regsvr32', forfiles: 'forfiles', msiexec: 'msiexec',
493
+ };
494
+ /** Families with a Windows GUI variant named with a trailing `w` (`pythonw`, `pyw`, `javaw`, `rubyw`). */
495
+ const GUI_VARIANTS = new Set(['python', 'java', 'ruby']);
496
+ /** Roots long enough to recognise by prefix and a version (`python3-dbg`, `luajit-2.1`); shorter ones (`r`, `py`, `sh`) only exactly or with a version. */
497
+ const PREFIX_ROOTS = Object.keys(FAMILIES).filter(root => root.length >= 4).sort((left, right) => right.length - left.length);
498
+ /** bash's `source file [arguments]` and `. file [arguments]` (https://www.gnu.org/software/bash/manual/bash.html#Bourne-Shell-Builtins). */
499
+ const SOURCE = NO_OPTIONS;
500
+ /** `python3.12` → `python`, `bash-5` → `bash`: a name without trailing digits, dots and dashes. */
501
+ function withoutVersion(name) {
502
+ let end = name.length;
503
+ while (end > 0 && /[\d.-]/u.test(name[end - 1] ?? ''))
504
+ end--;
505
+ return name.slice(0, end);
506
+ }
507
+ /**
508
+ * The interpreter, script host or shell family a program's file name (see
509
+ * `programName`) stands for, however it is spelled: a root exactly, with a
510
+ * version (`python3.12`, `bash5`, `r4.3`), a longer root followed by a version
511
+ * and more (`python3-dbg`), or a GUI variant (`pythonw`, `python3.12w`, `pyw`).
512
+ */
513
+ function programFamily(name) {
514
+ const plain = (candidate) => {
515
+ const bare = withoutVersion(candidate);
516
+ if (Object.hasOwn(FAMILIES, candidate))
517
+ return FAMILIES[candidate];
518
+ if (bare !== candidate && Object.hasOwn(FAMILIES, bare))
519
+ return FAMILIES[bare];
520
+ const root = PREFIX_ROOTS.find(prefix => candidate.startsWith(prefix) && /[\d._-]/u.test(candidate[prefix.length] ?? ''));
521
+ return root === undefined ? undefined : FAMILIES[root];
522
+ };
523
+ const family = plain(name);
524
+ if (family !== undefined || !name.endsWith('w'))
525
+ return family;
526
+ const gui = plain(name.slice(0, -1));
527
+ return gui !== undefined && GUI_VARIANTS.has(gui) ? gui : undefined;
528
+ }
529
+ /**
530
+ * Whether a value may stand in the word `current` after `words[from…]`, the
531
+ * arguments of an interpreter: only after the script, a fixed word (which may
532
+ * hold a host path variable) after none but the allowed options. A host path
533
+ * variable may also stand in the script itself.
534
+ */
535
+ function interpreterAllows(spec, words, from, current, host, kind) {
536
+ let index = from;
537
+ for (; index < words.length; index++) {
538
+ const word = words[index] ?? '';
539
+ if (!fixedWord(word))
540
+ return false;
541
+ const plain = unquote(word, kind);
542
+ if (!/^[-+]/u.test(plain))
543
+ break;
544
+ if (!spec.options.includes(plain))
545
+ return false;
546
+ }
547
+ if (index < words.length) {
548
+ const script = unquote(words[index] ?? '', kind);
549
+ return script.length > 0 && spec.notScript?.includes(script) !== true;
550
+ }
551
+ // The value would stand in the script (or in an option before it): only a host path may.
552
+ return host && !/^[-+]/u.test(unquote(current, kind));
553
+ }
554
+ function isRunner(command) {
555
+ return RUNNERS.has(command) || RUNNERS.has(withoutVersion(command));
556
+ }
557
+ /** The {@link PACKAGE_MANAGERS} entry of a program's file name (`pip3.12` is `pip`), if it is one. */
558
+ function packageManager(command) {
559
+ if (Object.hasOwn(PACKAGE_MANAGERS, command))
560
+ return PACKAGE_MANAGERS[command];
561
+ const bare = withoutVersion(command);
562
+ return Object.hasOwn(PACKAGE_MANAGERS, bare) ? PACKAGE_MANAGERS[bare] : undefined;
563
+ }
564
+ /**
565
+ * How many words after the package manager at `words[at]` make up an allowed
566
+ * subcommand: fixed words right after the program, exactly as listed.
567
+ * Undefined when they make up none (a subcommand that runs code, a missing or
568
+ * dynamic one, or an option first).
569
+ */
570
+ function allowedSubcommand(allowed, words, at, kind) {
571
+ const matches = (path) => path.every((part, index) => {
572
+ const word = words[at + 1 + index];
573
+ return word !== undefined && fixedWord(word) && unquote(word, kind) === part;
574
+ });
575
+ return allowed.map(path => path.split(' ')).find(matches)?.length;
576
+ }
577
+ /**
578
+ * Where a value may stand on a package manager's line: only after an allowed
579
+ * subcommand, as an operand. Unless a `--` before it ends the options, the
580
+ * word must not start as an option (`--pkg=$1`) nor follow one (`--userconfig
581
+ * "$1"`, `--python "$1"`: options that choose a configuration, interpreter or
582
+ * credential program), and when the value starts the word it must not start
583
+ * with `-` itself, which only the value knows (`operand`).
584
+ */
585
+ function packageOperand(allowed, words, at, current, kind) {
586
+ const length = allowedSubcommand(allowed, words, at, kind);
587
+ const operands = at + 1 + (length ?? 0);
588
+ if (length === undefined || words.length < operands)
589
+ return 'refused';
590
+ if (words.slice(operands).some(word => unquote(word, kind) === '--'))
591
+ return 'argument';
592
+ const before = unquote(current, kind);
593
+ if (before.startsWith('-'))
594
+ return 'refused';
595
+ if (words.length > operands && unquote(words.at(-1) ?? '', kind).startsWith('-'))
596
+ return 'refused';
597
+ return before === '' ? 'operand' : 'argument';
598
+ }
599
+ /** The index of a simple command's program in its words, after assignments (bash) or the call operator (PowerShell). */
600
+ function programAt(words, kind) {
601
+ let at = kind === 'powershell' && words[0] === '&' ? 1 : 0;
602
+ while (kind === 'bash' && at < words.length && ASSIGNMENT.test(words[at] ?? ''))
603
+ at++;
604
+ return at;
605
+ }
606
+ /** Where the command a {@link WRAPPERS} wrapper at `words[at]` runs starts, or undefined when its words cannot be read. */
607
+ function afterWrapper(wrapper, words, at, kind) {
608
+ let index = at + 1;
609
+ for (; index < words.length; index++) {
610
+ const word = words[index] ?? '';
611
+ if (!fixedWord(word))
612
+ return undefined;
613
+ const plain = unquote(word, kind);
614
+ if (plain === '--') {
615
+ index++;
616
+ break;
617
+ }
618
+ if (!plain.startsWith('-') || plain === '-' && !wrapper.flags.includes('-'))
619
+ break;
620
+ if (wrapper.flags.includes(plain))
621
+ continue;
622
+ const option = wrapper.valued.find(name => plain === name || plain.startsWith(name.startsWith('--') ? `${name}=` : name));
623
+ if (option === undefined)
624
+ return undefined;
625
+ if (plain === option)
626
+ index++;
627
+ }
628
+ for (let operand = 0; operand < (wrapper.operands ?? 0); operand++, index++) {
629
+ if (!fixedWord(words[index] ?? '$'))
630
+ return undefined;
631
+ }
632
+ while (wrapper.assignments === true && index < words.length && ASSIGNMENT.test(words[index] ?? '')) {
633
+ if (!fixedWord(words[index] ?? ''))
634
+ return undefined;
635
+ index++;
636
+ }
637
+ return index > words.length ? undefined : index;
638
+ }
639
+ /**
640
+ * The index of the program a simple command runs: after assignments, the
641
+ * PowerShell call operator and every {@link WRAPPERS} wrapper (`command sh`,
642
+ * `env X=1 nice -n 5 sh` run `sh`). `words.length` when it runs none
643
+ * (`env` alone); undefined when a wrapper cannot be resolved.
644
+ */
645
+ function commandAt(words, kind) {
646
+ let at = programAt(words, kind);
647
+ while (at !== undefined && at < words.length) {
648
+ const name = words[at] ?? '';
649
+ const program = fixedWord(name) ? programName(name, kind) : '';
650
+ const wrapper = Object.hasOwn(WRAPPERS, program) ? WRAPPERS[program] : undefined;
651
+ if (wrapper === undefined || (wrapper.builtin === true && kind !== 'bash'))
652
+ return at;
653
+ at = afterWrapper(wrapper, words, at, kind);
654
+ }
655
+ return at;
656
+ }
657
+ /**
658
+ * Whether a simple command may run a package manager's code: a package
659
+ * manager outside its allowed subcommands, an unresolvable wrapper, or a
660
+ * program named at run time (which could be either).
661
+ */
662
+ function runsPackageCode(words, kind) {
663
+ const at = commandAt(words, kind);
664
+ if (at === undefined)
665
+ return true;
229
666
  const name = words[at];
230
- if (at === -1 || name === undefined || name.startsWith('-'))
667
+ if (name === undefined)
231
668
  return false;
232
- const args = words.slice(at + 1);
669
+ if (namedAtRunTime(name))
670
+ return true;
671
+ const program = programName(name, kind);
672
+ if (WRAPPING_RUNNERS.has(program))
673
+ return true;
674
+ const allowed = packageManager(program);
675
+ return allowed !== undefined && allowedSubcommand(allowed, words, at, kind) === undefined;
676
+ }
677
+ /** Whether a program word expands at run time (`$TOOL`, `` `which npm` ``), so that it could name any program. */
678
+ function namedAtRunTime(word) {
679
+ return /[$`]/u.test(word.replace(HOST_VARIABLE, ''));
680
+ }
681
+ /**
682
+ * Whether a simple command may read code from a stream (a pipe, standard
683
+ * input, a process substitution): an interpreter or shell not in its verified
684
+ * fixed-script form (see `interpreterAllows`), `source`/`.`, `sed`/`awk` with a
685
+ * program file that is a stream, any other runner (which may start one), a
686
+ * package manager outside its allowed subcommands, and PowerShell's runners
687
+ * but `ForEach-Object`/`Where-Object`. The program is the one wrappers run
688
+ * (see `commandAt`); an unresolvable wrapper or a dynamic program counts.
689
+ */
690
+ function readsCode(words, kind) {
691
+ const at = commandAt(words, kind);
692
+ // A wrapper that cannot be resolved, or a program named at run time, may be anything.
693
+ if (at === undefined)
694
+ return true;
695
+ const name = words[at];
696
+ if (name === undefined)
697
+ return false;
698
+ if (namedAtRunTime(name))
699
+ return true;
700
+ const command = programName(name, kind);
701
+ const fixedScript = (spec) => fixedWord(name) && interpreterAllows(spec, words, at + 1, '', false, kind)
702
+ && !words.slice(at + 1).some(word => STDIN_PATH.test(unquote(word, kind)));
703
+ if (kind === 'bash' && (name === '.' || name === 'source'))
704
+ return !fixedScript(SOURCE);
705
+ if (command === 'sed' || programFamily(command) === 'awk') {
706
+ return words.some((word, index) => {
707
+ const option = PROGRAM_FILE_OPTION.exec(unquote(word, kind));
708
+ if (option === null)
709
+ return false;
710
+ const attached = option[1] !== undefined && option[1] !== '';
711
+ const file = attached ? word : words[index + 1] ?? '-';
712
+ return !fixedWord(file) || STDIN_PATH.test(attached ? option[1] ?? '' : unquote(file, kind));
713
+ });
714
+ }
715
+ const family = programFamily(command);
716
+ if (family !== undefined) {
717
+ const interpreter = INTERPRETERS[family];
718
+ return interpreter === undefined || !fixedScript(interpreter);
719
+ }
720
+ if (isRunner(command) || runsPackageCode(words.slice(at), kind))
721
+ return true;
722
+ return kind === 'powershell' && POWERSHELL_RUNNERS.has(command) && !POWERSHELL_PIPELINE_BLOCKS.has(command);
723
+ }
724
+ /**
725
+ * Whether a value may stand in the word `current` being read after `words`
726
+ * (the words of the current simple command so far): only as an argument of a
727
+ * command named by a plain word, not as the command itself or an assignment,
728
+ * and not of a builtin or program that runs, evaluates or names what it is
729
+ * given; for a script interpreter, only after its script (see
730
+ * `interpreterAllows`); for a package manager, only as an operand of an
731
+ * allowed subcommand (see `packageOperand`). A host path variable (`host`) may
732
+ * also name the command, or an interpreter's script.
733
+ */
734
+ function argumentOf(words, current, kind, host) {
735
+ const placement = argumentPlacement(words, current, kind, host);
736
+ return typeof placement === 'string' ? placement : placement ? 'argument' : 'refused';
737
+ }
738
+ function argumentPlacement(words, current, kind, host) {
739
+ // PowerShell runs a command named by a string through the call operator `&`.
740
+ const call = kind === 'powershell' && words[0] === '&' ? 1 : 0;
741
+ let at = call;
742
+ while (kind === 'bash' && at < words.length && ASSIGNMENT.test(words[at] ?? ''))
743
+ at++;
744
+ const name = words[at];
745
+ if (name === undefined)
746
+ return host && (kind === 'bash' ? !ASSIGNMENT.test(current) : call === 1);
747
+ if (name.startsWith('-'))
748
+ return false;
749
+ const hostName = fixedWord(name) && name.replace(HOST_VARIABLE, '') !== name;
750
+ const command = programName(name, kind);
751
+ if (kind === 'bash' && (name === '.' || name === 'source'))
752
+ return interpreterAllows(SOURCE, words, at + 1, current, host, kind);
753
+ // An interpreter, script host or shell, however spelled: only a verified form takes a value; nothing falls back to the rules below.
754
+ const family = programFamily(command);
755
+ if (family !== undefined) {
756
+ const interpreter = INTERPRETERS[family];
757
+ return interpreter !== undefined && fixedWord(name) && interpreterAllows(interpreter, words, at + 1, current, host, kind);
758
+ }
759
+ if (isRunner(command))
760
+ return false;
761
+ const allowed = packageManager(command);
762
+ if (allowed !== undefined)
763
+ return packageOperand(allowed, words, at, current, kind);
233
764
  if (kind === 'powershell') {
234
- const command = basename(name.replace(/\\/gu, '/')).toLowerCase().replace(/\.exe$/u, '');
235
- return /^[\w./\\:+@,-]+$/u.test(name) && !POWERSHELL_RUNNERS.has(command) && !RUNNERS.has(command)
236
- && !args.some(arg => /^-(?:c|command|e|ec|encodedcommand|sb|scriptblock|cwa|commandwithargs)$/iu.test(arg));
765
+ return (/^[\w./\\:+@,-]+$/u.test(name) || hostName) && !POWERSHELL_RUNNERS.has(command)
766
+ && !words.some((arg, index) => index > at && /^-(?:c|command|e|ec|encodedcommand|sb|scriptblock|cwa|commandwithargs)$/iu.test(arg));
237
767
  }
238
- if (!/^[\w./:+@,-]+$|^\[$/u.test(name))
768
+ if (!/^[\w./:+@,-]+$|^\[$/u.test(name) && !hostName)
239
769
  return false;
240
- const command = basename(name);
241
- if (RUNNERS.has(command) || (command === 'find' && args.some(arg => /^-(?:exec|execdir|ok|okdir)$/u.test(arg))))
770
+ if ((command === 'find' && words.some((arg, index) => index > at && /^-(?:exec|execdir|ok|okdir)$/u.test(arg))))
242
771
  return false;
243
772
  if (!BASH_BUILTINS.has(name))
244
773
  return true;
@@ -251,12 +780,148 @@ function argumentOf(words, kind) {
251
780
  case 'false':
252
781
  case ':': return true;
253
782
  // `printf -v NAME` evaluates NAME; so would a value standing as the format.
254
- case 'printf': return args.length > 0 && !args.includes('-v');
783
+ case 'printf': return words.length > at + 1 && !words.slice(at + 1).includes('-v');
255
784
  case 'test':
256
- case '[': return TEST_OPERATOR.test(args.at(-1) ?? '');
785
+ case '[': return words.length > at + 1 && TEST_OPERATOR.test(words.at(-1) ?? '');
257
786
  default: return false;
258
787
  }
259
788
  }
789
+ /** Whether any argument may match `option` once unquoted: a dynamic argument may be anything, so it may. */
790
+ function anyArgument(args, option, kind) {
791
+ return args.some(arg => !fixedWord(arg) || option.test(unquote(arg, kind)));
792
+ }
793
+ /**
794
+ * Programs known to write files, by file name, with the arguments that make
795
+ * them write (a dynamic argument counts, since it could be one). Ordinary
796
+ * programs may write files in ways this list does not know: a documented
797
+ * residual. Output redirections are found separately (see `writesFile`).
798
+ */
799
+ const FILE_WRITERS = {
800
+ // Their purpose is to write or link a file they are given.
801
+ tee: () => true, cp: () => true, mv: () => true, ln: () => true, install: () => true, rsync: () => true, unzip: () => true, patch: () => true,
802
+ // wget saves what it fetches unless told to print it; any form counts.
803
+ wget: () => true,
804
+ // `dd of=FILE`; `sed -i`/`--in-place` and `perl -i` (also in a cluster such as `-pi`) edit in place.
805
+ dd: (args, kind) => anyArgument(args, /^of=/u, kind),
806
+ sed: (args, kind) => anyArgument(args, /^(?:-[^-]*i|--in-place)/u, kind),
807
+ perl: (args, kind) => anyArgument(args, /^-[^-]*i/u, kind),
808
+ // `curl -o FILE`, `-O` (the remote name), also in a cluster (`-sSLo`).
809
+ curl: (args, kind) => anyArgument(args, /^(?:-[^-]*[oO]|--output|--remote-name)/u, kind),
810
+ // `tar -x`/`x…` (the first argument may be the bare option cluster), `--extract`, `--get`.
811
+ tar: (args, kind) => anyArgument(args.slice(0, 1), /^-?[A-Za-z]*x/u, kind) || anyArgument(args, /^(?:-[^-]*x|--extract|--get)/u, kind),
812
+ // PowerShell's writers and their aliases (https://learn.microsoft.com/powershell/module/microsoft.powershell.management/,
813
+ // /microsoft.powershell.utility/ and /bitstransfer/): content and output cmdlets, copying, moving and renaming
814
+ // (a written file renamed to a script), creating an item (`New-Item -Value`), archives, downloads and exports.
815
+ // Aliases (`sc`, `cpi`, `mi`, `iwr` …) are read as these cmdlets (see `programName`).
816
+ 'tee-object': () => true, 'out-file': () => true, 'set-content': () => true, 'add-content': () => true,
817
+ 'copy-item': () => true, 'move-item': () => true, 'rename-item': () => true, 'new-item': () => true,
818
+ 'expand-archive': () => true, 'invoke-webrequest': () => true, 'start-bitstransfer': () => true,
819
+ 'invoke-restmethod': (args, kind) => anyArgument(args, /^-outf/iu, kind),
820
+ 'export-csv': () => true, 'export-clixml': () => true, 'export-alias': () => true,
821
+ 'export-formatdata': () => true, 'export-pssession': () => true, 'export-console': () => true, 'export-binarymilog': () => true,
822
+ };
823
+ /**
824
+ * Whether a simple command may write a file: an output redirection to a file
825
+ * (not the shell's null device or a descriptor copy), a {@link FILE_WRITERS} program, an
826
+ * unresolvable wrapper or a program named at run time.
827
+ */
828
+ function writesFile(words, kind) {
829
+ const redirected = redirectFiles(words.join(' '), kind);
830
+ if (redirected === undefined || redirected.some(file => file.writes))
831
+ return true;
832
+ const at = commandAt(words, kind);
833
+ if (at === undefined)
834
+ return true;
835
+ const name = words[at];
836
+ if (name === undefined)
837
+ return false;
838
+ if (namedAtRunTime(name))
839
+ return true;
840
+ const program = programName(name, kind);
841
+ return Object.hasOwn(FILE_WRITERS, program) && FILE_WRITERS[program](words.slice(at + 1), kind);
842
+ }
843
+ /** A command or process substitution, whose commands are not classified one by one: it may run anything. */
844
+ const SUBSTITUTION = /\$\(|`|^[<>]\(/u;
845
+ /**
846
+ * Whether a simple command may run code from a file: an interpreter, script
847
+ * host or shell, `source`/`.`/`eval`, a program named by a path (`./x`,
848
+ * `dir/x`) or at run time, any runner, `find … -exec`, a PowerShell runner, a
849
+ * command or process substitution, or an unresolvable wrapper.
850
+ */
851
+ function executesFile(words, kind) {
852
+ if (words.some(word => SUBSTITUTION.test(word)))
853
+ return true;
854
+ const at = commandAt(words, kind);
855
+ if (at === undefined)
856
+ return true;
857
+ const name = words[at];
858
+ if (name === undefined)
859
+ return false;
860
+ if (namedAtRunTime(name))
861
+ return true;
862
+ const plain = unquote(name, kind);
863
+ if (['.', 'source', 'eval'].includes(plain) || /[/\\]/u.test(plain))
864
+ return true;
865
+ const command = programName(name, kind);
866
+ if (programFamily(command) !== undefined || isRunner(command))
867
+ return true;
868
+ if (command === 'find' && words.some((arg, index) => index > at && /^-(?:exec|execdir|ok|okdir)$/u.test(arg)))
869
+ return true;
870
+ return kind === 'powershell' && POWERSHELL_RUNNERS.has(command);
871
+ }
872
+ /**
873
+ * Whether a command that runs a file comes after one that writes a file, in
874
+ * the order the steps are given: later, inside a common pipeline, loop,
875
+ * conditional, subshell or group, or concurrently with it (in the background).
876
+ * A value written there could then run as code.
877
+ */
878
+ export function writesThenRuns(steps) {
879
+ // One pass, indexing what each check needs: the first writer, how many write, and per group who writes and runs.
880
+ let firstWriter;
881
+ let writers = 0;
882
+ const backgroundRunners = [];
883
+ const groups = new Map();
884
+ for (const [at, step] of steps.entries()) {
885
+ const writes = step.writes;
886
+ const executes = step.executes;
887
+ if (writes) {
888
+ firstWriter ??= at;
889
+ writers++;
890
+ }
891
+ if (executes) {
892
+ // Later than a write by another step.
893
+ if (firstWriter !== undefined && firstWriter < at)
894
+ return true;
895
+ if (step.background)
896
+ backgroundRunners.push(writes);
897
+ }
898
+ if (!writes && !executes)
899
+ continue;
900
+ for (const group of step.groups) {
901
+ const tally = groups.get(group) ?? { writers: 0, runners: 0, both: 0 };
902
+ if (writes)
903
+ tally.writers++;
904
+ if (executes)
905
+ tally.runners++;
906
+ if (writes && executes)
907
+ tally.both++;
908
+ groups.set(group, tally);
909
+ }
910
+ }
911
+ // In the background, concurrently with another step's write.
912
+ if (backgroundRunners.some(alsoWrites => writers > (alsoWrites ? 1 : 0)))
913
+ return true;
914
+ // In a common group with another step's write: unless the only writer is the only runner.
915
+ for (const tally of groups.values()) {
916
+ if (tally.writers > 0 && tally.runners > 0 && !(tally.writers === 1 && tally.runners === 1 && tally.both === 1))
917
+ return true;
918
+ }
919
+ return false;
920
+ }
921
+ /** bash keywords that open a construct whose commands run in an order not known statically, and the one closing each. */
922
+ const BASH_CONSTRUCTS = { while: 'done', until: 'done', for: 'done', select: 'done', if: 'fi', case: 'esac', '{': '}' };
923
+ /** PowerShell loop keywords: a text with one has its commands in no static order. */
924
+ const POWERSHELL_LOOPS = /^(?:while|for|foreach|do|until)$/iu;
260
925
  /**
261
926
  * A shell line with each placeholder replaced by a reference to an
262
927
  * environment variable holding its value. Values never enter the source: a
@@ -276,6 +941,7 @@ export function shellCommand(command, kind, value) {
276
941
  const single = kind === 'powershell' ? /['\u2018\u2019\u201A\u201B]/u : /'/u;
277
942
  const double = kind === 'powershell' ? /["\u201C\u201D\u201E]/u : /"/u;
278
943
  const escape = kind === 'bash' ? '\\' : '`';
944
+ const defines = DEFINES[kind].test(command);
279
945
  let out = '';
280
946
  let index = 0;
281
947
  const take = (count) => {
@@ -287,20 +953,84 @@ export function shellCommand(command, kind, value) {
287
953
  // The words of the current simple command, read at the top level only.
288
954
  let words = [];
289
955
  let wordAt;
956
+ // Open constructs whose commands run in no static order (see `ShellStep`), innermost last, and the word or
957
+ // character that closes each; a counter names them.
958
+ const constructs = [];
959
+ let constructCount = 0;
960
+ const open = (close) => {
961
+ constructs.push({ id: `c${String(constructCount++)}`, close });
962
+ };
963
+ const close = (closer) => {
964
+ const at = constructs.map(construct => construct.close).lastIndexOf(closer);
965
+ if (at !== -1)
966
+ constructs.splice(at);
967
+ };
968
+ let loops = false;
290
969
  const endWord = () => {
291
970
  if (wordAt === undefined)
292
971
  return;
293
972
  const word = command.slice(wordAt, index);
973
+ if (words.length === 0 && kind === 'bash') {
974
+ if (Object.hasOwn(BASH_CONSTRUCTS, word))
975
+ open(BASH_CONSTRUCTS[word]);
976
+ else if (Object.values(BASH_CONSTRUCTS).includes(word))
977
+ close(word);
978
+ }
979
+ if (words.length === 0 && kind === 'powershell' && POWERSHELL_LOOPS.test(word))
980
+ loops = true;
294
981
  if (!(kind === 'bash' && words.length === 0 && BASH_PREFIXES.has(word)))
295
982
  words.push(word);
296
983
  wordAt = undefined;
297
984
  };
985
+ // Every simple command of the line, and whether anything on it feeds a program through a stream: a pipe, a
986
+ // process substitution or an input redirection. A value anywhere on such a line may reach that program.
987
+ const lineCommands = [];
988
+ // Each simple command with the constructs it stands in, for the write-then-run check; pipelines are numbered.
989
+ const steps = [];
990
+ let pipeline = 0;
991
+ const backgrounded = new Set();
992
+ let streams = false;
993
+ let valued = false;
994
+ // A value someone chose (an argument), not a path the host sets: what a written file could carry into code.
995
+ let chosen = false;
996
+ const operands = [];
997
+ const endCommand = (char, next) => {
998
+ endWord();
999
+ const previous = command[index - 1] ?? '';
1000
+ // `<(…)` and `>(…)`: the `<` or `>` before the parenthesis was read as a word; mark it as a process substitution.
1001
+ if (kind === 'bash' && char === '(' && (previous === '<' || previous === '>')) {
1002
+ if (words.at(-1) === previous)
1003
+ words[words.length - 1] = `${previous}(`;
1004
+ streams = true;
1005
+ }
1006
+ const pipe = (char === '|' && next !== '|' && previous !== '|') || (char === '&' && previous === '|');
1007
+ if (pipe)
1008
+ streams = true;
1009
+ if (words.some(word => /^\d*<(?!<)/u.test(word)))
1010
+ streams = true;
1011
+ lineCommands.push(words);
1012
+ // A lone `&` after a command (not `&&`, `|&` or part of a redirection) runs the pipeline before it in the
1013
+ // background: bash's job control and PowerShell 7's background operator alike.
1014
+ const background = char === '&' && next !== '&' && previous !== '&' && previous !== '|';
1015
+ steps.push({ words, groups: [`p${String(pipeline)}`, ...constructs.slice(0, 1).map(construct => construct.id)], pipeline });
1016
+ if (background)
1017
+ backgrounded.add(pipeline);
1018
+ if (!pipe)
1019
+ pipeline++;
1020
+ if (char === '(' || (kind === 'powershell' && char === '{'))
1021
+ open(char === '(' ? ')' : '}');
1022
+ else if (char === ')' || (kind === 'powershell' && char === '}'))
1023
+ close(char);
1024
+ words = [];
1025
+ };
298
1026
  const separates = (char, next) => {
299
1027
  const previous = command[index - 1] ?? '';
300
1028
  if (/[\n;()]/u.test(char))
301
1029
  return true;
1030
+ // PowerShell: `&` before a command is the call operator; after one (something already read), PowerShell 7's
1031
+ // background operator (https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_operators#background-operator-).
302
1032
  if (kind === 'powershell')
303
- return /[{}|]/u.test(char) || (char === '&' && (next === '&' || previous === '&'));
1033
+ return /[{}|]/u.test(char) || (char === '&' && (next === '&' || previous === '&' || powershellAmpersand(previous, next, words.length > 0 || wordAt !== undefined) === 'background'));
304
1034
  return (char === '|' && previous !== '>') || (char === '&' && !/[<>]/u.test(previous) && next !== '>');
305
1035
  };
306
1036
  while (index < command.length) {
@@ -321,10 +1051,8 @@ export function shellCommand(command, kind, value) {
321
1051
  if (stack.length === 0) {
322
1052
  if (/[ \t\r]/u.test(char))
323
1053
  endWord();
324
- else if (separates(char, next)) {
325
- endWord();
326
- words = [];
327
- }
1054
+ else if (separates(char, next))
1055
+ endCommand(char, next);
328
1056
  else
329
1057
  wordAt ??= index;
330
1058
  }
@@ -340,9 +1068,16 @@ export function shellCommand(command, kind, value) {
340
1068
  if (key !== undefined) {
341
1069
  if (frame !== undefined && !(stack.length === 1 && frame.kind === 'dq'))
342
1070
  return { refused: `an argument or path variable stands inside ${WHERE[frame.kind]}` };
343
- if (!argumentOf(words, kind) || DEFINES[kind].test(command))
1071
+ const host = match[1] !== undefined && match[1] !== 'CLAUDE_SESSION_ID';
1072
+ const placement = argumentOf(words, wordAt === undefined ? '' : command.slice(wordAt, index), kind, host);
1073
+ if (placement === 'refused' || defines)
344
1074
  return { refused: 'an argument or path variable stands where it is not plainly an argument of a command' };
1075
+ if (placement === 'operand')
1076
+ operands.push(key);
345
1077
  out += kind === 'powershell' ? `\${env:${key}}` : frame === undefined ? `"\${${key}}"` : `\${${key}}`;
1078
+ valued = true;
1079
+ if (!host)
1080
+ chosen = true;
346
1081
  index += match[0].length;
347
1082
  continue;
348
1083
  }
@@ -472,7 +1207,7 @@ export function shellCommand(command, kind, value) {
472
1207
  take(2);
473
1208
  continue;
474
1209
  }
475
- else if (kind === 'bash' && /(?:^|[;&|(\n])[ \t]*$/u.test(command.slice(0, index)) && /^let\b/u.test(command.slice(index))) {
1210
+ else if (kind === 'bash' && command.startsWith('let', index) && !/\w/u.test(command[index + 3] ?? '') && commandStart(command, index)) {
476
1211
  // `let` evaluates its arguments as arithmetic, to the end of the command (undefined: the end of the line).
477
1212
  const end = /[;&|\n]/u.exec(command.slice(index))?.[0];
478
1213
  stack.push({ kind: 'arith', ...(end !== undefined ? { end } : {}) });
@@ -498,7 +1233,31 @@ export function shellCommand(command, kind, value) {
498
1233
  }
499
1234
  take(1);
500
1235
  }
501
- return { command: out };
1236
+ endCommand('', '');
1237
+ if (valued && streams && lineCommands.some(words => readsCode(words, kind))) {
1238
+ return { refused: 'an argument or path variable is on a line where a program reads code from a pipe or a process substitution' };
1239
+ }
1240
+ if (valued && lineCommands.some(words => runsPackageCode(words, kind))) {
1241
+ return { refused: 'an argument or path variable is on a line where a package manager may run package or project code' };
1242
+ }
1243
+ const classified = steps.filter(step => step.words.length > 0).map(step => ({
1244
+ writes: writesFile(step.words, kind),
1245
+ executes: executesFile(step.words, kind),
1246
+ groups: loops ? ['loop', ...step.groups] : step.groups,
1247
+ background: backgrounded.has(step.pipeline),
1248
+ }));
1249
+ if (chosen && writesThenRuns(classified))
1250
+ return { refused: WRITE_THEN_RUN };
1251
+ return { command: out, operands, steps: classified, chosen };
1252
+ }
1253
+ /** Why a value is refused where a file written earlier may run (a shell line, or every shell line of a body). */
1254
+ const WRITE_THEN_RUN = 'a value could reach code through a file written earlier in this command';
1255
+ /** Whether only blanks stand between `index` and the start of a command (the line start or `;`, `&`, `|`, `(`). */
1256
+ function commandStart(command, index) {
1257
+ let at = index;
1258
+ while (at > 0 && (command[at - 1] === ' ' || command[at - 1] === '\t'))
1259
+ at--;
1260
+ return at === 0 || ';&|(\n'.includes(command[at - 1] ?? '');
502
1261
  }
503
1262
  async function execute(command, kind, values, context) {
504
1263
  const result = await context.shell.runShell(command, kind, {
@@ -524,7 +1283,7 @@ async function execute(command, kind, values, context) {
524
1283
  function fileReferences(text, context) {
525
1284
  const found = [];
526
1285
  for (const match of text.matchAll(/(?:^|\s)@([^\s`'"()<>]+)/gmu)) {
527
- const raw = (match[1] ?? '').replace(/[.,;:]+$/u, '');
1286
+ const raw = stripTrailing(match[1] ?? '', '.,;:');
528
1287
  if (!/[/\\.]/u.test(raw))
529
1288
  continue;
530
1289
  let fromArgument = false;
@@ -556,6 +1315,12 @@ function attach(references, context) {
556
1315
  const seen = new Set();
557
1316
  for (const reference of references) {
558
1317
  const path = reference.startsWith('~/') ? join(home, reference.slice(2)) : isAbsolute(reference) ? reference : resolve(context.cwd, reference);
1318
+ // On a network share the workspace is not on, or through a link to one: refused untouched, since on Windows
1319
+ // even a stat signs in to that server.
1320
+ if (reachesNewShare(reference, context.cwd) || linksReachNewShare(path, context.cwd)) {
1321
+ refused.push(reference);
1322
+ continue;
1323
+ }
559
1324
  let stat;
560
1325
  try {
561
1326
  stat = statSync(path);