@kirkchinese/harness-forge 0.0.0-stage → 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.
- package/LICENSE +21 -0
- package/README.md +46 -2
- package/assets/icon.svg +12 -0
- package/cordis.patch.yml +28 -0
- package/docs/DETAIL.zh.md +47 -0
- package/lib/agents/presets.d.ts +98 -0
- package/lib/agents/presets.js +292 -0
- package/lib/agents/profiles.d.ts +58 -0
- package/lib/agents/profiles.js +279 -0
- package/lib/agents/row.d.ts +17 -0
- package/lib/agents/row.js +148 -0
- package/lib/client/paths.d.ts +12 -0
- package/lib/client/paths.js +68 -0
- package/lib/client/styles.d.ts +8 -0
- package/lib/client/styles.js +89 -0
- package/lib/client/typert.d.ts +25 -0
- package/lib/client/typert.js +158 -0
- package/lib/client.js +23823 -0
- package/lib/commands/definition.d.ts +40 -0
- package/lib/commands/definition.js +113 -0
- package/lib/commands/output-styles.d.ts +42 -0
- package/lib/commands/output-styles.js +152 -0
- package/lib/commands/row.d.ts +9 -0
- package/lib/commands/row.js +157 -0
- package/lib/context/instructions.d.ts +32 -0
- package/lib/context/instructions.js +88 -0
- package/lib/context/row.d.ts +16 -0
- package/lib/context/row.js +17 -0
- package/lib/dsh/commands.d.ts +30 -0
- package/lib/dsh/commands.js +61 -0
- package/lib/dsh/host.d.ts +110 -0
- package/lib/dsh/host.js +217 -0
- package/lib/dsh/model-route.d.ts +21 -0
- package/lib/dsh/model-route.js +37 -0
- package/lib/dsh/session-records.d.ts +78 -0
- package/lib/dsh/session-records.js +36 -0
- package/lib/dsh/subagents.d.ts +46 -0
- package/lib/dsh/subagents.js +14 -0
- package/lib/forge/contract.d.ts +271 -0
- package/lib/forge/contract.js +45 -0
- package/lib/forge/follow.d.ts +30 -0
- package/lib/forge/follow.js +73 -0
- package/lib/forge/ledger.d.ts +206 -0
- package/lib/forge/ledger.js +1005 -0
- package/lib/forge/live-mounts.d.ts +45 -0
- package/lib/forge/live-mounts.js +78 -0
- package/lib/forge/npm.d.ts +31 -0
- package/lib/forge/npm.js +60 -0
- package/lib/forge/projects.d.ts +97 -0
- package/lib/forge/projects.js +343 -0
- package/lib/forge/receipts.d.ts +5 -0
- package/lib/forge/receipts.js +31 -0
- package/lib/forge/remote/archive.d.ts +65 -0
- package/lib/forge/remote/archive.js +565 -0
- package/lib/forge/remote/code-parts.d.ts +18 -0
- package/lib/forge/remote/code-parts.js +76 -0
- package/lib/forge/remote/fetch.d.ts +265 -0
- package/lib/forge/remote/fetch.js +1133 -0
- package/lib/forge/remote/service.d.ts +256 -0
- package/lib/forge/remote/service.js +868 -0
- package/lib/forge/row.d.ts +32 -0
- package/lib/forge/row.js +59 -0
- package/lib/forge/service.d.ts +115 -0
- package/lib/forge/service.js +290 -0
- package/lib/forge/settings.d.ts +43 -0
- package/lib/forge/settings.js +122 -0
- package/lib/forge/state.d.ts +129 -0
- package/lib/forge/state.js +266 -0
- package/lib/forge/trust.d.ts +48 -0
- package/lib/forge/trust.js +107 -0
- package/lib/forge/turns.d.ts +13 -0
- package/lib/forge/turns.js +56 -0
- package/lib/hooks/broker/engine.d.ts +112 -0
- package/lib/hooks/broker/engine.js +722 -0
- package/lib/hooks/broker/helpers.d.ts +10 -0
- package/lib/hooks/broker/helpers.js +22 -0
- package/lib/hooks/broker/lifecycle.d.ts +65 -0
- package/lib/hooks/broker/lifecycle.js +342 -0
- package/lib/hooks/broker/session-events.d.ts +27 -0
- package/lib/hooks/broker/session-events.js +205 -0
- package/lib/hooks/broker/tools.d.ts +52 -0
- package/lib/hooks/broker/tools.js +424 -0
- package/lib/hooks/broker/types.d.ts +264 -0
- package/lib/hooks/broker/types.js +1 -0
- package/lib/hooks/broker.d.ts +80 -0
- package/lib/hooks/broker.js +95 -0
- package/lib/hooks/codex-user.d.ts +5 -0
- package/lib/hooks/codex-user.js +109 -0
- package/lib/hooks/condition.d.ts +87 -0
- package/lib/hooks/condition.js +602 -0
- package/lib/hooks/config.d.ts +85 -0
- package/lib/hooks/config.js +154 -0
- package/lib/hooks/glob.d.ts +41 -0
- package/lib/hooks/glob.js +114 -0
- package/lib/hooks/matcher.d.ts +20 -0
- package/lib/hooks/matcher.js +39 -0
- package/lib/hooks/notice.d.ts +17 -0
- package/lib/hooks/notice.js +39 -0
- package/lib/hooks/output.d.ts +56 -0
- package/lib/hooks/output.js +214 -0
- package/lib/hooks/permissions.d.ts +19 -0
- package/lib/hooks/permissions.js +202 -0
- package/lib/hooks/powershell-aliases.d.ts +19 -0
- package/lib/hooks/powershell-aliases.js +58 -0
- package/lib/hooks/process.d.ts +64 -0
- package/lib/hooks/process.js +289 -0
- package/lib/hooks/row.d.ts +17 -0
- package/lib/hooks/row.js +96 -0
- package/lib/hooks/runner.d.ts +98 -0
- package/lib/hooks/runner.js +322 -0
- package/lib/hooks/shell-commands.d.ts +28 -0
- package/lib/hooks/shell-commands.js +241 -0
- package/lib/hooks/shell.d.ts +44 -0
- package/lib/hooks/shell.js +129 -0
- package/lib/hooks/transcript.d.ts +28 -0
- package/lib/hooks/transcript.js +141 -0
- package/lib/hooks/vocabulary.d.ts +57 -0
- package/lib/hooks/vocabulary.js +366 -0
- package/lib/index.d.ts +31 -0
- package/lib/index.js +287 -0
- package/lib/mcp/auth.d.ts +35 -0
- package/lib/mcp/auth.js +178 -0
- package/lib/mcp/catalog.d.ts +39 -0
- package/lib/mcp/catalog.js +69 -0
- package/lib/mcp/mount.d.ts +113 -0
- package/lib/mcp/mount.js +317 -0
- package/lib/mcp/policy.d.ts +42 -0
- package/lib/mcp/policy.js +43 -0
- package/lib/mcp/remote.d.ts +45 -0
- package/lib/mcp/remote.js +133 -0
- package/lib/mcp/row.d.ts +9 -0
- package/lib/mcp/row.js +225 -0
- package/lib/mods/bundler.d.ts +38 -0
- package/lib/mods/bundler.js +157 -0
- package/lib/mods/chain.d.ts +103 -0
- package/lib/mods/chain.js +436 -0
- package/lib/mods/claude.d.ts +27 -0
- package/lib/mods/claude.js +56 -0
- package/lib/mods/engine.d.ts +160 -0
- package/lib/mods/engine.js +701 -0
- package/lib/mods/expect.d.ts +8 -0
- package/lib/mods/expect.js +248 -0
- package/lib/mods/host.d.ts +105 -0
- package/lib/mods/host.js +462 -0
- package/lib/mods/loader.d.ts +53 -0
- package/lib/mods/loader.js +231 -0
- package/lib/mods/ops.d.ts +13 -0
- package/lib/mods/ops.js +117 -0
- package/lib/mods/row.d.ts +9 -0
- package/lib/mods/row.js +77 -0
- package/lib/mods/runtime.d.ts +60 -0
- package/lib/mods/runtime.js +133 -0
- package/lib/mods/service/commands.d.ts +17 -0
- package/lib/mods/service/commands.js +121 -0
- package/lib/mods/service/drawings.d.ts +36 -0
- package/lib/mods/service/drawings.js +64 -0
- package/lib/mods/service/sessions.d.ts +63 -0
- package/lib/mods/service/sessions.js +345 -0
- package/lib/mods/service/tools.d.ts +32 -0
- package/lib/mods/service/tools.js +253 -0
- package/lib/mods/service/turns.d.ts +33 -0
- package/lib/mods/service/turns.js +136 -0
- package/lib/mods/service/types.d.ts +151 -0
- package/lib/mods/service/types.js +1 -0
- package/lib/mods/service.d.ts +72 -0
- package/lib/mods/service.js +104 -0
- package/lib/mods/surfaces.d.ts +93 -0
- package/lib/mods/surfaces.js +309 -0
- package/lib/mods/values.d.ts +30 -0
- package/lib/mods/values.js +95 -0
- package/lib/opencode/bun.d.ts +40 -0
- package/lib/opencode/bun.js +168 -0
- package/lib/opencode/convert.d.ts +53 -0
- package/lib/opencode/convert.js +255 -0
- package/lib/opencode/row.d.ts +22 -0
- package/lib/opencode/row.js +104 -0
- package/lib/opencode/runtime/core.d.ts +74 -0
- package/lib/opencode/runtime/core.js +249 -0
- package/lib/opencode/runtime/events.d.ts +80 -0
- package/lib/opencode/runtime/events.js +281 -0
- package/lib/opencode/runtime/mount.d.ts +27 -0
- package/lib/opencode/runtime/mount.js +283 -0
- package/lib/opencode/runtime/server.d.ts +27 -0
- package/lib/opencode/runtime/server.js +354 -0
- package/lib/opencode/runtime/types.d.ts +109 -0
- package/lib/opencode/runtime/types.js +1 -0
- package/lib/opencode/runtime.d.ts +55 -0
- package/lib/opencode/runtime.js +79 -0
- package/lib/porting/adapter-paths.d.ts +13 -0
- package/lib/porting/adapter-paths.js +120 -0
- package/lib/porting/port-gap.d.ts +36 -0
- package/lib/porting/port-gap.js +158 -0
- package/lib/porting/port-sessions.d.ts +41 -0
- package/lib/porting/port-sessions.js +98 -0
- package/lib/porting/prompt.d.ts +23 -0
- package/lib/porting/prompt.js +51 -0
- package/lib/porting/row.d.ts +16 -0
- package/lib/porting/row.js +27 -0
- package/lib/porting/verify-port.d.ts +46 -0
- package/lib/porting/verify-port.js +82 -0
- package/lib/presets/fs-search.d.ts +25 -0
- package/lib/presets/fs-search.js +17 -0
- package/lib/presets/tool-filter.d.ts +35 -0
- package/lib/presets/tool-filter.js +91 -0
- package/lib/sessions/chat-import.d.ts +48 -0
- package/lib/sessions/chat-import.js +44 -0
- package/lib/sessions/claude.d.ts +35 -0
- package/lib/sessions/claude.js +104 -0
- package/lib/sessions/codex-discover.d.ts +34 -0
- package/lib/sessions/codex-discover.js +205 -0
- package/lib/sessions/codex-meta.d.ts +63 -0
- package/lib/sessions/codex-meta.js +148 -0
- package/lib/sessions/codex-text.d.ts +9 -0
- package/lib/sessions/codex-text.js +44 -0
- package/lib/sessions/codex.d.ts +42 -0
- package/lib/sessions/codex.js +270 -0
- package/lib/sessions/opencode.d.ts +38 -0
- package/lib/sessions/opencode.js +339 -0
- package/lib/sessions/persist.d.ts +162 -0
- package/lib/sessions/persist.js +377 -0
- package/lib/sessions/row.d.ts +15 -0
- package/lib/sessions/row.js +101 -0
- package/lib/sessions/turns.d.ts +31 -0
- package/lib/sessions/turns.js +63 -0
- package/lib/sessions/zstd.d.ts +15 -0
- package/lib/sessions/zstd.js +152 -0
- package/lib/shared/invocation.d.ts +169 -0
- package/lib/shared/invocation.js +325 -0
- package/lib/shared/render.d.ts +101 -0
- package/lib/shared/render.js +1353 -0
- package/lib/shared/util.d.ts +21 -0
- package/lib/shared/util.js +32 -0
- package/lib/skills/bundled.d.ts +3 -0
- package/lib/skills/bundled.js +42 -0
- package/lib/skills/provider.d.ts +74 -0
- package/lib/skills/provider.js +346 -0
- package/lib/skills/row.d.ts +22 -0
- package/lib/skills/row.js +204 -0
- package/lib/workbench/adapter-coverage.d.ts +65 -0
- package/lib/workbench/adapter-coverage.js +141 -0
- package/lib/workbench/model-tools.d.ts +10 -0
- package/lib/workbench/model-tools.js +122 -0
- package/lib/workbench/overview.d.ts +153 -0
- package/lib/workbench/overview.js +246 -0
- package/lib/workbench/remote.d.ts +161 -0
- package/lib/workbench/remote.js +561 -0
- package/lib/workbench/row.d.ts +15 -0
- package/lib/workbench/row.js +16 -0
- package/lib/workbench/settings.d.ts +19 -0
- package/lib/workbench/settings.js +60 -0
- package/lib/workbench/workbench.d.ts +130 -0
- package/lib/workbench/workbench.js +361 -0
- package/locale/agents/en.json +6 -0
- package/locale/agents/zh.json +6 -0
- package/locale/commands/en.json +6 -0
- package/locale/commands/zh.json +6 -0
- package/locale/context/en.json +6 -0
- package/locale/context/zh.json +6 -0
- package/locale/en.json +6 -0
- package/locale/hooks/en.json +6 -0
- package/locale/hooks/zh.json +6 -0
- package/locale/mcp/en.json +6 -0
- package/locale/mcp/zh.json +6 -0
- package/locale/mods/en.json +6 -0
- package/locale/mods/zh.json +6 -0
- package/locale/opencode/en.json +6 -0
- package/locale/opencode/zh.json +6 -0
- package/locale/porter/en.json +6 -0
- package/locale/porter/zh.json +6 -0
- package/locale/sessions/en.json +6 -0
- package/locale/sessions/zh.json +6 -0
- package/locale/skills/en.json +6 -0
- package/locale/skills/zh.json +6 -0
- package/locale/workbench/en.json +6 -0
- package/locale/workbench/zh.json +6 -0
- package/locale/zh.json +7 -0
- package/package.json +247 -3
- package/runtime/opencode-host.mjs +270 -0
- package/skills/harness-forge/SKILL.md +47 -0
|
@@ -0,0 +1,1353 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Render a Claude Code command or skill body as Claude Code does before the
|
|
3
|
+
* model sees it: argument placeholders, path variables, inline `` !`cmd` ``
|
|
4
|
+
* and fenced ```` ```! ```` shell injection, and `@file` attachments.
|
|
5
|
+
*
|
|
6
|
+
* The template's structure is fixed before any value goes in: shell lines and
|
|
7
|
+
* `@file` references are found in the body as written, so an argument (or a
|
|
8
|
+
* command's output) is always data and never becomes a shell line or an
|
|
9
|
+
* attachment. Inside a shell line a value reaches the shell only through an
|
|
10
|
+
* environment variable, referenced only where that reference provably stays
|
|
11
|
+
* data; a placeholder anywhere else keeps the line from running (a visible note
|
|
12
|
+
* says so), unlike Claude Code, which splices the text in. An `@file` reference
|
|
13
|
+
* attaches a file only where the template may reach (see `attach`); anything
|
|
14
|
+
* else gets a visible note.
|
|
15
|
+
* @module @kirkchinese/harness-forge
|
|
16
|
+
*/
|
|
17
|
+
import { readFileSync, statSync } from 'node:fs';
|
|
18
|
+
import { homedir } from 'node:os';
|
|
19
|
+
import { basename, isAbsolute, join, resolve } from 'node:path';
|
|
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';
|
|
24
|
+
/** What stands in place of a shell line that did not run. */
|
|
25
|
+
function shellNote(reason) {
|
|
26
|
+
return `[Harness Forge: this shell command was not run: ${reason}]`;
|
|
27
|
+
}
|
|
28
|
+
const COMMAND_TIMEOUT_MS = 120_000;
|
|
29
|
+
const FILE_LIMIT = 256 * 1024;
|
|
30
|
+
/** `\$`, a path variable, `$ARGUMENTS[n]`, `$ARGUMENTS`, `$n` or `$name`. */
|
|
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;
|
|
32
|
+
/** Split a body into prose and shell lines, as written: a fenced ```! block, or an inline !`cmd` at line start or after whitespace. */
|
|
33
|
+
function segmentsOf(body) {
|
|
34
|
+
// A scan in one pass: the equivalent pattern reads to the end of the body from every unclosed fence.
|
|
35
|
+
const segments = [];
|
|
36
|
+
const breaks = /[\n\r\u2028\u2029]/u;
|
|
37
|
+
const lineStart = (at) => at === 0 || breaks.test(body[at - 1] ?? '');
|
|
38
|
+
let cursor = 0;
|
|
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++;
|
|
70
|
+
}
|
|
71
|
+
segments.push({ kind: 'text', text: body.slice(cursor) });
|
|
72
|
+
return segments;
|
|
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
|
+
}
|
|
104
|
+
/** Render one body. */
|
|
105
|
+
export async function renderBody(body, context) {
|
|
106
|
+
const args = splitArguments(context.rawArguments);
|
|
107
|
+
let consumed = false;
|
|
108
|
+
/** The value a placeholder stands for; undefined leaves it as written. */
|
|
109
|
+
const valueOf = (match, variable, indexed, short, name) => {
|
|
110
|
+
if (variable !== undefined)
|
|
111
|
+
return pathVariable(variable, context);
|
|
112
|
+
if (match === '$ARGUMENTS') {
|
|
113
|
+
consumed = true;
|
|
114
|
+
return context.rawArguments.trim();
|
|
115
|
+
}
|
|
116
|
+
const index = indexed ?? short;
|
|
117
|
+
if (index !== undefined) {
|
|
118
|
+
const value = args[Number(index)];
|
|
119
|
+
if (value === undefined)
|
|
120
|
+
return undefined;
|
|
121
|
+
consumed = true;
|
|
122
|
+
return value;
|
|
123
|
+
}
|
|
124
|
+
if (name !== undefined) {
|
|
125
|
+
const position = context.argumentNames.indexOf(name);
|
|
126
|
+
if (position === -1)
|
|
127
|
+
return undefined;
|
|
128
|
+
consumed = true;
|
|
129
|
+
return args[position] ?? '';
|
|
130
|
+
}
|
|
131
|
+
return undefined;
|
|
132
|
+
};
|
|
133
|
+
const substituteText = (text) => text
|
|
134
|
+
.replace(PLACEHOLDER, (match, variable, indexed, short, name) => {
|
|
135
|
+
if (match === '\\$')
|
|
136
|
+
return '\\$';
|
|
137
|
+
return valueOf(match, variable, indexed, short, name) ?? match;
|
|
138
|
+
})
|
|
139
|
+
.replace(/\\\$(?=\d|ARGUMENTS|[A-Za-z_])/gu, '$');
|
|
140
|
+
const segments = segmentsOf(body);
|
|
141
|
+
const references = segments.flatMap(segment => segment.kind === 'text' ? fileReferences(segment.text, context) : []);
|
|
142
|
+
const kind = context.shellKind === 'powershell' ? 'powershell' : context.shell.defaultKind;
|
|
143
|
+
const lines = segments.map((segment) => {
|
|
144
|
+
if (segment.kind === 'text' || context.refuseShell !== undefined)
|
|
145
|
+
return undefined;
|
|
146
|
+
const values = {};
|
|
147
|
+
const line = shellCommand(segment.command, kind, (match, variable, indexed, short, name) => {
|
|
148
|
+
const value = valueOf(match, variable, indexed, short, name);
|
|
149
|
+
if (value === undefined)
|
|
150
|
+
return undefined;
|
|
151
|
+
const key = `HF_ARG_${String(Object.keys(values).length)}`;
|
|
152
|
+
values[key] = value;
|
|
153
|
+
return key;
|
|
154
|
+
});
|
|
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 ?? '');
|
|
176
|
+
continue;
|
|
177
|
+
}
|
|
178
|
+
commands += 1;
|
|
179
|
+
text += segment.lead + await execute(entry.line.command, kind, entry.values, context);
|
|
180
|
+
}
|
|
181
|
+
const withArguments = !consumed && context.rawArguments.trim().length > 0
|
|
182
|
+
? `${text.trimEnd()}\n\nARGUMENTS: ${context.rawArguments.trim()}`
|
|
183
|
+
: text;
|
|
184
|
+
const attached = attach(references, context);
|
|
185
|
+
const allowed = { user: 'the workspace and ~/.claude', project: 'the workspace', plugin: 'the plugin and the workspace' }[context.scope ?? 'plugin'];
|
|
186
|
+
const notes = attached.refused.map(reference => `[Harness Forge: @${reference} was not attached: it is outside ${allowed}]`);
|
|
187
|
+
return { text: [withArguments.trim(), ...notes].join('\n\n').trim(), files: attached.files, commands };
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* A Codex custom prompt with its arguments, as Codex expands it: `$1`…`$9`
|
|
191
|
+
* are the positional arguments, `$ARGUMENTS` all of them, `$NAME` the value
|
|
192
|
+
* of `NAME=value`, `$$` a literal `$`. Codex runs no commands and attaches
|
|
193
|
+
* no files from a prompt body.
|
|
194
|
+
*/
|
|
195
|
+
export function renderCodexPrompt(body, rawArguments) {
|
|
196
|
+
const words = splitArguments(rawArguments);
|
|
197
|
+
const named = new Map();
|
|
198
|
+
const positional = [];
|
|
199
|
+
for (const word of words) {
|
|
200
|
+
const match = /^([A-Z][A-Z0-9_]*)=(.*)$/su.exec(word);
|
|
201
|
+
if (match !== null)
|
|
202
|
+
named.set(match[1] ?? '', match[2] ?? '');
|
|
203
|
+
else
|
|
204
|
+
positional.push(word);
|
|
205
|
+
}
|
|
206
|
+
const text = body.replace(/\$\$|\$ARGUMENTS\b|\$([1-9])|\$([A-Z][A-Z0-9_]*)/gu, (match, digit, name) => {
|
|
207
|
+
if (match === '$$')
|
|
208
|
+
return '$';
|
|
209
|
+
if (match === '$ARGUMENTS')
|
|
210
|
+
return positional.join(' ');
|
|
211
|
+
if (digit !== undefined)
|
|
212
|
+
return positional[Number(digit) - 1] ?? '';
|
|
213
|
+
if (name !== undefined)
|
|
214
|
+
return named.get(name) ?? match;
|
|
215
|
+
return match;
|
|
216
|
+
});
|
|
217
|
+
return { text: text.trim(), files: [], commands: 0 };
|
|
218
|
+
}
|
|
219
|
+
/** Shell-style split: quotes group words; backslash escapes the next char. */
|
|
220
|
+
export function splitArguments(raw) {
|
|
221
|
+
const args = [];
|
|
222
|
+
let current = '';
|
|
223
|
+
let quote;
|
|
224
|
+
let started = false;
|
|
225
|
+
for (let index = 0; index < raw.length; index++) {
|
|
226
|
+
const char = raw[index] ?? '';
|
|
227
|
+
if (quote !== undefined) {
|
|
228
|
+
if (char === quote)
|
|
229
|
+
quote = undefined;
|
|
230
|
+
else if (char === '\\' && quote === '"' && index + 1 < raw.length)
|
|
231
|
+
current += raw[++index] ?? '';
|
|
232
|
+
else
|
|
233
|
+
current += char;
|
|
234
|
+
continue;
|
|
235
|
+
}
|
|
236
|
+
if (char === '"' || char === "'") {
|
|
237
|
+
quote = char;
|
|
238
|
+
started = true;
|
|
239
|
+
}
|
|
240
|
+
else if (/\s/u.test(char)) {
|
|
241
|
+
if (started)
|
|
242
|
+
args.push(current);
|
|
243
|
+
current = '';
|
|
244
|
+
started = false;
|
|
245
|
+
}
|
|
246
|
+
else {
|
|
247
|
+
if (char === '\\' && index + 1 < raw.length)
|
|
248
|
+
current += raw[++index] ?? '';
|
|
249
|
+
else
|
|
250
|
+
current += char;
|
|
251
|
+
started = true;
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
if (started)
|
|
255
|
+
args.push(current);
|
|
256
|
+
return args;
|
|
257
|
+
}
|
|
258
|
+
function pathVariable(name, context) {
|
|
259
|
+
const posix = (path) => path?.replace(/\\/gu, '/');
|
|
260
|
+
switch (name) {
|
|
261
|
+
case 'CLAUDE_SKILL_DIR': return posix(context.skillDir);
|
|
262
|
+
case 'CLAUDE_PROJECT_DIR': return posix(context.cwd);
|
|
263
|
+
case 'CLAUDE_SESSION_ID': return context.sessionId;
|
|
264
|
+
case 'CLAUDE_PLUGIN_ROOT': return posix(context.pluginRoot);
|
|
265
|
+
case 'CLAUDE_PLUGIN_DATA': return posix(context.dataDir);
|
|
266
|
+
default: return undefined;
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
const WHERE = {
|
|
270
|
+
dq: 'double quotes',
|
|
271
|
+
sq: 'single quotes',
|
|
272
|
+
ansi: "ANSI-C quotes ($'…')",
|
|
273
|
+
backtick: 'backticks',
|
|
274
|
+
subst: 'a nested command or subexpression',
|
|
275
|
+
param: 'a parameter expansion',
|
|
276
|
+
comment: 'a comment',
|
|
277
|
+
heredoc: 'a here-document',
|
|
278
|
+
arith: 'an arithmetic expression',
|
|
279
|
+
cond: 'a [[ ]] test',
|
|
280
|
+
herestring: 'a here-string',
|
|
281
|
+
'block-comment': 'a comment',
|
|
282
|
+
};
|
|
283
|
+
/** Words after which bash still expects a command name. */
|
|
284
|
+
const BASH_PREFIXES = new Set(['if', 'then', 'else', 'elif', 'do', 'while', 'until', '!', '{', '}', 'fi', 'done', 'esac']);
|
|
285
|
+
/** bash builtins and keywords: none may take a value, apart from those in `argumentOf`. */
|
|
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']);
|
|
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']);
|
|
430
|
+
/** A `test` / `[` operator whose operand stays a plain string or file name (not `-v`, `-a`, `-o`, `!`). */
|
|
431
|
+
const TEST_OPERATOR = /^(?:-[bcdefghknprsStuwxzGLNO]|-(?:eq|ne|lt|le|gt|ge|nt|ot|ef)|==?|!=)$/u;
|
|
432
|
+
/** A line that defines a function or alias, whose body may run its arguments. */
|
|
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
|
+
};
|
|
476
|
+
/**
|
|
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).
|
|
481
|
+
*/
|
|
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;
|
|
666
|
+
const name = words[at];
|
|
667
|
+
if (name === undefined)
|
|
668
|
+
return false;
|
|
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);
|
|
764
|
+
if (kind === 'powershell') {
|
|
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));
|
|
767
|
+
}
|
|
768
|
+
if (!/^[\w./:+@,-]+$|^\[$/u.test(name) && !hostName)
|
|
769
|
+
return false;
|
|
770
|
+
if ((command === 'find' && words.some((arg, index) => index > at && /^-(?:exec|execdir|ok|okdir)$/u.test(arg))))
|
|
771
|
+
return false;
|
|
772
|
+
if (!BASH_BUILTINS.has(name))
|
|
773
|
+
return true;
|
|
774
|
+
switch (name) {
|
|
775
|
+
case 'echo':
|
|
776
|
+
case 'cd':
|
|
777
|
+
case 'pushd':
|
|
778
|
+
case 'pwd':
|
|
779
|
+
case 'true':
|
|
780
|
+
case 'false':
|
|
781
|
+
case ':': return true;
|
|
782
|
+
// `printf -v NAME` evaluates NAME; so would a value standing as the format.
|
|
783
|
+
case 'printf': return words.length > at + 1 && !words.slice(at + 1).includes('-v');
|
|
784
|
+
case 'test':
|
|
785
|
+
case '[': return words.length > at + 1 && TEST_OPERATOR.test(words.at(-1) ?? '');
|
|
786
|
+
default: return false;
|
|
787
|
+
}
|
|
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;
|
|
925
|
+
/**
|
|
926
|
+
* A shell line with each placeholder replaced by a reference to an
|
|
927
|
+
* environment variable holding its value. Values never enter the source: a
|
|
928
|
+
* reference is written only where it provably stays one word of data (bash:
|
|
929
|
+
* unquoted or inside plain double quotes; PowerShell: outside quotes or inside
|
|
930
|
+
* plain double quotes), and only in an argument of a simple command that does
|
|
931
|
+
* not run it (see `argumentOf`), in a line that defines no function or alias.
|
|
932
|
+
* A placeholder anywhere else (single or ANSI-C quotes, here-documents and
|
|
933
|
+
* here-strings, backticks, `$(…)`, parameter expansions, arithmetic, `[[ ]]`,
|
|
934
|
+
* comments, the command position, an assignment, the arguments of `eval` and
|
|
935
|
+
* the like) makes the whole line refused. `\$` stays as written, for the shell.
|
|
936
|
+
*/
|
|
937
|
+
export function shellCommand(command, kind, value) {
|
|
938
|
+
const stack = [];
|
|
939
|
+
const heredocs = [];
|
|
940
|
+
const placeholder = new RegExp(PLACEHOLDER.source, 'uy');
|
|
941
|
+
const single = kind === 'powershell' ? /['\u2018\u2019\u201A\u201B]/u : /'/u;
|
|
942
|
+
const double = kind === 'powershell' ? /["\u201C\u201D\u201E]/u : /"/u;
|
|
943
|
+
const escape = kind === 'bash' ? '\\' : '`';
|
|
944
|
+
const defines = DEFINES[kind].test(command);
|
|
945
|
+
let out = '';
|
|
946
|
+
let index = 0;
|
|
947
|
+
const take = (count) => {
|
|
948
|
+
out += command.slice(index, index + count);
|
|
949
|
+
index += count;
|
|
950
|
+
};
|
|
951
|
+
const wordStart = () => index === 0 || /[\s;&|(<>]/u.test(command[index - 1] ?? '');
|
|
952
|
+
const lineStart = () => index === 0 || command[index - 1] === '\n';
|
|
953
|
+
// The words of the current simple command, read at the top level only.
|
|
954
|
+
let words = [];
|
|
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;
|
|
969
|
+
const endWord = () => {
|
|
970
|
+
if (wordAt === undefined)
|
|
971
|
+
return;
|
|
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;
|
|
981
|
+
if (!(kind === 'bash' && words.length === 0 && BASH_PREFIXES.has(word)))
|
|
982
|
+
words.push(word);
|
|
983
|
+
wordAt = undefined;
|
|
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
|
+
};
|
|
1026
|
+
const separates = (char, next) => {
|
|
1027
|
+
const previous = command[index - 1] ?? '';
|
|
1028
|
+
if (/[\n;()]/u.test(char))
|
|
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-).
|
|
1032
|
+
if (kind === 'powershell')
|
|
1033
|
+
return /[{}|]/u.test(char) || (char === '&' && (next === '&' || previous === '&' || powershellAmpersand(previous, next, words.length > 0 || wordAt !== undefined) === 'background'));
|
|
1034
|
+
return (char === '|' && previous !== '>') || (char === '&' && !/[<>]/u.test(previous) && next !== '>');
|
|
1035
|
+
};
|
|
1036
|
+
while (index < command.length) {
|
|
1037
|
+
const frame = stack.at(-1);
|
|
1038
|
+
const char = command[index] ?? '';
|
|
1039
|
+
const next = command[index + 1] ?? '';
|
|
1040
|
+
// A here-document (bash) or here-string (PowerShell) body ends at its own line.
|
|
1041
|
+
if ((frame?.kind === 'heredoc' || frame?.kind === 'herestring') && lineStart()) {
|
|
1042
|
+
const end = command.indexOf('\n', index);
|
|
1043
|
+
const line = command.slice(index, end === -1 ? command.length : end);
|
|
1044
|
+
const closes = frame.kind === 'heredoc' ? frame.end !== undefined && (frame.strip === true ? line.replace(/^\t+/u, '') : line) === frame.end : line.startsWith(frame.end ?? '\0');
|
|
1045
|
+
if (closes) {
|
|
1046
|
+
stack.pop();
|
|
1047
|
+
take(frame.kind === 'heredoc' ? line.length : (frame.end ?? '').length);
|
|
1048
|
+
continue;
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
if (stack.length === 0) {
|
|
1052
|
+
if (/[ \t\r]/u.test(char))
|
|
1053
|
+
endWord();
|
|
1054
|
+
else if (separates(char, next))
|
|
1055
|
+
endCommand(char, next);
|
|
1056
|
+
else
|
|
1057
|
+
wordAt ??= index;
|
|
1058
|
+
}
|
|
1059
|
+
if (char === '$' || char === '\\') {
|
|
1060
|
+
placeholder.lastIndex = index;
|
|
1061
|
+
const match = placeholder.exec(command);
|
|
1062
|
+
if (match !== null && match[0] === '\\$') {
|
|
1063
|
+
take(2);
|
|
1064
|
+
continue;
|
|
1065
|
+
}
|
|
1066
|
+
if (match !== null) {
|
|
1067
|
+
const key = value(match[0], match[1], match[2], match[3], match[4]);
|
|
1068
|
+
if (key !== undefined) {
|
|
1069
|
+
if (frame !== undefined && !(stack.length === 1 && frame.kind === 'dq'))
|
|
1070
|
+
return { refused: `an argument or path variable stands inside ${WHERE[frame.kind]}` };
|
|
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)
|
|
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);
|
|
1077
|
+
out += kind === 'powershell' ? `\${env:${key}}` : frame === undefined ? `"\${${key}}"` : `\${${key}}`;
|
|
1078
|
+
valued = true;
|
|
1079
|
+
if (!host)
|
|
1080
|
+
chosen = true;
|
|
1081
|
+
index += match[0].length;
|
|
1082
|
+
continue;
|
|
1083
|
+
}
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
if (frame?.kind === 'heredoc' || frame?.kind === 'herestring') {
|
|
1087
|
+
take(1);
|
|
1088
|
+
continue;
|
|
1089
|
+
}
|
|
1090
|
+
if (frame?.kind === 'comment') {
|
|
1091
|
+
// The line break ends the comment and is read again as code.
|
|
1092
|
+
if (char === '\n')
|
|
1093
|
+
stack.pop();
|
|
1094
|
+
else
|
|
1095
|
+
take(1);
|
|
1096
|
+
continue;
|
|
1097
|
+
}
|
|
1098
|
+
if (frame?.kind === 'block-comment') {
|
|
1099
|
+
if (char === '#' && next === '>') {
|
|
1100
|
+
stack.pop();
|
|
1101
|
+
take(2);
|
|
1102
|
+
}
|
|
1103
|
+
else
|
|
1104
|
+
take(1);
|
|
1105
|
+
continue;
|
|
1106
|
+
}
|
|
1107
|
+
if (frame?.kind === 'sq') {
|
|
1108
|
+
if (kind === 'powershell' && single.test(char) && single.test(next))
|
|
1109
|
+
take(2);
|
|
1110
|
+
else {
|
|
1111
|
+
if (single.test(char))
|
|
1112
|
+
stack.pop();
|
|
1113
|
+
take(1);
|
|
1114
|
+
}
|
|
1115
|
+
continue;
|
|
1116
|
+
}
|
|
1117
|
+
if (frame?.kind === 'ansi' || frame?.kind === 'backtick' || frame?.kind === 'param') {
|
|
1118
|
+
if (char === '\\' && index + 1 < command.length)
|
|
1119
|
+
take(2);
|
|
1120
|
+
else {
|
|
1121
|
+
const closes = frame.kind === 'ansi' ? char === "'" : frame.kind === 'backtick' ? char === '`' : char === '}';
|
|
1122
|
+
if (closes)
|
|
1123
|
+
stack.pop();
|
|
1124
|
+
else if (frame.kind === 'param' && char === '$' && next === '{')
|
|
1125
|
+
stack.push({ kind: 'param' });
|
|
1126
|
+
take(closes || !(char === '$' && next === '{') ? 1 : 2);
|
|
1127
|
+
}
|
|
1128
|
+
continue;
|
|
1129
|
+
}
|
|
1130
|
+
if (char === escape && index + 1 < command.length) {
|
|
1131
|
+
take(2);
|
|
1132
|
+
continue;
|
|
1133
|
+
}
|
|
1134
|
+
if (frame?.kind === 'dq') {
|
|
1135
|
+
if (double.test(char)) {
|
|
1136
|
+
if (kind === 'powershell' && double.test(next))
|
|
1137
|
+
take(2);
|
|
1138
|
+
else {
|
|
1139
|
+
stack.pop();
|
|
1140
|
+
take(1);
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
else if (char === '$' && next === '(') {
|
|
1144
|
+
stack.push({ kind: 'subst', depth: 0 });
|
|
1145
|
+
take(2);
|
|
1146
|
+
}
|
|
1147
|
+
else if (char === '$' && next === '{') {
|
|
1148
|
+
stack.push({ kind: 'param' });
|
|
1149
|
+
take(2);
|
|
1150
|
+
}
|
|
1151
|
+
else if (kind === 'bash' && char === '`') {
|
|
1152
|
+
stack.push({ kind: 'backtick' });
|
|
1153
|
+
take(1);
|
|
1154
|
+
}
|
|
1155
|
+
else
|
|
1156
|
+
take(1);
|
|
1157
|
+
continue;
|
|
1158
|
+
}
|
|
1159
|
+
if ((frame?.kind === 'arith' || frame?.kind === 'cond') && frame.end !== undefined && command.startsWith(frame.end, index)) {
|
|
1160
|
+
stack.pop();
|
|
1161
|
+
// A `let` ends at a separator, read again as code.
|
|
1162
|
+
if (!/^[;&|\n]$/u.test(frame.end))
|
|
1163
|
+
take(frame.end.length);
|
|
1164
|
+
continue;
|
|
1165
|
+
}
|
|
1166
|
+
// Code: the top level, a `$(…)`, an arithmetic expression or a `[[ ]]` test.
|
|
1167
|
+
if (char === '\n' && heredocs.length > 0) {
|
|
1168
|
+
take(1);
|
|
1169
|
+
stack.push(...heredocs.splice(0).reverse());
|
|
1170
|
+
continue;
|
|
1171
|
+
}
|
|
1172
|
+
if (kind === 'powershell' && char === '@' && (single.test(next) || double.test(next)) && /^[ \t]*\r?\n/u.test(command.slice(index + 2))) {
|
|
1173
|
+
stack.push({ kind: 'herestring', end: single.test(next) ? `'@` : `"@` });
|
|
1174
|
+
take(2);
|
|
1175
|
+
continue;
|
|
1176
|
+
}
|
|
1177
|
+
if (kind === 'powershell' && char === '<' && next === '#') {
|
|
1178
|
+
stack.push({ kind: 'block-comment' });
|
|
1179
|
+
take(2);
|
|
1180
|
+
continue;
|
|
1181
|
+
}
|
|
1182
|
+
if (kind === 'bash' && char === '$' && next === "'") {
|
|
1183
|
+
stack.push({ kind: 'ansi' });
|
|
1184
|
+
take(2);
|
|
1185
|
+
continue;
|
|
1186
|
+
}
|
|
1187
|
+
if (char === '$' && (next === '(' || next === '{' || (kind === 'bash' && next === '['))) {
|
|
1188
|
+
stack.push(next === '(' ? { kind: 'subst', depth: 0 } : next === '{' ? { kind: 'param' } : { kind: 'arith', end: ']' });
|
|
1189
|
+
take(2);
|
|
1190
|
+
continue;
|
|
1191
|
+
}
|
|
1192
|
+
if (single.test(char))
|
|
1193
|
+
stack.push({ kind: 'sq' });
|
|
1194
|
+
else if (double.test(char))
|
|
1195
|
+
stack.push({ kind: 'dq' });
|
|
1196
|
+
else if (kind === 'bash' && char === '`')
|
|
1197
|
+
stack.push({ kind: 'backtick' });
|
|
1198
|
+
else if (char === '#' && wordStart())
|
|
1199
|
+
stack.push({ kind: 'comment' });
|
|
1200
|
+
else if (kind === 'bash' && wordStart() && char === '(' && next === '(') {
|
|
1201
|
+
stack.push({ kind: 'arith', end: '))' });
|
|
1202
|
+
take(2);
|
|
1203
|
+
continue;
|
|
1204
|
+
}
|
|
1205
|
+
else if (kind === 'bash' && wordStart() && char === '[' && next === '[') {
|
|
1206
|
+
stack.push({ kind: 'cond', end: ']]' });
|
|
1207
|
+
take(2);
|
|
1208
|
+
continue;
|
|
1209
|
+
}
|
|
1210
|
+
else if (kind === 'bash' && command.startsWith('let', index) && !/\w/u.test(command[index + 3] ?? '') && commandStart(command, index)) {
|
|
1211
|
+
// `let` evaluates its arguments as arithmetic, to the end of the command (undefined: the end of the line).
|
|
1212
|
+
const end = /[;&|\n]/u.exec(command.slice(index))?.[0];
|
|
1213
|
+
stack.push({ kind: 'arith', ...(end !== undefined ? { end } : {}) });
|
|
1214
|
+
}
|
|
1215
|
+
else if (kind === 'bash' && char === '<' && next === '<' && command[index + 2] !== '<') {
|
|
1216
|
+
// A here-document: its body starts after this line and ends at the delimiter.
|
|
1217
|
+
const operator = /^<<(-?)[ \t]*(?:'([^'\n]+)'|"([^"\n]+)"|\\?([A-Za-z0-9_.-]+))/u.exec(command.slice(index));
|
|
1218
|
+
heredocs.push({ kind: 'heredoc', strip: operator?.[1] === '-', ...(operator !== null ? { end: operator[2] ?? operator[3] ?? operator[4] ?? '' } : {}) });
|
|
1219
|
+
take(operator?.[0].length ?? 2);
|
|
1220
|
+
continue;
|
|
1221
|
+
}
|
|
1222
|
+
else if (kind === 'bash' && char === '<' && next === '<') {
|
|
1223
|
+
take(3);
|
|
1224
|
+
continue;
|
|
1225
|
+
}
|
|
1226
|
+
else if (frame?.kind === 'subst' && char === '(')
|
|
1227
|
+
frame.depth = (frame.depth ?? 0) + 1;
|
|
1228
|
+
else if (frame?.kind === 'subst' && char === ')') {
|
|
1229
|
+
if ((frame.depth ?? 0) === 0)
|
|
1230
|
+
stack.pop();
|
|
1231
|
+
else
|
|
1232
|
+
frame.depth = (frame.depth ?? 0) - 1;
|
|
1233
|
+
}
|
|
1234
|
+
take(1);
|
|
1235
|
+
}
|
|
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] ?? '');
|
|
1261
|
+
}
|
|
1262
|
+
async function execute(command, kind, values, context) {
|
|
1263
|
+
const result = await context.shell.runShell(command, kind, {
|
|
1264
|
+
cwd: context.cwd,
|
|
1265
|
+
timeoutMs: COMMAND_TIMEOUT_MS,
|
|
1266
|
+
env: {
|
|
1267
|
+
...values,
|
|
1268
|
+
...(context.pluginRoot !== undefined ? { CLAUDE_PLUGIN_ROOT: context.pluginRoot.replace(/\\/gu, '/') } : {}),
|
|
1269
|
+
...(context.dataDir !== undefined ? { CLAUDE_PLUGIN_DATA: context.dataDir.replace(/\\/gu, '/') } : {}),
|
|
1270
|
+
CLAUDE_PROJECT_DIR: context.cwd.replace(/\\/gu, '/'),
|
|
1271
|
+
},
|
|
1272
|
+
...(context.signal !== undefined ? { signal: context.signal } : {}),
|
|
1273
|
+
});
|
|
1274
|
+
if (result.startError !== undefined)
|
|
1275
|
+
return `[command failed: ${result.startError}]`;
|
|
1276
|
+
// Claude Code merges stderr into stdout for injected commands.
|
|
1277
|
+
return `${result.stdout}${result.stderr}`.trimEnd();
|
|
1278
|
+
}
|
|
1279
|
+
/**
|
|
1280
|
+
* The `@path` references of a template's prose, with path variables expanded.
|
|
1281
|
+
* A reference built from an argument is not one: what the person typed stays text.
|
|
1282
|
+
*/
|
|
1283
|
+
function fileReferences(text, context) {
|
|
1284
|
+
const found = [];
|
|
1285
|
+
for (const match of text.matchAll(/(?:^|\s)@([^\s`'"()<>]+)/gmu)) {
|
|
1286
|
+
const raw = stripTrailing(match[1] ?? '', '.,;:');
|
|
1287
|
+
if (!/[/\\.]/u.test(raw))
|
|
1288
|
+
continue;
|
|
1289
|
+
let fromArgument = false;
|
|
1290
|
+
const reference = raw.replace(PLACEHOLDER, (whole, variable) => {
|
|
1291
|
+
if (variable !== undefined)
|
|
1292
|
+
return pathVariable(variable, context) ?? whole;
|
|
1293
|
+
if (whole !== '\\$')
|
|
1294
|
+
fromArgument = true;
|
|
1295
|
+
return whole;
|
|
1296
|
+
});
|
|
1297
|
+
if (!fromArgument)
|
|
1298
|
+
found.push(reference);
|
|
1299
|
+
}
|
|
1300
|
+
return found;
|
|
1301
|
+
}
|
|
1302
|
+
/**
|
|
1303
|
+
* Read the referenced files that lie where the template may reach; name the
|
|
1304
|
+
* others. A project's template reaches the workspace only; a plugin's its own
|
|
1305
|
+
* directory and the workspace; only the person's own templates reach `~/.claude`.
|
|
1306
|
+
*/
|
|
1307
|
+
function attach(references, context) {
|
|
1308
|
+
const home = context.home ?? homedir();
|
|
1309
|
+
const scope = context.scope ?? 'plugin';
|
|
1310
|
+
const roots = [workspaceRootOf(context.cwd), ...scope === 'project' ? [] : [context.pluginRoot, context.skillDir], ...scope === 'user' ? [join(home, '.claude')] : []]
|
|
1311
|
+
.filter((root) => root !== undefined)
|
|
1312
|
+
.map(realOrLexical);
|
|
1313
|
+
const files = [];
|
|
1314
|
+
const refused = [];
|
|
1315
|
+
const seen = new Set();
|
|
1316
|
+
for (const reference of references) {
|
|
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
|
+
}
|
|
1324
|
+
let stat;
|
|
1325
|
+
try {
|
|
1326
|
+
stat = statSync(path);
|
|
1327
|
+
}
|
|
1328
|
+
catch {
|
|
1329
|
+
continue; // A missing file stays literal text, as in Claude Code.
|
|
1330
|
+
}
|
|
1331
|
+
const real = realOrLexical(path);
|
|
1332
|
+
if (seen.has(real) || !stat.isFile() || stat.size > FILE_LIMIT)
|
|
1333
|
+
continue;
|
|
1334
|
+
seen.add(real);
|
|
1335
|
+
if (!roots.some(root => isInside(root, real))) {
|
|
1336
|
+
refused.push(reference);
|
|
1337
|
+
continue;
|
|
1338
|
+
}
|
|
1339
|
+
try {
|
|
1340
|
+
files.push({ path: reference, content: readFileSync(real, 'utf8') });
|
|
1341
|
+
}
|
|
1342
|
+
catch {
|
|
1343
|
+
// Unreadable references stay as literal text, as in Claude Code.
|
|
1344
|
+
}
|
|
1345
|
+
}
|
|
1346
|
+
return { files, refused };
|
|
1347
|
+
}
|
|
1348
|
+
/** Append `@` attachments to a rendered prompt. */
|
|
1349
|
+
export function withAttachments(rendered) {
|
|
1350
|
+
if (rendered.files.length === 0)
|
|
1351
|
+
return rendered.text;
|
|
1352
|
+
return [rendered.text, ...rendered.files.map(file => `<file path="${file.path}">\n${file.content}\n</file>`)].join('\n\n');
|
|
1353
|
+
}
|