@kirkchinese/harness-forge 0.0.0-stage → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (279) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +46 -2
  3. package/assets/icon.svg +12 -0
  4. package/cordis.patch.yml +28 -0
  5. package/docs/DETAIL.zh.md +47 -0
  6. package/lib/agents/presets.d.ts +98 -0
  7. package/lib/agents/presets.js +292 -0
  8. package/lib/agents/profiles.d.ts +58 -0
  9. package/lib/agents/profiles.js +279 -0
  10. package/lib/agents/row.d.ts +17 -0
  11. package/lib/agents/row.js +148 -0
  12. package/lib/client/paths.d.ts +12 -0
  13. package/lib/client/paths.js +68 -0
  14. package/lib/client/styles.d.ts +8 -0
  15. package/lib/client/styles.js +89 -0
  16. package/lib/client/typert.d.ts +25 -0
  17. package/lib/client/typert.js +158 -0
  18. package/lib/client.js +23823 -0
  19. package/lib/commands/definition.d.ts +40 -0
  20. package/lib/commands/definition.js +113 -0
  21. package/lib/commands/output-styles.d.ts +42 -0
  22. package/lib/commands/output-styles.js +152 -0
  23. package/lib/commands/row.d.ts +9 -0
  24. package/lib/commands/row.js +157 -0
  25. package/lib/context/instructions.d.ts +32 -0
  26. package/lib/context/instructions.js +88 -0
  27. package/lib/context/row.d.ts +16 -0
  28. package/lib/context/row.js +17 -0
  29. package/lib/dsh/commands.d.ts +30 -0
  30. package/lib/dsh/commands.js +61 -0
  31. package/lib/dsh/host.d.ts +110 -0
  32. package/lib/dsh/host.js +217 -0
  33. package/lib/dsh/model-route.d.ts +21 -0
  34. package/lib/dsh/model-route.js +37 -0
  35. package/lib/dsh/session-records.d.ts +78 -0
  36. package/lib/dsh/session-records.js +36 -0
  37. package/lib/dsh/subagents.d.ts +46 -0
  38. package/lib/dsh/subagents.js +14 -0
  39. package/lib/forge/contract.d.ts +271 -0
  40. package/lib/forge/contract.js +45 -0
  41. package/lib/forge/follow.d.ts +30 -0
  42. package/lib/forge/follow.js +73 -0
  43. package/lib/forge/ledger.d.ts +206 -0
  44. package/lib/forge/ledger.js +1005 -0
  45. package/lib/forge/live-mounts.d.ts +45 -0
  46. package/lib/forge/live-mounts.js +78 -0
  47. package/lib/forge/npm.d.ts +31 -0
  48. package/lib/forge/npm.js +60 -0
  49. package/lib/forge/projects.d.ts +97 -0
  50. package/lib/forge/projects.js +343 -0
  51. package/lib/forge/receipts.d.ts +5 -0
  52. package/lib/forge/receipts.js +31 -0
  53. package/lib/forge/remote/archive.d.ts +65 -0
  54. package/lib/forge/remote/archive.js +565 -0
  55. package/lib/forge/remote/code-parts.d.ts +18 -0
  56. package/lib/forge/remote/code-parts.js +76 -0
  57. package/lib/forge/remote/fetch.d.ts +265 -0
  58. package/lib/forge/remote/fetch.js +1133 -0
  59. package/lib/forge/remote/service.d.ts +256 -0
  60. package/lib/forge/remote/service.js +868 -0
  61. package/lib/forge/row.d.ts +32 -0
  62. package/lib/forge/row.js +59 -0
  63. package/lib/forge/service.d.ts +115 -0
  64. package/lib/forge/service.js +290 -0
  65. package/lib/forge/settings.d.ts +43 -0
  66. package/lib/forge/settings.js +122 -0
  67. package/lib/forge/state.d.ts +129 -0
  68. package/lib/forge/state.js +266 -0
  69. package/lib/forge/trust.d.ts +48 -0
  70. package/lib/forge/trust.js +107 -0
  71. package/lib/forge/turns.d.ts +13 -0
  72. package/lib/forge/turns.js +56 -0
  73. package/lib/hooks/broker/engine.d.ts +112 -0
  74. package/lib/hooks/broker/engine.js +722 -0
  75. package/lib/hooks/broker/helpers.d.ts +10 -0
  76. package/lib/hooks/broker/helpers.js +22 -0
  77. package/lib/hooks/broker/lifecycle.d.ts +65 -0
  78. package/lib/hooks/broker/lifecycle.js +342 -0
  79. package/lib/hooks/broker/session-events.d.ts +27 -0
  80. package/lib/hooks/broker/session-events.js +205 -0
  81. package/lib/hooks/broker/tools.d.ts +52 -0
  82. package/lib/hooks/broker/tools.js +424 -0
  83. package/lib/hooks/broker/types.d.ts +264 -0
  84. package/lib/hooks/broker/types.js +1 -0
  85. package/lib/hooks/broker.d.ts +80 -0
  86. package/lib/hooks/broker.js +95 -0
  87. package/lib/hooks/codex-user.d.ts +5 -0
  88. package/lib/hooks/codex-user.js +109 -0
  89. package/lib/hooks/condition.d.ts +87 -0
  90. package/lib/hooks/condition.js +602 -0
  91. package/lib/hooks/config.d.ts +85 -0
  92. package/lib/hooks/config.js +154 -0
  93. package/lib/hooks/glob.d.ts +41 -0
  94. package/lib/hooks/glob.js +114 -0
  95. package/lib/hooks/matcher.d.ts +20 -0
  96. package/lib/hooks/matcher.js +39 -0
  97. package/lib/hooks/notice.d.ts +17 -0
  98. package/lib/hooks/notice.js +39 -0
  99. package/lib/hooks/output.d.ts +56 -0
  100. package/lib/hooks/output.js +214 -0
  101. package/lib/hooks/permissions.d.ts +19 -0
  102. package/lib/hooks/permissions.js +202 -0
  103. package/lib/hooks/powershell-aliases.d.ts +19 -0
  104. package/lib/hooks/powershell-aliases.js +58 -0
  105. package/lib/hooks/process.d.ts +64 -0
  106. package/lib/hooks/process.js +289 -0
  107. package/lib/hooks/row.d.ts +17 -0
  108. package/lib/hooks/row.js +96 -0
  109. package/lib/hooks/runner.d.ts +98 -0
  110. package/lib/hooks/runner.js +322 -0
  111. package/lib/hooks/shell-commands.d.ts +28 -0
  112. package/lib/hooks/shell-commands.js +241 -0
  113. package/lib/hooks/shell.d.ts +44 -0
  114. package/lib/hooks/shell.js +129 -0
  115. package/lib/hooks/transcript.d.ts +28 -0
  116. package/lib/hooks/transcript.js +141 -0
  117. package/lib/hooks/vocabulary.d.ts +57 -0
  118. package/lib/hooks/vocabulary.js +366 -0
  119. package/lib/index.d.ts +31 -0
  120. package/lib/index.js +287 -0
  121. package/lib/mcp/auth.d.ts +35 -0
  122. package/lib/mcp/auth.js +178 -0
  123. package/lib/mcp/catalog.d.ts +39 -0
  124. package/lib/mcp/catalog.js +69 -0
  125. package/lib/mcp/mount.d.ts +113 -0
  126. package/lib/mcp/mount.js +317 -0
  127. package/lib/mcp/policy.d.ts +42 -0
  128. package/lib/mcp/policy.js +43 -0
  129. package/lib/mcp/remote.d.ts +45 -0
  130. package/lib/mcp/remote.js +133 -0
  131. package/lib/mcp/row.d.ts +9 -0
  132. package/lib/mcp/row.js +225 -0
  133. package/lib/mods/bundler.d.ts +38 -0
  134. package/lib/mods/bundler.js +157 -0
  135. package/lib/mods/chain.d.ts +103 -0
  136. package/lib/mods/chain.js +436 -0
  137. package/lib/mods/claude.d.ts +27 -0
  138. package/lib/mods/claude.js +56 -0
  139. package/lib/mods/engine.d.ts +160 -0
  140. package/lib/mods/engine.js +701 -0
  141. package/lib/mods/expect.d.ts +8 -0
  142. package/lib/mods/expect.js +248 -0
  143. package/lib/mods/host.d.ts +105 -0
  144. package/lib/mods/host.js +462 -0
  145. package/lib/mods/loader.d.ts +53 -0
  146. package/lib/mods/loader.js +231 -0
  147. package/lib/mods/ops.d.ts +13 -0
  148. package/lib/mods/ops.js +117 -0
  149. package/lib/mods/row.d.ts +9 -0
  150. package/lib/mods/row.js +77 -0
  151. package/lib/mods/runtime.d.ts +60 -0
  152. package/lib/mods/runtime.js +133 -0
  153. package/lib/mods/service/commands.d.ts +17 -0
  154. package/lib/mods/service/commands.js +121 -0
  155. package/lib/mods/service/drawings.d.ts +36 -0
  156. package/lib/mods/service/drawings.js +64 -0
  157. package/lib/mods/service/sessions.d.ts +63 -0
  158. package/lib/mods/service/sessions.js +345 -0
  159. package/lib/mods/service/tools.d.ts +32 -0
  160. package/lib/mods/service/tools.js +253 -0
  161. package/lib/mods/service/turns.d.ts +33 -0
  162. package/lib/mods/service/turns.js +136 -0
  163. package/lib/mods/service/types.d.ts +151 -0
  164. package/lib/mods/service/types.js +1 -0
  165. package/lib/mods/service.d.ts +72 -0
  166. package/lib/mods/service.js +104 -0
  167. package/lib/mods/surfaces.d.ts +93 -0
  168. package/lib/mods/surfaces.js +309 -0
  169. package/lib/mods/values.d.ts +30 -0
  170. package/lib/mods/values.js +95 -0
  171. package/lib/opencode/bun.d.ts +40 -0
  172. package/lib/opencode/bun.js +168 -0
  173. package/lib/opencode/convert.d.ts +53 -0
  174. package/lib/opencode/convert.js +255 -0
  175. package/lib/opencode/row.d.ts +22 -0
  176. package/lib/opencode/row.js +104 -0
  177. package/lib/opencode/runtime/core.d.ts +74 -0
  178. package/lib/opencode/runtime/core.js +249 -0
  179. package/lib/opencode/runtime/events.d.ts +80 -0
  180. package/lib/opencode/runtime/events.js +281 -0
  181. package/lib/opencode/runtime/mount.d.ts +27 -0
  182. package/lib/opencode/runtime/mount.js +283 -0
  183. package/lib/opencode/runtime/server.d.ts +27 -0
  184. package/lib/opencode/runtime/server.js +354 -0
  185. package/lib/opencode/runtime/types.d.ts +109 -0
  186. package/lib/opencode/runtime/types.js +1 -0
  187. package/lib/opencode/runtime.d.ts +55 -0
  188. package/lib/opencode/runtime.js +79 -0
  189. package/lib/porting/adapter-paths.d.ts +13 -0
  190. package/lib/porting/adapter-paths.js +120 -0
  191. package/lib/porting/port-gap.d.ts +36 -0
  192. package/lib/porting/port-gap.js +158 -0
  193. package/lib/porting/port-sessions.d.ts +41 -0
  194. package/lib/porting/port-sessions.js +98 -0
  195. package/lib/porting/prompt.d.ts +23 -0
  196. package/lib/porting/prompt.js +51 -0
  197. package/lib/porting/row.d.ts +16 -0
  198. package/lib/porting/row.js +27 -0
  199. package/lib/porting/verify-port.d.ts +46 -0
  200. package/lib/porting/verify-port.js +82 -0
  201. package/lib/presets/fs-search.d.ts +25 -0
  202. package/lib/presets/fs-search.js +17 -0
  203. package/lib/presets/tool-filter.d.ts +35 -0
  204. package/lib/presets/tool-filter.js +91 -0
  205. package/lib/sessions/chat-import.d.ts +48 -0
  206. package/lib/sessions/chat-import.js +44 -0
  207. package/lib/sessions/claude.d.ts +35 -0
  208. package/lib/sessions/claude.js +104 -0
  209. package/lib/sessions/codex-discover.d.ts +34 -0
  210. package/lib/sessions/codex-discover.js +205 -0
  211. package/lib/sessions/codex-meta.d.ts +63 -0
  212. package/lib/sessions/codex-meta.js +148 -0
  213. package/lib/sessions/codex-text.d.ts +9 -0
  214. package/lib/sessions/codex-text.js +44 -0
  215. package/lib/sessions/codex.d.ts +42 -0
  216. package/lib/sessions/codex.js +270 -0
  217. package/lib/sessions/opencode.d.ts +38 -0
  218. package/lib/sessions/opencode.js +339 -0
  219. package/lib/sessions/persist.d.ts +162 -0
  220. package/lib/sessions/persist.js +377 -0
  221. package/lib/sessions/row.d.ts +15 -0
  222. package/lib/sessions/row.js +101 -0
  223. package/lib/sessions/turns.d.ts +31 -0
  224. package/lib/sessions/turns.js +63 -0
  225. package/lib/sessions/zstd.d.ts +15 -0
  226. package/lib/sessions/zstd.js +152 -0
  227. package/lib/shared/invocation.d.ts +169 -0
  228. package/lib/shared/invocation.js +325 -0
  229. package/lib/shared/render.d.ts +101 -0
  230. package/lib/shared/render.js +1353 -0
  231. package/lib/shared/util.d.ts +21 -0
  232. package/lib/shared/util.js +32 -0
  233. package/lib/skills/bundled.d.ts +3 -0
  234. package/lib/skills/bundled.js +42 -0
  235. package/lib/skills/provider.d.ts +74 -0
  236. package/lib/skills/provider.js +346 -0
  237. package/lib/skills/row.d.ts +22 -0
  238. package/lib/skills/row.js +204 -0
  239. package/lib/workbench/adapter-coverage.d.ts +65 -0
  240. package/lib/workbench/adapter-coverage.js +141 -0
  241. package/lib/workbench/model-tools.d.ts +10 -0
  242. package/lib/workbench/model-tools.js +122 -0
  243. package/lib/workbench/overview.d.ts +153 -0
  244. package/lib/workbench/overview.js +246 -0
  245. package/lib/workbench/remote.d.ts +161 -0
  246. package/lib/workbench/remote.js +561 -0
  247. package/lib/workbench/row.d.ts +15 -0
  248. package/lib/workbench/row.js +16 -0
  249. package/lib/workbench/settings.d.ts +19 -0
  250. package/lib/workbench/settings.js +60 -0
  251. package/lib/workbench/workbench.d.ts +130 -0
  252. package/lib/workbench/workbench.js +361 -0
  253. package/locale/agents/en.json +6 -0
  254. package/locale/agents/zh.json +6 -0
  255. package/locale/commands/en.json +6 -0
  256. package/locale/commands/zh.json +6 -0
  257. package/locale/context/en.json +6 -0
  258. package/locale/context/zh.json +6 -0
  259. package/locale/en.json +6 -0
  260. package/locale/hooks/en.json +6 -0
  261. package/locale/hooks/zh.json +6 -0
  262. package/locale/mcp/en.json +6 -0
  263. package/locale/mcp/zh.json +6 -0
  264. package/locale/mods/en.json +6 -0
  265. package/locale/mods/zh.json +6 -0
  266. package/locale/opencode/en.json +6 -0
  267. package/locale/opencode/zh.json +6 -0
  268. package/locale/porter/en.json +6 -0
  269. package/locale/porter/zh.json +6 -0
  270. package/locale/sessions/en.json +6 -0
  271. package/locale/sessions/zh.json +6 -0
  272. package/locale/skills/en.json +6 -0
  273. package/locale/skills/zh.json +6 -0
  274. package/locale/workbench/en.json +6 -0
  275. package/locale/workbench/zh.json +6 -0
  276. package/locale/zh.json +7 -0
  277. package/package.json +247 -3
  278. package/runtime/opencode-host.mjs +270 -0
  279. package/skills/harness-forge/SKILL.md +47 -0
@@ -0,0 +1,289 @@
1
+ /**
2
+ * Run one hook process the way Claude Code does: JSON on stdin, output read
3
+ * until shortly after the process itself exits (a background child that
4
+ * keeps the pipes open does not hold the hook), an optional timeout, and
5
+ * cancellation through a signal. A timeout or cancellation ends the hook's
6
+ * whole process tree, not only the process that was started.
7
+ *
8
+ * Stdin is a file holding the input, not a pipe, when one can be made (see
9
+ * `stdinFile`): a hook that reads it synchronously at once (`readFileSync(0)`)
10
+ * then always gets all of it, where a socket could answer EAGAIN before the
11
+ * input has arrived. When no such file can be made, the input goes through a pipe.
12
+ * @module @kirkchinese/harness-forge
13
+ */
14
+ import { spawn } from 'node:child_process';
15
+ 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';
19
+ import { messageOf } from '../shared/util.js';
20
+ const OUTPUT_LIMIT = 8 * 1024 * 1024;
21
+ /** How long output is still read after the process exits. */
22
+ const DRAIN_MS = 250;
23
+ /** The command that ends a process and everything it started on Windows (`taskkill /T /F`). */
24
+ export function treeKillCommand(pid, platform = process.platform) {
25
+ return platform === 'win32' ? { file: 'taskkill', args: ['/T', '/F', '/PID', String(pid)] } : undefined;
26
+ }
27
+ /**
28
+ * End a spawned process and its descendants. On POSIX the process leads its own
29
+ * group (it was spawned `detached`), so the group is killed; on Windows
30
+ * `taskkill /T /F` walks the tree.
31
+ */
32
+ export function killProcessTree(child, platform = process.platform) {
33
+ const pid = child.pid;
34
+ if (pid === undefined) {
35
+ child.kill('SIGKILL');
36
+ return;
37
+ }
38
+ const windows = treeKillCommand(pid, platform);
39
+ if (windows !== undefined) {
40
+ try {
41
+ const killer = spawn(windows.file, windows.args, { stdio: 'ignore', windowsHide: true });
42
+ killer.on('error', () => { child.kill('SIGKILL'); });
43
+ killer.unref();
44
+ }
45
+ catch {
46
+ child.kill('SIGKILL');
47
+ }
48
+ return;
49
+ }
50
+ try {
51
+ process.kill(-pid, 'SIGKILL');
52
+ }
53
+ catch {
54
+ child.kill('SIGKILL');
55
+ }
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
+ }
190
+ /** Spawn without a shell and collect the outcome. Never rejects. */
191
+ export function runProcess(spec) {
192
+ const started = performance.now();
193
+ return new Promise((resolve) => {
194
+ let stdout = '';
195
+ let stderr = '';
196
+ let timedOut = false;
197
+ let cancelled = false;
198
+ let settled = false;
199
+ let exitCode;
200
+ let stdoutOpen = true;
201
+ let stderrOpen = true;
202
+ let drainTimer;
203
+ let child;
204
+ const leftover = spec.onLeftover ?? warnLeftover;
205
+ const input = stdinFile(spec.stdin, spec.stdinDir, spec.stdinRoot, leftover);
206
+ try {
207
+ // Detached on POSIX: the hook leads its own process group, which a timeout or cancellation kills whole.
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' });
209
+ }
210
+ catch (error) {
211
+ if (input !== undefined) {
212
+ closeQuietly(input.fd);
213
+ void discard(input.path, leftover);
214
+ }
215
+ resolve({ startError: messageOf(error), timedOut: false, cancelled: false, stdout: '', stderr: '', suspectCapture: false, durationMs: 0 });
216
+ return;
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
+ }
224
+ const finish = (suspectCapture, startError) => {
225
+ if (settled)
226
+ return;
227
+ settled = true;
228
+ clearTimeout(timer);
229
+ clearTimeout(drainTimer);
230
+ spec.signal?.removeEventListener('abort', onAbort);
231
+ if (suspectCapture || timedOut || cancelled) {
232
+ child.stdout?.destroy();
233
+ child.stderr?.destroy();
234
+ child.stdin?.destroy();
235
+ }
236
+ resolve({
237
+ ...(exitCode !== undefined && !timedOut && !cancelled ? { exitCode } : {}),
238
+ ...(startError !== undefined ? { startError } : {}),
239
+ timedOut,
240
+ cancelled,
241
+ stdout,
242
+ stderr,
243
+ suspectCapture,
244
+ durationMs: Math.round(performance.now() - started),
245
+ });
246
+ };
247
+ const timer = spec.timeoutMs === undefined
248
+ ? undefined
249
+ : setTimeout(() => {
250
+ timedOut = true;
251
+ killProcessTree(child);
252
+ finish(false);
253
+ }, spec.timeoutMs);
254
+ const onAbort = () => {
255
+ cancelled = true;
256
+ killProcessTree(child);
257
+ finish(false);
258
+ };
259
+ spec.signal?.addEventListener('abort', onAbort, { once: true });
260
+ if (spec.signal?.aborted === true)
261
+ onAbort();
262
+ const closed = () => {
263
+ if (exitCode !== undefined && !stdoutOpen && !stderrOpen)
264
+ finish(false);
265
+ };
266
+ child.stdout?.setEncoding('utf8').on('data', (chunk) => { if (stdout.length < OUTPUT_LIMIT)
267
+ stdout += chunk; });
268
+ child.stderr?.setEncoding('utf8').on('data', (chunk) => { if (stderr.length < OUTPUT_LIMIT)
269
+ stderr += chunk; });
270
+ child.stdout?.on('close', () => { stdoutOpen = false; closed(); });
271
+ child.stderr?.on('close', () => { stderrOpen = false; closed(); });
272
+ child.on('error', (error) => { finish(false, messageOf(error)); });
273
+ child.on('exit', (code, signal) => {
274
+ // The process has finished: a timeout that fires while its output drains is not the hook's.
275
+ clearTimeout(timer);
276
+ exitCode = code ?? (signal !== null ? 128 : undefined);
277
+ if (!stdoutOpen && !stderrOpen) {
278
+ finish(false);
279
+ return;
280
+ }
281
+ drainTimer = setTimeout(() => { finish(stdoutOpen || stderrOpen); }, DRAIN_MS);
282
+ });
283
+ // Without a stdin file (none could be written), the input goes through a pipe.
284
+ child.stdin?.on('error', () => {
285
+ // A hook that exits without reading stdin closes the pipe early.
286
+ });
287
+ child.stdin?.end(spec.stdin);
288
+ });
289
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * The hooks row: imported hooks configurations (plugin hooks, settings hooks,
3
+ * skill, agent and command frontmatter hooks) run through one broker on DSH's
4
+ * interception points, and the run-time parts of a user's Codex configuration
5
+ * (`notify`, global instructions). Mods and OpenCode plugins add to it
6
+ * (`tool.check`, `shell.env`) through its API; it asks nothing of them.
7
+ * @module @kirkchinese/harness-forge/hooks
8
+ */
9
+ import type { Context } from '@deepseek-ai/cordis';
10
+ import type { Disposer } from '../forge/contract.js';
11
+ import { type HarnessForge } from '../forge/service.js';
12
+ export declare const name = "harness-forge-hooks";
13
+ export declare const inject: string[];
14
+ /** The hooks row. */
15
+ export declare function apply(ctx: Context): void;
16
+ /** Start the hooks row on the shared service. Returns its teardown. */
17
+ export declare function startHooks(ctx: Context, forge: HarnessForge): Disposer;
@@ -0,0 +1,96 @@
1
+ import { HarnessError } from '@kirkchinese/harness-forge-core';
2
+ import { mountCodexInstructions, mountCodexNotify } from './codex-user.js';
3
+ import { onDsh } from '../dsh/host.js';
4
+ import { FORGE_SERVICE } from '../forge/service.js';
5
+ import { HookBroker } from './broker.js';
6
+ import { hookSource, parseHookTable, readHookTable } from './config.js';
7
+ import { mounted, Parts, rowEffect } from '../forge/row.js';
8
+ export const name = 'harness-forge-hooks';
9
+ export const inject = [FORGE_SERVICE];
10
+ /** The hooks row. */
11
+ export function apply(ctx) {
12
+ rowEffect(ctx, 'hooks', forge => startHooks(ctx, forge));
13
+ }
14
+ /** Start the hooks row on the shared service. Returns its teardown. */
15
+ export function startHooks(ctx, forge) {
16
+ let checker;
17
+ const shellEnvs = new Set();
18
+ const broker = new HookBroker(ctx, {
19
+ shell: forge.shell,
20
+ dataRoot: forge.dataRoot,
21
+ observe: ({ componentId, event, ok, detail }) => { forge.observe(componentId, `hook:${event}`, ok, detail); },
22
+ agentName: presetId => forge.lookup('agents')?.foreignName(presetId),
23
+ presetOf: foreignName => forge.lookup('agents')?.presetOf(foreignName),
24
+ skillHooks: skill => forge.lookup('skills')?.skillHooks(skill),
25
+ agentHooks: presetId => forge.lookup('agents')?.agentHooks(presetId),
26
+ reloadSkills: () => { forge.lookup('skills')?.reload(); },
27
+ environment: session => forge.settings.env(session),
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),
31
+ hooksDisabled: session => forge.settings.hooksDisabled(session),
32
+ prepareSession: (agent, cwd) => forge.projects.prepare(agent, cwd),
33
+ releaseSession: sessionId => forge.projects.release(sessionId),
34
+ check: (exec, verdict) => checker === undefined ? Promise.resolve(verdict) : checker.check(exec, verdict),
35
+ checks: exec => checker?.checks(exec) ?? false,
36
+ shellEnv: async (exec) => {
37
+ const env = {};
38
+ for (const provider of shellEnvs)
39
+ Object.assign(env, await provider(exec));
40
+ return env;
41
+ },
42
+ });
43
+ const api = {
44
+ rewrite: (callId, args) => { broker.rewrite(callId, args); },
45
+ expandSkill: (agent, skill, signal) => broker.expandSkill(agent, skill, signal),
46
+ expandCommand: (agent, command, signal) => broker.expandCommand(agent, command, signal),
47
+ add: source => broker.add(source),
48
+ setChecker: (next) => {
49
+ checker = next;
50
+ return () => { if (checker === next)
51
+ checker = undefined; };
52
+ },
53
+ addShellEnv: (provider) => {
54
+ shellEnvs.add(provider);
55
+ return () => { shellEnvs.delete(provider); };
56
+ },
57
+ };
58
+ const parts = new Parts(ctx, forge, 'hooks');
59
+ parts.add('broker', () => broker.install());
60
+ // A skill's frontmatter hooks run for the rest of the session once the skill is invoked.
61
+ parts.add('skill hooks', () => onDsh(ctx, 'tools/post-execute', ((exec, result, next) => {
62
+ if (exec.name === 'skill' && !result.isError && exec.agent !== undefined) {
63
+ const skill = exec.arguments?.name;
64
+ const source = typeof skill === 'string' ? forge.lookup('skills')?.skillHooks(skill) : undefined;
65
+ if (source !== undefined)
66
+ broker.add({ ...source, origin: 'skill', sessionId: exec.agent.session.header.id });
67
+ }
68
+ return next();
69
+ }), { owner: 'hooks' }));
70
+ parts.add('hooks mounter', () => forge.registerMounter('hooks', {
71
+ mount: async ({ component, plugin, dataDir, scope }) => {
72
+ if (component.kind !== 'hooks')
73
+ throw new HarnessError('component-failed', `action expects hooks: ${component.id}`);
74
+ const table = component.configPath.length > 0 ? readHookTable(component.configPath) : parseHookTable(component.inline ?? {});
75
+ const origin = component.metadata?.['origin'] === 'settings' ? 'settings' : 'plugin';
76
+ const dispose = broker.add({ ...hookSource(component.id, plugin, dataDir, table, origin), ...(scope.sessionId !== undefined ? { sessionId: scope.sessionId } : {}) });
77
+ return { outcome: mounted(component, 'L1b', [...table.keys()].join(',')), disposer: async () => { dispose(); } };
78
+ },
79
+ }));
80
+ parts.add('codex-notify mounter', () => forge.registerMounter('codex-notify', {
81
+ mount: async ({ component, plugin }) => {
82
+ const dispose = mountCodexNotify(ctx, plugin.root, (ok, detail) => { forge.observe(component.id, 'notify', ok, detail); });
83
+ return { outcome: mounted(component, 'L1b', 'runs after each completed turn'), disposer: async () => { dispose(); } };
84
+ },
85
+ }));
86
+ parts.add('codex-instructions mounter', () => forge.registerMounter('codex-instructions', {
87
+ mount: async ({ component, plugin }) => {
88
+ if (component.path === undefined)
89
+ throw new HarnessError('component-failed', `instructions without a file: ${component.id}`);
90
+ const dispose = mountCodexInstructions(ctx, plugin.root, component.path, (ok, detail) => { forge.observe(component.id, 'instructions', ok, detail); });
91
+ return { outcome: mounted(component, 'L1a', `${component.path} in the system prompt`), disposer: async () => { dispose(); } };
92
+ },
93
+ }));
94
+ parts.add('api', () => forge.provide('hooks', api));
95
+ return () => parts.dispose();
96
+ }
@@ -0,0 +1,98 @@
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 { McpToolCall, McpToolVerdict } from '../forge/contract.js';
20
+ import type { RawRun } from './output.js';
21
+ import type { ForeignShell } from './shell.js';
22
+ import type { HookDialect } from './vocabulary.js';
23
+ /** Paths and values a handler may reference. */
24
+ export interface HandlerPlaces {
25
+ readonly pluginRoot: string;
26
+ readonly dataDir: string;
27
+ readonly projectDir: string;
28
+ readonly cwd: string;
29
+ /** Plugin user-config values, by key. */
30
+ readonly options: Readonly<Record<string, string>>;
31
+ /** `CLAUDE_ENV_FILE`, for the events that receive it. */
32
+ readonly envFile?: string;
33
+ }
34
+ /** One run request. */
35
+ export interface HandlerRequest {
36
+ readonly event: string;
37
+ readonly dialect: HookDialect;
38
+ readonly payload: Readonly<Record<string, unknown>>;
39
+ readonly places: HandlerPlaces;
40
+ /** Undefined runs without a timeout. */
41
+ readonly timeoutMs?: number;
42
+ readonly signal: AbortSignal;
43
+ /** The agent the event belongs to, for prompt and agent handlers. */
44
+ readonly agent?: unknown;
45
+ }
46
+ /** A prompt or agent handler's verdict. */
47
+ export interface ModelVerdict {
48
+ readonly ok: boolean;
49
+ readonly reason?: string;
50
+ readonly impossible?: boolean;
51
+ }
52
+ /** A raw outcome, plus the verdict of a model-backed handler. */
53
+ export interface HandlerOutcome extends RawRun {
54
+ readonly verdict?: ModelVerdict;
55
+ readonly durationMs: number;
56
+ }
57
+ /** Executes handlers against the host. */
58
+ export declare class HandlerRunner {
59
+ private readonly ctx;
60
+ private readonly shell;
61
+ private readonly settingsEnv;
62
+ private readonly toolPolicy;
63
+ /**
64
+ * @param settingsEnv - the `env` of the harness settings in effect for the
65
+ * event's agent, under the hook-specific variables.
66
+ */
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);
72
+ /** The environment every command handler of a source receives. */
73
+ environment(places: HandlerPlaces, kind: 'bash' | 'powershell' | 'exec', agent?: unknown): Record<string, string | undefined>;
74
+ /** Run a command handler. */
75
+ command(handler: CommandHandler, request: HandlerRequest): Promise<HandlerOutcome>;
76
+ /** Run an HTTP handler. */
77
+ http(handler: HttpHandler, request: HandlerRequest): Promise<HandlerOutcome>;
78
+ /**
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.
86
+ */
87
+ mcpTool(handler: McpToolHandler, request: HandlerRequest, serverName: string | undefined): Promise<HandlerOutcome>;
88
+ /** Run a prompt handler: one model call that answers `{ ok, reason, impossible }`. */
89
+ prompt(handler: ModelHandler, request: HandlerRequest): Promise<HandlerOutcome>;
90
+ /** Run an agent handler: a delegated agent with tool access that answers `{ ok, reason }`. */
91
+ agent(handler: ModelHandler, request: HandlerRequest): Promise<HandlerOutcome>;
92
+ }
93
+ /** The hook model's `{"ok": …}` answer: the text from its first `{` to its last `}`. */
94
+ export declare function parseVerdict(text: string): ModelVerdict;
95
+ /** PowerShell shell form: path placeholders become `${env:NAME}`. */
96
+ export declare function powershellPlaceholders(command: string): string;
97
+ /** `${a.b}` fields from the input; a placeholder filling a whole value keeps its JSON type. */
98
+ export declare function fillTemplate(template: unknown, payload: Readonly<Record<string, unknown>>): unknown;