@matatbread/matbot-tool-types 0.4.4 → 0.4.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "matbotRuntime": [
4
4
  "node"
5
5
  ],
6
- "version": "0.4.4",
6
+ "version": "0.4.6",
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.4",
40
- "@matatbread/matbot-core": "^0.4.4"
39
+ "@matatbread/matbot-plugin-api": "^0.4.6",
40
+ "@matatbread/matbot-core": "^0.4.6"
41
41
  },
42
42
  "devDependencies": {
43
43
  "@types/node": "^22.0.0",
44
44
  "typescript": "^6.0.3",
45
- "@matatbread/matbot-core": "^0.4.4",
46
- "@matatbread/matbot-plugin-api": "^0.4.4"
45
+ "@matatbread/matbot-core": "^0.4.6",
46
+ "@matatbread/matbot-plugin-api": "^0.4.6"
47
47
  },
48
48
  "scripts": {
49
49
  "typecheck": "tsc --noEmit"
package/src/build-dts.ts CHANGED
@@ -92,11 +92,22 @@ export async function buildMatbotToolsDts(
92
92
  const { fileURLToPath } = await import('node:url');
93
93
  const { createRequire } = await import('node:module');
94
94
 
95
- // Anchor plugin-api at the monorepo source if present, else the installed package.
95
+ // Anchor plugin-api: the monorepo source if present, then the project's own install, and finally THIS
96
+ // module's own resolution — which always works, because tool-types peer-depends on plugin-api, so
97
+ // whatever copy the host loaded is reachable from here.
98
+ //
99
+ // The last step is not belt-and-braces. Without it, a deployment where matbot is not resolvable from the
100
+ // config dir (installed globally, or a config dir outside the project) returned null, and the *silence*
101
+ // was the damage: ToolTypeIndex has no dts, skills_compiler falls back to a three-arm hardcoded stub, and
102
+ // the model then generates against a view of the registry that omits most live tools. Measured: asked to
103
+ // call `whoami`, it declared a `ToolContracts` arm for it *itself* — inventing `{ id: string; type: string }`
104
+ // — which compiled clean and only happened to resemble the real `Principal`. A wrong guess compiles too,
105
+ // and the cast gate cannot see it: nothing was cast, a contract was asserted. Same failure the scaffold's
106
+ // dangling plugin-api link used to cause, and the same fix.
96
107
  const monorepoApi = join(projectRoot, 'plugin-api', 'src', 'index.ts');
97
108
  let pluginApiIndex: string | undefined = existsSync(monorepoApi) ? monorepoApi : undefined;
98
- if (!pluginApiIndex) {
99
- try { pluginApiIndex = createRequire(join(projectRoot, '_')).resolve('@matatbread/matbot-plugin-api'); } catch { /* unresolved */ }
109
+ for (const from of pluginApiIndex === undefined ? [join(projectRoot, '_'), fileURLToPath(import.meta.url)] : []) {
110
+ try { pluginApiIndex = createRequire(from).resolve('@matatbread/matbot-plugin-api'); break; } catch { /* try the next anchor */ }
100
111
  }
101
112
  if (!pluginApiIndex) return null;
102
113
 
@@ -237,31 +248,69 @@ export async function buildMatbotToolsDts(
237
248
  const importNames = new Set<string>();
238
249
  const bundledDecls = new Map<string, string>();
239
250
 
251
+ // Bundling flattens every referenced workspace type into ONE scope, but a type's name is only unique
252
+ // within its own file: two plugins each declaring a file-local `SkipKind` is legal TypeScript and here
253
+ // a deliberate one (`plugins/background/src/index.ts` says why it isn't shared), so the generator has
254
+ // to represent it rather than ask the sources not to do it. Emitted side by side they were a TS2300
255
+ // that nothing compiled the dts to catch, and both references then resolved to an error type — the
256
+ // narrowing the contract exists to give, silently gone. So the first symbol to claim a name keeps it
257
+ // and later ones are alpha-renamed (`SkipKind$1`), with every reference rewritten to match.
258
+ //
259
+ // Keyed by SYMBOL, never by declaration: a merged interface is several declarations of one symbol, and
260
+ // renaming those apart would break the merge the source relies on. Names already spoken for by a
261
+ // plugin-api import are reserved up front — which one of those gets imported isn't known until the
262
+ // walk ends, and a needless `$1` is cosmetic where a collision is fatal.
263
+ const bundleNames = new Map<TS.Symbol, string>();
264
+ const usedNames = new Set<string>(apiTypeNames);
265
+ const bundleName = (sym: TS.Symbol): string => {
266
+ const already = bundleNames.get(sym);
267
+ if (already !== undefined) return already;
268
+ const base = sym.name;
269
+ let name = base;
270
+ for (let i = 1; usedNames.has(name); i++) name = `${base}$${i}`;
271
+ usedNames.add(name);
272
+ bundleNames.set(sym, name);
273
+ return name;
274
+ };
275
+
240
276
  interface Ctx { imports: Set<string>; seen: Set<string>; heritageBail: string | null; }
241
277
 
242
278
  // Emit `node`'s source text with every bailing type-reference replaced in place by `unknown` (leaf
243
279
  // substitution). Accumulates imports (plugin-api refs) and bundled declarations (workspace refs,
244
280
  // recursively emitted through here too). Sets `ctx.heritageBail` if a bail sits in an `extends` base,
245
281
  // where `unknown` can't go — the caller then collapses that whole member.
246
- const emitNode = (node: TS.Node, ctx: Ctx): string => {
282
+ const emitNode = (node: TS.Node, ctx: Ctx, declName?: string): string => {
247
283
  const base = node.getStart();
248
284
  const repls: Array<{ s: number; e: number; t: string }> = [];
285
+ // Rewrite the declaration's OWN name when it was renamed out of a collision. Claim the name before
286
+ // recursing, so a self-referential type reaches the same entry instead of allocating a second.
287
+ if (declName !== undefined && (ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node))
288
+ && node.name.getText() !== declName) {
289
+ repls.push({ s: node.name.getStart() - base, e: node.name.getEnd() - base, t: declName });
290
+ }
249
291
  const bundle = (sym: TS.Symbol): void => {
292
+ const name = bundleName(sym);
250
293
  for (const d of sym.declarations ?? []) {
251
294
  if (!ts.isInterfaceDeclaration(d) && !ts.isTypeAliasDeclaration(d)) continue;
252
295
  const key = declKey(d);
253
296
  if (ctx.seen.has(key)) continue;
254
297
  ctx.seen.add(key);
255
- bundledDecls.set(key, stripModifiers(emitNode(d, ctx)));
298
+ bundledDecls.set(key, stripModifiers(emitNode(d, ctx, name)));
256
299
  }
257
300
  };
301
+ // A reference names a symbol, not a file, so it also carries the local spelling of an `import { X as Y }`.
302
+ // Rewriting to the allocated name settles both that and the collision rename in one substitution.
303
+ const rename = (ref: TS.Node, to: string): void => {
304
+ if (ref.getText() === to) return;
305
+ repls.push({ s: ref.getStart() - base, e: ref.getEnd() - base, t: to });
306
+ };
258
307
  const visit = (n: TS.Node): void => {
259
308
  if (ctx.heritageBail) return;
260
309
  if (ts.isTypeReferenceNode(n)) {
261
310
  const c = classifyEntity(n.typeName);
262
311
  if (c.tag === 'bail') { repls.push({ s: n.getStart() - base, e: n.getEnd() - base, t: unknownOf(c.label) }); return; }
263
312
  if (c.tag === 'api') importNames.add(n.typeName.getText());
264
- else if (c.tag === 'bundle') bundle(c.sym);
313
+ else if (c.tag === 'bundle') { rename(n.typeName, bundleName(c.sym)); bundle(c.sym); }
265
314
  n.typeArguments?.forEach(visit);
266
315
  return;
267
316
  }
@@ -269,7 +318,7 @@ export async function buildMatbotToolsDts(
269
318
  const c = classifyEntity(n.expression);
270
319
  if (c.tag === 'bail') { ctx.heritageBail = c.label; return; }
271
320
  if (c.tag === 'api') importNames.add(n.expression.getText());
272
- else if (c.tag === 'bundle') bundle(c.sym);
321
+ else if (c.tag === 'bundle') { rename(n.expression, bundleName(c.sym)); bundle(c.sym); }
273
322
  n.typeArguments?.forEach(visit);
274
323
  return;
275
324
  }
package/src/checker.ts CHANGED
@@ -116,10 +116,22 @@ async function runWorker(data: Record<string, unknown>): Promise<DiagnosticRecor
116
116
  return result.ok ? null : (result.diagnostics ?? []);
117
117
  }
118
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 });
119
+ /**
120
+ * Typecheck a compiled plugin's build dir against its own tsconfig. `output` is the full annotated
121
+ * report (anchored frames, related locations, hints, cascade-capped).
122
+ *
123
+ * `ownContracts` names the tools this compilation is entitled to declare a `ToolContracts` arm for — its
124
+ * own. Any other arm in the checked source is rejected like a cast: the dts is an input to generation,
125
+ * derived from the live registry, so an arm authored here asserts a shape nothing can contradict. Omit
126
+ * the option and the rule does not run (there is then no way to tell a self-declaration from an invention).
127
+ */
128
+ export async function checkProjectDir(
129
+ buildDir: string, opts?: { ownContracts?: readonly string[] },
130
+ ): Promise<CheckResult> {
131
+ const diags = await runWorker({
132
+ mode: 'project', buildDir,
133
+ ...(opts?.ownContracts !== undefined ? { ownContracts: [...opts.ownContracts] } : {}),
134
+ });
123
135
  if (diags === null) return { ok: true, output: '' };
124
136
  const parts: string[] = [];
125
137
  if (diags.length > 1) parts.push(`${diags.length} errors. Fix the FIRST error first — later errors often cascade from it.\n`);
@@ -237,6 +249,35 @@ try {
237
249
  return { file: sf, start: node.getStart(sf), length: node.getWidth(sf), code: code,
238
250
  category: ts.DiagnosticCategory.Error, messageText: msg, __syn: true };
239
251
  };
252
+ // ── contract gate: a generated tool declares its OWN ToolContracts arm and nobody else's ──
253
+ // The dts is an INPUT to code generation, derived from the live registry. A generated file that adds an
254
+ // arm for another tool is not describing anything — it is asserting a shape tsc then has no way to
255
+ // contradict, so a wrong guess compiles and fails at runtime. Measured, when the derived dts was
256
+ // unavailable and the model wanted \`whoami\`: it declared \`ToolContract<{ id: string; type: string }, {}>\`
257
+ // for it, which compiled clean and only resembled the real \`Principal\`. The cast gate cannot see this —
258
+ // nothing is cast. Only enforced when the caller says which names are the compilation's own; absent that
259
+ // list the rule cannot tell an invention from a legitimate self-declaration, so it does not run.
260
+ const own = Array.isArray(workerData.ownContracts) ? workerData.ownContracts : null;
261
+ const contractVisit = function (node, sf) {
262
+ if (own && ts.isModuleDeclaration(node) && ts.isStringLiteral(node.name)
263
+ && node.name.text === '@matatbread/matbot-plugin-api' && node.body && node.getStart(sf) >= minStart) {
264
+ node.body.forEachChild(function (decl) {
265
+ if (!ts.isInterfaceDeclaration(decl) || decl.name.text !== 'ToolContracts') return;
266
+ for (const member of decl.members) {
267
+ const name = member.name && member.name.getText ? member.name.getText(sf) : '';
268
+ if (name === '' || own.indexOf(name) !== -1) continue;
269
+ synth.push(mk(sf, member, 90004,
270
+ "the contract for '" + name + "' is not yours to declare — tool contracts come from the ambient " +
271
+ "tool dts, which is derived from the live registry. Declaring one here asserts a shape nothing " +
272
+ "can check, so a wrong guess compiles and fails at runtime. Delete this member: call the tool as " +
273
+ "'await tool." + name + "(...)' and use the value it returns, whose type is already precise. If '" +
274
+ name + "' is absent from the ambient dts then no such tool is loaded and it cannot be called at all."));
275
+ }
276
+ });
277
+ }
278
+ ts.forEachChild(node, function (c) { contractVisit(c, sf); });
279
+ };
280
+
240
281
  const skip = new Set();
241
282
  const visit = function (node, sf) {
242
283
  const isAssertion = ts.isAsExpression(node) || (ts.isTypeAssertionExpression && ts.isTypeAssertionExpression(node));
@@ -261,7 +302,7 @@ try {
261
302
  }
262
303
  ts.forEachChild(node, function (c) { visit(c, sf); });
263
304
  };
264
- for (const gf of gateFiles) visit(gf, gf);
305
+ for (const gf of gateFiles) { visit(gf, gf); contractVisit(gf, gf); }
265
306
 
266
307
  const errors = targets.filter(function (d) { return d.category === ts.DiagnosticCategory.Error; }).concat(synth);
267
308
  errors.sort(function (a, b) {