@matatbread/matbot-tool-types 0.4.20 → 0.4.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +5 -5
- package/src/build-dts.ts +64 -22
- package/src/checker.ts +6 -2
- package/src/index.ts +24 -15
package/package.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"matbotRuntime": [
|
|
4
4
|
"node"
|
|
5
5
|
],
|
|
6
|
-
"version": "0.4.
|
|
6
|
+
"version": "0.4.21",
|
|
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-
|
|
41
|
-
"@matatbread/matbot-
|
|
40
|
+
"@matatbread/matbot-plugin-api": "^0.4.21",
|
|
41
|
+
"@matatbread/matbot-core": "^0.4.21"
|
|
42
42
|
},
|
|
43
43
|
"devDependencies": {
|
|
44
44
|
"typescript": "^6.0.3",
|
|
45
|
-
"@matatbread/matbot-
|
|
46
|
-
"@matatbread/matbot-
|
|
45
|
+
"@matatbread/matbot-plugin-api": "^0.4.21",
|
|
46
|
+
"@matatbread/matbot-core": "^0.4.21"
|
|
47
47
|
},
|
|
48
48
|
"scripts": {
|
|
49
49
|
"typecheck": "tsc --noEmit"
|
package/src/build-dts.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import type TS from 'typescript';
|
|
2
|
+
import type { Runtime } from '@matatbread/matbot-plugin-api';
|
|
3
|
+
import { contractArms } from '@matatbread/matbot-plugin-api';
|
|
2
4
|
import { compileToolValidator, generateValidator, type ToolValidator, type ValidatorSource } from './validator.js';
|
|
3
5
|
|
|
4
6
|
// Derive a self-contained `declare module … { interface ToolContracts {…} interface MatbotServices {…} }`
|
|
@@ -76,6 +78,9 @@ export interface MatbotToolsDts {
|
|
|
76
78
|
* build read. Serialisable by construction, so a build can be kept beyond the process that made it; what
|
|
77
79
|
* it depends on is exactly its arguments, tool-types itself, and the content of `files`.
|
|
78
80
|
*/
|
|
81
|
+
/** A tool's `toolContract` string, with the declarations of its own it names (`toolContractTypes`). */
|
|
82
|
+
export interface SyntheticContract { contract: string; types?: string }
|
|
83
|
+
|
|
79
84
|
export interface ToolTypesData extends Omit<MatbotToolsDts, 'validators'> {
|
|
80
85
|
validators: Record<string, ValidatorSource>;
|
|
81
86
|
/** `dts` in pieces, one per tool, so {@link filterToolTypesData} can narrow it without a rebuild. */
|
|
@@ -111,7 +116,7 @@ export interface ToolTypeRoots {
|
|
|
111
116
|
/** What a build of `pluginEntryUrls` would scan, without building it. Null when there is nothing to scan
|
|
112
117
|
* beyond plugin-api, or plugin-api itself cannot be found. */
|
|
113
118
|
export async function collectToolTypeRoots(
|
|
114
|
-
projectRoot: string, pluginEntryUrls?: readonly string[],
|
|
119
|
+
projectRoot: string, pluginEntryUrls?: readonly string[], runtime: Runtime = 'node',
|
|
115
120
|
): Promise<ToolTypeRoots | null> {
|
|
116
121
|
const { readFileSync, readdirSync, statSync, existsSync } = await import('node:fs');
|
|
117
122
|
const { join } = await import('node:path');
|
|
@@ -163,6 +168,14 @@ export async function collectToolTypeRoots(
|
|
|
163
168
|
// `plugins/bash` and `plugins/docker-bash` — still merges by Program file order, so the unloaded one can
|
|
164
169
|
// win and describe the loaded one; that is what `conflicts` makes audible, and it cannot be filtered away
|
|
165
170
|
// because the name IS live.
|
|
171
|
+
//
|
|
172
|
+
// Plugins for another runtime are the exception: those are skipped, by the loader's own pre-import rule
|
|
173
|
+
// (a package whose `matbotRuntime` is present, non-empty and excludes `runtime`). `liveToolNames` cannot
|
|
174
|
+
// stand in for that, because a static caller has no live set — a typed client generated at build time —
|
|
175
|
+
// and an augmentation of a shared shape (google-drive's `managedBy` on `LoadedPluginSummary`) is
|
|
176
|
+
// no tool name to filter. `runtime` is the runtime being DESCRIBED, not the one this runs on: the web
|
|
177
|
+
// bundle's build runs here to describe a browser. The resolvedUrl roots need no such rule; the loader
|
|
178
|
+
// has already gated them.
|
|
166
179
|
// Generated `matbot-tools.d.ts` files are skipped (don't feed prior output back in).
|
|
167
180
|
if (existsSync(join(projectRoot, 'plugins'))) {
|
|
168
181
|
// Dot-directories wholesale rather than by name: this used to list `compiled-plugins` explicitly,
|
|
@@ -171,16 +184,24 @@ export async function collectToolTypeRoots(
|
|
|
171
184
|
// A source tree keeps no augmentations under a dot-directory; `.git`, `.plugins` and a build root
|
|
172
185
|
// sited there are all covered by one rule that cannot go stale.
|
|
173
186
|
const SKIP = new Set(['node_modules', 'dist']);
|
|
174
|
-
|
|
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,
|
|
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,
|
|
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,
|
|
281
|
-
const probe = ts.createSourceFile('/probe.ts',
|
|
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] =
|
|
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
|
-
|
|
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.
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
605
|
-
//
|
|
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,
|
|
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
|
@@ -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))
|
|
@@ -419,7 +424,6 @@ 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>(…)'.",
|
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
|
-
*
|
|
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,
|
|
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
|
-
|
|
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
|
});
|
|
@@ -451,6 +451,7 @@ export class ToolTypeIndexImpl implements ToolTypeIndex {
|
|
|
451
451
|
prefixLines: prefix.split('\n').length - 1,
|
|
452
452
|
...(apiIndex !== undefined ? { apiIndexPath: apiIndex } : {}),
|
|
453
453
|
...(Object.keys(importPaths).length > 0 ? { importPaths } : {}),
|
|
454
|
+
globalTypes: nodeGlobalTypes(),
|
|
454
455
|
...(restricted !== undefined ? { permittedImports: restricted } : {}),
|
|
455
456
|
// ENV-GATE's list, from the runner that withholds them. Absent with no runner, which is correct:
|
|
456
457
|
// nothing is withheld there either, so there is nothing to reject.
|
|
@@ -473,13 +474,12 @@ export class ToolTypeIndexImpl implements ToolTypeIndex {
|
|
|
473
474
|
// top-of-file import the derived block emits (every arm references it); when the scan produced nothing to
|
|
474
475
|
// import it (no source resolved, or an all-`MatbotServices` block), this block supplies that one import.
|
|
475
476
|
private registryBlock(derived: string): string {
|
|
476
|
-
const arms:
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
}
|
|
477
|
+
const { preamble, arms: armOf } = contractArms(this.machine.tools.list().filter(t => !this.covered.has(t.name)).map(t => ({
|
|
478
|
+
name: t.name, contract: t.toolContract ?? `ToolContract<unknown, ${schemaToTs(t.inputSchema)}>`, types: t.toolContractTypes,
|
|
479
|
+
})));
|
|
480
|
+
const arms = [...armOf].map(([name, arm]) => ` ${JSON.stringify(name)}: ${arm};`);
|
|
481
481
|
if (arms.length === 0) return derived;
|
|
482
|
-
const body = arms.join('\n');
|
|
482
|
+
const body = preamble + arms.join('\n');
|
|
483
483
|
// Import the plugin-api types these arms reference — `ToolContract` always, plus any plugin-api export a
|
|
484
484
|
// source-less `toolContract` names (e.g. `StoreQuery`) — minus whatever the derived block already imports
|
|
485
485
|
// (importing a name twice is a redeclaration error). A synthetic tool inlines its own shape types, so the
|
|
@@ -493,7 +493,7 @@ export class ToolTypeIndexImpl implements ToolTypeIndex {
|
|
|
493
493
|
const head = needed.length
|
|
494
494
|
? `${derived === '' ? "import '@matatbread/matbot-plugin-api';\n" : ''}import type { ${needed.join(', ')} } from '@matatbread/matbot-plugin-api';\n`
|
|
495
495
|
: '';
|
|
496
|
-
return `${head}${derived}\
|
|
496
|
+
return `${head}${derived}\n${preamble}declare module '@matatbread/matbot-plugin-api' {\n interface ToolContracts {\n${arms.join('\n')}\n }\n}\n`;
|
|
497
497
|
}
|
|
498
498
|
|
|
499
499
|
async toolValidators(): Promise<Record<string, ToolValidator>> {
|
|
@@ -520,6 +520,15 @@ export function createToolTypesPlugin(): MatbotPluginSpec {
|
|
|
520
520
|
export const plugin: MatbotPluginSpec = createToolTypesPlugin();
|
|
521
521
|
|
|
522
522
|
|
|
523
|
+
// The node globals a body has that the standard library does not declare: `Buffer`, and its overloads in
|
|
524
|
+
// buffer.buffer.d.ts. The rest of what a body is given (`fetch`, the timers, `console`, `TextEncoder`,
|
|
525
|
+
// `atob`) is in lib.dom. Loaded whether or not the runner withholds it, since ENV-GATE rejects a withheld
|
|
526
|
+
// name either way, and with no runner a body really has it.
|
|
527
|
+
function nodeGlobalTypes(): string[] {
|
|
528
|
+
const nodeTypes = dirname(createRequire(import.meta.url).resolve('@types/node/package.json'));
|
|
529
|
+
return ['buffer.buffer.d.ts', 'buffer.d.ts'].map(f => join(nodeTypes, f)).filter(f => existsSync(f));
|
|
530
|
+
}
|
|
531
|
+
|
|
523
532
|
// Where @types/node declares a builtin. Most have a file of their own, but a few subpaths are declared
|
|
524
533
|
// inside their parent's (`path/posix` in path.d.ts, `util/types` in util.d.ts, `test/reporters` in
|
|
525
534
|
// test.d.ts), and skipping those left a module the gate admits failing the check. The parent is taken
|