@matatbread/matbot-tool-types 0.4.20 → 0.4.25

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.20",
6
+ "version": "0.4.25",
7
7
  "engines": {
8
8
  "node": ">=24.0.0"
9
9
  },
@@ -37,13 +37,13 @@
37
37
  "typescript": "^6.0.3"
38
38
  },
39
39
  "peerDependencies": {
40
- "@matatbread/matbot-core": "^0.4.20",
41
- "@matatbread/matbot-plugin-api": "^0.4.20"
40
+ "@matatbread/matbot-plugin-api": "^0.4.25",
41
+ "@matatbread/matbot-core": "^0.4.25"
42
42
  },
43
43
  "devDependencies": {
44
44
  "typescript": "^6.0.3",
45
- "@matatbread/matbot-core": "^0.4.20",
46
- "@matatbread/matbot-plugin-api": "^0.4.20"
45
+ "@matatbread/matbot-plugin-api": "^0.4.25",
46
+ "@matatbread/matbot-core": "^0.4.25"
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
@@ -114,7 +114,7 @@ const MAX_FULL = 8;
114
114
  // A structural rule's label, by its private code. CAST-GATE is the default because it was the first and
115
115
  // is what the contract gate (90004) has always reported as; a rule about something other than types
116
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' };
117
+ const SYN_LABELS: Record<number, string> = { 90005: 'ENV-GATE', 90006: 'IMPORT-GATE', 90007: 'ESCAPE-GATE' };
118
118
 
119
119
  // One rule, one name, in every renderer: a per-rule label read off the record rather than spelled at
120
120
  // each render site, so a summary can never call a finding something its own entry did not.
@@ -240,6 +240,10 @@ export async function checkSnippetAgainst(opts: {
240
240
  * permitted module, so a module outside the set does not resolve and is a compile error rather than
241
241
  * something that typechecks and is refused at run time. Built by the caller, which knows the set. */
242
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[];
243
247
  /** The restriction itself, when there is one — `paths` cannot enforce it. Loading ONE builtin's
244
248
  * declaration file pulls in the ambient `declare module 'node:…'` blocks of everything its own
245
249
  * declarations reference (`node:fs` reaches `node:stream`, which reaches most of the rest), so a
@@ -262,6 +266,7 @@ export async function checkSnippetAgainst(opts: {
262
266
  virtualPath: `${opts.root}/__mb_toolcheck_${crypto.randomUUID()}.ts`,
263
267
  ...(opts.apiIndexPath !== undefined ? { apiIndexPath: opts.apiIndexPath } : {}),
264
268
  ...(opts.importPaths !== undefined ? { importPaths: opts.importPaths } : {}),
269
+ ...(opts.globalTypes !== undefined ? { globalTypes: opts.globalTypes } : {}),
265
270
  ...(opts.permittedImports !== undefined ? { permittedImports: opts.permittedImports } : {}),
266
271
  ...(opts.withheldGlobals !== undefined ? { withheldGlobals: opts.withheldGlobals } : {}),
267
272
  });
@@ -336,7 +341,7 @@ try {
336
341
  };
337
342
  const fe = host.fileExists.bind(host); host.fileExists = function (f) { return f === virtual || fe(f); };
338
343
  const rf = host.readFile.bind(host); host.readFile = function (f) { return f === virtual ? source : rf(f); };
339
- program = ts.createProgram([virtual], options, host);
344
+ program = ts.createProgram([virtual].concat(workerData.globalTypes ?? []), options, host);
340
345
  const sf = program.getSourceFile(virtual);
341
346
  targets = sf
342
347
  ? [].concat(program.getSyntacticDiagnostics(sf)).concat(program.getSemanticDiagnostics(sf))
@@ -406,8 +411,8 @@ try {
406
411
  //
407
412
  // WHICH names are withheld comes from the runner's withheldGlobals, because it is the only thing that
408
413
  // 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.
414
+ // fails at the first call, which is the one failure this gate exists to prevent. 'eval' is the worst
415
+ // to miss, being a lib.es global that typechecks in every configuration.
411
416
  //
412
417
  // The ADVICE stays here, because it is about repairing a snippet and that is this file's job, not the
413
418
  // runner's. A withheld name with no entry below still fires, with a generic line — the list is the
@@ -419,11 +424,9 @@ try {
419
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.",
420
425
  __filename: "'__filename' is not defined in a function body. There is no file — the body is compiled from source held in the session.",
421
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.",
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
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'.",
424
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'.",
425
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>(…)'.",
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
430
  };
428
431
  // A withheld global named in a TYPE is harmless: types are erased before the body is compiled, so
429
432
  // 'args: Buffer' never reaches the runner. Only the VALUE is rejected. Needed because the second half of
@@ -538,6 +541,103 @@ try {
538
541
  ts.forEachChild(node, function (c) { envVisit(c, sf); });
539
542
  };
540
543
 
544
+ // ── escape gate: what reaches past the runner without naming anything it withholds ──
545
+ // Shadowing works on NAMES, and these are not names: every function's '.constructor' is a compiler for
546
+ // the global scope, where the real 'process' and every ungated builtin are; 'getBuiltinModule' loads a
547
+ // builtin with no import to gate; and a shared object a body changes — a built-in, its prototype, or
548
+ // something it was handed — is changed for the rest of matbot. The runner refuses the first two at run
549
+ // time however they are reached, and cannot refuse the third, so this is where a plainly-spelled one is
550
+ // stopped and the author told why. A computed spelling gets past it; that is deliberate tampering,
551
+ // which no checker is the answer to. Only with a runner: without one nothing is refused, and saying so
552
+ // would be untrue.
553
+ const escapeGate = envGate && workerData.withheldGlobals !== undefined;
554
+ const ESCAPE = {
555
+ ctor: "a function's 'constructor' compiles a string as code in matbot's own scope — outside the runner, around every withheld global and permission gate — so a function body may not reach it, and it is refused at run time too. Write the code directly, import a module with 'await import(…)' (the user is asked), or call a tool.",
556
+ Function: "'Function' compiles a string as code in matbot's own scope — outside the runner, around every withheld global and permission gate — so a function body may not call it, and it is refused at run time too. Write the code directly. (As a TYPE annotation it is fine; this is about the value.)",
557
+ builtin: "'getBuiltinModule' loads a node builtin without the import gate, so a function body may not call it, and it is refused at run time too. Import the module with 'await import('node:…')', which asks the user.",
558
+ proto: "'__proto__' reaches a prototype shared with the rest of matbot, which a function body may neither reach nor change. For an object with a prototype of your own, use 'Object.create(proto)' or a class.",
559
+ mutate: function (what) {
560
+ return "this changes '" + what + "', which this function body did not create. Built-ins, their prototypes and what a body is handed are shared with the rest of matbot, so changing them changes matbot. Work on a copy ('const mine = { ...x }') or a wrapper of your own instead.";
561
+ },
562
+ };
563
+ const unwrap = function (e) {
564
+ while (e && (ts.isParenthesizedExpression(e) || ts.isNonNullExpression(e) || ts.isAsExpression(e)
565
+ || (ts.isTypeAssertionExpression && ts.isTypeAssertionExpression(e)) || ts.isSatisfiesExpression(e))) e = e.expression;
566
+ return e;
567
+ };
568
+ const memberName = function (e) {
569
+ if (ts.isPropertyAccessExpression(e)) return e.name.text;
570
+ if (ts.isElementAccessExpression(e) && ts.isStringLiteralLike(e.argumentExpression)) return e.argumentExpression.text;
571
+ return undefined;
572
+ };
573
+ const isGetPrototypeOf = function (e) {
574
+ return ts.isCallExpression(e) && ts.isPropertyAccessExpression(e.expression) && e.expression.name.text === 'getPrototypeOf';
575
+ };
576
+ // Whether an object a body is about to change is one it did not create: reached through a prototype,
577
+ // or rooted at a binding declared outside the snippet (a built-in, or 'tool' / 'context').
578
+ const shared = function (target) {
579
+ let e = unwrap(target);
580
+ for (;;) {
581
+ if (isGetPrototypeOf(e)) return true;
582
+ if (ts.isPropertyAccessExpression(e) || ts.isElementAccessExpression(e)) {
583
+ const n = memberName(e);
584
+ if (n === 'prototype' || n === '__proto__') return true;
585
+ e = unwrap(e.expression);
586
+ continue;
587
+ }
588
+ if (!ts.isIdentifier(e)) return false;
589
+ const sym = checker.getSymbolAtLocation(e);
590
+ return !!(sym && sym.declarations && sym.declarations.length > 0) && !authorDeclared(e);
591
+ }
592
+ };
593
+ const isCallable = function (e) {
594
+ const t = checker.getTypeAtLocation(e);
595
+ return t.getCallSignatures().length > 0 || t.getConstructSignatures().length > 0;
596
+ };
597
+ const MUTATORS = { Object: ['defineProperty', 'defineProperties', 'setPrototypeOf', 'assign'],
598
+ Reflect: ['defineProperty', 'set', 'setPrototypeOf', 'deleteProperty'] };
599
+ const isAssignment = function (k) {
600
+ return k >= ts.SyntaxKind.FirstAssignment && k <= ts.SyntaxKind.LastAssignment;
601
+ };
602
+ const escapeVisit = function (node, sf) {
603
+ if (escapeGate && node.getStart(sf) >= minStart) {
604
+ const name = (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) ? memberName(node) : undefined;
605
+ if (name === 'constructor') {
606
+ const obj = unwrap(node.expression);
607
+ if (isCallable(obj) || memberName(obj) === 'constructor') synth.push(mk(sf, node, 90007, ESCAPE.ctor));
608
+ } else if (name === 'getBuiltinModule') {
609
+ synth.push(mk(sf, node, 90007, ESCAPE.builtin));
610
+ } else if (name === '__proto__') {
611
+ synth.push(mk(sf, node, 90007, ESCAPE.proto));
612
+ } else if (ts.isIdentifier(node) && node.text === 'Function'
613
+ && !(node.parent && ts.isPropertyAccessExpression(node.parent) && node.parent.name === node)
614
+ && !(node.parent && (ts.isPropertyAssignment(node.parent) || ts.isPropertySignature(node.parent)) && node.parent.name === node)
615
+ && !(node.parent && ts.isBindingElement(node.parent) && node.parent.propertyName === node)
616
+ && !inTypePosition(node) && !authorDeclared(node)) {
617
+ synth.push(mk(sf, node, 90007, ESCAPE.Function));
618
+ }
619
+ let changed;
620
+ if (ts.isBinaryExpression(node) && isAssignment(node.operatorToken.kind)) changed = node.left;
621
+ else if ((ts.isPrefixUnaryExpression(node) || ts.isPostfixUnaryExpression(node))
622
+ && (node.operator === ts.SyntaxKind.PlusPlusToken || node.operator === ts.SyntaxKind.MinusMinusToken)) changed = node.operand;
623
+ else if (ts.isDeleteExpression(node)) changed = node.expression;
624
+ else if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression)
625
+ && ts.isIdentifier(node.expression.expression) && node.arguments.length > 0) {
626
+ const ns = MUTATORS[node.expression.expression.text];
627
+ if (ns && ns.indexOf(node.expression.name.text) !== -1 && !authorDeclared(node.expression.expression)) changed = node.arguments[0];
628
+ }
629
+ if (changed !== undefined) {
630
+ const c = unwrap(changed);
631
+ // Only a member: assigning a name rebinds the body's own variable, which shadowing makes harmless.
632
+ const member = ts.isPropertyAccessExpression(c) || ts.isElementAccessExpression(c);
633
+ if ((member && shared(c.expression)) || (!member && ts.isCallExpression(node) && shared(c))) {
634
+ synth.push(mk(sf, changed, 90007, ESCAPE.mutate(c.getText(sf))));
635
+ }
636
+ }
637
+ }
638
+ ts.forEachChild(node, function (c) { escapeVisit(c, sf); });
639
+ };
640
+
541
641
  const skip = new Set();
542
642
  const visit = function (node, sf) {
543
643
  const isAssertion = ts.isAsExpression(node) || (ts.isTypeAssertionExpression && ts.isTypeAssertionExpression(node));
@@ -562,7 +662,7 @@ try {
562
662
  }
563
663
  ts.forEachChild(node, function (c) { visit(c, sf); });
564
664
  };
565
- for (const gf of gateFiles) { visit(gf, gf); contractVisit(gf, gf); envVisit(gf, gf); }
665
+ for (const gf of gateFiles) { visit(gf, gf); contractVisit(gf, gf); envVisit(gf, gf); escapeVisit(gf, gf); }
566
666
 
567
667
  // A bare 'node' is not the builtins namespace — it resolves to @types/node's index.d.ts, which is
568
668
  // references and ambient blocks with no export, so tsc reports "File '<matbot's own node_modules>/
package/src/index.ts CHANGED
@@ -1,10 +1,10 @@
1
1
  import { dirname, join, resolve } from 'node:path';
2
2
  import { existsSync, readFileSync } from 'node:fs';
3
3
  import { createRequire } from 'node:module';
4
- import { PLUGIN_API_VERSION, RegistryChangeKind, importPermitted, importableByName } from '@matatbread/matbot-plugin-api';
4
+ import { PLUGIN_API_VERSION, RegistryChangeKind, contractArms, importPermitted, importableByName } from '@matatbread/matbot-plugin-api';
5
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. */
@@ -230,9 +230,9 @@ export class ToolTypeIndexImpl implements ToolTypeIndex {
230
230
  // which they were described to the model in full and then enforced only by their loose
231
231
  // `inputSchema`, which is backwards: their params were authored by an LLM, not a compiler.
232
232
  const live = this.machine.tools.list();
233
- const synthetic = Object.fromEntries(
234
- live.flatMap(t => (t.toolContract !== undefined ? [[t.name, t.toolContract] as const] : [])),
235
- );
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
+ : [])));
236
236
  const built = await this.fill({
237
237
  projectRoot: root, pluginEntryUrls: urls, liveToolNames: live.map(t => t.name), syntheticContracts: synthetic,
238
238
  });
@@ -401,6 +401,7 @@ export class ToolTypeIndexImpl implements ToolTypeIndex {
401
401
  return `${note}`
402
402
  + (withheld.length > 0
403
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
+ + `// Nor can it build code from a string: 'Function' and every function's '.constructor' refuse a body.\n`
404
405
  : '');
405
406
  }
406
407
 
@@ -451,6 +452,7 @@ export class ToolTypeIndexImpl implements ToolTypeIndex {
451
452
  prefixLines: prefix.split('\n').length - 1,
452
453
  ...(apiIndex !== undefined ? { apiIndexPath: apiIndex } : {}),
453
454
  ...(Object.keys(importPaths).length > 0 ? { importPaths } : {}),
455
+ globalTypes: nodeGlobalTypes(),
454
456
  ...(restricted !== undefined ? { permittedImports: restricted } : {}),
455
457
  // ENV-GATE's list, from the runner that withholds them. Absent with no runner, which is correct:
456
458
  // nothing is withheld there either, so there is nothing to reject.
@@ -473,13 +475,12 @@ export class ToolTypeIndexImpl implements ToolTypeIndex {
473
475
  // top-of-file import the derived block emits (every arm references it); when the scan produced nothing to
474
476
  // import it (no source resolved, or an all-`MatbotServices` block), this block supplies that one import.
475
477
  private registryBlock(derived: string): string {
476
- const arms: string[] = [];
477
- for (const t of this.machine.tools.list()) {
478
- if (this.covered.has(t.name)) continue;
479
- arms.push(` ${JSON.stringify(t.name)}: ${t.toolContract ?? `ToolContract<unknown, ${schemaToTs(t.inputSchema)}>`};`);
480
- }
478
+ const { preamble, arms: armOf } = contractArms(this.machine.tools.list().filter(t => !this.covered.has(t.name)).map(t => ({
479
+ name: t.name, contract: t.toolContract ?? `ToolContract<unknown, ${schemaToTs(t.inputSchema)}>`, types: t.toolContractTypes,
480
+ })));
481
+ const arms = [...armOf].map(([name, arm]) => ` ${JSON.stringify(name)}: ${arm};`);
481
482
  if (arms.length === 0) return derived;
482
- const body = arms.join('\n');
483
+ const body = preamble + arms.join('\n');
483
484
  // Import the plugin-api types these arms reference — `ToolContract` always, plus any plugin-api export a
484
485
  // source-less `toolContract` names (e.g. `StoreQuery`) — minus whatever the derived block already imports
485
486
  // (importing a name twice is a redeclaration error). A synthetic tool inlines its own shape types, so the
@@ -493,7 +494,7 @@ export class ToolTypeIndexImpl implements ToolTypeIndex {
493
494
  const head = needed.length
494
495
  ? `${derived === '' ? "import '@matatbread/matbot-plugin-api';\n" : ''}import type { ${needed.join(', ')} } from '@matatbread/matbot-plugin-api';\n`
495
496
  : '';
496
- return `${head}${derived}\ndeclare module '@matatbread/matbot-plugin-api' {\n interface ToolContracts {\n${body}\n }\n}\n`;
497
+ return `${head}${derived}\n${preamble}declare module '@matatbread/matbot-plugin-api' {\n interface ToolContracts {\n${arms.join('\n')}\n }\n}\n`;
497
498
  }
498
499
 
499
500
  async toolValidators(): Promise<Record<string, ToolValidator>> {
@@ -520,6 +521,15 @@ export function createToolTypesPlugin(): MatbotPluginSpec {
520
521
  export const plugin: MatbotPluginSpec = createToolTypesPlugin();
521
522
 
522
523
 
524
+ // The node globals a body has that the standard library does not declare: `Buffer`, and its overloads in
525
+ // buffer.buffer.d.ts. The rest of what a body is given (`fetch`, the timers, `console`, `TextEncoder`,
526
+ // `atob`) is in lib.dom. Loaded whether or not the runner withholds it, since ENV-GATE rejects a withheld
527
+ // name either way, and with no runner a body really has it.
528
+ function nodeGlobalTypes(): string[] {
529
+ const nodeTypes = dirname(createRequire(import.meta.url).resolve('@types/node/package.json'));
530
+ return ['buffer.buffer.d.ts', 'buffer.d.ts'].map(f => join(nodeTypes, f)).filter(f => existsSync(f));
531
+ }
532
+
523
533
  // Where @types/node declares a builtin. Most have a file of their own, but a few subpaths are declared
524
534
  // inside their parent's (`path/posix` in path.d.ts, `util/types` in util.d.ts, `test/reporters` in
525
535
  // test.d.ts), and skipping those left a module the gate admits failing the check. The parent is taken