@matatbread/matbot-tool-types 0.4.18 → 0.4.20

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 (3) hide show
  1. package/package.json +6 -6
  2. package/src/checker.ts +284 -17
  3. package/src/index.ts +218 -9
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.20",
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-core": "^0.4.20",
41
+ "@matatbread/matbot-plugin-api": "^0.4.20"
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-core": "^0.4.20",
46
+ "@matatbread/matbot-plugin-api": "^0.4.20"
47
47
  },
48
48
  "scripts": {
49
49
  "typecheck": "tsc --noEmit"
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,22 @@ 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
+ /** The restriction itself, when there is one — `paths` cannot enforce it. Loading ONE builtin's
244
+ * declaration file pulls in the ambient `declare module 'node:…'` blocks of everything its own
245
+ * declarations reference (`node:fs` reaches `node:stream`, which reaches most of the rest), so a
246
+ * forbidden specifier resolves anyway and typechecks clean. A literal `import('…')` is therefore
247
+ * checked STRUCTURALLY against this list, the way the cast gate and ENV-GATE close the other holes
248
+ * the type system cannot. Absent ⇒ unrestricted, and nothing is checked. */
249
+ permittedImports?: readonly string[];
250
+ /** The identifiers the RUNNER does not bind, from `FunctionRunner.withheldGlobals` — the list ENV-GATE
251
+ * rejects. It comes from the runner because a copy here could not be kept in step with it, and a name
252
+ * that is shadowed but not rejected typechecks and then fails at the first call. Absent ⇒ nothing is
253
+ * rejected: with no runner there is no claim about what a body does not have. */
254
+ withheldGlobals?: readonly string[];
199
255
  }): Promise<ToolCheckReport> {
200
256
  const diags = await runWorker({
201
257
  mode: 'snippet',
@@ -205,12 +261,18 @@ export async function checkSnippetAgainst(opts: {
205
261
  prefixLines: opts.prefixLines,
206
262
  virtualPath: `${opts.root}/__mb_toolcheck_${crypto.randomUUID()}.ts`,
207
263
  ...(opts.apiIndexPath !== undefined ? { apiIndexPath: opts.apiIndexPath } : {}),
264
+ ...(opts.importPaths !== undefined ? { importPaths: opts.importPaths } : {}),
265
+ ...(opts.permittedImports !== undefined ? { permittedImports: opts.permittedImports } : {}),
266
+ ...(opts.withheldGlobals !== undefined ? { withheldGlobals: opts.withheldGlobals } : {}),
208
267
  });
209
- return reportOf(diags ?? []);
268
+ return reportOf(diags ?? [], 'snippet');
210
269
  }
211
270
 
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
271
+ // The worker body: CommonJS (Worker eval mode is CJS, so `require` exists and no loader hooks are
272
+ // needed — the host's .ts strip-hooks do not reliably reach worker threads). Type annotations are
273
+ // fine here because the worker is started with `--input-type=commonjs-typescript`, so node strips them
274
+ // rather than guessing whether the source is TS (see runWorker). Anything beyond erasable syntax is not —
275
+ // no enums, no parameter properties. It loads the SAME
214
276
  // typescript module the main thread resolved and posts back JSON-safe records: flattened message
215
277
  // chains, related-information locations (e.g. which contract arm an expected type came from), and a
216
278
  // caret-anchored source frame per error. In snippet mode every position is remapped to be
@@ -255,7 +317,18 @@ try {
255
317
  target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.NodeNext, moduleResolution: ts.ModuleResolutionKind.NodeNext,
256
318
  strict: true, exactOptionalPropertyTypes: true, noEmit: true, skipLibCheck: true, baseUrl: baseDir,
257
319
  };
258
- if (workerData.apiIndexPath) options.paths = { '@matatbread/matbot-plugin-api': [workerData.apiIndexPath] };
320
+ // Module types come in through 'paths', one entry per PERMITTED specifier, never through
321
+ // types:['node'] — which is all-or-nothing (it makes every builtin resolve, so a module the install
322
+ // forbids typechecks clean and is refused only at run time) and pulls 168 files where this pulls 65.
323
+ // The plugin-api entry is needed in BOTH modes, and in snippet mode it is not about a body's imports
324
+ // at all: the generated declarations refer to their own types inline as
325
+ // import('@matatbread/matbot-plugin-api').ToolProxy, so without it every one of them collapses to any
326
+ // and bad snippets pass silently. That a BODY must not import the package is a separate fact,
327
+ // enforced structurally below — it cannot be expressed by withholding the resolution.
328
+ options.paths = {
329
+ ...(workerData.apiIndexPath ? { '@matatbread/matbot-plugin-api': [workerData.apiIndexPath] } : {}),
330
+ ...(workerData.importPaths ?? {}),
331
+ };
259
332
  const host = ts.createCompilerHost(options);
260
333
  const getSF = host.getSourceFile.bind(host);
261
334
  host.getSourceFile = function (f, lang, onErr, create) {
@@ -322,6 +395,149 @@ try {
322
395
  ts.forEachChild(node, function (c) { contractVisit(c, sf); });
323
396
  };
324
397
 
398
+ // ── env gate: a global that TypeScript resolves but the runner does not define ──
399
+ // A tool_function body is compiled as a bare async function expression, not a module and not a CJS
400
+ // wrapper, so 'require', 'module', 'exports', '__dirname' and '__filename' are all undefined at
401
+ // runtime and 'import.meta' will not even compile. Loading node's types to check await import('node:…')
402
+ // declares every one of them as a global, which makes the commonest wrong guess — require('node:fs') —
403
+ // typecheck clean and fail at the first call: correct against the types it was shown, so the repair loop
404
+ // cannot repair it. Rejected structurally for the same reason a cast is, with the working form named.
405
+ // Only in snippet mode: a compiled plugin IS a module and legitimately has 'import.meta'.
406
+ //
407
+ // WHICH names are withheld comes from the runner's withheldGlobals, because it is the only thing that
408
+ // knows and a copy here could not be kept in step: a name shadowed but not rejected typechecks and
409
+ // fails at the first call, which is the one failure this gate exists to prevent. 'eval' and 'Function'
410
+ // are the worst to miss, being lib.es globals that typecheck in every configuration.
411
+ //
412
+ // The ADVICE stays here, because it is about repairing a snippet and that is this file's job, not the
413
+ // runner's. A withheld name with no entry below still fires, with a generic line — the list is the
414
+ // runner's to grow, and a new one must not pass silently for want of prose.
415
+ const ADVICE: Record<string, string> = {
416
+ 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')'.",
417
+ 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.",
418
+ 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.",
419
+ __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.",
420
+ __filename: "'__filename' is not defined in a function body. There is no file — the body is compiled from source held in the session.",
421
+ 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.",
422
+ Buffer: "'Buffer' is not defined in a function body — the runner withholds it. Use a 'Uint8Array', or import it where the gate can be asked: 'const { Buffer } = await import('node:buffer')'.",
423
+ 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'.",
424
+ 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'.",
425
+ 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>(…)'.",
426
+ 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.)",
427
+ };
428
+ // A withheld global named in a TYPE is harmless: types are erased before the body is compiled, so
429
+ // 'args: Buffer' never reaches the runner. Only the VALUE is rejected. Needed because the second half of
430
+ // the list above — unlike 'require' and friends — are types as well as values.
431
+ const inTypePosition = function (node) {
432
+ for (let a = node.parent; a; a = a.parent) {
433
+ if (ts.isTypeNode(a)) return true;
434
+ if (ts.isBlock(a) || ts.isSourceFile(a)) return false;
435
+ }
436
+ return false;
437
+ };
438
+ const envGate = workerData.mode === 'snippet';
439
+ // Where the rule fired, so tsc's own 'Cannot find name' for the same identifier can be dropped: without
440
+ // node's types loaded both report, and two findings for one fix read as a cascade when the second says
441
+ // nothing the first did not — except which repair to make, which is the one this rule carries.
442
+ const envStarts = new Set();
443
+ // Declared by the author rather than inherited from node's globals: their own binding shadows it and
444
+ // works, so the rule must not fire. Decided on where the symbol's declaration IS, not on the parent
445
+ // node kind — that catches 'const require = …', a parameter and an import alias with one test.
446
+ const authorDeclared = function (node) {
447
+ const sym = checker.getSymbolAtLocation(node);
448
+ const decls = sym && sym.declarations;
449
+ if (!decls) return false;
450
+ return decls.some(function (d) {
451
+ return d.getSourceFile().fileName === virtual && d.getStart() >= minStart;
452
+ });
453
+ };
454
+ // The permit's boundary rule and the by-name rule, inlined: the worker is a CommonJS realm with no
455
+ // loader hooks, so it cannot import 'importPermitted' or 'importableByName' from plugin-api, which is
456
+ // where both rules live and are documented.
457
+ const byName = function (spec) {
458
+ return spec !== '' && !/[^\\w@.~+!$&'()*,;=:/-]/.test(spec) && !/^[./]/.test(spec)
459
+ && (spec.indexOf('node:') === 0 || !/^[a-z][a-z0-9+.-]*:/i.test(spec))
460
+ && !spec.split('/').some(function (seg) { return seg === '.' || seg === '..'; });
461
+ };
462
+ // The node runner's canonicalImport, which is what the gate asks about: 'os' is 'node:os', so a
463
+ // restriction of 'node:' admits it at both.
464
+ const isBuiltin = require('node:module').isBuiltin;
465
+ const canonical = function (spec) {
466
+ return spec.indexOf(':') < 0 && isBuiltin(spec) ? 'node:' + spec : spec;
467
+ };
468
+ const permits = workerData.permittedImports;
469
+ const API_PKG = '@matatbread/matbot-plugin-api';
470
+ const withheld = new Set<string>(workerData.withheldGlobals ?? []);
471
+ const permitted = function (spec) {
472
+ return permits.some(function (p) {
473
+ return spec === p
474
+ || (p.charAt(p.length - 1) === '/' || p.charAt(p.length - 1) === ':'
475
+ ? spec.indexOf(p) === 0
476
+ : spec.indexOf(p + '/') === 0);
477
+ });
478
+ };
479
+ // Where an import was reported on by a rule of ours, so tsc's own complaint about the same specifier is
480
+ // dropped. Both fire whenever the module does not resolve, and tsc's is actively misleading here: it
481
+ // offers "Do you need to install type definitions for node?" about a module the INSTALLATION forbids,
482
+ // which is not a thing the author can fix — or, for a specifier that lands on a declaration-only
483
+ // package, a path inside matbot's own node_modules. Which of the three tsc emits depends on whether
484
+ // @types/node happens to be reachable from the program root, so these rules are the deterministic ones.
485
+ const importStarts = new Set();
486
+ // Every literal import()'s specifier and where it sits, recorded whether or not a restriction exists:
487
+ // the rewrite below is about SPELLING, which no permit decides.
488
+ const importSpecs = new Map();
489
+ const envVisit = function (node, sf) {
490
+ if (envGate && node.getStart(sf) >= minStart) {
491
+ if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword
492
+ && node.arguments.length > 0 && ts.isStringLiteralLike(node.arguments[0])) {
493
+ const spec = node.arguments[0].text;
494
+ const at = node.arguments[0].getStart(sf);
495
+ importSpecs.set(at, spec);
496
+ // Resolvable for TYPES (the declarations above refer to it) and not at run time: the runner's
497
+ // import resolves from the CLI's own module, where under pnpm this package is not present. So it
498
+ // typechecked clean and died at the first call — exactly the hole this gate exists to close —
499
+ // and nothing a body needs is in there anyway.
500
+ if (spec === API_PKG || spec.indexOf(API_PKG + '/') === 0) {
501
+ synth.push(mk(sf, node.arguments[0], 90006,
502
+ "'" + 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."));
503
+ importStarts.add(at);
504
+ } else if (!byName(spec)) {
505
+ // Whatever the runner: the gate refuses these without asking, so a body naming one is refused
506
+ // at definition rather than at its first call.
507
+ synth.push(mk(sf, node.arguments[0], 90006,
508
+ "'" + 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."));
509
+ importStarts.add(at);
510
+ } else if (permits !== undefined && !permitted(canonical(spec))) {
511
+ synth.push(mk(sf, node.arguments[0], 90006,
512
+ permits.length === 0
513
+ ? "module imports are switched off on this installation, so '" + spec + "' cannot be imported. Compute with the tools available instead."
514
+ : "'" + spec + "' is not permitted on this installation, which allows only: " + permits.join(', ')
515
+ + ". This is configuration, not a permission anyone can grant at the call — use a permitted module, or none."));
516
+ importStarts.add(at);
517
+ }
518
+ }
519
+ if (ts.isMetaProperty(node) && node.keywordToken === ts.SyntaxKind.ImportKeyword) {
520
+ synth.push(mk(sf, node, 90005,
521
+ "'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."));
522
+ } else if (ts.isIdentifier(node) && withheld.has(node.text)
523
+ && !(node.parent && ts.isPropertyAccessExpression(node.parent) && node.parent.name === node)
524
+ && !(node.parent && (ts.isPropertyAssignment(node.parent) || ts.isPropertySignature(node.parent)) && node.parent.name === node)
525
+ // The SOURCE half of a renamed destructuring is a property of the thing being unpacked,
526
+ // not the global: 'const { Buffer: B } = await import("node:buffer")' is the working
527
+ // form, and firing on it recommended almost exactly the code it was rejecting. The
528
+ // shorthand is already exempt by a different route — there the identifier IS the local
529
+ // declaration, so 'authorDeclared' answers for it.
530
+ && !(node.parent && ts.isBindingElement(node.parent) && node.parent.propertyName === node)
531
+ && !inTypePosition(node)
532
+ && !authorDeclared(node)) {
533
+ synth.push(mk(sf, node, 90005, ADVICE[node.text]
534
+ ?? ("'" + node.text + "' is not defined in a function body — the runner withholds it.")));
535
+ envStarts.add(node.getStart(sf));
536
+ }
537
+ }
538
+ ts.forEachChild(node, function (c) { envVisit(c, sf); });
539
+ };
540
+
325
541
  const skip = new Set();
326
542
  const visit = function (node, sf) {
327
543
  const isAssertion = ts.isAsExpression(node) || (ts.isTypeAssertionExpression && ts.isTypeAssertionExpression(node));
@@ -346,9 +562,60 @@ try {
346
562
  }
347
563
  ts.forEachChild(node, function (c) { visit(c, sf); });
348
564
  };
349
- for (const gf of gateFiles) { visit(gf, gf); contractVisit(gf, gf); }
565
+ for (const gf of gateFiles) { visit(gf, gf); contractVisit(gf, gf); envVisit(gf, gf); }
566
+
567
+ // A bare 'node' is not the builtins namespace — it resolves to @types/node's index.d.ts, which is
568
+ // references and ambient blocks with no export, so tsc reports "File '<matbot's own node_modules>/
569
+ // @types/node/index.d.ts' is not a module": a path the body never named and its author cannot act on.
570
+ // Rewritten only where tsc ALREADY failed on it, so a package genuinely called 'node' is untouched,
571
+ // and only where no gate has spoken at that position, so one mistake stays one finding. It is also what
572
+ // a restriction of ["node"] permits — a package of that name, no builtin — which is why this fires with
573
+ // no restriction in force too.
574
+ for (const d of targets) {
575
+ if (d.code !== 2306 && d.code !== 2307) continue;
576
+ if (importSpecs.get(d.start) !== 'node' || importStarts.has(d.start)) continue;
577
+ synth.push({ file: d.file, start: d.start, length: d.length, code: 90006,
578
+ category: ts.DiagnosticCategory.Error, __syn: true,
579
+ 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." });
580
+ importStarts.add(d.start);
581
+ }
582
+
583
+ // ── TS2591's repair is never actionable in a snippet ──
584
+ // "Cannot find name 'process'. Do you need to install type definitions for node? Try 'npm i --save-dev
585
+ // @types/node'" is tsc telling a function body to run a package manager: there is no package.json to
586
+ // install into, and what a body is typed against is fixed by the runner, not by what happens to be
587
+ // installed. It fires for any global node declares that this configuration did not type — most often
588
+ // 'process', which ENV-GATE does not reach when NO runner is loaded, because then nothing is withheld.
589
+ // The finding is right and only the advice is wrong, so the message is replaced and the position
590
+ // suppressed exactly as a withheld name's is. No list of names here, deliberately: the trigger is
591
+ // tsc's own code, so this cannot drift out of step with what the runner withholds.
592
+ if (envGate) {
593
+ for (const d of targets) {
594
+ if (d.code !== 2591 || !d.file || typeof d.start !== 'number') continue;
595
+ if (envStarts.has(d.start) || importStarts.has(d.start)) continue;
596
+ // tsc raises the same code for an import() of a builtin it has no declarations for, at the
597
+ // specifier — which is a module, not a global, and is repaired differently.
598
+ const spec = importSpecs.get(d.start);
599
+ if (spec !== undefined) {
600
+ synth.push({ file: d.file, start: d.start, length: d.length, code: 90006,
601
+ category: ts.DiagnosticCategory.Error, __syn: true,
602
+ 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." });
603
+ importStarts.add(d.start);
604
+ continue;
605
+ }
606
+ const name = d.file.text.substr(d.start, d.length);
607
+ synth.push({ file: d.file, start: d.start, length: d.length, code: 90005,
608
+ category: ts.DiagnosticCategory.Error, __syn: true,
609
+ 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'." });
610
+ envStarts.add(d.start);
611
+ }
612
+ }
350
613
 
351
- const errors = targets.filter(function (d) { return d.category === ts.DiagnosticCategory.Error; }).concat(synth);
614
+ const errors = targets.filter(function (d) {
615
+ if (d.category !== ts.DiagnosticCategory.Error) return false;
616
+ if ((d.code === 2306 || d.code === 2307 || d.code === 2591) && importStarts.has(d.start)) return false;
617
+ return !((d.code === 2304 || d.code === 2591) && envStarts.has(d.start));
618
+ }).concat(synth);
352
619
  errors.sort(function (a, b) {
353
620
  const fa = a.file ? a.file.fileName : '', fb = b.file ? b.file.fileName : '';
354
621
  return fa < fb ? -1 : fa > fb ? 1 : (a.start || 0) - (b.start || 0);
package/src/index.ts CHANGED
@@ -1,8 +1,8 @@
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, 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
7
  import { buildToolTypesData, compileToolValidators, type ToolTypesData } from './build-dts.js';
8
8
  import { checkSnippetAgainst } from './checker.js';
@@ -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
  }
@@ -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,29 @@ 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
+ ...(restricted !== undefined ? { permittedImports: restricted } : {}),
455
+ // ENV-GATE's list, from the runner that withholds them. Absent with no runner, which is correct:
456
+ // nothing is withheld there either, so there is nothing to reject.
457
+ ...(withheld !== undefined ? { withheldGlobals: withheld } : {}),
271
458
  });
459
+ // Stamped here and nowhere else, from the same two lists that were just passed to the worker, so the
460
+ // fingerprint cannot describe an environment other than the one graded against. Only on a verdict
461
+ // that exists: `checked: false` has nothing to be stale.
462
+ return report.checked ? { ...report, environment: fingerprintOf(runner, settings) } : report;
272
463
  }
273
464
 
274
465
  // Every live tool the source scan didn't already declare: a source-less tool that carries its contract as
@@ -327,3 +518,21 @@ export function createToolTypesPlugin(): MatbotPluginSpec {
327
518
  }
328
519
 
329
520
  export const plugin: MatbotPluginSpec = createToolTypesPlugin();
521
+
522
+
523
+ // Where @types/node declares a builtin. Most have a file of their own, but a few subpaths are declared
524
+ // inside their parent's (`path/posix` in path.d.ts, `util/types` in util.d.ts, `test/reporters` in
525
+ // test.d.ts), and skipping those left a module the gate admits failing the check. The parent is taken
526
+ // only if it actually declares the module under one spelling or the other, so a builtin @types/node
527
+ // knows nothing about still gets no entry rather than a path that types something else.
528
+ function declarationFile(nodeTypes: string, bare: string): string | undefined {
529
+ const own = join(nodeTypes, `${bare}.d.ts`);
530
+ if (existsSync(own)) return own;
531
+ const slash = bare.indexOf('/');
532
+ if (slash < 0) return undefined;
533
+ const parent = join(nodeTypes, `${bare.slice(0, slash)}.d.ts`);
534
+ if (!existsSync(parent)) return undefined;
535
+ const text = readFileSync(parent, 'utf8');
536
+ return [bare, `node:${bare}`].some(m => text.includes(`declare module "${m}"`) || text.includes(`declare module '${m}'`))
537
+ ? parent : undefined;
538
+ }