@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,227 @@
1
+ /**
2
+ * Load a hooks module the way Claude Code does: its `.ts`/`.tsx`/`.js`
3
+ * sources bundled (extensionless, directory and `.js`-for-`.ts` imports,
4
+ * classic JSX on the global `h`/`Fragment`), then run in an environment of
5
+ * its own with the globals claude-code.d.ts lists and no others: no Node, no
6
+ * DOM, no timers, no code generation from strings.
7
+ * @module @kirkchinese/harness-forge/mods
8
+ */
9
+ import { createHash, getRandomValues, randomUUID, subtle } from 'node:crypto';
10
+ import { readFileSync } from 'node:fs';
11
+ import { dirname, extname, isAbsolute } from 'node:path';
12
+ import vm from 'node:vm';
13
+ import { CLAUDE_CODE_MODULE, Fragment, h } from './runtime.js';
14
+ /** Modules a hooks module imports from the engine rather than from its folder. */
15
+ const VIRTUAL = ['claude-code', 'claude-code/testing'];
16
+ /** Bundle a module and everything it imports from its plugin. */
17
+ export async function bundleModule(entry, bundler) {
18
+ const warnings = [];
19
+ const result = await bundler.build({
20
+ input: entry,
21
+ cwd: dirname(entry),
22
+ write: false,
23
+ platform: 'neutral',
24
+ external: VIRTUAL,
25
+ resolve: {
26
+ extensions: ['.ts', '.tsx', '.mts', '.cts', '.js', '.jsx', '.mjs', '.cjs', '.json'],
27
+ extensionAlias: { '.js': ['.ts', '.tsx', '.js'], '.jsx': ['.tsx', '.jsx'], '.mjs': ['.mts', '.mjs'], '.cjs': ['.cts', '.cjs'] },
28
+ mainFields: ['module', 'main'],
29
+ },
30
+ transform: { jsx: { runtime: 'classic', pragma: 'h', pragmaFrag: 'Fragment' } },
31
+ onLog: (level, log) => { if (level === 'warn' && log.code !== 'CONFIGURATION_FIELD_CONFLICT')
32
+ warnings.push(log.message); },
33
+ output: { format: 'cjs', exports: 'named', codeSplitting: false },
34
+ });
35
+ const chunk = result.output.find(item => item.type === 'chunk');
36
+ if (chunk?.code === undefined)
37
+ throw new Error(`bundling ${entry} produced no module${warnings.length > 0 ? `: ${warnings.join('; ')}` : ''}`);
38
+ const files = (chunk.moduleIds ?? []).filter(id => isAbsolute(id) && !/[\\/]node_modules[\\/]/u.test(id));
39
+ return { code: chunk.code, entry, files, digest: createHash('sha256').update(chunk.code).digest('hex').slice(0, 16) };
40
+ }
41
+ /** The globals of a hooks module's environment. */
42
+ function environmentGlobals(extra) {
43
+ return {
44
+ h,
45
+ Fragment,
46
+ AbortSignal,
47
+ AbortController,
48
+ TextEncoder,
49
+ TextDecoder,
50
+ URL,
51
+ URLSearchParams,
52
+ atob,
53
+ btoa,
54
+ structuredClone,
55
+ crypto: Object.freeze({ subtle: Object.freeze({ digest: subtle.digest.bind(subtle) }), randomUUID, getRandomValues }),
56
+ performance: Object.freeze({ now: () => performance.now() }),
57
+ ...extra,
58
+ };
59
+ }
60
+ /** A fresh environment for one load of a module. */
61
+ export function createEnvironment(extra = {}) {
62
+ return vm.createContext(environmentGlobals(extra), { codeGeneration: { strings: false, wasm: false }, name: 'claude-code hooks module' });
63
+ }
64
+ /**
65
+ * Run a bundle in an environment and return its exports.
66
+ * @param imports - the virtual modules it may import (`claude-code`, `claude-code/testing`).
67
+ */
68
+ export function evaluateBundle(bundle, context, imports = {}) {
69
+ const modules = { 'claude-code': CLAUDE_CODE_MODULE, ...imports };
70
+ const wrapper = new vm.Script(`(function (exports, require, module) {\n${bundle.code}\n})`, { filename: bundle.entry });
71
+ const run = wrapper.runInContext(context);
72
+ const module = { exports: {} };
73
+ run(module.exports, (name) => {
74
+ if (name in modules)
75
+ return modules[name];
76
+ throw new Error(`a hooks module imports only from its plugin and from claude-code; "${name}" is neither`);
77
+ }, module);
78
+ return module.exports;
79
+ }
80
+ /**
81
+ * What a module hooks and calls, read off its source as `plugin.register`
82
+ * reports it: its `on(...)` patterns in order, the `$` calls it spells
83
+ * (sorted), and the variables its `$.env` calls name.
84
+ */
85
+ export function scanUses(source) {
86
+ const events = [];
87
+ for (const match of source.matchAll(/\bon\(\s*(['"`])([^'"`]+)\1/gu))
88
+ if (!events.includes(match[2]))
89
+ events.push(match[2]);
90
+ const calls = new Set();
91
+ for (const match of source.matchAll(/\$\.([a-z]+)\.([a-zA-Z]+)\s*\(/gu))
92
+ calls.add(`${match[1]}.${match[2]}`);
93
+ const reads = new Set();
94
+ const writes = new Set();
95
+ for (const match of source.matchAll(/\$\.env\.(get|set)\(\s*(['"`])([^'"`]+)\2/gu))
96
+ (match[1] === 'get' ? reads : writes).add(match[3]);
97
+ return {
98
+ events,
99
+ calls: [...calls].sort(),
100
+ ...(reads.size > 0 || writes.size > 0 ? { env: { reads: [...reads].sort(), writes: [...writes].sort() } } : {}),
101
+ };
102
+ }
103
+ function isNode(value) {
104
+ return typeof value === 'object' && value !== null && typeof value.type === 'string';
105
+ }
106
+ function walk(node, visit) {
107
+ if (Array.isArray(node)) {
108
+ for (const item of node)
109
+ walk(item, visit);
110
+ return;
111
+ }
112
+ if (!isNode(node))
113
+ return;
114
+ visit(node);
115
+ for (const [key, value] of Object.entries(node))
116
+ if (key !== 'type' && typeof value === 'object')
117
+ walk(value, visit);
118
+ }
119
+ function rootName(node) {
120
+ if (!isNode(node))
121
+ return undefined;
122
+ if (node.type === 'Identifier')
123
+ return node['name'];
124
+ if (node.type === 'MemberExpression')
125
+ return rootName(node['object']);
126
+ return undefined;
127
+ }
128
+ /**
129
+ * Why the engine would refuse a module, read off its source as Claude Code's
130
+ * scan does: an `engine.create` step that keeps the table it is handed, to
131
+ * call later, outside the fold. Undefined when the module loads.
132
+ */
133
+ export function scanRefusal(source, parseAst, lang = 'js') {
134
+ let ast;
135
+ for (const attempt of [source, `(${source})`, `({${source}})`]) {
136
+ try {
137
+ ast = parseAst(attempt, { lang });
138
+ break;
139
+ }
140
+ catch {
141
+ // Try the next reading: a function's text, or a method's.
142
+ }
143
+ }
144
+ if (ast === undefined)
145
+ return undefined;
146
+ let problem;
147
+ walk(ast, (node) => {
148
+ if (problem !== undefined || node.type !== 'CallExpression')
149
+ return;
150
+ const callee = node['callee'];
151
+ const args = node['arguments'];
152
+ if (!isNode(callee) || callee.type !== 'Identifier' || callee['name'] !== 'on')
153
+ return;
154
+ const first = args[0];
155
+ if (!isNode(first) || first.type !== 'Literal' || first['value'] !== 'engine.create')
156
+ return;
157
+ const hook = args.at(-1);
158
+ if (!isNode(hook) || !/Function/u.test(hook.type))
159
+ return;
160
+ const params = hook['params'].map(rootName);
161
+ const nextName = params[2];
162
+ const local = new Set(params.filter((name) => name !== undefined));
163
+ const tables = new Set();
164
+ const isTable = (value) => {
165
+ if (!isNode(value))
166
+ return false;
167
+ if (value.type === 'AwaitExpression')
168
+ return isTable(value['argument']);
169
+ if (value.type === 'CallExpression')
170
+ return isNode(value['callee']) && value['callee']['name'] === nextName;
171
+ return value.type === 'Identifier' && tables.has(value['name']);
172
+ };
173
+ walk(hook['body'], (inner) => {
174
+ if (inner.type === 'VariableDeclarator') {
175
+ const name = rootName(inner['id']);
176
+ if (name !== undefined) {
177
+ local.add(name);
178
+ if (isTable(inner['init']))
179
+ tables.add(name);
180
+ }
181
+ }
182
+ });
183
+ walk(hook['body'], (inner) => {
184
+ if (problem !== undefined || inner.type !== 'AssignmentExpression')
185
+ return;
186
+ const target = rootName(inner['left']);
187
+ if (target !== undefined && !local.has(target) && isTable(inner['right'])) {
188
+ problem = `its engine.create step keeps the table it is handed (in ${target}), to call outside the fold`;
189
+ }
190
+ });
191
+ });
192
+ return problem;
193
+ }
194
+ /** The scan over a bundle's own source files, as written (not as bundled). */
195
+ export function scanBundleRefusal(bundle, parseAst) {
196
+ for (const file of bundle.files) {
197
+ const ext = extname(file).toLowerCase();
198
+ const lang = ext === '.tsx' ? 'tsx' : ext === '.ts' || ext === '.mts' || ext === '.cts' ? 'ts' : ext === '.jsx' ? 'jsx' : 'js';
199
+ let text;
200
+ try {
201
+ text = readFileSync(file, 'utf8');
202
+ }
203
+ catch {
204
+ continue;
205
+ }
206
+ const problem = scanRefusal(text, parseAst, lang);
207
+ if (problem !== undefined)
208
+ return problem;
209
+ }
210
+ return undefined;
211
+ }
212
+ /** The `uses` of a bundle, read off its own source files. */
213
+ export function scanBundleUses(bundle) {
214
+ const texts = bundle.files.map((file) => {
215
+ try {
216
+ return readFileSync(file, 'utf8');
217
+ }
218
+ catch {
219
+ return '';
220
+ }
221
+ });
222
+ return scanUses(texts.length > 0 ? texts.join('\n') : bundle.code);
223
+ }
224
+ /** The `Error` of an environment, for errors a module there receives. */
225
+ export function realmOf(context) {
226
+ return { Error: vm.runInContext('Error', context) };
227
+ }
@@ -0,0 +1,13 @@
1
+ export type OpKind = 'value' | 'fire' | 'event';
2
+ export interface OpSpec {
3
+ readonly event: string;
4
+ readonly kind: OpKind;
5
+ /** The event input built from the call's arguments. */
6
+ readonly input: (args: readonly unknown[]) => Record<string, unknown>;
7
+ }
8
+ /** Every method of `$` that crosses to the host, by `<noun>.<method>`. */
9
+ export declare const OPS: Readonly<Record<string, OpSpec>>;
10
+ /** The engine's own events a test's `$` (and a plugin) may raise by name. */
11
+ export declare const ENGINE_EVENTS: readonly string[];
12
+ /** Settings hook events, raised as `classic.<Event>`. */
13
+ export declare const CLASSIC_EVENTS: readonly string[];
@@ -0,0 +1,117 @@
1
+ /**
2
+ * The mods API (`$`) as calls on the chain, read off claude-code.d.ts
3
+ * `CoreEngineInterface`, `OpEventOf` and `EventCalls`: each method raises the
4
+ * event of its own name with the call's arguments as its input.
5
+ *
6
+ * - `value` ops: hooks see `{ value } | { deny }`; the caller gets the value
7
+ * or a rejection `<plugin>: $.<op>: <reason>`;
8
+ * - `fire` ops return nothing at once and raise in the background;
9
+ * - `event` calls raise one of the engine's own events and resolve to its
10
+ * result as the event defines it.
11
+ * @module @kirkchinese/harness-forge/mods
12
+ */
13
+ import { isRecord } from './values.js';
14
+ const none = () => ({});
15
+ const first = (args) => (isRecord(args[0]) ? { ...args[0] } : {});
16
+ const named = (...names) => (args) => {
17
+ const input = {};
18
+ names.forEach((name, index) => { if (args[index] !== undefined)
19
+ input[name] = args[index]; });
20
+ return input;
21
+ };
22
+ /** Every method of `$` that crosses to the host, by `<noun>.<method>`. */
23
+ export const OPS = Object.freeze({
24
+ 'ui.notice': { event: 'ui.notice', kind: 'fire', input: args => ({ tool_use_id: args[0], text: args[1] }) },
25
+ 'ui.invalidate': { event: 'ui.invalidate', kind: 'fire', input: named('event') },
26
+ 'ui.blit': { event: 'ui.blit', kind: 'value', input: first },
27
+ 'ui.log': { event: 'ui.log', kind: 'fire', input: args => ({ text: args[0], to: (isRecord(args[1]) && typeof args[1]['to'] === 'string' ? args[1]['to'] : 'transcript') }) },
28
+ 'ui.toast': { event: 'ui.toast', kind: 'fire', input: args => ({ text: args[0], ...(isRecord(args[1]) && typeof args[1]['timeoutMs'] === 'number' ? { timeoutMs: args[1]['timeoutMs'] } : {}) }) },
29
+ 'ui.status': { event: 'ui.status', kind: 'fire', input: args => ({ text: args[0] }) },
30
+ 'ui.notify': { event: 'ui.notify', kind: 'value', input: args => (isRecord(args[0]) ? { ...args[0] } : { text: args[0], ...(isRecord(args[1]) ? args[1] : {}) }) },
31
+ 'ui.copy': { event: 'ui.copy', kind: 'value', input: args => (isRecord(args[0]) ? { ...args[0] } : { text: args[0] }) },
32
+ 'ui.selection': { event: 'ui.selection', kind: 'value', input: first },
33
+ 'ui.open': { event: 'ui.open', kind: 'value', input: first },
34
+ 'ui.close': { event: 'ui.close', kind: 'value', input: args => ({ ...first(args), origin: { kind: 'plugin' } }) },
35
+ 'ui.panes': { event: 'ui.panes', kind: 'value', input: none },
36
+ 'ui.scroll': { event: 'ui.scroll', kind: 'event', input: first },
37
+ 'ui.focus': { event: 'ui.focus', kind: 'event', input: first },
38
+ 'model.complete': { event: 'model.complete', kind: 'value', input: first },
39
+ 'model.fork': { event: 'model.fork', kind: 'value', input: first },
40
+ 'model.classify': { event: 'model.classify', kind: 'value', input: named('text', 'labels', 'options') },
41
+ 'audio.play': { event: 'audio.play', kind: 'value', input: args => ({ clip: args[0], shouldLoop: isRecord(args[1]) && args[1]['loop'] === true, ...(isRecord(args[1]) && typeof args[1]['gain'] === 'number' ? { gain: args[1]['gain'] } : {}) }) },
42
+ 'audio.speak': { event: 'audio.speak', kind: 'value', input: args => ({ text: args[0], ...(isRecord(args[1]) && typeof args[1]['voice'] === 'string' ? { voice: args[1]['voice'] } : {}) }) },
43
+ 'mcp.call': { event: 'mcp.call', kind: 'value', input: args => ({ server: args[0], tool: args[1], args: isRecord(args[2]) ? args[2] : {} }) },
44
+ 'mcp.connect': { event: 'mcp.connect', kind: 'value', input: named('server') },
45
+ 'session.messages': { event: 'session.messages', kind: 'value', input: none },
46
+ 'session.cwd': { event: 'session.cwd', kind: 'value', input: none },
47
+ 'session.root': { event: 'session.root', kind: 'value', input: none },
48
+ 'session.model': { event: 'session.model', kind: 'value', input: none },
49
+ 'session.turns': { event: 'session.turns', kind: 'value', input: none },
50
+ 'session.id': { event: 'session.id', kind: 'value', input: none },
51
+ 'session.repo': { event: 'session.repo', kind: 'value', input: none },
52
+ 'session.surfaces': { event: 'session.surfaces', kind: 'value', input: none },
53
+ 'session.surface': { event: 'session.surface', kind: 'value', input: none },
54
+ 'session.usage': { event: 'session.usage', kind: 'value', input: first },
55
+ 'session.version': { event: 'session.version', kind: 'value', input: none },
56
+ 'session.compact': { event: 'session.compact', kind: 'event', input: first },
57
+ 'session.append': { event: 'session.append', kind: 'event', input: first },
58
+ 'session.send': { event: 'session.send', kind: 'event', input: first },
59
+ 'session.authorize': { event: 'session.authorize', kind: 'value', input: none },
60
+ 'session.identity': { event: 'session.identity', kind: 'value', input: none },
61
+ 'turn.abort': { event: 'turn.abort', kind: 'value', input: first },
62
+ 'prompt.submit': { event: 'prompt.submit', kind: 'event', input: first },
63
+ 'prompt.read': { event: 'prompt.read', kind: 'value', input: none },
64
+ 'prompt.fill': { event: 'prompt.fill', kind: 'event', input: first },
65
+ 'prompt.suggest': { event: 'prompt.suggest', kind: 'event', input: first },
66
+ 'prompt.compose': { event: 'prompt.compose', kind: 'event', input: first },
67
+ 'tool.list': { event: 'tool.list', kind: 'value', input: none },
68
+ 'tool.call': { event: 'tool.call', kind: 'event', input: first },
69
+ 'tool.check': { event: 'tool.check', kind: 'event', input: first },
70
+ 'tool.register': { event: 'tool.register', kind: 'value', input: first },
71
+ 'command.list': { event: 'command.list', kind: 'value', input: none },
72
+ 'command.run': { event: 'command.run', kind: 'event', input: first },
73
+ 'command.register': { event: 'command.register', kind: 'value', input: first },
74
+ 'config.list': { event: 'config.list', kind: 'value', input: none },
75
+ 'config.set': { event: 'config.set', kind: 'event', input: first },
76
+ 'agent.spawn': { event: 'agent.spawn', kind: 'event', input: first },
77
+ 'agent.list': { event: 'agent.list', kind: 'value', input: none },
78
+ 'agent.register': { event: 'agent.register', kind: 'value', input: first },
79
+ 'fs.read': { event: 'fs.read', kind: 'value', input: args => ({ path: args[0], as: isRecord(args[1]) && args[1]['as'] === 'bytes' ? 'bytes' : 'text' }) },
80
+ 'fs.write': { event: 'fs.write', kind: 'value', input: named('path', 'text') },
81
+ 'fs.list': { event: 'fs.list', kind: 'value', input: args => ({ path: args[0] ?? '.' }) },
82
+ 'fs.exists': { event: 'fs.exists', kind: 'value', input: named('path') },
83
+ 'fs.stat': { event: 'fs.stat', kind: 'value', input: args => ({ path: args[0], resolve: isRecord(args[1]) && args[1]['resolve'] === true }) },
84
+ 'fs.ancestors': { event: 'fs.ancestors', kind: 'value', input: first },
85
+ 'store.get': { event: 'store.get', kind: 'value', input: named('key') },
86
+ 'store.set': { event: 'store.set', kind: 'value', input: args => ({ key: args[0], value: args[1] }) },
87
+ 'store.delete': { event: 'store.delete', kind: 'value', input: named('key') },
88
+ 'store.keys': { event: 'store.keys', kind: 'value', input: none },
89
+ 'clock.now': { event: 'clock.now', kind: 'value', input: none },
90
+ 'clock.sleep': { event: 'clock.sleep', kind: 'value', input: named('ms') },
91
+ 'http.fetch': { event: 'http.fetch', kind: 'value', input: args => ({ url: args[0], ...(isRecord(args[1]) ? { init: args[1] } : {}) }) },
92
+ 'process.run': { event: 'process.run', kind: 'value', input: args => ({ argv: args[0], ...(isRecord(args[1]) ? { init: args[1] } : {}) }) },
93
+ 'settings.read': { event: 'settings.read', kind: 'value', input: first },
94
+ 'env.get': { event: 'env.get', kind: 'value', input: named('name') },
95
+ 'env.set': { event: 'env.set', kind: 'value', input: args => ({ name: args[0], ...(args[1] !== undefined ? { value: args[1] } : {}) }) },
96
+ // $.telemetry (mods reference): a record is sent only when Claude Code or a built-in makes the call.
97
+ 'telemetry.log': { event: 'telemetry.log', kind: 'value', input: first },
98
+ 'telemetry.mark': { event: 'telemetry.mark', kind: 'value', input: first },
99
+ });
100
+ /** The engine's own events a test's `$` (and a plugin) may raise by name. */
101
+ export const ENGINE_EVENTS = [
102
+ 'tool.call', 'tool.check', 'tool.describe', 'command.run', 'command.describe', 'config.set', 'config.describe',
103
+ 'prompt.submit', 'prompt.fill', 'prompt.suggest', 'prompt.edit', 'prompt.section', 'prompt.context', 'prompt.attachment',
104
+ 'prompt.compose', 'prompt.mention', 'prompt.autocomplete', 'skill.prompt', 'attribution.text', 'agent.offer', 'agent.spawn',
105
+ 'session.start', 'session.receive', 'session.send', 'session.append', 'session.compact', 'session.attach', 'session.detach',
106
+ 'session.measure', 'session.end', 'plugin.register', 'turn.start', 'turn.step', 'turn.complete', 'engine.create',
107
+ 'ui.render', 'ui.resolve', 'ui.press', 'ui.input', 'ui.select', 'ui.message', 'ui.scroll', 'ui.focus', 'ui.fault', 'ui.close',
108
+ 'settings.read',
109
+ ];
110
+ /** Settings hook events, raised as `classic.<Event>`. */
111
+ export const CLASSIC_EVENTS = [
112
+ 'PreToolUse', 'PostToolUse', 'PostToolUseFailure', 'PostToolBatch', 'PermissionDenied', 'PermissionRequest', 'Notification',
113
+ 'UserPromptSubmit', 'UserPromptExpansion', 'SessionStart', 'SessionEnd', 'Stop', 'StopFailure', 'SubagentStart', 'SubagentStop',
114
+ 'PreCompact', 'PostCompact', 'PreModelSwitch', 'PostModelSwitch', 'Setup', 'TeammateIdle', 'TaskCreated', 'TaskCompleted',
115
+ 'Elicitation', 'ElicitationResult', 'ConfigChange', 'InstructionsLoaded', 'WorktreeCreate', 'WorktreeRemove', 'CwdChanged',
116
+ 'FileChanged', 'DirectoryAdded', 'MessageDisplay',
117
+ ];
@@ -0,0 +1,9 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import type { Disposer } from '../forge/contract.js';
3
+ import { type HarnessForge } from '../forge/service.js';
4
+ export declare const name = "harness-forge-mods";
5
+ export declare const inject: string[];
6
+ /** The mods row. */
7
+ export declare function apply(ctx: Context): void;
8
+ /** Start the mods row on the shared service. Returns its teardown. */
9
+ export declare function startMods(ctx: Context, forge: HarnessForge): Disposer;
@@ -0,0 +1,77 @@
1
+ /**
2
+ * The mods row: Claude Code mods, one engine per root session. Its hooks wrap
3
+ * everything Claude Code itself does, so it hooks `tool.check` into the hooks
4
+ * row's permission decision when that row runs; the hooks row knows nothing
5
+ * of mods.
6
+ * @module @kirkchinese/harness-forge/mods
7
+ */
8
+ import { join } from 'node:path';
9
+ import { HarnessError } from '@kirkchinese/harness-forge-core';
10
+ import { FORGE_SERVICE } from '../forge/service.js';
11
+ import { loggerOf, messageOf } from '../shared/util.js';
12
+ import { bundlerInstalled, bundlerPrefix, ensureBundler, ROLLDOWN_VERSION } from './bundler.js';
13
+ import { mountClaudeMod } from './claude.js';
14
+ import { ModsService } from './service.js';
15
+ import { mounted, Parts, rowEffect } from '../forge/row.js';
16
+ export const name = 'harness-forge-mods';
17
+ export const inject = [FORGE_SERVICE];
18
+ /** The mods row. */
19
+ export function apply(ctx) {
20
+ rowEffect(ctx, 'mods', forge => startMods(ctx, forge));
21
+ }
22
+ /** Start the mods row on the shared service. Returns its teardown. */
23
+ export function startMods(ctx, forge) {
24
+ const mods = new ModsService(ctx, {
25
+ shell: forge.shell,
26
+ storeRoot: join(forge.dataRoot, 'mod-store'),
27
+ disposedLog: join(forge.dataRoot, 'mods-disposed.jsonl'),
28
+ directory: (agent, signal) => forge.directory(agent, signal),
29
+ settings: (session, source) => forge.settings.claudeSettings(session, source),
30
+ rewrite: (callId, args) => { forge.lookup('hooks')?.rewrite(callId, args); },
31
+ agentName: presetId => forge.lookup('agents')?.foreignName(presetId),
32
+ presetOf: foreignName => forge.lookup('agents')?.presetOf(foreignName),
33
+ observe: (componentId, event) => {
34
+ if (event.startsWith('call:'))
35
+ forge.observe(componentId, `modcall:${event.slice('call:'.length)}`, true, `the mod called $.${event.slice('call:'.length)}`);
36
+ else
37
+ forge.observe(componentId, `mod:${event}`, true, `a hook ran for ${event}`);
38
+ },
39
+ });
40
+ const api = {
41
+ watch: (sessionId, listener) => mods.watch(sessionId, listener),
42
+ act: (sessionId, generation, actionId, value) => mods.act(sessionId, generation, actionId, value),
43
+ closePane: (sessionId, id) => mods.closePane(sessionId, id),
44
+ move: (sessionId, kind, target) => mods.move(sessionId, kind, target),
45
+ };
46
+ // The first mod waits for the bundler's install; a failed install is the mods row's fault and that mod's
47
+ // failure, and the row runs on (the next mod tries the install again).
48
+ const bundler = async () => {
49
+ if (!bundlerInstalled(forge.dataRoot))
50
+ loggerOf(ctx)?.info?.(`harness-forge: mods: waiting for the bundler (installing rolldown ${ROLLDOWN_VERSION} into ${bundlerPrefix(forge.dataRoot)})`);
51
+ try {
52
+ return await ensureBundler(forge.dataRoot);
53
+ }
54
+ catch (error) {
55
+ forge.fault('mods', error);
56
+ throw new HarnessError('component-failed', messageOf(error));
57
+ }
58
+ };
59
+ const parts = new Parts(ctx, forge, 'mods');
60
+ parts.add('engine', () => mods.install());
61
+ // Torn down before the engine: every live session's mods hear `session.end` while the listeners are there.
62
+ parts.add('session end', () => () => mods.shutdown());
63
+ parts.add('tool.check', () => forge.watch('hooks', hooks => hooks.setChecker({
64
+ checks: exec => mods.checks(exec),
65
+ check: (exec, verdict) => mods.check(exec, verdict),
66
+ })));
67
+ parts.add('mod mounter', () => forge.registerMounter('claude-mod', {
68
+ mount: async ({ component, plugin }) => {
69
+ if (component.kind !== 'code')
70
+ throw new HarnessError('component-failed', `action expects code: ${component.id}`);
71
+ const mount = await mountClaudeMod(mods, component, plugin, bundler);
72
+ return { outcome: mounted(component, 'L1b', `claude-mod ${mount.name} (${mount.tier})`), disposer: mount.dispose };
73
+ },
74
+ }));
75
+ parts.add('api', () => forge.provide('mods', api));
76
+ return () => parts.dispose();
77
+ }
@@ -0,0 +1,60 @@
1
+ /** A `$.state` value: its name and default. */
2
+ export interface Atom<T = unknown> {
3
+ readonly plugin: string;
4
+ readonly key: string;
5
+ readonly initial: T;
6
+ }
7
+ interface Derived {
8
+ readonly derived: true;
9
+ readonly from: readonly Readable[];
10
+ readonly compute: (...values: unknown[]) => unknown;
11
+ }
12
+ interface Member {
13
+ readonly member: true;
14
+ readonly of: Atom;
15
+ readonly key: string;
16
+ readonly initial: unknown;
17
+ }
18
+ type Readable = Atom | Derived | Member;
19
+ /** Name a `$.state` value and its default. */
20
+ export declare function atom<T>(id: {
21
+ plugin: string;
22
+ key: string;
23
+ }, initial: T): Atom<T>;
24
+ /** A value computed from others; `read` recomputes it, a render reading it subscribes to its sources. */
25
+ export declare function derive(from: Readable | readonly Readable[], compute: (...values: unknown[]) => unknown): Derived;
26
+ /** One member of an object-valued atom, read and written on its own. */
27
+ export declare function memberOf(of: Atom, key: string, initial?: unknown): Member;
28
+ /** Read a value: the stored one, or its default. */
29
+ export declare function read($: unknown, value: Readable): Promise<unknown>;
30
+ /** Write a value from the current one; resolves to what was written. */
31
+ export declare function update($: unknown, value: Atom | Member, change: (current: unknown) => unknown): Promise<unknown>;
32
+ /** The `claude-code` module as a hooks module imports it at run time. */
33
+ export declare const CLAUDE_CODE_MODULE: Readonly<{
34
+ atom: typeof atom;
35
+ read: typeof read;
36
+ update: typeof update;
37
+ derive: typeof derive;
38
+ memberOf: typeof memberOf;
39
+ }>;
40
+ /** A plain-data element. */
41
+ export interface Element {
42
+ readonly type: string;
43
+ readonly props: Readonly<Record<string, unknown>>;
44
+ readonly children?: readonly unknown[];
45
+ }
46
+ /** Flatten JSX children: false, null, undefined and true are dropped; numbers drawn as strings. */
47
+ export declare function normalizeChildren(children: readonly unknown[]): unknown[];
48
+ /** The JSX factory: a plain-data element from a constructor or a tag name. */
49
+ export declare function h(tag: unknown, props: Record<string, unknown> | null | undefined, ...children: unknown[]): unknown;
50
+ /** `<>...</>`: a column Box around the children. */
51
+ export declare function Fragment(props: {
52
+ children?: unknown;
53
+ }): Element;
54
+ /**
55
+ * The element table of a surface: a frozen constructor per element it draws.
56
+ * Given a plugin, its controls carry `press: { plugin }`, as the runtime
57
+ * stamps the elements a plugin's hook draws.
58
+ */
59
+ export declare function elementTable(surface: string, plugin?: string): Readonly<Record<string, unknown>>;
60
+ export {};
@@ -0,0 +1,133 @@
1
+ /**
2
+ * What a hooks module's environment provides beyond plain JavaScript: the
3
+ * `claude-code` module's run-time helpers (`atom`, `read`, `update`, `derive`,
4
+ * `memberOf` over `$.state`), the JSX factory `h` / `Fragment`, and the
5
+ * element tables `$.ui.resolve(e)` returns, by surface.
6
+ * @module @kirkchinese/harness-forge/mods
7
+ */
8
+ import { isRecord } from './values.js';
9
+ function stateOf($) {
10
+ const state = isRecord($) ? $['state'] : undefined;
11
+ if (!isRecord(state) || typeof state['get'] !== 'function')
12
+ throw new Error('read, update and derive take the hook\'s $');
13
+ return state;
14
+ }
15
+ /** Name a `$.state` value and its default. */
16
+ export function atom(id, initial) {
17
+ if (!isRecord(id) || typeof id.plugin !== 'string' || typeof id.key !== 'string')
18
+ throw new Error('atom takes { plugin, key } and a default');
19
+ return Object.freeze({ plugin: id.plugin, key: id.key, initial });
20
+ }
21
+ /** A value computed from others; `read` recomputes it, a render reading it subscribes to its sources. */
22
+ export function derive(from, compute) {
23
+ return Object.freeze({ derived: true, from: Object.freeze(Array.isArray(from) ? [...from] : [from]), compute });
24
+ }
25
+ /** One member of an object-valued atom, read and written on its own. */
26
+ export function memberOf(of, key, initial) {
27
+ return Object.freeze({ member: true, of, key, initial });
28
+ }
29
+ /** Read a value: the stored one, or its default. */
30
+ export async function read($, value) {
31
+ if ('derived' in value)
32
+ return value.compute(...await Promise.all(value.from.map(source => read($, source))));
33
+ if ('member' in value) {
34
+ const whole = await read($, value.of);
35
+ return isRecord(whole) && value.key in whole ? whole[value.key] : value.initial;
36
+ }
37
+ const stored = await stateOf($).get({ plugin: value.plugin, key: value.key });
38
+ return stored === undefined ? value.initial : stored;
39
+ }
40
+ /** Write a value from the current one; resolves to what was written. */
41
+ export async function update($, value, change) {
42
+ if ('member' in value) {
43
+ const whole = await read($, value.of);
44
+ const current = isRecord(whole) && value.key in whole ? whole[value.key] : value.initial;
45
+ const next = await change(current);
46
+ await stateOf($).set({ plugin: value.of.plugin, key: value.of.key }, { ...(isRecord(whole) ? whole : {}), [value.key]: next });
47
+ return next;
48
+ }
49
+ const next = await change(await read($, value));
50
+ await stateOf($).set({ plugin: value.plugin, key: value.key }, next);
51
+ return next;
52
+ }
53
+ /** The `claude-code` module as a hooks module imports it at run time. */
54
+ export const CLAUDE_CODE_MODULE = Object.freeze({ atom, read, update, derive, memberOf });
55
+ /** Flatten JSX children: false, null, undefined and true are dropped; numbers drawn as strings. */
56
+ export function normalizeChildren(children) {
57
+ const out = [];
58
+ const visit = (child) => {
59
+ if (child === null || child === undefined || typeof child === 'boolean')
60
+ return;
61
+ if (Array.isArray(child)) {
62
+ for (const item of child)
63
+ visit(item);
64
+ return;
65
+ }
66
+ if (typeof child === 'number') {
67
+ out.push(String(child));
68
+ return;
69
+ }
70
+ out.push(child);
71
+ };
72
+ for (const child of children)
73
+ visit(child);
74
+ return out;
75
+ }
76
+ /** The JSX factory: a plain-data element from a constructor or a tag name. */
77
+ export function h(tag, props, ...children) {
78
+ const given = { ...(props ?? {}) };
79
+ if (children.length > 0)
80
+ given['children'] = children.length === 1 ? children[0] : children;
81
+ if (typeof tag === 'function')
82
+ return tag(given);
83
+ if (typeof tag === 'string')
84
+ return element(tag, given);
85
+ throw new Error(`h: ${String(tag)} is no element constructor`);
86
+ }
87
+ /** `<>...</>`: a column Box around the children. */
88
+ export function Fragment(props) {
89
+ return element('Box', { flexDirection: 'column', children: props.children });
90
+ }
91
+ function element(type, props) {
92
+ const { children, ...rest } = props;
93
+ const list = normalizeChildren(children === undefined ? [] : [children]);
94
+ if (type === 'Button') {
95
+ // The label may be the one string child; the key defaults to the label.
96
+ const label = typeof rest['label'] === 'string' ? rest['label'] : list.every(child => typeof child === 'string') ? list.join('') : undefined;
97
+ const key = typeof rest['key'] === 'string' ? rest['key'] : label;
98
+ return Object.freeze({
99
+ type,
100
+ props: Object.freeze({ ...rest, ...(label !== undefined ? { label } : {}), ...(key !== undefined ? { key } : {}) }),
101
+ ...(list.length > 0 && !list.every(child => typeof child === 'string') ? { children: Object.freeze(list) } : {}),
102
+ });
103
+ }
104
+ return Object.freeze({ type, props: Object.freeze(rest), ...(list.length > 0 ? { children: Object.freeze(list) } : {}) });
105
+ }
106
+ /** Elements each surface draws (mods reference, "Elements"). */
107
+ const SURFACE_ELEMENTS = {
108
+ terminal: ['Box', 'Text', 'Button', 'Link', 'Code', 'Markdown', 'Input', 'Select', 'Client', 'Raster', 'Image'],
109
+ desktop: ['Box', 'Text', 'Button', 'Link', 'Code', 'Markdown', 'Input', 'Select', 'Svg', 'Client'],
110
+ vscode: ['Box', 'Text', 'Button', 'Link', 'Code', 'Markdown', 'Input', 'Select', 'Svg'],
111
+ mobile: ['Box', 'Text', 'Button', 'Link', 'Code', 'Markdown', 'Input', 'Select'],
112
+ };
113
+ const tables = new Map();
114
+ /** Elements whose callbacks a press reaches: the runtime stamps whose they are. */
115
+ const CONTROLS = new Set(['Button', 'Input', 'Select', 'Markdown']);
116
+ /**
117
+ * The element table of a surface: a frozen constructor per element it draws.
118
+ * Given a plugin, its controls carry `press: { plugin }`, as the runtime
119
+ * stamps the elements a plugin's hook draws.
120
+ */
121
+ export function elementTable(surface, plugin) {
122
+ const cacheKey = `${surface}\u0000${plugin ?? ''}`;
123
+ const cached = tables.get(cacheKey);
124
+ if (cached !== undefined)
125
+ return cached;
126
+ const names = SURFACE_ELEMENTS[surface] ?? SURFACE_ELEMENTS['terminal'];
127
+ const table = Object.freeze(Object.fromEntries(names.map(name => [name, (props) => {
128
+ const made = element(name, props ?? {});
129
+ return plugin === undefined || !CONTROLS.has(name) ? made : Object.freeze({ ...made, press: Object.freeze({ plugin }) });
130
+ }])));
131
+ tables.set(cacheKey, table);
132
+ return table;
133
+ }