@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,214 @@
|
|
|
1
|
+
/** Universal JSON output fields and their types. */
|
|
2
|
+
const UNIVERSAL = {
|
|
3
|
+
continue: 'boolean',
|
|
4
|
+
stopReason: 'string',
|
|
5
|
+
suppressOutput: 'boolean',
|
|
6
|
+
systemMessage: 'string',
|
|
7
|
+
terminalSequence: 'string',
|
|
8
|
+
reason: 'string',
|
|
9
|
+
};
|
|
10
|
+
/** Events whose stdout Claude Code reads as plain text context. */
|
|
11
|
+
const PLAIN_CONTEXT = new Set(['UserPromptSubmit', 'UserPromptExpansion', 'SessionStart', 'PostModelSwitch', 'PreCompact']);
|
|
12
|
+
/** Decode a synchronous run. */
|
|
13
|
+
export function decodeRun(event, dialect, run) {
|
|
14
|
+
if (run.failure !== undefined) {
|
|
15
|
+
if (run.failure.kind === 'cancelled')
|
|
16
|
+
return { failed: false, cancelled: true };
|
|
17
|
+
return { error: run.failure.message, failed: true };
|
|
18
|
+
}
|
|
19
|
+
const classified = classify(run.stdout, false);
|
|
20
|
+
const checked = classified.kind === 'json' ? validate(event, dialect, classified.value) : classified;
|
|
21
|
+
const stderr = run.stderr.trim();
|
|
22
|
+
if (run.exitCode === 2) {
|
|
23
|
+
if (missingFileBlock(event, run))
|
|
24
|
+
return { error: `exit 2: ${firstLine(stderr)}`, failed: true };
|
|
25
|
+
const json = checked.kind === 'json' ? checked.value : undefined;
|
|
26
|
+
const reason = jsonReason(json) ?? (stderr.length > 0 ? stderr : `${event} hook exited 2`);
|
|
27
|
+
return { ...(json !== undefined ? { json } : {}), block: reason, failed: false };
|
|
28
|
+
}
|
|
29
|
+
if (checked.kind === 'invalid')
|
|
30
|
+
return { error: checked.message, failed: true };
|
|
31
|
+
if (run.exitCode === 0) {
|
|
32
|
+
if (checked.kind === 'json')
|
|
33
|
+
return { json: checked.value, failed: false };
|
|
34
|
+
if (dialect === 'codex' && (event === 'Stop' || event === 'SubagentStop') && checked.text.length > 0) {
|
|
35
|
+
return { error: `${event} hooks must print JSON; got plain text`, failed: true };
|
|
36
|
+
}
|
|
37
|
+
return { ...(checked.text.length > 0 ? { plain: checked.text } : {}), failed: false };
|
|
38
|
+
}
|
|
39
|
+
if (checked.kind === 'json')
|
|
40
|
+
return { json: checked.value, failed: true };
|
|
41
|
+
const detail = firstLine(stderr) || firstLine(run.stdout);
|
|
42
|
+
return { error: `Failed with non-blocking status code ${String(run.exitCode ?? 'none')}${detail.length > 0 ? `: ${detail}` : ''}`, failed: true };
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Decode a background (`async`) run: the JSON response may span stdout alone
|
|
46
|
+
* or sit on one line among other text; fields of the wrong type are dropped.
|
|
47
|
+
*/
|
|
48
|
+
export function decodeAsyncRun(event, dialect, run) {
|
|
49
|
+
if (run.failure !== undefined)
|
|
50
|
+
return run.failure.kind === 'cancelled' ? { failed: false, cancelled: true } : { error: run.failure.message, failed: true };
|
|
51
|
+
const classified = classify(run.stdout, true);
|
|
52
|
+
const json = classified.kind === 'json' ? dropInvalid(event, classified.value) : undefined;
|
|
53
|
+
const failed = run.exitCode !== 0 && run.exitCode !== 2;
|
|
54
|
+
return {
|
|
55
|
+
...(json !== undefined ? { json } : {}),
|
|
56
|
+
...(run.exitCode === 2 ? { block: run.stderr.trim() || run.stdout.trim() } : {}),
|
|
57
|
+
...(failed ? { error: `Failed with status code ${String(run.exitCode ?? 'none')}: ${firstLine(run.stderr)}` } : {}),
|
|
58
|
+
failed,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
/** Whether plain stdout of a successful run becomes context on this event. */
|
|
62
|
+
export function plainIsContext(event, dialect) {
|
|
63
|
+
if (dialect === 'codex')
|
|
64
|
+
return event === 'SessionStart' || event === 'UserPromptSubmit' || event === 'SubagentStart';
|
|
65
|
+
return PLAIN_CONTEXT.has(event);
|
|
66
|
+
}
|
|
67
|
+
/** The `hookSpecificOutput` object of a decoded run. */
|
|
68
|
+
export function specific(decoded) {
|
|
69
|
+
const value = decoded.json?.['hookSpecificOutput'];
|
|
70
|
+
return isRecord(value) ? value : undefined;
|
|
71
|
+
}
|
|
72
|
+
/** The context strings a run adds: `additionalContext`, plus plain stdout where the event reads it. */
|
|
73
|
+
export function contextsOf(event, dialect, decoded) {
|
|
74
|
+
const out = [];
|
|
75
|
+
const additional = specific(decoded)?.['additionalContext'];
|
|
76
|
+
if (typeof additional === 'string' && additional.length > 0)
|
|
77
|
+
out.push(additional);
|
|
78
|
+
if (decoded.plain !== undefined && plainIsContext(event, dialect) && event !== 'PreCompact')
|
|
79
|
+
out.push(decoded.plain);
|
|
80
|
+
return out;
|
|
81
|
+
}
|
|
82
|
+
function classify(stdout, async) {
|
|
83
|
+
const text = stdout.trim();
|
|
84
|
+
if (text.length === 0)
|
|
85
|
+
return { kind: 'plain', text: '' };
|
|
86
|
+
if (text.startsWith('{') && text.endsWith('}')) {
|
|
87
|
+
try {
|
|
88
|
+
const value = JSON.parse(text);
|
|
89
|
+
if (isRecord(value))
|
|
90
|
+
return { kind: 'json', value };
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
// Several JSON lines, or a parse failure; see below.
|
|
94
|
+
}
|
|
95
|
+
const lines = text.split(/\r?\n/u).map(line => line.trim()).filter(line => line.length > 0);
|
|
96
|
+
const parsed = lines.map(tryParse);
|
|
97
|
+
if (lines.length > 1 && parsed.every(item => item.ok)) {
|
|
98
|
+
const objects = parsed.map(item => item.value).filter(isRecord);
|
|
99
|
+
if (async && objects.length >= 1)
|
|
100
|
+
return { kind: 'json', value: objects.at(-1) };
|
|
101
|
+
return objects.some(object => Object.keys(object).length > 0)
|
|
102
|
+
? { kind: 'invalid', message: 'stdout holds several JSON values; print one JSON object only' }
|
|
103
|
+
: { kind: 'plain', text };
|
|
104
|
+
}
|
|
105
|
+
if (!async)
|
|
106
|
+
return { kind: 'invalid', message: `invalid JSON output: ${parseError(text)}` };
|
|
107
|
+
}
|
|
108
|
+
if (async) {
|
|
109
|
+
const line = text.split(/\r?\n/u).map(item => item.trim()).filter(item => item.startsWith('{') && item.endsWith('}')).map(tryParse).find(item => item.ok && isRecord(item.value));
|
|
110
|
+
if (line !== undefined)
|
|
111
|
+
return { kind: 'json', value: line.value };
|
|
112
|
+
}
|
|
113
|
+
return { kind: 'plain', text };
|
|
114
|
+
}
|
|
115
|
+
function validate(event, dialect, value) {
|
|
116
|
+
for (const [field, type] of Object.entries(UNIVERSAL)) {
|
|
117
|
+
if (field in value && typeof value[field] !== type)
|
|
118
|
+
return { kind: 'invalid', message: `JSON output field "${field}" must be a ${type}` };
|
|
119
|
+
}
|
|
120
|
+
if ('decision' in value) {
|
|
121
|
+
const decision = value['decision'];
|
|
122
|
+
const allowed = event === 'PreToolUse' ? ['block', 'approve'] : ['block'];
|
|
123
|
+
if (typeof decision !== 'string' || !allowed.includes(decision))
|
|
124
|
+
return { kind: 'invalid', message: `JSON output field "decision" must be ${allowed.map(item => `"${item}"`).join(' or ')}` };
|
|
125
|
+
}
|
|
126
|
+
const hso = value['hookSpecificOutput'];
|
|
127
|
+
if (hso !== undefined) {
|
|
128
|
+
if (!isRecord(hso))
|
|
129
|
+
return { kind: 'invalid', message: 'hookSpecificOutput must be an object' };
|
|
130
|
+
if (hso['hookEventName'] !== event)
|
|
131
|
+
return { kind: 'invalid', message: `hookSpecificOutput.hookEventName must be "${event}"` };
|
|
132
|
+
if ('additionalContext' in hso && typeof hso['additionalContext'] !== 'string')
|
|
133
|
+
return { kind: 'invalid', message: 'additionalContext must be a string' };
|
|
134
|
+
if (event === 'PreToolUse' && 'permissionDecision' in hso && !['allow', 'deny', 'ask', 'defer'].includes(String(hso['permissionDecision']))) {
|
|
135
|
+
return { kind: 'invalid', message: 'permissionDecision must be "allow", "deny", "ask" or "defer"' };
|
|
136
|
+
}
|
|
137
|
+
if ('updatedInput' in hso && !isRecord(hso['updatedInput']))
|
|
138
|
+
return { kind: 'invalid', message: 'updatedInput must be an object' };
|
|
139
|
+
if (event === 'PermissionRequest' && 'decision' in hso) {
|
|
140
|
+
const decision = hso['decision'];
|
|
141
|
+
if (!isRecord(decision) || (decision['behavior'] !== 'allow' && decision['behavior'] !== 'deny')) {
|
|
142
|
+
return { kind: 'invalid', message: 'decision.behavior must be "allow" or "deny"' };
|
|
143
|
+
}
|
|
144
|
+
if (dialect === 'codex' && ('updatedInput' in decision || 'updatedPermissions' in decision || 'interrupt' in decision)) {
|
|
145
|
+
return { kind: 'invalid', message: 'Codex PermissionRequest hooks may not return updatedInput, updatedPermissions or interrupt' };
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
if (dialect === 'codex' && event === 'PreToolUse') {
|
|
150
|
+
for (const field of ['continue', 'stopReason', 'suppressOutput']) {
|
|
151
|
+
if (field in value)
|
|
152
|
+
return { kind: 'invalid', message: `Codex PreToolUse hooks do not support "${field}"` };
|
|
153
|
+
}
|
|
154
|
+
if (isRecord(hso) && hso['permissionDecision'] === 'ask')
|
|
155
|
+
return { kind: 'invalid', message: 'Codex PreToolUse hooks do not support permissionDecision "ask"' };
|
|
156
|
+
if (value['decision'] === 'approve')
|
|
157
|
+
return { kind: 'invalid', message: 'Codex PreToolUse hooks do not support decision "approve"' };
|
|
158
|
+
}
|
|
159
|
+
return { kind: 'json', value };
|
|
160
|
+
}
|
|
161
|
+
/** Async output: keep the fields whose types are right. */
|
|
162
|
+
function dropInvalid(event, value) {
|
|
163
|
+
const out = {};
|
|
164
|
+
for (const [field, type] of Object.entries(UNIVERSAL)) {
|
|
165
|
+
if (typeof value[field] === type)
|
|
166
|
+
out[field] = value[field];
|
|
167
|
+
}
|
|
168
|
+
const hso = value['hookSpecificOutput'];
|
|
169
|
+
if (isRecord(hso) && hso['hookEventName'] === event && typeof hso['additionalContext'] === 'string') {
|
|
170
|
+
out['hookSpecificOutput'] = { hookEventName: event, additionalContext: hso['additionalContext'] };
|
|
171
|
+
}
|
|
172
|
+
return out;
|
|
173
|
+
}
|
|
174
|
+
/** The block reason a JSON output names for itself. */
|
|
175
|
+
function jsonReason(json) {
|
|
176
|
+
if (json === undefined)
|
|
177
|
+
return undefined;
|
|
178
|
+
const hso = isRecord(json['hookSpecificOutput']) ? json['hookSpecificOutput'] : {};
|
|
179
|
+
for (const value of [hso['permissionDecisionReason'], isRecord(hso['decision']) ? hso['decision']['message'] : undefined, json['reason']]) {
|
|
180
|
+
if (typeof value === 'string' && value.length > 0)
|
|
181
|
+
return value;
|
|
182
|
+
}
|
|
183
|
+
return undefined;
|
|
184
|
+
}
|
|
185
|
+
/** Stop, SubagentStop and a plugin's UserPromptSubmit: exit 2 caused by a missing file is a non-blocking error. */
|
|
186
|
+
function missingFileBlock(event, run) {
|
|
187
|
+
return (event === 'Stop' || event === 'SubagentStop' || event === 'TaskCompleted' || event === 'UserPromptSubmit')
|
|
188
|
+
&& run.stdout.trim().length === 0
|
|
189
|
+
&& /No such file or directory|cannot find the (path|file)/iu.test(run.stderr);
|
|
190
|
+
}
|
|
191
|
+
function tryParse(text) {
|
|
192
|
+
try {
|
|
193
|
+
return { ok: true, value: JSON.parse(text) };
|
|
194
|
+
}
|
|
195
|
+
catch {
|
|
196
|
+
return { ok: false };
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
function parseError(text) {
|
|
200
|
+
try {
|
|
201
|
+
JSON.parse(text);
|
|
202
|
+
return 'not an object';
|
|
203
|
+
}
|
|
204
|
+
catch (error) {
|
|
205
|
+
return error instanceof Error ? error.message : String(error);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
/** The first non-empty line, trimmed and bounded. */
|
|
209
|
+
export function firstLine(text) {
|
|
210
|
+
return text.split(/\r?\n/u).find(line => line.trim().length > 0)?.trim().slice(0, 500) ?? '';
|
|
211
|
+
}
|
|
212
|
+
function isRecord(value) {
|
|
213
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
214
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { type ForeignTool } from './vocabulary.js';
|
|
2
|
+
/** A rule in Claude Code's syntax, with the directory its `/path` file patterns anchor at (see `conditionMatches`). */
|
|
3
|
+
export type PermissionRule = string | {
|
|
4
|
+
readonly rule: string;
|
|
5
|
+
readonly root: string;
|
|
6
|
+
};
|
|
7
|
+
/** Rules in Claude Code's syntax. */
|
|
8
|
+
export interface PermissionRuleSet {
|
|
9
|
+
readonly allow: readonly PermissionRule[];
|
|
10
|
+
readonly deny: readonly PermissionRule[];
|
|
11
|
+
readonly ask: readonly PermissionRule[];
|
|
12
|
+
}
|
|
13
|
+
/** The decision rules make for one call; undefined leaves it to the host. */
|
|
14
|
+
export type RuleVerdict = {
|
|
15
|
+
readonly kind: 'deny' | 'ask' | 'allow';
|
|
16
|
+
readonly rule: string;
|
|
17
|
+
} | undefined;
|
|
18
|
+
/** Evaluate rules against one call. */
|
|
19
|
+
export declare function ruleVerdict(rules: PermissionRuleSet, tool: ForeignTool, cwd: string): RuleVerdict;
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Claude Code permission rules (`permissions.allow` / `ask` / `deny` in
|
|
3
|
+
* settings) evaluated against one tool call, as Claude Code evaluates them:
|
|
4
|
+
* deny, then ask, then allow; the first match decides and rule specificity
|
|
5
|
+
* does not change the order.
|
|
6
|
+
*
|
|
7
|
+
* - A shell call matches a deny or ask rule when any subcommand matches; it
|
|
8
|
+
* matches allow only when every subcommand matches an allow rule.
|
|
9
|
+
* - Deny and ask rules may name a top-level input parameter,
|
|
10
|
+
* `Tool(param:value)` with `*` wildcards; an omitted parameter never matches.
|
|
11
|
+
* A tool's primary content field cannot be matched this way.
|
|
12
|
+
* - Tool-specific specifiers (`WebFetch(domain:…)`) are read before
|
|
13
|
+
* parameter rules.
|
|
14
|
+
* - Allow rules accept a tool-name glob only after a literal `mcp__<server>__`.
|
|
15
|
+
* - A `/path` file rule anchors at the directory of the settings source that
|
|
16
|
+
* defines it; a rule without one anchors there at the working directory.
|
|
17
|
+
* - Shell rules match the argv; a redirection's file is checked as Claude Code
|
|
18
|
+
* checks it (https://code.claude.com/docs/en/permissions#redirections): a
|
|
19
|
+
* file written needs an `Edit` allow rule and one read outside the working
|
|
20
|
+
* directory a `Read` allow rule, a target with `~`, a glob or an expansion is
|
|
21
|
+
* never approved, and `Edit`/`Read` deny rules deny the call.
|
|
22
|
+
* @module @kirkchinese/harness-forge
|
|
23
|
+
*/
|
|
24
|
+
import { isAbsolute, relative, resolve } from 'node:path';
|
|
25
|
+
import { conditionMatches, isFileCall, realPathOf, redirectFiles, shellOf } from './condition.js';
|
|
26
|
+
import { wildcard } from './glob.js';
|
|
27
|
+
import { shellCommands } from './shell-commands.js';
|
|
28
|
+
import { isShellTool } from './vocabulary.js';
|
|
29
|
+
const PRIMARY_FIELDS = new Set(['command', 'file_path', 'path', 'notebook_path', 'url']);
|
|
30
|
+
/**
|
|
31
|
+
* Specifier prefixes a tool reads itself, which are not input parameters
|
|
32
|
+
* (https://code.claude.com/docs/en/permissions#webfetch). `Agent(Name)` and
|
|
33
|
+
* `Skill(skill:…)` need no entry: a name has no colon, and `skill` is a parameter.
|
|
34
|
+
*/
|
|
35
|
+
const TOOL_SPECIFIERS = { WebFetch: ['domain'] };
|
|
36
|
+
function ruleOf(rule) {
|
|
37
|
+
return typeof rule === 'string' ? { text: rule, root: undefined } : { text: rule.rule, root: rule.root };
|
|
38
|
+
}
|
|
39
|
+
/** Evaluate rules against one call. */
|
|
40
|
+
export function ruleVerdict(rules, tool, cwd) {
|
|
41
|
+
const own = callVerdict(rules, tool, cwd);
|
|
42
|
+
if (!isShellTool(tool.dshName))
|
|
43
|
+
return own;
|
|
44
|
+
const files = redirectionsOf(tool);
|
|
45
|
+
// Each redirection target is the file call that would read or write it, with that call's own verdict.
|
|
46
|
+
const parts = [own, ...(files ?? []).flatMap(file => fileToolsOf(file).map(call => targetVerdict(rules, file, call, cwd)))];
|
|
47
|
+
for (const kind of ['deny', 'ask']) {
|
|
48
|
+
const found = parts.find(part => part?.kind === kind);
|
|
49
|
+
if (found !== undefined)
|
|
50
|
+
return found;
|
|
51
|
+
}
|
|
52
|
+
// An unreadable command approves nothing; an allow needs every part allowed.
|
|
53
|
+
return files !== undefined && parts.every(part => part?.kind === 'allow') ? own : undefined;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* One call's verdict: deny, then ask, then allow. A file call's path is
|
|
57
|
+
* allowed only when the path as spelled and its real path both are, each by
|
|
58
|
+
* an allow rule or, with `insideApproves`, by lying inside the working
|
|
59
|
+
* directory (the real path inside the real one); deny and ask rules match
|
|
60
|
+
* either path (see `conditionMatches`).
|
|
61
|
+
*/
|
|
62
|
+
function callVerdict(rules, tool, cwd, insideApproves = false) {
|
|
63
|
+
const deny = rules.deny.map(ruleOf).find(rule => restrictiveMatch(rule, tool, cwd));
|
|
64
|
+
if (deny !== undefined)
|
|
65
|
+
return { kind: 'deny', rule: deny.text };
|
|
66
|
+
const ask = rules.ask.map(ruleOf).find(rule => restrictiveMatch(rule, tool, cwd));
|
|
67
|
+
if (ask !== undefined)
|
|
68
|
+
return { kind: 'ask', rule: ask.text };
|
|
69
|
+
const allowRules = rules.allow.map(ruleOf);
|
|
70
|
+
if (!isFileCall(tool)) {
|
|
71
|
+
const allow = allowMatch(allowRules, tool, cwd);
|
|
72
|
+
return allow === undefined ? undefined : { kind: 'allow', rule: allow.text };
|
|
73
|
+
}
|
|
74
|
+
const target = resolve(cwd, String(tool.input['file_path'] ?? tool.input['path']));
|
|
75
|
+
const approved = (path) => {
|
|
76
|
+
const within = path === 'spelled' ? inside(cwd, target) : inside(realPathOf(resolve(cwd), cwd), realPathOf(target, cwd));
|
|
77
|
+
return insideApproves && within ? INSIDE_WORKING_DIRECTORY : allowMatch(allowRules, tool, cwd, path)?.text;
|
|
78
|
+
};
|
|
79
|
+
const asSpelled = approved('spelled');
|
|
80
|
+
return asSpelled !== undefined && approved('real') !== undefined ? { kind: 'allow', rule: asSpelled } : undefined;
|
|
81
|
+
}
|
|
82
|
+
/** Why a read inside the working directory is approved without a `Read` rule, as in Claude Code. */
|
|
83
|
+
const INSIDE_WORKING_DIRECTORY = 'a read inside the working directory';
|
|
84
|
+
/**
|
|
85
|
+
* A redirection target's verdict, as the file call `call` would get it. A
|
|
86
|
+
* target that is not plain (`~`, a glob, an expansion) is never approved; a
|
|
87
|
+
* read inside the working directory needs no `Read` allow rule.
|
|
88
|
+
*/
|
|
89
|
+
function targetVerdict(rules, file, call, cwd) {
|
|
90
|
+
const verdict = callVerdict(rules, call, cwd, call.name === 'Read');
|
|
91
|
+
return !file.plain && verdict?.kind === 'allow' ? undefined : verdict;
|
|
92
|
+
}
|
|
93
|
+
/** Whether `path` lies in `directory`; a real path that cannot be known (undefined) lies nowhere. */
|
|
94
|
+
function inside(directory, path) {
|
|
95
|
+
if (directory === undefined || path === undefined)
|
|
96
|
+
return false;
|
|
97
|
+
const rel = relative(directory, path);
|
|
98
|
+
return !rel.startsWith('..') && !isAbsolute(rel);
|
|
99
|
+
}
|
|
100
|
+
/** The files a shell call's redirections read or write; undefined when its words cannot be read. */
|
|
101
|
+
function redirectionsOf(tool) {
|
|
102
|
+
const parsed = shellCommands(String(tool.input['command'] ?? ''), shellOf(tool));
|
|
103
|
+
if (parsed === undefined)
|
|
104
|
+
return undefined;
|
|
105
|
+
const files = [];
|
|
106
|
+
for (const command of parsed.commands) {
|
|
107
|
+
const found = redirectFiles(command, shellOf(tool));
|
|
108
|
+
if (found === undefined)
|
|
109
|
+
return undefined;
|
|
110
|
+
files.push(...found);
|
|
111
|
+
}
|
|
112
|
+
return files;
|
|
113
|
+
}
|
|
114
|
+
/** The `Read` and `Write` calls that would read or write a redirection's file. */
|
|
115
|
+
function fileToolsOf(file) {
|
|
116
|
+
return [
|
|
117
|
+
...file.reads ? [{ dshName: 'read', name: 'Read', aliases: ['Read'], input: { file_path: file.path } }] : [],
|
|
118
|
+
...file.writes ? [{ dshName: 'write', name: 'Write', aliases: ['Write'], input: { file_path: file.path } }] : [],
|
|
119
|
+
];
|
|
120
|
+
}
|
|
121
|
+
function split(rule) {
|
|
122
|
+
const match = /^\s*([A-Za-z0-9_\-:.*]+?)\s*(?:\((.*)\))?\s*$/su.exec(rule);
|
|
123
|
+
return match === null ? undefined : { name: match[1] ?? '', specifier: match[2] };
|
|
124
|
+
}
|
|
125
|
+
/** A deny or ask rule: tool-name globs, parameter rules, then the `if`-rule match. */
|
|
126
|
+
function restrictiveMatch({ text: rule, root }, tool, cwd) {
|
|
127
|
+
const parts = split(rule);
|
|
128
|
+
if (parts === undefined)
|
|
129
|
+
return false;
|
|
130
|
+
const { name, specifier } = parts;
|
|
131
|
+
if (name.includes('*') && !name.startsWith('mcp__')) {
|
|
132
|
+
// Over budget a restricting rule matches.
|
|
133
|
+
if (!(globName(name).match(tool.name) ?? true) && !tool.aliases.some(alias => globName(name).match(alias) ?? true))
|
|
134
|
+
return false;
|
|
135
|
+
return specifier === undefined || specifier.trim() === '' || specifier.trim() === '*';
|
|
136
|
+
}
|
|
137
|
+
if (name.startsWith('mcp__') && name.includes('*')) {
|
|
138
|
+
// `mcp__*`, `mcp__server__*`, `mcp__server__get_*`.
|
|
139
|
+
return specifier === undefined && (globName(name).match(tool.name) ?? true);
|
|
140
|
+
}
|
|
141
|
+
const parameter = specifier === undefined ? undefined : /^\s*([A-Za-z_][A-Za-z0-9_]*)\s*:\s*(.*)$/su.exec(specifier);
|
|
142
|
+
const toolSpecific = parameter !== null && parameter !== undefined && TOOL_SPECIFIERS[name]?.includes(parameter[1] ?? '') === true;
|
|
143
|
+
if (parameter !== null && parameter !== undefined && !toolSpecific && !specifier.trim().endsWith(':*')) {
|
|
144
|
+
const key = parameter[1] ?? '';
|
|
145
|
+
if (Object.hasOwn(tool.input, key) || !isShellTool(tool.dshName)) {
|
|
146
|
+
if (PRIMARY_FIELDS.has(key))
|
|
147
|
+
return false;
|
|
148
|
+
if (!conditionMatches(name, tool, cwd, true, { root, restricts: true }))
|
|
149
|
+
return false;
|
|
150
|
+
const value = tool.input[key];
|
|
151
|
+
if (value === undefined || (typeof value === 'object' && value !== null))
|
|
152
|
+
return false;
|
|
153
|
+
return globName((parameter[2] ?? '').trimEnd()).match(String(value)) ?? true;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return conditionMatches(rule, tool, cwd, true, { root, restricts: true });
|
|
157
|
+
}
|
|
158
|
+
/** The allow rule that approves the call, if any; `path` picks the path a file rule matches (see `RuleUse.path`). */
|
|
159
|
+
function allowMatch(rules, tool, cwd, path) {
|
|
160
|
+
const usable = rules.filter(({ text: rule }) => {
|
|
161
|
+
const parts = split(rule);
|
|
162
|
+
if (parts === undefined)
|
|
163
|
+
return false;
|
|
164
|
+
// An unanchored tool-name glob never auto-approves.
|
|
165
|
+
if (parts.name.includes('*'))
|
|
166
|
+
return /^mcp__[^*_][^*]*?__/u.test(parts.name);
|
|
167
|
+
return true;
|
|
168
|
+
});
|
|
169
|
+
if (usable.length === 0)
|
|
170
|
+
return undefined;
|
|
171
|
+
if (isShellTool(tool.dshName)) {
|
|
172
|
+
const whole = usable.find((rule) => {
|
|
173
|
+
const parts = split(rule.text);
|
|
174
|
+
return (parts.specifier === undefined || parts.specifier.trim() === '*') && conditionMatches(parts.name, tool, cwd, false);
|
|
175
|
+
});
|
|
176
|
+
if (whole !== undefined)
|
|
177
|
+
return whole;
|
|
178
|
+
const parsed = shellCommands(String(tool.input['command'] ?? ''), shellOf(tool));
|
|
179
|
+
if (parsed === undefined || parsed.dynamic || parsed.commands.length === 0)
|
|
180
|
+
return undefined;
|
|
181
|
+
let first;
|
|
182
|
+
for (const command of parsed.commands) {
|
|
183
|
+
const single = { ...tool, input: { ...tool.input, command } };
|
|
184
|
+
const rule = usable.find(candidate => conditionMatches(candidate.text, single, cwd, false));
|
|
185
|
+
if (rule === undefined)
|
|
186
|
+
return undefined;
|
|
187
|
+
first ??= rule;
|
|
188
|
+
}
|
|
189
|
+
return first;
|
|
190
|
+
}
|
|
191
|
+
return usable.find(({ text: rule, root }) => {
|
|
192
|
+
const parts = split(rule);
|
|
193
|
+
if (parts.name.startsWith('mcp__')) {
|
|
194
|
+
// An MCP allow rule with a specifier matches no call.
|
|
195
|
+
return parts.specifier === undefined && (parts.name.includes('*') ? globName(parts.name).match(tool.name) ?? false : conditionMatches(rule, tool, cwd, false));
|
|
196
|
+
}
|
|
197
|
+
return conditionMatches(rule, tool, cwd, false, { ...(root !== undefined ? { root } : {}), ...(path !== undefined ? { path } : {}) });
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
function globName(pattern) {
|
|
201
|
+
return wildcard(pattern);
|
|
202
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PowerShell's default aliases, and the cmdlet (or function) each stands for,
|
|
3
|
+
* from the built-in alias list `BuiltInAliases` of PowerShell's
|
|
4
|
+
* InitialSessionState (https://github.com/PowerShell/PowerShell/blob/master/src/System.Management.Automation/engine/InitialSessionState.cs),
|
|
5
|
+
* which the docs summarise (https://learn.microsoft.com/powershell/scripting/learn/shell/using-aliases and
|
|
6
|
+
* https://learn.microsoft.com/powershell/scripting/whats-new/unix-support#aliases-not-available-on-linux-or-macos).
|
|
7
|
+
* Claude Code normalises these before matching a PowerShell rule
|
|
8
|
+
* (https://code.claude.com/docs/en/permissions#powershell): `PowerShell(Get-ChildItem *)` matches `gci`, `ls` and `dir`.
|
|
9
|
+
* The one table Harness Forge reads PowerShell command names through.
|
|
10
|
+
* @module @kirkchinese/harness-forge
|
|
11
|
+
*/
|
|
12
|
+
/**
|
|
13
|
+
* Which aliases to read a command name through: `all` (every table, on every platform: what a restricting
|
|
14
|
+
* rule and a classifier use, so an alias can never hide a command) or `here` (only those PowerShell 7
|
|
15
|
+
* defines on this platform: what an approving rule uses, so `PowerShell(Remove-Item *)` approves no native `rm`).
|
|
16
|
+
*/
|
|
17
|
+
export type PowerShellAliases = 'all' | 'here';
|
|
18
|
+
/** A PowerShell command name in lower case, an alias replaced by its cmdlet. */
|
|
19
|
+
export declare function powershellCommand(name: string, aliases: PowerShellAliases): string;
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PowerShell's default aliases, and the cmdlet (or function) each stands for,
|
|
3
|
+
* from the built-in alias list `BuiltInAliases` of PowerShell's
|
|
4
|
+
* InitialSessionState (https://github.com/PowerShell/PowerShell/blob/master/src/System.Management.Automation/engine/InitialSessionState.cs),
|
|
5
|
+
* which the docs summarise (https://learn.microsoft.com/powershell/scripting/learn/shell/using-aliases and
|
|
6
|
+
* https://learn.microsoft.com/powershell/scripting/whats-new/unix-support#aliases-not-available-on-linux-or-macos).
|
|
7
|
+
* Claude Code normalises these before matching a PowerShell rule
|
|
8
|
+
* (https://code.claude.com/docs/en/permissions#powershell): `PowerShell(Get-ChildItem *)` matches `gci`, `ls` and `dir`.
|
|
9
|
+
* The one table Harness Forge reads PowerShell command names through.
|
|
10
|
+
* @module @kirkchinese/harness-forge
|
|
11
|
+
*/
|
|
12
|
+
/** Aliases PowerShell defines on every platform. */
|
|
13
|
+
const EVERYWHERE = {
|
|
14
|
+
foreach: 'foreach-object', '%': 'foreach-object', where: 'where-object', '?': 'where-object', clc: 'clear-content', cli: 'clear-item',
|
|
15
|
+
clp: 'clear-itemproperty', clv: 'clear-variable', cpi: 'copy-item', cvpa: 'convert-path', dbp: 'disable-psbreakpoint', ebp: 'enable-psbreakpoint',
|
|
16
|
+
epal: 'export-alias', epcsv: 'export-csv', fl: 'format-list', ft: 'format-table', fw: 'format-wide', gal: 'get-alias', gbp: 'get-psbreakpoint',
|
|
17
|
+
gc: 'get-content', gci: 'get-childitem', gcm: 'get-command', gdr: 'get-psdrive', gcs: 'get-pscallstack', ghy: 'get-history', gi: 'get-item',
|
|
18
|
+
gl: 'get-location', gm: 'get-member', gmo: 'get-module', gp: 'get-itemproperty', gpv: 'get-itempropertyvalue', gps: 'get-process',
|
|
19
|
+
group: 'group-object', gu: 'get-unique', gv: 'get-variable', iex: 'invoke-expression', ihy: 'invoke-history', ii: 'invoke-item',
|
|
20
|
+
ipmo: 'import-module', ipal: 'import-alias', ipcsv: 'import-csv', measure: 'measure-object', mi: 'move-item', mp: 'move-itemproperty',
|
|
21
|
+
nal: 'new-alias', ndr: 'new-psdrive', ni: 'new-item', nv: 'new-variable', nmo: 'new-module', oh: 'out-host', rbp: 'remove-psbreakpoint',
|
|
22
|
+
rdr: 'remove-psdrive', ri: 'remove-item', rni: 'rename-item', rnp: 'rename-itemproperty', rp: 'remove-itemproperty', rmo: 'remove-module',
|
|
23
|
+
rv: 'remove-variable', gerr: 'get-error', rvpa: 'resolve-path', sal: 'set-alias', sbp: 'set-psbreakpoint', select: 'select-object', si: 'set-item',
|
|
24
|
+
sl: 'set-location', sp: 'set-itemproperty', saps: 'start-process', spps: 'stop-process', sv: 'set-variable', irm: 'invoke-restmethod',
|
|
25
|
+
iwr: 'invoke-webrequest', cd: 'set-location', dir: 'get-childitem', echo: 'write-output', fc: 'format-custom', pwd: 'get-location',
|
|
26
|
+
type: 'get-content', h: 'get-history', history: 'get-history', md: 'mkdir', popd: 'pop-location', pushd: 'push-location', r: 'invoke-history',
|
|
27
|
+
cls: 'clear-host', chdir: 'set-location', copy: 'copy-item', del: 'remove-item', erase: 'remove-item', move: 'move-item', rd: 'remove-item',
|
|
28
|
+
ren: 'rename-item', set: 'set-variable', icm: 'invoke-command', clhy: 'clear-history', gjb: 'get-job', rcjb: 'receive-job', rjb: 'remove-job',
|
|
29
|
+
sajb: 'start-job', spjb: 'stop-job', wjb: 'wait-job', nsn: 'new-pssession', gsn: 'get-pssession', rsn: 'remove-pssession', etsn: 'enter-pssession',
|
|
30
|
+
rcsn: 'receive-pssession', exsn: 'exit-pssession', sls: 'select-string',
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* Aliases PowerShell 7 defines on Windows only (`#if !UNIX`): on Linux and macOS it leaves them out so the
|
|
34
|
+
* native programs of those names run (`ls`, `cp`, `mv`, `rm`, `cat`, `ps`, `kill`, `sleep`, `sort` …).
|
|
35
|
+
*/
|
|
36
|
+
const WINDOWS = {
|
|
37
|
+
ac: 'add-content', clear: 'clear-host', compare: 'compare-object', cpp: 'copy-itemproperty', diff: 'compare-object', gsv: 'get-service',
|
|
38
|
+
sleep: 'start-sleep', sort: 'sort-object', start: 'start-process', sasv: 'start-service', spsv: 'stop-service', tee: 'tee-object',
|
|
39
|
+
write: 'write-output', cat: 'get-content', cp: 'copy-item', ls: 'get-childitem', man: 'help', mount: 'new-psdrive', mv: 'move-item',
|
|
40
|
+
ps: 'get-process', rm: 'remove-item', rmdir: 'remove-item', cnsn: 'connect-pssession', dnsn: 'disconnect-pssession', ogv: 'out-gridview',
|
|
41
|
+
shcm: 'show-command', kill: 'stop-process',
|
|
42
|
+
};
|
|
43
|
+
/** Aliases only Windows PowerShell 5.1 defines (`#if !CORECLR`); PowerShell 7 has none of them. */
|
|
44
|
+
const WINDOWS_POWERSHELL = {
|
|
45
|
+
gwmi: 'get-wmiobject', iwmi: 'invoke-wmimethod', ise: 'powershell_ise.exe', rwmi: 'remove-wmiobject', sc: 'set-content', swmi: 'set-wmiinstance',
|
|
46
|
+
trcm: 'trace-command', sujb: 'suspend-job', rujb: 'resume-job', npssc: 'new-pssessionconfigurationfile', ipsn: 'import-pssession',
|
|
47
|
+
epsn: 'export-pssession',
|
|
48
|
+
};
|
|
49
|
+
/** A PowerShell command name in lower case, an alias replaced by its cmdlet. */
|
|
50
|
+
export function powershellCommand(name, aliases) {
|
|
51
|
+
const lower = name.toLowerCase();
|
|
52
|
+
const tables = aliases === 'all' ? [EVERYWHERE, WINDOWS, WINDOWS_POWERSHELL] : process.platform === 'win32' ? [EVERYWHERE, WINDOWS] : [EVERYWHERE];
|
|
53
|
+
for (const table of tables) {
|
|
54
|
+
if (Object.hasOwn(table, lower))
|
|
55
|
+
return table[lower];
|
|
56
|
+
}
|
|
57
|
+
return lower;
|
|
58
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Run one hook process the way Claude Code does: JSON on stdin, output read
|
|
3
|
+
* until shortly after the process itself exits (a background child that
|
|
4
|
+
* keeps the pipes open does not hold the hook), an optional timeout, and
|
|
5
|
+
* cancellation through a signal. A timeout or cancellation ends the hook's
|
|
6
|
+
* whole process tree, not only the process that was started.
|
|
7
|
+
*
|
|
8
|
+
* Stdin is a file holding the input, not a pipe, when one can be made (see
|
|
9
|
+
* `stdinFile`): a hook that reads it synchronously at once (`readFileSync(0)`)
|
|
10
|
+
* then always gets all of it, where a socket could answer EAGAIN before the
|
|
11
|
+
* input has arrived. When no such file can be made, the input goes through a pipe.
|
|
12
|
+
* @module @kirkchinese/harness-forge
|
|
13
|
+
*/
|
|
14
|
+
import { spawn } from 'node:child_process';
|
|
15
|
+
/** One process to run. */
|
|
16
|
+
export interface ProcessSpec {
|
|
17
|
+
readonly file: string;
|
|
18
|
+
readonly args: readonly string[];
|
|
19
|
+
readonly cwd: string;
|
|
20
|
+
readonly env: NodeJS.ProcessEnv;
|
|
21
|
+
readonly stdin: string;
|
|
22
|
+
/** A private directory for the stdin file; default: one under the system temporary directory. */
|
|
23
|
+
readonly stdinDir?: string;
|
|
24
|
+
/** The data root `stdinDir` lies in: no folder between them may be a symbolic link. */
|
|
25
|
+
readonly stdinRoot?: string;
|
|
26
|
+
/** Told of a stdin file that could not be removed (default: a process warning). */
|
|
27
|
+
readonly onLeftover?: (path: string) => void;
|
|
28
|
+
/** Undefined runs without a timeout. */
|
|
29
|
+
readonly timeoutMs?: number;
|
|
30
|
+
readonly signal?: AbortSignal;
|
|
31
|
+
}
|
|
32
|
+
/** What one run produced. */
|
|
33
|
+
export interface ProcessOutcome {
|
|
34
|
+
/** Exit code; undefined when the process could not start, timed out or was cancelled. */
|
|
35
|
+
readonly exitCode?: number;
|
|
36
|
+
/** Why the process could not start. */
|
|
37
|
+
readonly startError?: string;
|
|
38
|
+
readonly timedOut: boolean;
|
|
39
|
+
readonly cancelled: boolean;
|
|
40
|
+
readonly stdout: string;
|
|
41
|
+
readonly stderr: string;
|
|
42
|
+
/** The process exited while something it started still held its output open. */
|
|
43
|
+
readonly suspectCapture: boolean;
|
|
44
|
+
readonly durationMs: number;
|
|
45
|
+
}
|
|
46
|
+
/** The command that ends a process and everything it started on Windows (`taskkill /T /F`). */
|
|
47
|
+
export declare function treeKillCommand(pid: number, platform?: NodeJS.Platform): {
|
|
48
|
+
file: string;
|
|
49
|
+
args: string[];
|
|
50
|
+
} | undefined;
|
|
51
|
+
/**
|
|
52
|
+
* End a spawned process and its descendants. On POSIX the process leads its own
|
|
53
|
+
* group (it was spawned `detached`), so the group is killed; on Windows
|
|
54
|
+
* `taskkill /T /F` walks the tree.
|
|
55
|
+
*/
|
|
56
|
+
export declare function killProcessTree(child: ReturnType<typeof spawn>, platform?: NodeJS.Platform): void;
|
|
57
|
+
/**
|
|
58
|
+
* Remove a file Windows still holds open (a child that has not let go of it),
|
|
59
|
+
* trying again a bounded number of times.
|
|
60
|
+
* @returns whether it is gone.
|
|
61
|
+
*/
|
|
62
|
+
export declare function removeWithRetries(path: string, attempts?: number, delayMs?: number, remove?: (path: string) => boolean): Promise<boolean>;
|
|
63
|
+
/** Spawn without a shell and collect the outcome. Never rejects. */
|
|
64
|
+
export declare function runProcess(spec: ProcessSpec): Promise<ProcessOutcome>;
|