@matatbread/matbot-tool-types 0.4.1 → 0.4.3
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 +249 -18
- package/src/index.ts +9 -3
package/package.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"matbotRuntime": [
|
|
4
4
|
"node"
|
|
5
5
|
],
|
|
6
|
-
"version": "0.4.
|
|
6
|
+
"version": "0.4.3",
|
|
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.
|
|
40
|
-
"@matatbread/matbot-core": "^0.4.
|
|
39
|
+
"@matatbread/matbot-plugin-api": "^0.4.3",
|
|
40
|
+
"@matatbread/matbot-core": "^0.4.3"
|
|
41
41
|
},
|
|
42
42
|
"devDependencies": {
|
|
43
43
|
"@types/node": "^22.0.0",
|
|
44
44
|
"typescript": "^6.0.3",
|
|
45
|
-
"@matatbread/matbot-plugin-api": "^0.4.
|
|
46
|
-
"@matatbread/matbot-core": "^0.4.
|
|
45
|
+
"@matatbread/matbot-plugin-api": "^0.4.3",
|
|
46
|
+
"@matatbread/matbot-core": "^0.4.3"
|
|
47
47
|
},
|
|
48
48
|
"scripts": {
|
|
49
49
|
"typecheck": "tsc --noEmit"
|
package/src/build-dts.ts
CHANGED
|
@@ -27,13 +27,35 @@ import type TS from 'typescript';
|
|
|
27
27
|
// Acceptable once-per-compile; the planned coverage work (drive off the live loaded-plugin set, build
|
|
28
28
|
// lazily + dirty on plugin load) also removes that cost. Coverage today is the monorepo `plugins/` tree.
|
|
29
29
|
|
|
30
|
+
/**
|
|
31
|
+
* A registry key declared more than once, with DIFFERENT types, across the scanned files. Declaration
|
|
32
|
+
* merging requires the declarations to be identical (TS2717 otherwise) — but this scan reads the
|
|
33
|
+
* checker and never the Program's diagnostics, so the error is invisible here: one declaration wins on
|
|
34
|
+
* Program file order and the emitted contract asserts its shape for the tool.
|
|
35
|
+
*
|
|
36
|
+
* That is worse than the untyped fallback. An unregistered tool resolves to `unknown` and forces a
|
|
37
|
+
* generator to narrow; a wrong-but-concrete shape typechecks, so the check loop rejects the correct
|
|
38
|
+
* field and accepts one that reads `undefined` at runtime. Reported, never resolved — picking a winner
|
|
39
|
+
* here would just relocate the arbitrariness.
|
|
40
|
+
*/
|
|
41
|
+
export interface ContractConflict {
|
|
42
|
+
registry: 'ToolContracts' | 'MatbotServices';
|
|
43
|
+
key: string;
|
|
44
|
+
/** `file:line` of the declaration that won the merge — the shape actually emitted. */
|
|
45
|
+
winner: string;
|
|
46
|
+
/** `file:line` of each declaration that lost, in declaration order. */
|
|
47
|
+
losers: string[];
|
|
48
|
+
}
|
|
49
|
+
|
|
30
50
|
export interface MatbotToolsDts {
|
|
31
51
|
dts: string;
|
|
32
52
|
tools: { emitted: string[]; unknown: string[] };
|
|
33
53
|
services: { emitted: string[]; unknown: string[] };
|
|
34
|
-
|
|
35
|
-
//
|
|
36
|
-
//
|
|
54
|
+
conflicts: ContractConflict[];
|
|
55
|
+
// Per source-scanned tool (live ones only, as with the dts): its wire contract — the flattened
|
|
56
|
+
// `params`/`result` union text, extracted from the `ToolContracts` arms. The single authored contract
|
|
57
|
+
// (the arms) is thus also the source of the wire description, so a source tool's `ToolContracts`
|
|
58
|
+
// augmentation is its single contract.
|
|
37
59
|
contracts: Record<string, { params: string; result: string }>;
|
|
38
60
|
// The names of every plugin-api type export. A source-less tool's `toolContract` string may name one
|
|
39
61
|
// (e.g. `StoreQuery`); the consumer (ToolTypeIndex) uses this to import the ones it references so those
|
|
@@ -53,7 +75,17 @@ type Classification =
|
|
|
53
75
|
// augmenting files transitively, so coverage follows the actual loaded set (npm / `.plugins/` / local),
|
|
54
76
|
// not just the monorepo tree. When none resolve to on-disk source, falls back to globbing the monorepo
|
|
55
77
|
// `plugins/` tree. Returns null when neither yields anything (the caller then uses its static DTS).
|
|
56
|
-
|
|
78
|
+
//
|
|
79
|
+
// `liveToolNames` is the live tool registry (`machine.tools.list()`), and it is what makes the emitted
|
|
80
|
+
// `ToolContracts` a description of what a generator can actually CALL rather than of what happens to be on
|
|
81
|
+
// disk: the roots are a superset of the loaded set by construction (see the glob below), so a name absent
|
|
82
|
+
// from the registry is declared, typed, and uncallable — `tool.telegram_send(…)` typechecks clean and
|
|
83
|
+
// throws "not registered" at runtime, which is the one failure the check gate exists to prevent. Omit it
|
|
84
|
+
// only when the caller genuinely wants the whole scanned tree (the clash census test); the registry is not
|
|
85
|
+
// optional information for anything that shows the dts to a model.
|
|
86
|
+
export async function buildMatbotToolsDts(
|
|
87
|
+
projectRoot: string, pluginEntryUrls?: readonly string[], liveToolNames?: readonly string[],
|
|
88
|
+
): Promise<MatbotToolsDts | null> {
|
|
57
89
|
const ts = (await import('typescript')).default as typeof TS;
|
|
58
90
|
const { readFileSync, readdirSync, statSync, existsSync } = await import('node:fs');
|
|
59
91
|
const { join } = await import('node:path');
|
|
@@ -86,11 +118,15 @@ export async function buildMatbotToolsDts(projectRoot: string, pluginEntryUrls?:
|
|
|
86
118
|
// plugin with a resolvedUrl — notably the app-embedded `plugin`/`provider` builtins in `plugins/tool-plugin/`,
|
|
87
119
|
// which the host constructs directly. The glob catches those. In a real deployment there is no `plugins/`
|
|
88
120
|
// tree, so this no-ops and the scan is purely resolvedUrl-driven. Dedup is by path (a Set of roots).
|
|
89
|
-
//
|
|
90
|
-
//
|
|
91
|
-
//
|
|
92
|
-
//
|
|
93
|
-
//
|
|
121
|
+
//
|
|
122
|
+
// So the roots deliberately over-reach: wherever that tree exists — this repo, or an embedder that vendors
|
|
123
|
+
// it — plugins for OTHER runtimes and plugins nobody loaded are scanned too. Two consequences, and they
|
|
124
|
+
// need different answers. A key declared by an unloaded plugin is filtered out by `liveToolNames` at emit
|
|
125
|
+
// (a scanned root may contribute a contract, never the FACT of a tool). A key declared by both — `bash` by
|
|
126
|
+
// `plugins/bash` and `plugins/docker-bash` — still merges by Program file order, so the unloaded one can
|
|
127
|
+
// win and describe the loaded one; that is what `conflicts` makes audible, and it cannot be filtered away
|
|
128
|
+
// because the name IS live.
|
|
129
|
+
// Generated `matbot-tools.d.ts` files are skipped (don't feed prior output back in).
|
|
94
130
|
if (existsSync(join(projectRoot, 'plugins'))) {
|
|
95
131
|
const SKIP = new Set(['node_modules', 'dist', '.git', 'compiled-plugins']);
|
|
96
132
|
const walk = (dir: string): void => {
|
|
@@ -104,7 +140,13 @@ export async function buildMatbotToolsDts(projectRoot: string, pluginEntryUrls?:
|
|
|
104
140
|
if (isDir) { walk(p); continue; }
|
|
105
141
|
if (!name.endsWith('.ts') || name.endsWith('matbot-tools.d.ts')) continue;
|
|
106
142
|
const src = readFileSync(p, 'utf8');
|
|
107
|
-
|
|
143
|
+
// Any augmentation of plugin-api, not just one naming `ToolContracts`/`MatbotServices`. Those two
|
|
144
|
+
// are the interfaces EMITTED, but they are not the only ones that change what they mean: a tool
|
|
145
|
+
// result is now a named interface (`LoadedPluginSummary`), so a file adding a field to one — the
|
|
146
|
+
// google-drive `plugin` override does exactly that — alters `ToolContracts['plugin']` without
|
|
147
|
+
// ever mentioning `ToolContracts`. Filtering on the emitted names left such a file unrooted and
|
|
148
|
+
// its field invisible to the very generators the augmentation exists to inform.
|
|
149
|
+
if (/declare\s+module\s+['"]@matatbread\/matbot-plugin-api['"]/.test(src)) roots.add(p);
|
|
108
150
|
}
|
|
109
151
|
};
|
|
110
152
|
walk(join(projectRoot, 'plugins'));
|
|
@@ -240,14 +282,19 @@ export async function buildMatbotToolsDts(projectRoot: string, pluginEntryUrls?:
|
|
|
240
282
|
};
|
|
241
283
|
|
|
242
284
|
// Emit one augmentable interface's plugin-contributed members. `onlyAugmented` skips base members
|
|
243
|
-
// already visible via plugin-api (no-op for ToolContracts).
|
|
244
|
-
|
|
285
|
+
// already visible via plugin-api (no-op for ToolContracts). `only`, when given, keeps just those keys —
|
|
286
|
+
// for `ToolContracts` that is the live registry, so a scanned-but-unloaded plugin's arm is dropped before
|
|
287
|
+
// `emitNode` runs and its referenced types are never bundled or imported either.
|
|
288
|
+
const emitInterface = (
|
|
289
|
+
interfaceName: string, onlyAugmented: boolean, only?: ReadonlySet<string>,
|
|
290
|
+
): { lines: string[]; emitted: string[]; unknown: string[] } => {
|
|
245
291
|
const sym = findCanonicalSymbol(interfaceName);
|
|
246
292
|
const lines: string[] = [], emitted: string[] = [], unknownNames: string[] = [];
|
|
247
293
|
if (!sym) return { lines, emitted, unknown: unknownNames };
|
|
248
294
|
const props = [...checker.getPropertiesOfType(checker.getDeclaredTypeOfSymbol(sym))].sort((a, b) => a.name.localeCompare(b.name));
|
|
249
295
|
for (const prop of props) {
|
|
250
296
|
if (onlyAugmented && inPluginApi(prop)) continue;
|
|
297
|
+
if (only !== undefined && !only.has(prop.name)) continue;
|
|
251
298
|
const optional = (prop.flags & ts.SymbolFlags.Optional) !== 0 ? '?' : '';
|
|
252
299
|
const decl = (prop.declarations ?? []).find(d => ts.isPropertySignature(d));
|
|
253
300
|
const ann = decl && ts.isPropertySignature(decl) ? decl.type : undefined;
|
|
@@ -273,19 +320,201 @@ export async function buildMatbotToolsDts(projectRoot: string, pluginEntryUrls?:
|
|
|
273
320
|
return { lines, emitted, unknown: unknownNames };
|
|
274
321
|
};
|
|
275
322
|
|
|
276
|
-
|
|
323
|
+
// A tool the registry doesn't hold isn't a tool. `MatbotServices` takes no such filter: a member there is
|
|
324
|
+
// consumed as `services.X?.` and its absence is already a type (the `?:` IS the "may not be loaded"
|
|
325
|
+
// signal), whereas a `ToolContracts` key carries no such qualifier — declared means callable.
|
|
326
|
+
const live = liveToolNames !== undefined ? new Set(liveToolNames) : undefined;
|
|
327
|
+
const tools = emitInterface('ToolContracts', false, live);
|
|
277
328
|
const services = emitInterface('MatbotServices', true);
|
|
278
329
|
|
|
330
|
+
// Re-emit plugin-side augmentations of plugin-api interfaces. A contract that references a plugin-api
|
|
331
|
+
// type is emitted as that NAME plus an import, so the generated compilation resolves it against the
|
|
332
|
+
// real package — which carries none of the `declare module` additions a plugin made. That is precisely
|
|
333
|
+
// where a named result shape earns its keep (google-drive's `plugin` override adds `managedBy` to
|
|
334
|
+
// `LoadedPluginSummary`), so the field has to travel with the dts or it is invisible exactly where it
|
|
335
|
+
// is meant to be used. Members go through `emitNode`, so a reference to a plugin-local type is bundled
|
|
336
|
+
// or `unknown`-substituted like any other — an augmentation cannot leave a dangling name behind and
|
|
337
|
+
// collapse the whole check. `ToolContracts`/`MatbotServices` are excluded: they are computed above from
|
|
338
|
+
// the merged symbol, and re-emitting them here would declare their members twice.
|
|
339
|
+
const COMPUTED_INTERFACES = new Set(['ToolContracts', 'MatbotServices']);
|
|
340
|
+
const augmentations: string[] = [];
|
|
341
|
+
const seenAugments = new Set<string>();
|
|
342
|
+
for (const sf of program.getSourceFiles()) {
|
|
343
|
+
if (sf.fileName.includes('/plugin-api/') || sf.fileName.includes('/node_modules/')) continue;
|
|
344
|
+
ts.forEachChild(sf, n => {
|
|
345
|
+
if (!ts.isModuleDeclaration(n) || !ts.isStringLiteral(n.name)
|
|
346
|
+
|| n.name.text !== '@matatbread/matbot-plugin-api'
|
|
347
|
+
|| n.body === undefined || !ts.isModuleBlock(n.body)) return;
|
|
348
|
+
for (const m of n.body.statements) {
|
|
349
|
+
if (!ts.isInterfaceDeclaration(m) || COMPUTED_INTERFACES.has(m.name.text)) continue;
|
|
350
|
+
const key = declKey(m);
|
|
351
|
+
if (seenAugments.has(key)) continue;
|
|
352
|
+
seenAugments.add(key);
|
|
353
|
+
const ctx: Ctx = { imports: new Set(), seen: new Set(), heritageBail: null };
|
|
354
|
+
const text = emitNode(m, ctx);
|
|
355
|
+
if (ctx.heritageBail) continue;
|
|
356
|
+
ctx.imports.forEach(i => importNames.add(i));
|
|
357
|
+
augmentations.push(` ${stripModifiers(text)}`);
|
|
358
|
+
}
|
|
359
|
+
});
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
// Clash census. Derived from the symbol table already walked above rather than from
|
|
363
|
+
// `getPreEmitDiagnostics`, which costs ~4x this whole build (measured: +750ms on a 40-root scan) and
|
|
364
|
+
// says less: a raw TS2717 filter reports only the losing site, whereas the merged symbol's
|
|
365
|
+
// declaration list names the winner too — and it can't distinguish a real clash from the legal
|
|
366
|
+
// identical re-declaration TypeScript never complains about (`bash`, `mcp_action` and
|
|
367
|
+
// `url_for_resource` are each declared twice here, identically, and are not conflicts).
|
|
368
|
+
const relPath = (f: string): string => f.startsWith(projectRoot) ? f.slice(projectRoot.length + 1) : f;
|
|
369
|
+
const siteOf = (d: TS.Node): string =>
|
|
370
|
+
`${relPath(d.getSourceFile().fileName)}:${d.getSourceFile().getLineAndCharacterOfPosition(d.getStart()).line + 1}`;
|
|
371
|
+
|
|
372
|
+
const collectConflicts = (interfaceName: 'ToolContracts' | 'MatbotServices'): ContractConflict[] => {
|
|
373
|
+
const sym = findCanonicalSymbol(interfaceName);
|
|
374
|
+
if (!sym) return [];
|
|
375
|
+
const out: ContractConflict[] = [];
|
|
376
|
+
for (const prop of checker.getPropertiesOfType(checker.getDeclaredTypeOfSymbol(sym))) {
|
|
377
|
+
// Don't warn about a clash between two tools that aren't there: nothing is emitted for them, so
|
|
378
|
+
// there is no wrong shape to act on, and the warning would point at a fix nobody needs to make.
|
|
379
|
+
if (interfaceName === 'ToolContracts' && live !== undefined && !live.has(prop.name)) continue;
|
|
380
|
+
// Declaration order is merge order: `emitInterface` reads the first property signature, so that
|
|
381
|
+
// one is the winner by the same rule that produced the emitted text.
|
|
382
|
+
const sites = (prop.declarations ?? []).flatMap(d =>
|
|
383
|
+
ts.isPropertySignature(d) && d.type !== undefined ? [{ node: d, type: d.type }] : []);
|
|
384
|
+
if (sites.length < 2) continue;
|
|
385
|
+
const distinct = new Set(sites.map(s =>
|
|
386
|
+
checker.typeToString(checker.getTypeFromTypeNode(s.type), undefined, ts.TypeFormatFlags.NoTruncation)));
|
|
387
|
+
if (distinct.size < 2) continue;
|
|
388
|
+
out.push({
|
|
389
|
+
registry: interfaceName,
|
|
390
|
+
key: prop.name,
|
|
391
|
+
winner: siteOf(sites[0]!.node),
|
|
392
|
+
losers: sites.slice(1).map(s => siteOf(s.node)),
|
|
393
|
+
});
|
|
394
|
+
}
|
|
395
|
+
return out;
|
|
396
|
+
};
|
|
397
|
+
const conflicts = [...collectConflicts('ToolContracts'), ...collectConflicts('MatbotServices')];
|
|
398
|
+
// Warned here rather than by the caller because both callers (ToolTypeIndex and skills_compiler) need
|
|
399
|
+
// it and neither can act on it — the fix is always in the clashing source, not at the call site.
|
|
400
|
+
for (const c of conflicts) {
|
|
401
|
+
console.warn(`[matbot] ${c.registry}.${c.key} is declared ${c.losers.length + 1}× with different types — `
|
|
402
|
+
+ `"${c.winner}" wins, ignoring ${c.losers.join(', ')}. The emitted contract may not match what the tool returns.`);
|
|
403
|
+
}
|
|
404
|
+
|
|
279
405
|
// Per-tool wire contract: flatten each `ToolContracts` arm to its `params`/`result` union source text.
|
|
280
406
|
// Only pure `ToolContract<R, P>`-arm entries yield one (a bare/plain entry is skipped — it keeps whatever
|
|
281
407
|
// the tool authored). This is the flat params/result union the wire description needs, from the arms.
|
|
408
|
+
// Follow a bare reference to a type alias through to the alias's own type node, so a tool that NAMES
|
|
409
|
+
// its arm union (`plugin: PluginToolContract`) flattens exactly like one spelled out inline. Naming
|
|
410
|
+
// the union is what lets two implementations of one tool name share ONE declaration rather than two
|
|
411
|
+
// that merge only while they stay textually identical.
|
|
412
|
+
const resolveAlias = (node: TS.TypeNode): TS.TypeNode => {
|
|
413
|
+
if (!ts.isTypeReferenceNode(node) || node.typeArguments !== undefined) return node;
|
|
414
|
+
const sym = checker.getSymbolAtLocation(node.typeName);
|
|
415
|
+
if (!sym) return node;
|
|
416
|
+
const target = (sym.flags & ts.SymbolFlags.Alias) !== 0 ? checker.getAliasedSymbol(sym) : sym;
|
|
417
|
+
const decl = (target.declarations ?? []).find(ts.isTypeAliasDeclaration);
|
|
418
|
+
return decl?.type ?? node;
|
|
419
|
+
};
|
|
420
|
+
|
|
421
|
+
// Expand named shapes to their structure for the WIRE text only. The dts bundles a referenced
|
|
422
|
+
// declaration alongside the reference, so a name resolves there; a tool description carries nothing
|
|
423
|
+
// but this string, so `result: PluginListResult` would tell the model nothing about the fields. Naming
|
|
424
|
+
// a result type is an API-side decision — it is what makes the shape augmentable — and it must not
|
|
425
|
+
// cost the model the shape. Only workspace/plugin-api interfaces and aliases expand: a lib or
|
|
426
|
+
// node_modules name stays as written (`Date`, `AbortSignal` mean more as names than as members), and
|
|
427
|
+
// so does anything past the depth cap or already on the path, which is what terminates a recursive
|
|
428
|
+
// shape rather than diverging.
|
|
429
|
+
//
|
|
430
|
+
// The cap is 2 because that is PARITY, not a tuning choice: it reproduces what an inline object
|
|
431
|
+
// literal used to render — the arm's own shape, and the shape of what its members hold, with anything
|
|
432
|
+
// deeper left as a name (`tools: ToolSummary[]` read exactly so before these types were named, and
|
|
433
|
+
// reads so now). Every level costs tokens in every tool description of every turn: unbounded
|
|
434
|
+
// expansion doubled the total wire text across the 38 source tools, mostly by inlining `Session` and
|
|
435
|
+
// `StoreQuery` into `session_action`.
|
|
436
|
+
const WIRE_DEPTH = 2;
|
|
437
|
+
const expandNamed = (node: TS.TypeNode, path: ReadonlySet<string>, depth: number): string => {
|
|
438
|
+
const base = node.getStart();
|
|
439
|
+
const repls: Array<{ s: number; e: number; t: string }> = [];
|
|
440
|
+
|
|
441
|
+
const expansionOf = (ref: TS.TypeReferenceNode): string | undefined => {
|
|
442
|
+
if (ref.typeArguments !== undefined || depth >= WIRE_DEPTH) return undefined;
|
|
443
|
+
const raw = checker.getSymbolAtLocation(ref.typeName);
|
|
444
|
+
if (!raw) return undefined;
|
|
445
|
+
const sym = (raw.flags & ts.SymbolFlags.Alias) !== 0 ? checker.getAliasedSymbol(raw) : raw;
|
|
446
|
+
const decls = sym.declarations ?? [];
|
|
447
|
+
if (decls.length === 0) return undefined;
|
|
448
|
+
const files = decls.map(d => d.getSourceFile());
|
|
449
|
+
if (files.some(f => program.isSourceFileDefaultLibrary(f) || f.fileName.includes('/node_modules/'))) return undefined;
|
|
450
|
+
|
|
451
|
+
const key = declKey(decls[0]!);
|
|
452
|
+
if (path.has(key)) return undefined;
|
|
453
|
+
const nextPath = new Set([...path, key]);
|
|
454
|
+
|
|
455
|
+
// A union or intersection substituted into a reference position needs its own parentheses:
|
|
456
|
+
// `readonly Runtime[]` with `Runtime = 'node' | 'browser'` would otherwise render as
|
|
457
|
+
// `readonly 'node' | 'browser'[]`, which parses as a union whose second arm is an array.
|
|
458
|
+
const parenthesised = (t: string): string => {
|
|
459
|
+
let d = 0;
|
|
460
|
+
for (let i = 0; i < t.length; i++) {
|
|
461
|
+
const c = t[i];
|
|
462
|
+
if (c === '<' || c === '{' || c === '(' || c === '[') d++;
|
|
463
|
+
else if (c === '>' || c === '}' || c === ')' || c === ']') d--;
|
|
464
|
+
else if (d === 0 && (c === '|' || c === '&')) return `(${t})`;
|
|
465
|
+
}
|
|
466
|
+
return t;
|
|
467
|
+
};
|
|
468
|
+
|
|
469
|
+
const alias = decls.find(ts.isTypeAliasDeclaration);
|
|
470
|
+
if (alias) return parenthesised(expandNamed(alias.type, nextPath, depth + 1));
|
|
471
|
+
if (!decls.some(ts.isInterfaceDeclaration)) return undefined;
|
|
472
|
+
|
|
473
|
+
// Read members off the MERGED symbol, not one declaration: an interface that a plugin augmented
|
|
474
|
+
// (the whole point of naming these) carries its added members on the merged type only, and
|
|
475
|
+
// inherited members come through the same call.
|
|
476
|
+
const declared = checker.getDeclaredTypeOfSymbol(sym);
|
|
477
|
+
const members: string[] = [];
|
|
478
|
+
// Index signatures are not properties, and dropping one inverts its meaning: `ModelParameters`
|
|
479
|
+
// would read as a closed set of four generation knobs when the whole point of its
|
|
480
|
+
// `[key: string]: unknown` is that a provider takes arbitrary ones.
|
|
481
|
+
for (const info of checker.getIndexInfosOfType(declared)) {
|
|
482
|
+
members.push(`[key: ${checker.typeToString(info.keyType)}]: ${checker.typeToString(info.type)}`);
|
|
483
|
+
}
|
|
484
|
+
for (const prop of checker.getPropertiesOfType(declared)) {
|
|
485
|
+
const sig = (prop.declarations ?? []).find(ts.isPropertySignature);
|
|
486
|
+
if (!sig?.type) return undefined; // a member we can't render ⇒ keep the name
|
|
487
|
+
const opt = (prop.flags & ts.SymbolFlags.Optional) !== 0 ? '?' : '';
|
|
488
|
+
members.push(`${prop.name}${opt}: ${expandNamed(sig.type, nextPath, depth + 1)}`);
|
|
489
|
+
}
|
|
490
|
+
return members.length ? `{ ${members.join('; ')} }` : undefined;
|
|
491
|
+
};
|
|
492
|
+
|
|
493
|
+
const visit = (n: TS.Node): void => {
|
|
494
|
+
if (ts.isTypeReferenceNode(n)) {
|
|
495
|
+
const text = expansionOf(n);
|
|
496
|
+
if (text !== undefined) { repls.push({ s: n.getStart() - base, e: n.getEnd() - base, t: text }); return; }
|
|
497
|
+
n.typeArguments?.forEach(visit);
|
|
498
|
+
return;
|
|
499
|
+
}
|
|
500
|
+
ts.forEachChild(n, visit);
|
|
501
|
+
};
|
|
502
|
+
visit(node);
|
|
503
|
+
|
|
504
|
+
let text = node.getText();
|
|
505
|
+
for (const r of repls.sort((a, b) => b.s - a.s)) text = text.slice(0, r.s) + r.t + text.slice(r.e);
|
|
506
|
+
return text;
|
|
507
|
+
};
|
|
508
|
+
|
|
282
509
|
const extractArms = (ann: TS.TypeNode): { params: string; result: string } | undefined => {
|
|
283
|
-
const
|
|
510
|
+
const resolved = resolveAlias(ann);
|
|
511
|
+
const arms = ts.isUnionTypeNode(resolved) ? [...resolved.types] : [resolved];
|
|
284
512
|
const params: string[] = [], results: string[] = [];
|
|
285
|
-
for (const
|
|
513
|
+
for (const raw of arms) {
|
|
514
|
+
const a = resolveAlias(raw);
|
|
286
515
|
if (!ts.isTypeReferenceNode(a) || a.typeName.getText() !== 'ToolContract' || a.typeArguments?.length !== 2) return undefined;
|
|
287
|
-
results.push(a.typeArguments[0]
|
|
288
|
-
params.push(a.typeArguments[1]
|
|
516
|
+
results.push(expandNamed(a.typeArguments[0]!, new Set(), 0));
|
|
517
|
+
params.push(expandNamed(a.typeArguments[1]!, new Set(), 0));
|
|
289
518
|
}
|
|
290
519
|
return { result: results.join(' | '), params: params.join(' | ') };
|
|
291
520
|
};
|
|
@@ -293,6 +522,7 @@ export async function buildMatbotToolsDts(projectRoot: string, pluginEntryUrls?:
|
|
|
293
522
|
const toolContractsSym = findCanonicalSymbol('ToolContracts');
|
|
294
523
|
if (toolContractsSym) {
|
|
295
524
|
for (const prop of checker.getPropertiesOfType(checker.getDeclaredTypeOfSymbol(toolContractsSym))) {
|
|
525
|
+
if (live !== undefined && !live.has(prop.name)) continue; // same live-registry filter as the dts
|
|
296
526
|
const decl = (prop.declarations ?? []).find(d => ts.isPropertySignature(d));
|
|
297
527
|
const ann = decl && ts.isPropertySignature(decl) ? decl.type : undefined;
|
|
298
528
|
if (!ann) continue;
|
|
@@ -308,12 +538,13 @@ export async function buildMatbotToolsDts(projectRoot: string, pluginEntryUrls?:
|
|
|
308
538
|
const bundleBlock = bundledDecls.size ? `${[...bundledDecls.values()].join('\n\n')}\n\n` : '';
|
|
309
539
|
const dts = `import '@matatbread/matbot-plugin-api';
|
|
310
540
|
${importLine}${bundleBlock}declare module '@matatbread/matbot-plugin-api' {
|
|
311
|
-
${block('ToolContracts', tools.lines)}${block('MatbotServices', services.lines)}}
|
|
541
|
+
${block('ToolContracts', tools.lines)}${block('MatbotServices', services.lines)}${augmentations.length ? `${augmentations.join('\n')}\n` : ''}}
|
|
312
542
|
`;
|
|
313
543
|
return {
|
|
314
544
|
dts,
|
|
315
545
|
tools: { emitted: tools.emitted, unknown: tools.unknown },
|
|
316
546
|
services: { emitted: services.emitted, unknown: services.unknown },
|
|
547
|
+
conflicts,
|
|
317
548
|
contracts,
|
|
318
549
|
apiExports: [...apiTypeNames],
|
|
319
550
|
};
|
package/src/index.ts
CHANGED
|
@@ -126,10 +126,16 @@ class ToolTypeIndexImpl implements ToolTypeIndex {
|
|
|
126
126
|
const root = this.machine.configPath !== undefined ? dirname(this.machine.configPath) : '.';
|
|
127
127
|
// Scan the source each loaded plugin was actually loaded from (its resolvedUrl) — builtin, compiled
|
|
128
128
|
// (compiled-plugins/), or installed (.plugins/) alike — so every registered tool's real augmentation
|
|
129
|
-
// is read. build-dts
|
|
130
|
-
//
|
|
129
|
+
// is read. build-dts UNIONs a glob of the monorepo `plugins/` tree onto these roots (not a fallback:
|
|
130
|
+
// it catches host-constructed builtins that have no resolvedUrl), so the scanned set is a SUPERSET of
|
|
131
|
+
// the loaded one — wherever that tree exists, plugins for other runtimes and plugins nobody loaded are
|
|
132
|
+
// read too. Hence the live tool names: a scanned root may supply a tool's contract, never the fact that
|
|
133
|
+
// the tool exists. Otherwise the dts declares uncallable tools (`telegram_send` from an unloaded
|
|
134
|
+
// telegram frontend), which `check()` then grades generated code against — clean typecheck, "not
|
|
135
|
+
// registered" at runtime. What the scan CAN'T settle is two roots declaring one live name; that stays
|
|
136
|
+
// Program-order and audible via `conflicts`.
|
|
131
137
|
const urls = getRegisteredPlugins().map(p => p.resolvedUrl).filter((u): u is string => u !== undefined);
|
|
132
|
-
const built = await buildMatbotToolsDts(root, urls);
|
|
138
|
+
const built = await buildMatbotToolsDts(root, urls, this.machine.tools.list().map(t => t.name));
|
|
133
139
|
this.cache = built?.dts ?? '';
|
|
134
140
|
this.covered = new Set([...(built?.tools.emitted ?? []), ...(built?.tools.unknown ?? [])]);
|
|
135
141
|
this.contracts = built?.contracts ?? {};
|