@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,436 @@
1
+ /**
2
+ * The middleware chain a mods event runs through, as Claude Code's mods
3
+ * engine defines it (claude-code.d.ts `Next`, `TraceEntry`, `HookBudget`,
4
+ * `CatchHandler`; mods docs "Run alongside other mods"):
5
+ *
6
+ * - hooks nest by tier (prepend, user, append, builtin), then load order,
7
+ * then registration order; core (the host) is innermost;
8
+ * - `next(e)` runs everything beneath again on each call; a hook that returns
9
+ * without it answers the event;
10
+ * - a hook that throws, misreturns or outruns its budget is absent: its
11
+ * `.catch` handler answers within its grace, else beneath runs in its
12
+ * place (it had not called `next`) or its last `next` result stands;
13
+ * - `next.to` (managed tiers only) continues at a later tier, tracing the
14
+ * links it bypasses; `next.trace` lists what settled beneath, nearest first.
15
+ * @module @kirkchinese/harness-forge/mods
16
+ */
17
+ import { errorLine, frozenCopy, isRecord, isRegExp, isThenable, messageOf } from './values.js';
18
+ /** The chain's tiers, outermost first. */
19
+ export const TIERS = ['prepend', 'user', 'append', 'builtin', 'core'];
20
+ export const ENGINE_ORIGIN = Object.freeze({ plugin: 'engine', tier: 'core' });
21
+ /** A hook's own time and a `.catch` handler's grace, in milliseconds. */
22
+ export const HOOK_BUDGET_MS = 10_000;
23
+ export const CATCH_BUDGET_MS = 1_000;
24
+ /** Whether `pattern` (a name, `ns.*`, `*`, or `!pattern`) selects `event`. */
25
+ export function selects(pattern, event) {
26
+ if (pattern.startsWith('!'))
27
+ return !selects(pattern.slice(1), event) && !event.startsWith('telemetry.');
28
+ if (pattern === '*')
29
+ return !event.startsWith('telemetry.');
30
+ if (pattern.endsWith('.*'))
31
+ return event.startsWith(pattern.slice(0, -1));
32
+ return pattern === event;
33
+ }
34
+ /**
35
+ * Whether a matcher accepts a value: a scalar is `===`, a RegExp tests the
36
+ * value as a string, an array is any-of, an object a partial at any depth;
37
+ * against an array value a pattern holds when some element matches.
38
+ */
39
+ export function matches(pattern, value) {
40
+ if (Array.isArray(pattern))
41
+ return pattern.some(item => matches(item, value));
42
+ if (Array.isArray(value) && !Array.isArray(pattern))
43
+ return value.some(item => matches(pattern, item));
44
+ if (isRegExp(pattern)) {
45
+ if (value === undefined || value === null || typeof value === 'object')
46
+ return false;
47
+ pattern.lastIndex = 0;
48
+ return pattern.test(String(value));
49
+ }
50
+ if (isRecord(pattern)) {
51
+ if (!isRecord(value))
52
+ return false;
53
+ return Object.entries(pattern).every(([key, item]) => matches(item, value[key]));
54
+ }
55
+ return pattern === value;
56
+ }
57
+ /** Chain order: tier, then load order, then registration order. */
58
+ export function chainOrder(a, b) {
59
+ return TIERS.indexOf(a.mod.tier) - TIERS.indexOf(b.mod.tier) || a.mod.rank - b.mod.rank || a.seq - b.seq;
60
+ }
61
+ /** A rejection that passes up through the links that let it pass. */
62
+ class LinkRejection {
63
+ error;
64
+ constructor(error) {
65
+ this.error = error;
66
+ }
67
+ }
68
+ /** A hook's own-time clock: it stands still while `next` or `$` is in flight. */
69
+ class OwnClock {
70
+ ms;
71
+ onExpire;
72
+ spentMs = 0;
73
+ since;
74
+ paused = 0;
75
+ timer;
76
+ done = false;
77
+ constructor(ms, onExpire) {
78
+ this.ms = ms;
79
+ this.onExpire = onExpire;
80
+ }
81
+ start() {
82
+ this.since = performance.now();
83
+ this.arm();
84
+ }
85
+ pause() {
86
+ if (this.done)
87
+ return () => { };
88
+ if (this.paused++ === 0)
89
+ this.halt();
90
+ let resumed = false;
91
+ return () => {
92
+ if (resumed || this.done)
93
+ return;
94
+ resumed = true;
95
+ if (--this.paused === 0) {
96
+ this.since = performance.now();
97
+ this.arm();
98
+ }
99
+ };
100
+ }
101
+ stop() {
102
+ if (this.done)
103
+ return;
104
+ this.halt();
105
+ this.done = true;
106
+ }
107
+ get spent() {
108
+ return this.spentMs + (this.since === undefined ? 0 : performance.now() - this.since);
109
+ }
110
+ get remaining() {
111
+ return Math.max(0, this.ms - this.spent);
112
+ }
113
+ halt() {
114
+ if (this.since !== undefined)
115
+ this.spentMs += performance.now() - this.since;
116
+ this.since = undefined;
117
+ if (this.timer !== undefined)
118
+ clearTimeout(this.timer);
119
+ this.timer = undefined;
120
+ }
121
+ arm() {
122
+ if (this.timer !== undefined)
123
+ clearTimeout(this.timer);
124
+ this.timer = setTimeout(() => {
125
+ this.timer = undefined;
126
+ if (this.paused === 0 && !this.done)
127
+ this.onExpire();
128
+ }, Math.max(0, this.ms - this.spentMs));
129
+ this.timer.unref?.();
130
+ }
131
+ }
132
+ /** Run one dispatch through its hooks and core. */
133
+ export async function dispatch(request) {
134
+ const signal = request.signal ?? new AbortController().signal;
135
+ const root = { bypassed: [], first: undefined };
136
+ try {
137
+ return await runFrom(request, 0, frozenCopy(request.input), root, signal, undefined);
138
+ }
139
+ catch (error) {
140
+ throw error instanceof LinkRejection ? error.error : error;
141
+ }
142
+ }
143
+ function runFrom(request, index, e, call, signal, above) {
144
+ for (let at = index; at < request.hooks.length; at++) {
145
+ const hook = request.hooks[at];
146
+ if (!request.applies(hook, e))
147
+ continue;
148
+ const cause = request.reentry?.(hook);
149
+ if (cause !== undefined && cause !== false)
150
+ return reentered(request, at, hook, e, call, signal, cause, above);
151
+ return runLink(request, at, hook, e, call, signal, above);
152
+ }
153
+ return runCore(request, e, call, signal, above);
154
+ }
155
+ async function runCore(request, e, call, signal, above) {
156
+ const link = { index: request.hooks.length, event: request.event, plugin: 'engine', tier: 'core', outcome: undefined, received: e, returned: undefined, ms: 0, lastCall: undefined };
157
+ call.first ??= link;
158
+ const started = performance.now();
159
+ try {
160
+ const result = frozenCopy(await request.bottom(e, signal, above));
161
+ link.outcome = 'returned';
162
+ link.returned = result;
163
+ return result;
164
+ }
165
+ catch (error) {
166
+ link.outcome = 'rejected';
167
+ throw error instanceof LinkRejection ? error : new LinkRejection(error);
168
+ }
169
+ finally {
170
+ link.ms = performance.now() - started;
171
+ }
172
+ }
173
+ /** A hook skipped because the event came from its own `$` call: its `.catch` may answer. */
174
+ async function reentered(request, index, hook, e, call, signal, cause, above) {
175
+ if (hook.catchFn !== undefined) {
176
+ const failure = { kind: 're-entry', budget: request.catchMs ?? CATCH_BUDGET_MS, ...(cause === true ? {} : { cause }) };
177
+ const link = newLink(index, request.event, hook, e);
178
+ call.first ??= link;
179
+ const answer = await runCatch(request, index, hook, e, link, signal, failure, undefined).catch(() => undefined);
180
+ if (answer !== undefined)
181
+ return answer;
182
+ }
183
+ return runFrom(request, index + 1, e, call, signal, above);
184
+ }
185
+ function newLink(index, event, hook, e) {
186
+ return { index, event, plugin: hook.mod.name, tier: hook.mod.tier, outcome: undefined, received: e, returned: undefined, ms: 0, lastCall: undefined };
187
+ }
188
+ async function runLink(request, index, hook, e, call, parentSignal, above) {
189
+ const link = newLink(index, request.event, hook, e);
190
+ call.first ??= link;
191
+ const controller = new AbortController();
192
+ const abort = () => { controller.abort(parentSignal.reason); };
193
+ if (parentSignal.aborted)
194
+ abort();
195
+ else
196
+ parentSignal.addEventListener('abort', abort, { once: true });
197
+ let expire;
198
+ const expired = new Promise((_resolve, reject) => {
199
+ expire = () => { reject(new ExpiredError()); };
200
+ });
201
+ expired.catch(() => { });
202
+ const clock = new OwnClock(request.budgetMs ?? HOOK_BUDGET_MS, () => {
203
+ controller.abort(new Error(`${hook.mod.name}: ${request.event} hook ran out of its budget`));
204
+ expire?.();
205
+ });
206
+ const state = { called: false, last: undefined, lastSettled: undefined };
207
+ const next = makeNext(request, index, hook, link, state, clock, controller.signal);
208
+ let active = true;
209
+ const frame = { hook, event: request.event, origin: request.origin, signal: controller.signal, get active() { return active; }, pause: () => clock.pause() };
210
+ clock.start();
211
+ try {
212
+ let result;
213
+ try {
214
+ const out = hook.fn(request.api(frame), e, next);
215
+ result = isThenable(out) ? await Promise.race([out, expired]) : out;
216
+ }
217
+ finally {
218
+ active = false;
219
+ clock.stop();
220
+ link.ms = clock.spent;
221
+ }
222
+ if (result === undefined)
223
+ throw new Error('returned nothing');
224
+ const wrong = request.validate?.(result, state.called);
225
+ if (wrong !== undefined)
226
+ throw new Error(wrong);
227
+ const passed = state.lastSettled?.ok === true && (state.lastSettled.value === result || (request.received !== undefined && request.received(hook, state.lastSettled.value) === result));
228
+ const settled = passed ? result : frozenCopy(result);
229
+ link.outcome = passed ? 'passed' : 'returned';
230
+ link.returned = settled;
231
+ if (!passed)
232
+ request.observe?.(hook, settled);
233
+ return settled;
234
+ }
235
+ catch (error) {
236
+ // A rejection from beneath that the hook let pass: its `.catch` hears it, else it passes on.
237
+ const rejected = error instanceof LinkRejection ? error.error : state.lastSettled?.ok === false && error === state.lastSettled.error ? error : undefined;
238
+ if (rejected !== undefined && hook.catchFn === undefined) {
239
+ link.outcome = 'rejected';
240
+ throw error instanceof LinkRejection ? error : new LinkRejection(error);
241
+ }
242
+ const timedOut = error instanceof ExpiredError;
243
+ const failure = {
244
+ kind: timedOut ? 'timeout' : 'throw',
245
+ ...(timedOut ? (state.lastSettled?.ok === false ? { message: messageOf(state.lastSettled.error) } : {}) : { message: messageOf(rejected ?? error) }),
246
+ budget: request.catchMs ?? CATCH_BUDGET_MS,
247
+ };
248
+ request.report(`${hook.mod.name}: ${request.event} hook ${hook.catchFn === undefined ? 'skipped' : 'failed'}: ${timedOut ? `timed out after ${String(request.budgetMs ?? HOOK_BUDGET_MS)}ms` : `threw ${errorLine(error)}`}`);
249
+ // The handler runs once a call in flight has settled.
250
+ if (state.last !== undefined)
251
+ await state.last.catch(() => undefined);
252
+ if (hook.catchFn !== undefined) {
253
+ const answer = await runCatch(request, index, hook, e, link, parentSignal, failure, state).catch((caught) => {
254
+ request.report(`${hook.mod.name}: ${request.event} hook's .catch skipped: threw ${errorLine(caught)}`);
255
+ return undefined;
256
+ });
257
+ if (answer !== undefined) {
258
+ link.outcome = 'caught';
259
+ link.returned = answer;
260
+ request.observe?.(hook, answer);
261
+ return answer;
262
+ }
263
+ }
264
+ if (!state.called) {
265
+ link.outcome = timedOut ? 'expired' : 'skipped';
266
+ const beneath = { bypassed: [], first: undefined };
267
+ link.lastCall = beneath;
268
+ return runFrom(request, index + 1, e, beneath, parentSignal, above);
269
+ }
270
+ link.outcome = timedOut ? 'expired' : 'kept';
271
+ const last = state.lastSettled;
272
+ if (last?.ok === false)
273
+ throw last.error instanceof LinkRejection ? last.error : new LinkRejection(last.error);
274
+ link.returned = last?.value;
275
+ return last?.value;
276
+ }
277
+ finally {
278
+ parentSignal.removeEventListener('abort', abort);
279
+ }
280
+ }
281
+ class ExpiredError extends Error {
282
+ }
283
+ /**
284
+ * A hook's `.catch` handler: its `next` is replay-safe. When the hook had
285
+ * called `next`, `next(e)` resolves to that call's settled result; otherwise
286
+ * it runs beneath once and later calls replay it.
287
+ */
288
+ async function runCatch(request, index, hook, e, link, signal, failure, state) {
289
+ const handler = hook.catchFn;
290
+ let replay = state?.lastSettled === undefined
291
+ ? undefined
292
+ : state.lastSettled.ok ? Promise.resolve(state.lastSettled.value) : Promise.reject(state.lastSettled.error);
293
+ replay?.catch(() => { });
294
+ const controller = new AbortController();
295
+ let expire;
296
+ const expired = new Promise((_resolve, reject) => { expire = () => { reject(new ExpiredError()); }; });
297
+ expired.catch(() => { });
298
+ const clock = new OwnClock(request.catchMs ?? CATCH_BUDGET_MS, () => {
299
+ controller.abort(new Error(`${hook.mod.name}: ${request.event} .catch ran out of its grace`));
300
+ expire?.();
301
+ });
302
+ const next = Object.assign((argument) => {
303
+ if (replay === undefined) {
304
+ const beneath = { bypassed: [], first: undefined };
305
+ link.lastCall = beneath;
306
+ const resume = clock.pause();
307
+ replay = runFrom(request, index + 1, argument === undefined ? e : frozenCopy(argument), beneath, signal, hook).finally(resume);
308
+ }
309
+ return replay.catch((error) => { throw error instanceof LinkRejection ? error.error : error; });
310
+ }, {
311
+ error: Object.freeze({ ...failure }),
312
+ called: state?.called ?? false,
313
+ to: () => Promise.reject(new Error(`${hook.mod.name}: next.to is not available in a .catch handler`)),
314
+ signal: controller.signal,
315
+ event: request.event,
316
+ origin: request.origin,
317
+ is: (pattern, _e) => selects(pattern, request.event),
318
+ });
319
+ live(next, () => traceOf(link.lastCall), () => Object.freeze({ ms: clock.ms, remainingMs: clock.remaining }));
320
+ let active = true;
321
+ const frame = { hook, event: request.event, origin: request.origin, signal: controller.signal, get active() { return active; }, pause: () => clock.pause() };
322
+ clock.start();
323
+ try {
324
+ const out = handler(request.api(frame), e, Object.freeze(next));
325
+ const result = isThenable(out) ? await Promise.race([out, expired]) : out;
326
+ if (result === undefined)
327
+ return undefined;
328
+ const wrong = request.validate?.(result, true);
329
+ if (wrong !== undefined)
330
+ throw new Error(wrong);
331
+ return frozenCopy(result);
332
+ }
333
+ finally {
334
+ active = false;
335
+ clock.stop();
336
+ }
337
+ }
338
+ function makeNext(request, index, hook, link, state, clock, signal) {
339
+ const call = (argument, start, bypassed) => {
340
+ // A rewrite of a pinned field is refused before anything beneath runs: the hook has not called next.
341
+ let passed;
342
+ try {
343
+ passed = frozenCopy(argument);
344
+ if (request.passing !== undefined)
345
+ passed = frozenCopy(request.passing(link.received, passed));
346
+ }
347
+ catch (error) {
348
+ return Promise.reject(error);
349
+ }
350
+ const record = { bypassed, first: undefined };
351
+ link.lastCall = record;
352
+ state.called = true;
353
+ const resume = clock.pause();
354
+ const run = (async () => {
355
+ try {
356
+ return await runFrom(request, start, passed, record, signal, hook);
357
+ }
358
+ finally {
359
+ resume();
360
+ }
361
+ })();
362
+ state.last = run;
363
+ run.then((value) => { if (state.last === run)
364
+ state.lastSettled = { ok: true, value }; }, (error) => { if (state.last === run)
365
+ state.lastSettled = { ok: false, error: error instanceof LinkRejection ? error.error : error }; });
366
+ return run.then(value => (request.received === undefined ? value : request.received(hook, value)), (error) => { throw error instanceof LinkRejection ? error.error : error; });
367
+ };
368
+ const next = function next(...args) {
369
+ if (args.length === 0)
370
+ return Promise.reject(new Error(`${hook.mod.name}: ${request.event} hook called next() without its event`));
371
+ return call(args[0], index + 1, []);
372
+ };
373
+ const to = (argument, tier) => {
374
+ const own = TIERS.indexOf(hook.mod.tier);
375
+ const target = TIERS.indexOf(tier);
376
+ if (hook.mod.tier !== 'prepend' && hook.mod.tier !== 'append')
377
+ return Promise.reject(new Error(`${hook.mod.name}: next.to is for managed plugins (prepend, append); this plugin is ${hook.mod.tier}`));
378
+ if (target <= own || tier === 'user' || tier === 'prepend')
379
+ return Promise.reject(new Error(`${hook.mod.name}: next.to cannot continue at ${tier} from ${hook.mod.tier}`));
380
+ let start = index + 1;
381
+ const bypassed = [];
382
+ while (start < request.hooks.length && TIERS.indexOf(request.hooks[start].mod.tier) < target) {
383
+ const skipped = request.hooks[start];
384
+ if (request.applies(skipped, argument)) {
385
+ bypassed.push({ ...newLink(start, request.event, skipped, argument), outcome: 'skipped', reason: `bypassed by ${hook.mod.name}` });
386
+ }
387
+ start++;
388
+ }
389
+ return call(argument, start, bypassed);
390
+ };
391
+ Object.assign(next, {
392
+ to,
393
+ signal,
394
+ event: request.event,
395
+ origin: request.origin,
396
+ is: (pattern, _e) => selects(pattern, request.event),
397
+ });
398
+ live(next, () => traceOf(link.lastCall), () => Object.freeze({ ms: clock.ms, remainingMs: clock.remaining }));
399
+ return Object.freeze(next);
400
+ }
401
+ /** `next.trace` and `next.budget` are read fresh on each access. */
402
+ function live(next, trace, budget) {
403
+ Object.defineProperty(next, 'trace', { get: trace, enumerable: true });
404
+ Object.defineProperty(next, 'budget', { get: budget, enumerable: true });
405
+ }
406
+ /** What settled beneath a link's latest call, nearest first. */
407
+ function traceOf(call) {
408
+ const entries = [];
409
+ const seen = new Set();
410
+ let current = call;
411
+ while (current !== undefined && !seen.has(current)) {
412
+ seen.add(current);
413
+ for (const link of current.bypassed)
414
+ entries.push(entryOf(link));
415
+ const link = current.first;
416
+ if (link === undefined)
417
+ break;
418
+ if (link.outcome !== undefined)
419
+ entries.push(entryOf(link));
420
+ current = link.lastCall;
421
+ }
422
+ return Object.freeze(entries);
423
+ }
424
+ function entryOf(link) {
425
+ return Object.freeze({
426
+ index: link.index,
427
+ plugin: link.plugin,
428
+ tier: link.tier,
429
+ event: link.event,
430
+ outcome: link.outcome ?? 'returned',
431
+ ...(link.reason !== undefined ? { reason: link.reason } : {}),
432
+ ms: link.ms,
433
+ received: link.received,
434
+ returned: link.outcome === 'rejected' || link.outcome === 'skipped' ? undefined : link.returned,
435
+ });
436
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Claude Code mods: an imported hooks module is bundled once, scanned as
3
+ * Claude Code scans it, and handed to the mods service, which loads it into
4
+ * every session's engine.
5
+ * @module @kirkchinese/harness-forge
6
+ */
7
+ import type { CodeComponent, ForeignPlugin } from '@kirkchinese/harness-forge-core';
8
+ import { type Bundler } from './loader.js';
9
+ import type { PluginTier } from './chain.js';
10
+ import type { ModsService } from './service.js';
11
+ /**
12
+ * Where a mod sits in the chain. Claude Code's own mods (Anthropic's, by the
13
+ * names it ships) sit where Claude Code seats them: the guard outermost, the
14
+ * others built in; every other mod is the person's.
15
+ */
16
+ export declare function modTier(plugin: ForeignPlugin): PluginTier;
17
+ /** One loaded Claude mod. */
18
+ export interface ClaudeModMount {
19
+ readonly name: string;
20
+ readonly tier: PluginTier;
21
+ readonly dispose: () => Promise<void>;
22
+ }
23
+ /**
24
+ * Bundle a mod's hooks module and add it to every session.
25
+ * @param bundler - the bundler, which may still have to be installed (see `bundler.ts`).
26
+ */
27
+ export declare function mountClaudeMod(mods: ModsService, component: CodeComponent, plugin: ForeignPlugin, bundler: () => Promise<Bundler>): Promise<ClaudeModMount>;
@@ -0,0 +1,56 @@
1
+ import { bundleModule, scanBundleRefusal, scanBundleUses } from './loader.js';
2
+ /** The mods Claude Code builds in, by name: they sit where it seats them. */
3
+ const BUILT_IN_MODS = new Set(['diff', 'privacy', 'agents-md', 'telemetry']);
4
+ /**
5
+ * Where a mod sits in the chain. Claude Code's own mods (Anthropic's, by the
6
+ * names it ships) sit where Claude Code seats them: the guard outermost, the
7
+ * others built in; every other mod is the person's.
8
+ */
9
+ export function modTier(plugin) {
10
+ const author = plugin.manifest['author'];
11
+ const authorName = typeof author === 'string' ? author : typeof author === 'object' && author !== null ? author.name : undefined;
12
+ const isAnthropic = typeof authorName === 'string' && /^anthropic$/iu.test(authorName.trim());
13
+ if (isAnthropic && plugin.name === 'sec-default')
14
+ return 'prepend';
15
+ if (isAnthropic && BUILT_IN_MODS.has(plugin.name))
16
+ return 'builtin';
17
+ return 'user';
18
+ }
19
+ /** The defaults the manifest's `userConfig` declares, as `register(on, options)` receives them. */
20
+ function optionsOf(plugin) {
21
+ const config = plugin.manifest['userConfig'];
22
+ const options = {};
23
+ if (typeof config !== 'object' || config === null)
24
+ return options;
25
+ for (const [key, field] of Object.entries(config)) {
26
+ if (typeof field === 'object' && field !== null && field.default !== undefined)
27
+ options[key] = field.default;
28
+ }
29
+ return options;
30
+ }
31
+ /**
32
+ * Bundle a mod's hooks module and add it to every session.
33
+ * @param bundler - the bundler, which may still have to be installed (see `bundler.ts`).
34
+ */
35
+ export async function mountClaudeMod(mods, component, plugin, bundler) {
36
+ if (component.entryPath === undefined)
37
+ throw new Error(`code component "${component.name}" has no entry path`);
38
+ const tools = await bundler();
39
+ const bundle = await bundleModule(component.entryPath, tools);
40
+ const refusal = scanBundleRefusal(bundle, tools.parseAst);
41
+ const tier = modTier(plugin);
42
+ const version = typeof plugin.manifest['version'] === 'string' ? plugin.manifest['version'] : undefined;
43
+ const dispose = await mods.add({
44
+ componentId: component.id,
45
+ name: plugin.name,
46
+ tier,
47
+ root: plugin.root,
48
+ bundle,
49
+ options: optionsOf(plugin),
50
+ uses: scanBundleUses(bundle),
51
+ provenance: `${plugin.name}@${tier === 'user' ? 'harness-forge' : 'builtin'}`,
52
+ ...(version !== undefined ? { version } : {}),
53
+ ...(refusal !== undefined ? { refusal } : {}),
54
+ });
55
+ return { name: plugin.name, tier, dispose };
56
+ }
@@ -0,0 +1,160 @@
1
+ import { type HookEntry, type ModRef, type Origin, type PluginTier } from './chain.js';
2
+ /** A mod as the host hands it to the engine. */
3
+ export interface ModDefinition {
4
+ readonly name: string;
5
+ readonly tier?: PluginTier;
6
+ readonly root?: string;
7
+ readonly version?: string;
8
+ /** Where the plugin came from, as `plugin.register` reports it. */
9
+ readonly provenance?: string;
10
+ /** What the module hooks and calls, read off its source. */
11
+ readonly uses?: Readonly<Record<string, unknown>>;
12
+ readonly options?: Readonly<Record<string, unknown>>;
13
+ readonly register: (on: unknown, options: unknown) => unknown;
14
+ /** Why the engine's scan of the module's source refuses it, when it does. */
15
+ readonly refusal?: string;
16
+ /** The module's environment, whose `Error` the rejections it receives are made of. */
17
+ readonly realm?: {
18
+ readonly Error: ErrorConstructor;
19
+ };
20
+ }
21
+ /** One loaded mod. */
22
+ export interface LoadedMod {
23
+ readonly ref: ModRef;
24
+ readonly definition: ModDefinition;
25
+ readonly hooks: HookEntry[];
26
+ readonly timers: Set<{
27
+ cancel(): void;
28
+ }>;
29
+ }
30
+ /** What core knows about the call it serves. */
31
+ export interface CoreContext {
32
+ /** Who raised the event. */
33
+ readonly origin: Origin;
34
+ /** The mod whose `$` call this is, for an op. */
35
+ readonly mod?: LoadedMod;
36
+ readonly signal: AbortSignal;
37
+ }
38
+ /** What the host supplies. */
39
+ export interface EngineHost {
40
+ /**
41
+ * Core at an event: the engine's own behavior, innermost. An op (a `$` call)
42
+ * answers `{ value }` or `{ deny }`; an engine event answers its result.
43
+ * Throwing rejects the dispatch.
44
+ */
45
+ core(event: string, e: unknown, context: CoreContext): unknown;
46
+ /** A line for the debug log, naming the mod, the event and why. */
47
+ report(line: string): void;
48
+ /** The element table `$.ui.resolve(e)` reads when no hook changes it, its controls stamped with the plugin. */
49
+ elements?(surface: string, component: string, plugin: string): Readonly<Record<string, unknown>>;
50
+ /** A `$.state` value was read inside a `ui.render` run, or written. */
51
+ /** A mod's hook (or its `.catch`) is about to run for an event. */
52
+ ran?(mod: string, event: string): void;
53
+ stateRead?(key: string, render: RenderFrame): void;
54
+ stateWritten?(key: string): void;
55
+ }
56
+ /** The `ui.render` run a state read belongs to. */
57
+ export interface RenderFrame {
58
+ readonly mod: string;
59
+ readonly requestId?: unknown;
60
+ readonly component?: unknown;
61
+ }
62
+ /** The engine's limits; Claude Code's when absent. */
63
+ export interface EngineOptions {
64
+ readonly budgetMs?: number;
65
+ readonly catchMs?: number;
66
+ }
67
+ /** A `$` call the chain refused or could not serve, as the calling plugin receives it. */
68
+ export declare class HooksError extends Error {
69
+ readonly name = "HooksError";
70
+ }
71
+ /** The mods engine of one session. */
72
+ export declare class ModsEngine {
73
+ private readonly host;
74
+ private readonly options;
75
+ readonly mods: LoadedMod[];
76
+ /** `$.state`, keyed `<plugin>\u0000<key>`. */
77
+ readonly state: Map<string, unknown>;
78
+ private hooks;
79
+ /** Nouns the plugins' `engine.create` steps added: noun → method → its owner's function. */
80
+ private nouns;
81
+ private readonly context;
82
+ private rank;
83
+ private disposed;
84
+ constructor(host: EngineHost, options?: EngineOptions);
85
+ /** The hooks of every loaded mod, in chain order. */
86
+ get registered(): readonly HookEntry[];
87
+ /**
88
+ * Load mods: each passes `plugin.register` (the loaded mods may refuse it),
89
+ * runs `register(on, options)`, and the batch's `engine.create` fold adds
90
+ * the nouns they provide.
91
+ * @returns the names refused, with who refused and why, and the ones whose
92
+ * `register` threw.
93
+ */
94
+ load(definitions: readonly ModDefinition[]): Promise<{
95
+ refused: Array<{
96
+ name: string;
97
+ by: string;
98
+ reason: string;
99
+ }>;
100
+ failed: Array<{
101
+ name: string;
102
+ error: string;
103
+ }>;
104
+ }>;
105
+ /** Mods registering in a load, before they join the chain. */
106
+ private readonly pending;
107
+ /** Unload one mod: its hooks leave the chain and its timers stop. */
108
+ unload(name: string): Promise<void>;
109
+ /** Stop every mod's timers; the engine raises nothing more. */
110
+ dispose(): void;
111
+ /**
112
+ * Raise one of the engine's events through every hook on it, core last.
113
+ * @param origin who raised it: the engine unless a client or test says so.
114
+ */
115
+ raise(event: string, input: unknown, options?: {
116
+ origin?: Origin;
117
+ signal?: AbortSignal;
118
+ }): Promise<unknown>;
119
+ /** The `$` a mod's code holds outside any hook (its `register`, timers, buttons). */
120
+ apiOf(name: string): unknown;
121
+ /** Run `fn` outside any hook's call context: what it schedules is the engine's own, not a re-entry of a hook. */
122
+ outside(fn: () => void): void;
123
+ /** The current `ui.render` run of a state read, if any. */
124
+ currentRender(): RenderFrame | undefined;
125
+ private nounOwners;
126
+ private register;
127
+ /**
128
+ * The `engine.create` fold over a batch: the nouns its steps add. Between
129
+ * steps the table crosses as descriptors: each step sees objects whose
130
+ * methods raise their events as that step's plugin, so a step calling a
131
+ * noun off its table is gated as any caller is.
132
+ */
133
+ private create;
134
+ /** The owner's function behind a noun method handed to a step. */
135
+ private readonly ownerOf;
136
+ private coreNouns;
137
+ /** Hooks selected by an event, in chain order. */
138
+ private selected;
139
+ private applies;
140
+ private reentry;
141
+ private dispatchEngine;
142
+ private modOf;
143
+ /**
144
+ * A mod's `$` call: the event of its name, raised by that mod; the calling
145
+ * hook (or, outside hooks, the mod) is skipped by everything it raises.
146
+ */
147
+ private callOp;
148
+ /** A plugin noun's method: its event through the hooks, the owner's function as core. */
149
+ private callNoun;
150
+ /** Build the `$` a hook run (or the mod's code outside hooks) receives. */
151
+ private api;
152
+ private resolveElements;
153
+ /** `$.ui.ask`: a `tool.call` of AskUserQuestion; resolves to the label chosen. */
154
+ private ask;
155
+ private timer;
156
+ private stateGet;
157
+ private stateSet;
158
+ }
159
+ /** The `claudeMd` block text for a list of instruction files, framed as the engine frames them. */
160
+ export declare function claudeMdText(files: readonly unknown[]): string;