toolfunnel 0.5.0 → 0.6.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 (69) hide show
  1. package/README.md +231 -167
  2. package/bin/toolfunnel.js +372 -147
  3. package/docs/KNOWN_BUGS.md +99 -33
  4. package/docs/MANUAL.pdf +0 -0
  5. package/docs/design.md +70 -0
  6. package/docs/packaging.md +115 -115
  7. package/hooks/hooks.manifest.json +27 -27
  8. package/hooks/scripts/example-audit.js +21 -21
  9. package/hooks/scripts/example-deny-dangerous.js +31 -31
  10. package/mcp/expose.example.json +30 -30
  11. package/mcp/servers/mock-modern/server.js +147 -0
  12. package/mcp/servers/mock-upstream/server.js +192 -12
  13. package/package.json +1 -1
  14. package/src/auth/config.js +174 -174
  15. package/src/auth/install.js +181 -181
  16. package/src/auth/resource-server.js +344 -344
  17. package/src/core/config-home.js +134 -134
  18. package/src/core/events.js +105 -105
  19. package/src/core/hook-engine.js +275 -275
  20. package/src/core/hook-loader.js +791 -791
  21. package/src/core/hook-runner.js +346 -346
  22. package/src/core/logger.js +171 -171
  23. package/src/core/matcher.js +51 -51
  24. package/src/core/metrics.js +75 -75
  25. package/src/core/requires.js +138 -138
  26. package/src/core/server-config.js +98 -77
  27. package/src/core/tool-registry.js +180 -180
  28. package/src/extend/add-hook.md +152 -142
  29. package/src/extend/add-mcp.md +122 -121
  30. package/src/extend/configure.md +87 -0
  31. package/src/extend/create-tool.md +168 -152
  32. package/src/extend/howto.js +102 -98
  33. package/src/extend/package.md +187 -187
  34. package/src/extend/wrap.md +99 -0
  35. package/src/mcp/aggregator.js +1246 -807
  36. package/src/mcp/expose-store.js +460 -430
  37. package/src/mcp/gated-run.js +201 -194
  38. package/src/mcp/http-transport.js +1311 -1012
  39. package/src/mcp/mcp-client.js +907 -530
  40. package/src/mcp/modern.js +372 -0
  41. package/src/mcp/protocol.js +468 -466
  42. package/src/mcp/server.js +2688 -1405
  43. package/src/packages/packager.js +715 -715
  44. package/src/tools/drift.js +138 -138
  45. package/src/tools/registry.js +513 -513
  46. package/src/tools/tool-state.js +170 -104
  47. package/src/ui/public/app.js +1174 -1055
  48. package/src/ui/public/index.html +286 -249
  49. package/src/ui/public/styles.css +535 -535
  50. package/src/ui/server.js +1348 -1190
  51. package/tools/scripts/base64.js +139 -139
  52. package/tools/scripts/danger.js +61 -61
  53. package/tools/scripts/echo.js +39 -39
  54. package/tools/scripts/hash.js +101 -101
  55. package/tools/scripts/json.js +109 -109
  56. package/tools/scripts/text-stats.js +131 -131
  57. package/tools/scripts/tf-env.js +43 -43
  58. package/tools/scripts/tf-hook-add.js +151 -151
  59. package/tools/scripts/tf-hook-set.js +112 -112
  60. package/tools/scripts/tf-list.js +192 -192
  61. package/tools/scripts/tf-log.js +86 -86
  62. package/tools/scripts/tf-mcp-add.js +117 -117
  63. package/tools/scripts/tf-mcp-set.js +121 -102
  64. package/tools/scripts/tf-pack.js +237 -237
  65. package/tools/scripts/tf-tool-add.js +134 -129
  66. package/tools/scripts/tf-tool-set.js +142 -142
  67. package/tools/scripts/tf-wrap.js +103 -0
  68. package/tools/scripts/uuid.js +102 -102
  69. package/tools/tools.register.json +227 -216
@@ -1,513 +1,513 @@
1
- 'use strict';
2
-
3
- /**
4
- * registry.js — the dynamic, persisted Tool Register (see the architecture doc §5).
5
- *
6
- * This is distinct from src/core/tool-registry.js: that one is the in-memory
7
- * catalogue of tools handed to a backend at connect time. THIS one is the
8
- * structured, on-disk register the lean meta-tools (toolfunnel_list_tools /
9
- * toolfunnel_tool_instructions / toolfunnel_run_tool) read every call — so register edits
10
- * are visible with no reconnect (§1, "no restart for register changes").
11
- *
12
- * Register entry shape (tools.register.json -> { version, description, tools:[] }):
13
- * { id, name, summary, category, instructions, invoke, mode? }
14
- * invoke is one of:
15
- * { type: "script", path: "scripts/<file>" } // run a host-local script
16
- * { type: "shell", command: "..." } // run a shell command
17
- * mode (optional) is one of:
18
- * "gateway" — execute the invoke server-side via the gated run path (default for
19
- * a script/shell invoke; the original behaviour).
20
- * "reference" — do NOT execute; toolfunnel_run_tool returns the instructions so the
21
- * connected AI runs the action itself. invoke may be omitted.
22
- * When mode is absent it is inferred: script/shell invoke -> "gateway", else "reference".
23
- *
24
- * Responsibilities:
25
- * list({filter?, category?}) -> briefs only [{id,name,summary,category}]
26
- * instructions(id) -> the full instructions string (throws on unknown)
27
- * getEntry(id) -> the full entry (clone; throws on unknown)
28
- * add(entry) / update(id,patch) / remove(id) -> mutate + ATOMIC persist
29
- * resolveExecution(id, args) -> { type, run: () => Promise<result> }
30
- * describes HOW to run the invoke. It does NOT
31
- * gate — gating is gated-run.js's job (§9).
32
- *
33
- * Pure-ish: the registry only touches its own JSON file + (for script invokes)
34
- * spawns node on a path resolved under this src/tools dir. Dependencies that a
35
- * test may want to stub (the executor) are injectable.
36
- *
37
- * CommonJS, Node built-ins only, atomic writes (temp + rename).
38
- */
39
-
40
- const fs = require('node:fs');
41
- const path = require('node:path');
42
- const { spawn } = require('node:child_process');
43
-
44
- const VALID_INVOKE_TYPES = new Set(['script', 'shell']);
45
-
46
- /**
47
- * Execution modes (optional per-entry "mode" field):
48
- * "gateway" — ToolFunnel EXECUTES the invoke server-side through the gated run path
49
- * (the original behaviour for every script/shell tool).
50
- * "reference" — ToolFunnel does NOT execute. toolfunnel_run_tool returns the tool's
51
- * instructions so the connected AI performs the action in ITS OWN
52
- * environment. A reference tool needs no invoke (nothing runs here).
53
- */
54
- const VALID_MODES = new Set(['reference', 'gateway']);
55
-
56
- /**
57
- * Resolve an entry's execution mode. An explicit, valid `mode` wins. When absent it is
58
- * INFERRED backward-compatibly: a script/shell invoke means "gateway" (run it here, as
59
- * every existing tool does); anything else means "reference" (there is nothing to run).
60
- * @param {object} entry a register entry
61
- * @returns {"gateway"|"reference"}
62
- */
63
- function resolveMode(entry) {
64
- if (entry && (entry.mode === 'reference' || entry.mode === 'gateway')) return entry.mode;
65
- const t = entry && entry.invoke && entry.invoke.type;
66
- return t === 'script' || t === 'shell' ? 'gateway' : 'reference';
67
- }
68
-
69
- /** Deep-ish clone for plain JSON entries (structuredClone may be absent on old node). */
70
- function cloneEntry(entry) {
71
- return JSON.parse(JSON.stringify(entry));
72
- }
73
-
74
- /**
75
- * Atomic write: serialise to a temp file in the SAME directory as the target
76
- * (so rename is atomic on the same filesystem/drive), fsync, then rename over
77
- * the target. A crash leaves either the old file or the new file, never a
78
- * half-written register.
79
- */
80
- function atomicWriteJson(targetPath, obj) {
81
- const dir = path.dirname(targetPath);
82
- const base = path.basename(targetPath);
83
- const tmp = path.join(dir, `.${base}.${process.pid}.${Date.now()}.tmp`);
84
- const data = JSON.stringify(obj, null, 2) + '\n';
85
- const fd = fs.openSync(tmp, 'w');
86
- try {
87
- fs.writeSync(fd, data, 0, 'utf8');
88
- fs.fsyncSync(fd);
89
- } finally {
90
- fs.closeSync(fd);
91
- }
92
- fs.renameSync(tmp, targetPath);
93
- }
94
-
95
- /** Validate a register entry shape; throws with a clear message on a bad shape. */
96
- function validateEntry(entry, { requireId = true } = {}) {
97
- if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
98
- throw new Error('Registry: entry must be an object');
99
- }
100
- if (requireId && (typeof entry.id !== 'string' || entry.id.length === 0)) {
101
- throw new Error('Registry: entry.id must be a non-empty string');
102
- }
103
- if (typeof entry.name !== 'string' || entry.name.length === 0) {
104
- throw new Error(`Registry: entry.name must be a non-empty string (id=${entry.id})`);
105
- }
106
- // Optional execution mode. When present it must be one of the valid modes.
107
- if (entry.mode !== undefined && !VALID_MODES.has(entry.mode)) {
108
- throw new Error(
109
- `Registry: entry.mode must be one of ${[...VALID_MODES].join('|')} (id=${entry.id})`
110
- );
111
- }
112
- // A reference tool executes nothing server-side, so its invoke may be omitted. Only an
113
- // EXPLICIT mode:"reference" relaxes this — with mode absent the invoke is still required
114
- // (backward-compatible: every existing tool keeps its mandatory invoke).
115
- if (entry.mode === 'reference' && entry.invoke === undefined) {
116
- return entry;
117
- }
118
- const inv = entry.invoke;
119
- if (!inv || typeof inv !== 'object') {
120
- throw new Error(`Registry: entry.invoke is required (id=${entry.id})`);
121
- }
122
- if (!VALID_INVOKE_TYPES.has(inv.type)) {
123
- throw new Error(
124
- `Registry: entry.invoke.type must be one of ${[...VALID_INVOKE_TYPES].join('|')} (id=${entry.id})`
125
- );
126
- }
127
- if (inv.type === 'script' && (typeof inv.path !== 'string' || inv.path.length === 0)) {
128
- throw new Error(`Registry: script invoke needs a non-empty "path" (id=${entry.id})`);
129
- }
130
- if (inv.type === 'shell' && (typeof inv.command !== 'string' || inv.command.length === 0)) {
131
- throw new Error(`Registry: shell invoke needs a non-empty "command" (id=${entry.id})`);
132
- }
133
- // Optional MCP input schema. When present it must be a plain object — a hot-promoted tool
134
- // advertises it VERBATIM to MCP clients (tools/list), so a typo'd shape must fail loudly at
135
- // authoring time rather than silently degrade to the free-form fallback at surface time.
136
- if (
137
- entry.inputSchema !== undefined &&
138
- (typeof entry.inputSchema !== 'object' || entry.inputSchema === null || Array.isArray(entry.inputSchema))
139
- ) {
140
- throw new Error(`Registry: entry.inputSchema must be an object when present (id=${entry.id})`);
141
- }
142
- return entry;
143
- }
144
-
145
- /**
146
- * Default script executor: spawn `node <resolved script>` with the structured
147
- * args passed in env TOOLFUNNEL_TOOL_ARGS. Resolves with { ok, code, stdout, stderr }.
148
- * Never rejects on a non-zero exit — the caller (the gated runner / meta-tool)
149
- * decides how to surface a tool failure. It DOES reject only on spawn failure.
150
- *
151
- * Path safety: the script path must resolve INSIDE scriptsRoot (defense-in-depth
152
- * for the isolation rule — a register entry must not become a path-escape).
153
- */
154
- function defaultRunScript(scriptsRoot, invoke, args) {
155
- return new Promise((resolve, reject) => {
156
- const resolved = path.resolve(scriptsRoot, path.basename(invoke.path));
157
- // path.basename strips any directory traversal; confirm anyway.
158
- const rel = path.relative(scriptsRoot, resolved);
159
- if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel)) {
160
- reject(new Error(`Registry: script path escapes scripts root ("${invoke.path}")`));
161
- return;
162
- }
163
- if (!fs.existsSync(resolved)) {
164
- reject(new Error(`Registry: script not found ("${resolved}")`));
165
- return;
166
- }
167
- const child = spawn(process.execPath, [resolved], {
168
- env: { ...process.env, TOOLFUNNEL_TOOL_ARGS: JSON.stringify(args ?? null) },
169
- stdio: ['ignore', 'pipe', 'pipe'],
170
- });
171
- let stdout = '';
172
- let stderr = '';
173
- child.stdout.on('data', (d) => { stdout += d.toString(); });
174
- child.stderr.on('data', (d) => { stderr += d.toString(); });
175
- child.on('error', reject);
176
- child.on('close', (code) => {
177
- resolve({ ok: code === 0, code, stdout, stderr });
178
- });
179
- });
180
- }
181
-
182
- class Registry {
183
- /**
184
- * @param {object} opts
185
- * @param {string} opts.filePath path to tools.register.json (source of truth on disk)
186
- * @param {object} opts.data parsed register data { version, description, tools }
187
- * @param {string} [opts.scriptsRoot] dir holding script-invoke targets (default: <fileDir>/scripts)
188
- * @param {Function} [opts.runScript] injectable (scriptsRoot, invoke, args) => Promise<result>
189
- */
190
- constructor({ filePath, data, scriptsRoot, runScript } = {}) {
191
- if (!filePath) throw new Error('Registry: filePath is required');
192
- this._filePath = filePath;
193
- this._scriptsRoot = scriptsRoot || path.join(path.dirname(filePath), 'scripts');
194
- this._runScript = runScript || defaultRunScript;
195
-
196
- const d = data && typeof data === 'object' ? data : {};
197
- this._version = typeof d.version === 'number' ? d.version : 1;
198
- this._description = typeof d.description === 'string' ? d.description : '';
199
- const tools = Array.isArray(d.tools) ? d.tools : [];
200
-
201
- // Index by id; reject duplicate ids at load (a duplicate id makes
202
- // instructions(id)/run(id) ambiguous).
203
- this._byId = new Map();
204
- for (const t of tools) {
205
- validateEntry(t);
206
- if (this._byId.has(t.id)) {
207
- throw new Error(`Registry: duplicate tool id "${t.id}" in ${filePath}`);
208
- }
209
- this._byId.set(t.id, cloneEntry(t));
210
- }
211
- }
212
-
213
- // ---- read API -----------------------------------------------------------
214
-
215
- /**
216
- * Briefs only — the surface toolfunnel_list_tools returns. Optional case-insensitive
217
- * substring `filter` (matched against id/name/summary) and exact `category`.
218
- * @returns {Array<{id,name,summary,category}>} in insertion order.
219
- */
220
- list({ filter, category } = {}) {
221
- const needle = typeof filter === 'string' && filter.length ? filter.toLowerCase() : null;
222
- const out = [];
223
- for (const t of this._byId.values()) {
224
- if (category && t.category !== category) continue;
225
- if (needle) {
226
- const hay = `${t.id} ${t.name} ${t.summary || ''}`.toLowerCase();
227
- if (!hay.includes(needle)) continue;
228
- }
229
- out.push({
230
- id: t.id,
231
- name: t.name,
232
- summary: t.summary || '',
233
- category: t.category || '',
234
- });
235
- }
236
- return out;
237
- }
238
-
239
- /** Full instructions string for one tool. Throws on unknown id (per §5 contract). */
240
- instructions(id) {
241
- const t = this._byId.get(id);
242
- if (!t) throw new Error(`Registry.instructions: unknown tool id "${id}"`);
243
- return typeof t.instructions === 'string' ? t.instructions : '';
244
- }
245
-
246
- /** Full entry (cloned so callers can't mutate internal state). Throws on unknown id. */
247
- getEntry(id) {
248
- const t = this._byId.get(id);
249
- if (!t) throw new Error(`Registry.getEntry: unknown tool id "${id}"`);
250
- return cloneEntry(t);
251
- }
252
-
253
- /** @returns {boolean} */
254
- has(id) {
255
- return this._byId.has(id);
256
- }
257
-
258
- // ---- write API (atomic persist) ----------------------------------------
259
-
260
- /** Add a new entry. Throws if id missing/duplicate or shape invalid. Persists. */
261
- add(entry) {
262
- validateEntry(entry);
263
- if (this._byId.has(entry.id)) {
264
- throw new Error(`Registry.add: tool id "${entry.id}" already exists`);
265
- }
266
- this._byId.set(entry.id, cloneEntry(entry));
267
- this._persist();
268
- return this.getEntry(entry.id);
269
- }
270
-
271
- /**
272
- * Patch an existing entry. `id` cannot be changed via patch (it's the key).
273
- * Merges shallow over the existing entry, re-validates, persists.
274
- */
275
- update(id, patch) {
276
- const existing = this._byId.get(id);
277
- if (!existing) throw new Error(`Registry.update: unknown tool id "${id}"`);
278
- if (!patch || typeof patch !== 'object') {
279
- throw new Error('Registry.update: patch must be an object');
280
- }
281
- const merged = { ...existing, ...patch, id };
282
- validateEntry(merged);
283
- this._byId.set(id, cloneEntry(merged));
284
- this._persist();
285
- return this.getEntry(id);
286
- }
287
-
288
- /** Remove an entry. Throws on unknown id. Persists. */
289
- remove(id) {
290
- if (!this._byId.has(id)) throw new Error(`Registry.remove: unknown tool id "${id}"`);
291
- this._byId.delete(id);
292
- this._persist();
293
- return true;
294
- }
295
-
296
- /**
297
- * Re-read the register FILE and swap the in-memory index — the hot-reload seam. A running
298
- * gateway holds ONE Registry instance (captured by the protocol adapter at build time), while
299
- * tf_tool_add / the UI / a hand edit mutate the FILE from another process — without this, those
300
- * edits are invisible until restart. LAST-GOOD semantics: the replacement index is built and
301
- * fully validated FIRST; any read/parse/validation failure (including a mid-write partial file)
302
- * leaves the current index untouched and returns false. NEVER throws.
303
- * @returns {boolean} true when the on-disk register replaced the in-memory index
304
- */
305
- reload() {
306
- let data;
307
- try {
308
- data = JSON.parse(fs.readFileSync(this._filePath, 'utf8'));
309
- } catch (_e) {
310
- return false; // unreadable / mid-write / bad JSON → keep last-good
311
- }
312
- if (!data || typeof data !== 'object' || Array.isArray(data)) return false;
313
- const tools = Array.isArray(data.tools) ? data.tools : [];
314
- const next = new Map();
315
- try {
316
- for (const t of tools) {
317
- validateEntry(t);
318
- if (next.has(t.id)) throw new Error(`duplicate tool id "${t.id}"`);
319
- next.set(t.id, cloneEntry(t));
320
- }
321
- } catch (_e) {
322
- return false; // an invalid entry → keep last-good
323
- }
324
- if (typeof data.version === 'number') this._version = data.version;
325
- if (typeof data.description === 'string') this._description = data.description;
326
- this._byId = next;
327
- return true;
328
- }
329
-
330
- /**
331
- * Write a host-local script's text under this scriptsRoot, atomically.
332
- *
333
- * Resolves path.basename(invokePath) under scriptsRoot (basename strips any
334
- * directory traversal) and GUARDS that the resolved path stays inside
335
- * scriptsRoot — the same path-escape defence as defaultRunScript, so a
336
- * tf_tool_add(scriptText) can never write outside the isolation root. Writes
337
- * `text` via a temp file in the same dir + fsync + rename (mirror of
338
- * atomicWriteJson): a crash leaves either no file or the complete file.
339
- *
340
- * @param {string} invokePath e.g. "scripts/foo.js" — only the basename is honoured
341
- * @param {string} text full file contents to write
342
- * @returns {string} the resolved absolute path that was written
343
- */
344
- writeScript(invokePath, text) {
345
- if (typeof invokePath !== 'string' || invokePath.length === 0) {
346
- throw new Error('Registry.writeScript: invokePath (non-empty string) is required');
347
- }
348
- if (typeof text !== 'string') {
349
- throw new Error('Registry.writeScript: text must be a string');
350
- }
351
- const scriptsRoot = this._scriptsRoot;
352
- const resolved = path.resolve(scriptsRoot, path.basename(invokePath));
353
- // path.basename strips any directory traversal; confirm anyway.
354
- const rel = path.relative(scriptsRoot, resolved);
355
- if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel)) {
356
- throw new Error(`Registry.writeScript: script path escapes scripts root ("${invokePath}")`);
357
- }
358
- fs.mkdirSync(scriptsRoot, { recursive: true });
359
- const dir = path.dirname(resolved);
360
- const base = path.basename(resolved);
361
- const tmp = path.join(dir, `.${base}.${process.pid}.${Date.now()}.tmp`);
362
- const fd = fs.openSync(tmp, 'w');
363
- try {
364
- fs.writeSync(fd, text, 0, 'utf8');
365
- fs.fsyncSync(fd);
366
- } finally {
367
- fs.closeSync(fd);
368
- }
369
- fs.renameSync(tmp, resolved);
370
- return resolved;
371
- }
372
-
373
- // ---- execution description (does NOT gate) ------------------------------
374
-
375
- /**
376
- * Describe HOW to run a tool's invoke. Returns { type, run } where `run` is a
377
- * zero-arg function returning a Promise of the tool result. resolveExecution
378
- * performs NO gating — toolfunnel_run_tool / gated-run.js fires the PreToolUse hook
379
- * and only then calls `run()` (the architecture doc §2/§9). Keeping the gate
380
- * out of here keeps the safety case in one auditable place.
381
- *
382
- * - script invoke: run() spawns node on the host-local script (via the injected
383
- * runScript), passing args in TOOLFUNNEL_TOOL_ARGS.
384
- * - shell invoke: run() does NOT execute here. It returns a descriptor
385
- * { type:'shell', command, args } so the gated runner owns the actual shell
386
- * spawn (the broadest power) behind the gate. This keeps arbitrary shell
387
- * execution out of the un-gated register module by design.
388
- *
389
- * @param {string} id
390
- * @param {any} args structured args forwarded to the tool
391
- * @returns {{ type: string, run: () => Promise<any> }}
392
- */
393
- resolveExecution(id, args) {
394
- const entry = this._byId.get(id);
395
- if (!entry) throw new Error(`Registry.resolveExecution: unknown tool id "${id}"`);
396
- const mode = resolveMode(entry);
397
-
398
- // ---- reference mode: nothing runs here. ----------------------------------
399
- // The connected AI performs the action in its own environment. We hand back the
400
- // tool's instructions (no `run`) so the run-path takes the no-spawn branch — a
401
- // reference tool never spawns server-side. The instruction HANDOFF is still gated
402
- // in protocol.runTool (a PreToolUse deny withholds the instructions); it's execution,
403
- // not the gate, that's absent here.
404
- if (mode === 'reference') {
405
- return {
406
- type: 'reference',
407
- mode: 'reference',
408
- instructions: typeof entry.instructions === 'string' ? entry.instructions : '',
409
- };
410
- }
411
-
412
- const invoke = entry.invoke;
413
-
414
- if (invoke.type === 'script') {
415
- const scriptsRoot = this._scriptsRoot;
416
- const runScript = this._runScript;
417
- return {
418
- type: 'script',
419
- mode: 'gateway',
420
- run: () => runScript(scriptsRoot, invoke, args),
421
- };
422
- }
423
-
424
- if (invoke.type === 'shell') {
425
- // Deliberately do NOT spawn a shell here. Hand the descriptor to the
426
- // gated runner, which executes shell only after PreToolUse allows it.
427
- return {
428
- type: 'shell',
429
- mode: 'gateway',
430
- run: async () => ({
431
- deferred: true,
432
- type: 'shell',
433
- command: invoke.command,
434
- args: args ?? null,
435
- }),
436
- };
437
- }
438
-
439
- // validateEntry guards the load path, but guard here too for late mutation.
440
- throw new Error(`Registry.resolveExecution: unsupported invoke.type for "${id}"`);
441
- }
442
-
443
- /**
444
- * The resolved execution mode for a tool ("gateway" | "reference"). Exposed so callers
445
- * (UI, tests) can ask without resolving a full executor. Throws on unknown id.
446
- * @param {string} id
447
- * @returns {"gateway"|"reference"}
448
- */
449
- mode(id) {
450
- const entry = this._byId.get(id);
451
- if (!entry) throw new Error(`Registry.mode: unknown tool id "${id}"`);
452
- return resolveMode(entry);
453
- }
454
-
455
- // ---- internals ----------------------------------------------------------
456
-
457
- /** Serialise current state back to the register file atomically. */
458
- _persist() {
459
- const obj = {
460
- version: this._version,
461
- description: this._description,
462
- tools: [...this._byId.values()],
463
- };
464
- atomicWriteJson(this._filePath, obj);
465
- }
466
-
467
- /** @returns {number} */
468
- get size() {
469
- return this._byId.size;
470
- }
471
- }
472
-
473
- /**
474
- * loadRegistry(path) -> Registry
475
- *
476
- * Reads + parses the register JSON at `filePath` and returns a Registry bound to
477
- * it. Throws a clear error on a missing/malformed file or a bad entry shape so
478
- * misconfiguration is caught at load time, not at model-call time.
479
- *
480
- * @param {string} filePath
481
- * @param {object} [opts] forwarded to the Registry ctor (scriptsRoot, runScript)
482
- * @returns {Registry}
483
- */
484
- function loadRegistry(filePath, opts = {}) {
485
- if (typeof filePath !== 'string' || filePath.length === 0) {
486
- throw new Error('loadRegistry: filePath (non-empty string) is required');
487
- }
488
- let raw;
489
- try {
490
- raw = fs.readFileSync(filePath, 'utf8');
491
- } catch (err) {
492
- throw new Error(`loadRegistry: cannot read register at "${filePath}": ${err.message}`);
493
- }
494
- let data;
495
- try {
496
- data = JSON.parse(raw);
497
- } catch (err) {
498
- throw new Error(`loadRegistry: register at "${filePath}" is not valid JSON: ${err.message}`);
499
- }
500
- return new Registry({ filePath, data, ...opts });
501
- }
502
-
503
- module.exports = {
504
- Registry,
505
- loadRegistry,
506
- // exported for unit tests / the gated runner
507
- atomicWriteJson,
508
- validateEntry,
509
- defaultRunScript,
510
- resolveMode,
511
- VALID_INVOKE_TYPES,
512
- VALID_MODES,
513
- };
1
+ 'use strict';
2
+
3
+ /**
4
+ * registry.js - the dynamic, persisted Tool Register (see the architecture doc §5).
5
+ *
6
+ * This is distinct from src/core/tool-registry.js: that one is the in-memory
7
+ * catalogue of tools handed to a backend at connect time. THIS one is the
8
+ * structured, on-disk register the lean meta-tools (toolfunnel_list_tools /
9
+ * toolfunnel_tool_instructions / toolfunnel_run_tool) read every call - so register edits
10
+ * are visible with no reconnect (§1, "no restart for register changes").
11
+ *
12
+ * Register entry shape (tools.register.json -> { version, description, tools:[] }):
13
+ * { id, name, summary, category, instructions, invoke, mode? }
14
+ * invoke is one of:
15
+ * { type: "script", path: "scripts/<file>" } // run a host-local script
16
+ * { type: "shell", command: "..." } // run a shell command
17
+ * mode (optional) is one of:
18
+ * "gateway" - execute the invoke server-side via the gated run path (default for
19
+ * a script/shell invoke; the original behaviour).
20
+ * "reference" - do NOT execute; toolfunnel_run_tool returns the instructions so the
21
+ * connected AI runs the action itself. invoke may be omitted.
22
+ * When mode is absent it is inferred: script/shell invoke -> "gateway", else "reference".
23
+ *
24
+ * Responsibilities:
25
+ * list({filter?, category?}) -> briefs only [{id,name,summary,category}]
26
+ * instructions(id) -> the full instructions string (throws on unknown)
27
+ * getEntry(id) -> the full entry (clone; throws on unknown)
28
+ * add(entry) / update(id,patch) / remove(id) -> mutate + ATOMIC persist
29
+ * resolveExecution(id, args) -> { type, run: () => Promise<result> }
30
+ * describes HOW to run the invoke. It does NOT
31
+ * gate - gating is gated-run.js's job (§9).
32
+ *
33
+ * Pure-ish: the registry only touches its own JSON file + (for script invokes)
34
+ * spawns node on a path resolved under this src/tools dir. Dependencies that a
35
+ * test may want to stub (the executor) are injectable.
36
+ *
37
+ * CommonJS, Node built-ins only, atomic writes (temp + rename).
38
+ */
39
+
40
+ const fs = require('node:fs');
41
+ const path = require('node:path');
42
+ const { spawn } = require('node:child_process');
43
+
44
+ const VALID_INVOKE_TYPES = new Set(['script', 'shell']);
45
+
46
+ /**
47
+ * Execution modes (optional per-entry "mode" field):
48
+ * "gateway" - ToolFunnel EXECUTES the invoke server-side through the gated run path
49
+ * (the original behaviour for every script/shell tool).
50
+ * "reference" - ToolFunnel does NOT execute. toolfunnel_run_tool returns the tool's
51
+ * instructions so the connected AI performs the action in ITS OWN
52
+ * environment. A reference tool needs no invoke (nothing runs here).
53
+ */
54
+ const VALID_MODES = new Set(['reference', 'gateway']);
55
+
56
+ /**
57
+ * Resolve an entry's execution mode. An explicit, valid `mode` wins. When absent it is
58
+ * INFERRED backward-compatibly: a script/shell invoke means "gateway" (run it here, as
59
+ * every existing tool does); anything else means "reference" (there is nothing to run).
60
+ * @param {object} entry a register entry
61
+ * @returns {"gateway"|"reference"}
62
+ */
63
+ function resolveMode(entry) {
64
+ if (entry && (entry.mode === 'reference' || entry.mode === 'gateway')) return entry.mode;
65
+ const t = entry && entry.invoke && entry.invoke.type;
66
+ return t === 'script' || t === 'shell' ? 'gateway' : 'reference';
67
+ }
68
+
69
+ /** Deep-ish clone for plain JSON entries (structuredClone may be absent on old node). */
70
+ function cloneEntry(entry) {
71
+ return JSON.parse(JSON.stringify(entry));
72
+ }
73
+
74
+ /**
75
+ * Atomic write: serialise to a temp file in the SAME directory as the target
76
+ * (so rename is atomic on the same filesystem/drive), fsync, then rename over
77
+ * the target. A crash leaves either the old file or the new file, never a
78
+ * half-written register.
79
+ */
80
+ function atomicWriteJson(targetPath, obj) {
81
+ const dir = path.dirname(targetPath);
82
+ const base = path.basename(targetPath);
83
+ const tmp = path.join(dir, `.${base}.${process.pid}.${Date.now()}.tmp`);
84
+ const data = JSON.stringify(obj, null, 2) + '\n';
85
+ const fd = fs.openSync(tmp, 'w');
86
+ try {
87
+ fs.writeSync(fd, data, 0, 'utf8');
88
+ fs.fsyncSync(fd);
89
+ } finally {
90
+ fs.closeSync(fd);
91
+ }
92
+ fs.renameSync(tmp, targetPath);
93
+ }
94
+
95
+ /** Validate a register entry shape; throws with a clear message on a bad shape. */
96
+ function validateEntry(entry, { requireId = true } = {}) {
97
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
98
+ throw new Error('Registry: entry must be an object');
99
+ }
100
+ if (requireId && (typeof entry.id !== 'string' || entry.id.length === 0)) {
101
+ throw new Error('Registry: entry.id must be a non-empty string');
102
+ }
103
+ if (typeof entry.name !== 'string' || entry.name.length === 0) {
104
+ throw new Error(`Registry: entry.name must be a non-empty string (id=${entry.id})`);
105
+ }
106
+ // Optional execution mode. When present it must be one of the valid modes.
107
+ if (entry.mode !== undefined && !VALID_MODES.has(entry.mode)) {
108
+ throw new Error(
109
+ `Registry: entry.mode must be one of ${[...VALID_MODES].join('|')} (id=${entry.id})`
110
+ );
111
+ }
112
+ // A reference tool executes nothing server-side, so its invoke may be omitted. Only an
113
+ // EXPLICIT mode:"reference" relaxes this - with mode absent the invoke is still required
114
+ // (backward-compatible: every existing tool keeps its mandatory invoke).
115
+ if (entry.mode === 'reference' && entry.invoke === undefined) {
116
+ return entry;
117
+ }
118
+ const inv = entry.invoke;
119
+ if (!inv || typeof inv !== 'object') {
120
+ throw new Error(`Registry: entry.invoke is required (id=${entry.id})`);
121
+ }
122
+ if (!VALID_INVOKE_TYPES.has(inv.type)) {
123
+ throw new Error(
124
+ `Registry: entry.invoke.type must be one of ${[...VALID_INVOKE_TYPES].join('|')} (id=${entry.id})`
125
+ );
126
+ }
127
+ if (inv.type === 'script' && (typeof inv.path !== 'string' || inv.path.length === 0)) {
128
+ throw new Error(`Registry: script invoke needs a non-empty "path" (id=${entry.id})`);
129
+ }
130
+ if (inv.type === 'shell' && (typeof inv.command !== 'string' || inv.command.length === 0)) {
131
+ throw new Error(`Registry: shell invoke needs a non-empty "command" (id=${entry.id})`);
132
+ }
133
+ // Optional MCP input schema. When present it must be a plain object - a hot-promoted tool
134
+ // advertises it VERBATIM to MCP clients (tools/list), so a typo'd shape must fail loudly at
135
+ // authoring time rather than silently degrade to the free-form fallback at surface time.
136
+ if (
137
+ entry.inputSchema !== undefined &&
138
+ (typeof entry.inputSchema !== 'object' || entry.inputSchema === null || Array.isArray(entry.inputSchema))
139
+ ) {
140
+ throw new Error(`Registry: entry.inputSchema must be an object when present (id=${entry.id})`);
141
+ }
142
+ return entry;
143
+ }
144
+
145
+ /**
146
+ * Default script executor: spawn `node <resolved script>` with the structured
147
+ * args passed in env TOOLFUNNEL_TOOL_ARGS. Resolves with { ok, code, stdout, stderr }.
148
+ * Never rejects on a non-zero exit - the caller (the gated runner / meta-tool)
149
+ * decides how to surface a tool failure. It DOES reject only on spawn failure.
150
+ *
151
+ * Path safety: the script path must resolve INSIDE scriptsRoot (defense-in-depth
152
+ * for the isolation rule - a register entry must not become a path-escape).
153
+ */
154
+ function defaultRunScript(scriptsRoot, invoke, args) {
155
+ return new Promise((resolve, reject) => {
156
+ const resolved = path.resolve(scriptsRoot, path.basename(invoke.path));
157
+ // path.basename strips any directory traversal; confirm anyway.
158
+ const rel = path.relative(scriptsRoot, resolved);
159
+ if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel)) {
160
+ reject(new Error(`Registry: script path escapes scripts root ("${invoke.path}")`));
161
+ return;
162
+ }
163
+ if (!fs.existsSync(resolved)) {
164
+ reject(new Error(`Registry: script not found ("${resolved}")`));
165
+ return;
166
+ }
167
+ const child = spawn(process.execPath, [resolved], {
168
+ env: { ...process.env, TOOLFUNNEL_TOOL_ARGS: JSON.stringify(args ?? null) },
169
+ stdio: ['ignore', 'pipe', 'pipe'],
170
+ });
171
+ let stdout = '';
172
+ let stderr = '';
173
+ child.stdout.on('data', (d) => { stdout += d.toString(); });
174
+ child.stderr.on('data', (d) => { stderr += d.toString(); });
175
+ child.on('error', reject);
176
+ child.on('close', (code) => {
177
+ resolve({ ok: code === 0, code, stdout, stderr });
178
+ });
179
+ });
180
+ }
181
+
182
+ class Registry {
183
+ /**
184
+ * @param {object} opts
185
+ * @param {string} opts.filePath path to tools.register.json (source of truth on disk)
186
+ * @param {object} opts.data parsed register data { version, description, tools }
187
+ * @param {string} [opts.scriptsRoot] dir holding script-invoke targets (default: <fileDir>/scripts)
188
+ * @param {Function} [opts.runScript] injectable (scriptsRoot, invoke, args) => Promise<result>
189
+ */
190
+ constructor({ filePath, data, scriptsRoot, runScript } = {}) {
191
+ if (!filePath) throw new Error('Registry: filePath is required');
192
+ this._filePath = filePath;
193
+ this._scriptsRoot = scriptsRoot || path.join(path.dirname(filePath), 'scripts');
194
+ this._runScript = runScript || defaultRunScript;
195
+
196
+ const d = data && typeof data === 'object' ? data : {};
197
+ this._version = typeof d.version === 'number' ? d.version : 1;
198
+ this._description = typeof d.description === 'string' ? d.description : '';
199
+ const tools = Array.isArray(d.tools) ? d.tools : [];
200
+
201
+ // Index by id; reject duplicate ids at load (a duplicate id makes
202
+ // instructions(id)/run(id) ambiguous).
203
+ this._byId = new Map();
204
+ for (const t of tools) {
205
+ validateEntry(t);
206
+ if (this._byId.has(t.id)) {
207
+ throw new Error(`Registry: duplicate tool id "${t.id}" in ${filePath}`);
208
+ }
209
+ this._byId.set(t.id, cloneEntry(t));
210
+ }
211
+ }
212
+
213
+ // ---- read API -----------------------------------------------------------
214
+
215
+ /**
216
+ * Briefs only - the surface toolfunnel_list_tools returns. Optional case-insensitive
217
+ * substring `filter` (matched against id/name/summary) and exact `category`.
218
+ * @returns {Array<{id,name,summary,category}>} in insertion order.
219
+ */
220
+ list({ filter, category } = {}) {
221
+ const needle = typeof filter === 'string' && filter.length ? filter.toLowerCase() : null;
222
+ const out = [];
223
+ for (const t of this._byId.values()) {
224
+ if (category && t.category !== category) continue;
225
+ if (needle) {
226
+ const hay = `${t.id} ${t.name} ${t.summary || ''}`.toLowerCase();
227
+ if (!hay.includes(needle)) continue;
228
+ }
229
+ out.push({
230
+ id: t.id,
231
+ name: t.name,
232
+ summary: t.summary || '',
233
+ category: t.category || '',
234
+ });
235
+ }
236
+ return out;
237
+ }
238
+
239
+ /** Full instructions string for one tool. Throws on unknown id (per §5 contract). */
240
+ instructions(id) {
241
+ const t = this._byId.get(id);
242
+ if (!t) throw new Error(`Registry.instructions: unknown tool id "${id}"`);
243
+ return typeof t.instructions === 'string' ? t.instructions : '';
244
+ }
245
+
246
+ /** Full entry (cloned so callers can't mutate internal state). Throws on unknown id. */
247
+ getEntry(id) {
248
+ const t = this._byId.get(id);
249
+ if (!t) throw new Error(`Registry.getEntry: unknown tool id "${id}"`);
250
+ return cloneEntry(t);
251
+ }
252
+
253
+ /** @returns {boolean} */
254
+ has(id) {
255
+ return this._byId.has(id);
256
+ }
257
+
258
+ // ---- write API (atomic persist) ----------------------------------------
259
+
260
+ /** Add a new entry. Throws if id missing/duplicate or shape invalid. Persists. */
261
+ add(entry) {
262
+ validateEntry(entry);
263
+ if (this._byId.has(entry.id)) {
264
+ throw new Error(`Registry.add: tool id "${entry.id}" already exists`);
265
+ }
266
+ this._byId.set(entry.id, cloneEntry(entry));
267
+ this._persist();
268
+ return this.getEntry(entry.id);
269
+ }
270
+
271
+ /**
272
+ * Patch an existing entry. `id` cannot be changed via patch (it's the key).
273
+ * Merges shallow over the existing entry, re-validates, persists.
274
+ */
275
+ update(id, patch) {
276
+ const existing = this._byId.get(id);
277
+ if (!existing) throw new Error(`Registry.update: unknown tool id "${id}"`);
278
+ if (!patch || typeof patch !== 'object') {
279
+ throw new Error('Registry.update: patch must be an object');
280
+ }
281
+ const merged = { ...existing, ...patch, id };
282
+ validateEntry(merged);
283
+ this._byId.set(id, cloneEntry(merged));
284
+ this._persist();
285
+ return this.getEntry(id);
286
+ }
287
+
288
+ /** Remove an entry. Throws on unknown id. Persists. */
289
+ remove(id) {
290
+ if (!this._byId.has(id)) throw new Error(`Registry.remove: unknown tool id "${id}"`);
291
+ this._byId.delete(id);
292
+ this._persist();
293
+ return true;
294
+ }
295
+
296
+ /**
297
+ * Re-read the register FILE and swap the in-memory index - the hot-reload seam. A running
298
+ * gateway holds ONE Registry instance (captured by the protocol adapter at build time), while
299
+ * tf_tool_add / the UI / a hand edit mutate the FILE from another process - without this, those
300
+ * edits are invisible until restart. LAST-GOOD semantics: the replacement index is built and
301
+ * fully validated FIRST; any read/parse/validation failure (including a mid-write partial file)
302
+ * leaves the current index untouched and returns false. NEVER throws.
303
+ * @returns {boolean} true when the on-disk register replaced the in-memory index
304
+ */
305
+ reload() {
306
+ let data;
307
+ try {
308
+ data = JSON.parse(fs.readFileSync(this._filePath, 'utf8'));
309
+ } catch (_e) {
310
+ return false; // unreadable / mid-write / bad JSON -> keep last-good
311
+ }
312
+ if (!data || typeof data !== 'object' || Array.isArray(data)) return false;
313
+ const tools = Array.isArray(data.tools) ? data.tools : [];
314
+ const next = new Map();
315
+ try {
316
+ for (const t of tools) {
317
+ validateEntry(t);
318
+ if (next.has(t.id)) throw new Error(`duplicate tool id "${t.id}"`);
319
+ next.set(t.id, cloneEntry(t));
320
+ }
321
+ } catch (_e) {
322
+ return false; // an invalid entry -> keep last-good
323
+ }
324
+ if (typeof data.version === 'number') this._version = data.version;
325
+ if (typeof data.description === 'string') this._description = data.description;
326
+ this._byId = next;
327
+ return true;
328
+ }
329
+
330
+ /**
331
+ * Write a host-local script's text under this scriptsRoot, atomically.
332
+ *
333
+ * Resolves path.basename(invokePath) under scriptsRoot (basename strips any
334
+ * directory traversal) and GUARDS that the resolved path stays inside
335
+ * scriptsRoot - the same path-escape defence as defaultRunScript, so a
336
+ * tf_tool_add(scriptText) can never write outside the isolation root. Writes
337
+ * `text` via a temp file in the same dir + fsync + rename (mirror of
338
+ * atomicWriteJson): a crash leaves either no file or the complete file.
339
+ *
340
+ * @param {string} invokePath e.g. "scripts/foo.js" - only the basename is honoured
341
+ * @param {string} text full file contents to write
342
+ * @returns {string} the resolved absolute path that was written
343
+ */
344
+ writeScript(invokePath, text) {
345
+ if (typeof invokePath !== 'string' || invokePath.length === 0) {
346
+ throw new Error('Registry.writeScript: invokePath (non-empty string) is required');
347
+ }
348
+ if (typeof text !== 'string') {
349
+ throw new Error('Registry.writeScript: text must be a string');
350
+ }
351
+ const scriptsRoot = this._scriptsRoot;
352
+ const resolved = path.resolve(scriptsRoot, path.basename(invokePath));
353
+ // path.basename strips any directory traversal; confirm anyway.
354
+ const rel = path.relative(scriptsRoot, resolved);
355
+ if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel)) {
356
+ throw new Error(`Registry.writeScript: script path escapes scripts root ("${invokePath}")`);
357
+ }
358
+ fs.mkdirSync(scriptsRoot, { recursive: true });
359
+ const dir = path.dirname(resolved);
360
+ const base = path.basename(resolved);
361
+ const tmp = path.join(dir, `.${base}.${process.pid}.${Date.now()}.tmp`);
362
+ const fd = fs.openSync(tmp, 'w');
363
+ try {
364
+ fs.writeSync(fd, text, 0, 'utf8');
365
+ fs.fsyncSync(fd);
366
+ } finally {
367
+ fs.closeSync(fd);
368
+ }
369
+ fs.renameSync(tmp, resolved);
370
+ return resolved;
371
+ }
372
+
373
+ // ---- execution description (does NOT gate) ------------------------------
374
+
375
+ /**
376
+ * Describe HOW to run a tool's invoke. Returns { type, run } where `run` is a
377
+ * zero-arg function returning a Promise of the tool result. resolveExecution
378
+ * performs NO gating - toolfunnel_run_tool / gated-run.js fires the PreToolUse hook
379
+ * and only then calls `run()` (the architecture doc §2/§9). Keeping the gate
380
+ * out of here keeps the safety case in one auditable place.
381
+ *
382
+ * - script invoke: run() spawns node on the host-local script (via the injected
383
+ * runScript), passing args in TOOLFUNNEL_TOOL_ARGS.
384
+ * - shell invoke: run() does NOT execute here. It returns a descriptor
385
+ * { type:'shell', command, args } so the gated runner owns the actual shell
386
+ * spawn (the broadest power) behind the gate. This keeps arbitrary shell
387
+ * execution out of the un-gated register module by design.
388
+ *
389
+ * @param {string} id
390
+ * @param {any} args structured args forwarded to the tool
391
+ * @returns {{ type: string, run: () => Promise<any> }}
392
+ */
393
+ resolveExecution(id, args) {
394
+ const entry = this._byId.get(id);
395
+ if (!entry) throw new Error(`Registry.resolveExecution: unknown tool id "${id}"`);
396
+ const mode = resolveMode(entry);
397
+
398
+ // ---- reference mode: nothing runs here. ----------------------------------
399
+ // The connected AI performs the action in its own environment. We hand back the
400
+ // tool's instructions (no `run`) so the run-path takes the no-spawn branch - a
401
+ // reference tool never spawns server-side. The instruction HANDOFF is still gated
402
+ // in protocol.runTool (a PreToolUse deny withholds the instructions); it's execution,
403
+ // not the gate, that's absent here.
404
+ if (mode === 'reference') {
405
+ return {
406
+ type: 'reference',
407
+ mode: 'reference',
408
+ instructions: typeof entry.instructions === 'string' ? entry.instructions : '',
409
+ };
410
+ }
411
+
412
+ const invoke = entry.invoke;
413
+
414
+ if (invoke.type === 'script') {
415
+ const scriptsRoot = this._scriptsRoot;
416
+ const runScript = this._runScript;
417
+ return {
418
+ type: 'script',
419
+ mode: 'gateway',
420
+ run: () => runScript(scriptsRoot, invoke, args),
421
+ };
422
+ }
423
+
424
+ if (invoke.type === 'shell') {
425
+ // Deliberately do NOT spawn a shell here. Hand the descriptor to the
426
+ // gated runner, which executes shell only after PreToolUse allows it.
427
+ return {
428
+ type: 'shell',
429
+ mode: 'gateway',
430
+ run: async () => ({
431
+ deferred: true,
432
+ type: 'shell',
433
+ command: invoke.command,
434
+ args: args ?? null,
435
+ }),
436
+ };
437
+ }
438
+
439
+ // validateEntry guards the load path, but guard here too for late mutation.
440
+ throw new Error(`Registry.resolveExecution: unsupported invoke.type for "${id}"`);
441
+ }
442
+
443
+ /**
444
+ * The resolved execution mode for a tool ("gateway" | "reference"). Exposed so callers
445
+ * (UI, tests) can ask without resolving a full executor. Throws on unknown id.
446
+ * @param {string} id
447
+ * @returns {"gateway"|"reference"}
448
+ */
449
+ mode(id) {
450
+ const entry = this._byId.get(id);
451
+ if (!entry) throw new Error(`Registry.mode: unknown tool id "${id}"`);
452
+ return resolveMode(entry);
453
+ }
454
+
455
+ // ---- internals ----------------------------------------------------------
456
+
457
+ /** Serialise current state back to the register file atomically. */
458
+ _persist() {
459
+ const obj = {
460
+ version: this._version,
461
+ description: this._description,
462
+ tools: [...this._byId.values()],
463
+ };
464
+ atomicWriteJson(this._filePath, obj);
465
+ }
466
+
467
+ /** @returns {number} */
468
+ get size() {
469
+ return this._byId.size;
470
+ }
471
+ }
472
+
473
+ /**
474
+ * loadRegistry(path) -> Registry
475
+ *
476
+ * Reads + parses the register JSON at `filePath` and returns a Registry bound to
477
+ * it. Throws a clear error on a missing/malformed file or a bad entry shape so
478
+ * misconfiguration is caught at load time, not at model-call time.
479
+ *
480
+ * @param {string} filePath
481
+ * @param {object} [opts] forwarded to the Registry ctor (scriptsRoot, runScript)
482
+ * @returns {Registry}
483
+ */
484
+ function loadRegistry(filePath, opts = {}) {
485
+ if (typeof filePath !== 'string' || filePath.length === 0) {
486
+ throw new Error('loadRegistry: filePath (non-empty string) is required');
487
+ }
488
+ let raw;
489
+ try {
490
+ raw = fs.readFileSync(filePath, 'utf8');
491
+ } catch (err) {
492
+ throw new Error(`loadRegistry: cannot read register at "${filePath}": ${err.message}`);
493
+ }
494
+ let data;
495
+ try {
496
+ data = JSON.parse(raw);
497
+ } catch (err) {
498
+ throw new Error(`loadRegistry: register at "${filePath}" is not valid JSON: ${err.message}`);
499
+ }
500
+ return new Registry({ filePath, data, ...opts });
501
+ }
502
+
503
+ module.exports = {
504
+ Registry,
505
+ loadRegistry,
506
+ // exported for unit tests / the gated runner
507
+ atomicWriteJson,
508
+ validateEntry,
509
+ defaultRunScript,
510
+ resolveMode,
511
+ VALID_INVOKE_TYPES,
512
+ VALID_MODES,
513
+ };