@matatbread/matbot-tool-types 0.3.1 → 0.3.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 CHANGED
@@ -3,7 +3,7 @@
3
3
  "matbotRuntime": [
4
4
  "node"
5
5
  ],
6
- "version": "0.3.1",
6
+ "version": "0.3.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.3.1",
40
- "@matatbread/matbot-core": "^0.3.1"
39
+ "@matatbread/matbot-plugin-api": "^0.3.3",
40
+ "@matatbread/matbot-core": "^0.3.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.3.1",
46
- "@matatbread/matbot-core": "^0.3.1"
45
+ "@matatbread/matbot-plugin-api": "^0.3.3",
46
+ "@matatbread/matbot-core": "^0.3.3"
47
47
  },
48
48
  "scripts": {
49
49
  "typecheck": "tsc --noEmit"
package/src/checker.ts ADDED
@@ -0,0 +1,307 @@
1
+ // The one TypeScript checker for LLM-generated code: the compiler API run in a worker thread
2
+ // (synchronous + CPU-bound, so never on the main loop — a check on the main thread freezes every
3
+ // frontend for its whole duration), returning STRUCTURED diagnostics formatted into anchored, hinted
4
+ // error text a code-generating model can act on in one pass. Two entry modes over one worker:
5
+ // checkProjectDir — a compiled plugin's build dir (tsconfig-driven), used by skills_compiler
6
+ // checkSnippetAgainst — a virtual file (ambient dts prefix + snippet), used by ToolTypeIndex.check
7
+ // to grade function-tools lambdas, with all positions snippet-relative
8
+ // There is deliberately NO fallback path: the inputs are fully determined (our own scaffold or our
9
+ // own virtual file, the same resolved typescript module), so a checker failure is a plumbing bug
10
+ // that must surface as the caller's error, not be absorbed by a quieter path.
11
+
12
+ export interface CheckResult { ok: boolean; output: string }
13
+
14
+ interface DiagnosticRecord {
15
+ code: number;
16
+ message: string;
17
+ file?: string;
18
+ line?: number;
19
+ col?: number;
20
+ frame?: string;
21
+ sourceLine?: string;
22
+ related?: string[];
23
+ /** True for a cast-gate finding (a structural rule, not a tsc error) — rendered as CAST, not TSnnnn. */
24
+ syn?: boolean;
25
+ }
26
+
27
+ // Hints keyed on error code plus (optionally) a pattern over the offending source line or message —
28
+ // the pattern is what makes them directed rather than generic. Kept few and high-confidence: a wrong
29
+ // hint is worse than none.
30
+ const HINTS: { codes: number[]; pattern?: RegExp; hint: string }[] = [
31
+ {
32
+ codes: [2739, 2322],
33
+ pattern: /ReturnType\s*<\s*typeof\s+tool\./,
34
+ hint: "an overload set does not narrow through ReturnType. Type the variable ToolResultOf<'<tool_name>'> (the union across the tool's arms, narrowed with a runtime guard before use), or assign the call directly: const r = await tool.<name>({ action: '...' }).",
35
+ },
36
+ {
37
+ codes: [2769, 2345],
38
+ pattern: /\btool\.\w+\s*\(/,
39
+ hint: 'the params must match exactly one arm of this tool\'s contract — check the action value and the required keys against the declared tool contracts.',
40
+ },
41
+ {
42
+ codes: [2532, 18048, 2531],
43
+ hint: 'noUncheckedIndexedAccess: an indexed access (array[i], record[key]) is T | undefined — guard it (if (v !== undefined) …) before use.',
44
+ },
45
+ {
46
+ codes: [2322, 2345],
47
+ pattern: /\| undefined' is not assignable/,
48
+ hint: 'the value may be undefined — often an indexed access (array[i], record[key]) under noUncheckedIndexedAccess. Guard it (if (v !== undefined) …) rather than asserting.',
49
+ },
50
+ {
51
+ codes: [1484, 1485],
52
+ hint: 'verbatimModuleSyntax: types must be imported with `import type { … }`; values with a plain `import`.',
53
+ },
54
+ {
55
+ codes: [2375, 2379, 2412],
56
+ hint: 'exactOptionalPropertyTypes: never assign undefined to an optional property — omit the key instead, e.g. ...(v !== undefined ? { k: v } : {}).',
57
+ },
58
+ {
59
+ codes: [2307],
60
+ hint: "only '@matatbread/matbot-plugin-api' is importable here; there are no other modules.",
61
+ },
62
+ {
63
+ codes: [2305],
64
+ pattern: /@matatbread\/matbot-plugin-api/,
65
+ hint: 'the package exports only the plugin API surface (ToolContract, ToolResultOf, ToolExecutor, ToolEvent, ToolContext, MatbotPluginSpec, MatbotMachine, makeToolBox, PLUGIN_API_VERSION). Types that appear inside tool contracts (SkillSummary, Trigger, …) are ambient in the tool dts and must NOT be imported — remove them from the import list and let inference carry the values (const r = await tool.x(...)), or inline the structural shape where you need a name.',
66
+ },
67
+ {
68
+ codes: [2304, 2552],
69
+ pattern: /\b(ToolContract|ToolResultOf|ToolExecutor|ToolEvent|ToolContext|MatbotPluginSpec|MatbotMachine|makeToolBox|PLUGIN_API_VERSION)\b/,
70
+ hint: "this name IS a real export of '@matatbread/matbot-plugin-api' — add it to the `import`/`import type { … }` list at the top of the file. Ignore any \"Did you mean\" suggestion pointing at a different name.",
71
+ },
72
+ ];
73
+
74
+ function hintFor(d: DiagnosticRecord): string | undefined {
75
+ for (const h of HINTS) {
76
+ if (!h.codes.includes(d.code)) continue;
77
+ if (h.pattern && !h.pattern.test(d.sourceLine ?? '') && !h.pattern.test(d.message)) continue;
78
+ return h.hint;
79
+ }
80
+ return undefined;
81
+ }
82
+
83
+ const MAX_FULL = 8;
84
+
85
+ function formatOne(d: DiagnosticRecord): string {
86
+ const loc = d.file !== undefined ? `${d.file}(${d.line},${d.col})`
87
+ : d.line !== undefined ? `line ${d.line}` : '(project)';
88
+ const parts = [`${loc} ${d.syn ? 'CAST-GATE' : `TS${d.code}`}: ${d.message}`];
89
+ if (d.frame !== undefined) parts.push(d.frame);
90
+ if (d.related) for (const r of d.related) parts.push(` related: ${r}`);
91
+ const hint = hintFor(d);
92
+ if (hint !== undefined) parts.push(` HINT: ${hint}`);
93
+ return parts.join('\n');
94
+ }
95
+
96
+ function overflowNote(diags: DiagnosticRecord[]): string {
97
+ const byCode = new Map<number, number>();
98
+ for (const d of diags.slice(MAX_FULL)) byCode.set(d.code, (byCode.get(d.code) ?? 0) + 1);
99
+ return `…plus ${diags.length - MAX_FULL} more: ${[...byCode.entries()].map(([c, n]) => `TS${c}×${n}`).join(', ')} — likely cascading from the errors above.`;
100
+ }
101
+
102
+ async function runWorker(data: Record<string, unknown>): Promise<DiagnosticRecord[] | null> {
103
+ const { Worker } = await import('node:worker_threads');
104
+ const { createRequire } = await import('node:module');
105
+ const typescriptPath = createRequire(import.meta.url).resolve('typescript');
106
+
107
+ const result = await new Promise<{ ok?: boolean; diagnostics?: DiagnosticRecord[]; error?: string }>((resolve, reject) => {
108
+ const w = new Worker(TS_WORKER_JS, { eval: true, workerData: { ...data, typescriptPath } });
109
+ const timer = setTimeout(() => { void w.terminate(); reject(new Error('typecheck worker timed out')); }, 120_000);
110
+ w.once('message', m => { clearTimeout(timer); resolve(m as never); void w.terminate(); });
111
+ w.once('error', e => { clearTimeout(timer); reject(e); });
112
+ w.once('exit', code => { clearTimeout(timer); if (code !== 0) reject(new Error(`typecheck worker exited with ${code}`)); });
113
+ });
114
+
115
+ if (result.error !== undefined) throw new Error(result.error);
116
+ return result.ok ? null : (result.diagnostics ?? []);
117
+ }
118
+
119
+ /** Typecheck a compiled plugin's build dir against its own tsconfig. `output` is the full annotated
120
+ * report (anchored frames, related locations, hints, cascade-capped). */
121
+ export async function checkProjectDir(buildDir: string): Promise<CheckResult> {
122
+ const diags = await runWorker({ mode: 'project', buildDir });
123
+ if (diags === null) return { ok: true, output: '' };
124
+ const parts: string[] = [];
125
+ if (diags.length > 1) parts.push(`${diags.length} errors. Fix the FIRST error first — later errors often cascade from it.\n`);
126
+ for (const d of diags.slice(0, MAX_FULL)) { parts.push(formatOne(d)); parts.push(''); }
127
+ if (diags.length > MAX_FULL) parts.push(overflowNote(diags));
128
+ return { ok: false, output: parts.join('\n').trim() };
129
+ }
130
+
131
+ /** Typecheck a snippet against an ambient prefix (the derived tool dts) as one virtual module rooted
132
+ * at `root`. Returns one annotated block per diagnostic, positions snippet-relative — the shape
133
+ * {@link ToolTypeIndex.check} has always returned, upgraded from bare `line N: message` strings. */
134
+ export async function checkSnippetAgainst(opts: {
135
+ root: string;
136
+ source: string;
137
+ prefixLen: number;
138
+ prefixLines: number;
139
+ apiIndexPath?: string;
140
+ }): Promise<string[]> {
141
+ const diags = await runWorker({
142
+ mode: 'snippet',
143
+ root: opts.root,
144
+ source: opts.source,
145
+ prefixLen: opts.prefixLen,
146
+ prefixLines: opts.prefixLines,
147
+ virtualPath: `${opts.root}/__mb_toolcheck_${crypto.randomUUID()}.ts`,
148
+ ...(opts.apiIndexPath !== undefined ? { apiIndexPath: opts.apiIndexPath } : {}),
149
+ });
150
+ if (diags === null) return [];
151
+ const out = diags.slice(0, MAX_FULL).map(formatOne);
152
+ if (diags.length > MAX_FULL) out.push(overflowNote(diags));
153
+ return out;
154
+ }
155
+
156
+ // The worker body: plain CommonJS (Worker eval mode is CJS, so `require` exists and no loader hooks
157
+ // are needed — the host's .ts strip-hooks do not reliably reach worker threads). It loads the SAME
158
+ // typescript module the main thread resolved and posts back JSON-safe records: flattened message
159
+ // chains, related-information locations (e.g. which contract arm an expected type came from), and a
160
+ // caret-anchored source frame per error. In snippet mode every position is remapped to be
161
+ // snippet-relative (the ambient dts prefix is invisible to the caller) and prefix-internal
162
+ // diagnostics are dropped — a broken derived dts is our bug, not the snippet's.
163
+ const TS_WORKER_JS = `
164
+ const { parentPort, workerData } = require('node:worker_threads');
165
+ const path = require('node:path');
166
+ try {
167
+ const ts = require(workerData.typescriptPath);
168
+ let targets, virtual = null, lineOffset = 0, baseDir, program, gateFiles = [], minStart = 0;
169
+
170
+ if (workerData.mode === 'project') {
171
+ baseDir = workerData.buildDir;
172
+ const configPath = path.join(baseDir, 'tsconfig.json');
173
+ const host = Object.assign({}, ts.sys, {
174
+ onUnRecoverableConfigFileDiagnostic: function (d) {
175
+ throw new Error(ts.flattenDiagnosticMessageText(d.messageText, ' '));
176
+ },
177
+ });
178
+ const parsed = ts.getParsedCommandLineOfConfigFile(configPath, undefined, host);
179
+ if (!parsed) throw new Error('could not parse ' + configPath);
180
+ program = ts.createProgram({ rootNames: parsed.fileNames, options: Object.assign({}, parsed.options, { noEmit: true }) });
181
+ targets = []
182
+ .concat(program.getConfigFileParsingDiagnostics())
183
+ .concat(program.getOptionsDiagnostics())
184
+ .concat(program.getSyntacticDiagnostics())
185
+ .concat(program.getGlobalDiagnostics())
186
+ .concat(program.getSemanticDiagnostics());
187
+ gateFiles = program.getSourceFiles().filter(function (f) {
188
+ return !f.isDeclarationFile
189
+ && f.fileName.indexOf('node_modules') === -1
190
+ && !path.relative(baseDir, f.fileName).startsWith('..');
191
+ });
192
+ } else {
193
+ baseDir = workerData.root;
194
+ virtual = workerData.virtualPath;
195
+ lineOffset = workerData.prefixLines;
196
+ minStart = workerData.prefixLen;
197
+ const source = workerData.source;
198
+ const options = {
199
+ target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.NodeNext, moduleResolution: ts.ModuleResolutionKind.NodeNext,
200
+ strict: true, exactOptionalPropertyTypes: true, noEmit: true, skipLibCheck: true, baseUrl: baseDir,
201
+ };
202
+ if (workerData.apiIndexPath) options.paths = { '@matatbread/matbot-plugin-api': [workerData.apiIndexPath] };
203
+ const host = ts.createCompilerHost(options);
204
+ const getSF = host.getSourceFile.bind(host);
205
+ host.getSourceFile = function (f, lang, onErr, create) {
206
+ return f === virtual ? ts.createSourceFile(f, source, lang, true) : getSF(f, lang, onErr, create);
207
+ };
208
+ const fe = host.fileExists.bind(host); host.fileExists = function (f) { return f === virtual || fe(f); };
209
+ const rf = host.readFile.bind(host); host.readFile = function (f) { return f === virtual ? source : rf(f); };
210
+ program = ts.createProgram([virtual], options, host);
211
+ const sf = program.getSourceFile(virtual);
212
+ targets = sf
213
+ ? [].concat(program.getSyntacticDiagnostics(sf)).concat(program.getSemanticDiagnostics(sf))
214
+ .filter(function (d) { return typeof d.start === 'number' && d.start >= minStart; })
215
+ : [];
216
+ if (sf) gateFiles = [sf];
217
+ }
218
+
219
+ // ── cast gate: structural rules over the generated source, reported as synthetic diagnostics ──
220
+ // tsc accepts type assertions unconditionally, so a generated tool can re-assert a shape onto a
221
+ // value the proxy already typed precisely — a hallucinated field then compiles and fails silently
222
+ // at runtime. Three rules: 'as any' (always); 'as unknown as T' (laundering); a checker-verified
223
+ // widening of an already-typed value to a loosening target (Record<...>, object, unknown, or an
224
+ // index-signature-only literal) — the first step of the widen-then-reassert pattern. Assertions on
225
+ // genuinely-unknown sources (the executor's input, await resp.json(), catch variables) pass, as do
226
+ // narrowing assertions and 'as const'.
227
+ const checker = program.getTypeChecker();
228
+ const synth = [];
229
+ const isLoosening = function (t) {
230
+ if (!t) return false;
231
+ if (t.kind === ts.SyntaxKind.UnknownKeyword || t.kind === ts.SyntaxKind.ObjectKeyword) return true;
232
+ if (ts.isTypeReferenceNode(t) && t.typeName.getText() === 'Record') return true;
233
+ if (ts.isTypeLiteralNode(t) && t.members.length > 0 && t.members.every(function (m) { return ts.isIndexSignatureDeclaration(m); })) return true;
234
+ return false;
235
+ };
236
+ const mk = function (sf, node, code, msg) {
237
+ return { file: sf, start: node.getStart(sf), length: node.getWidth(sf), code: code,
238
+ category: ts.DiagnosticCategory.Error, messageText: msg, __syn: true };
239
+ };
240
+ const skip = new Set();
241
+ const visit = function (node, sf) {
242
+ const isAssertion = ts.isAsExpression(node) || (ts.isTypeAssertionExpression && ts.isTypeAssertionExpression(node));
243
+ if (isAssertion && !skip.has(node) && node.getStart(sf) >= minStart) {
244
+ const target = node.type;
245
+ const inner = node.expression;
246
+ if (target.kind === ts.SyntaxKind.AnyKeyword) {
247
+ synth.push(mk(sf, node, 90001,
248
+ "'as any' is forbidden in generated tools — it disables the type checking that guards this code. Use the value's declared type directly, or narrow with a runtime guard ('field' in x, Array.isArray(x), typeof x === '...')."));
249
+ } else if ((ts.isAsExpression(inner) || (ts.isTypeAssertionExpression && ts.isTypeAssertionExpression(inner)))
250
+ && inner.type.kind === ts.SyntaxKind.UnknownKeyword) {
251
+ skip.add(inner); // one finding per construct — the inner 'as unknown' is part of this one
252
+ synth.push(mk(sf, node, 90002,
253
+ "double assertion ('as unknown as T') launders a type the checker already knows — remove both assertions and narrow with a runtime guard instead."));
254
+ } else if (isLoosening(target)) {
255
+ const f = checker.getTypeAtLocation(inner).flags;
256
+ if (!(f & ts.TypeFlags.Any) && !(f & ts.TypeFlags.Unknown)) {
257
+ synth.push(mk(sf, node, 90003,
258
+ "this expression is already precisely typed — widening it to '" + target.getText(sf) + "' discards the checked structure, so every later read of it is unverifiable. Use the typed value directly, or narrow with a runtime guard."));
259
+ }
260
+ }
261
+ }
262
+ ts.forEachChild(node, function (c) { visit(c, sf); });
263
+ };
264
+ for (const gf of gateFiles) visit(gf, gf);
265
+
266
+ const errors = targets.filter(function (d) { return d.category === ts.DiagnosticCategory.Error; }).concat(synth);
267
+ errors.sort(function (a, b) {
268
+ const fa = a.file ? a.file.fileName : '', fb = b.file ? b.file.fileName : '';
269
+ return fa < fb ? -1 : fa > fb ? 1 : (a.start || 0) - (b.start || 0);
270
+ });
271
+ const rec = function (d) {
272
+ const out = { code: d.code, message: ts.flattenDiagnosticMessageText(d.messageText, '\\n ') };
273
+ if (d.__syn) out.syn = true;
274
+ if (d.file && typeof d.start === 'number') {
275
+ const pos = d.file.getLineAndCharacterOfPosition(d.start);
276
+ if (d.file.fileName !== virtual) out.file = path.relative(baseDir, d.file.fileName);
277
+ out.line = pos.line + 1 - lineOffset;
278
+ out.col = pos.character + 1;
279
+ const lines = d.file.text.split(/\\r?\\n/);
280
+ const from = Math.max(lineOffset, pos.line - 2);
281
+ const to = Math.min(lines.length - 1, pos.line + 1);
282
+ const frame = [];
283
+ for (let i = from; i <= to; i++) {
284
+ frame.push((i === pos.line ? '>' : ' ') + ' ' + String(i + 1 - lineOffset).padStart(4) + ' | ' + lines[i]);
285
+ if (i === pos.line) frame.push(' ' + ' '.repeat(4) + ' | ' + ' '.repeat(pos.character) + '^');
286
+ }
287
+ out.frame = frame.join('\\n');
288
+ out.sourceLine = lines[pos.line] || '';
289
+ }
290
+ if (d.relatedInformation && d.relatedInformation.length) {
291
+ out.related = d.relatedInformation.map(function (r) {
292
+ let loc = '';
293
+ if (r.file && typeof r.start === 'number') {
294
+ const p = r.file.getLineAndCharacterOfPosition(r.start);
295
+ const name = r.file.fileName === virtual ? 'ambient tool types' : path.basename(r.file.fileName);
296
+ loc = name + '(' + (p.line + 1) + ',' + (p.character + 1) + '): ';
297
+ }
298
+ return loc + ts.flattenDiagnosticMessageText(r.messageText, ' ');
299
+ });
300
+ }
301
+ return out;
302
+ };
303
+ parentPort.postMessage({ ok: errors.length === 0, diagnostics: errors.map(rec) });
304
+ } catch (e) {
305
+ parentPort.postMessage({ error: String((e && e.message) || e) });
306
+ }
307
+ `;
package/src/index.ts CHANGED
@@ -1,4 +1,3 @@
1
- import type TS from 'typescript';
2
1
  import { dirname, join } from 'node:path';
3
2
  import { existsSync } from 'node:fs';
4
3
  import { createRequire } from 'node:module';
@@ -6,8 +5,10 @@ import { PLUGIN_API_VERSION } from '@matatbread/matbot-plugin-api';
6
5
  import type { MatbotMachine, MatbotPluginSpec, ToolTypeIndex } from '@matatbread/matbot-plugin-api';
7
6
  import { getRegisteredPlugins } from '@matatbread/matbot-core';
8
7
  import { buildMatbotToolsDts } from './build-dts.js';
8
+ import { checkSnippetAgainst } from './checker.js';
9
9
 
10
10
  export { buildMatbotToolsDts, type MatbotToolsDts } from './build-dts.js';
11
+ export { checkProjectDir, checkSnippetAgainst, type CheckResult } from './checker.js';
11
12
 
12
13
  // Split a string on `sep` at bracket-depth 0 only (respecting `<> {} () []`), so a top-level `|` or `,`
13
14
  // inside a nested type isn't mistaken for a separator.
@@ -100,7 +101,7 @@ function schemaToTs(schema: unknown, depth = 0): string {
100
101
  * tool (a `function-tools` function; the `tool-store` per-namespace tool) carries its contract on the
101
102
  * registered `Tool` as a `toolContract` string, appended in a second augmentation block; a name the scan
102
103
  * already declares is skipped, so nothing is declared twice. `declare const tool: ToolProxy` (mapped over
103
- * the merged `ToolContracts`) is what generators call.
104
+ * the merged `ToolContracts`) plus its override factory `toolInContext` is what generators call.
104
105
  */
105
106
  class ToolTypeIndexImpl implements ToolTypeIndex {
106
107
  private readonly machine: MatbotMachine;
@@ -142,11 +143,13 @@ class ToolTypeIndexImpl implements ToolTypeIndex {
142
143
 
143
144
  async dts(): Promise<string> {
144
145
  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`;
146
+ // `tool` — the injected proxy `function-tools`/compiled skills call — is a `ToolProxy`, a mapped type
147
+ // over the (augmented) `ToolContracts`: each multi-arm entry becomes an overload set, so `await
148
+ // tool.x(params)` narrows its result by the params, and a non-existent tool name is a compile error.
149
+ // `toolInContext(override)` is the sibling factory for a context override. Both derived, never
150
+ // hand-authored; `check()` uses this same string, so what a generator is shown is exactly what it is
151
+ // graded against.
152
+ return `${this.registryBlock(this.cache!)}\ndeclare const tool: import('@matatbread/matbot-plugin-api').ToolProxy;\ndeclare const toolInContext: import('@matatbread/matbot-plugin-api').ToolBox;\n`;
150
153
  }
151
154
 
152
155
  async wireContracts(): Promise<Record<string, { params: string; result: string }>> {
@@ -161,11 +164,9 @@ class ToolTypeIndexImpl implements ToolTypeIndex {
161
164
  }
162
165
 
163
166
  async check(snippet: string): Promise<string[]> {
164
- const ts = (await import('typescript')).default;
165
167
  const root = this.machine.configPath !== undefined ? dirname(this.machine.configPath) : '.';
166
168
  const prefix = `${await this.dts()}\n`;
167
169
  const source = `${prefix}${snippet}\nexport {};\n`; // trailing export ⇒ this file is a module
168
- const virtual = `${root}/__mb_toolcheck_${crypto.randomUUID()}.ts`;
169
170
 
170
171
  // Anchor `@matatbread/matbot-plugin-api` — it isn't a bare-resolvable dep of the project root, so map it
171
172
  // to the monorepo source (or the installed package). Without this the imports fail and every type
@@ -176,31 +177,14 @@ class ToolTypeIndexImpl implements ToolTypeIndex {
176
177
  try { apiIndex = createRequire(join(root, '_')).resolve('@matatbread/matbot-plugin-api'); } catch { /* unresolved */ }
177
178
  }
178
179
 
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;
180
+ // Worker-hosted check (see checker.ts) — off the main loop, and each diagnostic comes back as an
181
+ // annotated block (caret-anchored frame, related locations, HINT) with snippet-relative positions.
182
+ return checkSnippetAgainst({
183
+ root, source,
184
+ prefixLen: prefix.length,
185
+ prefixLines: prefix.split('\n').length - 1,
186
+ ...(apiIndex !== undefined ? { apiIndexPath: apiIndex } : {}),
187
+ });
204
188
  }
205
189
 
206
190
  // Every live tool the source scan didn't already declare: a source-less tool that carries its contract as
@@ -0,0 +1,73 @@
1
+ // Force a compiled tool's registered name to the value the compiler dictated.
2
+ //
3
+ // The tool name is compiler-owned metadata — it names the build dir, the package, and the version
4
+ // file — but it also has to appear inside the generated source (the `register({ name })` call, the
5
+ // `ToolContracts` arm key, and the `ToolResultOf<'…'>` literals), so the codegen prompt asks the
6
+ // model to transcribe it. A model that ignores that instruction and names the tool something else
7
+ // (e.g. after the skill) produces source that typechecks and installs but registers under the wrong
8
+ // name — silently, until it clashes with a real tool. The name is not the model's to choose, so this
9
+ // does not detect-and-repair (that would spend repair passes re-rolling a decision that was never
10
+ // the model's); it deterministically rewrites the model's chosen name to the expected one.
11
+ //
12
+ // This is a SYNTACTIC pass (parse + AST walk over one file), not the semantic check — cheap enough
13
+ // for the main thread, unlike the worker-hosted type check whose cost is program-wide analysis.
14
+
15
+ import type TS from 'typescript';
16
+
17
+ export interface NameNormalization { source: string; renamedFrom?: string }
18
+
19
+ /** Rewrite the registered tool name (and its contract-key / ToolResultOf occurrences) to `expected`
20
+ * if the source registered it under a different name. Returns the (possibly unchanged) source and,
21
+ * when a rewrite happened, the name it replaced. */
22
+ export async function normalizeRegisteredName(source: string, expected: string): Promise<NameNormalization> {
23
+ const ts = (await import('typescript')).default as typeof TS;
24
+ const sf = ts.createSourceFile('index.ts', source, ts.ScriptTarget.ES2022, true);
25
+
26
+ // Find the `services.tools.register({ name: <string literal>, … })` call and read its name.
27
+ let actual: string | undefined;
28
+ const findRegister = (node: TS.Node): void => {
29
+ if (actual !== undefined) return;
30
+ if (ts.isCallExpression(node)
31
+ && ts.isPropertyAccessExpression(node.expression)
32
+ && node.expression.name.text === 'register'
33
+ && node.arguments.length > 0
34
+ && ts.isObjectLiteralExpression(node.arguments[0]!)) {
35
+ for (const p of node.arguments[0].properties) {
36
+ if (ts.isPropertyAssignment(p)
37
+ && (ts.isIdentifier(p.name) || ts.isStringLiteral(p.name))
38
+ && p.name.text === 'name'
39
+ && ts.isStringLiteralLike(p.initializer)) {
40
+ actual = p.initializer.text;
41
+ return;
42
+ }
43
+ }
44
+ }
45
+ ts.forEachChild(node, findRegister);
46
+ };
47
+ findRegister(sf);
48
+
49
+ if (actual === undefined || actual === expected) return { source };
50
+
51
+ // Collect exact spans to rewrite: every string literal whose *entire* text is the old name (the
52
+ // register name, the ToolResultOf<'…'> / ToolContract literals — never a description sentence,
53
+ // which is never string-equal to an identifier), plus the ToolContracts arm's property-signature
54
+ // key. Rewriting by span (not text substitution) can't touch an unrelated substring.
55
+ const edits: { start: number; end: number }[] = [];
56
+ const collect = (node: TS.Node): void => {
57
+ if (ts.isStringLiteralLike(node) && node.text === actual) {
58
+ edits.push({ start: node.getStart(sf) + 1, end: node.getEnd() - 1 }); // inner text, keep quotes
59
+ } else if (ts.isPropertySignature(node) && node.name && (ts.isIdentifier(node.name) || ts.isStringLiteral(node.name)) && node.name.text === actual) {
60
+ const isQuoted = ts.isStringLiteral(node.name);
61
+ edits.push({ start: node.name.getStart(sf) + (isQuoted ? 1 : 0), end: node.name.getEnd() - (isQuoted ? 1 : 0) });
62
+ }
63
+ ts.forEachChild(node, collect);
64
+ };
65
+ collect(sf);
66
+
67
+ // Only code/type/contract positions are rewritten — a comment (e.g. the template's
68
+ // `// await tool.<name>(params)`) may retain the old name. That is cosmetic: it affects neither
69
+ // runtime, typecheck, nor composition, and the iterate path re-runs this pass, so it self-heals.
70
+ let out = source;
71
+ for (const e of edits.sort((a, b) => b.start - a.start)) out = out.slice(0, e.start) + expected + out.slice(e.end);
72
+ return { source: out, renamedFrom: actual };
73
+ }