@matatbread/matbot-tool-types 0.4.13 → 0.4.17

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.13",
6
+ "version": "0.4.17",
7
7
  "engines": {
8
8
  "node": ">=24.0.0"
9
9
  },
@@ -36,14 +36,14 @@
36
36
  "typescript": "^6.0.3"
37
37
  },
38
38
  "peerDependencies": {
39
- "@matatbread/matbot-plugin-api": "^0.4.14",
40
- "@matatbread/matbot-core": "^0.4.14"
39
+ "@matatbread/matbot-plugin-api": "^0.4.17",
40
+ "@matatbread/matbot-core": "^0.4.17"
41
41
  },
42
42
  "devDependencies": {
43
43
  "@types/node": "^22.0.0",
44
44
  "typescript": "^6.0.3",
45
- "@matatbread/matbot-core": "^0.4.14",
46
- "@matatbread/matbot-plugin-api": "^0.4.14"
45
+ "@matatbread/matbot-plugin-api": "^0.4.17",
46
+ "@matatbread/matbot-core": "^0.4.17"
47
47
  },
48
48
  "scripts": {
49
49
  "typecheck": "tsc --noEmit"
package/src/build-dts.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type TS from 'typescript';
2
- import { buildToolValidator, type ToolValidator } from './validator.js';
2
+ import { compileToolValidator, generateValidator, type ToolValidator, type ValidatorSource } from './validator.js';
3
3
 
4
4
  // Derive a self-contained `declare module … { interface ToolContracts {…} interface MatbotServices {…} }`
5
5
  // from the live type graph, so a compiled (or hand-rolled) plugin's compilation sees correct types for
@@ -24,9 +24,10 @@ import { buildToolValidator, type ToolValidator } from './validator.js';
24
24
  // For `MatbotServices` only the plugin-contributed members are emitted; the base members (`Vault`,
25
25
  // `StorageBackend?`, `KnowledgeIndex`) are already visible through plugin-api.
26
26
  //
27
- // Caveat: `ts.createProgram` over the workspace runs in-process and briefly blocks the event loop.
28
- // Acceptable once-per-compile; the planned coverage work (drive off the live loaded-plugin set, build
29
- // lazily + dirty on plugin load) also removes that cost. Coverage today is the monorepo `plugins/` tree.
27
+ // Caveat: `ts.createProgram` over the scanned roots runs in-process, synchronously — about 2 s of blocked
28
+ // event loop on a one-CPU host — paid by whichever caller first needs the index (a tool call's validator,
29
+ // a turn's wire contracts), and again after any tool registry change. The index shares one build among
30
+ // callers that meet; `@matatbread/matbot-caching-tool-types` carries a build over from one process to the next.
30
31
 
31
32
  /**
32
33
  * A registry key declared more than once, with DIFFERENT types, across the scanned files. Declaration
@@ -62,7 +63,7 @@ export interface MatbotToolsDts {
62
63
  // RESOLVED type in this same pass — so conditionals/generics/`Omit` are already evaluated and no
63
64
  // second `ts.Program` is ever built. A contract that cannot be honestly validated yields
64
65
  // `{ refused }` rather than a permissive validator — and those refusals are the census of what the
65
- // typed path does not cover. The emitted TEXT is not carried: `generateValidator` regenerates it.
66
+ // typed path does not cover.
66
67
  validators: Record<string, ToolValidator>;
67
68
  // The names of every plugin-api type export. A source-less tool's `toolContract` string may name one
68
69
  // (e.g. `StoreQuery`); the consumer (ToolTypeIndex) uses this to import the ones it references so those
@@ -70,6 +71,28 @@ export interface MatbotToolsDts {
70
71
  apiExports: string[];
71
72
  }
72
73
 
74
+ /**
75
+ * A build as plain data: {@link MatbotToolsDts} with each validator as its SOURCE, plus every file the
76
+ * build read. Serialisable by construction, so a build can be kept beyond the process that made it; what
77
+ * it depends on is exactly its arguments, tool-types itself, and the content of `files`.
78
+ */
79
+ export interface ToolTypesData extends Omit<MatbotToolsDts, 'validators'> {
80
+ validators: Record<string, ValidatorSource>;
81
+ /** `dts` in pieces, one per tool, so {@link filterToolTypesData} can narrow it without a rebuild. */
82
+ dtsParts: DtsParts;
83
+ /** Every source file either Program read (lib files, plugin-api, each root and what it imports). */
84
+ files: string[];
85
+ }
86
+
87
+ export interface DtsParts {
88
+ /** Everything before the `ToolContracts` block: imports, bundled declarations, the module opener. */
89
+ head: string;
90
+ /** Each tool's `ToolContracts` member line, by tool name, in emit order. */
91
+ tools: Record<string, string>;
92
+ /** Everything after it: `MatbotServices`, re-emitted augmentations, the closing brace. */
93
+ tail: string;
94
+ }
95
+
73
96
  type Classification =
74
97
  | { tag: 'ignore' }
75
98
  | { tag: 'lib' }
@@ -77,34 +100,19 @@ type Classification =
77
100
  | { tag: 'bundle'; sym: TS.Symbol }
78
101
  | { tag: 'bail'; label: string };
79
102
 
80
- // `pluginEntryUrls` are the resolved import URLs of the LIVE loaded plugins (each plugin's `resolvedUrl`,
81
- // via the `plugin` tool's `list`). Each entry is used as a Program root: it pulls in that plugin's own
82
- // augmenting files transitively, so coverage follows the actual loaded set (npm / `.plugins/` / local),
83
- // not just the monorepo tree. When none resolve to on-disk source, falls back to globbing the monorepo
84
- // `plugins/` tree. Returns null when neither yields anything (the caller then uses its static DTS).
85
- //
86
- // `liveToolNames` is the live tool registry (`machine.tools.list()`), and it is what makes the emitted
87
- // `ToolContracts` a description of what a generator can actually CALL rather than of what happens to be on
88
- // disk: the roots are a superset of the loaded set by construction (see the glob below), so a name absent
89
- // from the registry is declared, typed, and uncallable — `tool.telegram_send(…)` typechecks clean and
90
- // throws "not registered" at runtime, which is the one failure the check gate exists to prevent. Omit it
91
- // only when the caller genuinely wants the whole scanned tree (the clash census test); the registry is not
92
- // optional information for anything that shows the dts to a model.
93
- // `syntheticContracts` maps a tool name to its `toolContract` STRING — the form a tool built at runtime
94
- // must use, having no source to carry a `ToolContracts` augmentation (`function-tools`' generated
95
- // functions, `tool-store`'s per-namespace tools). They are rendered into one virtual augmentation file
96
- // added to THIS Program, so declaration merging puts them in the same `ToolContracts` as every scanned
97
- // arm and the validator generator below reaches them with no second code path and no second Program.
98
- //
99
- // They are then held OUT of the emitted dts and out of `contracts`: the caller splices those verbatim
100
- // from the same strings (`registryBlock`, `splitContract`), which is what the model already sees, and
101
- // re-deriving that text from the resolved type would change it — expanding an alias the author wrote
102
- // deliberately — for no gain. So this argument buys exactly one thing: the validators.
103
- export async function buildMatbotToolsDts(
104
- projectRoot: string, pluginEntryUrls?: readonly string[], liveToolNames?: readonly string[],
105
- syntheticContracts?: Readonly<Record<string, string>>,
106
- ): Promise<MatbotToolsDts | null> {
107
- const ts = (await import('typescript')).default as typeof TS;
103
+ export interface ToolTypeRoots {
104
+ /** The plugin-api entry every build is anchored on; always `roots[0]`. */
105
+ pluginApiIndex: string;
106
+ /** The Program's root files, in the order the Program is given them — which is the order declaration
107
+ * merging sees, so it decides a `conflicts` winner and is part of what a build depends on. */
108
+ roots: string[];
109
+ }
110
+
111
+ /** What a build of `pluginEntryUrls` would scan, without building it. Null when there is nothing to scan
112
+ * beyond plugin-api, or plugin-api itself cannot be found. */
113
+ export async function collectToolTypeRoots(
114
+ projectRoot: string, pluginEntryUrls?: readonly string[],
115
+ ): Promise<ToolTypeRoots | null> {
108
116
  const { readFileSync, readdirSync, statSync, existsSync } = await import('node:fs');
109
117
  const { join } = await import('node:path');
110
118
  const { fileURLToPath } = await import('node:url');
@@ -186,6 +194,41 @@ export async function buildMatbotToolsDts(
186
194
  walk(join(projectRoot, 'plugins'));
187
195
  }
188
196
  if (roots.size === 1) return null; // nothing to scan beyond plugin-api itself
197
+ return { pluginApiIndex, roots: [...roots] };
198
+ }
199
+
200
+ // `pluginEntryUrls` are the resolved import URLs of the LIVE loaded plugins (each plugin's `resolvedUrl`,
201
+ // via the `plugin` tool's `list`). Each entry is used as a Program root: it pulls in that plugin's own
202
+ // augmenting files transitively, so coverage follows the actual loaded set (npm / `.plugins/` / local),
203
+ // not just the monorepo tree. When none resolve to on-disk source, falls back to globbing the monorepo
204
+ // `plugins/` tree. Returns null when neither yields anything (the caller then uses its static DTS).
205
+ //
206
+ // `liveToolNames` is the live tool registry (`machine.tools.list()`), and it is what makes the emitted
207
+ // `ToolContracts` a description of what a generator can actually CALL rather than of what happens to be on
208
+ // disk: the roots are a superset of the loaded set by construction (see the glob below), so a name absent
209
+ // from the registry is declared, typed, and uncallable — `tool.telegram_send(…)` typechecks clean and
210
+ // throws "not registered" at runtime, which is the one failure the check gate exists to prevent. Omit it
211
+ // only when the caller genuinely wants the whole scanned tree (the clash census test); the registry is not
212
+ // optional information for anything that shows the dts to a model.
213
+ // `syntheticContracts` maps a tool name to its `toolContract` STRING — the form a tool built at runtime
214
+ // must use, having no source to carry a `ToolContracts` augmentation (`function-tools`' generated
215
+ // functions, `tool-store`'s per-namespace tools). They are rendered into one virtual augmentation file
216
+ // added to THIS Program, so declaration merging puts them in the same `ToolContracts` as every scanned
217
+ // arm and the validator generator below reaches them with no second code path and no second Program.
218
+ //
219
+ // They are then held OUT of the emitted dts and out of `contracts`: the caller splices those verbatim
220
+ // from the same strings (`registryBlock`, `splitContract`), which is what the model already sees, and
221
+ // re-deriving that text from the resolved type would change it — expanding an alias the author wrote
222
+ // deliberately — for no gain. So this argument buys exactly one thing: the validators.
223
+ export async function buildToolTypesData(
224
+ projectRoot: string, pluginEntryUrls?: readonly string[], liveToolNames?: readonly string[],
225
+ syntheticContracts?: Readonly<Record<string, string>>,
226
+ ): Promise<ToolTypesData | null> {
227
+ const ts = (await import('typescript')).default as typeof TS;
228
+ const { join } = await import('node:path');
229
+ const found = await collectToolTypeRoots(projectRoot, pluginEntryUrls);
230
+ if (!found) return null;
231
+ const { pluginApiIndex, roots } = found;
189
232
 
190
233
  const options: TS.CompilerOptions = {
191
234
  target: ts.ScriptTarget.ES2022,
@@ -197,8 +240,9 @@ export async function buildMatbotToolsDts(
197
240
  skipLibCheck: true,
198
241
  baseUrl: projectRoot,
199
242
  };
200
- const program = ts.createProgram([...roots], options);
243
+ const program = ts.createProgram(roots, options);
201
244
  const checker = program.getTypeChecker();
245
+ const files = new Set(program.getSourceFiles().map(f => f.fileName));
202
246
 
203
247
  const apiSf = program.getSourceFile(pluginApiIndex)
204
248
  ?? program.getSourceFiles().find(f => f.fileName.includes('/plugin-api/') && /\/index\.d?\.ts$/.test(f.fileName));
@@ -225,8 +269,8 @@ export async function buildMatbotToolsDts(
225
269
  * by the caller and are what the model already reads; re-deriving them from the resolved type would
226
270
  * expand an alias the author wrote deliberately, for no gain.
227
271
  */
228
- const syntheticValidators = (): Record<string, ToolValidator> => {
229
- const out: Record<string, ToolValidator> = {};
272
+ const syntheticValidators = (): Record<string, ValidatorSource> => {
273
+ const out: Record<string, ValidatorSource> = {};
230
274
  const usable: Record<string, string> = {};
231
275
 
232
276
  // Screened one at a time, BEFORE any is rendered into the shared file: they become properties of one
@@ -269,6 +313,7 @@ export async function buildMatbotToolsDts(
269
313
  ...options, paths: { '@matatbread/matbot-plugin-api': [pluginApiIndex] },
270
314
  }, host);
271
315
  const chk = prog.getTypeChecker();
316
+ for (const f of prog.getSourceFiles()) if (f.fileName !== virtualPath) files.add(f.fileName);
272
317
  const sf = prog.getSourceFile(virtualPath);
273
318
  if (!sf) return out;
274
319
 
@@ -318,7 +363,7 @@ export async function buildMatbotToolsDts(
318
363
  paramNodes.push(a.typeArguments[1]!);
319
364
  }
320
365
  out[name] = ok
321
- ? buildToolValidator(ts, chk, paramNodes.map(nd => chk.getTypeFromTypeNode(nd)), ann, { excessProperties: 'reject' })
366
+ ? generateValidator(ts, chk, paramNodes.map(nd => chk.getTypeFromTypeNode(nd)), ann, { excessProperties: 'reject' })
322
367
  : { refused: 'toolContract is not `ToolContract<Result, Args>` (or a union of those)' };
323
368
  }
324
369
  }
@@ -479,10 +524,11 @@ export async function buildMatbotToolsDts(
479
524
  // `emitNode` runs and its referenced types are never bundled or imported either.
480
525
  const emitInterface = (
481
526
  interfaceName: string, onlyAugmented: boolean, only?: ReadonlySet<string>,
482
- ): { lines: string[]; emitted: string[]; unknown: string[] } => {
527
+ ): { lines: string[]; named: Record<string, string>; emitted: string[]; unknown: string[] } => {
483
528
  const sym = findCanonicalSymbol(interfaceName);
484
529
  const lines: string[] = [], emitted: string[] = [], unknownNames: string[] = [];
485
- if (!sym) return { lines, emitted, unknown: unknownNames };
530
+ const named: Record<string, string> = {};
531
+ if (!sym) return { lines, named, emitted, unknown: unknownNames };
486
532
  const props = [...checker.getPropertiesOfType(checker.getDeclaredTypeOfSymbol(sym))].sort((a, b) => a.name.localeCompare(b.name));
487
533
  for (const prop of props) {
488
534
  if (onlyAugmented && inPluginApi(prop)) continue;
@@ -491,25 +537,25 @@ export async function buildMatbotToolsDts(
491
537
  const decl = (prop.declarations ?? []).find(d => ts.isPropertySignature(d));
492
538
  const ann = decl && ts.isPropertySignature(decl) ? decl.type : undefined;
493
539
  if (!ann) {
494
- lines.push(` ${prop.name}${optional}: ${unknownOf('no type annotation')};`);
540
+ lines.push(named[prop.name] = ` ${prop.name}${optional}: ${unknownOf('no type annotation')};`);
495
541
  unknownNames.push(prop.name);
496
542
  continue;
497
543
  }
498
544
  const ctx: Ctx = { imports: new Set(), seen: new Set(), heritageBail: null };
499
545
  const text = emitNode(ann, ctx);
500
546
  if (ctx.heritageBail) { // can't substitute in `extends` — whole member unknown
501
- lines.push(` ${prop.name}${optional}: ${unknownOf(ctx.heritageBail)};`);
547
+ lines.push(named[prop.name] = ` ${prop.name}${optional}: ${unknownOf(ctx.heritageBail)};`);
502
548
  unknownNames.push(prop.name);
503
549
  continue;
504
550
  }
505
551
  ctx.imports.forEach(n => importNames.add(n));
506
- lines.push(` ${prop.name}${optional}: ${text};`);
552
+ lines.push(named[prop.name] = ` ${prop.name}${optional}: ${text};`);
507
553
  // A member whose own annotation was entirely replaced is effectively unknown; one with only nested
508
554
  // substitutions is still a usable typed surface.
509
555
  if (/^unknown\b/.test(text.trim())) unknownNames.push(prop.name);
510
556
  else emitted.push(prop.name);
511
557
  }
512
- return { lines, emitted, unknown: unknownNames };
558
+ return { lines, named, emitted, unknown: unknownNames };
513
559
  };
514
560
 
515
561
  // A tool the registry doesn't hold isn't a tool. `MatbotServices` takes no such filter: a member there is
@@ -712,7 +758,7 @@ export async function buildMatbotToolsDts(
712
758
  return { result: results.join(' | '), params: params.join(' | '), paramNodes };
713
759
  };
714
760
  const contracts: Record<string, { params: string; result: string }> = {};
715
- const validators: Record<string, ToolValidator> = {};
761
+ const validators: Record<string, ValidatorSource> = {};
716
762
  const toolContractsSym = findCanonicalSymbol('ToolContracts');
717
763
  if (toolContractsSym) {
718
764
  for (const prop of checker.getPropertiesOfType(checker.getDeclaredTypeOfSymbol(toolContractsSym))) {
@@ -730,7 +776,7 @@ export async function buildMatbotToolsDts(
730
776
  // most common tool-call hallucination into an error the model can repair. It also makes `NoParams`
731
777
  // consistent rather than accidentally special: `Record<string, never>` already refuses every key,
732
778
  // via its index signature's `never`, so without this a closed contract was the LOOSER of the two.
733
- validators[prop.name] = buildToolValidator(
779
+ validators[prop.name] = generateValidator(
734
780
  ts, checker, c.paramNodes.map(nd => checker.getTypeFromTypeNode(nd)), ann,
735
781
  { excessProperties: 'reject' },
736
782
  );
@@ -742,22 +788,67 @@ export async function buildMatbotToolsDts(
742
788
  // for a tool it also registers dynamically, and then the compiler-checked one is the truth.
743
789
  for (const [name, v] of Object.entries(syntheticValidators())) validators[name] ??= v;
744
790
 
745
- const block = (name: string, lines: string[]): string =>
746
- lines.length ? ` interface ${name} {\n${lines.join('\n')}\n }\n` : '';
747
791
  const imports = [...importNames].filter(n => apiTypeNames.has(n)).sort();
748
792
  const importLine = imports.length ? `import type { ${imports.join(', ')} } from '@matatbread/matbot-plugin-api';\n` : '';
749
793
  const bundleBlock = bundledDecls.size ? `${[...bundledDecls.values()].join('\n\n')}\n\n` : '';
750
- const dts = `import '@matatbread/matbot-plugin-api';
751
- ${importLine}${bundleBlock}declare module '@matatbread/matbot-plugin-api' {
752
- ${block('ToolContracts', tools.lines)}${block('MatbotServices', services.lines)}${augmentations.length ? `${augmentations.join('\n')}\n` : ''}}
753
- `;
794
+ const dtsParts: DtsParts = {
795
+ head: `import '@matatbread/matbot-plugin-api';\n${importLine}${bundleBlock}declare module '@matatbread/matbot-plugin-api' {\n`,
796
+ tools: tools.named,
797
+ tail: `${interfaceBlock('MatbotServices', services.lines)}${augmentations.length ? `${augmentations.join('\n')}\n` : ''}}\n`,
798
+ };
754
799
  return {
755
- dts,
800
+ dts: assembleDts(dtsParts),
801
+ dtsParts,
756
802
  tools: { emitted: tools.emitted, unknown: tools.unknown },
757
803
  services: { emitted: services.emitted, unknown: services.unknown },
758
804
  conflicts,
759
805
  contracts,
760
806
  validators,
761
807
  apiExports: [...apiTypeNames],
808
+ files: [...files],
809
+ };
810
+ }
811
+
812
+ const interfaceBlock = (name: string, lines: readonly string[]): string =>
813
+ lines.length ? ` interface ${name} {\n${lines.join('\n')}\n }\n` : '';
814
+
815
+ function assembleDts(parts: DtsParts): string {
816
+ return `${parts.head}${interfaceBlock('ToolContracts', Object.values(parts.tools))}${parts.tail}`;
817
+ }
818
+
819
+ /**
820
+ * A build narrowed to the live tools, as if `liveToolNames` had been passed to it. Nothing a build derives
821
+ * for one tool depends on which others are live, so a build made over every scanned tool can serve any
822
+ * live set. The one difference: `head` keeps the imports and bundled declarations that only filtered-out
823
+ * tools referenced — extra, unreferenced declarations, which change nothing a snippet is checked against.
824
+ */
825
+ export function filterToolTypesData(data: ToolTypesData, liveToolNames: readonly string[]): ToolTypesData {
826
+ const live = new Set(liveToolNames);
827
+ const keep = <V>(r: Readonly<Record<string, V>>): Record<string, V> =>
828
+ Object.fromEntries(Object.entries(r).filter(([name]) => live.has(name)));
829
+ const dtsParts: DtsParts = { ...data.dtsParts, tools: keep(data.dtsParts.tools) };
830
+ return {
831
+ ...data,
832
+ dts: assembleDts(dtsParts),
833
+ dtsParts,
834
+ tools: { emitted: data.tools.emitted.filter(n => live.has(n)), unknown: data.tools.unknown.filter(n => live.has(n)) },
835
+ conflicts: data.conflicts.filter(c => c.registry !== 'ToolContracts' || live.has(c.key)),
836
+ contracts: keep(data.contracts),
837
+ validators: keep(data.validators),
762
838
  };
763
839
  }
840
+
841
+ /** {@link buildToolTypesData}, with every validator compiled — the in-process form. */
842
+ export async function buildMatbotToolsDts(
843
+ projectRoot: string, pluginEntryUrls?: readonly string[], liveToolNames?: readonly string[],
844
+ syntheticContracts?: Readonly<Record<string, string>>,
845
+ ): Promise<MatbotToolsDts | null> {
846
+ const data = await buildToolTypesData(projectRoot, pluginEntryUrls, liveToolNames, syntheticContracts);
847
+ if (!data) return null;
848
+ const { files: _files, dtsParts: _parts, validators, ...rest } = data;
849
+ return { ...rest, validators: compileToolValidators(validators) };
850
+ }
851
+
852
+ export function compileToolValidators(sources: Readonly<Record<string, ValidatorSource>>): Record<string, ToolValidator> {
853
+ return Object.fromEntries(Object.entries(sources).map(([name, s]) => [name, compileToolValidator(s)]));
854
+ }
package/src/index.ts CHANGED
@@ -4,14 +4,17 @@ import { createRequire } from 'node:module';
4
4
  import { PLUGIN_API_VERSION, RegistryChangeKind } from '@matatbread/matbot-plugin-api';
5
5
  import type { MatbotMachine, MatbotPluginSpec, ToolCheckReport, ToolTypeIndex } from '@matatbread/matbot-plugin-api';
6
6
  import { getRegisteredPlugins } from '@matatbread/matbot-core';
7
- import { buildMatbotToolsDts } from './build-dts.js';
7
+ import { buildToolTypesData, compileToolValidators, type ToolTypesData } from './build-dts.js';
8
8
  import { checkSnippetAgainst } from './checker.js';
9
9
  import type { ToolValidator } from './validator.js';
10
10
 
11
- export { buildMatbotToolsDts, type MatbotToolsDts } from './build-dts.js';
11
+ export {
12
+ buildMatbotToolsDts, buildToolTypesData, collectToolTypeRoots, compileToolValidators, filterToolTypesData,
13
+ type DtsParts, type MatbotToolsDts, type ToolTypesData, type ToolTypeRoots,
14
+ } from './build-dts.js';
12
15
  export { checkProjectDir, checkSnippetAgainst, type CheckResult } from './checker.js';
13
16
  export {
14
- generateValidator, buildToolValidator, compileValidator,
17
+ generateValidator, buildToolValidator, compileValidator, compileToolValidator,
15
18
  type ValidationError, type Validator, type ValidatorSource, type ToolValidator,
16
19
  } from './validator.js';
17
20
 
@@ -127,8 +130,23 @@ function schemaToTs(schema: unknown, depth = 0): string {
127
130
  return 'unknown';
128
131
  }
129
132
 
133
+ /** Everything a build reads from the live machine, gathered before the build's first await. */
134
+ export interface ToolTypesInputs {
135
+ projectRoot: string;
136
+ pluginEntryUrls: string[];
137
+ /** Absent ⇒ every scanned tool, for a build meant to serve any live set (see `filterToolTypesData`). */
138
+ liveToolNames?: string[];
139
+ syntheticContracts: Record<string, string>;
140
+ }
141
+
142
+ /** Where the index gets a build from on a miss. The default builds one; a specialisation may find one. */
143
+ export type ToolTypesFill = (inputs: ToolTypesInputs) => Promise<ToolTypesData | null>;
144
+
145
+ export const buildToolTypes: ToolTypesFill = i =>
146
+ buildToolTypesData(i.projectRoot, i.pluginEntryUrls, i.liveToolNames, i.syntheticContracts);
147
+
130
148
  /**
131
- * Derives (via {@link buildMatbotToolsDts}) and caches the `.d.ts` of what the loaded tools' calls resolve
149
+ * Derives (via {@link buildToolTypesData}) and caches the `.d.ts` of what the loaded tools' calls resolve
132
150
  * to, invalidating on any tool-registry change. The scan is driven off the loaded plugins' `resolvedUrl`s —
133
151
  * the real source each tool was loaded from — so builtin, compiled, and installed plugins are all covered
134
152
  * (the types are erased at runtime, but the `.ts` the runtime loaded from is still on disk). A source-less
@@ -137,57 +155,75 @@ function schemaToTs(schema: unknown, depth = 0): string {
137
155
  * already declares is skipped, so nothing is declared twice. `declare const tool: ToolProxy` (mapped over
138
156
  * the merged `ToolContracts`) plus its override factory `toolInContext` is what generators call.
139
157
  */
140
- class ToolTypeIndexImpl implements ToolTypeIndex {
158
+ export class ToolTypeIndexImpl implements ToolTypeIndex {
141
159
  private readonly machine: MatbotMachine;
160
+ private readonly fill: ToolTypesFill;
142
161
  private readonly ac = new AbortController();
143
162
  private covered = new Set<string>(); // tool names the source scan already declares (registry-block dedup)
144
163
  private cache: string | null = null; // null ⇒ (re)build needed
145
164
  private contracts: Record<string, { params: string; result: string }> = {}; // per-tool wire contract
146
165
  private validators: Record<string, ToolValidator> = {}; // per-tool compiled validator
147
166
  private apiExports: string[] = []; // plugin-api type export names (for importing those a toolContract names)
148
- private dirty = true;
167
+ private generation = 0; // tool registry changes seen
168
+ private builtFor = -1; // the generation the cached build reflects
169
+ private building: Promise<void> | null = null;
149
170
 
150
- constructor(machine: MatbotMachine) {
171
+ constructor(machine: MatbotMachine, fill: ToolTypesFill = buildToolTypes) {
151
172
  this.machine = machine;
173
+ this.fill = fill;
152
174
  // Any tool CRUD invalidates the generated dts; the event itself carries nothing we need.
153
- machine.Notifier.consume(() => { this.dirty = true; }, this.ac.signal,
175
+ machine.Notifier.consume(() => { this.generation++; }, this.ac.signal,
154
176
  n => n.kind === RegistryChangeKind && n.registry === 'tools');
155
177
  }
156
178
 
157
179
  close(): void { this.ac.abort(); }
158
180
 
181
+ // One build at a time, joined by every caller that arrives while it runs: each would otherwise build its
182
+ // own Program, synchronously and one after another. A caller that arrives after a registry change waits
183
+ // for a build that includes it, rather than taking one already under way from before it.
159
184
  private async ensureBuilt(): Promise<void> {
160
- if (this.dirty || this.cache === null) {
161
- const root = this.machine.configPath !== undefined ? dirname(this.machine.configPath) : '.';
162
- // Scan the source each loaded plugin was actually loaded from (its resolvedUrl) — builtin, compiled
163
- // (.compiled-plugins/), or installed (.plugins/) alike — so every registered tool's real augmentation
164
- // is read. build-dts UNIONs a glob of the monorepo `plugins/` tree onto these roots (not a fallback:
165
- // it catches host-constructed builtins that have no resolvedUrl), so the scanned set is a SUPERSET of
166
- // the loaded one — wherever that tree exists, plugins for other runtimes and plugins nobody loaded are
167
- // read too. Hence the live tool names: a scanned root may supply a tool's contract, never the fact that
168
- // the tool exists. Otherwise the dts declares uncallable tools (`telegram_send` from an unloaded
169
- // telegram frontend), which `check()` then grades generated code against — clean typecheck, "not
170
- // registered" at runtime. What the scan CAN'T settle is two roots declaring one live name; that stays
171
- // Program-order and audible via `conflicts`.
172
- const urls = getRegisteredPlugins().map(p => p.resolvedUrl).filter((u): u is string => u !== undefined);
173
- // A tool built at runtime declares its contract as a string, having no source to augment from. The
174
- // scan cannot see those, so they are handed over to be typed from a virtual augmentation — without
175
- // which they were described to the model in full and then enforced only by their loose
176
- // `inputSchema`, which is backwards: their params were authored by an LLM, not a compiler.
177
- const live = this.machine.tools.list();
178
- const synthetic = Object.fromEntries(
179
- live.flatMap(t => (t.toolContract !== undefined ? [[t.name, t.toolContract] as const] : [])),
180
- );
181
- const built = await buildMatbotToolsDts(root, urls, live.map(t => t.name), synthetic);
182
- this.cache = built?.dts ?? '';
183
- this.covered = new Set([...(built?.tools.emitted ?? []), ...(built?.tools.unknown ?? [])]);
184
- this.contracts = built?.contracts ?? {};
185
- this.validators = built?.validators ?? {};
186
- this.apiExports = built?.apiExports ?? [];
187
- this.dirty = false;
185
+ const wanted = this.generation;
186
+ while (this.builtFor < wanted) {
187
+ this.building ??= this.build().finally(() => { this.building = null; });
188
+ await this.building;
188
189
  }
189
190
  }
190
191
 
192
+ private async build(): Promise<void> {
193
+ // Read before anything is awaited, with the live tool list: a change that lands while this builds
194
+ // leaves the result stale, for the next caller to rebuild, instead of being marked seen.
195
+ const generation = this.generation;
196
+ const root = this.machine.configPath !== undefined ? dirname(this.machine.configPath) : '.';
197
+ // Scan the source each loaded plugin was actually loaded from (its resolvedUrl) — builtin, compiled
198
+ // (.compiled-plugins/), or installed (.plugins/) alike — so every registered tool's real augmentation
199
+ // is read. build-dts UNIONs a glob of the monorepo `plugins/` tree onto these roots (not a fallback:
200
+ // it catches host-constructed builtins that have no resolvedUrl), so the scanned set is a SUPERSET of
201
+ // the loaded one — wherever that tree exists, plugins for other runtimes and plugins nobody loaded are
202
+ // read too. Hence the live tool names: a scanned root may supply a tool's contract, never the fact that
203
+ // the tool exists. Otherwise the dts declares uncallable tools (`telegram_send` from an unloaded
204
+ // telegram frontend), which `check()` then grades generated code against — clean typecheck, "not
205
+ // registered" at runtime. What the scan CAN'T settle is two roots declaring one live name; that stays
206
+ // Program-order and audible via `conflicts`.
207
+ const urls = getRegisteredPlugins().map(p => p.resolvedUrl).filter((u): u is string => u !== undefined);
208
+ // A tool built at runtime declares its contract as a string, having no source to augment from. The
209
+ // scan cannot see those, so they are handed over to be typed from a virtual augmentation — without
210
+ // which they were described to the model in full and then enforced only by their loose
211
+ // `inputSchema`, which is backwards: their params were authored by an LLM, not a compiler.
212
+ 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
+ );
216
+ const built = await this.fill({
217
+ projectRoot: root, pluginEntryUrls: urls, liveToolNames: live.map(t => t.name), syntheticContracts: synthetic,
218
+ });
219
+ this.cache = built?.dts ?? '';
220
+ this.covered = new Set([...(built?.tools.emitted ?? []), ...(built?.tools.unknown ?? [])]);
221
+ this.contracts = built?.contracts ?? {};
222
+ this.validators = compileToolValidators(built?.validators ?? {});
223
+ this.apiExports = built?.apiExports ?? [];
224
+ this.builtFor = generation;
225
+ }
226
+
191
227
  async dts(): Promise<string> {
192
228
  await this.ensureBuilt();
193
229
  // `tool` — the injected proxy `function-tools`/compiled skills call — is a `ToolProxy`, a mapped type
package/src/validator.ts CHANGED
@@ -31,28 +31,27 @@ export type ValidatorSource =
31
31
  /**
32
32
  * What a consumer wants: the callable validator, plus what it does NOT constrain.
33
33
  *
34
- * The emitted source is deliberately not handed out. Anyone who wants the text calls
35
- * {@link generateValidator}, which is the same generation this went through — so carrying a copy on
36
- * every entry would be a second way to obtain one thing. (Note `validate.toString()` is NOT that copy:
37
- * the helper functions live in the enclosing scope of `new Function`, so it recovers only the entry
38
- * stub, never the logic.)
39
- *
40
- * Compiling eagerly rather than lazily is deliberate: `new Function` compiles in the GLOBAL scope, so
41
- * the validator captures nothing — not the checker, not a `ts.Type`, not this module's locals — and the
42
- * `ts.Program` is collectable the moment the build returns either way. There is nothing to defer.
34
+ * The build hands out {@link ValidatorSource}, not this: the source is plain data, so a build can be
35
+ * kept, moved or persisted and compiled wherever it lands (`validate.toString()` could not stand in —
36
+ * the helper functions live in the enclosing scope of `new Function`, so it recovers only the entry stub).
37
+ * `new Function` compiles in the GLOBAL scope, so a compiled validator captures nothing — not the
38
+ * checker, not a `ts.Type` — and compiling from a stored copy is the same act as compiling a fresh one.
43
39
  */
44
40
  export type ToolValidator =
45
41
  | { validate: Validator; warnings: string[] }
46
42
  | { refused: string };
47
43
 
48
- /** Generate and compile in one step — {@link generateValidator} followed by {@link compileValidator}. */
44
+ /** Compile a {@link ValidatorSource}; a refusal passes through unchanged. */
45
+ export function compileToolValidator(source: ValidatorSource): ToolValidator {
46
+ return 'refused' in source ? source : { validate: compileValidator(source.src), warnings: source.warnings };
47
+ }
48
+
49
+ /** Generate and compile in one step — {@link generateValidator} followed by {@link compileToolValidator}. */
49
50
  export function buildToolValidator(
50
51
  ts: typeof TS, checker: TS.TypeChecker, root: TS.Type | readonly TS.Type[], location: TS.Node,
51
52
  opts: { excessProperties?: 'allow' | 'reject' } = {},
52
53
  ): ToolValidator {
53
- const out = generateValidator(ts, checker, root, location, opts);
54
- if ('refused' in out) return out;
55
- return { validate: compileValidator(out.src), warnings: out.warnings };
54
+ return compileToolValidator(generateValidator(ts, checker, root, location, opts));
56
55
  }
57
56
 
58
57
  class Unsupported extends Error {
@@ -252,7 +251,21 @@ export function generateValidator(
252
251
  const c = check(a, 'v', 'p', `${where}|${i}`);
253
252
  return ` if (${c.reports ? c.expr.replace(/, e\)$/, ', scratch)') : c.expr}) return true;`;
254
253
  }).join('\n');
255
- return ` const scratch = [];\n${attempts}\n E(p, 'no union member matched', v, e);\n return false;`;
254
+ return `${excessAcrossArms(arms)} const scratch = [];\n${attempts}\n E(p, 'no union member matched', v, e);\n return false;`;
255
+ }
256
+
257
+ // A key no arm declares fails EVERY arm, so it can be reported by name before the arms are tried —
258
+ // exact, not a guess at which arm was meant. Without it, a call that invents a key (an `action` on a
259
+ // tool that has none) is reported as whatever else that arm lacks, which sends the caller to fix the
260
+ // arguments it did pass instead of the key it should not have.
261
+ function excessAcrossArms(arms: readonly TS.Type[]): string {
262
+ const objectLike = F.Object | F.Intersection;
263
+ if (!reject || !arms.every(a => (a.flags & objectLike) && !checker.getIndexInfoOfType(a, ts.IndexKind.String))) return '';
264
+ const known = [...new Set(arms.flatMap(a => checker.getPropertiesOfType(a).map(s => s.name)))];
265
+ return ` if (typeof v === 'object' && v !== null && !Array.isArray(v)) {\n`
266
+ + ` let excess = false;\n`
267
+ + ` for (const k of Object.keys(v)) if (!${lit(known)}.includes(k)) { E(K(p, k), 'unexpected property', v[k], e); excess = true; }\n`
268
+ + ` if (excess) return false;\n }\n`;
256
269
  }
257
270
 
258
271
  function bodyOf(t: TS.Type, where: string): string {
@@ -363,8 +376,9 @@ export function generateValidator(
363
376
  }
364
377
  }
365
378
 
366
- /** Instantiate a generated validator. The source is emitted by {@link generateValidator} from a type
367
- * in this process — never from user input — and is plain JS with no free identifiers but `Object`. */
379
+ /** Instantiate a generated validator. The source is emitted by {@link generateValidator} from a type —
380
+ * never from user input — and is plain JS with no free identifiers but `Object`. A stored copy is
381
+ * therefore exactly as trusted as the medium it was stored in. */
368
382
  export function compileValidator(src: string): Validator {
369
383
  return new Function(src)() as Validator;
370
384
  }