@matatbread/matbot-tool-types 0.3.0

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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Mat Woolf
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "@matatbread/matbot-tool-types",
3
+ "matbotRuntime": [
4
+ "node"
5
+ ],
6
+ "version": "0.3.0",
7
+ "engines": {
8
+ "node": ">=24.0.0"
9
+ },
10
+ "files": [
11
+ "src"
12
+ ],
13
+ "description": "Node-only ToolTypeIndex service: derives a self-contained .d.ts of the loaded tools' result/service types (by compiling their `declare module` augmentations) so tool-call code generators and composers can type what `tool` calls resolve to.",
14
+ "keywords": [
15
+ "matbot",
16
+ "matbot-plugin",
17
+ "llm",
18
+ "ai",
19
+ "agent",
20
+ "typescript"
21
+ ],
22
+ "license": "Apache-2.0",
23
+ "type": "module",
24
+ "exports": {
25
+ ".": "./src/index.ts"
26
+ },
27
+ "repository": {
28
+ "type": "git",
29
+ "url": "git+https://github.com/MatAtBread/matbot.git",
30
+ "directory": "plugins/tool-types"
31
+ },
32
+ "publishConfig": {
33
+ "access": "public"
34
+ },
35
+ "dependencies": {
36
+ "typescript": "^6.0.3"
37
+ },
38
+ "peerDependencies": {
39
+ "@matatbread/matbot-core": "^0.3.0",
40
+ "@matatbread/matbot-plugin-api": "^0.3.0"
41
+ },
42
+ "devDependencies": {
43
+ "@types/node": "^22.0.0",
44
+ "typescript": "^6.0.3",
45
+ "@matatbread/matbot-plugin-api": "^0.3.0",
46
+ "@matatbread/matbot-core": "^0.3.0"
47
+ },
48
+ "scripts": {
49
+ "typecheck": "tsc --noEmit"
50
+ }
51
+ }
@@ -0,0 +1,320 @@
1
+ import type TS from 'typescript';
2
+
3
+ // Derive a self-contained `declare module … { interface ToolContracts {…} interface MatbotServices {…} }`
4
+ // from the live type graph, so a compiled (or hand-rolled) plugin's compilation sees correct types for
5
+ // the tools it can call (`toolResult`) AND the registry services on its `MatbotMachine` (`services.X`) —
6
+ // the practical goal being that the codegen/typecheck loop gets the earliest possible warning that
7
+ // generated code is unsound. The runtime registry can't supply this (result/service types are erased);
8
+ // only a TS compilation reading each plugin's `declare module` augmentation can.
9
+ //
10
+ // Each member's type closure is walked. A referenced named type is classified and:
11
+ // - plugin-api export → referenced by name + imported from plugin-api (the generated plugin has it).
12
+ // - TS-lib global → referenced by name (global, nothing to do).
13
+ // - workspace interface/type-alias → its declaration is EMITTED into the DTS (recursing its own refs),
14
+ // so the DTS stays self-contained.
15
+ // - workspace class/enum/function, or any `node_modules`/unresolved type → can't be made
16
+ // self-contained, so that *leaf* is replaced in place with `unknown` and a
17
+ // comment naming it (LEAF substitution — `(req: unknown /* IncomingMessage */) =>
18
+ // …` keeps the rest of the type useful). `unknown` is sound here: permissive in
19
+ // a parameter, narrow-forcing in a result. The whole member only collapses to
20
+ // `unknown` when the offender sits where `unknown` can't go (e.g. an `extends`
21
+ // base). The naming comment is emitted once per distinct offender.
22
+ //
23
+ // For `MatbotServices` only the plugin-contributed members are emitted; the base members (`Vault`,
24
+ // `StorageBackend?`, `KnowledgeIndex`) are already visible through plugin-api.
25
+ //
26
+ // Caveat: `ts.createProgram` over the workspace runs in-process and briefly blocks the event loop.
27
+ // Acceptable once-per-compile; the planned coverage work (drive off the live loaded-plugin set, build
28
+ // lazily + dirty on plugin load) also removes that cost. Coverage today is the monorepo `plugins/` tree.
29
+
30
+ export interface MatbotToolsDts {
31
+ dts: string;
32
+ tools: { emitted: string[]; unknown: string[] };
33
+ services: { emitted: string[]; unknown: string[] };
34
+ // Per source-scanned tool: its wire contract — the flattened `params`/`result` union text, extracted
35
+ // from the `ToolContracts` arms. The single authored contract (the arms) is thus also the source of the
36
+ // wire description, so a source tool's `ToolContracts` augmentation is its single contract.
37
+ contracts: Record<string, { params: string; result: string }>;
38
+ // The names of every plugin-api type export. A source-less tool's `toolContract` string may name one
39
+ // (e.g. `StoreQuery`); the consumer (ToolTypeIndex) uses this to import the ones it references so those
40
+ // references resolve rather than dangle.
41
+ apiExports: string[];
42
+ }
43
+
44
+ type Classification =
45
+ | { tag: 'ignore' }
46
+ | { tag: 'lib' }
47
+ | { tag: 'api' }
48
+ | { tag: 'bundle'; sym: TS.Symbol }
49
+ | { tag: 'bail'; label: string };
50
+
51
+ // `pluginEntryUrls` are the resolved import URLs of the LIVE loaded plugins (each plugin's `resolvedUrl`,
52
+ // via the `plugin` tool's `list`). Each entry is used as a Program root: it pulls in that plugin's own
53
+ // augmenting files transitively, so coverage follows the actual loaded set (npm / `.plugins/` / local),
54
+ // not just the monorepo tree. When none resolve to on-disk source, falls back to globbing the monorepo
55
+ // `plugins/` tree. Returns null when neither yields anything (the caller then uses its static DTS).
56
+ export async function buildMatbotToolsDts(projectRoot: string, pluginEntryUrls?: readonly string[]): Promise<MatbotToolsDts | null> {
57
+ const ts = (await import('typescript')).default as typeof TS;
58
+ const { readFileSync, readdirSync, statSync, existsSync } = await import('node:fs');
59
+ const { join } = await import('node:path');
60
+ const { fileURLToPath } = await import('node:url');
61
+ const { createRequire } = await import('node:module');
62
+
63
+ // Anchor plugin-api at the monorepo source if present, else the installed package.
64
+ const monorepoApi = join(projectRoot, 'plugin-api', 'src', 'index.ts');
65
+ let pluginApiIndex: string | undefined = existsSync(monorepoApi) ? monorepoApi : undefined;
66
+ if (!pluginApiIndex) {
67
+ try { pluginApiIndex = createRequire(join(projectRoot, '_')).resolve('@matatbread/matbot-plugin-api'); } catch { /* unresolved */ }
68
+ }
69
+ if (!pluginApiIndex) return null;
70
+
71
+ const roots = new Set<string>([pluginApiIndex]);
72
+
73
+ // A loaded plugin's `resolvedUrl` → an on-disk type-bearing source file. `.ts`/`.d.ts` used directly;
74
+ // an npm `.js` entry maps to its sibling `.d.ts`; anything else (blob:, bare specifier, missing) skipped.
75
+ const toSource = (u: string): string | undefined => {
76
+ let p: string;
77
+ try { p = u.startsWith('file:') ? fileURLToPath(u) : u; } catch { return undefined; }
78
+ if (/\.d\.ts$|(?<!\.d)\.ts$/.test(p)) return existsSync(p) ? p : undefined;
79
+ if (p.endsWith('.js')) { const d = p.replace(/\.js$/, '.d.ts'); return existsSync(d) ? d : undefined; }
80
+ return undefined;
81
+ };
82
+ for (const u of pluginEntryUrls ?? []) { const p = toSource(u); if (p) roots.add(p); }
83
+
84
+ // UNION with a glob of the monorepo `plugins/` tree (not a fallback): the resolvedUrl roots above cover
85
+ // every *loaded* plugin (builtin, compiled, installed), but miss monorepo source that isn't loaded as a
86
+ // plugin with a resolvedUrl — notably the app-embedded `plugin`/`provider` builtins in `plugins/tool-plugin/`,
87
+ // which the host constructs directly. The glob catches those. In a real deployment there is no `plugins/`
88
+ // tree, so this no-ops and the scan is purely resolvedUrl-driven. Dedup is by path (a Set of roots).
89
+ // Generated `matbot-tools.d.ts` files are skipped (don't feed prior output back in). `skills_compiler` IS
90
+ // scanned — it declares its own `skill_compiler` ToolContracts arm, which must be seen; its loose
91
+ // `MatbotServices.SkillManager` slice is a harmless duplicate of the real one (the skills package is
92
+ // walked first, so its full declaration wins the emit; and `services.SkillManager` isn't referenced by
93
+ // generated/compiled plugin code anyway).
94
+ if (existsSync(join(projectRoot, 'plugins'))) {
95
+ const SKIP = new Set(['node_modules', 'dist', '.git', 'compiled-plugins']);
96
+ const walk = (dir: string): void => {
97
+ let entries: string[];
98
+ try { entries = readdirSync(dir); } catch { return; }
99
+ for (const name of entries) {
100
+ if (SKIP.has(name)) continue;
101
+ const p = join(dir, name);
102
+ let isDir: boolean;
103
+ try { isDir = statSync(p).isDirectory(); } catch { continue; }
104
+ if (isDir) { walk(p); continue; }
105
+ if (!name.endsWith('.ts') || name.endsWith('matbot-tools.d.ts')) continue;
106
+ const src = readFileSync(p, 'utf8');
107
+ if (/declare\s+module\s+['"]@matatbread\/matbot-plugin-api['"]/.test(src) && /\binterface\s+(?:ToolContracts|MatbotServices)\b/.test(src)) roots.add(p);
108
+ }
109
+ };
110
+ walk(join(projectRoot, 'plugins'));
111
+ }
112
+ if (roots.size === 1) return null; // nothing to scan beyond plugin-api itself
113
+
114
+ const program = ts.createProgram([...roots], {
115
+ target: ts.ScriptTarget.ES2022,
116
+ module: ts.ModuleKind.NodeNext,
117
+ moduleResolution: ts.ModuleResolutionKind.NodeNext,
118
+ strict: true,
119
+ exactOptionalPropertyTypes: true,
120
+ noEmit: true,
121
+ skipLibCheck: true,
122
+ baseUrl: projectRoot,
123
+ });
124
+ const checker = program.getTypeChecker();
125
+
126
+ const apiSf = program.getSourceFile(pluginApiIndex)
127
+ ?? program.getSourceFiles().find(f => f.fileName.includes('/plugin-api/') && /\/index\.d?\.ts$/.test(f.fileName));
128
+ if (!apiSf) return null;
129
+ const apiModule = checker.getSymbolAtLocation(apiSf);
130
+ if (!apiModule) return null;
131
+ const apiExports = checker.getExportsOfModule(apiModule);
132
+ const TYPE_FLAGS = ts.SymbolFlags.Type | ts.SymbolFlags.Interface | ts.SymbolFlags.TypeAlias;
133
+ const apiTypeNames = new Set(apiExports.filter(s => (s.flags & TYPE_FLAGS) !== 0).map(s => s.name));
134
+
135
+ // Resolve an augmentable interface from its CANONICAL top-level declaration in plugin-api, not the
136
+ // index.ts re-export: `export * from './plugin.js'` (MatbotServices) exposes a stunted re-export view
137
+ // that drops cross-file augmentations; the canonical declaration's symbol carries the merged set.
138
+ const findCanonicalSymbol = (name: string): TS.Symbol | undefined => {
139
+ for (const sf of program.getSourceFiles()) {
140
+ if (!sf.fileName.includes('/plugin-api/')) continue;
141
+ let found: TS.Symbol | undefined;
142
+ const visit = (n: TS.Node): void => {
143
+ if (found) return;
144
+ if (ts.isInterfaceDeclaration(n) && n.name.text === name && !ts.isModuleBlock(n.parent)) {
145
+ found = checker.getSymbolAtLocation(n.name);
146
+ return;
147
+ }
148
+ ts.forEachChild(n, visit);
149
+ };
150
+ ts.forEachChild(sf, visit);
151
+ if (found) return found;
152
+ }
153
+ return undefined;
154
+ };
155
+
156
+ const inPluginApi = (sym: TS.Symbol): boolean =>
157
+ (sym.declarations ?? []).every(d => d.getSourceFile().fileName.includes('/plugin-api/'));
158
+
159
+ // Classify a referenced type symbol (resolving import aliases to the real declaration first).
160
+ const classify = (raw: TS.Symbol): Classification => {
161
+ const wasAlias = (raw.flags & ts.SymbolFlags.Alias) !== 0;
162
+ const sym = wasAlias ? checker.getAliasedSymbol(raw) : raw;
163
+ if ((sym.flags & ts.SymbolFlags.TypeParameter) !== 0) return { tag: 'ignore' };
164
+ const decls = sym.declarations ?? [];
165
+ // An alias resolving to nothing is an unresolved external import (e.g. `IncomingMessage` from
166
+ // `node:http` when @types/node isn't in this program). A non-alias with no declarations is an
167
+ // intrinsic/synthesised type.
168
+ if (decls.length === 0) return wasAlias ? { tag: 'bail', label: `${raw.name} (external)` } : { tag: 'ignore' };
169
+ const files = decls.map(d => d.getSourceFile());
170
+ if (files.every(f => program.isSourceFileDefaultLibrary(f))) return { tag: 'lib' };
171
+ if (files.some(f => f.fileName.includes('/plugin-api/'))) return { tag: 'api' };
172
+ if (files.some(f => f.fileName.includes('/node_modules/'))) return { tag: 'bail', label: `${sym.name} (external)` };
173
+ const d0 = decls[0]!;
174
+ if (ts.isInterfaceDeclaration(d0) || ts.isTypeAliasDeclaration(d0)) return { tag: 'bundle', sym };
175
+ const kind = ts.isClassDeclaration(d0) ? 'class' : ts.isEnumDeclaration(d0) ? 'enum' : ts.isFunctionDeclaration(d0) ? 'function' : 'value';
176
+ return { tag: 'bail', label: `${kind} ${sym.name}` };
177
+ };
178
+ const classifyEntity = (entity: TS.EntityName): Classification => {
179
+ const sym = checker.getSymbolAtLocation(entity);
180
+ if (!sym) return { tag: 'bail', label: `${entity.getText()} (unresolved)` };
181
+ return classify(sym);
182
+ };
183
+
184
+ const stripModifiers = (text: string): string => text.replace(/^export\s+/, '').replace(/^declare\s+/, '');
185
+ const declKey = (d: TS.Node): string => `${d.getSourceFile().fileName}:${d.getStart()}`;
186
+
187
+ // Emit comment-per-offender once, so a recurring external type doesn't litter every site.
188
+ const commented = new Set<string>();
189
+ const unknownOf = (label: string): string => {
190
+ if (commented.has(label)) return 'unknown';
191
+ commented.add(label);
192
+ return `unknown /* ${label} */`;
193
+ };
194
+
195
+ const importNames = new Set<string>();
196
+ const bundledDecls = new Map<string, string>();
197
+
198
+ interface Ctx { imports: Set<string>; seen: Set<string>; heritageBail: string | null; }
199
+
200
+ // Emit `node`'s source text with every bailing type-reference replaced in place by `unknown` (leaf
201
+ // substitution). Accumulates imports (plugin-api refs) and bundled declarations (workspace refs,
202
+ // recursively emitted through here too). Sets `ctx.heritageBail` if a bail sits in an `extends` base,
203
+ // where `unknown` can't go — the caller then collapses that whole member.
204
+ const emitNode = (node: TS.Node, ctx: Ctx): string => {
205
+ const base = node.getStart();
206
+ const repls: Array<{ s: number; e: number; t: string }> = [];
207
+ const bundle = (sym: TS.Symbol): void => {
208
+ for (const d of sym.declarations ?? []) {
209
+ if (!ts.isInterfaceDeclaration(d) && !ts.isTypeAliasDeclaration(d)) continue;
210
+ const key = declKey(d);
211
+ if (ctx.seen.has(key)) continue;
212
+ ctx.seen.add(key);
213
+ bundledDecls.set(key, stripModifiers(emitNode(d, ctx)));
214
+ }
215
+ };
216
+ const visit = (n: TS.Node): void => {
217
+ if (ctx.heritageBail) return;
218
+ if (ts.isTypeReferenceNode(n)) {
219
+ const c = classifyEntity(n.typeName);
220
+ if (c.tag === 'bail') { repls.push({ s: n.getStart() - base, e: n.getEnd() - base, t: unknownOf(c.label) }); return; }
221
+ if (c.tag === 'api') importNames.add(n.typeName.getText());
222
+ else if (c.tag === 'bundle') bundle(c.sym);
223
+ n.typeArguments?.forEach(visit);
224
+ return;
225
+ }
226
+ if (ts.isExpressionWithTypeArguments(n) && ts.isIdentifier(n.expression)) { // heritage base
227
+ const c = classifyEntity(n.expression);
228
+ if (c.tag === 'bail') { ctx.heritageBail = c.label; return; }
229
+ if (c.tag === 'api') importNames.add(n.expression.getText());
230
+ else if (c.tag === 'bundle') bundle(c.sym);
231
+ n.typeArguments?.forEach(visit);
232
+ return;
233
+ }
234
+ ts.forEachChild(n, visit);
235
+ };
236
+ visit(node);
237
+ let text = node.getText();
238
+ for (const r of repls.sort((a, b) => b.s - a.s)) text = text.slice(0, r.s) + r.t + text.slice(r.e);
239
+ return text;
240
+ };
241
+
242
+ // Emit one augmentable interface's plugin-contributed members. `onlyAugmented` skips base members
243
+ // already visible via plugin-api (no-op for ToolContracts).
244
+ const emitInterface = (interfaceName: string, onlyAugmented: boolean): { lines: string[]; emitted: string[]; unknown: string[] } => {
245
+ const sym = findCanonicalSymbol(interfaceName);
246
+ const lines: string[] = [], emitted: string[] = [], unknownNames: string[] = [];
247
+ if (!sym) return { lines, emitted, unknown: unknownNames };
248
+ const props = [...checker.getPropertiesOfType(checker.getDeclaredTypeOfSymbol(sym))].sort((a, b) => a.name.localeCompare(b.name));
249
+ for (const prop of props) {
250
+ if (onlyAugmented && inPluginApi(prop)) continue;
251
+ const optional = (prop.flags & ts.SymbolFlags.Optional) !== 0 ? '?' : '';
252
+ const decl = (prop.declarations ?? []).find(d => ts.isPropertySignature(d));
253
+ const ann = decl && ts.isPropertySignature(decl) ? decl.type : undefined;
254
+ if (!ann) {
255
+ lines.push(` ${prop.name}${optional}: ${unknownOf('no type annotation')};`);
256
+ unknownNames.push(prop.name);
257
+ continue;
258
+ }
259
+ const ctx: Ctx = { imports: new Set(), seen: new Set(), heritageBail: null };
260
+ const text = emitNode(ann, ctx);
261
+ if (ctx.heritageBail) { // can't substitute in `extends` — whole member unknown
262
+ lines.push(` ${prop.name}${optional}: ${unknownOf(ctx.heritageBail)};`);
263
+ unknownNames.push(prop.name);
264
+ continue;
265
+ }
266
+ ctx.imports.forEach(n => importNames.add(n));
267
+ lines.push(` ${prop.name}${optional}: ${text};`);
268
+ // A member whose own annotation was entirely replaced is effectively unknown; one with only nested
269
+ // substitutions is still a usable typed surface.
270
+ if (/^unknown\b/.test(text.trim())) unknownNames.push(prop.name);
271
+ else emitted.push(prop.name);
272
+ }
273
+ return { lines, emitted, unknown: unknownNames };
274
+ };
275
+
276
+ const tools = emitInterface('ToolContracts', false);
277
+ const services = emitInterface('MatbotServices', true);
278
+
279
+ // Per-tool wire contract: flatten each `ToolContracts` arm to its `params`/`result` union source text.
280
+ // Only pure `ToolContract<R, P>`-arm entries yield one (a bare/plain entry is skipped — it keeps whatever
281
+ // the tool authored). This is the flat params/result union the wire description needs, from the arms.
282
+ const extractArms = (ann: TS.TypeNode): { params: string; result: string } | undefined => {
283
+ const arms = ts.isUnionTypeNode(ann) ? [...ann.types] : [ann];
284
+ const params: string[] = [], results: string[] = [];
285
+ for (const a of arms) {
286
+ if (!ts.isTypeReferenceNode(a) || a.typeName.getText() !== 'ToolContract' || a.typeArguments?.length !== 2) return undefined;
287
+ results.push(a.typeArguments[0]!.getText());
288
+ params.push(a.typeArguments[1]!.getText());
289
+ }
290
+ return { result: results.join(' | '), params: params.join(' | ') };
291
+ };
292
+ const contracts: Record<string, { params: string; result: string }> = {};
293
+ const toolContractsSym = findCanonicalSymbol('ToolContracts');
294
+ if (toolContractsSym) {
295
+ for (const prop of checker.getPropertiesOfType(checker.getDeclaredTypeOfSymbol(toolContractsSym))) {
296
+ const decl = (prop.declarations ?? []).find(d => ts.isPropertySignature(d));
297
+ const ann = decl && ts.isPropertySignature(decl) ? decl.type : undefined;
298
+ if (!ann) continue;
299
+ const c = extractArms(ann);
300
+ if (c) contracts[prop.name] = c;
301
+ }
302
+ }
303
+
304
+ const block = (name: string, lines: string[]): string =>
305
+ lines.length ? ` interface ${name} {\n${lines.join('\n')}\n }\n` : '';
306
+ const imports = [...importNames].filter(n => apiTypeNames.has(n)).sort();
307
+ const importLine = imports.length ? `import type { ${imports.join(', ')} } from '@matatbread/matbot-plugin-api';\n` : '';
308
+ const bundleBlock = bundledDecls.size ? `${[...bundledDecls.values()].join('\n\n')}\n\n` : '';
309
+ const dts = `import '@matatbread/matbot-plugin-api';
310
+ ${importLine}${bundleBlock}declare module '@matatbread/matbot-plugin-api' {
311
+ ${block('ToolContracts', tools.lines)}${block('MatbotServices', services.lines)}}
312
+ `;
313
+ return {
314
+ dts,
315
+ tools: { emitted: tools.emitted, unknown: tools.unknown },
316
+ services: { emitted: services.emitted, unknown: services.unknown },
317
+ contracts,
318
+ apiExports: [...apiTypeNames],
319
+ };
320
+ }
package/src/index.ts ADDED
@@ -0,0 +1,256 @@
1
+ import type TS from 'typescript';
2
+ import { dirname, join } from 'node:path';
3
+ import { existsSync } from 'node:fs';
4
+ import { createRequire } from 'node:module';
5
+ import { PLUGIN_API_VERSION } from '@matatbread/matbot-plugin-api';
6
+ import type { MatbotMachine, MatbotPluginSpec, ToolTypeIndex } from '@matatbread/matbot-plugin-api';
7
+ import { getRegisteredPlugins } from '@matatbread/matbot-core';
8
+ import { buildMatbotToolsDts } from './build-dts.js';
9
+
10
+ export { buildMatbotToolsDts, type MatbotToolsDts } from './build-dts.js';
11
+
12
+ // Split a string on `sep` at bracket-depth 0 only (respecting `<> {} () []`), so a top-level `|` or `,`
13
+ // inside a nested type isn't mistaken for a separator.
14
+ function splitTopLevel(s: string, sep: string): string[] {
15
+ const parts: string[] = [];
16
+ let depth = 0, start = 0;
17
+ for (let i = 0; i < s.length; i++) {
18
+ const c = s[i];
19
+ if (c === '<' || c === '{' || c === '(' || c === '[') depth++;
20
+ else if (c === '>' || c === '}' || c === ')' || c === ']') depth--;
21
+ else if (depth === 0 && c === sep) { parts.push(s.slice(start, i)); start = i + 1; }
22
+ }
23
+ parts.push(s.slice(start));
24
+ return parts;
25
+ }
26
+
27
+ // Flatten a `toolContract` (`ToolContract<Result, Args>`, or a `|`-union of such arms) to the wire's
28
+ // `params`/`result` union text — the same projection build-dts derives from source arms.
29
+ function splitContract(contract: string): { params: string; result: string } {
30
+ const results: string[] = [], params: string[] = [];
31
+ for (const armText of splitTopLevel(contract, '|')) {
32
+ const m = armText.trim().match(/^ToolContract\s*<([\s\S]*)>$/);
33
+ if (!m) continue;
34
+ const inner = splitTopLevel(m[1]!, ',');
35
+ if (inner[0] !== undefined) results.push(inner[0].trim());
36
+ if (inner[1] !== undefined) params.push(inner[1].trim());
37
+ }
38
+ return { result: results.join(' | ') || 'unknown', params: params.join(' | ') || 'unknown' };
39
+ }
40
+
41
+ // Best-effort JSON-Schema → TypeScript type text. Used only for the params half of a tool that has neither
42
+ // a source augmentation nor a `toolContract` (a foreign/MCP proxy): its `inputSchema` is always present, so
43
+ // we synthesise *something* structural rather than leaving `unknown` — so a composer sees real fields. There
44
+ // is no 1:1 JSON-Schema↔TS mapping; this is deliberately shallow and total — anything unrecognised degrades
45
+ // to `unknown` (never throws), and the output is purely structural (no named refs) so the dts stays
46
+ // self-contained. `unknown` here flows back through `ArmCallSig`'s `unknown extends P` branch to an
47
+ // optional param, so an opaque schema still leaves the tool callable arg-less.
48
+ // Enhancement (parked, not needed now): a fuller conversion — $ref/allOf/format/pattern/const/tuples —
49
+ // could be delegated to a package like `json-schema-to-typescript`. This dependency-free shallow pass is
50
+ // enough to give a composer real fields for the common MCP shapes.
51
+ function schemaToTs(schema: unknown, depth = 0): string {
52
+ if (depth > 6 || schema === null || typeof schema !== 'object') return 'unknown';
53
+ const s = schema as Record<string, unknown>;
54
+ const lit = (v: unknown): string =>
55
+ typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean' || v === null ? JSON.stringify(v) : 'unknown';
56
+
57
+ const union = s['anyOf'] ?? s['oneOf'];
58
+ if (Array.isArray(union)) {
59
+ const parts = [...new Set(union.map(u => schemaToTs(u, depth + 1)))];
60
+ return parts.length ? parts.join(' | ') : 'unknown';
61
+ }
62
+ if (Array.isArray(s['enum'])) {
63
+ const parts = [...new Set(s['enum'].map(lit))];
64
+ return parts.length ? parts.join(' | ') : 'unknown';
65
+ }
66
+ const type = s['type'];
67
+ if (Array.isArray(type)) return [...new Set(type.map(t => schemaToTs({ ...s, type: t }, depth)))].join(' | ') || 'unknown';
68
+ switch (type) {
69
+ case 'string': return 'string';
70
+ case 'integer':
71
+ case 'number': return 'number';
72
+ case 'boolean': return 'boolean';
73
+ case 'null': return 'null';
74
+ case 'array': {
75
+ const items = Array.isArray(s['items']) ? 'unknown' : schemaToTs(s['items'], depth + 1);
76
+ return /[ |&]/.test(items) ? `Array<${items}>` : `${items}[]`;
77
+ }
78
+ }
79
+ const props = s['properties'] && typeof s['properties'] === 'object' ? s['properties'] as Record<string, unknown> : undefined;
80
+ if (props && Object.keys(props).length > 0) {
81
+ const required = new Set(Array.isArray(s['required']) ? s['required'] as unknown[] : []);
82
+ const members = Object.entries(props).map(([k, v]) => {
83
+ const key = /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(k) ? k : JSON.stringify(k);
84
+ return `${key}${required.has(k) ? '' : '?'}: ${schemaToTs(v, depth + 1)}`;
85
+ });
86
+ return `{ ${members.join('; ')} }`;
87
+ }
88
+ if (type === 'object') {
89
+ const ap = s['additionalProperties'];
90
+ return ap !== null && typeof ap === 'object' ? `Record<string, ${schemaToTs(ap, depth + 1)}>` : 'Record<string, unknown>';
91
+ }
92
+ return 'unknown';
93
+ }
94
+
95
+ /**
96
+ * Derives (via {@link buildMatbotToolsDts}) and caches the `.d.ts` of what the loaded tools' calls resolve
97
+ * to, invalidating on any tool-registry change. The scan is driven off the loaded plugins' `resolvedUrl`s —
98
+ * the real source each tool was loaded from — so builtin, compiled, and installed plugins are all covered
99
+ * (the types are erased at runtime, but the `.ts` the runtime loaded from is still on disk). A source-less
100
+ * tool (a `function-tools` function; the `tool-store` per-namespace tool) carries its contract on the
101
+ * registered `Tool` as a `toolContract` string, appended in a second augmentation block; a name the scan
102
+ * already declares is skipped, so nothing is declared twice. `declare const tool: ToolProxy` (mapped over
103
+ * the merged `ToolContracts`) is what generators call.
104
+ */
105
+ class ToolTypeIndexImpl implements ToolTypeIndex {
106
+ private readonly machine: MatbotMachine;
107
+ private readonly ac = new AbortController();
108
+ private covered = new Set<string>(); // tool names the source scan already declares (registry-block dedup)
109
+ private cache: string | null = null; // null ⇒ (re)build needed
110
+ private contracts: Record<string, { params: string; result: string }> = {}; // per-tool wire contract
111
+ private apiExports: string[] = []; // plugin-api type export names (for importing those a toolContract names)
112
+ private dirty = true;
113
+
114
+ constructor(machine: MatbotMachine) {
115
+ this.machine = machine;
116
+ void this.watchTools();
117
+ }
118
+
119
+ private async watchTools(): Promise<void> {
120
+ try { for await (const _ev of this.machine.tools.watch(this.ac.signal)) this.dirty = true; }
121
+ catch { /* signal aborted on teardown */ }
122
+ }
123
+
124
+ close(): void { this.ac.abort(); }
125
+
126
+ private async ensureBuilt(): Promise<void> {
127
+ if (this.dirty || this.cache === null) {
128
+ const root = this.machine.configPath !== undefined ? dirname(this.machine.configPath) : '.';
129
+ // Scan the source each loaded plugin was actually loaded from (its resolvedUrl) — builtin, compiled
130
+ // (compiled-plugins/), or installed (.plugins/) alike — so every registered tool's real augmentation
131
+ // is read. build-dts globs the monorepo `plugins/` tree ONLY as a fallback, when no resolvedUrl
132
+ // resolves to on-disk source (a host that constructed its plugins by hand).
133
+ const urls = getRegisteredPlugins().map(p => p.resolvedUrl).filter((u): u is string => u !== undefined);
134
+ const built = await buildMatbotToolsDts(root, urls);
135
+ this.cache = built?.dts ?? '';
136
+ this.covered = new Set([...(built?.tools.emitted ?? []), ...(built?.tools.unknown ?? [])]);
137
+ this.contracts = built?.contracts ?? {};
138
+ this.apiExports = built?.apiExports ?? [];
139
+ this.dirty = false;
140
+ }
141
+ }
142
+
143
+ async dts(): Promise<string> {
144
+ await this.ensureBuilt();
145
+ // `tool` — the injected proxy `function-tools`/compiled skills call — is `ToolProxy`, a mapped type over
146
+ // the (augmented) `ToolContracts`: each multi-arm entry becomes an overload set, so `await tool.x(params)`
147
+ // narrows its result by the params. Derived, never hand-authored; `check()` uses this same string, so what
148
+ // a generator is shown is exactly what it is graded against.
149
+ return `${this.registryBlock(this.cache!)}\ndeclare const tool: import('@matatbread/matbot-plugin-api').ToolProxy;\n`;
150
+ }
151
+
152
+ async wireContracts(): Promise<Record<string, { params: string; result: string }>> {
153
+ await this.ensureBuilt();
154
+ const out: Record<string, { params: string; result: string }> = {};
155
+ for (const [name, c] of Object.entries(this.contracts)) out[name] = c; // source tools: arms flattened by build-dts
156
+ for (const t of this.machine.tools.list()) { // source-less tools: split their toolContract
157
+ if (out[t.name] !== undefined || t.toolContract === undefined) continue;
158
+ out[t.name] = splitContract(t.toolContract);
159
+ }
160
+ return out;
161
+ }
162
+
163
+ async check(snippet: string): Promise<string[]> {
164
+ const ts = (await import('typescript')).default;
165
+ const root = this.machine.configPath !== undefined ? dirname(this.machine.configPath) : '.';
166
+ const prefix = `${await this.dts()}\n`;
167
+ const source = `${prefix}${snippet}\nexport {};\n`; // trailing export ⇒ this file is a module
168
+ const virtual = `${root}/__mb_toolcheck_${crypto.randomUUID()}.ts`;
169
+
170
+ // Anchor `@matatbread/matbot-plugin-api` — it isn't a bare-resolvable dep of the project root, so map it
171
+ // to the monorepo source (or the installed package). Without this the imports fail and every type
172
+ // collapses to `any`, silently passing bad snippets.
173
+ const monorepoApi = join(root, 'plugin-api', 'src', 'index.ts');
174
+ let apiIndex: string | undefined = existsSync(monorepoApi) ? monorepoApi : undefined;
175
+ if (apiIndex === undefined) {
176
+ try { apiIndex = createRequire(join(root, '_')).resolve('@matatbread/matbot-plugin-api'); } catch { /* unresolved */ }
177
+ }
178
+
179
+ const options: TS.CompilerOptions = {
180
+ target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.NodeNext, moduleResolution: ts.ModuleResolutionKind.NodeNext,
181
+ strict: true, exactOptionalPropertyTypes: true, noEmit: true, skipLibCheck: true, baseUrl: root,
182
+ ...(apiIndex !== undefined ? { paths: { '@matatbread/matbot-plugin-api': [apiIndex] } } : {}),
183
+ };
184
+ const host = ts.createCompilerHost(options);
185
+ const getSF = host.getSourceFile.bind(host);
186
+ host.getSourceFile = (f, lang, onErr, create) =>
187
+ f === virtual ? ts.createSourceFile(f, source, lang, true) : getSF(f, lang, onErr, create);
188
+ const fileExists = host.fileExists.bind(host); host.fileExists = f => f === virtual || fileExists(f);
189
+ const readFile = host.readFile.bind(host); host.readFile = f => (f === virtual ? source : readFile(f));
190
+
191
+ const program = ts.createProgram([virtual], options, host);
192
+ const sf = program.getSourceFile(virtual);
193
+ if (sf === undefined) return [];
194
+
195
+ const prefixLen = prefix.length;
196
+ const prefixLines = prefix.split('\n').length - 1;
197
+ const out: string[] = [];
198
+ for (const d of [...program.getSyntacticDiagnostics(sf), ...program.getSemanticDiagnostics(sf)]) {
199
+ if (typeof d.start !== 'number' || d.start < prefixLen) continue; // only the caller's snippet
200
+ const { line } = sf.getLineAndCharacterOfPosition(d.start);
201
+ out.push(`line ${line - prefixLines + 1}: ${ts.flattenDiagnosticMessageText(d.messageText, '\n')}`);
202
+ }
203
+ return out;
204
+ }
205
+
206
+ // Every live tool the source scan didn't already declare: a source-less tool that carries its contract as
207
+ // a `toolContract` string (a `function-tools` function; the `tool-store` per-namespace tool), spliced
208
+ // verbatim; plus any tool with neither augmentation nor `toolContract` (a foreign/MCP proxy, or a plugin
209
+ // with no resolvable source) — for which the result stays `unknown` but the params are synthesised from
210
+ // the tool's (always-present) `inputSchema` (see {@link schemaToTs}), so it isn't a bare
211
+ // `ToolContract<unknown, unknown>` and a composer sees real fields. Either way it appears in
212
+ // `keyof ToolContracts`, hence in `ToolProxy`, and stays callable. Names the source scan already declared
213
+ // are skipped, so nothing is declared twice. `ToolContract` is referenced bare — it resolves to the
214
+ // top-of-file import the derived block emits (every arm references it); when the scan produced nothing to
215
+ // import it (no source resolved, or an all-`MatbotServices` block), this block supplies that one import.
216
+ private registryBlock(derived: string): string {
217
+ const arms: string[] = [];
218
+ for (const t of this.machine.tools.list()) {
219
+ if (this.covered.has(t.name)) continue;
220
+ arms.push(` ${JSON.stringify(t.name)}: ${t.toolContract ?? `ToolContract<unknown, ${schemaToTs(t.inputSchema)}>`};`);
221
+ }
222
+ if (arms.length === 0) return derived;
223
+ const body = arms.join('\n');
224
+ // Import the plugin-api types these arms reference — `ToolContract` always, plus any plugin-api export a
225
+ // source-less `toolContract` names (e.g. `StoreQuery`) — minus whatever the derived block already imports
226
+ // (importing a name twice is a redeclaration error). A synthetic tool inlines its own shape types, so the
227
+ // only names left here are genuine plugin-api exports.
228
+ const alreadyImported = new Set(
229
+ (derived.match(/^import type \{([^}]*)\} from '@matatbread\/matbot-plugin-api'/m)?.[1] ?? '')
230
+ .split(',').map(s => s.trim()).filter(Boolean),
231
+ );
232
+ const referenced = ['ToolContract', ...this.apiExports.filter(n => new RegExp(`\\b${n}\\b`).test(body))];
233
+ const needed = [...new Set(referenced)].filter(n => !alreadyImported.has(n));
234
+ const head = needed.length
235
+ ? `${derived === '' ? "import '@matatbread/matbot-plugin-api';\n" : ''}import type { ${needed.join(', ')} } from '@matatbread/matbot-plugin-api';\n`
236
+ : '';
237
+ return `${head}${derived}\ndeclare module '@matatbread/matbot-plugin-api' {\n interface ToolContracts {\n${body}\n }\n}\n`;
238
+ }
239
+ }
240
+
241
+ export function createToolTypesPlugin(): MatbotPluginSpec {
242
+ let impl: ToolTypeIndexImpl | undefined;
243
+ return {
244
+ apiVersion: PLUGIN_API_VERSION,
245
+ manifest: { description: 'Node-only ToolTypeIndex service: derives a .d.ts of the loaded tools\' result/service types so tool-call code generators and composers (skills_compiler, function-tools) can type what `tool` calls resolve to.' },
246
+
247
+ async setup(services) {
248
+ impl = new ToolTypeIndexImpl(services);
249
+ await services.register('ToolTypeIndex', impl);
250
+ },
251
+
252
+ async teardown() { impl?.close(); },
253
+ };
254
+ }
255
+
256
+ export const plugin: MatbotPluginSpec = createToolTypesPlugin();