@kirkchinese/harness-forge 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/README.md +4 -0
  2. package/docs/DETAIL.zh.md +47 -0
  3. package/lib/agents/presets.d.ts +7 -0
  4. package/lib/agents/presets.js +11 -1
  5. package/lib/agents/profiles.js +3 -2
  6. package/lib/agents/row.js +3 -1
  7. package/lib/client/paths.d.ts +12 -0
  8. package/lib/client/paths.js +68 -0
  9. package/lib/client/typert.d.ts +12 -1
  10. package/lib/client/typert.js +54 -6
  11. package/lib/client.js +1593 -270
  12. package/lib/commands/row.js +1 -1
  13. package/lib/context/instructions.js +5 -5
  14. package/lib/dsh/host.d.ts +3 -0
  15. package/lib/dsh/host.js +3 -0
  16. package/lib/forge/contract.d.ts +42 -2
  17. package/lib/forge/contract.js +3 -1
  18. package/lib/forge/follow.d.ts +30 -0
  19. package/lib/forge/follow.js +73 -0
  20. package/lib/forge/ledger.d.ts +70 -7
  21. package/lib/forge/ledger.js +314 -42
  22. package/lib/forge/projects.d.ts +5 -2
  23. package/lib/forge/projects.js +23 -16
  24. package/lib/forge/remote/archive.d.ts +65 -0
  25. package/lib/forge/remote/archive.js +565 -0
  26. package/lib/forge/remote/code-parts.d.ts +18 -0
  27. package/lib/forge/remote/code-parts.js +76 -0
  28. package/lib/forge/remote/fetch.d.ts +265 -0
  29. package/lib/forge/remote/fetch.js +1133 -0
  30. package/lib/forge/remote/service.d.ts +256 -0
  31. package/lib/forge/remote/service.js +868 -0
  32. package/lib/forge/service.d.ts +19 -9
  33. package/lib/forge/service.js +47 -31
  34. package/lib/forge/settings.d.ts +5 -3
  35. package/lib/forge/settings.js +11 -4
  36. package/lib/forge/state.d.ts +60 -0
  37. package/lib/forge/state.js +174 -58
  38. package/lib/hooks/broker/engine.js +2 -8
  39. package/lib/hooks/broker/session-events.d.ts +5 -0
  40. package/lib/hooks/broker/session-events.js +12 -3
  41. package/lib/hooks/broker/types.d.ts +7 -5
  42. package/lib/hooks/condition.d.ts +78 -2
  43. package/lib/hooks/condition.js +494 -73
  44. package/lib/hooks/config.d.ts +1 -1
  45. package/lib/hooks/config.js +4 -0
  46. package/lib/hooks/glob.d.ts +41 -0
  47. package/lib/hooks/glob.js +114 -0
  48. package/lib/hooks/permissions.d.ts +8 -3
  49. package/lib/hooks/permissions.js +119 -26
  50. package/lib/hooks/powershell-aliases.d.ts +19 -0
  51. package/lib/hooks/powershell-aliases.js +58 -0
  52. package/lib/hooks/process.d.ts +17 -0
  53. package/lib/hooks/process.js +156 -1
  54. package/lib/hooks/row.js +2 -0
  55. package/lib/hooks/runner.d.ts +17 -4
  56. package/lib/hooks/runner.js +42 -13
  57. package/lib/hooks/shell-commands.d.ts +10 -1
  58. package/lib/hooks/shell-commands.js +74 -10
  59. package/lib/hooks/shell.d.ts +3 -2
  60. package/lib/hooks/shell.js +5 -2
  61. package/lib/hooks/vocabulary.js +3 -1
  62. package/lib/mcp/catalog.d.ts +5 -2
  63. package/lib/mcp/catalog.js +18 -10
  64. package/lib/mcp/mount.d.ts +40 -2
  65. package/lib/mcp/mount.js +131 -31
  66. package/lib/mcp/policy.d.ts +42 -0
  67. package/lib/mcp/policy.js +43 -0
  68. package/lib/mcp/remote.js +5 -15
  69. package/lib/mcp/row.js +111 -17
  70. package/lib/mods/loader.js +4 -0
  71. package/lib/mods/service/turns.d.ts +8 -7
  72. package/lib/mods/service/turns.js +10 -35
  73. package/lib/opencode/bun.js +14 -2
  74. package/lib/opencode/row.d.ts +14 -1
  75. package/lib/opencode/row.js +38 -20
  76. package/lib/opencode/runtime/server.js +2 -1
  77. package/lib/porting/adapter-paths.d.ts +13 -0
  78. package/lib/porting/adapter-paths.js +120 -0
  79. package/lib/porting/port-gap.d.ts +10 -4
  80. package/lib/porting/port-gap.js +43 -7
  81. package/lib/porting/prompt.js +9 -7
  82. package/lib/porting/row.js +7 -5
  83. package/lib/porting/verify-port.d.ts +3 -10
  84. package/lib/porting/verify-port.js +12 -34
  85. package/lib/sessions/chat-import.d.ts +48 -0
  86. package/lib/sessions/chat-import.js +44 -0
  87. package/lib/sessions/claude.d.ts +16 -10
  88. package/lib/sessions/claude.js +76 -55
  89. package/lib/sessions/codex-discover.d.ts +34 -0
  90. package/lib/sessions/codex-discover.js +205 -0
  91. package/lib/sessions/codex-meta.d.ts +63 -0
  92. package/lib/sessions/codex-meta.js +148 -0
  93. package/lib/sessions/codex-text.d.ts +9 -0
  94. package/lib/sessions/codex-text.js +44 -0
  95. package/lib/sessions/codex.d.ts +34 -22
  96. package/lib/sessions/codex.js +150 -183
  97. package/lib/sessions/opencode.d.ts +15 -9
  98. package/lib/sessions/opencode.js +77 -58
  99. package/lib/sessions/persist.d.ts +162 -0
  100. package/lib/sessions/persist.js +377 -0
  101. package/lib/sessions/row.d.ts +2 -1
  102. package/lib/sessions/row.js +75 -9
  103. package/lib/sessions/turns.d.ts +31 -0
  104. package/lib/sessions/turns.js +63 -0
  105. package/lib/sessions/zstd.d.ts +15 -0
  106. package/lib/sessions/zstd.js +152 -0
  107. package/lib/shared/render.d.ts +30 -1
  108. package/lib/shared/render.js +813 -48
  109. package/lib/skills/provider.d.ts +2 -0
  110. package/lib/skills/provider.js +8 -2
  111. package/lib/skills/row.js +1 -1
  112. package/lib/workbench/adapter-coverage.d.ts +20 -2
  113. package/lib/workbench/adapter-coverage.js +46 -7
  114. package/lib/workbench/overview.d.ts +77 -27
  115. package/lib/workbench/overview.js +99 -12
  116. package/lib/workbench/remote.d.ts +64 -21
  117. package/lib/workbench/remote.js +181 -42
  118. package/lib/workbench/settings.d.ts +5 -1
  119. package/lib/workbench/settings.js +6 -2
  120. package/lib/workbench/workbench.d.ts +34 -4
  121. package/lib/workbench/workbench.js +147 -46
  122. package/locale/zh.json +2 -1
  123. package/package.json +3 -2
  124. package/lib/forge/marketplace-install.d.ts +0 -3
  125. package/lib/forge/marketplace-install.js +0 -64
@@ -1,4 +1,4 @@
1
- import type { ForeignPlugin } from '@kirkchinese/harness-forge-core';
1
+ import { type ForeignPlugin } from '@kirkchinese/harness-forge-core';
2
2
  /** Fields every handler type accepts. */
3
3
  interface HandlerCommon {
4
4
  /** The `if` permission rule. */
@@ -6,8 +6,12 @@
6
6
  * @module @kirkchinese/harness-forge
7
7
  */
8
8
  import { readFileSync } from 'node:fs';
9
+ import { LEADS_TO_SHARE, leadsToShare } from '@kirkchinese/harness-forge-core';
9
10
  /** Read a hooks file or settings file. */
10
11
  export function readHookTable(path) {
12
+ // A file on a link to a network share it is not on fails as unreadable (see `leadsToShare`).
13
+ if (leadsToShare(path))
14
+ throw new Error(`${path} ${LEADS_TO_SHARE}`);
11
15
  return parseHookTable(JSON.parse(readFileSync(path, 'utf8').replace(/^\uFEFF/u, '')));
12
16
  }
13
17
  /**
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Wildcard patterns matched in O(text × pattern) time, within a work budget.
3
+ * A wildcard rule turned into a regular expression (`*` → `.*`) backtracks
4
+ * polynomially in the number of wildcards, and rules and the text they match
5
+ * both come from outside; this matcher walks every reachable pattern position
6
+ * at once instead. That still runs on the synchronous permission path, so a
7
+ * pattern, text or text × pattern product beyond the budget below is not
8
+ * matched at all and answers undefined: the caller decides which way an
9
+ * unknown answer falls (deny, ask and hook conditions match: they fail closed).
10
+ * @module @kirkchinese/harness-forge
11
+ */
12
+ type Test = (char: string) => boolean;
13
+ /** At most this many pattern positions… */
14
+ export declare const GLOB_PATTERN_LIMIT = 1000;
15
+ /** …this many characters of text… */
16
+ export declare const GLOB_TEXT_LIMIT = 100000;
17
+ /** …and this much work (text × pattern) for one match. */
18
+ export declare const GLOB_WORK_LIMIT = 4000000;
19
+ /** A pattern built piece by piece; `test` matches a whole text. */
20
+ export declare class Glob {
21
+ private readonly nodes;
22
+ /** Set for a pattern refused before it was built: it matches nothing and answers undefined. */
23
+ private oversized;
24
+ /** A pattern too long to build: every match is undefined. Check {@link tooLong} before building one. */
25
+ static refused(): Glob;
26
+ /** Whether a pattern of this text is beyond the budget, known before anything is built (no pattern character makes more than one position). */
27
+ static tooLong(pattern: string): boolean;
28
+ /** These characters, exactly. */
29
+ literal(text: string): this;
30
+ /** One character that passes `test`. */
31
+ one(test?: Test): this;
32
+ /** Any number of characters that pass `test`. */
33
+ many(test?: Test): this;
34
+ /** What `build` adds, or nothing. */
35
+ optional(build: (glob: this) => void): this;
36
+ /** Whether the whole text matches; undefined when the pattern or the text is beyond the budget. */
37
+ match(text: string): boolean | undefined;
38
+ }
39
+ /** `*` any run of characters, everything else literal. */
40
+ export declare function wildcard(pattern: string, star?: Test): Glob;
41
+ export {};
@@ -0,0 +1,114 @@
1
+ /**
2
+ * Wildcard patterns matched in O(text × pattern) time, within a work budget.
3
+ * A wildcard rule turned into a regular expression (`*` → `.*`) backtracks
4
+ * polynomially in the number of wildcards, and rules and the text they match
5
+ * both come from outside; this matcher walks every reachable pattern position
6
+ * at once instead. That still runs on the synchronous permission path, so a
7
+ * pattern, text or text × pattern product beyond the budget below is not
8
+ * matched at all and answers undefined: the caller decides which way an
9
+ * unknown answer falls (deny, ask and hook conditions match: they fail closed).
10
+ * @module @kirkchinese/harness-forge
11
+ */
12
+ const ANY = () => true;
13
+ /** At most this many pattern positions… */
14
+ export const GLOB_PATTERN_LIMIT = 1_000;
15
+ /** …this many characters of text… */
16
+ export const GLOB_TEXT_LIMIT = 100_000;
17
+ /** …and this much work (text × pattern) for one match. */
18
+ export const GLOB_WORK_LIMIT = 4_000_000;
19
+ /** A pattern built piece by piece; `test` matches a whole text. */
20
+ export class Glob {
21
+ nodes = [];
22
+ /** Set for a pattern refused before it was built: it matches nothing and answers undefined. */
23
+ oversized = false;
24
+ /** A pattern too long to build: every match is undefined. Check {@link tooLong} before building one. */
25
+ static refused() {
26
+ const glob = new Glob();
27
+ glob.oversized = true;
28
+ return glob;
29
+ }
30
+ /** Whether a pattern of this text is beyond the budget, known before anything is built (no pattern character makes more than one position). */
31
+ static tooLong(pattern) {
32
+ return pattern.length > GLOB_PATTERN_LIMIT;
33
+ }
34
+ /** These characters, exactly. */
35
+ literal(text) {
36
+ for (const char of text)
37
+ this.nodes.push({ kind: 'one', test: other => other === char });
38
+ return this;
39
+ }
40
+ /** One character that passes `test`. */
41
+ one(test = ANY) {
42
+ this.nodes.push({ kind: 'one', test });
43
+ return this;
44
+ }
45
+ /** Any number of characters that pass `test`. */
46
+ many(test = ANY) {
47
+ this.nodes.push({ kind: 'many', test });
48
+ return this;
49
+ }
50
+ /** What `build` adds, or nothing. */
51
+ optional(build) {
52
+ const skip = { kind: 'skip', to: 0 };
53
+ this.nodes.push(skip);
54
+ build(this);
55
+ skip.to = this.nodes.length;
56
+ return this;
57
+ }
58
+ /** Whether the whole text matches; undefined when the pattern or the text is beyond the budget. */
59
+ match(text) {
60
+ const end = this.nodes.length;
61
+ if (this.oversized || end > GLOB_PATTERN_LIMIT || text.length > GLOB_TEXT_LIMIT || (end + 1) * text.length > GLOB_WORK_LIMIT)
62
+ return undefined;
63
+ let current = new Uint8Array(end + 1);
64
+ let next = new Uint8Array(end + 1);
65
+ const add = (set, start) => {
66
+ const stack = [start];
67
+ while (stack.length > 0) {
68
+ const at = stack.pop() ?? end;
69
+ if (set[at] === 1)
70
+ continue;
71
+ set[at] = 1;
72
+ const node = this.nodes[at];
73
+ if (node === undefined)
74
+ continue;
75
+ if (node.kind === 'skip')
76
+ stack.push(at + 1, node.to);
77
+ else if (node.kind === 'many')
78
+ stack.push(at + 1);
79
+ }
80
+ };
81
+ add(current, 0);
82
+ for (const char of text) {
83
+ next.fill(0);
84
+ let alive = false;
85
+ for (let at = 0; at < end; at++) {
86
+ if (current[at] !== 1)
87
+ continue;
88
+ const node = this.nodes[at];
89
+ if (node === undefined || node.kind === 'skip' || !node.test(char))
90
+ continue;
91
+ add(next, node.kind === 'one' ? at + 1 : at);
92
+ alive = true;
93
+ }
94
+ if (!alive)
95
+ return false;
96
+ const swap = current;
97
+ current = next;
98
+ next = swap;
99
+ }
100
+ return current[end] === 1;
101
+ }
102
+ }
103
+ /** `*` any run of characters, everything else literal. */
104
+ export function wildcard(pattern, star = ANY) {
105
+ if (Glob.tooLong(pattern))
106
+ return Glob.refused();
107
+ const glob = new Glob();
108
+ pattern.split('*').forEach((part, index) => {
109
+ if (index > 0)
110
+ glob.many(star);
111
+ glob.literal(part);
112
+ });
113
+ return glob;
114
+ }
@@ -1,9 +1,14 @@
1
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
+ };
2
7
  /** Rules in Claude Code's syntax. */
3
8
  export interface PermissionRuleSet {
4
- readonly allow: readonly string[];
5
- readonly deny: readonly string[];
6
- readonly ask: readonly string[];
9
+ readonly allow: readonly PermissionRule[];
10
+ readonly deny: readonly PermissionRule[];
11
+ readonly ask: readonly PermissionRule[];
7
12
  }
8
13
  /** The decision rules make for one call; undefined leaves it to the host. */
9
14
  export type RuleVerdict = {
@@ -9,62 +9,155 @@
9
9
  * - Deny and ask rules may name a top-level input parameter,
10
10
  * `Tool(param:value)` with `*` wildcards; an omitted parameter never matches.
11
11
  * A tool's primary content field cannot be matched this way.
12
+ * - Tool-specific specifiers (`WebFetch(domain:…)`) are read before
13
+ * parameter rules.
12
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.
13
22
  * @module @kirkchinese/harness-forge
14
23
  */
15
- import { conditionMatches } from './condition.js';
24
+ import { isAbsolute, relative, resolve } from 'node:path';
25
+ import { conditionMatches, isFileCall, realPathOf, redirectFiles, shellOf } from './condition.js';
26
+ import { wildcard } from './glob.js';
16
27
  import { shellCommands } from './shell-commands.js';
17
28
  import { isShellTool } from './vocabulary.js';
18
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
+ }
19
39
  /** Evaluate rules against one call. */
20
40
  export function ruleVerdict(rules, tool, cwd) {
21
- const deny = rules.deny.find(rule => restrictiveMatch(rule, 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));
22
64
  if (deny !== undefined)
23
- return { kind: 'deny', rule: deny };
24
- const ask = rules.ask.find(rule => restrictiveMatch(rule, tool, cwd));
65
+ return { kind: 'deny', rule: deny.text };
66
+ const ask = rules.ask.map(ruleOf).find(rule => restrictiveMatch(rule, tool, cwd));
25
67
  if (ask !== undefined)
26
- return { kind: 'ask', rule: ask };
27
- const allow = allowMatch(rules.allow, tool, cwd);
28
- return allow === undefined ? undefined : { kind: 'allow', rule: allow };
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
+ ];
29
120
  }
30
121
  function split(rule) {
31
122
  const match = /^\s*([A-Za-z0-9_\-:.*]+?)\s*(?:\((.*)\))?\s*$/su.exec(rule);
32
123
  return match === null ? undefined : { name: match[1] ?? '', specifier: match[2] };
33
124
  }
34
125
  /** A deny or ask rule: tool-name globs, parameter rules, then the `if`-rule match. */
35
- function restrictiveMatch(rule, tool, cwd) {
126
+ function restrictiveMatch({ text: rule, root }, tool, cwd) {
36
127
  const parts = split(rule);
37
128
  if (parts === undefined)
38
129
  return false;
39
130
  const { name, specifier } = parts;
40
131
  if (name.includes('*') && !name.startsWith('mcp__')) {
41
- if (!globName(name).test(tool.name) && !tool.aliases.some(alias => globName(name).test(alias)))
132
+ // Over budget a restricting rule matches.
133
+ if (!(globName(name).match(tool.name) ?? true) && !tool.aliases.some(alias => globName(name).match(alias) ?? true))
42
134
  return false;
43
135
  return specifier === undefined || specifier.trim() === '' || specifier.trim() === '*';
44
136
  }
45
137
  if (name.startsWith('mcp__') && name.includes('*')) {
46
138
  // `mcp__*`, `mcp__server__*`, `mcp__server__get_*`.
47
- return specifier === undefined && globName(name).test(tool.name);
139
+ return specifier === undefined && (globName(name).match(tool.name) ?? true);
48
140
  }
49
- const parameter = specifier === undefined ? undefined : /^\s*([A-Za-z_][A-Za-z0-9_]*)\s*:\s*(.*?)\s*$/su.exec(specifier);
50
- if (parameter !== null && parameter !== undefined && !specifier.trim().endsWith(':*')) {
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(':*')) {
51
144
  const key = parameter[1] ?? '';
52
145
  if (Object.hasOwn(tool.input, key) || !isShellTool(tool.dshName)) {
53
146
  if (PRIMARY_FIELDS.has(key))
54
147
  return false;
55
- if (!conditionMatches(name, tool, cwd))
148
+ if (!conditionMatches(name, tool, cwd, true, { root, restricts: true }))
56
149
  return false;
57
150
  const value = tool.input[key];
58
151
  if (value === undefined || (typeof value === 'object' && value !== null))
59
152
  return false;
60
- return globName(parameter[2] ?? '').test(String(value));
153
+ return globName((parameter[2] ?? '').trimEnd()).match(String(value)) ?? true;
61
154
  }
62
155
  }
63
- return conditionMatches(rule, tool, cwd);
156
+ return conditionMatches(rule, tool, cwd, true, { root, restricts: true });
64
157
  }
65
- /** The allow rule that approves the call, if any. */
66
- function allowMatch(rules, tool, cwd) {
67
- const usable = rules.filter((rule) => {
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 }) => {
68
161
  const parts = split(rule);
69
162
  if (parts === undefined)
70
163
  return false;
@@ -77,33 +170,33 @@ function allowMatch(rules, tool, cwd) {
77
170
  return undefined;
78
171
  if (isShellTool(tool.dshName)) {
79
172
  const whole = usable.find((rule) => {
80
- const parts = split(rule);
81
- return (parts.specifier === undefined || parts.specifier.trim() === '*') && conditionMatches(parts.name, tool, cwd);
173
+ const parts = split(rule.text);
174
+ return (parts.specifier === undefined || parts.specifier.trim() === '*') && conditionMatches(parts.name, tool, cwd, false);
82
175
  });
83
176
  if (whole !== undefined)
84
177
  return whole;
85
- const parsed = shellCommands(String(tool.input['command'] ?? ''));
178
+ const parsed = shellCommands(String(tool.input['command'] ?? ''), shellOf(tool));
86
179
  if (parsed === undefined || parsed.dynamic || parsed.commands.length === 0)
87
180
  return undefined;
88
181
  let first;
89
182
  for (const command of parsed.commands) {
90
183
  const single = { ...tool, input: { ...tool.input, command } };
91
- const rule = usable.find(candidate => conditionMatches(candidate, single, cwd));
184
+ const rule = usable.find(candidate => conditionMatches(candidate.text, single, cwd, false));
92
185
  if (rule === undefined)
93
186
  return undefined;
94
187
  first ??= rule;
95
188
  }
96
189
  return first;
97
190
  }
98
- return usable.find((rule) => {
191
+ return usable.find(({ text: rule, root }) => {
99
192
  const parts = split(rule);
100
193
  if (parts.name.startsWith('mcp__')) {
101
194
  // An MCP allow rule with a specifier matches no call.
102
- return parts.specifier === undefined && (parts.name.includes('*') ? globName(parts.name).test(tool.name) : conditionMatches(rule, tool, cwd));
195
+ return parts.specifier === undefined && (parts.name.includes('*') ? globName(parts.name).match(tool.name) ?? false : conditionMatches(rule, tool, cwd, false));
103
196
  }
104
- return conditionMatches(rule, tool, cwd);
197
+ return conditionMatches(rule, tool, cwd, false, { ...(root !== undefined ? { root } : {}), ...(path !== undefined ? { path } : {}) });
105
198
  });
106
199
  }
107
200
  function globName(pattern) {
108
- return new RegExp(`^${pattern.split('*').map(part => part.replace(/[.+?^${}()|[\]\\]/gu, '\\$&')).join('.*')}$`, 'su');
201
+ return wildcard(pattern);
109
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
+ }
@@ -4,6 +4,11 @@
4
4
  * keeps the pipes open does not hold the hook), an optional timeout, and
5
5
  * cancellation through a signal. A timeout or cancellation ends the hook's
6
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.
7
12
  * @module @kirkchinese/harness-forge
8
13
  */
9
14
  import { spawn } from 'node:child_process';
@@ -14,6 +19,12 @@ export interface ProcessSpec {
14
19
  readonly cwd: string;
15
20
  readonly env: NodeJS.ProcessEnv;
16
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;
17
28
  /** Undefined runs without a timeout. */
18
29
  readonly timeoutMs?: number;
19
30
  readonly signal?: AbortSignal;
@@ -43,5 +54,11 @@ export declare function treeKillCommand(pid: number, platform?: NodeJS.Platform)
43
54
  * `taskkill /T /F` walks the tree.
44
55
  */
45
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>;
46
63
  /** Spawn without a shell and collect the outcome. Never rejects. */
47
64
  export declare function runProcess(spec: ProcessSpec): Promise<ProcessOutcome>;