@matatbread/matbot-tool-types 0.4.18 → 0.4.21

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.
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "matbotRuntime": [
4
4
  "node"
5
5
  ],
6
- "version": "0.4.18",
6
+ "version": "0.4.21",
7
7
  "engines": {
8
8
  "node": ">=24.0.0"
9
9
  },
@@ -33,17 +33,17 @@
33
33
  "access": "public"
34
34
  },
35
35
  "dependencies": {
36
+ "@types/node": "^22.0.0",
36
37
  "typescript": "^6.0.3"
37
38
  },
38
39
  "peerDependencies": {
39
- "@matatbread/matbot-plugin-api": "^0.4.18",
40
- "@matatbread/matbot-core": "^0.4.18"
40
+ "@matatbread/matbot-plugin-api": "^0.4.21",
41
+ "@matatbread/matbot-core": "^0.4.21"
41
42
  },
42
43
  "devDependencies": {
43
- "@types/node": "^22.0.0",
44
44
  "typescript": "^6.0.3",
45
- "@matatbread/matbot-plugin-api": "^0.4.18",
46
- "@matatbread/matbot-core": "^0.4.18"
45
+ "@matatbread/matbot-plugin-api": "^0.4.21",
46
+ "@matatbread/matbot-core": "^0.4.21"
47
47
  },
48
48
  "scripts": {
49
49
  "typecheck": "tsc --noEmit"
package/src/build-dts.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  import type TS from 'typescript';
2
+ import type { Runtime } from '@matatbread/matbot-plugin-api';
3
+ import { contractArms } from '@matatbread/matbot-plugin-api';
2
4
  import { compileToolValidator, generateValidator, type ToolValidator, type ValidatorSource } from './validator.js';
3
5
 
4
6
  // Derive a self-contained `declare module … { interface ToolContracts {…} interface MatbotServices {…} }`
@@ -76,6 +78,9 @@ export interface MatbotToolsDts {
76
78
  * build read. Serialisable by construction, so a build can be kept beyond the process that made it; what
77
79
  * it depends on is exactly its arguments, tool-types itself, and the content of `files`.
78
80
  */
81
+ /** A tool's `toolContract` string, with the declarations of its own it names (`toolContractTypes`). */
82
+ export interface SyntheticContract { contract: string; types?: string }
83
+
79
84
  export interface ToolTypesData extends Omit<MatbotToolsDts, 'validators'> {
80
85
  validators: Record<string, ValidatorSource>;
81
86
  /** `dts` in pieces, one per tool, so {@link filterToolTypesData} can narrow it without a rebuild. */
@@ -111,7 +116,7 @@ export interface ToolTypeRoots {
111
116
  /** What a build of `pluginEntryUrls` would scan, without building it. Null when there is nothing to scan
112
117
  * beyond plugin-api, or plugin-api itself cannot be found. */
113
118
  export async function collectToolTypeRoots(
114
- projectRoot: string, pluginEntryUrls?: readonly string[],
119
+ projectRoot: string, pluginEntryUrls?: readonly string[], runtime: Runtime = 'node',
115
120
  ): Promise<ToolTypeRoots | null> {
116
121
  const { readFileSync, readdirSync, statSync, existsSync } = await import('node:fs');
117
122
  const { join } = await import('node:path');
@@ -163,6 +168,14 @@ export async function collectToolTypeRoots(
163
168
  // `plugins/bash` and `plugins/docker-bash` — still merges by Program file order, so the unloaded one can
164
169
  // win and describe the loaded one; that is what `conflicts` makes audible, and it cannot be filtered away
165
170
  // because the name IS live.
171
+ //
172
+ // Plugins for another runtime are the exception: those are skipped, by the loader's own pre-import rule
173
+ // (a package whose `matbotRuntime` is present, non-empty and excludes `runtime`). `liveToolNames` cannot
174
+ // stand in for that, because a static caller has no live set — a typed client generated at build time —
175
+ // and an augmentation of a shared shape (google-drive's `managedBy` on `LoadedPluginSummary`) is
176
+ // no tool name to filter. `runtime` is the runtime being DESCRIBED, not the one this runs on: the web
177
+ // bundle's build runs here to describe a browser. The resolvedUrl roots need no such rule; the loader
178
+ // has already gated them.
166
179
  // Generated `matbot-tools.d.ts` files are skipped (don't feed prior output back in).
167
180
  if (existsSync(join(projectRoot, 'plugins'))) {
168
181
  // Dot-directories wholesale rather than by name: this used to list `compiled-plugins` explicitly,
@@ -171,16 +184,24 @@ export async function collectToolTypeRoots(
171
184
  // A source tree keeps no augmentations under a dot-directory; `.git`, `.plugins` and a build root
172
185
  // sited there are all covered by one rule that cannot go stale.
173
186
  const SKIP = new Set(['node_modules', 'dist']);
174
- const walk = (dir: string): void => {
187
+ // A directory with no package.json inherits its parent's answer, so each file is judged by its
188
+ // nearest package. Nothing is pruned: a package nested inside an excluded one answers for itself.
189
+ const admits = (dir: string, inherited: boolean): boolean => {
190
+ let declared: unknown;
191
+ try { declared = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')).matbotRuntime; } catch { return inherited; }
192
+ return !Array.isArray(declared) || declared.length === 0 || declared.includes(runtime);
193
+ };
194
+ const walk = (dir: string, inherited: boolean): void => {
175
195
  let entries: string[];
176
196
  try { entries = readdirSync(dir); } catch { return; }
197
+ const admitted = admits(dir, inherited);
177
198
  for (const name of entries) {
178
199
  if (SKIP.has(name) || name.startsWith('.')) continue;
179
200
  const p = join(dir, name);
180
201
  let isDir: boolean;
181
202
  try { isDir = statSync(p).isDirectory(); } catch { continue; }
182
- if (isDir) { walk(p); continue; }
183
- if (!name.endsWith('.ts') || name.endsWith('matbot-tools.d.ts')) continue;
203
+ if (isDir) { walk(p, admitted); continue; }
204
+ if (!admitted || !name.endsWith('.ts') || name.endsWith('matbot-tools.d.ts')) continue;
184
205
  const src = readFileSync(p, 'utf8');
185
206
  // Any augmentation of plugin-api, not just one naming `ToolContracts`/`MatbotServices`. Those two
186
207
  // are the interfaces EMITTED, but they are not the only ones that change what they mean: a tool
@@ -191,7 +212,7 @@ export async function collectToolTypeRoots(
191
212
  if (/declare\s+module\s+['"]@matatbread\/matbot-plugin-api['"]/.test(src)) roots.add(p);
192
213
  }
193
214
  };
194
- walk(join(projectRoot, 'plugins'));
215
+ walk(join(projectRoot, 'plugins'), true);
195
216
  }
196
217
  if (roots.size === 1) return null; // nothing to scan beyond plugin-api itself
197
218
  return { pluginApiIndex, roots: [...roots] };
@@ -222,11 +243,11 @@ export async function collectToolTypeRoots(
222
243
  // deliberately — for no gain. So this argument buys exactly one thing: the validators.
223
244
  export async function buildToolTypesData(
224
245
  projectRoot: string, pluginEntryUrls?: readonly string[], liveToolNames?: readonly string[],
225
- syntheticContracts?: Readonly<Record<string, string>>,
246
+ syntheticContracts?: Readonly<Record<string, SyntheticContract>>, runtime: Runtime = 'node',
226
247
  ): Promise<ToolTypesData | null> {
227
248
  const ts = (await import('typescript')).default as typeof TS;
228
249
  const { join } = await import('node:path');
229
- const found = await collectToolTypeRoots(projectRoot, pluginEntryUrls);
250
+ const found = await collectToolTypeRoots(projectRoot, pluginEntryUrls, runtime);
230
251
  if (!found) return null;
231
252
  const { pluginApiIndex, roots } = found;
232
253
 
@@ -253,6 +274,14 @@ export async function buildToolTypesData(
253
274
  const TYPE_FLAGS = ts.SymbolFlags.Type | ts.SymbolFlags.Interface | ts.SymbolFlags.TypeAlias;
254
275
  const apiTypeNames = new Set(apiExports.filter(s => (s.flags & TYPE_FLAGS) !== 0).map(s => s.name));
255
276
 
277
+ // The namespace of contract types (see `contractArms`) that a diagnostic at `at` sits inside, as the tools it serves.
278
+ const namespaceServing = (sf: TS.SourceFile, at: number, namespaces: ReadonlyMap<string, readonly string[]>): readonly string[] | undefined => {
279
+ for (const st of sf.statements) {
280
+ if (ts.isModuleDeclaration(st) && at >= st.getStart() && at < st.getEnd()) return namespaces.get(st.name.getText());
281
+ }
282
+ return undefined;
283
+ };
284
+
256
285
  /**
257
286
  * Validators for the tools whose contract is a `toolContract` STRING. The emitter needs a `ts.Type`,
258
287
  * and a string is not one, so the strings are rendered into a virtual augmentation file and typed.
@@ -271,28 +300,31 @@ export async function buildToolTypesData(
271
300
  */
272
301
  const syntheticValidators = (): Record<string, ValidatorSource> => {
273
302
  const out: Record<string, ValidatorSource> = {};
274
- const usable: Record<string, string> = {};
303
+ const usable: Record<string, SyntheticContract> = {};
275
304
 
276
305
  // Screened one at a time, BEFORE any is rendered into the shared file: they become properties of one
277
306
  // interface, where a single stray brace would swallow every arm after it and take the whole batch
278
307
  // down. A malformed string is a stated refusal rather than a silent absence — nothing else in the
279
308
  // system parses these, so until now a broken one was merely bad documentation.
280
- for (const [name, text] of Object.entries(syntheticContracts ?? {})) {
281
- const probe = ts.createSourceFile('/probe.ts', `type __P = ${text};\n`, ts.ScriptTarget.ES2022, true);
309
+ for (const [name, c] of Object.entries(syntheticContracts ?? {})) {
310
+ const probe = ts.createSourceFile('/probe.ts',
311
+ `type __P = ${c.contract};\n${c.types !== undefined ? `declare namespace __N {\n${c.types}\n}\n` : ''}`, ts.ScriptTarget.ES2022, true);
282
312
  const bad = (probe as unknown as { parseDiagnostics?: readonly TS.Diagnostic[] }).parseDiagnostics ?? [];
283
313
  if (bad.length > 0) {
284
314
  out[name] = { refused: `toolContract does not parse as a type: ${ts.flattenDiagnosticMessageText(bad[0]!.messageText, ' ')}` };
285
- } else out[name] = (usable[name] = text, { refused: 'not resolved' }); // replaced below, or kept as the refusal
315
+ } else out[name] = (usable[name] = c, { refused: 'not resolved' }); // replaced below, or kept as the refusal
286
316
  }
287
317
  const names = Object.keys(usable);
288
318
  if (names.length === 0) return out;
289
319
 
290
- const body = names.map(n => ` ${JSON.stringify(n)}: ${usable[n]!};`).join('\n');
320
+ // A contract naming types of its own gets them in a namespace beside it, and its arm is the alias there.
321
+ const { preamble, arms, namespaces } = contractArms(names.map(n => ({ name: n, contract: usable[n]!.contract, types: usable[n]!.types })));
322
+ const body = names.map(n => ` ${JSON.stringify(n)}: ${arms.get(n)!};`).join('\n');
291
323
  // Exactly the plugin-api types these arms name, from the resolved export set — the same rule
292
- // `registryBlock` uses for the dts. A synthetic tool inlines its own shape types, so what is left is
293
- // genuine plugin-api exports.
294
- const referenced = ['ToolContract', ...[...apiTypeNames].filter(t => new RegExp(`\\b${t}\\b`).test(body))];
295
- const src = `import type { ${[...new Set(referenced)].join(', ')} } from '@matatbread/matbot-plugin-api';\n`
324
+ // `registryBlock` uses for the dts. What a contract declares itself is in the preamble, so what is left
325
+ // is genuine plugin-api exports.
326
+ const referenced = ['ToolContract', ...[...apiTypeNames].filter(t => new RegExp(`\\b${t}\\b`).test(preamble + body))];
327
+ const src = `import type { ${[...new Set(referenced)].join(', ')} } from '@matatbread/matbot-plugin-api';\n${preamble}`
296
328
  + `declare module '@matatbread/matbot-plugin-api' {\n interface ToolContracts {\n${body}\n }\n}\n`;
297
329
 
298
330
  const virtualPath = join(projectRoot, '__matbot_synthetic_contracts__.ts');
@@ -335,11 +367,20 @@ export async function buildToolTypesData(
335
367
  ? (ts.isStringLiteral(n.name) || ts.isIdentifier(n.name) ? n.name.text : undefined)
336
368
  : undefined;
337
369
  const msg = ts.flattenDiagnosticMessageText(d.messageText, ' ');
338
- if (name !== undefined) broken.set(name, msg);
370
+ // Inside a namespace of contract types, it is the fault of the tools that namespace serves, and theirs
371
+ // only. Asked first: a property signature found in there belongs to a declared interface, not to an arm.
372
+ const served = namespaceServing(sf, d.start, namespaces);
373
+ if (served !== undefined) for (const k of served) broken.set(k, msg);
374
+ else if (name !== undefined) broken.set(name, msg);
339
375
  // A file-level diagnostic (a failed import) cannot be attributed to one arm, so it condemns them all.
340
376
  else for (const k of names) broken.set(k, msg);
341
377
  }
342
378
 
379
+ const aliasedContract = (node: TS.TypeNode): TS.TypeNode | undefined => {
380
+ if (!ts.isTypeReferenceNode(node) || !ts.isQualifiedName(node.typeName) || !namespaces.has(node.typeName.left.getText())) return undefined;
381
+ return chk.getSymbolAtLocation(node.typeName.right)?.declarations?.find(ts.isTypeAliasDeclaration)?.type;
382
+ };
383
+
343
384
  // Read the arms off the virtual file's own declarations rather than the merged ToolContracts symbol:
344
385
  // this Program has no scanned arms to merge, and going via the file keeps each tool's node in hand.
345
386
  const walk = (n: TS.Node): void => {
@@ -352,7 +393,8 @@ export async function buildToolTypesData(
352
393
  out[name] = { refused: `toolContract does not typecheck: ${fault}` };
353
394
  return;
354
395
  }
355
- const ann = n.type;
396
+ // An arm that names a contract-types alias is read through to the contract written there.
397
+ const ann = aliasedContract(n.type) ?? n.type;
356
398
  const arms = ts.isUnionTypeNode(ann) ? [...ann.types] : [ann];
357
399
  const paramNodes: TS.TypeNode[] = [];
358
400
  let ok = true;
@@ -601,8 +643,8 @@ export async function buildToolTypesData(
601
643
  // `getPreEmitDiagnostics`, which costs ~4x this whole build (measured: +750ms on a 40-root scan) and
602
644
  // says less: a raw TS2717 filter reports only the losing site, whereas the merged symbol's
603
645
  // declaration list names the winner too — and it can't distinguish a real clash from the legal
604
- // identical re-declaration TypeScript never complains about (`bash`, `mcp_action` and
605
- // `url_for_resource` are each declared twice here, identically, and are not conflicts).
646
+ // identical re-declaration TypeScript never complains about (`bash` and `mcp_action` are each declared
647
+ // twice here, identically, and are not conflicts; so is `url_for_resource` in a browser build).
606
648
  const relPath = (f: string): string => f.startsWith(projectRoot) ? f.slice(projectRoot.length + 1) : f;
607
649
  const siteOf = (d: TS.Node): string =>
608
650
  `${relPath(d.getSourceFile().fileName)}:${d.getSourceFile().getLineAndCharacterOfPosition(d.getStart()).line + 1}`;
@@ -841,9 +883,9 @@ export function filterToolTypesData(data: ToolTypesData, liveToolNames: readonly
841
883
  /** {@link buildToolTypesData}, with every validator compiled — the in-process form. */
842
884
  export async function buildMatbotToolsDts(
843
885
  projectRoot: string, pluginEntryUrls?: readonly string[], liveToolNames?: readonly string[],
844
- syntheticContracts?: Readonly<Record<string, string>>,
886
+ syntheticContracts?: Readonly<Record<string, SyntheticContract>>, runtime: Runtime = 'node',
845
887
  ): Promise<MatbotToolsDts | null> {
846
- const data = await buildToolTypesData(projectRoot, pluginEntryUrls, liveToolNames, syntheticContracts);
888
+ const data = await buildToolTypesData(projectRoot, pluginEntryUrls, liveToolNames, syntheticContracts, runtime);
847
889
  if (!data) return null;
848
890
  const { files: _files, dtsParts: _parts, validators, ...rest } = data;
849
891
  return { ...rest, validators: compileToolValidators(validators) };
package/src/checker.ts CHANGED
@@ -23,14 +23,21 @@ interface DiagnosticRecord {
23
23
  frame?: string;
24
24
  sourceLine?: string;
25
25
  related?: string[];
26
- /** True for a cast-gate finding (a structural rule, not a tsc error) — labelled CAST-GATE, not TSnnnn. */
26
+ /** True for a structural-rule finding (not a tsc error) — labelled by {@link SYN_LABELS}, not TSnnnn. */
27
27
  syn?: boolean;
28
28
  }
29
29
 
30
30
  // Hints keyed on error code plus (optionally) a pattern over the offending source line or message —
31
31
  // the pattern is what makes them directed rather than generic. Kept few and high-confidence: a wrong
32
32
  // hint is worse than none.
33
- const HINTS: { codes: number[]; pattern?: RegExp; hint: string }[] = [
33
+ //
34
+ // `only` is which entry MODE an entry is true in, and it is load-bearing rather than tidy. A compiled
35
+ // plugin is a module: it has a top of file to add an import to, `@matatbread/matbot-plugin-api` is a real
36
+ // dependency of its build dir, and nothing else is importable. A `tool_function` body is
37
+ // `async function __fn(…) { … }`: no top of file, no static imports, and a different importable set
38
+ // entirely — whatever this installation permits. These were written for the first and fired in both, so
39
+ // a body that mistyped `node:fs` was told there are no modules here.
40
+ const HINTS: { codes: number[]; pattern?: RegExp; only?: 'project' | 'snippet'; hint: string }[] = [
34
41
  {
35
42
  codes: [2739, 2322],
36
43
  pattern: /ReturnType\s*<\s*typeof\s+tool\./,
@@ -50,6 +57,11 @@ const HINTS: { codes: number[]; pattern?: RegExp; hint: string }[] = [
50
57
  pattern: /\| undefined' is not assignable/,
51
58
  hint: 'the value may be undefined — often an indexed access (array[i], record[key]) under noUncheckedIndexedAccess. Guard it (if (v !== undefined) …) rather than asserting.',
52
59
  },
60
+ {
61
+ codes: [90003],
62
+ pattern: /Object\.(?:keys|values|entries|assign)\s*\(/,
63
+ hint: "Object.keys/values/entries already accept a precisely-typed object — drop the cast and pass the value itself. (If you wanted the key names as a type, that is `keyof typeof x`.)",
64
+ },
53
65
  {
54
66
  codes: [1484, 1485],
55
67
  hint: 'verbatimModuleSyntax: types must be imported with `import type { … }`; values with a plain `import`.',
@@ -60,23 +72,37 @@ const HINTS: { codes: number[]; pattern?: RegExp; hint: string }[] = [
60
72
  },
61
73
  {
62
74
  codes: [2307],
75
+ only: 'project',
63
76
  hint: "only '@matatbread/matbot-plugin-api' is importable here; there are no other modules.",
64
77
  },
78
+ {
79
+ codes: [2307],
80
+ only: 'snippet',
81
+ // No list: the declarations above already carry one, derived from the same permitted set, and a
82
+ // second copy here would be the thing that goes stale. What this adds is WHY a specifier can be
83
+ // absent, since "not permitted" and "has no declarations" are repaired differently.
84
+ hint: 'this module is not typed here. The comment block at the top of these declarations says what this installation permits; a node builtin has real types (either spelling: `node:os` or `os`), while a bare package or an http(s) URL has none, and importing one of those needs noTypeCheck.',
85
+ },
65
86
  {
66
87
  codes: [2305],
88
+ only: 'project',
67
89
  pattern: /@matatbread\/matbot-plugin-api/,
68
90
  hint: 'the package exports only the plugin API surface (ToolContract, ToolResultOf, ToolExecutor, ToolEvent, ToolContext, MatbotPluginSpec, MatbotMachine, makeToolBox, PLUGIN_API_VERSION). Types that appear inside tool contracts (SkillSummary, Trigger, …) are ambient in the tool dts and must NOT be imported — remove them from the import list and let inference carry the values (const r = await tool.x(...)), or inline the structural shape where you need a name.',
69
91
  },
70
92
  {
71
93
  codes: [2304, 2552],
94
+ only: 'project',
72
95
  pattern: /\b(ToolContract|ToolResultOf|ToolExecutor|ToolEvent|ToolContext|MatbotPluginSpec|MatbotMachine|makeToolBox|PLUGIN_API_VERSION)\b/,
73
96
  hint: "this name IS a real export of '@matatbread/matbot-plugin-api' — add it to the `import`/`import type { … }` list at the top of the file. Ignore any \"Did you mean\" suggestion pointing at a different name.",
74
97
  },
75
98
  ];
76
99
 
77
- function hintFor(d: DiagnosticRecord): string | undefined {
100
+ type Mode = 'project' | 'snippet';
101
+
102
+ function hintFor(d: DiagnosticRecord, mode: Mode): string | undefined {
78
103
  for (const h of HINTS) {
79
104
  if (!h.codes.includes(d.code)) continue;
105
+ if (h.only !== undefined && h.only !== mode) continue;
80
106
  if (h.pattern && !h.pattern.test(d.sourceLine ?? '') && !h.pattern.test(d.message)) continue;
81
107
  return h.hint;
82
108
  }
@@ -85,19 +111,24 @@ function hintFor(d: DiagnosticRecord): string | undefined {
85
111
 
86
112
  const MAX_FULL = 8;
87
113
 
114
+ // A structural rule's label, by its private code. CAST-GATE is the default because it was the first and
115
+ // is what the contract gate (90004) has always reported as; a rule about something other than types
116
+ // needs its own name, or the label says the wrong thing about the finding under it.
117
+ const SYN_LABELS: Record<number, string> = { 90005: 'ENV-GATE', 90006: 'IMPORT-GATE' };
118
+
88
119
  // One rule, one name, in every renderer: a per-rule label read off the record rather than spelled at
89
120
  // each render site, so a summary can never call a finding something its own entry did not.
90
121
  function label(d: DiagnosticRecord): string {
91
- return d.syn ? 'CAST-GATE' : `TS${d.code}`;
122
+ return d.syn ? (SYN_LABELS[d.code] ?? 'CAST-GATE') : `TS${d.code}`;
92
123
  }
93
124
 
94
- function formatOne(d: DiagnosticRecord): string {
125
+ function formatOne(d: DiagnosticRecord, mode: Mode): string {
95
126
  const loc = d.file !== undefined ? `${d.file}(${d.line},${d.col})`
96
127
  : d.line !== undefined ? `line ${d.line}` : '(project)';
97
128
  const parts = [`${loc} ${label(d)}: ${d.message}`];
98
129
  if (d.frame !== undefined) parts.push(d.frame);
99
130
  if (d.related) for (const r of d.related) parts.push(` related: ${r}`);
100
- const hint = hintFor(d);
131
+ const hint = hintFor(d, mode);
101
132
  if (hint !== undefined) parts.push(` HINT: ${hint}`);
102
133
  return parts.join('\n');
103
134
  }
@@ -121,7 +152,7 @@ function omittedOf(diags: DiagnosticRecord[]): { count: number; byLabel: Record<
121
152
  * The typed record existed upstream all along and was discarded at render time; it is kept now, and the
122
153
  * text is one field of it.
123
154
  */
124
- function reportOf(diags: DiagnosticRecord[]): ToolCheckReport {
155
+ function reportOf(diags: DiagnosticRecord[], mode: Mode): ToolCheckReport {
125
156
  const omitted = omittedOf(diags);
126
157
  const detailed: ToolCheckDiagnostic[] = diags.slice(0, MAX_FULL).map(d => ({
127
158
  label: label(d),
@@ -132,9 +163,9 @@ function reportOf(diags: DiagnosticRecord[]): ToolCheckReport {
132
163
  ...(d.col !== undefined ? { col: d.col } : {}),
133
164
  ...(d.frame !== undefined ? { frame: d.frame } : {}),
134
165
  ...(d.related !== undefined ? { related: d.related } : {}),
135
- ...(hintFor(d) !== undefined ? { hint: hintFor(d)! } : {}),
166
+ ...(hintFor(d, mode) !== undefined ? { hint: hintFor(d, mode)! } : {}),
136
167
  ...(d.syn === true ? { syn: true as const } : {}),
137
- rendered: formatOne(d),
168
+ rendered: formatOne(d, mode),
138
169
  }));
139
170
  return {
140
171
  ok: diags.length === 0,
@@ -151,7 +182,16 @@ async function runWorker(data: Record<string, unknown>): Promise<DiagnosticRecor
151
182
  const typescriptPath = createRequire(import.meta.url).resolve('typescript');
152
183
 
153
184
  const result = await new Promise<{ ok?: boolean; diagnostics?: DiagnosticRecord[]; error?: string }>((resolve, reject) => {
154
- const w = new Worker(TS_WORKER_JS, { eval: true, workerData: { ...data, typescriptPath } });
185
+ // Parsed AS TypeScript, never left to node to guess: without the flag eval'd code runs as JS and is
186
+ // retried as TS only if it fails to parse, and `new Set<string>(x)` parses fine as two comparisons —
187
+ // so it would have thrown `string is not defined` but for an unrelated annotation elsewhere in the
188
+ // source happening to be a JS syntax error. It REPLACES the inherited flags rather than adding to
189
+ // them: node refuses process-wide ones in a worker's execArgv (the test runner passes several), and
190
+ // the worker needs none of them — it loads no hooks, by design.
191
+ const w = new Worker(TS_WORKER_JS, {
192
+ eval: true, workerData: { ...data, typescriptPath },
193
+ execArgv: ['--input-type=commonjs-typescript'],
194
+ });
155
195
  const timer = setTimeout(() => { void w.terminate(); reject(new Error('typecheck worker timed out')); }, 120_000);
156
196
  w.once('message', m => { clearTimeout(timer); resolve(m as never); void w.terminate(); });
157
197
  w.once('error', e => { clearTimeout(timer); reject(e); });
@@ -179,7 +219,7 @@ export async function checkProjectDir(
179
219
  ...(opts?.ownContracts !== undefined ? { ownContracts: [...opts.ownContracts] } : {}),
180
220
  });
181
221
  if (diags === null) return { ok: true, output: '' };
182
- const report = reportOf(diags);
222
+ const report = reportOf(diags, 'project');
183
223
  const parts: string[] = [];
184
224
  if (report.total > 1) parts.push(`${report.total} errors. Fix the FIRST error first — later errors often cascade from it.\n`);
185
225
  for (const d of report.diagnostics) { parts.push(d.rendered); parts.push(''); }
@@ -196,6 +236,26 @@ export async function checkSnippetAgainst(opts: {
196
236
  prefixLen: number;
197
237
  prefixLines: number;
198
238
  apiIndexPath?: string;
239
+ /** `paths` entries for the module specifiers this installation permits a body to import — one per
240
+ * permitted module, so a module outside the set does not resolve and is a compile error rather than
241
+ * something that typechecks and is refused at run time. Built by the caller, which knows the set. */
242
+ importPaths?: Record<string, string[]>;
243
+ /** Declaration files for the globals a body HAS beyond the standard library, loaded as roots: on node,
244
+ * `Buffer`. Module types arrive only through {@link importPaths}, which load on an import, so a body
245
+ * using a node global without importing anything would otherwise fail on a name it really has. */
246
+ globalTypes?: readonly string[];
247
+ /** The restriction itself, when there is one — `paths` cannot enforce it. Loading ONE builtin's
248
+ * declaration file pulls in the ambient `declare module 'node:…'` blocks of everything its own
249
+ * declarations reference (`node:fs` reaches `node:stream`, which reaches most of the rest), so a
250
+ * forbidden specifier resolves anyway and typechecks clean. A literal `import('…')` is therefore
251
+ * checked STRUCTURALLY against this list, the way the cast gate and ENV-GATE close the other holes
252
+ * the type system cannot. Absent ⇒ unrestricted, and nothing is checked. */
253
+ permittedImports?: readonly string[];
254
+ /** The identifiers the RUNNER does not bind, from `FunctionRunner.withheldGlobals` — the list ENV-GATE
255
+ * rejects. It comes from the runner because a copy here could not be kept in step with it, and a name
256
+ * that is shadowed but not rejected typechecks and then fails at the first call. Absent ⇒ nothing is
257
+ * rejected: with no runner there is no claim about what a body does not have. */
258
+ withheldGlobals?: readonly string[];
199
259
  }): Promise<ToolCheckReport> {
200
260
  const diags = await runWorker({
201
261
  mode: 'snippet',
@@ -205,12 +265,19 @@ export async function checkSnippetAgainst(opts: {
205
265
  prefixLines: opts.prefixLines,
206
266
  virtualPath: `${opts.root}/__mb_toolcheck_${crypto.randomUUID()}.ts`,
207
267
  ...(opts.apiIndexPath !== undefined ? { apiIndexPath: opts.apiIndexPath } : {}),
268
+ ...(opts.importPaths !== undefined ? { importPaths: opts.importPaths } : {}),
269
+ ...(opts.globalTypes !== undefined ? { globalTypes: opts.globalTypes } : {}),
270
+ ...(opts.permittedImports !== undefined ? { permittedImports: opts.permittedImports } : {}),
271
+ ...(opts.withheldGlobals !== undefined ? { withheldGlobals: opts.withheldGlobals } : {}),
208
272
  });
209
- return reportOf(diags ?? []);
273
+ return reportOf(diags ?? [], 'snippet');
210
274
  }
211
275
 
212
- // The worker body: plain CommonJS (Worker eval mode is CJS, so `require` exists and no loader hooks
213
- // are needed — the host's .ts strip-hooks do not reliably reach worker threads). It loads the SAME
276
+ // The worker body: CommonJS (Worker eval mode is CJS, so `require` exists and no loader hooks are
277
+ // needed — the host's .ts strip-hooks do not reliably reach worker threads). Type annotations are
278
+ // fine here because the worker is started with `--input-type=commonjs-typescript`, so node strips them
279
+ // rather than guessing whether the source is TS (see runWorker). Anything beyond erasable syntax is not —
280
+ // no enums, no parameter properties. It loads the SAME
214
281
  // typescript module the main thread resolved and posts back JSON-safe records: flattened message
215
282
  // chains, related-information locations (e.g. which contract arm an expected type came from), and a
216
283
  // caret-anchored source frame per error. In snippet mode every position is remapped to be
@@ -255,7 +322,18 @@ try {
255
322
  target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.NodeNext, moduleResolution: ts.ModuleResolutionKind.NodeNext,
256
323
  strict: true, exactOptionalPropertyTypes: true, noEmit: true, skipLibCheck: true, baseUrl: baseDir,
257
324
  };
258
- if (workerData.apiIndexPath) options.paths = { '@matatbread/matbot-plugin-api': [workerData.apiIndexPath] };
325
+ // Module types come in through 'paths', one entry per PERMITTED specifier, never through
326
+ // types:['node'] — which is all-or-nothing (it makes every builtin resolve, so a module the install
327
+ // forbids typechecks clean and is refused only at run time) and pulls 168 files where this pulls 65.
328
+ // The plugin-api entry is needed in BOTH modes, and in snippet mode it is not about a body's imports
329
+ // at all: the generated declarations refer to their own types inline as
330
+ // import('@matatbread/matbot-plugin-api').ToolProxy, so without it every one of them collapses to any
331
+ // and bad snippets pass silently. That a BODY must not import the package is a separate fact,
332
+ // enforced structurally below — it cannot be expressed by withholding the resolution.
333
+ options.paths = {
334
+ ...(workerData.apiIndexPath ? { '@matatbread/matbot-plugin-api': [workerData.apiIndexPath] } : {}),
335
+ ...(workerData.importPaths ?? {}),
336
+ };
259
337
  const host = ts.createCompilerHost(options);
260
338
  const getSF = host.getSourceFile.bind(host);
261
339
  host.getSourceFile = function (f, lang, onErr, create) {
@@ -263,7 +341,7 @@ try {
263
341
  };
264
342
  const fe = host.fileExists.bind(host); host.fileExists = function (f) { return f === virtual || fe(f); };
265
343
  const rf = host.readFile.bind(host); host.readFile = function (f) { return f === virtual ? source : rf(f); };
266
- program = ts.createProgram([virtual], options, host);
344
+ program = ts.createProgram([virtual].concat(workerData.globalTypes ?? []), options, host);
267
345
  const sf = program.getSourceFile(virtual);
268
346
  targets = sf
269
347
  ? [].concat(program.getSyntacticDiagnostics(sf)).concat(program.getSemanticDiagnostics(sf))
@@ -322,6 +400,148 @@ try {
322
400
  ts.forEachChild(node, function (c) { contractVisit(c, sf); });
323
401
  };
324
402
 
403
+ // ── env gate: a global that TypeScript resolves but the runner does not define ──
404
+ // A tool_function body is compiled as a bare async function expression, not a module and not a CJS
405
+ // wrapper, so 'require', 'module', 'exports', '__dirname' and '__filename' are all undefined at
406
+ // runtime and 'import.meta' will not even compile. Loading node's types to check await import('node:…')
407
+ // declares every one of them as a global, which makes the commonest wrong guess — require('node:fs') —
408
+ // typecheck clean and fail at the first call: correct against the types it was shown, so the repair loop
409
+ // cannot repair it. Rejected structurally for the same reason a cast is, with the working form named.
410
+ // Only in snippet mode: a compiled plugin IS a module and legitimately has 'import.meta'.
411
+ //
412
+ // WHICH names are withheld comes from the runner's withheldGlobals, because it is the only thing that
413
+ // knows and a copy here could not be kept in step: a name shadowed but not rejected typechecks and
414
+ // fails at the first call, which is the one failure this gate exists to prevent. 'eval' and 'Function'
415
+ // are the worst to miss, being lib.es globals that typecheck in every configuration.
416
+ //
417
+ // The ADVICE stays here, because it is about repairing a snippet and that is this file's job, not the
418
+ // runner's. A withheld name with no entry below still fires, with a generic line — the list is the
419
+ // runner's to grow, and a new one must not pass silently for want of prose.
420
+ const ADVICE: Record<string, string> = {
421
+ require: "'require' is not defined in a function body — it is compiled as a bare async function, not a module. Use a dynamic import instead: 'const fs = await import('node:fs/promises')'.",
422
+ module: "'module' is not defined in a function body — it is compiled as a bare async function, not a CommonJS module. Return a value instead of assigning to an export.",
423
+ exports: "'exports' is not defined in a function body — it is compiled as a bare async function, not a CommonJS module. Return a value instead of assigning to an export.",
424
+ __dirname: "'__dirname' is not defined in a function body, and neither is 'process' — a body computes and calls tools, it does not navigate the filesystem by hand. 'context.workdir' is the directory a call was given, when it was given one.",
425
+ __filename: "'__filename' is not defined in a function body. There is no file — the body is compiled from source held in the session.",
426
+ process: "'process' is not defined in a function body — the runner withholds it, so there is no 'process.env', 'process.cwd()' or 'process.getBuiltinModule()'. A module comes from a gated 'await import('node:…')', and 'context.workdir' is the directory a call was given.",
427
+ globalThis: "'globalThis' is not defined in a function body — the runner withholds it, so a host global cannot be reached by name. Everything a body is given is already in scope: 'tool', 'toolInContext' and 'context'.",
428
+ global: "'global' is not defined in a function body — the runner withholds it, and it is node's older alias for 'globalThis', which is withheld too. Everything a body is given is already in scope: 'tool', 'toolInContext' and 'context'.",
429
+ eval: "'eval' is not defined in a function body — the runner withholds it. There is nothing to evaluate at run time: write the code, or call another tool with 'await tool.<name>(…)'.",
430
+ Function: "'Function' is not defined in a function body — the runner withholds the constructor, so 'new Function(…)' cannot build code at run time. Write the code directly. (As a TYPE annotation it is fine; this is about the value.)",
431
+ };
432
+ // A withheld global named in a TYPE is harmless: types are erased before the body is compiled, so
433
+ // 'args: Buffer' never reaches the runner. Only the VALUE is rejected. Needed because the second half of
434
+ // the list above — unlike 'require' and friends — are types as well as values.
435
+ const inTypePosition = function (node) {
436
+ for (let a = node.parent; a; a = a.parent) {
437
+ if (ts.isTypeNode(a)) return true;
438
+ if (ts.isBlock(a) || ts.isSourceFile(a)) return false;
439
+ }
440
+ return false;
441
+ };
442
+ const envGate = workerData.mode === 'snippet';
443
+ // Where the rule fired, so tsc's own 'Cannot find name' for the same identifier can be dropped: without
444
+ // node's types loaded both report, and two findings for one fix read as a cascade when the second says
445
+ // nothing the first did not — except which repair to make, which is the one this rule carries.
446
+ const envStarts = new Set();
447
+ // Declared by the author rather than inherited from node's globals: their own binding shadows it and
448
+ // works, so the rule must not fire. Decided on where the symbol's declaration IS, not on the parent
449
+ // node kind — that catches 'const require = …', a parameter and an import alias with one test.
450
+ const authorDeclared = function (node) {
451
+ const sym = checker.getSymbolAtLocation(node);
452
+ const decls = sym && sym.declarations;
453
+ if (!decls) return false;
454
+ return decls.some(function (d) {
455
+ return d.getSourceFile().fileName === virtual && d.getStart() >= minStart;
456
+ });
457
+ };
458
+ // The permit's boundary rule and the by-name rule, inlined: the worker is a CommonJS realm with no
459
+ // loader hooks, so it cannot import 'importPermitted' or 'importableByName' from plugin-api, which is
460
+ // where both rules live and are documented.
461
+ const byName = function (spec) {
462
+ return spec !== '' && !/[^\\w@.~+!$&'()*,;=:/-]/.test(spec) && !/^[./]/.test(spec)
463
+ && (spec.indexOf('node:') === 0 || !/^[a-z][a-z0-9+.-]*:/i.test(spec))
464
+ && !spec.split('/').some(function (seg) { return seg === '.' || seg === '..'; });
465
+ };
466
+ // The node runner's canonicalImport, which is what the gate asks about: 'os' is 'node:os', so a
467
+ // restriction of 'node:' admits it at both.
468
+ const isBuiltin = require('node:module').isBuiltin;
469
+ const canonical = function (spec) {
470
+ return spec.indexOf(':') < 0 && isBuiltin(spec) ? 'node:' + spec : spec;
471
+ };
472
+ const permits = workerData.permittedImports;
473
+ const API_PKG = '@matatbread/matbot-plugin-api';
474
+ const withheld = new Set<string>(workerData.withheldGlobals ?? []);
475
+ const permitted = function (spec) {
476
+ return permits.some(function (p) {
477
+ return spec === p
478
+ || (p.charAt(p.length - 1) === '/' || p.charAt(p.length - 1) === ':'
479
+ ? spec.indexOf(p) === 0
480
+ : spec.indexOf(p + '/') === 0);
481
+ });
482
+ };
483
+ // Where an import was reported on by a rule of ours, so tsc's own complaint about the same specifier is
484
+ // dropped. Both fire whenever the module does not resolve, and tsc's is actively misleading here: it
485
+ // offers "Do you need to install type definitions for node?" about a module the INSTALLATION forbids,
486
+ // which is not a thing the author can fix — or, for a specifier that lands on a declaration-only
487
+ // package, a path inside matbot's own node_modules. Which of the three tsc emits depends on whether
488
+ // @types/node happens to be reachable from the program root, so these rules are the deterministic ones.
489
+ const importStarts = new Set();
490
+ // Every literal import()'s specifier and where it sits, recorded whether or not a restriction exists:
491
+ // the rewrite below is about SPELLING, which no permit decides.
492
+ const importSpecs = new Map();
493
+ const envVisit = function (node, sf) {
494
+ if (envGate && node.getStart(sf) >= minStart) {
495
+ if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword
496
+ && node.arguments.length > 0 && ts.isStringLiteralLike(node.arguments[0])) {
497
+ const spec = node.arguments[0].text;
498
+ const at = node.arguments[0].getStart(sf);
499
+ importSpecs.set(at, spec);
500
+ // Resolvable for TYPES (the declarations above refer to it) and not at run time: the runner's
501
+ // import resolves from the CLI's own module, where under pnpm this package is not present. So it
502
+ // typechecked clean and died at the first call — exactly the hole this gate exists to close —
503
+ // and nothing a body needs is in there anyway.
504
+ if (spec === API_PKG || spec.indexOf(API_PKG + '/') === 0) {
505
+ synth.push(mk(sf, node.arguments[0], 90006,
506
+ "'" + spec + "' cannot be imported by a function body: it is in scope for TYPES only. Everything a body is given is already ambient — 'tool', 'toolInContext' and 'context' — so there is nothing to import from it."));
507
+ importStarts.add(at);
508
+ } else if (!byName(spec)) {
509
+ // Whatever the runner: the gate refuses these without asking, so a body naming one is refused
510
+ // at definition rather than at its first call.
511
+ synth.push(mk(sf, node.arguments[0], 90006,
512
+ "'" + spec + "' cannot be imported by a function body, which imports only node builtins ('node:fs') and packages already installed where matbot runs, by name — never a path or a URL. To use other code, install it as a package, or as a matbot plugin with the 'plugin' tool."));
513
+ importStarts.add(at);
514
+ } else if (permits !== undefined && !permitted(canonical(spec))) {
515
+ synth.push(mk(sf, node.arguments[0], 90006,
516
+ permits.length === 0
517
+ ? "module imports are switched off on this installation, so '" + spec + "' cannot be imported. Compute with the tools available instead."
518
+ : "'" + spec + "' is not permitted on this installation, which allows only: " + permits.join(', ')
519
+ + ". This is configuration, not a permission anyone can grant at the call — use a permitted module, or none."));
520
+ importStarts.add(at);
521
+ }
522
+ }
523
+ if (ts.isMetaProperty(node) && node.keywordToken === ts.SyntaxKind.ImportKeyword) {
524
+ synth.push(mk(sf, node, 90005,
525
+ "'import.meta' is only available in a module, and a function body is not one — this is a syntax error when the body is compiled, so it cannot run at all. Remove it."));
526
+ } else if (ts.isIdentifier(node) && withheld.has(node.text)
527
+ && !(node.parent && ts.isPropertyAccessExpression(node.parent) && node.parent.name === node)
528
+ && !(node.parent && (ts.isPropertyAssignment(node.parent) || ts.isPropertySignature(node.parent)) && node.parent.name === node)
529
+ // The SOURCE half of a renamed destructuring is a property of the thing being unpacked,
530
+ // not the global: 'const { Buffer: B } = await import("node:buffer")' is the working
531
+ // form, and firing on it recommended almost exactly the code it was rejecting. The
532
+ // shorthand is already exempt by a different route — there the identifier IS the local
533
+ // declaration, so 'authorDeclared' answers for it.
534
+ && !(node.parent && ts.isBindingElement(node.parent) && node.parent.propertyName === node)
535
+ && !inTypePosition(node)
536
+ && !authorDeclared(node)) {
537
+ synth.push(mk(sf, node, 90005, ADVICE[node.text]
538
+ ?? ("'" + node.text + "' is not defined in a function body — the runner withholds it.")));
539
+ envStarts.add(node.getStart(sf));
540
+ }
541
+ }
542
+ ts.forEachChild(node, function (c) { envVisit(c, sf); });
543
+ };
544
+
325
545
  const skip = new Set();
326
546
  const visit = function (node, sf) {
327
547
  const isAssertion = ts.isAsExpression(node) || (ts.isTypeAssertionExpression && ts.isTypeAssertionExpression(node));
@@ -346,9 +566,60 @@ try {
346
566
  }
347
567
  ts.forEachChild(node, function (c) { visit(c, sf); });
348
568
  };
349
- for (const gf of gateFiles) { visit(gf, gf); contractVisit(gf, gf); }
569
+ for (const gf of gateFiles) { visit(gf, gf); contractVisit(gf, gf); envVisit(gf, gf); }
570
+
571
+ // A bare 'node' is not the builtins namespace — it resolves to @types/node's index.d.ts, which is
572
+ // references and ambient blocks with no export, so tsc reports "File '<matbot's own node_modules>/
573
+ // @types/node/index.d.ts' is not a module": a path the body never named and its author cannot act on.
574
+ // Rewritten only where tsc ALREADY failed on it, so a package genuinely called 'node' is untouched,
575
+ // and only where no gate has spoken at that position, so one mistake stays one finding. It is also what
576
+ // a restriction of ["node"] permits — a package of that name, no builtin — which is why this fires with
577
+ // no restriction in force too.
578
+ for (const d of targets) {
579
+ if (d.code !== 2306 && d.code !== 2307) continue;
580
+ if (importSpecs.get(d.start) !== 'node' || importStarts.has(d.start)) continue;
581
+ synth.push({ file: d.file, start: d.start, length: d.length, code: 90006,
582
+ category: ts.DiagnosticCategory.Error, __syn: true,
583
+ messageText: "there is no module called 'node'. Node's builtins carry the 'node:' prefix — import 'node:fs/promises' or 'node:os', naming the one you need." });
584
+ importStarts.add(d.start);
585
+ }
586
+
587
+ // ── TS2591's repair is never actionable in a snippet ──
588
+ // "Cannot find name 'process'. Do you need to install type definitions for node? Try 'npm i --save-dev
589
+ // @types/node'" is tsc telling a function body to run a package manager: there is no package.json to
590
+ // install into, and what a body is typed against is fixed by the runner, not by what happens to be
591
+ // installed. It fires for any global node declares that this configuration did not type — most often
592
+ // 'process', which ENV-GATE does not reach when NO runner is loaded, because then nothing is withheld.
593
+ // The finding is right and only the advice is wrong, so the message is replaced and the position
594
+ // suppressed exactly as a withheld name's is. No list of names here, deliberately: the trigger is
595
+ // tsc's own code, so this cannot drift out of step with what the runner withholds.
596
+ if (envGate) {
597
+ for (const d of targets) {
598
+ if (d.code !== 2591 || !d.file || typeof d.start !== 'number') continue;
599
+ if (envStarts.has(d.start) || importStarts.has(d.start)) continue;
600
+ // tsc raises the same code for an import() of a builtin it has no declarations for, at the
601
+ // specifier — which is a module, not a global, and is repaired differently.
602
+ const spec = importSpecs.get(d.start);
603
+ if (spec !== undefined) {
604
+ synth.push({ file: d.file, start: d.start, length: d.length, code: 90006,
605
+ category: ts.DiagnosticCategory.Error, __syn: true,
606
+ messageText: "'" + spec + "' has no type declarations here, so nothing it returns can be checked. The comment block at the top of these declarations lists the modules this installation types — use one of those, or define this function with noTypeCheck." });
607
+ importStarts.add(d.start);
608
+ continue;
609
+ }
610
+ const name = d.file.text.substr(d.start, d.length);
611
+ synth.push({ file: d.file, start: d.start, length: d.length, code: 90005,
612
+ category: ts.DiagnosticCategory.Error, __syn: true,
613
+ messageText: "'" + name + "' is not declared for a function body: the declarations above are the whole of the environment a body is typed against, and there are no type definitions to install from here. A node builtin comes from an 'await import' of a 'node:…' specifier; everything else a body is given is already in scope — 'tool', 'toolInContext' and 'context'." });
614
+ envStarts.add(d.start);
615
+ }
616
+ }
350
617
 
351
- const errors = targets.filter(function (d) { return d.category === ts.DiagnosticCategory.Error; }).concat(synth);
618
+ const errors = targets.filter(function (d) {
619
+ if (d.category !== ts.DiagnosticCategory.Error) return false;
620
+ if ((d.code === 2306 || d.code === 2307 || d.code === 2591) && importStarts.has(d.start)) return false;
621
+ return !((d.code === 2304 || d.code === 2591) && envStarts.has(d.start));
622
+ }).concat(synth);
352
623
  errors.sort(function (a, b) {
353
624
  const fa = a.file ? a.file.fileName : '', fb = b.file ? b.file.fileName : '';
354
625
  return fa < fb ? -1 : fa > fb ? 1 : (a.start || 0) - (b.start || 0);
package/src/index.ts CHANGED
@@ -1,10 +1,10 @@
1
- import { dirname, join } from 'node:path';
2
- import { existsSync } from 'node:fs';
1
+ import { dirname, join, resolve } from 'node:path';
2
+ import { existsSync, readFileSync } from 'node:fs';
3
3
  import { createRequire } from 'node:module';
4
- import { PLUGIN_API_VERSION, RegistryChangeKind } from '@matatbread/matbot-plugin-api';
5
- import type { MatbotMachine, MatbotPluginSpec, ToolCheckReport, ToolTypeIndex } from '@matatbread/matbot-plugin-api';
4
+ import { PLUGIN_API_VERSION, RegistryChangeKind, contractArms, importPermitted, importableByName } from '@matatbread/matbot-plugin-api';
5
+ import type { FunctionRunSettings, FunctionRunner, MatbotMachine, MatbotPluginSpec, ToolCheckReport, ToolTypeIndex } from '@matatbread/matbot-plugin-api';
6
6
  import { getRegisteredPlugins } from '@matatbread/matbot-core';
7
- import { buildToolTypesData, compileToolValidators, type ToolTypesData } from './build-dts.js';
7
+ import { buildToolTypesData, compileToolValidators, type SyntheticContract, type ToolTypesData } from './build-dts.js';
8
8
  import { checkSnippetAgainst } from './checker.js';
9
9
  import type { ToolValidator } from './validator.js';
10
10
 
@@ -23,8 +23,8 @@ export {
23
23
  * type formation and analysis — it derives the dts, the wire contracts and the JSON Schemas from each
24
24
  * tool's `ToolContract`, and emits a validator from the checker's resolved params type — but it is not
25
25
  * itself a validator and registers no validator service. Enforcement is a consumer's:
26
- * `@matatbread/matbot-tool-ts-validation` calls this, applies a policy, and registers the
27
- * `ToolCallValidator` that core consults at the executor.
26
+ * `@matatbread/matbot-tool-ts-validation` calls this, applies a policy, and registers the `validate`
27
+ * hook that core dispatches at the executor.
28
28
  *
29
29
  * That separation is the point. A code generator (`skills_compiler`, `function-tools`) loads this package
30
30
  * for `dts()`/`check()` alone; if loading it also switched input enforcement on, adopting typed codegen
@@ -136,7 +136,7 @@ export interface ToolTypesInputs {
136
136
  pluginEntryUrls: string[];
137
137
  /** Absent ⇒ every scanned tool, for a build meant to serve any live set (see `filterToolTypesData`). */
138
138
  liveToolNames?: string[];
139
- syntheticContracts: Record<string, string>;
139
+ syntheticContracts: Record<string, SyntheticContract>;
140
140
  }
141
141
 
142
142
  /** Where the index gets a build from on a miss. The default builds one; a specialisation may find one. */
@@ -155,6 +155,18 @@ export const buildToolTypes: ToolTypesFill = i =>
155
155
  * already declares is skipped, so nothing is declared twice. `declare const tool: ToolProxy` (mapped over
156
156
  * the merged `ToolContracts`) plus its override factory `toolInContext` is what generators call.
157
157
  */
158
+ /** The two arrays a runner states, printed: a stable fingerprint of the environment a check's verdict
159
+ * was reached under, for a caller that PERSISTS the verdict (`function-tools` stores one beside each
160
+ * definition and compares it). Sorted and printed rather than identity-derived, because it has to
161
+ * survive a restart — unlike the `paths` cache, whose job is the opposite and which keys on the array
162
+ * itself. */
163
+ function fingerprintOf(runner: FunctionRunner | undefined, settings: FunctionRunSettings | undefined): string {
164
+ if (runner === undefined) return 'no-runner';
165
+ const permit = settings?.permittedImports;
166
+ return `permit=${permit === undefined ? '*' : [...permit].sort().join(',')};`
167
+ + `withheld=${[...(runner.withheldGlobals ?? [])].sort().join(',')}`;
168
+ }
169
+
158
170
  export class ToolTypeIndexImpl implements ToolTypeIndex {
159
171
  private readonly machine: MatbotMachine;
160
172
  private readonly fill: ToolTypesFill;
@@ -172,6 +184,14 @@ export class ToolTypeIndexImpl implements ToolTypeIndex {
172
184
  this.machine = machine;
173
185
  this.fill = fill;
174
186
  // Any tool CRUD invalidates the generated dts; the event itself carries nothing we need.
187
+ //
188
+ // A `FunctionRunner` arriving or leaving deliberately does NOT, though it is the obvious thing to
189
+ // reach for now that the runner is a plugin and can appear after a dts has been handed out. Nothing
190
+ // derived from it is held: each `dts`/`check`/`environment` reads the runner and its settings once at
191
+ // its start, and the one cache over them — {@link importPaths} — keys on the permit list's CONTENT,
192
+ // so a different list is a different key. What IS cached is the source scan, which the
193
+ // runner has no part in. Subscribing would throw away a good TypeScript build every time the runner
194
+ // was registered or hot-reloaded, to recompute something that was never stale.
175
195
  machine.Notifier.consume(() => { this.generation++; }, this.ac.signal,
176
196
  n => n.kind === RegistryChangeKind && n.registry === 'tools');
177
197
  }
@@ -210,9 +230,9 @@ export class ToolTypeIndexImpl implements ToolTypeIndex {
210
230
  // which they were described to the model in full and then enforced only by their loose
211
231
  // `inputSchema`, which is backwards: their params were authored by an LLM, not a compiler.
212
232
  const live = this.machine.tools.list();
213
- const synthetic = Object.fromEntries(
214
- live.flatMap(t => (t.toolContract !== undefined ? [[t.name, t.toolContract] as const] : [])),
215
- );
233
+ const synthetic = Object.fromEntries(live.flatMap(t => (t.toolContract !== undefined
234
+ ? [[t.name, { contract: t.toolContract, ...(t.toolContractTypes !== undefined ? { types: t.toolContractTypes } : {}) }] as const]
235
+ : [])));
216
236
  const built = await this.fill({
217
237
  projectRoot: root, pluginEntryUrls: urls, liveToolNames: live.map(t => t.name), syntheticContracts: synthetic,
218
238
  });
@@ -224,7 +244,17 @@ export class ToolTypeIndexImpl implements ToolTypeIndex {
224
244
  this.builtFor = generation;
225
245
  }
226
246
 
227
- async dts(): Promise<string> {
247
+ /** The runner and its settings, read once for one invocation of this index — a `dts`, a `check` — and
248
+ * passed to everything inside it. Per invocation, never cached: whose settings they are depends on how
249
+ * the settings store is partitioned, and the next invocation may be another principal's. */
250
+ private async runnerNow(): Promise<{ runner: FunctionRunner | undefined; settings: FunctionRunSettings | undefined }> {
251
+ const runner = this.machine.FunctionRunner;
252
+ return { runner, settings: await runner?.settings?.() };
253
+ }
254
+
255
+ async dts(): Promise<string> { return this.dtsUnder(await this.runnerNow()); }
256
+
257
+ private async dtsUnder(env: { runner: FunctionRunner | undefined; settings: FunctionRunSettings | undefined }): Promise<string> {
228
258
  await this.ensureBuilt();
229
259
  // `tool` — the injected proxy `function-tools`/compiled skills call — is a `ToolProxy`, a mapped type
230
260
  // over the (augmented) `ToolContracts`: each multi-arm entry becomes an overload set, so `await
@@ -233,7 +263,12 @@ export class ToolTypeIndexImpl implements ToolTypeIndex {
233
263
  // hand-authored; `check()` uses this same string, so what a generator is shown is exactly what it is
234
264
  // graded against — which is also why `context` is declared here and not merely described in prose:
235
265
  // undeclared, every body reading it would fail the very check this string backs.
236
- return `${this.registryBlock(this.cache!)}\ndeclare const tool: import('@matatbread/matbot-plugin-api').ToolProxy;\ndeclare const toolInContext: import('@matatbread/matbot-plugin-api').ToolBox;\ndeclare const context: import('@matatbread/matbot-plugin-api').ComposedCallContext;\n`;
266
+ // The import line is in the dts rather than in prose on the wire because this string is what a body is
267
+ // GRADED against: an author told elsewhere that imports work would still have to guess whether the
268
+ // checker agreed. It names what is permitted HERE, from the live set, rather than claiming imports
269
+ // work in general — a module outside the set does not resolve, which is the whole point of scoping
270
+ // the types to it. `require` and the rest are rejected by the env gate, not left to fail at a call.
271
+ return `${this.registryBlock(this.cache!)}\ndeclare const tool: import('@matatbread/matbot-plugin-api').ToolProxy;\ndeclare const toolInContext: import('@matatbread/matbot-plugin-api').ToolBox;\ndeclare const context: import('@matatbread/matbot-plugin-api').ComposedCallContext;\n${await this.importNote(env.runner, env.settings)}`;
237
272
  }
238
273
 
239
274
  async wireContracts(): Promise<Record<string, { params: string; result: string }>> {
@@ -247,9 +282,148 @@ export class ToolTypeIndexImpl implements ToolTypeIndex {
247
282
  return out;
248
283
  }
249
284
 
285
+ /**
286
+ * `paths` for the modules this installation permits a body to import, so `await import('node:os')` is
287
+ * checked against the real signatures and a module outside the permitted set simply does not resolve.
288
+ *
289
+ * The set is read off the {@link FunctionRunner}, which is where it lives because the runner IS the
290
+ * execution environment and two consumers need one answer — the capability that imports, and this,
291
+ * which types it. An absent restriction means every builtin: a body may ASK for anything and the gate
292
+ * decides, so refusing to type what it may legitimately ask for would make the prompt unreachable.
293
+ * Resolved from THIS package, where `@types/node` is a dependency: the program is
294
+ * rooted at the `matbot.yaml` directory, which under pnpm and in any published install has no
295
+ * `node_modules/@types` in its lookup chain, so nothing would resolve from there.
296
+ *
297
+ * A builtin gets its real declaration file. A bare package name is left to ordinary resolution: if it
298
+ * is installed it types properly, and if it is not, the error is honest.
299
+ *
300
+ * A path or a URL gets nothing, because a body cannot import one at all (`importableByName`), and
301
+ * IMPORT-GATE says so at the check.
302
+ */
303
+ /** {@link importPaths} is read twice per check — once for the program's `paths`, once by {@link
304
+ * importNote} through the dts — and it walks every builtin with a stat apiece. Cached against the
305
+ * CONTENT of the permit list it was computed from: settings are read afresh per invocation, so each
306
+ * read is a new array and an identity key would never hit. */
307
+ private pathsFor?: { key: string; paths: Record<string, string[]> };
308
+
309
+ private async importPaths(restricted: readonly string[] | undefined): Promise<Record<string, string[]>> {
310
+ const key = restricted === undefined ? '*' : JSON.stringify(restricted);
311
+ if (this.pathsFor !== undefined && this.pathsFor.key === key) return this.pathsFor.paths;
312
+ const paths = await this.computeImportPaths(restricted);
313
+ this.pathsFor = { key, paths };
314
+ return paths;
315
+ }
316
+
317
+ private async computeImportPaths(restricted: readonly string[] | undefined): Promise<Record<string, string[]>> {
318
+ // Absent ⇒ unrestricted, so every builtin is typed and the gate decides each import at the call. A
319
+ // configured restriction narrows this to its own subset, which is what makes a forbidden module a
320
+ // COMPILE error rather than something that typechecks and is refused later.
321
+ if (restricted?.length === 0) return {};
322
+ const { builtinModules } = await import('node:module');
323
+ const req = createRequire(import.meta.url);
324
+ const nodeTypes = dirname(req.resolve('@types/node/package.json'));
325
+ const out: Record<string, string[]> = {};
326
+ // Every builtin tested against the shared boundary rule, rather than an entry's own spelling being
327
+ // expanded here: `node:fs` admits `node:fs/promises` at the gate, so it must TYPE the submodule too.
328
+ // Emitting the exact specifier alone left a permitted import failing the check, reachable only with
329
+ // `noTypeCheck` — the one divergence between what runs and what is graded.
330
+ // What the GATE would allow, which is the only set worth typing: unrestricted admits any spelling, a
331
+ // restriction admits what its boundary rule admits. Anything else is a divergence between what runs
332
+ // and what is graded, in one direction or the other.
333
+ const allowed = (spec: string): boolean => restricted === undefined || importPermitted(restricted, spec);
334
+ for (const m of builtinModules) {
335
+ if (m.startsWith('_')) continue;
336
+ // Some entries ALREADY carry the prefix — node:sea, node:sqlite, node:test, node:test/reporters,
337
+ // which have no unprefixed spelling — so prefixing unconditionally wrote `node:node:sqlite`, and
338
+ // those four got no entry at all. `await import('node:sqlite')` then failed the check with tsc's
339
+ // "install type definitions for node", which is the message IMPORT-GATE exists to replace.
340
+ const prefixed = m.startsWith('node:');
341
+ const bare = prefixed ? m.slice('node:'.length) : m;
342
+ const file = declarationFile(nodeTypes, bare);
343
+ if (file === undefined) continue;
344
+ if (allowed(`node:${bare}`)) out[`node:${bare}`] = [file];
345
+ // The UNPREFIXED spelling too, where node has one: `import('os')` resolves to `node:os` at run
346
+ // time, and a bare specifier is the spelling a model reaches for first. Allowed by the PREFIXED
347
+ // spelling, because that is what the gate asks about (`canonicalImport`) — so `['node:']` types
348
+ // `os`, as the gate admits it.
349
+ if (!prefixed && allowed(`node:${bare}`)) out[bare] = [file];
350
+ }
351
+ return out;
352
+ }
353
+
354
+ /** The part of the dts that is about imports: which modules this install permits AND which of those
355
+ * have types, that second half being this package's own knowledge. Everything else about the
356
+ * environment — the gate, what is not in scope — is the runner's to state, and is appended verbatim. */
357
+ private async importNote(runner: FunctionRunner | undefined, settings: FunctionRunSettings | undefined): Promise<string> {
358
+ const restricted = settings?.permittedImports;
359
+ const typed = new Set(Object.keys(await this.importPaths(restricted)));
360
+ // "Switched off" is `permit: []` and nothing else — the one configured "never". Derived from the
361
+ // TYPED set instead, it fired for any restriction naming no builtin (`permit: ['lodash']`), telling
362
+ // an author imports were off while the gate was perfectly willing to ask about one.
363
+ // An entry is typed if it names a declaration itself or admits one — `node:` and `node:fs` both do,
364
+ // through their submodules. A bare package admits none, which is a stated refusal rather than a fake
365
+ // type, so the listing says so where the author will read it.
366
+ const covered = (p: string): boolean => typed.has(p) || [...typed].some(t => importPermitted([p], t));
367
+ // The EXPANDED set, because a prefix is not an answer: `node:` tells an author nothing about which
368
+ // builtins exist, and `node:fs` hides that `node:fs/promises` came with it. Restriction entries that
369
+ // admit no declaration at all are listed after it, marked — a bare package is untypeable here, which
370
+ // is a stated refusal rather than a fake type, and the author needs to know which it is.
371
+ // A bare `node` is the one entry that is not merely untypeable but unimportable: the boundary rule
372
+ // reads it as a PACKAGE of that name (it admits `node/sub`, never `node:os`), so an install meaning
373
+ // the builtins and missing the colon permits nothing a body can use. Listing it as "untyped —
374
+ // import it only with noTypeCheck" invited exactly the attempt that cannot work, so it says what it is.
375
+ // A path or a URL is unimportable outright, whoever's runner listed it: the gate never asks about one.
376
+ const mark = (p: string): string => p === 'node'
377
+ ? `${p} (a PACKAGE of that name — not node's builtins, which are spelled 'node:fs'; nothing here can import it)`
378
+ : !importableByName(p.replace(/\/$/, ''))
379
+ ? `${p} (a path or a URL — a body imports only builtins and packages, by name; nothing here can import it)`
380
+ : `${p} (untyped — import it only with noTypeCheck)`;
381
+ const listing = [
382
+ ...[...typed].sort(),
383
+ ...(restricted ?? []).filter(p => !covered(p)).sort().map(mark),
384
+ ];
385
+ // Whether an import is GATED is whether a runner routes it, not whether a restriction exists. With no
386
+ // runner nothing rewrites `import(…)`: it reaches node's own loader, unasked and unchecked. Saying
387
+ // "you will be asked" there is a promise nothing keeps, and a body discovers the contradiction the
388
+ // first time it imports something.
389
+ const gated = runner !== undefined;
390
+ const subject = gated ? ', each subject to permission at the call' : '';
391
+ const note = restricted !== undefined && restricted.length === 0
392
+ ? `// Module imports are switched off on this installation.\n`
393
+ : restricted === undefined
394
+ ? `// A body may import node builtins${subject}${gated ? ' — you will be asked\n// the first time' : ''}: const fs = await import('node:fs/promises');\n`
395
+ : `// A body may import these${subject}:\n`
396
+ + `${listing.map(p => `// ${p}`).join('\n')}\n`;
397
+ // Composed from what the runner STATES — the permitted set above, and the identifiers it does not
398
+ // bind — never from prose it supplies: the facts are the runner's, the wording is this file's, and
399
+ // the same two arrays are what IMPORT-GATE and ENV-GATE enforce, so the note cannot drift from them.
400
+ const withheld = runner?.withheldGlobals ?? [];
401
+ return `${note}`
402
+ + (withheld.length > 0
403
+ ? `// A body is a bare async function, not a module, and not every global is in scope. Absent: ${withheld.join(', ')}, import.meta.\n`
404
+ : '');
405
+ }
406
+
407
+ /** The two arrays again, printed: a stable fingerprint of the environment a check's verdict was
408
+ * reached under, for a caller that PERSISTS the verdict (`function-tools` stores one beside each
409
+ * definition). Sorted and printed rather than identity-derived, because it has to survive a restart
410
+ * — unlike {@link pathsFor}, whose job is the opposite and which keys on the array itself. */
411
+ async environment(): Promise<string> {
412
+ const { runner, settings } = await this.runnerNow();
413
+ return fingerprintOf(runner, settings);
414
+ }
415
+
250
416
  async check(snippet: string): Promise<ToolCheckReport> {
251
- const root = this.machine.configPath !== undefined ? dirname(this.machine.configPath) : '.';
252
- const prefix = `${await this.dts()}\n`;
417
+ // ABSOLUTE, always. The virtual file is named `<root>/…`, and `ts.createProgram` normalises a
418
+ // relative one to a different string than the hook compares against — so `getSourceFile(virtual)`
419
+ // missed, there were no files to check, and the snippet came back clean whatever was in it. A
420
+ // checker that silently passes everything is the one failure mode this path must not have.
421
+ const root = resolve(this.machine.configPath !== undefined ? dirname(this.machine.configPath) : '.');
422
+ // Read ONCE, before anything else: the dts, the `paths`, the worker's restriction and the fingerprint
423
+ // stamped below all have to describe one environment — the one this was graded against — not
424
+ // whatever is current by the time each is computed.
425
+ const env = await this.runnerNow();
426
+ const prefix = `${await this.dtsUnder(env)}\n`;
253
427
  const source = `${prefix}${snippet}\nexport {};\n`; // trailing export ⇒ this file is a module
254
428
 
255
429
  // Anchor `@matatbread/matbot-plugin-api` — it isn't a bare-resolvable dep of the project root, so map it
@@ -263,12 +437,30 @@ export class ToolTypeIndexImpl implements ToolTypeIndex {
263
437
 
264
438
  // Worker-hosted check (see checker.ts) — off the main loop, and each diagnostic comes back as an
265
439
  // annotated block (caret-anchored frame, related locations, HINT) with snippet-relative positions.
266
- return checkSnippetAgainst({
440
+ const { runner, settings } = env;
441
+ const importPaths = await this.importPaths(settings?.permittedImports);
442
+ // The restriction goes too, and not only its `paths`: one builtin's declaration file drags in the
443
+ // ambient `declare module 'node:…'` blocks of everything its own declarations reference, so a
444
+ // forbidden specifier resolves through the back door and typechecks clean. The checker closes that
445
+ // structurally. Absent stays absent — unrestricted means nothing to enforce.
446
+ const restricted = settings?.permittedImports;
447
+ const withheld = runner?.withheldGlobals;
448
+ const report = await checkSnippetAgainst({
267
449
  root, source,
268
450
  prefixLen: prefix.length,
269
451
  prefixLines: prefix.split('\n').length - 1,
270
452
  ...(apiIndex !== undefined ? { apiIndexPath: apiIndex } : {}),
453
+ ...(Object.keys(importPaths).length > 0 ? { importPaths } : {}),
454
+ globalTypes: nodeGlobalTypes(),
455
+ ...(restricted !== undefined ? { permittedImports: restricted } : {}),
456
+ // ENV-GATE's list, from the runner that withholds them. Absent with no runner, which is correct:
457
+ // nothing is withheld there either, so there is nothing to reject.
458
+ ...(withheld !== undefined ? { withheldGlobals: withheld } : {}),
271
459
  });
460
+ // Stamped here and nowhere else, from the same two lists that were just passed to the worker, so the
461
+ // fingerprint cannot describe an environment other than the one graded against. Only on a verdict
462
+ // that exists: `checked: false` has nothing to be stale.
463
+ return report.checked ? { ...report, environment: fingerprintOf(runner, settings) } : report;
272
464
  }
273
465
 
274
466
  // Every live tool the source scan didn't already declare: a source-less tool that carries its contract as
@@ -282,13 +474,12 @@ export class ToolTypeIndexImpl implements ToolTypeIndex {
282
474
  // top-of-file import the derived block emits (every arm references it); when the scan produced nothing to
283
475
  // import it (no source resolved, or an all-`MatbotServices` block), this block supplies that one import.
284
476
  private registryBlock(derived: string): string {
285
- const arms: string[] = [];
286
- for (const t of this.machine.tools.list()) {
287
- if (this.covered.has(t.name)) continue;
288
- arms.push(` ${JSON.stringify(t.name)}: ${t.toolContract ?? `ToolContract<unknown, ${schemaToTs(t.inputSchema)}>`};`);
289
- }
477
+ const { preamble, arms: armOf } = contractArms(this.machine.tools.list().filter(t => !this.covered.has(t.name)).map(t => ({
478
+ name: t.name, contract: t.toolContract ?? `ToolContract<unknown, ${schemaToTs(t.inputSchema)}>`, types: t.toolContractTypes,
479
+ })));
480
+ const arms = [...armOf].map(([name, arm]) => ` ${JSON.stringify(name)}: ${arm};`);
290
481
  if (arms.length === 0) return derived;
291
- const body = arms.join('\n');
482
+ const body = preamble + arms.join('\n');
292
483
  // Import the plugin-api types these arms reference — `ToolContract` always, plus any plugin-api export a
293
484
  // source-less `toolContract` names (e.g. `StoreQuery`) — minus whatever the derived block already imports
294
485
  // (importing a name twice is a redeclaration error). A synthetic tool inlines its own shape types, so the
@@ -302,7 +493,7 @@ export class ToolTypeIndexImpl implements ToolTypeIndex {
302
493
  const head = needed.length
303
494
  ? `${derived === '' ? "import '@matatbread/matbot-plugin-api';\n" : ''}import type { ${needed.join(', ')} } from '@matatbread/matbot-plugin-api';\n`
304
495
  : '';
305
- return `${head}${derived}\ndeclare module '@matatbread/matbot-plugin-api' {\n interface ToolContracts {\n${body}\n }\n}\n`;
496
+ return `${head}${derived}\n${preamble}declare module '@matatbread/matbot-plugin-api' {\n interface ToolContracts {\n${arms.join('\n')}\n }\n}\n`;
306
497
  }
307
498
 
308
499
  async toolValidators(): Promise<Record<string, ToolValidator>> {
@@ -327,3 +518,30 @@ export function createToolTypesPlugin(): MatbotPluginSpec {
327
518
  }
328
519
 
329
520
  export const plugin: MatbotPluginSpec = createToolTypesPlugin();
521
+
522
+
523
+ // The node globals a body has that the standard library does not declare: `Buffer`, and its overloads in
524
+ // buffer.buffer.d.ts. The rest of what a body is given (`fetch`, the timers, `console`, `TextEncoder`,
525
+ // `atob`) is in lib.dom. Loaded whether or not the runner withholds it, since ENV-GATE rejects a withheld
526
+ // name either way, and with no runner a body really has it.
527
+ function nodeGlobalTypes(): string[] {
528
+ const nodeTypes = dirname(createRequire(import.meta.url).resolve('@types/node/package.json'));
529
+ return ['buffer.buffer.d.ts', 'buffer.d.ts'].map(f => join(nodeTypes, f)).filter(f => existsSync(f));
530
+ }
531
+
532
+ // Where @types/node declares a builtin. Most have a file of their own, but a few subpaths are declared
533
+ // inside their parent's (`path/posix` in path.d.ts, `util/types` in util.d.ts, `test/reporters` in
534
+ // test.d.ts), and skipping those left a module the gate admits failing the check. The parent is taken
535
+ // only if it actually declares the module under one spelling or the other, so a builtin @types/node
536
+ // knows nothing about still gets no entry rather than a path that types something else.
537
+ function declarationFile(nodeTypes: string, bare: string): string | undefined {
538
+ const own = join(nodeTypes, `${bare}.d.ts`);
539
+ if (existsSync(own)) return own;
540
+ const slash = bare.indexOf('/');
541
+ if (slash < 0) return undefined;
542
+ const parent = join(nodeTypes, `${bare.slice(0, slash)}.d.ts`);
543
+ if (!existsSync(parent)) return undefined;
544
+ const text = readFileSync(parent, 'utf8');
545
+ return [bare, `node:${bare}`].some(m => text.includes(`declare module "${m}"`) || text.includes(`declare module '${m}'`))
546
+ ? parent : undefined;
547
+ }