@matatbread/matbot-tool-types 0.4.21 → 0.5.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/package.json +7 -6
- package/src/anchor.ts +23 -0
- package/src/build-dts.ts +21 -18
- package/src/checker.ts +190 -62
- package/src/index.ts +107 -186
- package/src/parameters.cts +140 -0
package/package.json
CHANGED
|
@@ -3,12 +3,13 @@
|
|
|
3
3
|
"matbotRuntime": [
|
|
4
4
|
"node"
|
|
5
5
|
],
|
|
6
|
-
"version": "0.
|
|
6
|
+
"version": "0.5.0",
|
|
7
7
|
"engines": {
|
|
8
8
|
"node": ">=24.0.0"
|
|
9
9
|
},
|
|
10
10
|
"files": [
|
|
11
|
-
"src"
|
|
11
|
+
"src",
|
|
12
|
+
"src/parameters.cts"
|
|
12
13
|
],
|
|
13
14
|
"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
15
|
"keywords": [
|
|
@@ -37,13 +38,13 @@
|
|
|
37
38
|
"typescript": "^6.0.3"
|
|
38
39
|
},
|
|
39
40
|
"peerDependencies": {
|
|
40
|
-
"@matatbread/matbot-plugin-api": "^0.
|
|
41
|
-
"@matatbread/matbot-core": "^0.
|
|
41
|
+
"@matatbread/matbot-plugin-api": "^0.5.0",
|
|
42
|
+
"@matatbread/matbot-core": "^0.5.0"
|
|
42
43
|
},
|
|
43
44
|
"devDependencies": {
|
|
44
45
|
"typescript": "^6.0.3",
|
|
45
|
-
"@matatbread/matbot-plugin-api": "^0.
|
|
46
|
-
"@matatbread/matbot-core": "^0.
|
|
46
|
+
"@matatbread/matbot-plugin-api": "^0.5.0",
|
|
47
|
+
"@matatbread/matbot-core": "^0.5.0"
|
|
47
48
|
},
|
|
48
49
|
"scripts": {
|
|
49
50
|
"typecheck": "tsc --noEmit"
|
package/src/anchor.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { createRequire } from 'node:module';
|
|
5
|
+
|
|
6
|
+
// Where a matbot package's types are read from, for every Program tool-types builds: the monorepo source
|
|
7
|
+
// if present, then the project's own install, and finally THIS module's own resolution — which reaches the
|
|
8
|
+
// copy the host loaded, tool-types peer-depending on plugin-api (and core, through it). For a plugin fetched
|
|
9
|
+
// over http, "this module" is the mirrored copy, and the cache's `node_modules` links the host's singletons.
|
|
10
|
+
//
|
|
11
|
+
// One function because there were two copies, and they drifted: the dts build had the last step and the
|
|
12
|
+
// snippet check did not, so in any project where plugin-api is not resolvable from the config directory (a
|
|
13
|
+
// pnpm project, a globally installed CLI, a bare directory holding only matbot.yaml) the check's import of
|
|
14
|
+
// plugin-api failed, `tool` was `any`, and every tool call in a function body typechecked — a wrong
|
|
15
|
+
// argument, an unknown property, a tool that does not exist.
|
|
16
|
+
export function anchorPackage(projectRoot: string, dir: string, name: string): string | undefined {
|
|
17
|
+
const monorepo = join(projectRoot, dir, 'src', 'index.ts');
|
|
18
|
+
if (existsSync(monorepo)) return monorepo;
|
|
19
|
+
for (const from of [join(projectRoot, '_'), fileURLToPath(import.meta.url)]) {
|
|
20
|
+
try { return createRequire(from).resolve(name); } catch { /* try the next anchor */ }
|
|
21
|
+
}
|
|
22
|
+
return undefined;
|
|
23
|
+
}
|
package/src/build-dts.ts
CHANGED
|
@@ -2,6 +2,7 @@ import type TS from 'typescript';
|
|
|
2
2
|
import type { Runtime } from '@matatbread/matbot-plugin-api';
|
|
3
3
|
import { contractArms } from '@matatbread/matbot-plugin-api';
|
|
4
4
|
import { compileToolValidator, generateValidator, type ToolValidator, type ValidatorSource } from './validator.js';
|
|
5
|
+
import { anchorPackage } from './anchor.js';
|
|
5
6
|
|
|
6
7
|
// Derive a self-contained `declare module … { interface ToolContracts {…} interface MatbotServices {…} }`
|
|
7
8
|
// from the live type graph, so a compiled (or hand-rolled) plugin's compilation sees correct types for
|
|
@@ -121,7 +122,6 @@ export async function collectToolTypeRoots(
|
|
|
121
122
|
const { readFileSync, readdirSync, statSync, existsSync } = await import('node:fs');
|
|
122
123
|
const { join } = await import('node:path');
|
|
123
124
|
const { fileURLToPath } = await import('node:url');
|
|
124
|
-
const { createRequire } = await import('node:module');
|
|
125
125
|
|
|
126
126
|
// Anchor plugin-api: the monorepo source if present, then the project's own install, and finally THIS
|
|
127
127
|
// module's own resolution — which always works, because tool-types peer-depends on plugin-api, so
|
|
@@ -135,14 +135,15 @@ export async function collectToolTypeRoots(
|
|
|
135
135
|
// — which compiled clean and only happened to resemble the real `Principal`. A wrong guess compiles too,
|
|
136
136
|
// and the cast gate cannot see it: nothing was cast, a contract was asserted. Same failure the scaffold's
|
|
137
137
|
// dangling plugin-api link used to cause, and the same fix.
|
|
138
|
-
const
|
|
139
|
-
let pluginApiIndex: string | undefined = existsSync(monorepoApi) ? monorepoApi : undefined;
|
|
140
|
-
for (const from of pluginApiIndex === undefined ? [join(projectRoot, '_'), fileURLToPath(import.meta.url)] : []) {
|
|
141
|
-
try { pluginApiIndex = createRequire(from).resolve('@matatbread/matbot-plugin-api'); break; } catch { /* try the next anchor */ }
|
|
142
|
-
}
|
|
138
|
+
const pluginApiIndex = anchorPackage(projectRoot, 'plugin-api', '@matatbread/matbot-plugin-api');
|
|
143
139
|
if (!pluginApiIndex) return null;
|
|
144
140
|
|
|
145
|
-
|
|
141
|
+
// Core is a root too, for the tools `assembleMachine` registers itself (`about_matbot`, `single_turn`,
|
|
142
|
+
// `gate_action`). Nothing else reliably reaches them: no plugin owns them, so no `resolvedUrl` does, and
|
|
143
|
+
// the `plugins/` glob below finds core only through some plugin's import of it — which made those three
|
|
144
|
+
// typed or not by whichever plugins an installation happened to load.
|
|
145
|
+
const coreIndex = anchorPackage(projectRoot, 'core', '@matatbread/matbot-core');
|
|
146
|
+
const roots = new Set<string>([pluginApiIndex, ...(coreIndex !== undefined ? [coreIndex] : [])]);
|
|
146
147
|
|
|
147
148
|
// A loaded plugin's `resolvedUrl` → an on-disk type-bearing source file. `.ts`/`.d.ts` used directly;
|
|
148
149
|
// an npm `.js` entry maps to its sibling `.d.ts`; anything else (blob:, bare specifier, missing) skipped.
|
|
@@ -156,10 +157,10 @@ export async function collectToolTypeRoots(
|
|
|
156
157
|
for (const u of pluginEntryUrls ?? []) { const p = toSource(u); if (p) roots.add(p); }
|
|
157
158
|
|
|
158
159
|
// UNION with a glob of the monorepo `plugins/` tree (not a fallback): the resolvedUrl roots above cover
|
|
159
|
-
// every *loaded* plugin (builtin, compiled, installed), but
|
|
160
|
-
// plugin
|
|
161
|
-
//
|
|
162
|
-
//
|
|
160
|
+
// every *loaded* plugin (builtin, compiled, installed), but a static caller has no loaded set at all —
|
|
161
|
+
// the web bundle's build describes every plugin it bakes, none of which is loaded where it runs. The
|
|
162
|
+
// glob is how that caller sees them. In a real deployment there is no `plugins/` tree, so this no-ops
|
|
163
|
+
// and the scan is purely resolvedUrl-driven. Dedup is by path (a Set of roots).
|
|
163
164
|
//
|
|
164
165
|
// So the roots deliberately over-reach: wherever that tree exists — this repo, or an embedder that vendors
|
|
165
166
|
// it — plugins for OTHER runtimes and plugins nobody loaded are scanned too. Two consequences, and they
|
|
@@ -479,9 +480,8 @@ export async function buildToolTypesData(
|
|
|
479
480
|
const bundledDecls = new Map<string, string>();
|
|
480
481
|
|
|
481
482
|
// Bundling flattens every referenced workspace type into ONE scope, but a type's name is only unique
|
|
482
|
-
// within its own file: two plugins each declaring a file-local
|
|
483
|
-
//
|
|
484
|
-
// to represent it rather than ask the sources not to do it. Emitted side by side they were a TS2300
|
|
483
|
+
// within its own file: two plugins each declaring a file-local type of one name is legal TypeScript, so
|
|
484
|
+
// the generator has to represent it rather than ask the sources not to do it. Emitted side by side they were a TS2300
|
|
485
485
|
// that nothing compiled the dts to catch, and both references then resolved to an error type — the
|
|
486
486
|
// narrowing the contract exists to give, silently gone. So the first symbol to claim a name keeps it
|
|
487
487
|
// and later ones are alpha-renamed (`SkipKind$1`), with every reference rewritten to match.
|
|
@@ -792,10 +792,13 @@ export async function buildToolTypesData(
|
|
|
792
792
|
const params: string[] = [], results: string[] = [], paramNodes: TS.TypeNode[] = [];
|
|
793
793
|
for (const raw of arms) {
|
|
794
794
|
const a = resolveAlias(raw);
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
795
|
+
// Two arguments, or three with a `Call` signature, which is the proxy's alone: the wire is `Result`/`Args`.
|
|
796
|
+
if (!ts.isTypeReferenceNode(a) || a.typeName.getText() !== 'ToolContract') return undefined;
|
|
797
|
+
const [result, args, ...rest] = a.typeArguments ?? [];
|
|
798
|
+
if (result === undefined || args === undefined || rest.length > 1) return undefined;
|
|
799
|
+
results.push(expandNamed(result, new Set(), 0));
|
|
800
|
+
params.push(expandNamed(args, new Set(), 0));
|
|
801
|
+
paramNodes.push(args);
|
|
799
802
|
}
|
|
800
803
|
return { result: results.join(' | '), params: params.join(' | '), paramNodes };
|
|
801
804
|
};
|
package/src/checker.ts
CHANGED
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
// own virtual file, the same resolved typescript module), so a checker failure is a plumbing bug
|
|
10
10
|
// that must surface as the caller's error, not be absorbed by a quieter path.
|
|
11
11
|
|
|
12
|
+
import { fileURLToPath } from 'node:url';
|
|
12
13
|
import { renderToolCheckOmitted } from '@matatbread/matbot-plugin-api';
|
|
13
14
|
import type { ToolCheckDiagnostic, ToolCheckReport } from '@matatbread/matbot-plugin-api';
|
|
14
15
|
|
|
@@ -35,7 +36,7 @@ interface DiagnosticRecord {
|
|
|
35
36
|
// plugin is a module: it has a top of file to add an import to, `@matatbread/matbot-plugin-api` is a real
|
|
36
37
|
// dependency of its build dir, and nothing else is importable. A `tool_function` body is
|
|
37
38
|
// `async function __fn(…) { … }`: no top of file, no static imports, and a different importable set
|
|
38
|
-
// entirely —
|
|
39
|
+
// entirely — node's builtins and installed packages, by name. These were written for the first and fired in both, so
|
|
39
40
|
// a body that mistyped `node:fs` was told there are no modules here.
|
|
40
41
|
const HINTS: { codes: number[]; pattern?: RegExp; only?: 'project' | 'snippet'; hint: string }[] = [
|
|
41
42
|
{
|
|
@@ -78,10 +79,9 @@ const HINTS: { codes: number[]; pattern?: RegExp; only?: 'project' | 'snippet';
|
|
|
78
79
|
{
|
|
79
80
|
codes: [2307],
|
|
80
81
|
only: 'snippet',
|
|
81
|
-
//
|
|
82
|
-
//
|
|
83
|
-
|
|
84
|
-
hint: 'this module is not typed here. The comment block at the top of these declarations says what this installation permits; a node builtin has real types (either spelling: `node:os` or `os`), while a bare package or an http(s) URL has none, and importing one of those needs noTypeCheck.',
|
|
82
|
+
// What this adds is WHY a specifier can be absent: a refused one is IMPORT-GATE's finding, at the same
|
|
83
|
+
// position, and this one's is dropped there, so what is left is a module with no declarations.
|
|
84
|
+
hint: 'this module is not typed here. A node builtin has real types (either spelling: `node:os` or `os`); a package has them only if it is installed with declarations of its own, and otherwise importing it needs noTypeCheck.',
|
|
85
85
|
},
|
|
86
86
|
{
|
|
87
87
|
codes: [2305],
|
|
@@ -114,7 +114,7 @@ const MAX_FULL = 8;
|
|
|
114
114
|
// A structural rule's label, by its private code. CAST-GATE is the default because it was the first and
|
|
115
115
|
// is what the contract gate (90004) has always reported as; a rule about something other than types
|
|
116
116
|
// needs its own name, or the label says the wrong thing about the finding under it.
|
|
117
|
-
const SYN_LABELS: Record<number, string> = { 90005: 'ENV-GATE', 90006: 'IMPORT-GATE' };
|
|
117
|
+
const SYN_LABELS: Record<number, string> = { 90005: 'ENV-GATE', 90006: 'IMPORT-GATE', 90007: 'ESCAPE-GATE' };
|
|
118
118
|
|
|
119
119
|
// One rule, one name, in every renderer: a per-rule label read off the record rather than spelled at
|
|
120
120
|
// each render site, so a summary can never call a finding something its own entry did not.
|
|
@@ -176,12 +176,14 @@ function reportOf(diags: DiagnosticRecord[], mode: Mode): ToolCheckReport {
|
|
|
176
176
|
};
|
|
177
177
|
}
|
|
178
178
|
|
|
179
|
-
|
|
179
|
+
type CheckParameters = NonNullable<ToolCheckReport['parameters']>;
|
|
180
|
+
|
|
181
|
+
async function runWorker(data: Record<string, unknown>, importRefused?: (spec: string) => boolean): Promise<{ diags: DiagnosticRecord[] | null; parameters?: CheckParameters }> {
|
|
180
182
|
const { Worker } = await import('node:worker_threads');
|
|
181
183
|
const { createRequire } = await import('node:module');
|
|
182
184
|
const typescriptPath = createRequire(import.meta.url).resolve('typescript');
|
|
183
185
|
|
|
184
|
-
const result = await new Promise<{ ok?: boolean; diagnostics?: DiagnosticRecord[]; error?: string }>((resolve, reject) => {
|
|
186
|
+
const result = await new Promise<{ ok?: boolean; diagnostics?: DiagnosticRecord[]; parameters?: CheckParameters; error?: string }>((resolve, reject) => {
|
|
185
187
|
// Parsed AS TypeScript, never left to node to guess: without the flag eval'd code runs as JS and is
|
|
186
188
|
// retried as TS only if it fails to parse, and `new Set<string>(x)` parses fine as two comparisons —
|
|
187
189
|
// so it would have thrown `string is not defined` but for an unrelated annotation elsewhere in the
|
|
@@ -193,13 +195,31 @@ async function runWorker(data: Record<string, unknown>): Promise<DiagnosticRecor
|
|
|
193
195
|
execArgv: ['--input-type=commonjs-typescript'],
|
|
194
196
|
});
|
|
195
197
|
const timer = setTimeout(() => { void w.terminate(); reject(new Error('typecheck worker timed out')); }, 120_000);
|
|
196
|
-
|
|
198
|
+
// At most one question before the result: which of the literal specifiers it found are refused. A
|
|
199
|
+
// predicate is a closure over this thread's gate snapshot and cannot be cloned into the worker, and a
|
|
200
|
+
// list cannot be computed in advance, packages being an open set; so the worker finishes the program,
|
|
201
|
+
// asks, and completes its findings from the answer.
|
|
202
|
+
w.on('message', (m: { ask?: string[] }) => {
|
|
203
|
+
if (m.ask !== undefined) {
|
|
204
|
+
// A predicate that throws is a plumbing fault, and surfaces as one: thrown here it would be an
|
|
205
|
+
// uncaught exception in a listener, and answered "not refused" a fail-open nobody saw.
|
|
206
|
+
let refused: string[];
|
|
207
|
+
try { refused = m.ask.filter(spec => importRefused?.(spec) === true); }
|
|
208
|
+
catch (e) { clearTimeout(timer); void w.terminate(); reject(e); return; }
|
|
209
|
+
w.postMessage({ refused });
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
clearTimeout(timer); resolve(m as never); void w.terminate();
|
|
213
|
+
});
|
|
197
214
|
w.once('error', e => { clearTimeout(timer); reject(e); });
|
|
198
215
|
w.once('exit', code => { clearTimeout(timer); if (code !== 0) reject(new Error(`typecheck worker exited with ${code}`)); });
|
|
199
216
|
});
|
|
200
217
|
|
|
201
218
|
if (result.error !== undefined) throw new Error(result.error);
|
|
202
|
-
return
|
|
219
|
+
return {
|
|
220
|
+
diags: result.ok ? null : (result.diagnostics ?? []),
|
|
221
|
+
...(result.parameters !== undefined ? { parameters: result.parameters } : {}),
|
|
222
|
+
};
|
|
203
223
|
}
|
|
204
224
|
|
|
205
225
|
/**
|
|
@@ -214,7 +234,7 @@ async function runWorker(data: Record<string, unknown>): Promise<DiagnosticRecor
|
|
|
214
234
|
export async function checkProjectDir(
|
|
215
235
|
buildDir: string, opts?: { ownContracts?: readonly string[] },
|
|
216
236
|
): Promise<CheckResult> {
|
|
217
|
-
const diags = await runWorker({
|
|
237
|
+
const { diags } = await runWorker({
|
|
218
238
|
mode: 'project', buildDir,
|
|
219
239
|
...(opts?.ownContracts !== undefined ? { ownContracts: [...opts.ownContracts] } : {}),
|
|
220
240
|
});
|
|
@@ -236,28 +256,31 @@ export async function checkSnippetAgainst(opts: {
|
|
|
236
256
|
prefixLen: number;
|
|
237
257
|
prefixLines: number;
|
|
238
258
|
apiIndexPath?: string;
|
|
239
|
-
/** `paths` entries for the
|
|
240
|
-
*
|
|
241
|
-
* something that typechecks and is refused at run time. Built by the caller, which knows the set. */
|
|
259
|
+
/** `paths` entries for the builtins a body may import — one per module the gate does not refuse, so
|
|
260
|
+
* nothing is typed that the call will never hand over. Built by the caller, which holds the answer. */
|
|
242
261
|
importPaths?: Record<string, string[]>;
|
|
243
262
|
/** Declaration files for the globals a body HAS beyond the standard library, loaded as roots: on node,
|
|
244
263
|
* `Buffer`. Module types arrive only through {@link importPaths}, which load on an import, so a body
|
|
245
264
|
* using a node global without importing anything would otherwise fail on a name it really has. */
|
|
246
265
|
globalTypes?: readonly string[];
|
|
247
|
-
/**
|
|
248
|
-
* declaration file pulls in the ambient `declare module
|
|
249
|
-
* declarations reference (`node:fs` reaches `node:stream`,
|
|
250
|
-
*
|
|
251
|
-
*
|
|
252
|
-
* the
|
|
253
|
-
|
|
266
|
+
/** Whether the gate refuses an import outright ({@link ToolCheckOptions.importRefused}) — `paths`
|
|
267
|
+
* cannot enforce that. Loading ONE builtin's declaration file pulls in the ambient `declare module
|
|
268
|
+
* 'node:…'` blocks of everything its own declarations reference (`node:fs` reaches `node:stream`,
|
|
269
|
+
* which reaches most of the rest), so a refused specifier resolves anyway and typechecks clean, and an
|
|
270
|
+
* installed package resolves by ordinary lookup. A literal `import('…')` is therefore checked
|
|
271
|
+
* STRUCTURALLY, the way the cast gate and ENV-GATE close the other holes the type system cannot: the
|
|
272
|
+
* worker sends the literal specifiers it found back here once, and this answers which are refused.
|
|
273
|
+
* Absent ⇒ nothing is refused, and nothing is asked. */
|
|
274
|
+
importRefused?: (spec: string) => boolean;
|
|
254
275
|
/** The identifiers the RUNNER does not bind, from `FunctionRunner.withheldGlobals` — the list ENV-GATE
|
|
255
276
|
* rejects. It comes from the runner because a copy here could not be kept in step with it, and a name
|
|
256
277
|
* that is shadowed but not rejected typechecks and then fails at the first call. Absent ⇒ nothing is
|
|
257
278
|
* rejected: with no runner there is no claim about what a body does not have. */
|
|
258
279
|
withheldGlobals?: readonly string[];
|
|
280
|
+
/** Functions in the snippet whose parameter schemas to report ({@link ToolCheckOptions.parametersOf}). */
|
|
281
|
+
parametersOf?: readonly string[];
|
|
259
282
|
}): Promise<ToolCheckReport> {
|
|
260
|
-
const diags = await runWorker({
|
|
283
|
+
const { diags, parameters } = await runWorker({
|
|
261
284
|
mode: 'snippet',
|
|
262
285
|
root: opts.root,
|
|
263
286
|
source: opts.source,
|
|
@@ -267,10 +290,14 @@ export async function checkSnippetAgainst(opts: {
|
|
|
267
290
|
...(opts.apiIndexPath !== undefined ? { apiIndexPath: opts.apiIndexPath } : {}),
|
|
268
291
|
...(opts.importPaths !== undefined ? { importPaths: opts.importPaths } : {}),
|
|
269
292
|
...(opts.globalTypes !== undefined ? { globalTypes: opts.globalTypes } : {}),
|
|
270
|
-
...(opts.
|
|
293
|
+
...(opts.importRefused !== undefined ? { askImports: true } : {}),
|
|
271
294
|
...(opts.withheldGlobals !== undefined ? { withheldGlobals: opts.withheldGlobals } : {}),
|
|
272
|
-
|
|
273
|
-
|
|
295
|
+
...(opts.parametersOf !== undefined && opts.parametersOf.length > 0
|
|
296
|
+
? { parametersOf: [...opts.parametersOf], parametersModule: fileURLToPath(new URL('./parameters.cts', import.meta.url)) }
|
|
297
|
+
: {}),
|
|
298
|
+
}, opts.importRefused);
|
|
299
|
+
const report = reportOf(diags ?? [], 'snippet');
|
|
300
|
+
return parameters !== undefined ? { ...report, parameters } : report;
|
|
274
301
|
}
|
|
275
302
|
|
|
276
303
|
// The worker body: CommonJS (Worker eval mode is CJS, so `require` exists and no loader hooks are
|
|
@@ -411,8 +438,8 @@ try {
|
|
|
411
438
|
//
|
|
412
439
|
// WHICH names are withheld comes from the runner's withheldGlobals, because it is the only thing that
|
|
413
440
|
// knows and a copy here could not be kept in step: a name shadowed but not rejected typechecks and
|
|
414
|
-
// fails at the first call, which is the one failure this gate exists to prevent. 'eval'
|
|
415
|
-
//
|
|
441
|
+
// fails at the first call, which is the one failure this gate exists to prevent. 'eval' is the worst
|
|
442
|
+
// to miss, being a lib.es global that typechecks in every configuration.
|
|
416
443
|
//
|
|
417
444
|
// The ADVICE stays here, because it is about repairing a snippet and that is this file's job, not the
|
|
418
445
|
// runner's. A withheld name with no entry below still fires, with a generic line — the list is the
|
|
@@ -427,7 +454,6 @@ try {
|
|
|
427
454
|
globalThis: "'globalThis' is not defined in a function body — the runner withholds it, so a host global cannot be reached by name. Everything a body is given is already in scope: 'tool', 'toolInContext' and 'context'.",
|
|
428
455
|
global: "'global' is not defined in a function body — the runner withholds it, and it is node's older alias for 'globalThis', which is withheld too. Everything a body is given is already in scope: 'tool', 'toolInContext' and 'context'.",
|
|
429
456
|
eval: "'eval' is not defined in a function body — the runner withholds it. There is nothing to evaluate at run time: write the code, or call another tool with 'await tool.<name>(…)'.",
|
|
430
|
-
Function: "'Function' is not defined in a function body — the runner withholds the constructor, so 'new Function(…)' cannot build code at run time. Write the code directly. (As a TYPE annotation it is fine; this is about the value.)",
|
|
431
457
|
};
|
|
432
458
|
// A withheld global named in a TYPE is harmless: types are erased before the body is compiled, so
|
|
433
459
|
// 'args: Buffer' never reaches the runner. Only the VALUE is rejected. Needed because the second half of
|
|
@@ -455,41 +481,28 @@ try {
|
|
|
455
481
|
return d.getSourceFile().fileName === virtual && d.getStart() >= minStart;
|
|
456
482
|
});
|
|
457
483
|
};
|
|
458
|
-
// The
|
|
459
|
-
//
|
|
460
|
-
// where both rules live and are documented.
|
|
484
|
+
// The by-name rule, inlined: the worker is a CommonJS realm with no loader hooks, so it cannot import
|
|
485
|
+
// 'importableByName' from plugin-api, which is where the rule lives and is documented.
|
|
461
486
|
const byName = function (spec) {
|
|
462
487
|
return spec !== '' && !/[^\\w@.~+!$&'()*,;=:/-]/.test(spec) && !/^[./]/.test(spec)
|
|
463
488
|
&& (spec.indexOf('node:') === 0 || !/^[a-z][a-z0-9+.-]*:/i.test(spec))
|
|
464
489
|
&& !spec.split('/').some(function (seg) { return seg === '.' || seg === '..'; });
|
|
465
490
|
};
|
|
466
|
-
// The node runner's canonicalImport, which is what the gate asks about: 'os' is 'node:os', so a
|
|
467
|
-
// restriction of 'node:' admits it at both.
|
|
468
|
-
const isBuiltin = require('node:module').isBuiltin;
|
|
469
|
-
const canonical = function (spec) {
|
|
470
|
-
return spec.indexOf(':') < 0 && isBuiltin(spec) ? 'node:' + spec : spec;
|
|
471
|
-
};
|
|
472
|
-
const permits = workerData.permittedImports;
|
|
473
491
|
const API_PKG = '@matatbread/matbot-plugin-api';
|
|
474
492
|
const withheld = new Set<string>(workerData.withheldGlobals ?? []);
|
|
475
|
-
const permitted = function (spec) {
|
|
476
|
-
return permits.some(function (p) {
|
|
477
|
-
return spec === p
|
|
478
|
-
|| (p.charAt(p.length - 1) === '/' || p.charAt(p.length - 1) === ':'
|
|
479
|
-
? spec.indexOf(p) === 0
|
|
480
|
-
: spec.indexOf(p + '/') === 0);
|
|
481
|
-
});
|
|
482
|
-
};
|
|
483
493
|
// Where an import was reported on by a rule of ours, so tsc's own complaint about the same specifier is
|
|
484
494
|
// dropped. Both fire whenever the module does not resolve, and tsc's is actively misleading here: it
|
|
485
|
-
// offers "Do you need to install type definitions for node?" about a module the
|
|
495
|
+
// offers "Do you need to install type definitions for node?" about a module the gate refuses,
|
|
486
496
|
// which is not a thing the author can fix — or, for a specifier that lands on a declaration-only
|
|
487
497
|
// package, a path inside matbot's own node_modules. Which of the three tsc emits depends on whether
|
|
488
498
|
// @types/node happens to be reachable from the program root, so these rules are the deterministic ones.
|
|
489
499
|
const importStarts = new Set();
|
|
490
|
-
// Every literal import()'s specifier and where it sits, recorded whether or not
|
|
491
|
-
// the rewrite below is about SPELLING, which no
|
|
500
|
+
// Every literal import()'s specifier and where it sits, recorded whether or not anything is refused:
|
|
501
|
+
// the rewrite below is about SPELLING, which no permission decides.
|
|
492
502
|
const importSpecs = new Map();
|
|
503
|
+
// The literal imports the gate may refuse — by name, and not the types-only package — asked about once
|
|
504
|
+
// the program is checked (see runWorker).
|
|
505
|
+
const importSites = [];
|
|
493
506
|
const envVisit = function (node, sf) {
|
|
494
507
|
if (envGate && node.getStart(sf) >= minStart) {
|
|
495
508
|
if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword
|
|
@@ -511,13 +524,8 @@ try {
|
|
|
511
524
|
synth.push(mk(sf, node.arguments[0], 90006,
|
|
512
525
|
"'" + spec + "' cannot be imported by a function body, which imports only node builtins ('node:fs') and packages already installed where matbot runs, by name — never a path or a URL. To use other code, install it as a package, or as a matbot plugin with the 'plugin' tool."));
|
|
513
526
|
importStarts.add(at);
|
|
514
|
-
} else
|
|
515
|
-
|
|
516
|
-
permits.length === 0
|
|
517
|
-
? "module imports are switched off on this installation, so '" + spec + "' cannot be imported. Compute with the tools available instead."
|
|
518
|
-
: "'" + spec + "' is not permitted on this installation, which allows only: " + permits.join(', ')
|
|
519
|
-
+ ". This is configuration, not a permission anyone can grant at the call — use a permitted module, or none."));
|
|
520
|
-
importStarts.add(at);
|
|
527
|
+
} else {
|
|
528
|
+
importSites.push({ sf: sf, node: node.arguments[0], spec: spec, at: at });
|
|
521
529
|
}
|
|
522
530
|
}
|
|
523
531
|
if (ts.isMetaProperty(node) && node.keywordToken === ts.SyntaxKind.ImportKeyword) {
|
|
@@ -542,6 +550,103 @@ try {
|
|
|
542
550
|
ts.forEachChild(node, function (c) { envVisit(c, sf); });
|
|
543
551
|
};
|
|
544
552
|
|
|
553
|
+
// ── escape gate: what reaches past the runner without naming anything it withholds ──
|
|
554
|
+
// Shadowing works on NAMES, and these are not names: every function's '.constructor' is a compiler for
|
|
555
|
+
// the global scope, where the real 'process' and every ungated builtin are; 'getBuiltinModule' loads a
|
|
556
|
+
// builtin with no import to gate; and a shared object a body changes — a built-in, its prototype, or
|
|
557
|
+
// something it was handed — is changed for the rest of matbot. The runner refuses the first two at run
|
|
558
|
+
// time however they are reached, and cannot refuse the third, so this is where a plainly-spelled one is
|
|
559
|
+
// stopped and the author told why. A computed spelling gets past it; that is deliberate tampering,
|
|
560
|
+
// which no checker is the answer to. Only with a runner: without one nothing is refused, and saying so
|
|
561
|
+
// would be untrue.
|
|
562
|
+
const escapeGate = envGate && workerData.withheldGlobals !== undefined;
|
|
563
|
+
const ESCAPE = {
|
|
564
|
+
ctor: "a function's 'constructor' compiles a string as code in matbot's own scope — outside the runner, around every withheld global and permission gate — so a function body may not reach it, and it is refused at run time too. Write the code directly, import a module with 'await import(…)' (the user is asked), or call a tool.",
|
|
565
|
+
Function: "'Function' compiles a string as code in matbot's own scope — outside the runner, around every withheld global and permission gate — so a function body may not call it, and it is refused at run time too. Write the code directly. (As a TYPE annotation it is fine; this is about the value.)",
|
|
566
|
+
builtin: "'getBuiltinModule' loads a node builtin without the import gate, so a function body may not call it, and it is refused at run time too. Import the module with 'await import('node:…')', which asks the user.",
|
|
567
|
+
proto: "'__proto__' reaches a prototype shared with the rest of matbot, which a function body may neither reach nor change. For an object with a prototype of your own, use 'Object.create(proto)' or a class.",
|
|
568
|
+
mutate: function (what) {
|
|
569
|
+
return "this changes '" + what + "', which this function body did not create. Built-ins, their prototypes and what a body is handed are shared with the rest of matbot, so changing them changes matbot. Work on a copy ('const mine = { ...x }') or a wrapper of your own instead.";
|
|
570
|
+
},
|
|
571
|
+
};
|
|
572
|
+
const unwrap = function (e) {
|
|
573
|
+
while (e && (ts.isParenthesizedExpression(e) || ts.isNonNullExpression(e) || ts.isAsExpression(e)
|
|
574
|
+
|| (ts.isTypeAssertionExpression && ts.isTypeAssertionExpression(e)) || ts.isSatisfiesExpression(e))) e = e.expression;
|
|
575
|
+
return e;
|
|
576
|
+
};
|
|
577
|
+
const memberName = function (e) {
|
|
578
|
+
if (ts.isPropertyAccessExpression(e)) return e.name.text;
|
|
579
|
+
if (ts.isElementAccessExpression(e) && ts.isStringLiteralLike(e.argumentExpression)) return e.argumentExpression.text;
|
|
580
|
+
return undefined;
|
|
581
|
+
};
|
|
582
|
+
const isGetPrototypeOf = function (e) {
|
|
583
|
+
return ts.isCallExpression(e) && ts.isPropertyAccessExpression(e.expression) && e.expression.name.text === 'getPrototypeOf';
|
|
584
|
+
};
|
|
585
|
+
// Whether an object a body is about to change is one it did not create: reached through a prototype,
|
|
586
|
+
// or rooted at a binding declared outside the snippet (a built-in, or 'tool' / 'context').
|
|
587
|
+
const shared = function (target) {
|
|
588
|
+
let e = unwrap(target);
|
|
589
|
+
for (;;) {
|
|
590
|
+
if (isGetPrototypeOf(e)) return true;
|
|
591
|
+
if (ts.isPropertyAccessExpression(e) || ts.isElementAccessExpression(e)) {
|
|
592
|
+
const n = memberName(e);
|
|
593
|
+
if (n === 'prototype' || n === '__proto__') return true;
|
|
594
|
+
e = unwrap(e.expression);
|
|
595
|
+
continue;
|
|
596
|
+
}
|
|
597
|
+
if (!ts.isIdentifier(e)) return false;
|
|
598
|
+
const sym = checker.getSymbolAtLocation(e);
|
|
599
|
+
return !!(sym && sym.declarations && sym.declarations.length > 0) && !authorDeclared(e);
|
|
600
|
+
}
|
|
601
|
+
};
|
|
602
|
+
const isCallable = function (e) {
|
|
603
|
+
const t = checker.getTypeAtLocation(e);
|
|
604
|
+
return t.getCallSignatures().length > 0 || t.getConstructSignatures().length > 0;
|
|
605
|
+
};
|
|
606
|
+
const MUTATORS = { Object: ['defineProperty', 'defineProperties', 'setPrototypeOf', 'assign'],
|
|
607
|
+
Reflect: ['defineProperty', 'set', 'setPrototypeOf', 'deleteProperty'] };
|
|
608
|
+
const isAssignment = function (k) {
|
|
609
|
+
return k >= ts.SyntaxKind.FirstAssignment && k <= ts.SyntaxKind.LastAssignment;
|
|
610
|
+
};
|
|
611
|
+
const escapeVisit = function (node, sf) {
|
|
612
|
+
if (escapeGate && node.getStart(sf) >= minStart) {
|
|
613
|
+
const name = (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) ? memberName(node) : undefined;
|
|
614
|
+
if (name === 'constructor') {
|
|
615
|
+
const obj = unwrap(node.expression);
|
|
616
|
+
if (isCallable(obj) || memberName(obj) === 'constructor') synth.push(mk(sf, node, 90007, ESCAPE.ctor));
|
|
617
|
+
} else if (name === 'getBuiltinModule') {
|
|
618
|
+
synth.push(mk(sf, node, 90007, ESCAPE.builtin));
|
|
619
|
+
} else if (name === '__proto__') {
|
|
620
|
+
synth.push(mk(sf, node, 90007, ESCAPE.proto));
|
|
621
|
+
} else if (ts.isIdentifier(node) && node.text === 'Function'
|
|
622
|
+
&& !(node.parent && ts.isPropertyAccessExpression(node.parent) && node.parent.name === node)
|
|
623
|
+
&& !(node.parent && (ts.isPropertyAssignment(node.parent) || ts.isPropertySignature(node.parent)) && node.parent.name === node)
|
|
624
|
+
&& !(node.parent && ts.isBindingElement(node.parent) && node.parent.propertyName === node)
|
|
625
|
+
&& !inTypePosition(node) && !authorDeclared(node)) {
|
|
626
|
+
synth.push(mk(sf, node, 90007, ESCAPE.Function));
|
|
627
|
+
}
|
|
628
|
+
let changed;
|
|
629
|
+
if (ts.isBinaryExpression(node) && isAssignment(node.operatorToken.kind)) changed = node.left;
|
|
630
|
+
else if ((ts.isPrefixUnaryExpression(node) || ts.isPostfixUnaryExpression(node))
|
|
631
|
+
&& (node.operator === ts.SyntaxKind.PlusPlusToken || node.operator === ts.SyntaxKind.MinusMinusToken)) changed = node.operand;
|
|
632
|
+
else if (ts.isDeleteExpression(node)) changed = node.expression;
|
|
633
|
+
else if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression)
|
|
634
|
+
&& ts.isIdentifier(node.expression.expression) && node.arguments.length > 0) {
|
|
635
|
+
const ns = MUTATORS[node.expression.expression.text];
|
|
636
|
+
if (ns && ns.indexOf(node.expression.name.text) !== -1 && !authorDeclared(node.expression.expression)) changed = node.arguments[0];
|
|
637
|
+
}
|
|
638
|
+
if (changed !== undefined) {
|
|
639
|
+
const c = unwrap(changed);
|
|
640
|
+
// Only a member: assigning a name rebinds the body's own variable, which shadowing makes harmless.
|
|
641
|
+
const member = ts.isPropertyAccessExpression(c) || ts.isElementAccessExpression(c);
|
|
642
|
+
if ((member && shared(c.expression)) || (!member && ts.isCallExpression(node) && shared(c))) {
|
|
643
|
+
synth.push(mk(sf, changed, 90007, ESCAPE.mutate(c.getText(sf))));
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
ts.forEachChild(node, function (c) { escapeVisit(c, sf); });
|
|
648
|
+
};
|
|
649
|
+
|
|
545
650
|
const skip = new Set();
|
|
546
651
|
const visit = function (node, sf) {
|
|
547
652
|
const isAssertion = ts.isAsExpression(node) || (ts.isTypeAssertionExpression && ts.isTypeAssertionExpression(node));
|
|
@@ -566,15 +671,23 @@ try {
|
|
|
566
671
|
}
|
|
567
672
|
ts.forEachChild(node, function (c) { visit(c, sf); });
|
|
568
673
|
};
|
|
569
|
-
for (const gf of gateFiles) { visit(gf, gf); contractVisit(gf, gf); envVisit(gf, gf); }
|
|
674
|
+
for (const gf of gateFiles) { visit(gf, gf); contractVisit(gf, gf); envVisit(gf, gf); escapeVisit(gf, gf); }
|
|
675
|
+
|
|
676
|
+
const finish = function (refused) {
|
|
677
|
+
try {
|
|
678
|
+
// Before the rewrites below, which defer to a position a gate has already spoken at.
|
|
679
|
+
for (const site of importSites) {
|
|
680
|
+
if (!refused.has(site.spec)) continue;
|
|
681
|
+
synth.push(mk(site.sf, site.node, 90006,
|
|
682
|
+
"'" + site.spec + "' is refused to this function by the permission policy in force — a standing answer, so the import would be refused at the call too. Use another module, or none; this is not something to work around."));
|
|
683
|
+
importStarts.add(site.at);
|
|
684
|
+
}
|
|
570
685
|
|
|
571
686
|
// A bare 'node' is not the builtins namespace — it resolves to @types/node's index.d.ts, which is
|
|
572
687
|
// references and ambient blocks with no export, so tsc reports "File '<matbot's own node_modules>/
|
|
573
688
|
// @types/node/index.d.ts' is not a module": a path the body never named and its author cannot act on.
|
|
574
689
|
// Rewritten only where tsc ALREADY failed on it, so a package genuinely called 'node' is untouched,
|
|
575
|
-
// and only where no gate has spoken at that position, so one mistake stays one finding.
|
|
576
|
-
// a restriction of ["node"] permits — a package of that name, no builtin — which is why this fires with
|
|
577
|
-
// no restriction in force too.
|
|
690
|
+
// and only where no gate has spoken at that position, so one mistake stays one finding.
|
|
578
691
|
for (const d of targets) {
|
|
579
692
|
if (d.code !== 2306 && d.code !== 2307) continue;
|
|
580
693
|
if (importSpecs.get(d.start) !== 'node' || importStarts.has(d.start)) continue;
|
|
@@ -603,7 +716,7 @@ try {
|
|
|
603
716
|
if (spec !== undefined) {
|
|
604
717
|
synth.push({ file: d.file, start: d.start, length: d.length, code: 90006,
|
|
605
718
|
category: ts.DiagnosticCategory.Error, __syn: true,
|
|
606
|
-
messageText: "'" + spec + "' has no type declarations here, so nothing it returns can be checked.
|
|
719
|
+
messageText: "'" + spec + "' has no type declarations here, so nothing it returns can be checked. Use a builtin that has them, or define this function with noTypeCheck." });
|
|
607
720
|
importStarts.add(d.start);
|
|
608
721
|
continue;
|
|
609
722
|
}
|
|
@@ -656,7 +769,22 @@ try {
|
|
|
656
769
|
}
|
|
657
770
|
return out;
|
|
658
771
|
};
|
|
659
|
-
|
|
772
|
+
// Read from the program just checked, so a schema describes exactly the types that were graded.
|
|
773
|
+
const parameters = workerData.parametersOf && virtual !== null
|
|
774
|
+
? require(workerData.parametersModule).parametersOf(ts, program.getTypeChecker(), program.getSourceFile(virtual), workerData.parametersOf)
|
|
775
|
+
: undefined;
|
|
776
|
+
parentPort.postMessage({ ok: errors.length === 0, diagnostics: errors.map(rec), ...(parameters ? { parameters } : {}) });
|
|
777
|
+
} catch (e) {
|
|
778
|
+
parentPort.postMessage({ error: String((e && e.message) || e) });
|
|
779
|
+
}
|
|
780
|
+
};
|
|
781
|
+
|
|
782
|
+
const asked = workerData.askImports ? [...new Set(importSites.map(function (s) { return s.spec; }))] : [];
|
|
783
|
+
if (asked.length === 0) finish(new Set());
|
|
784
|
+
else {
|
|
785
|
+
parentPort.once('message', function (m) { finish(new Set(m.refused)); });
|
|
786
|
+
parentPort.postMessage({ ask: asked });
|
|
787
|
+
}
|
|
660
788
|
} catch (e) {
|
|
661
789
|
parentPort.postMessage({ error: String((e && e.message) || e) });
|
|
662
790
|
}
|
package/src/index.ts
CHANGED
|
@@ -1,13 +1,19 @@
|
|
|
1
1
|
import { dirname, join, resolve } from 'node:path';
|
|
2
2
|
import { existsSync, readFileSync } from 'node:fs';
|
|
3
|
-
import { createRequire } from 'node:module';
|
|
4
|
-
import {
|
|
5
|
-
import
|
|
3
|
+
import { builtinModules, createRequire } from 'node:module';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { PLUGIN_API_VERSION, RegistryChangeKind, contractArms, splitContract } from '@matatbread/matbot-plugin-api';
|
|
6
|
+
import type { FunctionRunner, MatbotMachine, MatbotPluginSpec, ToolCheckOptions, ToolCheckReport, ToolTypeIndex } from '@matatbread/matbot-plugin-api';
|
|
6
7
|
import { getRegisteredPlugins } from '@matatbread/matbot-core';
|
|
7
8
|
import { buildToolTypesData, compileToolValidators, type SyntheticContract, type ToolTypesData } from './build-dts.js';
|
|
8
9
|
import { checkSnippetAgainst } from './checker.js';
|
|
10
|
+
import { anchorPackage } from './anchor.js';
|
|
9
11
|
import type { ToolValidator } from './validator.js';
|
|
10
12
|
|
|
13
|
+
// Where to resolve from when the host names no project: this package's own install, from which plugin-api,
|
|
14
|
+
// core and `@types/node` all resolve. Never the working directory — a plugin is handed its directories.
|
|
15
|
+
const OWN_DIR = fileURLToPath(new URL('..', import.meta.url));
|
|
16
|
+
|
|
11
17
|
export {
|
|
12
18
|
buildMatbotToolsDts, buildToolTypesData, collectToolTypeRoots, compileToolValidators, filterToolTypesData,
|
|
13
19
|
type DtsParts, type MatbotToolsDts, type ToolTypesData, type ToolTypeRoots,
|
|
@@ -47,35 +53,6 @@ export function asToolValidatorSupplier(index: unknown): ToolValidatorSupplier |
|
|
|
47
53
|
: undefined;
|
|
48
54
|
}
|
|
49
55
|
|
|
50
|
-
// Split a string on `sep` at bracket-depth 0 only (respecting `<> {} () []`), so a top-level `|` or `,`
|
|
51
|
-
// inside a nested type isn't mistaken for a separator.
|
|
52
|
-
function splitTopLevel(s: string, sep: string): string[] {
|
|
53
|
-
const parts: string[] = [];
|
|
54
|
-
let depth = 0, start = 0;
|
|
55
|
-
for (let i = 0; i < s.length; i++) {
|
|
56
|
-
const c = s[i];
|
|
57
|
-
if (c === '<' || c === '{' || c === '(' || c === '[') depth++;
|
|
58
|
-
else if (c === '>' || c === '}' || c === ')' || c === ']') depth--;
|
|
59
|
-
else if (depth === 0 && c === sep) { parts.push(s.slice(start, i)); start = i + 1; }
|
|
60
|
-
}
|
|
61
|
-
parts.push(s.slice(start));
|
|
62
|
-
return parts;
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
// Flatten a `toolContract` (`ToolContract<Result, Args>`, or a `|`-union of such arms) to the wire's
|
|
66
|
-
// `params`/`result` union text — the same projection build-dts derives from source arms.
|
|
67
|
-
function splitContract(contract: string): { params: string; result: string } {
|
|
68
|
-
const results: string[] = [], params: string[] = [];
|
|
69
|
-
for (const armText of splitTopLevel(contract, '|')) {
|
|
70
|
-
const m = armText.trim().match(/^ToolContract\s*<([\s\S]*)>$/);
|
|
71
|
-
if (!m) continue;
|
|
72
|
-
const inner = splitTopLevel(m[1]!, ',');
|
|
73
|
-
if (inner[0] !== undefined) results.push(inner[0].trim());
|
|
74
|
-
if (inner[1] !== undefined) params.push(inner[1].trim());
|
|
75
|
-
}
|
|
76
|
-
return { result: results.join(' | ') || 'unknown', params: params.join(' | ') || 'unknown' };
|
|
77
|
-
}
|
|
78
|
-
|
|
79
56
|
// Best-effort JSON-Schema → TypeScript type text. Used only for the params half of a tool that has neither
|
|
80
57
|
// a source augmentation nor a `toolContract` (a foreign/MCP proxy): its `inputSchema` is always present, so
|
|
81
58
|
// we synthesise *something* structural rather than leaving `unknown` — so a composer sees real fields. There
|
|
@@ -155,16 +132,12 @@ export const buildToolTypes: ToolTypesFill = i =>
|
|
|
155
132
|
* already declares is skipped, so nothing is declared twice. `declare const tool: ToolProxy` (mapped over
|
|
156
133
|
* the merged `ToolContracts`) plus its override factory `toolInContext` is what generators call.
|
|
157
134
|
*/
|
|
158
|
-
/**
|
|
159
|
-
*
|
|
160
|
-
*
|
|
161
|
-
|
|
162
|
-
* itself. */
|
|
163
|
-
function fingerprintOf(runner: FunctionRunner | undefined, settings: FunctionRunSettings | undefined): string {
|
|
135
|
+
/** What a runner states, printed: a stable fingerprint of the environment a check's verdict was reached
|
|
136
|
+
* under, for a caller that PERSISTS the verdict (`function-tools` stores one beside each definition and
|
|
137
|
+
* compares it). Sorted and printed rather than identity-derived, because it has to survive a restart. */
|
|
138
|
+
function fingerprintOf(runner: FunctionRunner | undefined): string {
|
|
164
139
|
if (runner === undefined) return 'no-runner';
|
|
165
|
-
|
|
166
|
-
return `permit=${permit === undefined ? '*' : [...permit].sort().join(',')};`
|
|
167
|
-
+ `withheld=${[...(runner.withheldGlobals ?? [])].sort().join(',')}`;
|
|
140
|
+
return `withheld=${[...(runner.withheldGlobals ?? [])].sort().join(',')}`;
|
|
168
141
|
}
|
|
169
142
|
|
|
170
143
|
export class ToolTypeIndexImpl implements ToolTypeIndex {
|
|
@@ -187,9 +160,9 @@ export class ToolTypeIndexImpl implements ToolTypeIndex {
|
|
|
187
160
|
//
|
|
188
161
|
// A `FunctionRunner` arriving or leaving deliberately does NOT, though it is the obvious thing to
|
|
189
162
|
// reach for now that the runner is a plugin and can appear after a dts has been handed out. Nothing
|
|
190
|
-
// derived from it is held: each `dts`/`check`/`environment` reads the runner
|
|
191
|
-
//
|
|
192
|
-
//
|
|
163
|
+
// derived from it is held: each `dts`/`check`/`environment` reads the runner once at its start, and
|
|
164
|
+
// the one cache near it — {@link importPaths} — keys on the refused set's CONTENT, so a different
|
|
165
|
+
// answer is a different key. What IS cached is the source scan, which the
|
|
193
166
|
// runner has no part in. Subscribing would throw away a good TypeScript build every time the runner
|
|
194
167
|
// was registered or hot-reloaded, to recompute something that was never stale.
|
|
195
168
|
machine.Notifier.consume(() => { this.generation++; }, this.ac.signal,
|
|
@@ -213,7 +186,7 @@ export class ToolTypeIndexImpl implements ToolTypeIndex {
|
|
|
213
186
|
// Read before anything is awaited, with the live tool list: a change that lands while this builds
|
|
214
187
|
// leaves the result stale, for the next caller to rebuild, instead of being marked seen.
|
|
215
188
|
const generation = this.generation;
|
|
216
|
-
const root = this.machine.
|
|
189
|
+
const root = this.machine.projectDir ?? OWN_DIR;
|
|
217
190
|
// Scan the source each loaded plugin was actually loaded from (its resolvedUrl) — builtin, compiled
|
|
218
191
|
// (.compiled-plugins/), or installed (.plugins/) alike — so every registered tool's real augmentation
|
|
219
192
|
// is read. build-dts UNIONs a glob of the monorepo `plugins/` tree onto these roots (not a fallback:
|
|
@@ -244,17 +217,9 @@ export class ToolTypeIndexImpl implements ToolTypeIndex {
|
|
|
244
217
|
this.builtFor = generation;
|
|
245
218
|
}
|
|
246
219
|
|
|
247
|
-
|
|
248
|
-
* passed to everything inside it. Per invocation, never cached: whose settings they are depends on how
|
|
249
|
-
* the settings store is partitioned, and the next invocation may be another principal's. */
|
|
250
|
-
private async runnerNow(): Promise<{ runner: FunctionRunner | undefined; settings: FunctionRunSettings | undefined }> {
|
|
251
|
-
const runner = this.machine.FunctionRunner;
|
|
252
|
-
return { runner, settings: await runner?.settings?.() };
|
|
253
|
-
}
|
|
254
|
-
|
|
255
|
-
async dts(): Promise<string> { return this.dtsUnder(await this.runnerNow()); }
|
|
220
|
+
async dts(): Promise<string> { return this.dtsUnder(this.machine.FunctionRunner); }
|
|
256
221
|
|
|
257
|
-
private async dtsUnder(
|
|
222
|
+
private async dtsUnder(runner: FunctionRunner | undefined): Promise<string> {
|
|
258
223
|
await this.ensureBuilt();
|
|
259
224
|
// `tool` — the injected proxy `function-tools`/compiled skills call — is a `ToolProxy`, a mapped type
|
|
260
225
|
// over the (augmented) `ToolContracts`: each multi-arm entry becomes an overload set, so `await
|
|
@@ -268,7 +233,7 @@ export class ToolTypeIndexImpl implements ToolTypeIndex {
|
|
|
268
233
|
// checker agreed. It names what is permitted HERE, from the live set, rather than claiming imports
|
|
269
234
|
// work in general — a module outside the set does not resolve, which is the whole point of scoping
|
|
270
235
|
// the types to it. `require` and the rest are rejected by the env gate, not left to fail at a call.
|
|
271
|
-
return `${this.registryBlock(this.cache!)}\ndeclare const tool: import('@matatbread/matbot-plugin-api').ToolProxy;\ndeclare const toolInContext: import('@matatbread/matbot-plugin-api').ToolBox;\ndeclare const context: import('@matatbread/matbot-plugin-api').ComposedCallContext;\n${
|
|
236
|
+
return `${this.registryBlock(this.cache!)}\ndeclare const tool: import('@matatbread/matbot-plugin-api').ToolProxy;\ndeclare const toolInContext: import('@matatbread/matbot-plugin-api').ToolBox;\ndeclare const context: import('@matatbread/matbot-plugin-api').ComposedCallContext;\n${this.importNote(runner)}`;
|
|
272
237
|
}
|
|
273
238
|
|
|
274
239
|
async wireContracts(): Promise<Record<string, { params: string; result: string }>> {
|
|
@@ -283,186 +248,112 @@ export class ToolTypeIndexImpl implements ToolTypeIndex {
|
|
|
283
248
|
}
|
|
284
249
|
|
|
285
250
|
/**
|
|
286
|
-
* `paths` for the
|
|
287
|
-
*
|
|
288
|
-
*
|
|
289
|
-
*
|
|
290
|
-
*
|
|
291
|
-
* which types it. An absent restriction means every builtin: a body may ASK for anything and the gate
|
|
292
|
-
* decides, so refusing to type what it may legitimately ask for would make the prompt unreachable.
|
|
293
|
-
* Resolved from THIS package, where `@types/node` is a dependency: the program is
|
|
251
|
+
* `paths` for the builtins a body may import, so `await import('node:os')` is checked against the real
|
|
252
|
+
* signatures — every builtin, less any the permission gate REFUSES the code being checked
|
|
253
|
+
* ({@link ToolCheckOptions.importRefused}). Not the set it would ALLOW: anything the gate has not
|
|
254
|
+
* refused may be asked for, and refusing to type what a body may legitimately ask for would make the
|
|
255
|
+
* prompt unreachable. Resolved from THIS package, where `@types/node` is a dependency: the program is
|
|
294
256
|
* rooted at the `matbot.yaml` directory, which under pnpm and in any published install has no
|
|
295
257
|
* `node_modules/@types` in its lookup chain, so nothing would resolve from there.
|
|
296
258
|
*
|
|
297
259
|
* A builtin gets its real declaration file. A bare package name is left to ordinary resolution: if it
|
|
298
|
-
* is installed it types properly, and if it is not, the error is honest.
|
|
260
|
+
* is installed it types properly, and if it is not, the error is honest. A refused one is IMPORT-GATE's.
|
|
299
261
|
*
|
|
300
262
|
* A path or a URL gets nothing, because a body cannot import one at all (`importableByName`), and
|
|
301
263
|
* IMPORT-GATE says so at the check.
|
|
302
264
|
*/
|
|
303
|
-
/**
|
|
304
|
-
*
|
|
305
|
-
* CONTENT of the permit list it was computed from: settings are read afresh per invocation, so each
|
|
306
|
-
* read is a new array and an identity key would never hit. */
|
|
265
|
+
/** It walks every builtin with a stat apiece, so it is cached against the CONTENT of the refused set:
|
|
266
|
+
* the gate is read afresh per check, and nearly always refuses the same builtins (usually none). */
|
|
307
267
|
private pathsFor?: { key: string; paths: Record<string, string[]> };
|
|
308
268
|
|
|
309
|
-
private async importPaths(
|
|
310
|
-
const key =
|
|
269
|
+
private async importPaths(refused: ReadonlySet<string>): Promise<Record<string, string[]>> {
|
|
270
|
+
const key = [...refused].sort().join(',');
|
|
311
271
|
if (this.pathsFor !== undefined && this.pathsFor.key === key) return this.pathsFor.paths;
|
|
312
|
-
const paths =
|
|
272
|
+
const paths = computeImportPaths(refused);
|
|
313
273
|
this.pathsFor = { key, paths };
|
|
314
274
|
return paths;
|
|
315
275
|
}
|
|
316
276
|
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
//
|
|
327
|
-
// expanded here: `node:fs` admits `node:fs/promises` at the gate, so it must TYPE the submodule too.
|
|
328
|
-
// Emitting the exact specifier alone left a permitted import failing the check, reachable only with
|
|
329
|
-
// `noTypeCheck` — the one divergence between what runs and what is graded.
|
|
330
|
-
// What the GATE would allow, which is the only set worth typing: unrestricted admits any spelling, a
|
|
331
|
-
// restriction admits what its boundary rule admits. Anything else is a divergence between what runs
|
|
332
|
-
// and what is graded, in one direction or the other.
|
|
333
|
-
const allowed = (spec: string): boolean => restricted === undefined || importPermitted(restricted, spec);
|
|
334
|
-
for (const m of builtinModules) {
|
|
335
|
-
if (m.startsWith('_')) continue;
|
|
336
|
-
// Some entries ALREADY carry the prefix — node:sea, node:sqlite, node:test, node:test/reporters,
|
|
337
|
-
// which have no unprefixed spelling — so prefixing unconditionally wrote `node:node:sqlite`, and
|
|
338
|
-
// those four got no entry at all. `await import('node:sqlite')` then failed the check with tsc's
|
|
339
|
-
// "install type definitions for node", which is the message IMPORT-GATE exists to replace.
|
|
340
|
-
const prefixed = m.startsWith('node:');
|
|
341
|
-
const bare = prefixed ? m.slice('node:'.length) : m;
|
|
342
|
-
const file = declarationFile(nodeTypes, bare);
|
|
343
|
-
if (file === undefined) continue;
|
|
344
|
-
if (allowed(`node:${bare}`)) out[`node:${bare}`] = [file];
|
|
345
|
-
// The UNPREFIXED spelling too, where node has one: `import('os')` resolves to `node:os` at run
|
|
346
|
-
// time, and a bare specifier is the spelling a model reaches for first. Allowed by the PREFIXED
|
|
347
|
-
// spelling, because that is what the gate asks about (`canonicalImport`) — so `['node:']` types
|
|
348
|
-
// `os`, as the gate admits it.
|
|
349
|
-
if (!prefixed && allowed(`node:${bare}`)) out[bare] = [file];
|
|
350
|
-
}
|
|
351
|
-
return out;
|
|
352
|
-
}
|
|
353
|
-
|
|
354
|
-
/** The part of the dts that is about imports: which modules this install permits AND which of those
|
|
355
|
-
* have types, that second half being this package's own knowledge. Everything else about the
|
|
356
|
-
* environment — the gate, what is not in scope — is the runner's to state, and is appended verbatim. */
|
|
357
|
-
private async importNote(runner: FunctionRunner | undefined, settings: FunctionRunSettings | undefined): Promise<string> {
|
|
358
|
-
const restricted = settings?.permittedImports;
|
|
359
|
-
const typed = new Set(Object.keys(await this.importPaths(restricted)));
|
|
360
|
-
// "Switched off" is `permit: []` and nothing else — the one configured "never". Derived from the
|
|
361
|
-
// TYPED set instead, it fired for any restriction naming no builtin (`permit: ['lodash']`), telling
|
|
362
|
-
// an author imports were off while the gate was perfectly willing to ask about one.
|
|
363
|
-
// An entry is typed if it names a declaration itself or admits one — `node:` and `node:fs` both do,
|
|
364
|
-
// through their submodules. A bare package admits none, which is a stated refusal rather than a fake
|
|
365
|
-
// type, so the listing says so where the author will read it.
|
|
366
|
-
const covered = (p: string): boolean => typed.has(p) || [...typed].some(t => importPermitted([p], t));
|
|
367
|
-
// The EXPANDED set, because a prefix is not an answer: `node:` tells an author nothing about which
|
|
368
|
-
// builtins exist, and `node:fs` hides that `node:fs/promises` came with it. Restriction entries that
|
|
369
|
-
// admit no declaration at all are listed after it, marked — a bare package is untypeable here, which
|
|
370
|
-
// is a stated refusal rather than a fake type, and the author needs to know which it is.
|
|
371
|
-
// A bare `node` is the one entry that is not merely untypeable but unimportable: the boundary rule
|
|
372
|
-
// reads it as a PACKAGE of that name (it admits `node/sub`, never `node:os`), so an install meaning
|
|
373
|
-
// the builtins and missing the colon permits nothing a body can use. Listing it as "untyped —
|
|
374
|
-
// import it only with noTypeCheck" invited exactly the attempt that cannot work, so it says what it is.
|
|
375
|
-
// A path or a URL is unimportable outright, whoever's runner listed it: the gate never asks about one.
|
|
376
|
-
const mark = (p: string): string => p === 'node'
|
|
377
|
-
? `${p} (a PACKAGE of that name — not node's builtins, which are spelled 'node:fs'; nothing here can import it)`
|
|
378
|
-
: !importableByName(p.replace(/\/$/, ''))
|
|
379
|
-
? `${p} (a path or a URL — a body imports only builtins and packages, by name; nothing here can import it)`
|
|
380
|
-
: `${p} (untyped — import it only with noTypeCheck)`;
|
|
381
|
-
const listing = [
|
|
382
|
-
...[...typed].sort(),
|
|
383
|
-
...(restricted ?? []).filter(p => !covered(p)).sort().map(mark),
|
|
384
|
-
];
|
|
385
|
-
// Whether an import is GATED is whether a runner routes it, not whether a restriction exists. With no
|
|
386
|
-
// runner nothing rewrites `import(…)`: it reaches node's own loader, unasked and unchecked. Saying
|
|
387
|
-
// "you will be asked" there is a promise nothing keeps, and a body discovers the contradiction the
|
|
388
|
-
// first time it imports something.
|
|
277
|
+
/** The part of the dts that is about imports. Composed from what the runner STATES — whether there is
|
|
278
|
+
* one, and the identifiers it does not bind — never from prose it supplies: the facts are the runner's,
|
|
279
|
+
* the wording is this file's, and the same list is what ENV-GATE enforces, so the note cannot drift
|
|
280
|
+
* from it. */
|
|
281
|
+
private importNote(runner: FunctionRunner | undefined): string {
|
|
282
|
+
// Whether an import is GATED is whether a runner routes it. With no runner nothing rewrites
|
|
283
|
+
// `import(…)`: it reaches node's own loader, unasked and unchecked. Saying "you will be asked" there
|
|
284
|
+
// is a promise nothing keeps, and a body discovers the contradiction the first time it imports
|
|
285
|
+
// something. Which modules the gate REFUSES is not listed: that is an answer about one function, and
|
|
286
|
+
// this text is shown to every one. A literal import of a refused module fails the check, saying so.
|
|
389
287
|
const gated = runner !== undefined;
|
|
390
|
-
const
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
: restricted === undefined
|
|
394
|
-
? `// A body may import node builtins${subject}${gated ? ' — you will be asked\n// the first time' : ''}: const fs = await import('node:fs/promises');\n`
|
|
395
|
-
: `// A body may import these${subject}:\n`
|
|
396
|
-
+ `${listing.map(p => `// ${p}`).join('\n')}\n`;
|
|
397
|
-
// Composed from what the runner STATES — the permitted set above, and the identifiers it does not
|
|
398
|
-
// bind — never from prose it supplies: the facts are the runner's, the wording is this file's, and
|
|
399
|
-
// the same two arrays are what IMPORT-GATE and ENV-GATE enforce, so the note cannot drift from them.
|
|
288
|
+
const note = gated
|
|
289
|
+
? `// A body may import node builtins and installed packages, each subject to permission at the call — you will be asked\n// the first time: const fs = await import('node:fs/promises');\n`
|
|
290
|
+
: `// A body may import node builtins and installed packages: const fs = await import('node:fs/promises');\n`;
|
|
400
291
|
const withheld = runner?.withheldGlobals ?? [];
|
|
401
292
|
return `${note}`
|
|
402
293
|
+ (withheld.length > 0
|
|
403
294
|
? `// A body is a bare async function, not a module, and not every global is in scope. Absent: ${withheld.join(', ')}, import.meta.\n`
|
|
295
|
+
+ `// Nor can it build code from a string: 'Function' and every function's '.constructor' refuse a body.\n`
|
|
404
296
|
: '');
|
|
405
297
|
}
|
|
406
298
|
|
|
407
|
-
/** The
|
|
299
|
+
/** The runner's statement, printed: a stable fingerprint of the environment a check's verdict was
|
|
408
300
|
* reached under, for a caller that PERSISTS the verdict (`function-tools` stores one beside each
|
|
409
|
-
* definition).
|
|
410
|
-
* — unlike {@link pathsFor}, whose job is the opposite and which keys on the array itself. */
|
|
301
|
+
* definition). */
|
|
411
302
|
async environment(): Promise<string> {
|
|
412
|
-
|
|
413
|
-
return fingerprintOf(runner, settings);
|
|
303
|
+
return fingerprintOf(this.machine.FunctionRunner);
|
|
414
304
|
}
|
|
415
305
|
|
|
416
|
-
async check(snippet: string): Promise<ToolCheckReport> {
|
|
306
|
+
async check(snippet: string, opts?: ToolCheckOptions): Promise<ToolCheckReport> {
|
|
417
307
|
// ABSOLUTE, always. The virtual file is named `<root>/…`, and `ts.createProgram` normalises a
|
|
418
308
|
// relative one to a different string than the hook compares against — so `getSourceFile(virtual)`
|
|
419
309
|
// missed, there were no files to check, and the snippet came back clean whatever was in it. A
|
|
420
310
|
// checker that silently passes everything is the one failure mode this path must not have.
|
|
421
|
-
const root = resolve(this.machine.
|
|
422
|
-
// Read ONCE, before anything else: the dts, the
|
|
423
|
-
//
|
|
424
|
-
//
|
|
425
|
-
const
|
|
426
|
-
const prefix = `${await this.dtsUnder(
|
|
311
|
+
const root = resolve(this.machine.projectDir ?? OWN_DIR);
|
|
312
|
+
// Read ONCE, before anything else: the dts, the worker's list and the fingerprint stamped below all
|
|
313
|
+
// have to describe one environment — the one this was graded against — not whatever is current by
|
|
314
|
+
// the time each is computed.
|
|
315
|
+
const runner = this.machine.FunctionRunner;
|
|
316
|
+
const prefix = `${await this.dtsUnder(runner)}\n`;
|
|
427
317
|
const source = `${prefix}${snippet}\nexport {};\n`; // trailing export ⇒ this file is a module
|
|
428
318
|
|
|
429
|
-
// Anchor `@matatbread/matbot-plugin-api`
|
|
430
|
-
//
|
|
431
|
-
//
|
|
432
|
-
const
|
|
433
|
-
let apiIndex: string | undefined = existsSync(monorepoApi) ? monorepoApi : undefined;
|
|
319
|
+
// Anchor `@matatbread/matbot-plugin-api` (see anchorPackage). Without it the dts's imports fail, `tool`
|
|
320
|
+
// is `any`, and every tool call in the snippet passes — so a check that cannot find it is a plumbing
|
|
321
|
+
// fault, and is refused as one rather than reported as a pass.
|
|
322
|
+
const apiIndex = anchorPackage(root, 'plugin-api', '@matatbread/matbot-plugin-api');
|
|
434
323
|
if (apiIndex === undefined) {
|
|
435
|
-
|
|
324
|
+
throw new Error('cannot type-check: @matatbread/matbot-plugin-api resolves neither from the project ' +
|
|
325
|
+
`directory (${root}) nor from tool-types itself, so every tool call would typecheck as \`any\`.`);
|
|
436
326
|
}
|
|
437
327
|
|
|
438
328
|
// Worker-hosted check (see checker.ts) — off the main loop, and each diagnostic comes back as an
|
|
439
329
|
// annotated block (caret-anchored frame, related locations, HINT) with snippet-relative positions.
|
|
440
|
-
const
|
|
441
|
-
const importPaths = await this.importPaths(
|
|
442
|
-
|
|
443
|
-
// ambient `declare module 'node:…'` blocks of everything its own declarations reference, so a
|
|
444
|
-
// forbidden specifier resolves through the back door and typechecks clean. The checker closes that
|
|
445
|
-
// structurally. Absent stays absent — unrestricted means nothing to enforce.
|
|
446
|
-
const restricted = settings?.permittedImports;
|
|
447
|
-
const withheld = runner?.withheldGlobals;
|
|
330
|
+
const refused = opts?.importRefused;
|
|
331
|
+
const importPaths = await this.importPaths(refusedBuiltins(refused));
|
|
332
|
+
const withheld = runner?.withheldGlobals;
|
|
448
333
|
const report = await checkSnippetAgainst({
|
|
449
334
|
root, source,
|
|
450
335
|
prefixLen: prefix.length,
|
|
451
336
|
prefixLines: prefix.split('\n').length - 1,
|
|
452
|
-
|
|
337
|
+
apiIndexPath: apiIndex,
|
|
453
338
|
...(Object.keys(importPaths).length > 0 ? { importPaths } : {}),
|
|
454
339
|
globalTypes: nodeGlobalTypes(),
|
|
455
|
-
|
|
340
|
+
// Not only its `paths`: one builtin's declaration file drags in the ambient `declare module
|
|
341
|
+
// 'node:…'` blocks of everything its own declarations reference, so a refused specifier resolves
|
|
342
|
+
// through the back door and typechecks clean, and a package resolves by ordinary lookup. The
|
|
343
|
+
// checker closes that structurally, asking this predicate about the literal imports it finds.
|
|
344
|
+
...(refused !== undefined ? { importRefused: refused } : {}),
|
|
456
345
|
// ENV-GATE's list, from the runner that withholds them. Absent with no runner, which is correct:
|
|
457
346
|
// nothing is withheld there either, so there is nothing to reject.
|
|
458
347
|
...(withheld !== undefined ? { withheldGlobals: withheld } : {}),
|
|
348
|
+
...(opts?.parametersOf !== undefined ? { parametersOf: opts.parametersOf } : {}),
|
|
459
349
|
});
|
|
460
|
-
// Stamped here and nowhere else, from the same
|
|
461
|
-
//
|
|
462
|
-
//
|
|
463
|
-
return report.checked ? { ...report, environment: fingerprintOf(runner
|
|
350
|
+
// Stamped here and nowhere else, from the same runner the worker was handed, so the fingerprint
|
|
351
|
+
// cannot describe an environment other than the one graded against. Only on a verdict that exists:
|
|
352
|
+
// `checked: false` has nothing to be stale.
|
|
353
|
+
return report.checked ? { ...report, environment: fingerprintOf(runner) } : report;
|
|
464
354
|
}
|
|
465
355
|
|
|
356
|
+
|
|
466
357
|
// Every live tool the source scan didn't already declare: a source-less tool that carries its contract as
|
|
467
358
|
// a `toolContract` string (a `function-tools` function; the `tool-store` per-namespace tool), spliced
|
|
468
359
|
// verbatim; plus any tool with neither augmentation nor `toolContract` (a foreign/MCP proxy, or a plugin
|
|
@@ -529,6 +420,36 @@ function nodeGlobalTypes(): string[] {
|
|
|
529
420
|
return ['buffer.buffer.d.ts', 'buffer.d.ts'].map(f => join(nodeTypes, f)).filter(f => existsSync(f));
|
|
530
421
|
}
|
|
531
422
|
|
|
423
|
+
// Every builtin by its canonical, prefixed name — the spelling the gate is asked about. Some entries
|
|
424
|
+
// ALREADY carry the prefix — node:sea, node:sqlite, node:test, node:test/reporters, which have no
|
|
425
|
+
// unprefixed spelling — so prefixing unconditionally wrote `node:node:sqlite`, and those four got no entry.
|
|
426
|
+
const BUILTINS: readonly string[] = builtinModules
|
|
427
|
+
.filter(m => !m.startsWith('_'))
|
|
428
|
+
.map(m => m.startsWith('node:') ? m : `node:${m}`);
|
|
429
|
+
|
|
430
|
+
// The builtins the gate refuses the code being checked, asked one at a time: each is its own question to
|
|
431
|
+
// the gate, and `node:fs` refused says nothing the gate did not say about `node:fs/promises`.
|
|
432
|
+
function refusedBuiltins(refused: ((spec: string) => boolean) | undefined): Set<string> {
|
|
433
|
+
return refused === undefined ? new Set() : new Set(BUILTINS.filter(b => refused(b)));
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
function computeImportPaths(refused: ReadonlySet<string>): Record<string, string[]> {
|
|
437
|
+
const nodeTypes = dirname(createRequire(import.meta.url).resolve('@types/node/package.json'));
|
|
438
|
+
const out: Record<string, string[]> = {};
|
|
439
|
+
for (const spec of BUILTINS) {
|
|
440
|
+
if (refused.has(spec)) continue;
|
|
441
|
+
const bare = spec.slice('node:'.length);
|
|
442
|
+
const file = declarationFile(nodeTypes, bare);
|
|
443
|
+
if (file === undefined) continue;
|
|
444
|
+
out[spec] = [file];
|
|
445
|
+
// The UNPREFIXED spelling too, where node has one: `import('os')` resolves to `node:os` at run time,
|
|
446
|
+
// and a bare specifier is the spelling a model reaches for first. Decided by the PREFIXED spelling,
|
|
447
|
+
// because that is what the gate asks about (`canonicalImport`).
|
|
448
|
+
if (builtinModules.includes(bare)) out[bare] = [file];
|
|
449
|
+
}
|
|
450
|
+
return out;
|
|
451
|
+
}
|
|
452
|
+
|
|
532
453
|
// Where @types/node declares a builtin. Most have a file of their own, but a few subpaths are declared
|
|
533
454
|
// inside their parent's (`path/posix` in path.d.ts, `util/types` in util.d.ts, `test/reporters` in
|
|
534
455
|
// test.d.ts), and skipping those left a module the gate admits failing the check. The parent is taken
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import type TS from 'typescript';
|
|
2
|
+
|
|
3
|
+
// The JSON Schema of a function's parameters, from the CHECKER'S RESOLVED TYPES — what a defined tool's
|
|
4
|
+
// `inputSchema` is on node. function-tools derives the same thing from the parameter text by hand, which is
|
|
5
|
+
// all the browser has; that derivation cannot see a named type, an imported one, an alias, `Omit<…>` or an
|
|
6
|
+
// indexed access, and degrades each to `{}`. Here every one of them arrives already evaluated.
|
|
7
|
+
//
|
|
8
|
+
// Required by the checker's worker, which runs as CommonJS with no loader hooks: hence `.cts`, which node
|
|
9
|
+
// strips like any other TypeScript, and `module.exports` rather than an `export`.
|
|
10
|
+
//
|
|
11
|
+
// The conventions are the hand path's, so the two agree wherever both can answer: the JSON projection of the
|
|
12
|
+
// type (`toJSON` wins, a method is absent), a union of scalars as a `type`/`enum` pair, and anything a
|
|
13
|
+
// provider or json-validation could not honour — a union with a structural arm, a tuple's positions, a
|
|
14
|
+
// function — as the permissive `{}` rather than a constraint that rejects a valid call.
|
|
15
|
+
|
|
16
|
+
type Schema = Record<string, unknown>;
|
|
17
|
+
|
|
18
|
+
interface Parameter { name: string; optional: boolean; schema: Schema }
|
|
19
|
+
|
|
20
|
+
const MAX_DEPTH = 6;
|
|
21
|
+
|
|
22
|
+
// Their instances stringify to `{}`: state behind accessors or internal slots, so nothing reaches the wire.
|
|
23
|
+
const EMPTY_JSON = new Set(['Map', 'Set', 'WeakMap', 'WeakSet', 'WeakRef', 'RegExp', 'Promise', 'Error']);
|
|
24
|
+
|
|
25
|
+
function schemaOf(ts: typeof TS, checker: TS.TypeChecker, location: TS.Node, root: TS.Type): Schema {
|
|
26
|
+
const F = ts.TypeFlags;
|
|
27
|
+
const onPath = new Set<TS.Type>();
|
|
28
|
+
|
|
29
|
+
const scalar = (t: TS.Type): { type: string; value?: string | number | boolean } | undefined => {
|
|
30
|
+
if (t.flags & F.StringLiteral) return { type: 'string', value: (t as TS.StringLiteralType).value };
|
|
31
|
+
if (t.flags & F.NumberLiteral) return { type: 'number', value: (t as TS.NumberLiteralType).value };
|
|
32
|
+
if (t.flags & F.BooleanLiteral) return { type: 'boolean', value: checker.typeToString(t) === 'true' };
|
|
33
|
+
if (t.flags & F.String) return { type: 'string' };
|
|
34
|
+
if (t.flags & F.Number) return { type: 'number' };
|
|
35
|
+
if (t.flags & F.Boolean) return { type: 'boolean' };
|
|
36
|
+
if (t.flags & F.Null) return { type: 'null' };
|
|
37
|
+
return undefined;
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
const walk = (t: TS.Type, depth: number): Schema => {
|
|
41
|
+
if (depth > MAX_DEPTH || onPath.has(t)) return {};
|
|
42
|
+
if (t.flags & (F.Any | F.Unknown | F.TypeParameter | F.Never)) return {};
|
|
43
|
+
|
|
44
|
+
if (t.isUnion()) {
|
|
45
|
+
const arms = t.types.filter(m => !(m.flags & (F.Undefined | F.Void)));
|
|
46
|
+
if (arms.length === 0) return {};
|
|
47
|
+
if (arms.length === 1) return walk(arms[0]!, depth);
|
|
48
|
+
const scalars = arms.map(scalar);
|
|
49
|
+
// A structural arm makes the union a job for `anyOf`, which json-validation does not enforce.
|
|
50
|
+
if (scalars.some(s => s === undefined)) return {};
|
|
51
|
+
const ss = scalars as { type: string; value?: string | number | boolean }[];
|
|
52
|
+
const open = new Set(ss.filter(s => s.value === undefined).map(s => s.type));
|
|
53
|
+
// `boolean` arrives as `true | false`; both together are the open type, not an enum of two.
|
|
54
|
+
if (ss.filter(s => s.type === 'boolean' && s.value !== undefined).length === 2) open.add('boolean');
|
|
55
|
+
const literals = ss.filter(s => s.value !== undefined && !open.has(s.type));
|
|
56
|
+
const types = [...new Set([...open, ...literals.map(s => s.type)])];
|
|
57
|
+
const typed: Schema = types.length === 1 ? { type: types[0] } : { type: types };
|
|
58
|
+
// `'a' | string` widens: an enum of the literal arms would reject the open one.
|
|
59
|
+
return open.size === 0 ? { ...typed, enum: literals.map(s => s.value) } : typed;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const s = scalar(t);
|
|
63
|
+
if (s !== undefined) return s.value !== undefined ? { type: s.type, enum: [s.value] } : { type: s.type };
|
|
64
|
+
if (t.flags & (F.BigInt | F.BigIntLiteral | F.ESSymbol | F.UniqueESSymbol)) return {};
|
|
65
|
+
if (t.getCallSignatures().length > 0) return {};
|
|
66
|
+
|
|
67
|
+
// `toJSON()` decides what is on the wire: a Date is its string.
|
|
68
|
+
const toJSON = checker.getPropertyOfType(t, 'toJSON');
|
|
69
|
+
if (toJSON !== undefined) {
|
|
70
|
+
const sig = checker.getTypeOfSymbolAtLocation(toJSON, location).getCallSignatures()[0];
|
|
71
|
+
if (sig !== undefined) return walk(checker.getReturnTypeOfSignature(sig), depth + 1);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
onPath.add(t);
|
|
75
|
+
try {
|
|
76
|
+
if (checker.isArrayType(t)) {
|
|
77
|
+
const el = checker.getTypeArguments(t as TS.TypeReference)[0];
|
|
78
|
+
return { type: 'array', ...(el !== undefined ? { items: walk(el, depth + 1) } : {}) };
|
|
79
|
+
}
|
|
80
|
+
if (checker.isTupleType(t)) return { type: 'array' };
|
|
81
|
+
const name = t.getSymbol()?.getName();
|
|
82
|
+
if (name !== undefined && EMPTY_JSON.has(name)) return { type: 'object' };
|
|
83
|
+
if (!(t.flags & F.Object) && !t.isIntersection()) return {};
|
|
84
|
+
|
|
85
|
+
const properties: Record<string, Schema> = {};
|
|
86
|
+
const required: string[] = [];
|
|
87
|
+
for (const p of checker.getPropertiesOfType(t)) {
|
|
88
|
+
const pt = checker.getTypeOfSymbolAtLocation(p, p.valueDeclaration ?? location);
|
|
89
|
+
if (pt.getCallSignatures().length > 0 && !pt.isUnion()) continue; // a method: never on the wire
|
|
90
|
+
properties[p.getName()] = walk(pt, depth + 1);
|
|
91
|
+
const optional = (p.flags & ts.SymbolFlags.Optional) !== 0
|
|
92
|
+
|| (pt.isUnion() && pt.types.some(m => m.flags & F.Undefined));
|
|
93
|
+
if (!optional) required.push(p.getName());
|
|
94
|
+
}
|
|
95
|
+
const index = checker.getIndexTypeOfType(t, ts.IndexKind.String);
|
|
96
|
+
return {
|
|
97
|
+
type: 'object',
|
|
98
|
+
...(Object.keys(properties).length > 0 ? { properties } : {}),
|
|
99
|
+
...(required.length > 0 ? { required } : {}),
|
|
100
|
+
...(index !== undefined ? { additionalProperties: walk(index, depth + 1) } : {}),
|
|
101
|
+
};
|
|
102
|
+
} finally {
|
|
103
|
+
onPath.delete(t);
|
|
104
|
+
}
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
return walk(root, 0);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** The function a top-level declaration of `name` gives the file: a function declaration, or a `const`
|
|
111
|
+
* initialised with a function or arrow expression. `export` or not. */
|
|
112
|
+
function findFunction(ts: typeof TS, sf: TS.SourceFile, name: string): TS.SignatureDeclaration | undefined {
|
|
113
|
+
for (const st of sf.statements) {
|
|
114
|
+
if (ts.isFunctionDeclaration(st) && st.name?.text === name) return st;
|
|
115
|
+
if (ts.isVariableStatement(st)) {
|
|
116
|
+
for (const d of st.declarationList.declarations) {
|
|
117
|
+
if (ts.isIdentifier(d.name) && d.name.text === name && d.initializer !== undefined
|
|
118
|
+
&& (ts.isArrowFunction(d.initializer) || ts.isFunctionExpression(d.initializer))) return d.initializer;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
return undefined;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Each named function's parameters with their schemas; a name the file does not declare is absent. */
|
|
126
|
+
function parametersOf(ts: typeof TS, checker: TS.TypeChecker, sf: TS.SourceFile, names: readonly string[]): Record<string, Parameter[]> {
|
|
127
|
+
const out: Record<string, Parameter[]> = {};
|
|
128
|
+
for (const name of names) {
|
|
129
|
+
const fn = findFunction(ts, sf, name);
|
|
130
|
+
if (fn === undefined) continue;
|
|
131
|
+
out[name] = fn.parameters.map((p, i) => ({
|
|
132
|
+
name: ts.isIdentifier(p.name) ? p.name.text : `arg${i}`,
|
|
133
|
+
optional: p.questionToken !== undefined || p.initializer !== undefined,
|
|
134
|
+
schema: schemaOf(ts, checker, p, checker.getTypeAtLocation(p)),
|
|
135
|
+
}));
|
|
136
|
+
}
|
|
137
|
+
return out;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
module.exports = { parametersOf };
|