@kirkchinese/harness-forge 0.0.0-stage → 0.4.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 (246) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +42 -2
  3. package/assets/icon.svg +12 -0
  4. package/cordis.patch.yml +28 -0
  5. package/lib/agents/presets.d.ts +91 -0
  6. package/lib/agents/presets.js +282 -0
  7. package/lib/agents/profiles.d.ts +58 -0
  8. package/lib/agents/profiles.js +278 -0
  9. package/lib/agents/row.d.ts +17 -0
  10. package/lib/agents/row.js +146 -0
  11. package/lib/client/styles.d.ts +8 -0
  12. package/lib/client/styles.js +89 -0
  13. package/lib/client/typert.d.ts +14 -0
  14. package/lib/client/typert.js +110 -0
  15. package/lib/client.js +22500 -0
  16. package/lib/commands/definition.d.ts +40 -0
  17. package/lib/commands/definition.js +113 -0
  18. package/lib/commands/output-styles.d.ts +42 -0
  19. package/lib/commands/output-styles.js +152 -0
  20. package/lib/commands/row.d.ts +9 -0
  21. package/lib/commands/row.js +157 -0
  22. package/lib/context/instructions.d.ts +32 -0
  23. package/lib/context/instructions.js +88 -0
  24. package/lib/context/row.d.ts +16 -0
  25. package/lib/context/row.js +17 -0
  26. package/lib/dsh/commands.d.ts +30 -0
  27. package/lib/dsh/commands.js +61 -0
  28. package/lib/dsh/host.d.ts +107 -0
  29. package/lib/dsh/host.js +214 -0
  30. package/lib/dsh/model-route.d.ts +21 -0
  31. package/lib/dsh/model-route.js +37 -0
  32. package/lib/dsh/session-records.d.ts +78 -0
  33. package/lib/dsh/session-records.js +36 -0
  34. package/lib/dsh/subagents.d.ts +46 -0
  35. package/lib/dsh/subagents.js +14 -0
  36. package/lib/forge/contract.d.ts +231 -0
  37. package/lib/forge/contract.js +43 -0
  38. package/lib/forge/ledger.d.ts +143 -0
  39. package/lib/forge/ledger.js +733 -0
  40. package/lib/forge/live-mounts.d.ts +45 -0
  41. package/lib/forge/live-mounts.js +78 -0
  42. package/lib/forge/marketplace-install.d.ts +3 -0
  43. package/lib/forge/marketplace-install.js +64 -0
  44. package/lib/forge/npm.d.ts +31 -0
  45. package/lib/forge/npm.js +60 -0
  46. package/lib/forge/projects.d.ts +94 -0
  47. package/lib/forge/projects.js +336 -0
  48. package/lib/forge/receipts.d.ts +5 -0
  49. package/lib/forge/receipts.js +31 -0
  50. package/lib/forge/row.d.ts +32 -0
  51. package/lib/forge/row.js +59 -0
  52. package/lib/forge/service.d.ts +105 -0
  53. package/lib/forge/service.js +274 -0
  54. package/lib/forge/settings.d.ts +41 -0
  55. package/lib/forge/settings.js +115 -0
  56. package/lib/forge/state.d.ts +69 -0
  57. package/lib/forge/state.js +150 -0
  58. package/lib/forge/trust.d.ts +48 -0
  59. package/lib/forge/trust.js +107 -0
  60. package/lib/forge/turns.d.ts +13 -0
  61. package/lib/forge/turns.js +56 -0
  62. package/lib/hooks/broker/engine.d.ts +112 -0
  63. package/lib/hooks/broker/engine.js +728 -0
  64. package/lib/hooks/broker/helpers.d.ts +10 -0
  65. package/lib/hooks/broker/helpers.js +22 -0
  66. package/lib/hooks/broker/lifecycle.d.ts +65 -0
  67. package/lib/hooks/broker/lifecycle.js +342 -0
  68. package/lib/hooks/broker/session-events.d.ts +22 -0
  69. package/lib/hooks/broker/session-events.js +196 -0
  70. package/lib/hooks/broker/tools.d.ts +52 -0
  71. package/lib/hooks/broker/tools.js +424 -0
  72. package/lib/hooks/broker/types.d.ts +262 -0
  73. package/lib/hooks/broker/types.js +1 -0
  74. package/lib/hooks/broker.d.ts +80 -0
  75. package/lib/hooks/broker.js +95 -0
  76. package/lib/hooks/codex-user.d.ts +5 -0
  77. package/lib/hooks/codex-user.js +109 -0
  78. package/lib/hooks/condition.d.ts +11 -0
  79. package/lib/hooks/condition.js +181 -0
  80. package/lib/hooks/config.d.ts +85 -0
  81. package/lib/hooks/config.js +150 -0
  82. package/lib/hooks/matcher.d.ts +20 -0
  83. package/lib/hooks/matcher.js +39 -0
  84. package/lib/hooks/notice.d.ts +17 -0
  85. package/lib/hooks/notice.js +39 -0
  86. package/lib/hooks/output.d.ts +56 -0
  87. package/lib/hooks/output.js +214 -0
  88. package/lib/hooks/permissions.d.ts +14 -0
  89. package/lib/hooks/permissions.js +109 -0
  90. package/lib/hooks/process.d.ts +47 -0
  91. package/lib/hooks/process.js +134 -0
  92. package/lib/hooks/row.d.ts +17 -0
  93. package/lib/hooks/row.js +94 -0
  94. package/lib/hooks/runner.d.ts +85 -0
  95. package/lib/hooks/runner.js +293 -0
  96. package/lib/hooks/shell-commands.d.ts +19 -0
  97. package/lib/hooks/shell-commands.js +177 -0
  98. package/lib/hooks/shell.d.ts +43 -0
  99. package/lib/hooks/shell.js +126 -0
  100. package/lib/hooks/transcript.d.ts +28 -0
  101. package/lib/hooks/transcript.js +141 -0
  102. package/lib/hooks/vocabulary.d.ts +57 -0
  103. package/lib/hooks/vocabulary.js +364 -0
  104. package/lib/index.d.ts +31 -0
  105. package/lib/index.js +287 -0
  106. package/lib/mcp/auth.d.ts +35 -0
  107. package/lib/mcp/auth.js +178 -0
  108. package/lib/mcp/catalog.d.ts +36 -0
  109. package/lib/mcp/catalog.js +61 -0
  110. package/lib/mcp/mount.d.ts +75 -0
  111. package/lib/mcp/mount.js +217 -0
  112. package/lib/mcp/remote.d.ts +45 -0
  113. package/lib/mcp/remote.js +143 -0
  114. package/lib/mcp/row.d.ts +9 -0
  115. package/lib/mcp/row.js +131 -0
  116. package/lib/mods/bundler.d.ts +38 -0
  117. package/lib/mods/bundler.js +157 -0
  118. package/lib/mods/chain.d.ts +103 -0
  119. package/lib/mods/chain.js +436 -0
  120. package/lib/mods/claude.d.ts +27 -0
  121. package/lib/mods/claude.js +56 -0
  122. package/lib/mods/engine.d.ts +160 -0
  123. package/lib/mods/engine.js +701 -0
  124. package/lib/mods/expect.d.ts +8 -0
  125. package/lib/mods/expect.js +248 -0
  126. package/lib/mods/host.d.ts +105 -0
  127. package/lib/mods/host.js +462 -0
  128. package/lib/mods/loader.d.ts +53 -0
  129. package/lib/mods/loader.js +227 -0
  130. package/lib/mods/ops.d.ts +13 -0
  131. package/lib/mods/ops.js +117 -0
  132. package/lib/mods/row.d.ts +9 -0
  133. package/lib/mods/row.js +77 -0
  134. package/lib/mods/runtime.d.ts +60 -0
  135. package/lib/mods/runtime.js +133 -0
  136. package/lib/mods/service/commands.d.ts +17 -0
  137. package/lib/mods/service/commands.js +121 -0
  138. package/lib/mods/service/drawings.d.ts +36 -0
  139. package/lib/mods/service/drawings.js +64 -0
  140. package/lib/mods/service/sessions.d.ts +63 -0
  141. package/lib/mods/service/sessions.js +345 -0
  142. package/lib/mods/service/tools.d.ts +32 -0
  143. package/lib/mods/service/tools.js +253 -0
  144. package/lib/mods/service/turns.d.ts +32 -0
  145. package/lib/mods/service/turns.js +161 -0
  146. package/lib/mods/service/types.d.ts +151 -0
  147. package/lib/mods/service/types.js +1 -0
  148. package/lib/mods/service.d.ts +72 -0
  149. package/lib/mods/service.js +104 -0
  150. package/lib/mods/surfaces.d.ts +93 -0
  151. package/lib/mods/surfaces.js +309 -0
  152. package/lib/mods/values.d.ts +30 -0
  153. package/lib/mods/values.js +95 -0
  154. package/lib/opencode/bun.d.ts +40 -0
  155. package/lib/opencode/bun.js +156 -0
  156. package/lib/opencode/convert.d.ts +53 -0
  157. package/lib/opencode/convert.js +255 -0
  158. package/lib/opencode/row.d.ts +9 -0
  159. package/lib/opencode/row.js +86 -0
  160. package/lib/opencode/runtime/core.d.ts +74 -0
  161. package/lib/opencode/runtime/core.js +249 -0
  162. package/lib/opencode/runtime/events.d.ts +80 -0
  163. package/lib/opencode/runtime/events.js +281 -0
  164. package/lib/opencode/runtime/mount.d.ts +27 -0
  165. package/lib/opencode/runtime/mount.js +283 -0
  166. package/lib/opencode/runtime/server.d.ts +27 -0
  167. package/lib/opencode/runtime/server.js +353 -0
  168. package/lib/opencode/runtime/types.d.ts +109 -0
  169. package/lib/opencode/runtime/types.js +1 -0
  170. package/lib/opencode/runtime.d.ts +55 -0
  171. package/lib/opencode/runtime.js +79 -0
  172. package/lib/porting/port-gap.d.ts +30 -0
  173. package/lib/porting/port-gap.js +122 -0
  174. package/lib/porting/port-sessions.d.ts +41 -0
  175. package/lib/porting/port-sessions.js +98 -0
  176. package/lib/porting/prompt.d.ts +23 -0
  177. package/lib/porting/prompt.js +49 -0
  178. package/lib/porting/row.d.ts +16 -0
  179. package/lib/porting/row.js +25 -0
  180. package/lib/porting/verify-port.d.ts +53 -0
  181. package/lib/porting/verify-port.js +104 -0
  182. package/lib/presets/fs-search.d.ts +25 -0
  183. package/lib/presets/fs-search.js +17 -0
  184. package/lib/presets/tool-filter.d.ts +35 -0
  185. package/lib/presets/tool-filter.js +91 -0
  186. package/lib/sessions/claude.d.ts +29 -0
  187. package/lib/sessions/claude.js +83 -0
  188. package/lib/sessions/codex.d.ts +30 -0
  189. package/lib/sessions/codex.js +303 -0
  190. package/lib/sessions/opencode.d.ts +32 -0
  191. package/lib/sessions/opencode.js +320 -0
  192. package/lib/sessions/row.d.ts +14 -0
  193. package/lib/sessions/row.js +35 -0
  194. package/lib/shared/invocation.d.ts +169 -0
  195. package/lib/shared/invocation.js +325 -0
  196. package/lib/shared/render.d.ts +72 -0
  197. package/lib/shared/render.js +588 -0
  198. package/lib/shared/util.d.ts +21 -0
  199. package/lib/shared/util.js +32 -0
  200. package/lib/skills/bundled.d.ts +3 -0
  201. package/lib/skills/bundled.js +42 -0
  202. package/lib/skills/provider.d.ts +72 -0
  203. package/lib/skills/provider.js +340 -0
  204. package/lib/skills/row.d.ts +22 -0
  205. package/lib/skills/row.js +204 -0
  206. package/lib/workbench/adapter-coverage.d.ts +47 -0
  207. package/lib/workbench/adapter-coverage.js +102 -0
  208. package/lib/workbench/model-tools.d.ts +10 -0
  209. package/lib/workbench/model-tools.js +122 -0
  210. package/lib/workbench/overview.d.ts +103 -0
  211. package/lib/workbench/overview.js +159 -0
  212. package/lib/workbench/remote.d.ts +118 -0
  213. package/lib/workbench/remote.js +422 -0
  214. package/lib/workbench/row.d.ts +15 -0
  215. package/lib/workbench/row.js +16 -0
  216. package/lib/workbench/settings.d.ts +15 -0
  217. package/lib/workbench/settings.js +56 -0
  218. package/lib/workbench/workbench.d.ts +100 -0
  219. package/lib/workbench/workbench.js +260 -0
  220. package/locale/agents/en.json +6 -0
  221. package/locale/agents/zh.json +6 -0
  222. package/locale/commands/en.json +6 -0
  223. package/locale/commands/zh.json +6 -0
  224. package/locale/context/en.json +6 -0
  225. package/locale/context/zh.json +6 -0
  226. package/locale/en.json +6 -0
  227. package/locale/hooks/en.json +6 -0
  228. package/locale/hooks/zh.json +6 -0
  229. package/locale/mcp/en.json +6 -0
  230. package/locale/mcp/zh.json +6 -0
  231. package/locale/mods/en.json +6 -0
  232. package/locale/mods/zh.json +6 -0
  233. package/locale/opencode/en.json +6 -0
  234. package/locale/opencode/zh.json +6 -0
  235. package/locale/porter/en.json +6 -0
  236. package/locale/porter/zh.json +6 -0
  237. package/locale/sessions/en.json +6 -0
  238. package/locale/sessions/zh.json +6 -0
  239. package/locale/skills/en.json +6 -0
  240. package/locale/skills/zh.json +6 -0
  241. package/locale/workbench/en.json +6 -0
  242. package/locale/workbench/zh.json +6 -0
  243. package/locale/zh.json +6 -0
  244. package/package.json +246 -3
  245. package/runtime/opencode-host.mjs +270 -0
  246. package/skills/harness-forge/SKILL.md +47 -0
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Run one hook handler of any type and return its raw outcome:
3
+ *
4
+ * - `command`: exec form (`args`) spawns the executable directly with the
5
+ * placeholders substituted as plain strings; shell form runs in Git Bash
6
+ * (which expands `${CLAUDE_PLUGIN_ROOT}` and friends from the exported
7
+ * environment, defaults included) or in PowerShell, where the placeholders
8
+ * become `${env:NAME}`.
9
+ * - `http`: POSTs the input as JSON; header values interpolate only the
10
+ * allowed environment variables.
11
+ * - `mcp_tool`: calls a tool of a connected MCP server with `${path}` fields
12
+ * filled from the input; its text output is read like stdout.
13
+ * - `prompt` / `agent`: a model call or a delegated agent that answers
14
+ * `{ ok, reason }`.
15
+ * @module @kirkchinese/harness-forge
16
+ */
17
+ import type { Context } from '@deepseek-ai/cordis';
18
+ import type { CommandHandler, HttpHandler, McpToolHandler, ModelHandler } from './config.js';
19
+ import type { RawRun } from './output.js';
20
+ import type { ForeignShell } from './shell.js';
21
+ import type { HookDialect } from './vocabulary.js';
22
+ /** Paths and values a handler may reference. */
23
+ export interface HandlerPlaces {
24
+ readonly pluginRoot: string;
25
+ readonly dataDir: string;
26
+ readonly projectDir: string;
27
+ readonly cwd: string;
28
+ /** Plugin user-config values, by key. */
29
+ readonly options: Readonly<Record<string, string>>;
30
+ /** `CLAUDE_ENV_FILE`, for the events that receive it. */
31
+ readonly envFile?: string;
32
+ }
33
+ /** One run request. */
34
+ export interface HandlerRequest {
35
+ readonly event: string;
36
+ readonly dialect: HookDialect;
37
+ readonly payload: Readonly<Record<string, unknown>>;
38
+ readonly places: HandlerPlaces;
39
+ /** Undefined runs without a timeout. */
40
+ readonly timeoutMs?: number;
41
+ readonly signal: AbortSignal;
42
+ /** The agent the event belongs to, for prompt and agent handlers. */
43
+ readonly agent?: unknown;
44
+ }
45
+ /** A prompt or agent handler's verdict. */
46
+ export interface ModelVerdict {
47
+ readonly ok: boolean;
48
+ readonly reason?: string;
49
+ readonly impossible?: boolean;
50
+ }
51
+ /** A raw outcome, plus the verdict of a model-backed handler. */
52
+ export interface HandlerOutcome extends RawRun {
53
+ readonly verdict?: ModelVerdict;
54
+ readonly durationMs: number;
55
+ }
56
+ /** Executes handlers against the host. */
57
+ export declare class HandlerRunner {
58
+ private readonly ctx;
59
+ private readonly shell;
60
+ private readonly settingsEnv;
61
+ /**
62
+ * @param settingsEnv - the `env` of the harness settings in effect for the
63
+ * event's agent, under the hook-specific variables.
64
+ */
65
+ constructor(ctx: Context, shell: ForeignShell, settingsEnv?: (agent: unknown) => Readonly<Record<string, string>>);
66
+ /** The environment every command handler of a source receives. */
67
+ environment(places: HandlerPlaces, kind: 'bash' | 'powershell' | 'exec', agent?: unknown): Record<string, string | undefined>;
68
+ /** Run a command handler. */
69
+ command(handler: CommandHandler, request: HandlerRequest): Promise<HandlerOutcome>;
70
+ /** Run an HTTP handler. */
71
+ http(handler: HttpHandler, request: HandlerRequest): Promise<HandlerOutcome>;
72
+ /**
73
+ * Run an MCP tool handler.
74
+ * @param toolName - the DSH tool name of `server`/`tool`.
75
+ */
76
+ mcpTool(handler: McpToolHandler, request: HandlerRequest, toolName: string): Promise<HandlerOutcome>;
77
+ /** Run a prompt handler: one model call that answers `{ ok, reason, impossible }`. */
78
+ prompt(handler: ModelHandler, request: HandlerRequest): Promise<HandlerOutcome>;
79
+ /** Run an agent handler: a delegated agent with tool access that answers `{ ok, reason }`. */
80
+ agent(handler: ModelHandler, request: HandlerRequest): Promise<HandlerOutcome>;
81
+ }
82
+ /** PowerShell shell form: path placeholders become `${env:NAME}`. */
83
+ export declare function powershellPlaceholders(command: string): string;
84
+ /** `${a.b}` fields from the input; a placeholder filling a whole value keeps its JSON type. */
85
+ export declare function fillTemplate(template: unknown, payload: Readonly<Record<string, unknown>>): unknown;
@@ -0,0 +1,293 @@
1
+ import { dshService } from '../dsh/host.js';
2
+ import { startActivation } from '../dsh/subagents.js';
3
+ import { messageOf } from '../shared/util.js';
4
+ const PATH_PLACEHOLDERS = ['CLAUDE_PROJECT_DIR', 'CLAUDE_PLUGIN_ROOT', 'CLAUDE_PLUGIN_DATA', 'PLUGIN_ROOT', 'PLUGIN_DATA'];
5
+ /** Executes handlers against the host. */
6
+ export class HandlerRunner {
7
+ ctx;
8
+ shell;
9
+ settingsEnv;
10
+ /**
11
+ * @param settingsEnv - the `env` of the harness settings in effect for the
12
+ * event's agent, under the hook-specific variables.
13
+ */
14
+ constructor(ctx, shell, settingsEnv = () => ({})) {
15
+ this.ctx = ctx;
16
+ this.shell = shell;
17
+ this.settingsEnv = settingsEnv;
18
+ }
19
+ /** The environment every command handler of a source receives. */
20
+ environment(places, kind, agent) {
21
+ const posix = (value) => value.replace(/\\/gu, '/');
22
+ const env = {
23
+ ...this.settingsEnv(agent),
24
+ CLAUDE_PROJECT_DIR: posix(places.projectDir),
25
+ CLAUDE_PLUGIN_ROOT: posix(places.pluginRoot),
26
+ CLAUDE_PLUGIN_DATA: posix(places.dataDir),
27
+ PLUGIN_ROOT: posix(places.pluginRoot),
28
+ PLUGIN_DATA: posix(places.dataDir),
29
+ CLAUDE_ENV_FILE: kind === 'powershell' ? undefined : places.envFile,
30
+ };
31
+ for (const [key, value] of Object.entries(places.options)) {
32
+ env[`CLAUDE_PLUGIN_OPTION_${key.toUpperCase().replace(/[^A-Z0-9]+/gu, '_')}`] = value;
33
+ }
34
+ return env;
35
+ }
36
+ /** Run a command handler. */
37
+ async command(handler, request) {
38
+ const { places } = request;
39
+ const stdin = `${JSON.stringify(request.payload)}${request.dialect === 'claude-code' ? '\n' : ''}`;
40
+ const base = { cwd: places.cwd, stdin, ...(request.timeoutMs !== undefined ? { timeoutMs: request.timeoutMs } : {}), signal: request.signal };
41
+ const command = process.platform === 'win32' && handler.commandWindows !== undefined ? handler.commandWindows : handler.command;
42
+ let outcome;
43
+ if (handler.args !== undefined) {
44
+ const substitute = (value) => substituteExec(value, places);
45
+ outcome = await this.shell.runExec(substitute(command), handler.args.map(substitute), { ...base, env: this.environment(places, 'exec', request.agent) });
46
+ }
47
+ else {
48
+ if (/\$\{user_config\./u.test(command)) {
49
+ return { stdout: '', stderr: '', durationMs: 0, failure: { kind: 'start', message: 'a shell-form plugin hook command references ${user_config.*}; use CLAUDE_PLUGIN_OPTION_<KEY> or exec form' } };
50
+ }
51
+ const kind = handler.shell ?? this.shell.defaultKind;
52
+ const line = kind === 'powershell' ? powershellPlaceholders(command) : command;
53
+ outcome = await this.shell.runShell(line, kind, { ...base, env: this.environment(places, kind, request.agent) });
54
+ }
55
+ if (outcome.startError !== undefined)
56
+ return { stdout: '', stderr: outcome.startError, durationMs: outcome.durationMs, failure: { kind: 'start', message: `failed to start: ${outcome.startError}` } };
57
+ if (outcome.timedOut)
58
+ return { stdout: outcome.stdout, stderr: outcome.stderr, durationMs: outcome.durationMs, failure: { kind: 'timeout', message: `timed out after ${String(request.timeoutMs)}ms` } };
59
+ if (outcome.cancelled)
60
+ return { stdout: '', stderr: '', durationMs: outcome.durationMs, failure: { kind: 'cancelled', message: 'cancelled' } };
61
+ return {
62
+ ...(outcome.exitCode !== undefined ? { exitCode: outcome.exitCode } : {}),
63
+ stdout: outcome.stdout,
64
+ stderr: outcome.stderr,
65
+ suspectCapture: outcome.suspectCapture,
66
+ durationMs: outcome.durationMs,
67
+ };
68
+ }
69
+ /** Run an HTTP handler. */
70
+ async http(handler, request) {
71
+ const started = performance.now();
72
+ const elapsed = () => Math.round(performance.now() - started);
73
+ const allowed = new Set(handler.allowedEnvVars ?? []);
74
+ const interpolate = (value) => value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)/gu, (_match, braced, bare) => {
75
+ const name = braced ?? bare ?? '';
76
+ return allowed.has(name) ? process.env[name] ?? '' : '';
77
+ });
78
+ const signals = [request.signal, ...(request.timeoutMs !== undefined ? [AbortSignal.timeout(request.timeoutMs)] : [])];
79
+ try {
80
+ const response = await fetch(handler.url, {
81
+ method: 'POST',
82
+ headers: { 'content-type': 'application/json', ...Object.fromEntries(Object.entries(handler.headers ?? {}).map(([key, value]) => [key, interpolate(value)])) },
83
+ body: JSON.stringify(request.payload),
84
+ signal: AbortSignal.any(signals),
85
+ });
86
+ const body = await response.text();
87
+ if (!response.ok)
88
+ return { stdout: '', stderr: body, durationMs: elapsed(), failure: { kind: 'transport', message: `HTTP ${String(response.status)} from ${handler.url}` } };
89
+ const trimmed = body.trim();
90
+ if (trimmed.length > 0 && !isJsonObject(trimmed)) {
91
+ return { stdout: '', stderr: body, durationMs: elapsed(), failure: { kind: 'transport', message: 'the response body is neither empty nor a JSON object' } };
92
+ }
93
+ return { exitCode: 0, stdout: trimmed, stderr: '', durationMs: elapsed() };
94
+ }
95
+ catch (error) {
96
+ if (request.signal.aborted)
97
+ return { stdout: '', stderr: '', durationMs: elapsed(), failure: { kind: 'cancelled', message: 'cancelled' } };
98
+ const timedOut = error instanceof Error && (error.name === 'TimeoutError' || error.name === 'AbortError');
99
+ return { stdout: '', stderr: '', durationMs: elapsed(), failure: timedOut ? { kind: 'timeout', message: `timed out after ${String(request.timeoutMs)}ms` } : { kind: 'transport', message: `request to ${handler.url} failed: ${messageOf(error)}` } };
100
+ }
101
+ }
102
+ /**
103
+ * Run an MCP tool handler.
104
+ * @param toolName - the DSH tool name of `server`/`tool`.
105
+ */
106
+ async mcpTool(handler, request, toolName) {
107
+ const started = performance.now();
108
+ const elapsed = () => Math.round(performance.now() - started);
109
+ const tools = dshService(this.ctx, 'tools');
110
+ const definition = tools?.get(toolName);
111
+ if (definition === undefined)
112
+ return { stdout: '', stderr: '', durationMs: 0, failure: { kind: 'transport', message: `MCP tool ${toolName} is not connected` } };
113
+ const input = fillTemplate(handler.input ?? {}, request.payload);
114
+ const signal = request.timeoutMs === undefined ? request.signal : AbortSignal.any([request.signal, AbortSignal.timeout(request.timeoutMs)]);
115
+ 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('');
118
+ const isError = typeof value === 'object' && value !== null && value.isError === true;
119
+ return isError
120
+ ? { stdout: '', stderr: text, durationMs: elapsed(), failure: { kind: 'transport', message: `MCP tool ${toolName} returned an error: ${text.slice(0, 300)}` } }
121
+ : { exitCode: 0, stdout: text, stderr: '', durationMs: elapsed() };
122
+ }
123
+ catch (error) {
124
+ if (request.signal.aborted)
125
+ return { stdout: '', stderr: '', durationMs: elapsed(), failure: { kind: 'cancelled', message: 'cancelled' } };
126
+ return { stdout: '', stderr: '', durationMs: elapsed(), failure: signal.aborted ? { kind: 'timeout', message: `timed out after ${String(request.timeoutMs)}ms` } : { kind: 'transport', message: messageOf(error) } };
127
+ }
128
+ }
129
+ /** Run a prompt handler: one model call that answers `{ ok, reason, impossible }`. */
130
+ async prompt(handler, request) {
131
+ const started = performance.now();
132
+ const elapsed = () => Math.round(performance.now() - started);
133
+ const llm = dshService(this.ctx, 'llm');
134
+ const options = request.agent?.options;
135
+ if (llm === undefined || options?.provider === undefined || options.model === undefined) {
136
+ return { stdout: '', stderr: '', durationMs: 0, failure: { kind: 'start', message: 'no model route is available for prompt hooks in this session' } };
137
+ }
138
+ const signal = request.timeoutMs === undefined ? request.signal : AbortSignal.any([request.signal, AbortSignal.timeout(request.timeoutMs)]);
139
+ try {
140
+ const call = await llm.prepareCall({ provider: options.provider, model: options.model, maxTokens: 1024 }, signal);
141
+ const chunks = [];
142
+ for await (const chunk of call.stream({
143
+ ...call.config,
144
+ messages: [{ role: 'user', content: [{ type: 'text', text: promptText(handler.prompt, request.payload) }], source: { kind: 'harness-forge', event: request.event } }],
145
+ system: VERDICT_SYSTEM,
146
+ purpose: 'hook-evaluation',
147
+ signal,
148
+ })) {
149
+ const text = textDelta(chunk);
150
+ if (text !== undefined)
151
+ chunks.push(text);
152
+ }
153
+ return { exitCode: 0, stdout: '', stderr: '', durationMs: elapsed(), verdict: parseVerdict(chunks.join('')) };
154
+ }
155
+ catch (error) {
156
+ if (request.signal.aborted)
157
+ return { stdout: '', stderr: '', durationMs: elapsed(), failure: { kind: 'cancelled', message: 'cancelled' } };
158
+ return { stdout: '', stderr: '', durationMs: elapsed(), failure: signal.aborted ? { kind: 'timeout', message: `timed out after ${String(request.timeoutMs)}ms` } : { kind: 'transport', message: `prompt hook model call failed: ${messageOf(error)}` } };
159
+ }
160
+ }
161
+ /** Run an agent handler: a delegated agent with tool access that answers `{ ok, reason }`. */
162
+ async agent(handler, request) {
163
+ const started = performance.now();
164
+ const elapsed = () => Math.round(performance.now() - started);
165
+ const subagents = dshService(this.ctx, 'subagents');
166
+ if (subagents === undefined || request.agent === undefined) {
167
+ return { stdout: '', stderr: '', durationMs: 0, failure: { kind: 'start', message: 'agent hooks need the DSH subagent runtime' } };
168
+ }
169
+ const signal = request.timeoutMs === undefined ? request.signal : AbortSignal.any([request.signal, AbortSignal.timeout(request.timeoutMs)]);
170
+ let activation;
171
+ try {
172
+ activation = await startActivation(subagents, {
173
+ parent: request.agent,
174
+ prompt: [{ type: 'text', text: `${promptText(handler.prompt, request.payload)}\n\n${VERDICT_SYSTEM}` }],
175
+ outputSchema: VERDICT_SCHEMA,
176
+ }, { provider: 'spawn', label: `${request.event} hook`, signal, delivery: 'caller' });
177
+ const onAbort = () => { void activation?.dispose(); };
178
+ signal.addEventListener('abort', onAbort, { once: true });
179
+ const result = await activation.result;
180
+ signal.removeEventListener('abort', onAbort);
181
+ const structured = result.structured;
182
+ const verdict = typeof structured === 'object' && structured !== null && typeof structured.ok === 'boolean'
183
+ ? structured
184
+ : parseVerdict((result.output ?? []).map(block => block.type === 'text' ? block.text ?? '' : '').join(''));
185
+ return { exitCode: 0, stdout: '', stderr: '', durationMs: elapsed(), verdict: { ok: verdict.ok, ...(verdict.reason !== undefined ? { reason: verdict.reason } : {}) } };
186
+ }
187
+ catch (error) {
188
+ void activation?.dispose().catch(() => undefined);
189
+ if (request.signal.aborted)
190
+ return { stdout: '', stderr: '', durationMs: elapsed(), failure: { kind: 'cancelled', message: 'cancelled' } };
191
+ return { stdout: '', stderr: '', durationMs: elapsed(), failure: signal.aborted ? { kind: 'timeout', message: `timed out after ${String(request.timeoutMs)}ms` } : { kind: 'transport', message: `agent hook failed: ${messageOf(error)}` } };
192
+ }
193
+ }
194
+ }
195
+ const VERDICT_SYSTEM = 'You evaluate a hook condition for a coding agent. Respond with only a JSON object: {"ok": true} when the condition holds or the action may proceed, or {"ok": false, "reason": "<why>"} when it does not. Add "impossible": true when the condition can never be satisfied.';
196
+ const VERDICT_SCHEMA = {
197
+ type: 'object',
198
+ properties: { ok: { type: 'boolean' }, reason: { type: 'string' } },
199
+ required: ['ok'],
200
+ additionalProperties: false,
201
+ };
202
+ /** `$ARGUMENTS` → the input JSON (`\$` escapes); appended when absent. */
203
+ function promptText(prompt, payload) {
204
+ const json = JSON.stringify(payload);
205
+ let used = false;
206
+ const text = prompt.replace(/\\\$|\$ARGUMENTS\b/gu, (match) => {
207
+ if (match === '\\$')
208
+ return '$';
209
+ used = true;
210
+ return json;
211
+ });
212
+ return used ? text : `${text}\n\n${json}`;
213
+ }
214
+ function parseVerdict(text) {
215
+ const match = /\{[\s\S]*\}/u.exec(text);
216
+ if (match !== null) {
217
+ try {
218
+ const value = JSON.parse(match[0]);
219
+ if (typeof value['ok'] === 'boolean') {
220
+ return {
221
+ ok: value['ok'],
222
+ ...(typeof value['reason'] === 'string' ? { reason: value['reason'] } : {}),
223
+ ...(value['impossible'] === true ? { impossible: true } : {}),
224
+ };
225
+ }
226
+ }
227
+ catch {
228
+ // Fall through.
229
+ }
230
+ }
231
+ return { ok: false, reason: `the hook model did not answer with {"ok": …}: ${text.slice(0, 200)}` };
232
+ }
233
+ function textDelta(chunk) {
234
+ if (typeof chunk !== 'object' || chunk === null)
235
+ return undefined;
236
+ const value = chunk;
237
+ if (value.type === 'text-delta' && typeof value.text === 'string')
238
+ return value.text;
239
+ if (value.type === 'text-delta' && typeof value.delta === 'string')
240
+ return value.delta;
241
+ if (value.type === 'text' && typeof value.text === 'string')
242
+ return value.text;
243
+ return undefined;
244
+ }
245
+ /** Exec form: placeholders are substituted as plain strings. */
246
+ function substituteExec(value, places) {
247
+ const posix = (path) => path.replace(/\\/gu, '/');
248
+ const values = {
249
+ CLAUDE_PROJECT_DIR: posix(places.projectDir),
250
+ CLAUDE_PLUGIN_ROOT: posix(places.pluginRoot),
251
+ CLAUDE_PLUGIN_DATA: posix(places.dataDir),
252
+ PLUGIN_ROOT: posix(places.pluginRoot),
253
+ PLUGIN_DATA: posix(places.dataDir),
254
+ };
255
+ return value
256
+ .replace(/\$\{user_config\.([A-Za-z0-9_.-]+)\}/gu, (_match, key) => places.options[key] ?? '')
257
+ .replace(/\$\{([A-Z_]+)\}/gu, (match, name) => values[name] ?? match);
258
+ }
259
+ /** PowerShell shell form: path placeholders become `${env:NAME}`. */
260
+ export function powershellPlaceholders(command) {
261
+ let out = command;
262
+ for (const name of PATH_PLACEHOLDERS)
263
+ out = out.split(`\${${name}}`).join(`\${env:${name}}`);
264
+ return out;
265
+ }
266
+ /** `${a.b}` fields from the input; a placeholder filling a whole value keeps its JSON type. */
267
+ export function fillTemplate(template, payload) {
268
+ const lookup = (path) => path.split('.').reduce((value, key) => (typeof value === 'object' && value !== null ? value[key] : undefined), payload);
269
+ if (typeof template === 'string') {
270
+ const whole = /^\$\{([A-Za-z0-9_.]+)\}$/u.exec(template);
271
+ if (whole !== null)
272
+ return lookup(whole[1] ?? '');
273
+ return template.replace(/\$\{([A-Za-z0-9_.]+)\}/gu, (_match, path) => {
274
+ const value = lookup(path);
275
+ return value === undefined ? '' : typeof value === 'string' ? value : JSON.stringify(value);
276
+ });
277
+ }
278
+ if (Array.isArray(template))
279
+ return template.map(item => fillTemplate(item, payload));
280
+ if (typeof template === 'object' && template !== null) {
281
+ return Object.fromEntries(Object.entries(template).map(([key, value]) => [key, fillTemplate(value, payload)]));
282
+ }
283
+ return template;
284
+ }
285
+ function isJsonObject(text) {
286
+ try {
287
+ const value = JSON.parse(text);
288
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
289
+ }
290
+ catch {
291
+ return false;
292
+ }
293
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * The commands one shell input runs, as Claude Code's `if` matching sees
3
+ * them: every subcommand of `&&`, `||`, `;`, `|`, `&` and newlines, every
4
+ * command inside `$(…)` and backticks, with leading `VAR=value` assignments
5
+ * stripped.
6
+ * @module @kirkchinese/harness-forge
7
+ */
8
+ /** The commands found in one input. */
9
+ export interface ShellCommands {
10
+ readonly commands: readonly string[];
11
+ /** The input expands something at run time: `$(…)`, backticks or `$VAR`. */
12
+ readonly dynamic: boolean;
13
+ }
14
+ /**
15
+ * Split a shell input into the commands it runs.
16
+ * @returns undefined when the input cannot be read reliably (unbalanced
17
+ * quotes or substitutions), in which case a caller treats every rule as a match.
18
+ */
19
+ export declare function shellCommands(input: string): ShellCommands | undefined;
@@ -0,0 +1,177 @@
1
+ /**
2
+ * The commands one shell input runs, as Claude Code's `if` matching sees
3
+ * them: every subcommand of `&&`, `||`, `;`, `|`, `&` and newlines, every
4
+ * command inside `$(…)` and backticks, with leading `VAR=value` assignments
5
+ * stripped.
6
+ * @module @kirkchinese/harness-forge
7
+ */
8
+ /**
9
+ * Split a shell input into the commands it runs.
10
+ * @returns undefined when the input cannot be read reliably (unbalanced
11
+ * quotes or substitutions), in which case a caller treats every rule as a match.
12
+ */
13
+ export function shellCommands(input) {
14
+ const commands = [];
15
+ let dynamic = false;
16
+ const visit = (text, depth) => {
17
+ if (depth > 8)
18
+ return false;
19
+ let current = '';
20
+ const flush = () => {
21
+ const command = stripAssignments(current.trim());
22
+ if (command.length > 0)
23
+ commands.push(command);
24
+ current = '';
25
+ };
26
+ for (let index = 0; index < text.length; index++) {
27
+ const char = text[index] ?? '';
28
+ const next = text[index + 1] ?? '';
29
+ if (char === '\\') {
30
+ current += char + next;
31
+ index++;
32
+ continue;
33
+ }
34
+ if (char === "'") {
35
+ const end = text.indexOf("'", index + 1);
36
+ if (end === -1)
37
+ return false;
38
+ current += text.slice(index, end + 1);
39
+ index = end;
40
+ continue;
41
+ }
42
+ if (char === '"') {
43
+ let end = index + 1;
44
+ let quoted = '';
45
+ for (; end < text.length; end++) {
46
+ const inner = text[end] ?? '';
47
+ if (inner === '\\') {
48
+ quoted += inner + (text[end + 1] ?? '');
49
+ end++;
50
+ continue;
51
+ }
52
+ if (inner === '"')
53
+ break;
54
+ if (inner === '$' && text[end + 1] === '(') {
55
+ const close = matchParen(text, end + 1);
56
+ if (close === -1)
57
+ return false;
58
+ dynamic = true;
59
+ if (!visit(text.slice(end + 2, close), depth + 1))
60
+ return false;
61
+ quoted += text.slice(end, close + 1);
62
+ end = close;
63
+ continue;
64
+ }
65
+ if (inner === '`') {
66
+ const close = text.indexOf('`', end + 1);
67
+ if (close === -1)
68
+ return false;
69
+ dynamic = true;
70
+ if (!visit(text.slice(end + 1, close), depth + 1))
71
+ return false;
72
+ quoted += text.slice(end, close + 1);
73
+ end = close;
74
+ continue;
75
+ }
76
+ if (inner === '$' && /[A-Za-z_{]/u.test(text[end + 1] ?? ''))
77
+ dynamic = true;
78
+ quoted += inner;
79
+ }
80
+ if (end >= text.length)
81
+ return false;
82
+ current += `"${quoted}"`;
83
+ index = end;
84
+ continue;
85
+ }
86
+ if (char === '$' && next === '(') {
87
+ const close = matchParen(text, index + 1);
88
+ if (close === -1)
89
+ return false;
90
+ dynamic = true;
91
+ if (!visit(text.slice(index + 2, close), depth + 1))
92
+ return false;
93
+ current += text.slice(index, close + 1);
94
+ index = close;
95
+ continue;
96
+ }
97
+ if (char === '`') {
98
+ const close = text.indexOf('`', index + 1);
99
+ if (close === -1)
100
+ return false;
101
+ dynamic = true;
102
+ if (!visit(text.slice(index + 1, close), depth + 1))
103
+ return false;
104
+ current += text.slice(index, close + 1);
105
+ index = close;
106
+ continue;
107
+ }
108
+ if (char === '$' && /[A-Za-z_{]/u.test(next))
109
+ dynamic = true;
110
+ if ((char === '&' && next === '&') || (char === '|' && next === '|')) {
111
+ flush();
112
+ index++;
113
+ continue;
114
+ }
115
+ if (char === ';' || char === '|' || char === '\n' || (char === '&' && next !== '>' && text[index - 1] !== '>')) {
116
+ flush();
117
+ continue;
118
+ }
119
+ // Grouping: `( cmd )` and `{ cmd; }` run the commands inside them.
120
+ if ((char === '(' || char === '{') && current.trim().length === 0)
121
+ continue;
122
+ if ((char === ')' || char === '}') && !/[({]/u.test(current)) {
123
+ flush();
124
+ continue;
125
+ }
126
+ current += char;
127
+ }
128
+ flush();
129
+ return true;
130
+ };
131
+ return visit(input, 0) ? { commands, dynamic } : undefined;
132
+ }
133
+ /** Remove leading `NAME=value` words. */
134
+ function stripAssignments(command) {
135
+ let rest = command;
136
+ 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);
141
+ }
142
+ }
143
+ /** Index of the `)` closing the `(` at `open`, honoring nesting and quotes. */
144
+ function matchParen(text, open) {
145
+ let depth = 0;
146
+ for (let index = open; index < text.length; index++) {
147
+ const char = text[index];
148
+ if (char === '\\') {
149
+ index++;
150
+ continue;
151
+ }
152
+ if (char === "'") {
153
+ const end = text.indexOf("'", index + 1);
154
+ if (end === -1)
155
+ return -1;
156
+ index = end;
157
+ continue;
158
+ }
159
+ if (char === '"') {
160
+ let end = index + 1;
161
+ while (end < text.length && text[end] !== '"')
162
+ end += text[end] === '\\' ? 2 : 1;
163
+ if (end >= text.length)
164
+ return -1;
165
+ index = end;
166
+ continue;
167
+ }
168
+ if (char === '(')
169
+ depth++;
170
+ if (char === ')') {
171
+ depth--;
172
+ if (depth === 0)
173
+ return index;
174
+ }
175
+ }
176
+ return -1;
177
+ }
@@ -0,0 +1,43 @@
1
+ import { type ProcessOutcome } from './process.js';
2
+ /** How one process runs. */
3
+ export interface RunOptions {
4
+ readonly cwd: string;
5
+ readonly env?: Readonly<Record<string, string | undefined>>;
6
+ readonly stdin?: string;
7
+ readonly timeoutMs?: number;
8
+ readonly signal?: AbortSignal;
9
+ }
10
+ /** The executors foreign code runs with. */
11
+ export interface ForeignShell {
12
+ /** Git Bash, bash, or `/bin/sh` without it; undefined on Windows without Git Bash. */
13
+ readonly bash?: string;
14
+ /** `pwsh.exe` when installed, else `powershell.exe` (`pwsh` elsewhere). */
15
+ readonly powershell: string;
16
+ /** The shell a shell-form command uses when none is named. */
17
+ readonly defaultKind: 'bash' | 'powershell';
18
+ /** The environment foreign processes start from, with `extra` applied. */
19
+ environment(extra?: Readonly<Record<string, string | undefined>>): NodeJS.ProcessEnv;
20
+ /** Run a shell-form command line. */
21
+ runShell(command: string, kind: 'bash' | 'powershell', options: RunOptions): Promise<ProcessOutcome>;
22
+ /** Spawn an executable directly with an argument vector (exec form). */
23
+ runExec(file: string, args: readonly string[], options: RunOptions): Promise<ProcessOutcome>;
24
+ }
25
+ /** Locate the POSIX shell foreign hooks expect. */
26
+ export declare function findPosixShell(env?: NodeJS.ProcessEnv): {
27
+ shell: string;
28
+ pathPrefix: string[];
29
+ } | undefined;
30
+ /** PowerShell 7 when it is on PATH, else Windows PowerShell. */
31
+ export declare function findPowerShell(env?: NodeJS.ProcessEnv): string;
32
+ /**
33
+ * Hook scripts call `python3`. On Windows that name is usually the Microsoft
34
+ * Store placeholder while the real interpreter is `python`; a one-line shim
35
+ * makes `python3` run it, so Python hooks work without changing the machine.
36
+ * @returns the shim directory to put first on PATH, when one is needed.
37
+ */
38
+ export declare function python3Shim(shimRoot: string, env?: NodeJS.ProcessEnv): string | undefined;
39
+ /**
40
+ * Build the executors.
41
+ * @param shimRoot - writable directory for command shims (see {@link python3Shim}).
42
+ */
43
+ export declare function createForeignShell(base?: NodeJS.ProcessEnv, shimRoot?: string): ForeignShell;