@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
@@ -4,9 +4,18 @@
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';
15
+ import { randomBytes } from 'node:crypto';
16
+ import { chmodSync, closeSync, lstatSync, mkdirSync, mkdtempSync, openSync, unlinkSync, writeSync } from 'node:fs';
17
+ import { tmpdir } from 'node:os';
18
+ import { dirname, join, resolve } from 'node:path';
10
19
  import { messageOf } from '../shared/util.js';
11
20
  const OUTPUT_LIMIT = 8 * 1024 * 1024;
12
21
  /** How long output is still read after the process exits. */
@@ -45,6 +54,139 @@ export function killProcessTree(child, platform = process.platform) {
45
54
  child.kill('SIGKILL');
46
55
  }
47
56
  }
57
+ let fallbackStdinDir;
58
+ /**
59
+ * Whether `dir` is a real directory of this user that no one else may enter,
60
+ * making it so when it is this user's: neither it nor any folder between it
61
+ * and `root` (when given) is a symbolic link.
62
+ *
63
+ * POSIX modes are not Windows ACLs: on Windows the mode only sets read-only,
64
+ * and the directory and its files take the ACL inherited from where they lie,
65
+ * Harness Forge's data folder in the user's profile directory, which only that
66
+ * user (and the system and administrators) can reach. There, only the link
67
+ * checks apply.
68
+ */
69
+ function privateDirectory(dir, root) {
70
+ if (root !== undefined) {
71
+ const top = resolve(root);
72
+ for (let folder = resolve(dir);; folder = dirname(folder)) {
73
+ // Every folder from `dir` up to and including the data root itself.
74
+ const link = lstatSync(folder);
75
+ if (link.isSymbolicLink() || !link.isDirectory())
76
+ return false;
77
+ if (folder === top)
78
+ break;
79
+ if (dirname(folder) === folder)
80
+ return false; // `dir` is not inside `root`.
81
+ }
82
+ }
83
+ const stat = lstatSync(dir);
84
+ if (stat.isSymbolicLink() || !stat.isDirectory())
85
+ return false;
86
+ if (process.platform === 'win32')
87
+ return true;
88
+ if (stat.uid !== process.getuid?.())
89
+ return false;
90
+ if ((stat.mode & 0o777) !== 0o700)
91
+ chmodSync(dir, 0o700);
92
+ return (lstatSync(dir).mode & 0o777) === 0o700;
93
+ }
94
+ /**
95
+ * A new file holding `input`, in a directory checked by `privateDirectory`
96
+ * (on POSIX: mode 0600 in a 0700 directory this user owns, so only this user
97
+ * can read it; on Windows: no owner-only ACL is set, and the file takes the
98
+ * ACL inherited from its folder, the user's profile by default), with a
99
+ * descriptor positioned at its start: the same descriptor that created
100
+ * the file is written (at explicit positions, leaving its offset at 0) and
101
+ * becomes the child's stdin, so nothing is opened again by path.
102
+ * @returns undefined when no such file can be made (the caller falls back to a pipe); nothing is left behind then.
103
+ */
104
+ function stdinFile(input, dir, dataRoot, leftover) {
105
+ let root;
106
+ try {
107
+ if (dir !== undefined) {
108
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
109
+ root = dir;
110
+ }
111
+ else {
112
+ root = fallbackStdinDir ??= mkdtempSync(join(tmpdir(), 'harness-forge-stdin-'));
113
+ }
114
+ if (!privateDirectory(root, dir !== undefined ? dataRoot : undefined))
115
+ return undefined;
116
+ }
117
+ catch {
118
+ return undefined;
119
+ }
120
+ const path = join(root, `${String(process.pid)}-${randomBytes(8).toString('hex')}.json`);
121
+ let fd;
122
+ try {
123
+ fd = openSync(path, 'wx+', 0o600);
124
+ }
125
+ catch {
126
+ return undefined;
127
+ }
128
+ try {
129
+ const bytes = Buffer.from(input, 'utf8');
130
+ for (let written = 0; written < bytes.length;) {
131
+ const count = writeSync(fd, bytes, written, bytes.length - written, written);
132
+ if (count <= 0)
133
+ throw new Error('the stdin file took no bytes');
134
+ written += count;
135
+ }
136
+ return { fd, path };
137
+ }
138
+ catch {
139
+ closeQuietly(fd);
140
+ void discard(path, leftover);
141
+ return undefined;
142
+ }
143
+ }
144
+ function closeQuietly(fd) {
145
+ try {
146
+ closeSync(fd);
147
+ }
148
+ catch {
149
+ // Already closed.
150
+ }
151
+ }
152
+ function removeFile(path) {
153
+ try {
154
+ unlinkSync(path);
155
+ return true;
156
+ }
157
+ catch (error) {
158
+ return error.code === 'ENOENT';
159
+ }
160
+ }
161
+ /**
162
+ * Remove a file Windows still holds open (a child that has not let go of it),
163
+ * trying again a bounded number of times.
164
+ * @returns whether it is gone.
165
+ */
166
+ export async function removeWithRetries(path, attempts = 10, delayMs = 200, remove = removeFile) {
167
+ for (let attempt = 0; attempt < attempts; attempt++) {
168
+ if (remove(path))
169
+ return true;
170
+ await new Promise(resolve => setTimeout(resolve, delayMs).unref());
171
+ }
172
+ return false;
173
+ }
174
+ /**
175
+ * The one way a stdin file goes: removed now, else (after `after`, the child's
176
+ * exit, for Windows, which keeps a file open in a process from being removed)
177
+ * a bounded number of times more; one that stays is reported, not left silently.
178
+ */
179
+ async function discard(path, leftover, after) {
180
+ if (removeFile(path))
181
+ return;
182
+ if (after !== undefined)
183
+ await after;
184
+ if (!await removeWithRetries(path))
185
+ leftover(path);
186
+ }
187
+ function warnLeftover(path) {
188
+ process.emitWarning(`harness-forge: could not remove the hook input file ${path}`);
189
+ }
48
190
  /** Spawn without a shell and collect the outcome. Never rejects. */
49
191
  export function runProcess(spec) {
50
192
  const started = performance.now();
@@ -59,14 +201,26 @@ export function runProcess(spec) {
59
201
  let stderrOpen = true;
60
202
  let drainTimer;
61
203
  let child;
204
+ const leftover = spec.onLeftover ?? warnLeftover;
205
+ const input = stdinFile(spec.stdin, spec.stdinDir, spec.stdinRoot, leftover);
62
206
  try {
63
207
  // Detached on POSIX: the hook leads its own process group, which a timeout or cancellation kills whole.
64
- child = spawn(spec.file, [...spec.args], { cwd: spec.cwd, env: spec.env, windowsHide: true, stdio: 'pipe', detached: process.platform !== 'win32' });
208
+ child = spawn(spec.file, [...spec.args], { cwd: spec.cwd, env: spec.env, windowsHide: true, stdio: [input?.fd ?? 'pipe', 'pipe', 'pipe'], detached: process.platform !== 'win32' });
65
209
  }
66
210
  catch (error) {
211
+ if (input !== undefined) {
212
+ closeQuietly(input.fd);
213
+ void discard(input.path, leftover);
214
+ }
67
215
  resolve({ startError: messageOf(error), timedOut: false, cancelled: false, stdout: '', stderr: '', suspectCapture: false, durationMs: 0 });
68
216
  return;
69
217
  }
218
+ // The child holds its own handle now: ours is closed and the file removed.
219
+ if (input !== undefined) {
220
+ closeQuietly(input.fd);
221
+ const started = child;
222
+ void discard(input.path, leftover, new Promise((done) => { started.once('exit', done); started.once('error', done); }));
223
+ }
70
224
  const finish = (suspectCapture, startError) => {
71
225
  if (settled)
72
226
  return;
@@ -126,6 +280,7 @@ export function runProcess(spec) {
126
280
  }
127
281
  drainTimer = setTimeout(() => { finish(stdoutOpen || stderrOpen); }, DRAIN_MS);
128
282
  });
283
+ // Without a stdin file (none could be written), the input goes through a pipe.
129
284
  child.stdin?.on('error', () => {
130
285
  // A hook that exits without reading stdin closes the pipe early.
131
286
  });
package/lib/hooks/row.js CHANGED
@@ -26,6 +26,8 @@ export function startHooks(ctx, forge) {
26
26
  reloadSkills: () => { forge.lookup('skills')?.reload(); },
27
27
  environment: session => forge.settings.env(session),
28
28
  permissionRules: session => forge.settings.permissionRules(session),
29
+ mcpToolPolicy: call => forge.lookup('mcp')?.toolPolicy(call),
30
+ mcpHookServer: (pluginId, server, sessionId) => forge.lookup('mcp')?.hookServer(pluginId, server, sessionId),
29
31
  hooksDisabled: session => forge.settings.hooksDisabled(session),
30
32
  prepareSession: (agent, cwd) => forge.projects.prepare(agent, cwd),
31
33
  releaseSession: sessionId => forge.projects.release(sessionId),
@@ -16,6 +16,7 @@
16
16
  */
17
17
  import type { Context } from '@deepseek-ai/cordis';
18
18
  import type { CommandHandler, HttpHandler, McpToolHandler, ModelHandler } from './config.js';
19
+ import type { McpToolCall, McpToolVerdict } from '../forge/contract.js';
19
20
  import type { RawRun } from './output.js';
20
21
  import type { ForeignShell } from './shell.js';
21
22
  import type { HookDialect } from './vocabulary.js';
@@ -58,11 +59,16 @@ export declare class HandlerRunner {
58
59
  private readonly ctx;
59
60
  private readonly shell;
60
61
  private readonly settingsEnv;
62
+ private readonly toolPolicy;
61
63
  /**
62
64
  * @param settingsEnv - the `env` of the harness settings in effect for the
63
65
  * event's agent, under the hook-specific variables.
64
66
  */
65
- constructor(ctx: Context, shell: ForeignShell, settingsEnv?: (agent: unknown) => Readonly<Record<string, string>>);
67
+ /**
68
+ * @param toolPolicy - the MCP row's tool policy (`McpApi.toolPolicy`), which an `mcp_tool` hook's call obeys as a
69
+ * model's call does; without the row no MCP tool is mounted, so nothing needs it.
70
+ */
71
+ constructor(ctx: Context, shell: ForeignShell, settingsEnv?: (agent: unknown) => Readonly<Record<string, string>>, toolPolicy?: (call: McpToolCall) => McpToolVerdict | undefined);
66
72
  /** The environment every command handler of a source receives. */
67
73
  environment(places: HandlerPlaces, kind: 'bash' | 'powershell' | 'exec', agent?: unknown): Record<string, string | undefined>;
68
74
  /** Run a command handler. */
@@ -70,15 +76,22 @@ export declare class HandlerRunner {
70
76
  /** Run an HTTP handler. */
71
77
  http(handler: HttpHandler, request: HandlerRequest): Promise<HandlerOutcome>;
72
78
  /**
73
- * Run an MCP tool handler.
74
- * @param toolName - the DSH tool name of `server`/`tool`.
79
+ * Run an MCP tool handler: the tool the MCP row mounted directly
80
+ * (`mcp__<server>__<tool>`) or, for a server the capability catalog serves,
81
+ * the catalog's `capability_call` with the entry `mcp:<server>/<tool>`.
82
+ * Codex runs such a hook on an already-connected server only, so a server
83
+ * that is neither is reported as not connected.
84
+ * @param serverName - the server as registered (`McpApi.hookServer`); undefined when neither the hook's plugin nor
85
+ * the user's configuration has a mounted server of the name it gives.
75
86
  */
76
- mcpTool(handler: McpToolHandler, request: HandlerRequest, toolName: string): Promise<HandlerOutcome>;
87
+ mcpTool(handler: McpToolHandler, request: HandlerRequest, serverName: string | undefined): Promise<HandlerOutcome>;
77
88
  /** Run a prompt handler: one model call that answers `{ ok, reason, impossible }`. */
78
89
  prompt(handler: ModelHandler, request: HandlerRequest): Promise<HandlerOutcome>;
79
90
  /** Run an agent handler: a delegated agent with tool access that answers `{ ok, reason }`. */
80
91
  agent(handler: ModelHandler, request: HandlerRequest): Promise<HandlerOutcome>;
81
92
  }
93
+ /** The hook model's `{"ok": …}` answer: the text from its first `{` to its last `}`. */
94
+ export declare function parseVerdict(text: string): ModelVerdict;
82
95
  /** PowerShell shell form: path placeholders become `${env:NAME}`. */
83
96
  export declare function powershellPlaceholders(command: string): string;
84
97
  /** `${a.b}` fields from the input; a placeholder filling a whole value keeps its JSON type. */
@@ -1,4 +1,6 @@
1
1
  import { dshService } from '../dsh/host.js';
2
+ import { CATALOG_CALL_TOOL } from '../mcp/catalog.js';
3
+ import { publicToolName } from '../mcp/policy.js';
2
4
  import { startActivation } from '../dsh/subagents.js';
3
5
  import { messageOf } from '../shared/util.js';
4
6
  const PATH_PLACEHOLDERS = ['CLAUDE_PROJECT_DIR', 'CLAUDE_PLUGIN_ROOT', 'CLAUDE_PLUGIN_DATA', 'PLUGIN_ROOT', 'PLUGIN_DATA'];
@@ -7,14 +9,20 @@ export class HandlerRunner {
7
9
  ctx;
8
10
  shell;
9
11
  settingsEnv;
12
+ toolPolicy;
10
13
  /**
11
14
  * @param settingsEnv - the `env` of the harness settings in effect for the
12
15
  * event's agent, under the hook-specific variables.
13
16
  */
14
- constructor(ctx, shell, settingsEnv = () => ({})) {
17
+ /**
18
+ * @param toolPolicy - the MCP row's tool policy (`McpApi.toolPolicy`), which an `mcp_tool` hook's call obeys as a
19
+ * model's call does; without the row no MCP tool is mounted, so nothing needs it.
20
+ */
21
+ constructor(ctx, shell, settingsEnv = () => ({}), toolPolicy = () => undefined) {
15
22
  this.ctx = ctx;
16
23
  this.shell = shell;
17
24
  this.settingsEnv = settingsEnv;
25
+ this.toolPolicy = toolPolicy;
18
26
  }
19
27
  /** The environment every command handler of a source receives. */
20
28
  environment(places, kind, agent) {
@@ -100,24 +108,43 @@ export class HandlerRunner {
100
108
  }
101
109
  }
102
110
  /**
103
- * Run an MCP tool handler.
104
- * @param toolName - the DSH tool name of `server`/`tool`.
111
+ * Run an MCP tool handler: the tool the MCP row mounted directly
112
+ * (`mcp__<server>__<tool>`) or, for a server the capability catalog serves,
113
+ * the catalog's `capability_call` with the entry `mcp:<server>/<tool>`.
114
+ * Codex runs such a hook on an already-connected server only, so a server
115
+ * that is neither is reported as not connected.
116
+ * @param serverName - the server as registered (`McpApi.hookServer`); undefined when neither the hook's plugin nor
117
+ * the user's configuration has a mounted server of the name it gives.
105
118
  */
106
- async mcpTool(handler, request, toolName) {
119
+ async mcpTool(handler, request, serverName) {
120
+ if (serverName === undefined) {
121
+ return { stdout: '', stderr: '', durationMs: 0, failure: { kind: 'transport', message: `MCP server "${handler.server}" is not a connected server of this plugin or of the user's configuration` } };
122
+ }
107
123
  const started = performance.now();
108
124
  const elapsed = () => Math.round(performance.now() - started);
109
125
  const tools = dshService(this.ctx, 'tools');
110
- const definition = tools?.get(toolName);
126
+ const direct = publicToolName(serverName, handler.tool);
127
+ const viaCatalog = tools?.get(direct) === undefined ? tools?.get(CATALOG_CALL_TOOL) : undefined;
128
+ const toolName = viaCatalog === undefined ? direct : CATALOG_CALL_TOOL;
129
+ const definition = viaCatalog ?? tools?.get(direct);
111
130
  if (definition === undefined)
112
- return { stdout: '', stderr: '', durationMs: 0, failure: { kind: 'transport', message: `MCP tool ${toolName} is not connected` } };
131
+ return { stdout: '', stderr: '', durationMs: 0, failure: { kind: 'transport', message: `MCP tool ${direct} is not connected` } };
113
132
  const input = fillTemplate(handler.input ?? {}, request.payload);
133
+ const args = viaCatalog === undefined ? input : { id: `mcp:${serverName}/${handler.tool}`, arguments: input };
134
+ // The server's own filters hold for a hook as for the model: Codex runs hooks only on "policy-allowed tools", and a
135
+ // filtered tool is not registered there, so here it is not available. Codex invokes them "without model-tool
136
+ // approval" (openai/codex#39296; https://developers.openai.com/codex/hooks, "MCP tool hooks": they "don't request
137
+ // tool approval"), the hook itself having passed the trust review, so an approval mode does not stop it.
138
+ const verdict = this.toolPolicy({ name: toolName, arguments: args, agent: request.agent });
139
+ if (verdict?.kind === 'deny')
140
+ return { stdout: '', stderr: '', durationMs: elapsed(), failure: { kind: 'transport', message: `MCP tool ${direct} is not available: ${verdict.reason}` } };
114
141
  const signal = request.timeoutMs === undefined ? request.signal : AbortSignal.any([request.signal, AbortSignal.timeout(request.timeoutMs)]);
115
142
  try {
116
- const value = await definition.execute(input, { name: toolName, arguments: input, callId: `hook-${Date.now().toString(36)}`, signal, agent: request.agent });
117
- const text = definition.output.render(input, value).map(block => block.text ?? '').join('');
143
+ const value = await definition.execute(args, { name: toolName, arguments: args, callId: `hook-${Date.now().toString(36)}`, signal, agent: request.agent });
144
+ const text = definition.output.render(args, value).map(block => block.text ?? '').join('');
118
145
  const isError = typeof value === 'object' && value !== null && value.isError === true;
119
146
  return isError
120
- ? { stdout: '', stderr: text, durationMs: elapsed(), failure: { kind: 'transport', message: `MCP tool ${toolName} returned an error: ${text.slice(0, 300)}` } }
147
+ ? { stdout: '', stderr: text, durationMs: elapsed(), failure: { kind: 'transport', message: `MCP tool ${direct} returned an error: ${text.slice(0, 300)}` } }
121
148
  : { exitCode: 0, stdout: text, stderr: '', durationMs: elapsed() };
122
149
  }
123
150
  catch (error) {
@@ -211,11 +238,13 @@ function promptText(prompt, payload) {
211
238
  });
212
239
  return used ? text : `${text}\n\n${json}`;
213
240
  }
214
- function parseVerdict(text) {
215
- const match = /\{[\s\S]*\}/u.exec(text);
216
- if (match !== null) {
241
+ /** The hook model's `{"ok": …}` answer: the text from its first `{` to its last `}`. */
242
+ export function parseVerdict(text) {
243
+ const start = text.indexOf('{');
244
+ const end = text.lastIndexOf('}');
245
+ if (start !== -1 && end > start) {
217
246
  try {
218
- const value = JSON.parse(match[0]);
247
+ const value = JSON.parse(text.slice(start, end + 1));
219
248
  if (typeof value['ok'] === 'boolean') {
220
249
  return {
221
250
  ok: value['ok'],
@@ -11,9 +11,18 @@ export interface ShellCommands {
11
11
  /** The input expands something at run time: `$(…)`, backticks or `$VAR`. */
12
12
  readonly dynamic: boolean;
13
13
  }
14
+ /**
15
+ * What a lone PowerShell `&` (not part of `&&`) is: the call operator before a
16
+ * command (`& ./x.ps1`), PowerShell 7's background operator after one
17
+ * (https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_operators#background-operator-),
18
+ * or, right after `>` or `<`, part of a merge such as `2>&1` (undefined).
19
+ * @param started - whether a command has begun before it.
20
+ */
21
+ export declare function powershellAmpersand(previous: string, next: string, started: boolean): 'call' | 'background' | undefined;
14
22
  /**
15
23
  * Split a shell input into the commands it runs.
24
+ * @param shell - the shell that reads it: in PowerShell `$null`, `$true` and `$false` are constants, no expansion.
16
25
  * @returns undefined when the input cannot be read reliably (unbalanced
17
26
  * quotes or substitutions), in which case a caller treats every rule as a match.
18
27
  */
19
- export declare function shellCommands(input: string): ShellCommands | undefined;
28
+ export declare function shellCommands(input: string, shell?: 'bash' | 'powershell'): ShellCommands | undefined;
@@ -5,14 +5,33 @@
5
5
  * stripped.
6
6
  * @module @kirkchinese/harness-forge
7
7
  */
8
+ /**
9
+ * PowerShell's constant automatic variables, which expand to nothing a caller
10
+ * chooses (https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_automatic_variables).
11
+ */
12
+ const POWERSHELL_CONSTANT = /^\$(?:null|true|false)(?![\w:])/iu;
13
+ /**
14
+ * What a lone PowerShell `&` (not part of `&&`) is: the call operator before a
15
+ * command (`& ./x.ps1`), PowerShell 7's background operator after one
16
+ * (https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_operators#background-operator-),
17
+ * or, right after `>` or `<`, part of a merge such as `2>&1` (undefined).
18
+ * @param started - whether a command has begun before it.
19
+ */
20
+ export function powershellAmpersand(previous, next, started) {
21
+ if (next === '&' || previous === '&' || previous === '>' || previous === '<')
22
+ return undefined;
23
+ return started ? 'background' : 'call';
24
+ }
8
25
  /**
9
26
  * Split a shell input into the commands it runs.
27
+ * @param shell - the shell that reads it: in PowerShell `$null`, `$true` and `$false` are constants, no expansion.
10
28
  * @returns undefined when the input cannot be read reliably (unbalanced
11
29
  * quotes or substitutions), in which case a caller treats every rule as a match.
12
30
  */
13
- export function shellCommands(input) {
31
+ export function shellCommands(input, shell = 'bash') {
14
32
  const commands = [];
15
33
  let dynamic = false;
34
+ const expands = (text, at) => /[A-Za-z_{]/u.test(text[at + 1] ?? '') && !(shell === 'powershell' && POWERSHELL_CONSTANT.test(text.slice(at)));
16
35
  const visit = (text, depth) => {
17
36
  if (depth > 8)
18
37
  return false;
@@ -73,7 +92,7 @@ export function shellCommands(input) {
73
92
  end = close;
74
93
  continue;
75
94
  }
76
- if (inner === '$' && /[A-Za-z_{]/u.test(text[end + 1] ?? ''))
95
+ if (inner === '$' && expands(text, end))
77
96
  dynamic = true;
78
97
  quoted += inner;
79
98
  }
@@ -105,14 +124,19 @@ export function shellCommands(input) {
105
124
  index = close;
106
125
  continue;
107
126
  }
108
- if (char === '$' && /[A-Za-z_{]/u.test(next))
127
+ if (char === '$' && expands(text, index))
109
128
  dynamic = true;
110
129
  if ((char === '&' && next === '&') || (char === '|' && next === '|')) {
111
130
  flush();
112
131
  index++;
113
132
  continue;
114
133
  }
115
- if (char === ';' || char === '|' || char === '\n' || (char === '&' && next !== '>' && text[index - 1] !== '>')) {
134
+ // A lone `&`: bash's background operator (not `&>` or `>&`); in PowerShell the call operator or the background
135
+ // operator (see `powershellAmpersand`), either way where a command starts or ends.
136
+ const ampersand = char === '&' && (shell === 'powershell'
137
+ ? powershellAmpersand(text[index - 1] ?? '', next, current.trim().length > 0) !== undefined
138
+ : next !== '>' && text[index - 1] !== '>');
139
+ if (char === ';' || char === '|' || char === '\n' || ampersand) {
116
140
  flush();
117
141
  continue;
118
142
  }
@@ -130,15 +154,55 @@ export function shellCommands(input) {
130
154
  };
131
155
  return visit(input, 0) ? { commands, dynamic } : undefined;
132
156
  }
133
- /** Remove leading `NAME=value` words. */
157
+ /**
158
+ * Remove leading `NAME=value` words that whitespace follows. A scan, not a
159
+ * pattern: a pattern for this backtracks exponentially on an assignment that
160
+ * nothing follows, and froze DSH.
161
+ */
134
162
  function stripAssignments(command) {
135
- let rest = command;
163
+ let start = 0;
136
164
  for (;;) {
137
- const match = /^[A-Za-z_][A-Za-z0-9_]*=(?:'[^']*'|"(?:\\.|[^"\\])*"|[^\s'"]*)+\s+/u.exec(rest);
138
- if (match === null)
139
- return rest;
140
- rest = rest.slice(match[0].length);
165
+ const end = assignmentEnd(command, start);
166
+ if (end === undefined || end >= command.length || !/\s/u.test(command[end] ?? ''))
167
+ return command.slice(start);
168
+ start = end;
169
+ while (start < command.length && /\s/u.test(command[start] ?? ''))
170
+ start++;
171
+ }
172
+ }
173
+ /** Where the `NAME=value` word at `start` ends, or undefined when none starts there (or a quote never closes). */
174
+ function assignmentEnd(text, start) {
175
+ let index = start;
176
+ if (!/[A-Za-z_]/u.test(text[index] ?? ''))
177
+ return undefined;
178
+ while (/[A-Za-z0-9_]/u.test(text[index] ?? ''))
179
+ index++;
180
+ if (text[index] !== '=')
181
+ return undefined;
182
+ index++;
183
+ while (index < text.length) {
184
+ const char = text[index] ?? '';
185
+ if (/\s/u.test(char))
186
+ break;
187
+ if (char === "'") {
188
+ const close = text.indexOf("'", index + 1);
189
+ if (close === -1)
190
+ return undefined;
191
+ index = close + 1;
192
+ }
193
+ else if (char === '"') {
194
+ index++;
195
+ while (index < text.length && text[index] !== '"')
196
+ index += text[index] === '\\' ? 2 : 1;
197
+ if (index >= text.length)
198
+ return undefined;
199
+ index++;
200
+ }
201
+ else {
202
+ index += char === '\\' ? 2 : 1;
203
+ }
141
204
  }
205
+ return Math.min(index, text.length);
142
206
  }
143
207
  /** Index of the `)` closing the `(` at `open`, honoring nesting and quotes. */
144
208
  function matchParen(text, open) {
@@ -38,6 +38,7 @@ export declare function findPowerShell(env?: NodeJS.ProcessEnv): string;
38
38
  export declare function python3Shim(shimRoot: string, env?: NodeJS.ProcessEnv): string | undefined;
39
39
  /**
40
40
  * Build the executors.
41
- * @param shimRoot - writable directory for command shims (see {@link python3Shim}).
41
+ * @param shimRoot - writable directory for command shims (see {@link python3Shim}) and the files that hold hook input.
42
+ * @param onLeftover - told of a hook input file that could not be removed.
42
43
  */
43
- export declare function createForeignShell(base?: NodeJS.ProcessEnv, shimRoot?: string): ForeignShell;
44
+ export declare function createForeignShell(base?: NodeJS.ProcessEnv, shimRoot?: string, onLeftover?: (path: string) => void): ForeignShell;
@@ -72,9 +72,10 @@ export function python3Shim(shimRoot, env = process.env) {
72
72
  }
73
73
  /**
74
74
  * Build the executors.
75
- * @param shimRoot - writable directory for command shims (see {@link python3Shim}).
75
+ * @param shimRoot - writable directory for command shims (see {@link python3Shim}) and the files that hold hook input.
76
+ * @param onLeftover - told of a hook input file that could not be removed.
76
77
  */
77
- export function createForeignShell(base = process.env, shimRoot) {
78
+ export function createForeignShell(base = process.env, shimRoot, onLeftover) {
78
79
  const posix = findPosixShell(base);
79
80
  const powershell = findPowerShell(base);
80
81
  const shims = shimRoot === undefined ? undefined : python3Shim(shimRoot, base);
@@ -103,6 +104,8 @@ export function createForeignShell(base = process.env, shimRoot) {
103
104
  cwd: options.cwd,
104
105
  env: environment(options.env),
105
106
  stdin: options.stdin ?? '',
107
+ ...(shimRoot !== undefined ? { stdinDir: join(shimRoot, 'stdin'), stdinRoot: shimRoot } : {}),
108
+ ...(onLeftover !== undefined ? { onLeftover } : {}),
106
109
  ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
107
110
  ...(options.signal !== undefined ? { signal: options.signal } : {}),
108
111
  });
@@ -65,7 +65,9 @@ export function foreignTool(dialect, dshName, args, context = {}) {
65
65
  export function dshToolsFor(foreignName, dialect) {
66
66
  if (foreignName.startsWith('mcp__'))
67
67
  return [foreignName, ...CATALOG_TOOLS];
68
- const bare = foreignName.replace(/\(.*\)$/u, '').trim();
68
+ // `Name(specifier)`: drop the specifier (a scan; `/\(.*\)$/` is quadratic on a run of `(`).
69
+ const open = foreignName.indexOf('(', foreignName.lastIndexOf('\n') + 1);
70
+ const bare = (open !== -1 && foreignName.endsWith(')') ? foreignName.slice(0, open) : foreignName).trim();
69
71
  const names = [];
70
72
  for (const [dsh, entry] of Object.entries(TABLE)) {
71
73
  // In one dialect a name means that dialect's tool only: Claude's `Write` is not Codex's patch-writer that also edits.
@@ -15,10 +15,13 @@ export declare const CATALOG_CALL_TOOL = "capability_call";
15
15
  export declare const CATALOG_TOOLS: readonly ["capability_search", "capability_describe", "capability_call"];
16
16
  /** The services the catalog provides. */
17
17
  export declare const CATALOG_SERVICES: readonly ["capabilityCatalogServers", "capabilityCatalog"];
18
+ /** The server and the raw tool name of a catalog entry id `mcp:<server>/<tool>`; a server name holds no `/`. */
19
+ export declare function catalogEntry(id: unknown): {
20
+ readonly server: string;
21
+ readonly tool: string;
22
+ } | undefined;
18
23
  /** The `mcp__<server>__<tool>` name of a catalog entry id `mcp:<server>/<tool>`. */
19
24
  export declare function catalogToolName(id: unknown): string | undefined;
20
- /** The tool a call runs: a catalog call runs the MCP tool its id names. */
21
- export declare function calledTool(name: string, args: unknown): string;
22
25
  /** The capability catalog's server registry. */
23
26
  export interface CatalogServers {
24
27
  addMcpServer(server: Record<string, unknown>): Promise<() => Promise<void>>;
@@ -1,20 +1,26 @@
1
1
  import { dshService } from '../dsh/host.js';
2
+ /**
3
+ * How long a catalog-started server may sit unused before the catalog stops
4
+ * it: started on demand, it is started again by the next call.
5
+ */
6
+ const CATALOG_IDLE_DISCONNECT_MS = 300_000;
2
7
  /** The catalog meta-tool that runs a catalog entry. */
3
8
  export const CATALOG_CALL_TOOL = 'capability_call';
4
9
  /** Every catalog meta-tool; an agent that may use an MCP tool may use these. */
5
10
  export const CATALOG_TOOLS = ['capability_search', 'capability_describe', CATALOG_CALL_TOOL];
6
11
  /** The services the catalog provides. */
7
12
  export const CATALOG_SERVICES = ['capabilityCatalogServers', 'capabilityCatalog'];
8
- /** The `mcp__<server>__<tool>` name of a catalog entry id `mcp:<server>/<tool>`. */
9
- export function catalogToolName(id) {
13
+ /** The server and the raw tool name of a catalog entry id `mcp:<server>/<tool>`; a server name holds no `/`. */
14
+ export function catalogEntry(id) {
10
15
  if (typeof id !== 'string')
11
16
  return undefined;
12
17
  const match = /^mcp:([^/]+)\/(.+)$/u.exec(id);
13
- return match === null ? undefined : `mcp__${match[1] ?? ''}__${match[2] ?? ''}`;
18
+ return match === null ? undefined : { server: match[1] ?? '', tool: match[2] ?? '' };
14
19
  }
15
- /** The tool a call runs: a catalog call runs the MCP tool its id names. */
16
- export function calledTool(name, args) {
17
- return name === CATALOG_CALL_TOOL ? catalogToolName(args?.id) ?? name : name;
20
+ /** The `mcp__<server>__<tool>` name of a catalog entry id `mcp:<server>/<tool>`. */
21
+ export function catalogToolName(id) {
22
+ const entry = catalogEntry(id);
23
+ return entry === undefined ? undefined : `mcp__${entry.server}__${entry.tool}`;
18
24
  }
19
25
  /** The catalog's server registry when the profile composes the catalog and it runs. */
20
26
  export function composedCatalog(ctx) {
@@ -42,11 +48,13 @@ export async function mountInCatalog(ctx, catalog, component, serverName, config
42
48
  env: config['env'],
43
49
  cwd: config['cwd'],
44
50
  headers: {},
45
- allowTools: [],
46
- denyTools: [],
51
+ // The catalog's filters are wildcard patterns, an empty allow list meaning every tool; MCP tool names
52
+ // (`[A-Za-z0-9_.-]`) hold no wildcard, so a name matches itself only. An empty `enabled_tools` enables none.
53
+ allowTools: component.enabledTools ?? [],
54
+ denyTools: component.enabledTools?.length === 0 ? ['*'] : component.disabledTools ?? [],
47
55
  families: [],
48
- idleDisconnectMs: 300_000,
49
- callTimeoutMs: 600_000,
56
+ idleDisconnectMs: CATALOG_IDLE_DISCONNECT_MS,
57
+ callTimeoutMs: config['toolCallTimeoutMs'],
50
58
  discoveryTimeoutMs,
51
59
  catalogTtlMs: 86_400_000,
52
60
  });