toolfunnel 0.3.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 (66) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +324 -0
  3. package/bin/toolfunnel.js +112 -0
  4. package/docs/admin-ui.md +404 -0
  5. package/docs/configuration.md +402 -0
  6. package/docs/hooks-and-gating.md +428 -0
  7. package/docs/logging.md +223 -0
  8. package/docs/management.md +429 -0
  9. package/docs/oauth.md +103 -0
  10. package/docs/setup.md +352 -0
  11. package/docs/tools-and-upstreams.md +469 -0
  12. package/hooks/hooks.manifest.json +27 -0
  13. package/hooks/scripts/.gitkeep +3 -0
  14. package/hooks/scripts/example-audit.js +21 -0
  15. package/hooks/scripts/example-deny-dangerous.js +31 -0
  16. package/mcp/expose.example.json +30 -0
  17. package/mcp/servers/mock-upstream/server.js +170 -0
  18. package/package.json +63 -0
  19. package/src/auth/config.js +172 -0
  20. package/src/auth/install.js +181 -0
  21. package/src/auth/resource-server.js +319 -0
  22. package/src/core/events.js +105 -0
  23. package/src/core/hook-engine.js +275 -0
  24. package/src/core/hook-loader.js +791 -0
  25. package/src/core/hook-runner.js +346 -0
  26. package/src/core/logger.js +169 -0
  27. package/src/core/matcher.js +51 -0
  28. package/src/core/metrics.js +75 -0
  29. package/src/core/tool-registry.js +180 -0
  30. package/src/extend/add-hook.md +142 -0
  31. package/src/extend/add-mcp.md +121 -0
  32. package/src/extend/create-tool.md +132 -0
  33. package/src/extend/howto.js +98 -0
  34. package/src/extend/package.md +154 -0
  35. package/src/mcp/aggregator.js +802 -0
  36. package/src/mcp/expose-store.js +430 -0
  37. package/src/mcp/gated-run.js +194 -0
  38. package/src/mcp/http-transport.js +962 -0
  39. package/src/mcp/mcp-client.js +524 -0
  40. package/src/mcp/protocol.js +466 -0
  41. package/src/mcp/server.js +1240 -0
  42. package/src/packages/packager.js +713 -0
  43. package/src/tools/drift.js +138 -0
  44. package/src/tools/registry.js +468 -0
  45. package/src/tools/tool-state.js +104 -0
  46. package/src/ui/public/app.js +1055 -0
  47. package/src/ui/public/index.html +249 -0
  48. package/src/ui/public/logo.jpg +0 -0
  49. package/src/ui/public/styles.css +535 -0
  50. package/src/ui/server.js +1144 -0
  51. package/tools/scripts/base64.js +139 -0
  52. package/tools/scripts/danger.js +61 -0
  53. package/tools/scripts/echo.js +39 -0
  54. package/tools/scripts/hash.js +101 -0
  55. package/tools/scripts/json.js +109 -0
  56. package/tools/scripts/text-stats.js +131 -0
  57. package/tools/scripts/tf-hook-add.js +152 -0
  58. package/tools/scripts/tf-hook-set.js +113 -0
  59. package/tools/scripts/tf-list.js +195 -0
  60. package/tools/scripts/tf-log.js +83 -0
  61. package/tools/scripts/tf-mcp-add.js +119 -0
  62. package/tools/scripts/tf-mcp-set.js +104 -0
  63. package/tools/scripts/tf-tool-add.js +129 -0
  64. package/tools/scripts/tf-tool-set.js +148 -0
  65. package/tools/scripts/uuid.js +102 -0
  66. package/tools/tools.register.json +171 -0
@@ -0,0 +1,430 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * expose-store.js — the persisted MCP config store (the architecture notes and
5
+ * the extension guide define the authoritative shape).
6
+ *
7
+ * This is a PURE, config-only module: no process spawning, no network, no MCP
8
+ * client. It is the on-disk source of truth that the (Phase 2) aggregator reads
9
+ * to know WHICH upstream MCPs to connect to and WHICH of their tools to surface
10
+ * downstream as curated-direct tools. Editing this store is how a human/model
11
+ * authors the MCP surface; the aggregator just consumes the result.
12
+ *
13
+ * Persisted file shape (src/mcp/expose.json):
14
+ * {
15
+ * "version": 1,
16
+ * "upstreams": [
17
+ * { id, transport:"stdio", command, args:[], env:{}, enabled:bool, description }
18
+ * ],
19
+ * "expose": [
20
+ * { upstream, tool, as, category, enabled:bool }
21
+ * ]
22
+ * }
23
+ *
24
+ * Two blocks (per the extension guide):
25
+ * - upstreams[] — one entry per upstream MCP. `id` is the stable key referenced
26
+ * by expose[].upstream. `transport:"stdio"` spawns command+args.
27
+ * - expose[] — which upstream tools become curated-direct. `(upstream,tool)`
28
+ * is the natural key; `as` is the downstream name the CLI sees
29
+ * (defaults to `<upstream>_<tool>` so two upstreams can't collide).
30
+ *
31
+ * Read/write discipline (mirrors src/tools/registry.js — the safety contract):
32
+ * - READS never throw and always return CLONES (callers cannot mutate internal
33
+ * state, and a missing file is simply an empty store).
34
+ * - WRITES validate and throw a clear error on a bad write; nothing is persisted
35
+ * when validation fails.
36
+ * - Persistence is ATOMIC: a temp file in the SAME directory, fsync, then rename
37
+ * over the target (copied exactly from registry.js::atomicWriteJson). A crash
38
+ * leaves either the old file or the new file, never a half-written config.
39
+ * - loadExposeStore on a MISSING file returns an empty store bound to the path;
40
+ * the file is NOT created until the first write (keeps the server starting
41
+ * clean with no live upstreams).
42
+ *
43
+ * CommonJS only. Node built-ins only. No new npm dependency.
44
+ */
45
+
46
+ const fs = require('node:fs');
47
+ const path = require('node:path');
48
+
49
+ const VALID_TRANSPORTS = new Set(['stdio']);
50
+
51
+ /** Deep-ish clone for plain JSON values (structuredClone may be absent on old node). */
52
+ function clone(value) {
53
+ return JSON.parse(JSON.stringify(value));
54
+ }
55
+
56
+ /**
57
+ * Atomic write: serialise to a temp file in the SAME directory as the target (so
58
+ * the rename is atomic on the same filesystem/drive), fsync, then rename over the
59
+ * target. Copied verbatim from src/tools/registry.js so the two stores share one
60
+ * proven persistence pattern.
61
+ */
62
+ function atomicWriteJson(targetPath, obj) {
63
+ const dir = path.dirname(targetPath);
64
+ const base = path.basename(targetPath);
65
+ const tmp = path.join(dir, `.${base}.${process.pid}.${Date.now()}.tmp`);
66
+ const data = JSON.stringify(obj, null, 2) + '\n';
67
+ const fd = fs.openSync(tmp, 'w');
68
+ try {
69
+ fs.writeSync(fd, data, 0, 'utf8');
70
+ fs.fsyncSync(fd);
71
+ } finally {
72
+ fs.closeSync(fd);
73
+ }
74
+ fs.renameSync(tmp, targetPath);
75
+ }
76
+
77
+ /** True for a non-empty string. */
78
+ function isNonEmptyString(v) {
79
+ return typeof v === 'string' && v.length > 0;
80
+ }
81
+
82
+ /**
83
+ * Normalise a raw upstream object into the canonical shape, filling sane defaults
84
+ * for the optional fields. Does NOT validate — used both on load (lenient) and as
85
+ * the base for write-validation. Always returns a fresh object.
86
+ */
87
+ function normaliseUpstream(raw) {
88
+ const u = raw && typeof raw === 'object' ? raw : {};
89
+ return {
90
+ id: typeof u.id === 'string' ? u.id : '',
91
+ transport: typeof u.transport === 'string' ? u.transport : 'stdio',
92
+ command: typeof u.command === 'string' ? u.command : '',
93
+ args: Array.isArray(u.args) ? u.args.slice() : [],
94
+ env: u.env && typeof u.env === 'object' && !Array.isArray(u.env) ? { ...u.env } : {},
95
+ enabled: typeof u.enabled === 'boolean' ? u.enabled : true,
96
+ description: typeof u.description === 'string' ? u.description : '',
97
+ };
98
+ }
99
+
100
+ /**
101
+ * Normalise a raw expose object into the canonical shape. `as` is left as-is (may
102
+ * be empty); exposedName() / addExpose() apply the `<upstream>_<tool>` default so
103
+ * the stored entry can carry an explicit override or fall back lazily.
104
+ */
105
+ function normaliseExpose(raw) {
106
+ const e = raw && typeof raw === 'object' ? raw : {};
107
+ return {
108
+ upstream: typeof e.upstream === 'string' ? e.upstream : '',
109
+ tool: typeof e.tool === 'string' ? e.tool : '',
110
+ as: typeof e.as === 'string' ? e.as : '',
111
+ category: typeof e.category === 'string' ? e.category : '',
112
+ enabled: typeof e.enabled === 'boolean' ? e.enabled : true,
113
+ };
114
+ }
115
+
116
+ /**
117
+ * Validate an upstream entry for a WRITE. Throws a clear error on a bad shape.
118
+ * - id must be a non-empty string and unique among the OTHER upstreams.
119
+ * - transport must be 'stdio' (the only baseline transport).
120
+ * - a stdio upstream requires a non-empty command.
121
+ * @param {object} entry normalised upstream
122
+ * @param {Map} byId existing upstreams keyed by id (for uniqueness)
123
+ * @param {string} [ignoreId] an id to skip in the uniqueness check (updates)
124
+ */
125
+ function validateUpstream(entry, byId, ignoreId) {
126
+ if (!isNonEmptyString(entry.id)) {
127
+ throw new Error('ExposeStore: upstream.id must be a non-empty string');
128
+ }
129
+ if (byId.has(entry.id) && entry.id !== ignoreId) {
130
+ throw new Error(`ExposeStore: upstream id "${entry.id}" already exists`);
131
+ }
132
+ if (!VALID_TRANSPORTS.has(entry.transport)) {
133
+ throw new Error(
134
+ `ExposeStore: upstream.transport must be one of ${[...VALID_TRANSPORTS].join('|')} (id=${entry.id})`
135
+ );
136
+ }
137
+ if (entry.transport === 'stdio' && !isNonEmptyString(entry.command)) {
138
+ throw new Error(`ExposeStore: stdio upstream needs a non-empty "command" (id=${entry.id})`);
139
+ }
140
+ return entry;
141
+ }
142
+
143
+ class ExposeStore {
144
+ /**
145
+ * @param {object} opts
146
+ * @param {string} opts.filePath path to expose.json (source of truth on disk)
147
+ * @param {object} [opts.data] parsed config { version, upstreams, expose }
148
+ */
149
+ constructor({ filePath, data } = {}) {
150
+ if (!isNonEmptyString(filePath)) throw new Error('ExposeStore: filePath is required');
151
+ this._filePath = filePath;
152
+
153
+ const d = data && typeof data === 'object' ? data : {};
154
+ this._version = typeof d.version === 'number' ? d.version : 1;
155
+
156
+ // Index upstreams by id; reject duplicate ids at load (a duplicate id makes
157
+ // getUpstream / cascade-remove ambiguous). Keep insertion order via the Map.
158
+ this._upstreams = new Map();
159
+ const rawUpstreams = Array.isArray(d.upstreams) ? d.upstreams : [];
160
+ for (const raw of rawUpstreams) {
161
+ const u = normaliseUpstream(raw);
162
+ if (!isNonEmptyString(u.id)) {
163
+ throw new Error(`ExposeStore: an upstream is missing its id in ${filePath}`);
164
+ }
165
+ if (this._upstreams.has(u.id)) {
166
+ throw new Error(`ExposeStore: duplicate upstream id "${u.id}" in ${filePath}`);
167
+ }
168
+ this._upstreams.set(u.id, u);
169
+ }
170
+
171
+ // expose[] is kept as an ordered array; the natural key is (upstream,tool).
172
+ // Reject duplicate (upstream,tool) pairs at load.
173
+ this._expose = [];
174
+ const seenExpose = new Set();
175
+ const rawExpose = Array.isArray(d.expose) ? d.expose : [];
176
+ for (const raw of rawExpose) {
177
+ const e = normaliseExpose(raw);
178
+ const key = `${e.upstream} ${e.tool}`;
179
+ if (seenExpose.has(key)) {
180
+ throw new Error(
181
+ `ExposeStore: duplicate expose entry (upstream="${e.upstream}", tool="${e.tool}") in ${filePath}`
182
+ );
183
+ }
184
+ seenExpose.add(key);
185
+ this._expose.push(e);
186
+ }
187
+ }
188
+
189
+ // ── upstreams: read API (clones, never throw) ─────────────────────────────
190
+
191
+ /** @returns {Array<{id,transport,command,args,env,enabled,description}>} cloned, in order. */
192
+ listUpstreams() {
193
+ return [...this._upstreams.values()].map(clone);
194
+ }
195
+
196
+ /** @returns {object|undefined} cloned upstream entry, or undefined if unknown. */
197
+ getUpstream(id) {
198
+ const u = this._upstreams.get(id);
199
+ return u ? clone(u) : undefined;
200
+ }
201
+
202
+ // ── upstreams: write API (validate + atomic persist) ──────────────────────
203
+
204
+ /**
205
+ * Add an upstream. Validates: unique non-empty id; transport === 'stdio';
206
+ * stdio requires a non-empty command. Persists atomically. Returns the clone.
207
+ */
208
+ addUpstream(entry) {
209
+ const u = normaliseUpstream(entry);
210
+ validateUpstream(u, this._upstreams);
211
+ this._upstreams.set(u.id, u);
212
+ this._persist();
213
+ return clone(u);
214
+ }
215
+
216
+ /**
217
+ * Shallow-merge `patch` over an existing upstream. `id` is immutable (the key);
218
+ * any `id` in the patch is ignored. Re-validates the merged result and persists.
219
+ */
220
+ updateUpstream(id, patch) {
221
+ const existing = this._upstreams.get(id);
222
+ if (!existing) throw new Error(`ExposeStore.updateUpstream: unknown upstream id "${id}"`);
223
+ if (!patch || typeof patch !== 'object' || Array.isArray(patch)) {
224
+ throw new Error('ExposeStore.updateUpstream: patch must be an object');
225
+ }
226
+ const merged = normaliseUpstream({ ...existing, ...patch, id });
227
+ validateUpstream(merged, this._upstreams, id);
228
+ this._upstreams.set(id, merged);
229
+ this._persist();
230
+ return clone(merged);
231
+ }
232
+
233
+ /**
234
+ * Remove an upstream AND cascade-remove any expose[] entries whose `upstream`
235
+ * matches this id (a dangling expose entry would reference a missing upstream).
236
+ * Persists atomically. Throws on an unknown id.
237
+ * @returns {true}
238
+ */
239
+ removeUpstream(id) {
240
+ if (!this._upstreams.has(id)) {
241
+ throw new Error(`ExposeStore.removeUpstream: unknown upstream id "${id}"`);
242
+ }
243
+ this._upstreams.delete(id);
244
+ this._expose = this._expose.filter((e) => e.upstream !== id);
245
+ this._persist();
246
+ return true;
247
+ }
248
+
249
+ /** Toggle an upstream's `enabled` flag; persists. Throws on unknown id. */
250
+ setUpstreamEnabled(id, enabled) {
251
+ return this.updateUpstream(id, { enabled: !!enabled });
252
+ }
253
+
254
+ // ── expose: read API (clones, never throw) ────────────────────────────────
255
+
256
+ /**
257
+ * List exposed entries. Optional filters:
258
+ * - `upstream` restrict to one upstream id.
259
+ * - `enabledOnly` only entries with enabled === true.
260
+ * @returns {Array<{upstream,tool,as,category,enabled}>} cloned, in order.
261
+ */
262
+ listExposed({ upstream, enabledOnly } = {}) {
263
+ const out = [];
264
+ for (const e of this._expose) {
265
+ if (upstream && e.upstream !== upstream) continue;
266
+ if (enabledOnly && e.enabled !== true) continue;
267
+ out.push(clone(e));
268
+ }
269
+ return out;
270
+ }
271
+
272
+ /** @returns {object|undefined} cloned expose entry for (upstream,tool), or undefined. */
273
+ getExposed(upstream, tool) {
274
+ const e = this._findExpose(upstream, tool);
275
+ return e ? clone(e) : undefined;
276
+ }
277
+
278
+ /**
279
+ * The downstream name the CLI sees for an expose entry: explicit `as` if set,
280
+ * else the namespaced default `<upstream>_<tool>`.
281
+ * @param {{upstream,tool,as?}} e
282
+ * @returns {string}
283
+ */
284
+ exposedName(e) {
285
+ const obj = e && typeof e === 'object' ? e : {};
286
+ if (isNonEmptyString(obj.as)) return obj.as;
287
+ return `${obj.upstream}_${obj.tool}`;
288
+ }
289
+
290
+ // ── expose: write API (validate + atomic persist) ─────────────────────────
291
+
292
+ /**
293
+ * Add an expose entry. Validates: the `upstream` must EXIST; `tool` must be a
294
+ * non-empty string; `(upstream,tool)` must be unique. `as` defaults to the
295
+ * namespaced `<upstream>_<tool>`. Persists atomically. Returns the clone.
296
+ */
297
+ addExpose(entry) {
298
+ const e = normaliseExpose(entry);
299
+ if (!isNonEmptyString(e.upstream)) {
300
+ throw new Error('ExposeStore.addExpose: expose.upstream must be a non-empty string');
301
+ }
302
+ if (!this._upstreams.has(e.upstream)) {
303
+ throw new Error(`ExposeStore.addExpose: unknown upstream "${e.upstream}" (add the upstream first)`);
304
+ }
305
+ if (!isNonEmptyString(e.tool)) {
306
+ throw new Error(`ExposeStore.addExpose: expose.tool must be a non-empty string (upstream=${e.upstream})`);
307
+ }
308
+ if (this._findExpose(e.upstream, e.tool)) {
309
+ throw new Error(
310
+ `ExposeStore.addExpose: expose entry (upstream="${e.upstream}", tool="${e.tool}") already exists`
311
+ );
312
+ }
313
+ // Persist an explicit `as` (default the namespaced name so the stored entry
314
+ // is self-describing and the aggregator never has to recompute it).
315
+ e.as = isNonEmptyString(e.as) ? e.as : `${e.upstream}_${e.tool}`;
316
+ this._expose.push(e);
317
+ this._persist();
318
+ return clone(e);
319
+ }
320
+
321
+ /**
322
+ * Shallow-merge `patch` over an existing expose entry. The natural key
323
+ * `(upstream,tool)` is immutable — any `upstream`/`tool` in the patch is ignored.
324
+ * Persists atomically. Throws on an unknown (upstream,tool).
325
+ */
326
+ updateExpose(upstream, tool, patch) {
327
+ const idx = this._indexOfExpose(upstream, tool);
328
+ if (idx === -1) {
329
+ throw new Error(`ExposeStore.updateExpose: unknown expose entry (upstream="${upstream}", tool="${tool}")`);
330
+ }
331
+ if (!patch || typeof patch !== 'object' || Array.isArray(patch)) {
332
+ throw new Error('ExposeStore.updateExpose: patch must be an object');
333
+ }
334
+ const merged = normaliseExpose({ ...this._expose[idx], ...patch, upstream, tool });
335
+ this._expose[idx] = merged;
336
+ this._persist();
337
+ return clone(merged);
338
+ }
339
+
340
+ /** Remove an expose entry. Persists. Throws on an unknown (upstream,tool). @returns {true} */
341
+ removeExpose(upstream, tool) {
342
+ const idx = this._indexOfExpose(upstream, tool);
343
+ if (idx === -1) {
344
+ throw new Error(`ExposeStore.removeExpose: unknown expose entry (upstream="${upstream}", tool="${tool}")`);
345
+ }
346
+ this._expose.splice(idx, 1);
347
+ this._persist();
348
+ return true;
349
+ }
350
+
351
+ /** Toggle an expose entry's `enabled` flag; persists. Throws on unknown (upstream,tool). */
352
+ setExposeEnabled(upstream, tool, enabled) {
353
+ return this.updateExpose(upstream, tool, { enabled: !!enabled });
354
+ }
355
+
356
+ // ── serialisation ─────────────────────────────────────────────────────────
357
+
358
+ /** @returns {{version, upstreams, expose}} a clone of the full config (safe to mutate). */
359
+ toJSON() {
360
+ return {
361
+ version: this._version,
362
+ upstreams: [...this._upstreams.values()].map(clone),
363
+ expose: this._expose.map(clone),
364
+ };
365
+ }
366
+
367
+ // ── internals ───────────────────────────────────────────────────────────
368
+
369
+ /** @returns {object|undefined} the LIVE expose entry (not a clone) for (upstream,tool). */
370
+ _findExpose(upstream, tool) {
371
+ return this._expose.find((e) => e.upstream === upstream && e.tool === tool);
372
+ }
373
+
374
+ /** @returns {number} index of the expose entry for (upstream,tool), or -1. */
375
+ _indexOfExpose(upstream, tool) {
376
+ return this._expose.findIndex((e) => e.upstream === upstream && e.tool === tool);
377
+ }
378
+
379
+ /** Serialise current state back to the config file atomically. */
380
+ _persist() {
381
+ atomicWriteJson(this._filePath, this.toJSON());
382
+ }
383
+ }
384
+
385
+ /**
386
+ * loadExposeStore(filePath) -> ExposeStore
387
+ *
388
+ * Reads + parses the config JSON at `filePath` and returns an ExposeStore bound to
389
+ * it.
390
+ * - MISSING file → return an empty store bound to filePath. The file is NOT
391
+ * created until the first write (keeps the server starting clean).
392
+ * - MALFORMED JSON (or a duplicate id / duplicate expose key) → throw a clear
393
+ * error so misconfiguration is caught at load, not at run time.
394
+ *
395
+ * @param {string} filePath
396
+ * @returns {ExposeStore}
397
+ */
398
+ function loadExposeStore(filePath) {
399
+ if (!isNonEmptyString(filePath)) {
400
+ throw new Error('loadExposeStore: filePath (non-empty string) is required');
401
+ }
402
+ let raw;
403
+ try {
404
+ raw = fs.readFileSync(filePath, 'utf8');
405
+ } catch (err) {
406
+ if (err && err.code === 'ENOENT') {
407
+ // Missing file is not an error — bind an empty store; defer file creation.
408
+ return new ExposeStore({ filePath, data: { version: 1, upstreams: [], expose: [] } });
409
+ }
410
+ throw new Error(`loadExposeStore: cannot read config at "${filePath}": ${err.message}`);
411
+ }
412
+ let data;
413
+ try {
414
+ data = JSON.parse(raw);
415
+ } catch (err) {
416
+ throw new Error(`loadExposeStore: config at "${filePath}" is not valid JSON: ${err.message}`);
417
+ }
418
+ return new ExposeStore({ filePath, data });
419
+ }
420
+
421
+ module.exports = {
422
+ ExposeStore,
423
+ loadExposeStore,
424
+ // exported for unit tests / the aggregator
425
+ atomicWriteJson,
426
+ normaliseUpstream,
427
+ normaliseExpose,
428
+ validateUpstream,
429
+ VALID_TRANSPORTS,
430
+ };
@@ -0,0 +1,194 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * gated-run.js — the SAFETY CRUX of the gateway.
5
+ *
6
+ * Contract: the architecture contract §2 (the `toolfunnel_run_tool` path) and §9 (the tested invariant).
7
+ * Hook contract: HOOK_ENGINE.md §1 (PreToolUse can block, PostToolUse cannot un-run) and §6
8
+ * (HookEngine.fire returns { injected, blocked, reason, stopLoop, results }; the engine has
9
+ * ALREADY normalised exit-2 / hookSpecificOutput.permissionDecision:"deny" into { blocked, reason }).
10
+ *
11
+ * This is the single place where "run a tool" becomes "fire PreToolUse → maybe execute →
12
+ * fire PostToolUse". Every powerful run-path (toolfunnel_run_tool, registry.run) funnels through here so
13
+ * the gate is impossible to bypass. The LOAD-BEARING INVARIANT, proven by test:
14
+ *
15
+ * A PreToolUse deny MUST prevent execute() from ever being called.
16
+ *
17
+ * Design rules:
18
+ * - PURE: `engine` and `execute` are INJECTED. No transport, no SDK, no host, no fs.
19
+ * Unit-testable under `node --test` with a fake engine + a spy execute().
20
+ * - NEVER throws out of gatedRun. A thrown execute() is captured as { ok:false, error }.
21
+ * A misbehaving engine.fire() (rejection or junk return) is treated conservatively.
22
+ * - PostToolUse is advisory (HOOK_ENGINE.md §1: a PostToolUse block cannot un-run the tool),
23
+ * so we fire it for feedback but never let it flip ok→false or throw the path.
24
+ *
25
+ * Return shape (always one of these, never an exception):
26
+ * blocked by PreToolUse : { ok:false, blocked:true, reason, output:null }
27
+ * execute threw : { ok:false, blocked:false, error, output:null }
28
+ * success : { ok:true, blocked:false, output }
29
+ *
30
+ * CommonJS only. Node built-ins only. No new dependencies.
31
+ */
32
+
33
+ // Activity log. Self-gating (no-op unless explicitly enabled) and contracted never to
34
+ // throw, so wiring it here cannot alter gate behaviour or break the run path.
35
+ const logger = require('../core/logger');
36
+
37
+ const EVENTS = {
38
+ PRE: 'PreToolUse',
39
+ POST: 'PostToolUse',
40
+ };
41
+
42
+ /**
43
+ * Fire one lifecycle event through the injected engine, defensively.
44
+ *
45
+ * The HookEngine contract (HOOK_ENGINE.md §6) says fire() never rejects, but gatedRun is the
46
+ * safety crux: we must not assume a perfectly-behaved engine. If fire() rejects or returns a
47
+ * non-object, we fail CLOSED on the gate (PreToolUse) — an engine we cannot trust to answer
48
+ * "allowed?" must not be read as "allowed". PostToolUse is advisory, so a failure there is benign.
49
+ *
50
+ * @param {object} engine an object exposing async fire(event, ctx, extra)
51
+ * @param {string} event one of EVENTS
52
+ * @param {object} ctx common hook context (session_id, transcript_path, cwd, …)
53
+ * @param {object} extra event-specific fields (per HOOK_ENGINE.md §2 table)
54
+ * @returns {Promise<{ injected:string, blocked:boolean, reason:(string|null),
55
+ * stopLoop:boolean, results:object[] }>}
56
+ */
57
+ async function fireSafely(engine, event, ctx, extra) {
58
+ try {
59
+ const res = await engine.fire(event, ctx, extra);
60
+ // The engine already normalises blocking to { blocked, reason }. Defensively coerce a
61
+ // junk/undefined return into a well-shaped result so callers can read fields safely.
62
+ if (res && typeof res === 'object') {
63
+ return {
64
+ injected: typeof res.injected === 'string' ? res.injected : '',
65
+ blocked: res.blocked === true,
66
+ reason: res.reason != null ? res.reason : null,
67
+ stopLoop: res.stopLoop === true,
68
+ results: Array.isArray(res.results) ? res.results : [],
69
+ };
70
+ }
71
+ // Non-object return from fire(): per-event. PreToolUse fails CLOSED — a gate that
72
+ // returns junk cannot be read as "allowed". PostToolUse is advisory → benign.
73
+ if (event === EVENTS.PRE) {
74
+ return {
75
+ injected: '',
76
+ blocked: true,
77
+ reason: 'hook engine returned a non-object for ' + event + ' — failing closed',
78
+ stopLoop: false,
79
+ results: [],
80
+ };
81
+ }
82
+ return { injected: '', blocked: false, reason: null, stopLoop: false, results: [] };
83
+ } catch (err) {
84
+ // fire() should never reject; if it does, fail closed on the GATE and benign on POST.
85
+ const reason =
86
+ 'hook engine error during ' + event + ': ' + ((err && err.message) || String(err));
87
+ if (event === EVENTS.PRE) {
88
+ // Fail CLOSED: an engine that cannot answer the gate denies the run.
89
+ return { injected: '', blocked: true, reason, stopLoop: false, results: [] };
90
+ }
91
+ // PostToolUse is advisory and cannot un-run the tool — a failure here is benign.
92
+ return { injected: '', blocked: false, reason: null, stopLoop: false, results: [] };
93
+ }
94
+ }
95
+
96
+ /**
97
+ * gatedRun — route a single tool invocation through the host's hook engine.
98
+ *
99
+ * Sequence (the architecture contract §2):
100
+ * 1. fire PreToolUse with { tool_name, tool_input: args }.
101
+ * 2. if blocked → return { ok:false, blocked:true, reason, output:null } and DO NOT call execute.
102
+ * 3. else await execute(); on throw, capture as error (output stays null).
103
+ * 4. fire PostToolUse with { tool_name, tool_input: args, tool_response: output }.
104
+ * (PostToolUse is advisory — fired for feedback even on the error path so PostToolUse hooks
105
+ * observe what happened; it never flips ok or throws.)
106
+ * 5. return { ok:true, blocked:false, output } | { ok:false, blocked:false, error, output:null }.
107
+ *
108
+ * @param {object} params
109
+ * @param {object} params.engine the host's HookEngine — async fire(event, ctx, extra). INJECTED.
110
+ * @param {object} [params.ctx] common hook context (session_id, transcript_path, cwd, …).
111
+ * @param {string} params.toolName the tool name (becomes tool_name in the payload).
112
+ * @param {*} [params.args] the tool input (becomes tool_input in the payload).
113
+ * @param {Function} params.execute thunk that performs the actual call (from
114
+ * registry.resolveExecution). `() => any | Promise<any>`. INJECTED.
115
+ * @returns {Promise<{ ok:boolean, blocked:boolean, reason?:(string|null),
116
+ * output:(*|null), error?:Error }>}
117
+ */
118
+ async function gatedRun(params) {
119
+ const p = params || {};
120
+ const { engine, ctx, toolName, args, execute } = p;
121
+
122
+ // ---- Validate injected dependencies, failing CLOSED (never execute on a bad wiring). ----
123
+ if (!engine || typeof engine.fire !== 'function') {
124
+ return {
125
+ ok: false,
126
+ blocked: true,
127
+ reason: 'gatedRun: engine with async fire() is required',
128
+ output: null,
129
+ };
130
+ }
131
+ if (typeof execute !== 'function') {
132
+ return {
133
+ ok: false,
134
+ blocked: true,
135
+ reason: 'gatedRun: execute thunk (function) is required',
136
+ output: null,
137
+ };
138
+ }
139
+
140
+ const context = ctx || {};
141
+
142
+ // ---- 1. PreToolUse gate. -------------------------------------------------------------
143
+ // tool_input carries the args verbatim (per HOOK_ENGINE.md §2 PreToolUse row).
144
+ const pre = await fireSafely(engine, EVENTS.PRE, context, {
145
+ tool_name: toolName,
146
+ tool_input: args,
147
+ });
148
+
149
+ // ---- Activity log: record the gate decision (allow|deny). Self-gates on enabled;
150
+ // never throws. Placed before the blocked-return so BOTH outcomes are logged. ---
151
+ logger.log({
152
+ type: 'gate',
153
+ tool: toolName,
154
+ decision: pre.blocked ? 'deny' : 'allow',
155
+ reason: pre.reason,
156
+ });
157
+
158
+ // ---- 2. Blocked → STOP. The load-bearing invariant: execute() is NOT called. ---------
159
+ if (pre.blocked) {
160
+ return {
161
+ ok: false,
162
+ blocked: true,
163
+ reason: pre.reason,
164
+ output: null,
165
+ };
166
+ }
167
+
168
+ // ---- 3. Allowed → execute the real call. Capture a throw as `error`. -----------------
169
+ let output = null;
170
+ let error = null;
171
+ try {
172
+ output = await execute();
173
+ } catch (err) {
174
+ // Normalise any thrown value into an Error so the caller always gets an Error instance.
175
+ error = err instanceof Error ? err : new Error(String(err));
176
+ }
177
+
178
+ // ---- 4. PostToolUse (advisory). Fired even on the error path so hooks see the outcome. -
179
+ // tool_response is the output (null when execute threw). PostToolUse cannot un-run the tool
180
+ // (HOOK_ENGINE.md §1), so its result never flips ok and never throws this path.
181
+ await fireSafely(engine, EVENTS.POST, context, {
182
+ tool_name: toolName,
183
+ tool_input: args,
184
+ tool_response: output,
185
+ });
186
+
187
+ // ---- 5. Final result. ----------------------------------------------------------------
188
+ if (error) {
189
+ return { ok: false, blocked: false, error, output: null };
190
+ }
191
+ return { ok: true, blocked: false, output };
192
+ }
193
+
194
+ module.exports = { gatedRun, EVENTS };