@vini-ds/agent 0.0.0-stage → 0.1.0-alpha.11
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/SETUP.md +263 -0
- package/SKILL.md +43 -0
- package/context/components.json +16694 -0
- package/context/current.json +904 -0
- package/context/examples.json +341 -0
- package/context/patterns.json +485 -0
- package/context/tokens.json +28758 -0
- package/mcp.mjs +340 -0
- package/package.json +25 -4
- package/supervisor.mjs +125 -0
- package/updates.mjs +361 -0
- package/version.mjs +34 -0
- package/README.md +0 -3
package/mcp.mjs
ADDED
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Public, read-only package documentation. The internal producer Gateway is not exposed.
|
|
3
|
+
import { realpath } from 'node:fs/promises';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { createHash } from 'node:crypto';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { boundedBytes, checkUpdates } from './updates.mjs';
|
|
8
|
+
|
|
9
|
+
const root = path.dirname(fileURLToPath(import.meta.url));
|
|
10
|
+
const load = async (name) => JSON.parse((await boundedBytes(path.join(root, name))).bytes.toString('utf8'));
|
|
11
|
+
const own = (record, key) => Object.hasOwn(record, key);
|
|
12
|
+
const maxBytes = 2 * 1024 * 1024;
|
|
13
|
+
// Bound each resource response conservatively for clients whose output limit is
|
|
14
|
+
// smaller than the worker's transport limit. Base64 slices exact UTF-8 bytes,
|
|
15
|
+
// including across multibyte characters; the manifest authenticates assembly.
|
|
16
|
+
const examplePartBytes = 1024;
|
|
17
|
+
const exampleFileMaxBytes = 128 * 1024;
|
|
18
|
+
// Resource content (including JSON quoting of its text) must fit this bound.
|
|
19
|
+
// Unusually large metadata fails closed instead of returning partial details.
|
|
20
|
+
const exampleResourceMaxBytes = 4000;
|
|
21
|
+
const sha256 = (bytes) => `sha256:${createHash('sha256').update(bytes).digest('hex')}`;
|
|
22
|
+
const protocols = ['2025-06-18', '2025-03-26', '2024-11-05', '2026-07-28'];
|
|
23
|
+
const annotations = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };
|
|
24
|
+
const schema = (properties, required = []) => ({ type: 'object', additionalProperties: false, properties, required });
|
|
25
|
+
const string = { type: 'string', minLength: 1 };
|
|
26
|
+
export const toolDefinitions = [
|
|
27
|
+
{ name: 'search_ds', description: 'Find public VINi components, patterns, or Foundation token names in this installed baseline.', inputSchema: schema({ query: string, kinds: { type: 'array', items: { enum: ['component', 'token', 'pattern'] } }, limit: { type: 'integer', minimum: 1, maximum: 50 } }, ['query']) },
|
|
28
|
+
{ name: 'get_pattern_contract', description: 'Read one public VINi pattern contract for the React DOM/web profile.', inputSchema: schema({ id: string, platform: string }, ['id']) },
|
|
29
|
+
{ name: 'get_component_contract', description: 'Read actual component exports, props, slots, constraints, known limitations and baseline TypeScript declarations.', inputSchema: schema({ id: string, platform: string }, ['id']) },
|
|
30
|
+
{ name: 'get_package_profile', description: 'Read the matching public React DOM package setup. Other profiles are not supported here.', inputSchema: schema({ id: string }, ['id']) },
|
|
31
|
+
{ name: 'get_platform_status', description: 'Read the scope of the public React DOM distribution; other renderers are explicitly unsupported.', inputSchema: schema({ id: string }, ['id']) },
|
|
32
|
+
{ name: 'get_token', description: 'Read a Foundation token and its available modes.', inputSchema: schema({ id: string }, ['id']) },
|
|
33
|
+
{ name: 'resolve_token', description: 'Resolve an existing token with explicitly selected Foundation modes; follows aliases and checked sums.', inputSchema: schema({ id: string, modeByCollection: { type: 'object', additionalProperties: { type: 'string' } } }, ['id', 'modeByCollection']) },
|
|
34
|
+
{ name: 'check_updates', description: 'Read installed VINi npm package versions and verify available latest release metadata from the public npm registry. Optionally compare a caller-selected exact target separately from latest. Does not install or execute packages. A registry failure is not evidence that no update exists.', inputSchema: schema({ target: schema({ version: string, ui: string, tokens: string, agent: string }, ['version', 'ui', 'tokens', 'agent']) }) },
|
|
35
|
+
].map((tool) => ({ ...tool, annotations: tool.name === 'check_updates' ? { ...annotations, openWorldHint: true } : annotations }));
|
|
36
|
+
|
|
37
|
+
function requiredString(value, label) {
|
|
38
|
+
if (typeof value !== 'string' || !value.trim()) throw new Error(`${label} is required`);
|
|
39
|
+
return value;
|
|
40
|
+
}
|
|
41
|
+
function object(value, label) {
|
|
42
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error(`${label} must be an object`);
|
|
43
|
+
return value;
|
|
44
|
+
}
|
|
45
|
+
function validateArguments(tool, args) {
|
|
46
|
+
object(args, 'arguments');
|
|
47
|
+
for (const key of Object.keys(args)) if (!own(tool.inputSchema.properties, key)) throw new Error(`Unknown argument ${key}`);
|
|
48
|
+
for (const key of tool.inputSchema.required) if (!own(args, key)) throw new Error(`Missing argument ${key}`);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// Optional only for an older context that does not declare the corresponding count.
|
|
52
|
+
// An announced, malformed or unreadable catalog always fails closed.
|
|
53
|
+
async function loadOptionalCatalog(metadata, countKey, file, kind) {
|
|
54
|
+
const announced = own(metadata, countKey);
|
|
55
|
+
if (announced && (!Number.isSafeInteger(metadata[countKey]) || metadata[countKey] < 0)) throw new Error(`Invalid ${countKey}`);
|
|
56
|
+
let entries;
|
|
57
|
+
try { entries = await load(file); }
|
|
58
|
+
catch (error) { if (!announced && error.code === 'ENOENT') return []; throw error; }
|
|
59
|
+
if (!Array.isArray(entries) || (announced && entries.length !== metadata[countKey])) throw new Error(`Invalid ${kind} catalog or count`);
|
|
60
|
+
const ids = new Set();
|
|
61
|
+
const validText = (value) => typeof value === 'string' && value.trim().length > 0;
|
|
62
|
+
const textArray = (value) => Array.isArray(value) && value.every(validText);
|
|
63
|
+
for (const entry of entries) {
|
|
64
|
+
if (!entry || typeof entry !== 'object' || Array.isArray(entry) || !validText(entry.id) || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(entry.id) || ids.has(entry.id)) throw new Error(`Invalid or duplicate ${kind} id`);
|
|
65
|
+
ids.add(entry.id);
|
|
66
|
+
if (kind === 'pattern' && !validText(entry.displayName)) throw new Error('Invalid pattern displayName');
|
|
67
|
+
if (kind === 'example') {
|
|
68
|
+
if (!validText(entry.title) || !validText(entry.description) || !textArray(entry.componentIds) || !textArray(entry.patternIds) || !textArray(entry.limitations) || !Array.isArray(entry.files) || !entry.files.length) throw new Error('Invalid example');
|
|
69
|
+
const names = new Set();
|
|
70
|
+
for (const file of entry.files) {
|
|
71
|
+
if (!file || typeof file !== 'object' || Array.isArray(file) || !validText(file.name) || !/^[A-Za-z0-9][A-Za-z0-9.-]*\.(?:jsx|tsx|css)$/u.test(file.name) || names.has(file.name) || !validText(file.language) || !validText(file.source)) throw new Error('Invalid example');
|
|
72
|
+
const bytes = Buffer.from(file.source, 'utf8');
|
|
73
|
+
if (bytes.length > exampleFileMaxBytes || bytes.toString('utf8') !== file.source) throw new Error('Invalid example file encoding or size');
|
|
74
|
+
names.add(file.name);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return entries;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// The resolver follows the same alias/mode/sum semantics as the internal Gateway.
|
|
82
|
+
export function resolveToken(tokens, id, modes) {
|
|
83
|
+
object(modes, 'modeByCollection');
|
|
84
|
+
for (const [collection, mode] of Object.entries(modes)) {
|
|
85
|
+
if (!own(tokens.collections, collection) || !tokens.collections[collection].modes.includes(mode)) throw new Error(`Unknown token mode ${collection}/${mode}`);
|
|
86
|
+
}
|
|
87
|
+
for (const [collection, contract] of Object.entries(tokens.collections)) {
|
|
88
|
+
if (contract.requiresExplicitMode && !own(modes, collection)) throw new Error(`Collection ${collection} requires an explicit mode`);
|
|
89
|
+
}
|
|
90
|
+
const trace = [], active = new Set();
|
|
91
|
+
function visit(name) {
|
|
92
|
+
if (active.has(name)) throw new Error(`Token alias cycle: ${name}`);
|
|
93
|
+
if (!own(tokens.tokens, name)) throw new Error(`Unknown token ${name}`);
|
|
94
|
+
const token = tokens.tokens[name], collection = tokens.collections[token.collection];
|
|
95
|
+
const mode = collection.requiresExplicitMode ? modes[token.collection] : collection.modes[0];
|
|
96
|
+
const declaration = token.values[mode];
|
|
97
|
+
if (!declaration) throw new Error(`Missing token mode ${name}/${mode}`);
|
|
98
|
+
trace.push({ id: name, collection: token.collection, mode, type: declaration.type });
|
|
99
|
+
if (declaration.type === 'alias') {
|
|
100
|
+
active.add(name); const value = visit(declaration.to); active.delete(name); return value;
|
|
101
|
+
}
|
|
102
|
+
if (declaration.type === 'derived') {
|
|
103
|
+
if (declaration.operation !== 'sum' || !Array.isArray(declaration.from)) throw new Error('Unsupported token derivation');
|
|
104
|
+
active.add(name); const values = declaration.from.map(visit); active.delete(name);
|
|
105
|
+
if (!values.every((value) => typeof value === 'number')) throw new Error('Token sum requires numeric inputs');
|
|
106
|
+
const result = values.reduce((sum, value) => sum + value, 0);
|
|
107
|
+
if (!Object.is(result, declaration.value)) throw new Error('Token sum differs from its recorded value');
|
|
108
|
+
return result;
|
|
109
|
+
}
|
|
110
|
+
if (!['float', 'color', 'string', 'boolean'].includes(declaration.type)) throw new Error('Unsupported token declaration');
|
|
111
|
+
return structuredClone(declaration.value);
|
|
112
|
+
}
|
|
113
|
+
return { value: visit(id), modeByCollection: modes, trace };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export async function createPublicService() {
|
|
117
|
+
const [metadata, components, tokens, setupBytes] = await Promise.all([load('context/current.json'), load('context/components.json'), load('context/tokens.json'), boundedBytes(path.join(root, 'SETUP.md'))]);
|
|
118
|
+
const [patterns, examples] = await Promise.all([loadOptionalCatalog(metadata, 'patternCount', 'context/patterns.json', 'pattern'), loadOptionalCatalog(metadata, 'exampleCount', 'context/examples.json', 'example')]);
|
|
119
|
+
const setup = setupBytes.bytes.toString('utf8');
|
|
120
|
+
const patternsById = new Map(patterns.map((pattern) => [pattern.id, pattern]));
|
|
121
|
+
const examplesById = new Map(examples.map((example) => [example.id, example]));
|
|
122
|
+
// Compute hashes from the immutable in-memory snapshot, not mutable paths.
|
|
123
|
+
const exampleFilesById = new Map(examples.map((example) => [example.id, new Map(example.files.map((file) => {
|
|
124
|
+
const bytes = Buffer.from(file.source, 'utf8');
|
|
125
|
+
return [file.name, { name: file.name, language: file.language, bytes, sha256: sha256(bytes), partCount: Math.ceil(bytes.length / examplePartBytes) }];
|
|
126
|
+
}))]));
|
|
127
|
+
const byId = new Map(components.map((component) => [component.id, component]));
|
|
128
|
+
const current = { ...metadata, installationVerification: 'not-performed-by-context-server', nativeClientVerification: 'read-this-resource-in-your-client', scope: 'public-documentation-projection' };
|
|
129
|
+
const imports = { ui: metadata.packages?.ui?.importName ?? '@vini/ui', tokens: metadata.packages?.tokens?.importName ?? '@vini/tokens' };
|
|
130
|
+
const profile = { id: 'react-dom-reference', packageVersion: metadata.version, packages: metadata.packages, imports, checkedRuntime: { react: '18.2.0', 'react-dom': '18.2.0' }, stylesheets: [`${imports.tokens}/fonts.css`, `${imports.tokens}/themes.css`, `${imports.tokens}/typography.css`, `${imports.ui}/styles.css`], rootProvider: { export: 'ThemeBrandProvider', props: { theme: 'light', brand: 'vini', colorway: 'blue', typographyScope: 'desktop' } }, maturity: 'alpha', productVerification: 'required-in-consumer', setup: 'vini://guidelines/setup' };
|
|
131
|
+
const resources = [
|
|
132
|
+
{ uri: 'vini://system/current', name: 'VINi public baseline', mimeType: 'application/json' },
|
|
133
|
+
{ uri: 'vini://guidelines/setup', name: 'VINi public setup', mimeType: 'text/markdown' },
|
|
134
|
+
{ uri: 'vini://agent-kit/quickstart', name: 'VINi public quickstart', mimeType: 'text/markdown' },
|
|
135
|
+
{ uri: 'vini://components', name: 'VINi component inventory', mimeType: 'application/json' },
|
|
136
|
+
{ uri: 'vini://packages/react-dom-reference', name: 'VINi React DOM profile', mimeType: 'application/json' },
|
|
137
|
+
{ uri: 'vini://patterns', name: 'VINi public patterns', mimeType: 'application/json' },
|
|
138
|
+
{ uri: 'vini://examples', name: 'VINi public examples', mimeType: 'application/json' },
|
|
139
|
+
];
|
|
140
|
+
const envelope = (data) => ({ packageVersion: metadata.version, baseline: metadata.baseline, ...data });
|
|
141
|
+
function contract(id, platform) {
|
|
142
|
+
requiredString(id, 'id');
|
|
143
|
+
if (platform !== undefined && platform !== 'web') throw new Error('Only the public React DOM/web profile is available');
|
|
144
|
+
if (!byId.has(id)) throw new Error(`Unknown component ${id}`);
|
|
145
|
+
return byId.get(id);
|
|
146
|
+
}
|
|
147
|
+
function patternContract(id, platform) {
|
|
148
|
+
requiredString(id, 'id');
|
|
149
|
+
if (platform !== undefined && platform !== 'web') throw new Error('Only the public React DOM/web profile is available');
|
|
150
|
+
if (!patternsById.has(id)) throw new Error(`Unknown pattern ${id}`);
|
|
151
|
+
return patternsById.get(id);
|
|
152
|
+
}
|
|
153
|
+
function exampleById(id) {
|
|
154
|
+
requiredString(id, 'id');
|
|
155
|
+
if (!examplesById.has(id)) throw new Error(`Unknown example ${id}`);
|
|
156
|
+
return examplesById.get(id);
|
|
157
|
+
}
|
|
158
|
+
function exampleManifest(id) {
|
|
159
|
+
const { title, componentIds, patternIds } = exampleById(id);
|
|
160
|
+
return envelope({ example: { id, title, componentIds, patternIds, files: [...exampleFilesById.get(id).values()].map(({ name, language, bytes, sha256: hash, partCount }) => ({
|
|
161
|
+
name, language, byteLength: bytes.length, sha256: hash, encoding: 'base64', partBytes: examplePartBytes, partCount,
|
|
162
|
+
partUriTemplate: `vini://examples/${id}/files/${name}/parts/{index}`,
|
|
163
|
+
})) } });
|
|
164
|
+
}
|
|
165
|
+
function exampleDetails(id) {
|
|
166
|
+
const example = exampleById(id);
|
|
167
|
+
const fields = ['id', 'title', 'description', 'componentIds', 'patternIds', 'limitations', 'sourceCorrespondence'];
|
|
168
|
+
return envelope({ example: Object.fromEntries(fields.filter((field) => own(example, field)).map((field) => [field, example[field]])) });
|
|
169
|
+
}
|
|
170
|
+
function exampleFilePart(id, name, indexText) {
|
|
171
|
+
exampleById(id);
|
|
172
|
+
const file = exampleFilesById.get(id).get(name);
|
|
173
|
+
if (!file) throw new Error(`Unknown example file ${name}`);
|
|
174
|
+
if (!/^(?:0|[1-9][0-9]*)$/u.test(indexText)) throw new Error('Invalid example part index');
|
|
175
|
+
const index = Number(indexText);
|
|
176
|
+
if (!Number.isSafeInteger(index) || index >= file.partCount) throw new Error('Example part index out of range');
|
|
177
|
+
const bytes = file.bytes.subarray(index * examplePartBytes, (index + 1) * examplePartBytes);
|
|
178
|
+
return envelope({ exampleId: id, file: { name: file.name, language: file.language, encoding: 'base64', byteLength: file.bytes.length, sha256: file.sha256,
|
|
179
|
+
partBytes: examplePartBytes, partCount: file.partCount, index, partByteLength: bytes.length, partSha256: sha256(bytes), content: bytes.toString('base64') } });
|
|
180
|
+
}
|
|
181
|
+
async function call(name, args = {}, signal) {
|
|
182
|
+
const definition = toolDefinitions.find((tool) => tool.name === name);
|
|
183
|
+
if (!definition) throw new Error(`Unknown tool ${name}`);
|
|
184
|
+
validateArguments(definition, args);
|
|
185
|
+
if (name === 'check_updates') return checkUpdates(metadata, { target: args.target, signal });
|
|
186
|
+
if (name === 'get_component_contract') return envelope({ component: contract(args.id, args.platform) });
|
|
187
|
+
if (name === 'get_pattern_contract') return envelope({ pattern: patternContract(args.id, args.platform) });
|
|
188
|
+
if (name === 'get_package_profile') {
|
|
189
|
+
if (args.id !== 'react-dom-reference') throw new Error('Only react-dom-reference is available in this public package');
|
|
190
|
+
return envelope({ profile });
|
|
191
|
+
}
|
|
192
|
+
if (name === 'get_platform_status') return envelope({ platform: { id: requiredString(args.id, 'id'), status: args.id === 'web' ? 'react-dom-reference' : 'unsupported-by-this-distribution', nativeAdapterIncluded: false, productVerification: 'not-claimed' } });
|
|
193
|
+
if (name === 'get_token' || name === 'resolve_token') {
|
|
194
|
+
const id = requiredString(args.id, 'id');
|
|
195
|
+
if (!own(tokens.tokens, id)) throw new Error(`Unknown token ${id}`);
|
|
196
|
+
const token = tokens.tokens[id];
|
|
197
|
+
if (name === 'get_token') return envelope({ token: { id, ...token }, collections: tokens.collections });
|
|
198
|
+
return envelope({ token: { id, collection: token.collection, resolvedType: token.resolvedType }, ...resolveToken(tokens, id, args.modeByCollection), units: token.resolvedType === 'FLOAT' ? 'renderer-defined' : 'not-applicable' });
|
|
199
|
+
}
|
|
200
|
+
const query = requiredString(args.query, 'query').toLocaleLowerCase();
|
|
201
|
+
const kinds = args.kinds ?? ['component', 'token'];
|
|
202
|
+
const limit = args.limit ?? 20;
|
|
203
|
+
if (!Array.isArray(kinds) || !kinds.length || !kinds.every((kind) => ['component', 'token', 'pattern'].includes(kind))) throw new Error('Invalid kinds');
|
|
204
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > 50) throw new Error('Limit must be 1..50');
|
|
205
|
+
const matches = [];
|
|
206
|
+
if (kinds.includes('component')) for (const component of components) if (JSON.stringify(component).toLocaleLowerCase().includes(query)) matches.push({ kind: 'component', id: component.id, name: component.displayName, exports: component.exports });
|
|
207
|
+
if (kinds.includes('token')) for (const id of Object.keys(tokens.tokens)) if (id.toLocaleLowerCase().includes(query)) matches.push({ kind: 'token', id });
|
|
208
|
+
if (kinds.includes('pattern')) for (const pattern of patterns) if (JSON.stringify(pattern).toLocaleLowerCase().includes(query)) matches.push({ kind: 'pattern', id: pattern.id, name: pattern.displayName });
|
|
209
|
+
return envelope({ results: matches.slice(0, limit), total: matches.length });
|
|
210
|
+
}
|
|
211
|
+
function readResource(uri) {
|
|
212
|
+
let data, boundedExampleResource = false;
|
|
213
|
+
if (uri === 'vini://guidelines/setup' || uri === 'vini://agent-kit/quickstart') return { uri, mimeType: 'text/markdown', text: setup };
|
|
214
|
+
if (uri === 'vini://system/current') data = current;
|
|
215
|
+
else if (uri === 'vini://components') data = components.map(({ id, displayName, exports }) => ({ id, displayName, exports }));
|
|
216
|
+
else if (uri === 'vini://packages/react-dom-reference') data = profile;
|
|
217
|
+
else if (uri === 'vini://patterns') data = envelope({ patterns: patterns.map(({ id, displayName }) => ({ id, displayName })) });
|
|
218
|
+
else if (uri === 'vini://examples') data = envelope({ examples: examples.map(({ id, title, description, componentIds, patternIds, limitations }) => ({ id, title, description, componentIds, patternIds, limitations })) });
|
|
219
|
+
else if (/^vini:\/\/patterns\/[a-z0-9-]+$/u.test(uri)) data = envelope({ pattern: patternContract(uri.slice('vini://patterns/'.length)) });
|
|
220
|
+
else if (/^vini:\/\/examples\/[a-z0-9-]+\/manifest$/u.test(uri)) { data = exampleManifest(uri.slice('vini://examples/'.length, -'/manifest'.length)); boundedExampleResource = true; }
|
|
221
|
+
else if (/^vini:\/\/examples\/[a-z0-9-]+\/details$/u.test(uri)) { data = exampleDetails(uri.slice('vini://examples/'.length, -'/details'.length)); boundedExampleResource = true; }
|
|
222
|
+
else if (/^vini:\/\/examples\/[a-z0-9-]+\/files\/[A-Za-z0-9][A-Za-z0-9.-]*\.(?:jsx|tsx|css)\/parts\/(?:0|[1-9][0-9]*)$/u.test(uri)) {
|
|
223
|
+
const [, id, name, index] = /^vini:\/\/examples\/([a-z0-9-]+)\/files\/([A-Za-z0-9][A-Za-z0-9.-]*\.(?:jsx|tsx|css))\/parts\/(0|[1-9][0-9]*)$/u.exec(uri);
|
|
224
|
+
data = exampleFilePart(id, name, index);
|
|
225
|
+
boundedExampleResource = true;
|
|
226
|
+
}
|
|
227
|
+
else if (/^vini:\/\/examples\/[a-z0-9-]+$/u.test(uri)) data = envelope({ example: exampleById(uri.slice('vini://examples/'.length)) });
|
|
228
|
+
else if (/^vini:\/\/components\/[a-z0-9-]+$/u.test(uri)) data = contract(uri.slice('vini://components/'.length));
|
|
229
|
+
else throw new Error(`Unknown resource ${uri}`);
|
|
230
|
+
const resource = { uri, mimeType: 'application/json', text: JSON.stringify(data) };
|
|
231
|
+
if (boundedExampleResource && Buffer.byteLength(JSON.stringify({ contents: [resource] }), 'utf8') > exampleResourceMaxBytes) throw new Error('Example resource exceeds bounded response size');
|
|
232
|
+
return resource;
|
|
233
|
+
}
|
|
234
|
+
const resourceTemplates = [
|
|
235
|
+
{ uriTemplate: 'vini://components/{id}', name: 'VINi component', mimeType: 'application/json' },
|
|
236
|
+
{ uriTemplate: 'vini://patterns/{id}', name: 'VINi public pattern', mimeType: 'application/json' },
|
|
237
|
+
{ uriTemplate: 'vini://examples/{id}', name: 'VINi public example', mimeType: 'application/json' },
|
|
238
|
+
{ uriTemplate: 'vini://examples/{id}/manifest', name: 'VINi example file manifest', mimeType: 'application/json' },
|
|
239
|
+
{ uriTemplate: 'vini://examples/{id}/details', name: 'VINi example details and limitations', mimeType: 'application/json' },
|
|
240
|
+
{ uriTemplate: 'vini://examples/{id}/files/{filename}/parts/{index}', name: 'VINi example file part (base64 UTF-8 bytes)', mimeType: 'application/json' },
|
|
241
|
+
];
|
|
242
|
+
return { current, call, readResource, resources, resourceTemplates };
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// One bounded request queue per stdio connection. Requests are independent:
|
|
246
|
+
// a slow registry read must not hold ping or component lookup behind it.
|
|
247
|
+
export function servePublicMcp(service, { input = process.stdin, output = process.stdout, requestTimeoutMs = 15000, maxInFlight = 16, maxOutputBytes = 8 * 1024 * 1024 } = {}) {
|
|
248
|
+
function result(id, value) { return { jsonrpc: '2.0', id, result: value }; }
|
|
249
|
+
function error(id, code, message) { return { jsonrpc: '2.0', id, error: { code, message } }; }
|
|
250
|
+
let closed = false, buffer = '', running = 0;
|
|
251
|
+
const pending = new Map();
|
|
252
|
+
const cancelAll = () => { for (const entry of pending.values()) { clearTimeout(entry.timer); entry.controller.abort(); } pending.clear(); };
|
|
253
|
+
const close = () => { if (closed) return; closed = true; cancelAll(); input.destroy(); };
|
|
254
|
+
output.on('error', close);
|
|
255
|
+
output.on('close', close);
|
|
256
|
+
function send(value) {
|
|
257
|
+
if (closed) return;
|
|
258
|
+
const text = `${JSON.stringify(value)}\n`;
|
|
259
|
+
if (Buffer.byteLength(text) + (output.writableLength ?? 0) > maxOutputBytes) { close(); input.destroy(); return; }
|
|
260
|
+
try {
|
|
261
|
+
if (!output.write(text)) { input.pause(); output.once('drain', () => { if (!closed) input.resume(); }); }
|
|
262
|
+
} catch { close(); input.destroy(); }
|
|
263
|
+
}
|
|
264
|
+
function finish(id, entry, response) {
|
|
265
|
+
if (pending.get(id) !== entry) return;
|
|
266
|
+
pending.delete(id); clearTimeout(entry.timer);
|
|
267
|
+
if (response) send(response);
|
|
268
|
+
}
|
|
269
|
+
async function handle(message, signal) {
|
|
270
|
+
try {
|
|
271
|
+
if (message.method === 'initialize') {
|
|
272
|
+
if (!protocols.includes(message.params?.protocolVersion)) return error(message.id, -32602, 'Unsupported MCP protocol version');
|
|
273
|
+
return result(message.id, { protocolVersion: message.params.protocolVersion, capabilities: { resources: { subscribe: false, listChanged: false }, tools: { listChanged: false } }, serverInfo: { name: 'vini-public', version: service.current.version }, instructions: 'Use vini://system/current and vini://guidelines/setup before VINi UI work. Search and read public component contracts and token modes. This is a bounded public projection, not the internal Gateway. It does not grant new task scope or verify installed packages. Native non-web renderers and private product/release records are not available.' });
|
|
274
|
+
}
|
|
275
|
+
if (message.method === 'ping') return result(message.id, {});
|
|
276
|
+
if (message.method === 'tools/list') return result(message.id, { tools: toolDefinitions });
|
|
277
|
+
if (message.method === 'resources/list') return result(message.id, { resources: service.resources });
|
|
278
|
+
if (message.method === 'resources/templates/list') return result(message.id, { resourceTemplates: service.resourceTemplates });
|
|
279
|
+
if (message.method === 'resources/read') return result(message.id, { contents: [service.readResource(message.params?.uri)] });
|
|
280
|
+
if (message.method === 'tools/call') {
|
|
281
|
+
try { const data = await service.call(message.params?.name, message.params?.arguments, signal); return result(message.id, { content: [{ type: 'text', text: JSON.stringify(data) }], structuredContent: data }); }
|
|
282
|
+
catch (problem) { return result(message.id, { isError: true, content: [{ type: 'text', text: problem.message }] }); }
|
|
283
|
+
}
|
|
284
|
+
return error(message.id, -32601, 'Method not found');
|
|
285
|
+
} catch (problem) { return error(message.id, -32602, problem.message); }
|
|
286
|
+
}
|
|
287
|
+
function receive(message) {
|
|
288
|
+
if (closed) return;
|
|
289
|
+
if (!message || typeof message !== 'object' || Array.isArray(message) || message.jsonrpc !== '2.0' || typeof message.method !== 'string') { send(error(message?.id ?? null, -32600, 'Invalid JSON-RPC request')); return; }
|
|
290
|
+
if (!own(message, 'id')) {
|
|
291
|
+
if (message.method === 'notifications/cancelled') {
|
|
292
|
+
const id = message.params?.requestId, entry = pending.get(id);
|
|
293
|
+
if (entry) { entry.controller.abort(); finish(id, entry, error(id, -32800, 'Request cancelled; outcome may be unknown')); }
|
|
294
|
+
}
|
|
295
|
+
return;
|
|
296
|
+
}
|
|
297
|
+
const id = message.id;
|
|
298
|
+
if (!(typeof id === 'string' || (typeof id === 'number' && Number.isSafeInteger(id)))) { send(error(null, -32600, 'Invalid request id')); return; }
|
|
299
|
+
const prior = pending.get(id);
|
|
300
|
+
if (prior) { prior.controller.abort(); finish(id, prior, error(id, -32600, 'Duplicate in-flight request id')); return; }
|
|
301
|
+
// A cancelled operation retains its slot until its actual work settles;
|
|
302
|
+
// cancellation cannot be used to accumulate unbounded abandoned work.
|
|
303
|
+
if (running >= maxInFlight) { send(error(id, -32000, 'Too many concurrent requests')); return; }
|
|
304
|
+
const entry = { controller: new AbortController() };
|
|
305
|
+
entry.timer = setTimeout(() => { entry.controller.abort(); finish(id, entry, error(id, -32000, 'Request timed out; outcome may be unknown')); }, requestTimeoutMs);
|
|
306
|
+
pending.set(id, entry); running += 1;
|
|
307
|
+
Promise.resolve().then(() => handle(message, entry.controller.signal)).then(response => finish(id, entry, response), problem => finish(id, entry, error(id, -32603, problem.message))).finally(() => { running -= 1; });
|
|
308
|
+
}
|
|
309
|
+
input.setEncoding('utf8');
|
|
310
|
+
input.on('data', chunk => {
|
|
311
|
+
buffer += chunk;
|
|
312
|
+
let index;
|
|
313
|
+
while ((index = buffer.indexOf('\n')) !== -1) {
|
|
314
|
+
const rawLine = buffer.slice(0, index); buffer = buffer.slice(index + 1);
|
|
315
|
+
if (Buffer.byteLength(rawLine) > maxBytes) { send(error(null, -32700, 'Message too large')); close(); return; }
|
|
316
|
+
const line = rawLine.trim();
|
|
317
|
+
if (!line) continue;
|
|
318
|
+
let message;
|
|
319
|
+
try { message = JSON.parse(line); } catch { send(error(null, -32700, 'Parse error')); continue; }
|
|
320
|
+
receive(message); if (closed) return;
|
|
321
|
+
}
|
|
322
|
+
if (Buffer.byteLength(buffer) > maxBytes) { send(error(null, -32700, 'Message too large')); close(); input.destroy(); }
|
|
323
|
+
});
|
|
324
|
+
input.on('end', () => { if (buffer.trim()) send(error(null, -32700, 'Incomplete message')); close(); });
|
|
325
|
+
input.on('close', close);
|
|
326
|
+
input.on('error', close);
|
|
327
|
+
return { close };
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
async function main() {
|
|
331
|
+
const service = await createPublicService();
|
|
332
|
+
if (process.argv.length === 3 && process.argv[2] === '--check') {
|
|
333
|
+
const { name, version, packages, baseline, componentCount, tokenCount, scope } = service.current;
|
|
334
|
+
console.log(JSON.stringify({ ok: true, name, version, packages, baseline, componentCount, tokenCount, scope })); return;
|
|
335
|
+
}
|
|
336
|
+
if (process.argv.length > 2) throw new Error('Usage: node mcp.mjs [--check]');
|
|
337
|
+
servePublicMcp(service);
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
if (process.argv[1] && await realpath(process.argv[1]).catch(() => null) === fileURLToPath(import.meta.url)) main().catch((problem) => { console.error(`VINi public MCP: ${problem.message}`); process.exitCode = 1; });
|
package/package.json
CHANGED
|
@@ -1,6 +1,27 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vini-ds/agent",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0-alpha.11",
|
|
4
|
+
"description": "Public VINi React DOM component and token context with a local read-only MCP server",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"engines": {
|
|
7
|
+
"node": ">=20"
|
|
8
|
+
},
|
|
9
|
+
"publishConfig": {
|
|
10
|
+
"access": "public"
|
|
11
|
+
},
|
|
12
|
+
"exports": {
|
|
13
|
+
"./mcp": "./mcp.mjs",
|
|
14
|
+
"./supervisor": "./supervisor.mjs",
|
|
15
|
+
"./skill": "./SKILL.md",
|
|
16
|
+
"./setup": "./SETUP.md"
|
|
17
|
+
},
|
|
18
|
+
"files": [
|
|
19
|
+
"mcp.mjs",
|
|
20
|
+
"supervisor.mjs",
|
|
21
|
+
"updates.mjs",
|
|
22
|
+
"version.mjs",
|
|
23
|
+
"SKILL.md",
|
|
24
|
+
"SETUP.md",
|
|
25
|
+
"context"
|
|
26
|
+
]
|
|
27
|
+
}
|
package/supervisor.mjs
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Per-connection public MCP supervisor. It never downloads or installs packages.
|
|
3
|
+
import { spawn, execFile } from 'node:child_process';
|
|
4
|
+
import { promisify } from 'node:util';
|
|
5
|
+
import { promises as fs } from 'node:fs';
|
|
6
|
+
import { constants as fsConstants } from 'node:fs';
|
|
7
|
+
import { randomUUID } from 'node:crypto';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { fileURLToPath } from 'node:url';
|
|
10
|
+
import { compareVersions, isExactVersion } from './version.mjs';
|
|
11
|
+
|
|
12
|
+
const run = promisify(execFile), keys = ['ui', 'tokens', 'agent'];
|
|
13
|
+
const maxBytes = 2 * 1024 * 1024, timeout = 15000;
|
|
14
|
+
const targetSchema = {type:'object',additionalProperties:false,properties:Object.fromEntries(['version',...keys].map(k=>[k,{type:'string',minLength:1,maxLength:214}])),required:['version',...keys]};
|
|
15
|
+
const reloadTool = {name:'refresh_connection',description:'Switch this connection to an explicitly selected, already installed compatible VINi release. Never installs packages.',inputSchema:{type:'object',additionalProperties:false,properties:{target:targetSchema},required:['target']},annotations:{readOnlyHint:false,destructiveHint:false,idempotentHint:false,openWorldHint:false}};
|
|
16
|
+
const runtimeResource = {uri:'vini://runtime/connection',name:'VINi public connection identity',mimeType:'application/json'};
|
|
17
|
+
const rpcError=(id,message)=>({jsonrpc:'2.0',id,error:{code:-32000,message}});
|
|
18
|
+
const ok=(id,result)=>({jsonrpc:'2.0',id,result});
|
|
19
|
+
const same=(a,b)=>JSON.stringify(a)===JSON.stringify(b);
|
|
20
|
+
const failure=(message)=>{throw new Error(message);};
|
|
21
|
+
async function noLock(root) { try { await fs.lstat(path.join(root,'.vini-npm-install.lock')); failure('Installation is in progress or recovery needs review'); } catch(e) { if(e.code!=='ENOENT') throw e; } }
|
|
22
|
+
async function boundedBytes(file){if(typeof fsConstants.O_NOFOLLOW!=='number'||typeof fsConstants.O_NONBLOCK!=='number')failure('Safe metadata reads are unsupported on this platform');const h=await fs.open(file,fsConstants.O_RDONLY|fsConstants.O_NOFOLLOW|fsConstants.O_NONBLOCK);try{const before=await h.stat({bigint:true});if(!before.isFile()||before.size>BigInt(maxBytes))failure('Metadata is unavailable or too large');const buffer=Buffer.alloc(Number(before.size)+1);let used=0;while(used<buffer.length){const {bytesRead}=await h.read(buffer,used,buffer.length-used,used);if(!bytesRead)break;used+=bytesRead;}const after=await h.stat({bigint:true}),entry=await fs.lstat(file,{bigint:true});if(!entry.isFile()||entry.isSymbolicLink()||before.dev!==after.dev||before.ino!==after.ino||after.dev!==entry.dev||after.ino!==entry.ino||before.size!==after.size||before.mtimeNs!==after.mtimeNs||before.ctimeNs!==after.ctimeNs||after.mtimeNs!==entry.mtimeNs||after.ctimeNs!==entry.ctimeNs||used!==Number(before.size))failure('Metadata changed during inspection');return buffer.subarray(0,used);}finally{await h.close();}}
|
|
23
|
+
async function boundedJson(file) {return JSON.parse((await boundedBytes(file)).toString('utf8'));}
|
|
24
|
+
async function acquireStartupLock(root){const dir=path.join(root,'.vini-npm-install.lock'),owner=path.join(dir,'owner.json');try{await fs.mkdir(dir,{mode:0o700});}catch(e){if(e.code==='EEXIST')failure('Installation is in progress or recovery needs review');throw e;}const identity=await fs.lstat(dir),contents=Buffer.from(JSON.stringify({version:1,nonce:randomUUID(),pid:process.pid,startedAt:new Date().toISOString(),command:'supervisor-start',recovery:null},null,2)+'\n');try{await fs.writeFile(owner,contents,{flag:'wx',mode:0o600});}catch(e){const now=await fs.lstat(dir).catch(()=>null);if(now?.dev===identity.dev&&now.ino===identity.ino&&(await fs.readdir(dir)).length===0)await fs.rmdir(dir);throw e;}let releasePromise;return {release(){return releasePromise??=(async()=>{const now=await fs.lstat(dir);if(!now.isDirectory()||now.isSymbolicLink()||now.dev!==identity.dev||now.ino!==identity.ino||!same(await fs.readdir(dir),['owner.json'])||!(await boundedBytes(owner)).equals(contents))failure('Startup lock changed; inspect .vini-npm-install.lock');await fs.unlink(owner);await fs.rmdir(dir);})();}};}
|
|
25
|
+
async function inspect(root, appRel, target, requireGeneration, lockOwned = false, signal) {
|
|
26
|
+
signal?.throwIfAborted();
|
|
27
|
+
if(!lockOwned) await noLock(root);
|
|
28
|
+
const kit=await fs.lstat(path.join(root,'.vini-ds'));if(!kit.isDirectory()||kit.isSymbolicLink())failure('Unsafe installation directory');const receiptPath=path.join(root,'.vini-ds/npm-install.json');
|
|
29
|
+
const bytes=await boundedBytes(receiptPath);
|
|
30
|
+
const receipt=JSON.parse(bytes), d=receipt.distribution;
|
|
31
|
+
if(receipt.installer!=='vini-npm'||receipt.appRoot!==appRel||!d||!keys.every(k=>typeof d[k]==='string')||!isExactVersion(d.version)) failure('Invalid installation receipt');
|
|
32
|
+
if(requireGeneration && (typeof receipt.generation!=='string'||receipt.generation.length!==36||!/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(receipt.generation))) failure('Receipt has no verified installation generation; reconnect the project MCP');
|
|
33
|
+
if(target && !['version',...keys].every(k=>d[k]===target[k])) failure('Selected target does not match installed receipt');
|
|
34
|
+
const app=await fs.realpath(path.resolve(root,appRel));
|
|
35
|
+
if(app!==root&&!app.startsWith(root+path.sep)) failure('Application is outside project');
|
|
36
|
+
const direct=keys.every(k=>d[k]===`@vini-ds/${k}`),legacy=keys.every(k=>d[k]===`@timelex/vini-${k}`),oldDirect=keys.every(k=>d[k]===`@vini/${k}`);
|
|
37
|
+
if(!direct&&!legacy&&!oldDirect) failure('Unsupported or mixed package family');
|
|
38
|
+
const scope=direct?'@vini-ds':'@vini';
|
|
39
|
+
const modulesPath=path.join(app,'node_modules'),moduleStat=await fs.lstat(modulesPath);if(!moduleStat.isDirectory()||moduleStat.isSymbolicLink())failure('Unsafe node_modules directory');const modules=await fs.realpath(modulesPath);
|
|
40
|
+
const code="const {createRequire}=require('node:module');const r=createRequire(process.argv[1]);process.stdout.write(JSON.stringify(Object.fromEntries(['ui','tokens','agent'].map(k=>[k,r.resolve(process.argv[2]+'/'+k+(k==='agent'?'/mcp':''))]))))";
|
|
41
|
+
const env=Object.fromEntries(['PATH','SystemRoot','SYSTEMROOT'].filter(k=>process.env[k]!==undefined).map(k=>[k,process.env[k]]));
|
|
42
|
+
signal?.throwIfAborted();const result=await run(process.execPath,['-e',code,path.join(app,'package.json'),scope],{env,timeout:5000,maxBuffer:1024*1024,signal});
|
|
43
|
+
const entries=JSON.parse(result.stdout);
|
|
44
|
+
const manifests={};for(const k of keys){signal?.throwIfAborted();const dir=await fs.realpath(path.join(modules,scope,k)); const entry=await fs.realpath(entries[k]);
|
|
45
|
+
if(!dir.startsWith(modules+path.sep)||!entry.startsWith(dir+path.sep)) failure('Package resolves outside project node_modules');
|
|
46
|
+
const manifest=await boundedJson(path.join(dir,'package.json'));
|
|
47
|
+
if(manifest.name!==d[k]||manifest.version!==d.version) failure('Installed package does not match receipt');manifests[k]=manifest;
|
|
48
|
+
}
|
|
49
|
+
if(direct){for(const manifest of Object.values(manifests))for(const section of ['dependencies','devDependencies','peerDependencies','optionalDependencies'])if(Object.values(manifest[section]??{}).some(v=>typeof v==='string'&&v.trim().startsWith('npm:')))failure('Unexpected package alias');const ui=manifests.ui,name=d.tokens,dep=ui.dependencies?.[name];if(['dependencies','devDependencies','peerDependencies','optionalDependencies','peerDependenciesMeta'].some(section=>Object.hasOwn(ui[section]??{},'@vini/tokens'))||ui.peerDependencies?.[name]!==d.version||(dep!==undefined&&dep!==d.version)||Object.hasOwn(ui.optionalDependencies??{},name)||ui.peerDependenciesMeta?.[name]?.optional===true)failure('UI token dependency does not match receipt');}
|
|
50
|
+
else if(legacy&&manifests.ui.dependencies?.['@vini/tokens']!==`npm:${d.tokens}@${d.version}`)failure('UI token dependency does not match receipt');
|
|
51
|
+
signal?.throwIfAborted();if(!lockOwned) await noLock(root);
|
|
52
|
+
if(!(await boundedBytes(receiptPath)).equals(bytes)) failure('Installation changed during inspection');
|
|
53
|
+
return {receipt,bytes,entry:entries.agent};
|
|
54
|
+
}
|
|
55
|
+
class Worker {
|
|
56
|
+
constructor(entry,root){
|
|
57
|
+
this.child=spawn(process.execPath,[entry],{cwd:root,stdio:['pipe','pipe','pipe']}); this.pending=new Map();this.seq=0;this.buffer='';this.dead=false;
|
|
58
|
+
let diagnosticBytes=0;this.child.stderr.on('data',b=>{if(diagnosticBytes<8192&&!process.stderr.writableNeedDrain){const part=b.subarray(0,8192-diagnosticBytes);diagnosticBytes+=part.length;process.stderr.write(part);}});
|
|
59
|
+
this.child.stdout.setEncoding('utf8');this.child.stdout.on('data',chunk=>{this.buffer+=chunk;if(Buffer.byteLength(this.buffer)>maxBytes){this.close();return;}let n;while((n=this.buffer.indexOf('\n'))>=0){const line=this.buffer.slice(0,n);this.buffer=this.buffer.slice(n+1);try {const msg=JSON.parse(line),p=this.pending.get(msg.id);if(p){this.pending.delete(msg.id);clearTimeout(p.timer);p.resolve(msg);}}catch{this.close();}}});
|
|
60
|
+
const ended=()=>{if(this.dead)return;this.dead=true;for(const p of this.pending.values()){clearTimeout(p.timer);p.reject(new Error('VINi MCP worker disconnected; request outcome may be unknown'));}this.pending.clear();};this.child.on('error',ended);this.child.on('close',ended);this.child.stdin.on('error',()=>{this.close();ended();});
|
|
61
|
+
}
|
|
62
|
+
request(method,params,onId){if(this.dead)return Promise.reject(new Error('VINi MCP worker unavailable'));const id=++this.seq,payload=JSON.stringify({jsonrpc:'2.0',id,method,...(params===undefined?{}:{params})})+'\n';if(this.pending.size>=64||this.child.stdin.writableLength+Buffer.byteLength(payload)>maxBytes)return Promise.reject(new Error('VINi MCP worker is busy; request was not executed'));onId?.(id);return new Promise((resolve,reject)=>{const timer=setTimeout(()=>{this.pending.delete(id);reject(new Error('VINi MCP request timed out; outcome is unknown'));},timeout);this.pending.set(id,{resolve,reject,timer});this.child.stdin.write(payload,e=>{if(e){clearTimeout(timer);this.pending.delete(id);reject(e);}});});}
|
|
63
|
+
notify(method,params){if(!this.dead){const payload=JSON.stringify({jsonrpc:'2.0',method,...(params===undefined?{}:{params})})+'\n';if(this.child.stdin.writableLength+Buffer.byteLength(payload)>maxBytes){this.close();return;}this.child.stdin.write(payload);}}
|
|
64
|
+
close(){if(!this.dead){this.child.stdin.end();this.child.kill('SIGTERM');const child=this.child;const timer=setTimeout(()=>{if(child.exitCode===null&&child.signalCode===null)child.kill('SIGKILL');},1000);child.once('close',()=>clearTimeout(timer));timer.unref();}}
|
|
65
|
+
async drain(){const until=Date.now()+timeout;while(this.pending.size&&Date.now()<until&&!this.dead)await new Promise(r=>setTimeout(r,20));this.close();}
|
|
66
|
+
}
|
|
67
|
+
function compatible(a,b){return same(a.protocolVersion,b.protocolVersion)&&same(a.capabilities,b.capabilities)&&same(a.serverInfo?.name,b.serverInfo?.name)&&same(a.instructions,b.instructions);}
|
|
68
|
+
function supportedTransition(from,to){const order=compareVersions(to.version,from.version),sameFamily=keys.every(k=>from[k]===to[k]);if(sameFamily)return order>=0;const legacy=keys.every(k=>from[k]===`@timelex/vini-${k}`),oldDirect=keys.every(k=>from[k]===`@vini/${k}`),toOld=keys.every(k=>to[k]===`@vini/${k}`),toNative=keys.every(k=>to[k]===`@vini-ds/${k}`);return order>0&&((legacy&&toOld)||((legacy||oldDirect)&&toNative));}
|
|
69
|
+
export async function startPublicSupervisor({projectRoot,appRoot='.',input=process.stdin,output=process.stdout,standalone=false}={}) {
|
|
70
|
+
const startupAbort=new AbortController(),earlySignal=()=>startupAbort.abort();process.once('SIGTERM',earlySignal);process.once('SIGINT',earlySignal);input.once('close',earlySignal);input.once('error',earlySignal);output.once('close',earlySignal);output.once('error',earlySignal);let root,startupLock,initial;const instanceId=randomUUID();
|
|
71
|
+
try{root=await fs.realpath(projectRoot);startupAbort.signal.throwIfAborted();if(input.destroyed||output.destroyed)failure('Connection closed during startup');startupLock=await acquireStartupLock(root);startupAbort.signal.throwIfAborted();initial=await inspect(root,appRoot,null,false,true,startupAbort.signal);startupAbort.signal.throwIfAborted();if(input.destroyed||output.destroyed)failure('Connection closed during startup');}catch(e){if(startupLock)await startupLock.release();throw e;}finally{process.removeListener('SIGTERM',earlySignal);process.removeListener('SIGINT',earlySignal);input.removeListener('close',earlySignal);input.removeListener('error',earlySignal);output.removeListener('close',earlySignal);output.removeListener('error',earlySignal);}
|
|
72
|
+
let active=new Worker(initial.entry,root), generation=initial.receipt.generation??null, current=initial.receipt.distribution, session=null, changing=false, closed=false,initializing=0,connectionRevision=0;const workers=new Set();let refreshAbort,refreshDone;
|
|
73
|
+
function ownWorker(worker){workers.add(worker);worker.child.once('close',()=>workers.delete(worker));}ownWorker(active);
|
|
74
|
+
let startupFinished=false;const startupTimer=setTimeout(()=>{if(!startupFinished){process.stderr.write('VINi MCP startup timed out; reconnect the client\n');shutdown();}},timeout);
|
|
75
|
+
async function releaseStartup(){if(startupFinished)return;await startupLock.release();startupFinished=true;clearTimeout(startupTimer);}
|
|
76
|
+
function shutdown(flush=false){if(closed)return;closed=true;refreshAbort?.abort();const owned=[...workers];const exits=owned.map(worker=>worker.dead?Promise.resolve():new Promise(resolve=>worker.child.once('close',resolve)));for(const worker of owned)worker.close();input.destroy();const finishOutput=(async()=>{if(flush)await Promise.race([outputQueue,new Promise(resolve=>setTimeout(resolve,500))]);output.destroy();})();const cleanup=Promise.allSettled([releaseStartup().catch(e=>process.stderr.write(`VINi MCP startup lock: ${e.message}\n`)),refreshDone??Promise.resolve(),finishOutput,...exits]);if(standalone){const deadline=setTimeout(()=>process.exit(1),3000);void cleanup.finally(()=>{clearTimeout(deadline);process.exit(0);});}}
|
|
77
|
+
output.on('error',()=>shutdown());output.on('close',()=>shutdown());
|
|
78
|
+
let outputQueue=Promise.resolve(),outputBytes=0;const inFlight=new Map();const send=x=>{const data=JSON.stringify(x)+'\n';outputBytes+=Buffer.byteLength(data);if(outputBytes>maxBytes){shutdown();input.destroy();return;}outputQueue=outputQueue.then(()=>new Promise((resolve,reject)=>output.write(data,e=>e?reject(e):resolve()))).finally(()=>{outputBytes-=Buffer.byteLength(data);}).catch(()=>{shutdown();});};
|
|
79
|
+
async function forward(worker,message){const ticket=inFlight.get(message.id);if(ticket?.cancelled)failure('Request cancelled before execution');const r=await worker.request(message.method,message.params,id=>{if(ticket){ticket.worker=worker;ticket.id=id;}});return {...r,id:message.id};}
|
|
80
|
+
async function handle(message){
|
|
81
|
+
if(closed)return;
|
|
82
|
+
if(!message||message.jsonrpc!=='2.0'||typeof message.method!=='string')return rpcError(message?.id??null,'Invalid JSON-RPC request');
|
|
83
|
+
if(message.id===undefined){if(message.method==='notifications/initialized'){if(session&&!session.initialized){session.initialized=true;active.notify(message.method,message.params);session.fingerprint=Promise.all(['tools/list','resources/list','resources/templates/list'].map(method=>active.request(method))).then(values=>values.every(item=>item.result&&!item.error)?values.map(item=>item.result):null).catch(()=>null);session.ready=(async()=>{const [fingerprint,baseline]=await Promise.all([session.fingerprint,active.request('resources/read',{uri:'vini://system/current'})]);let context;try{context=JSON.parse(baseline.result.contents[0].text);}catch{failure('Initial MCP context unavailable');}if(!fingerprint||context.version!==current.version||!keys.every(k=>context.packages?.[k]?.name===current[k]&&context.packages[k].version===current.version))failure('Initial MCP context differs from installed release');await releaseStartup();})();session.ready.catch(e=>{process.stderr.write(`VINi MCP startup: ${e.message}\n`);shutdown();});}}else if(message.method==='notifications/cancelled'){const pending=inFlight.get(message.params?.requestId);if(pending&&!pending.cancelled){pending.cancelled=true;if(pending.cancel)pending.cancel();else if(pending.worker)pending.worker.notify('notifications/cancelled',{...message.params,requestId:pending.id});}}return;}
|
|
84
|
+
try {
|
|
85
|
+
if(message.method==='initialize'){if(changing)failure('Connection is switching; retry initialization');if(session||initializing)failure('Connection already initialized');if(!['2025-06-18','2025-03-26','2024-11-05','2026-07-28'].includes(message.params?.protocolVersion))failure('Unsupported MCP protocol version');initializing++;try{const response=await forward(active,message);if(response.result)session={params:message.params,result:response.result,initialized:false};return response;}finally{initializing--;}}
|
|
86
|
+
if(!session?.initialized||initializing)failure('Connection is not initialized');
|
|
87
|
+
await session.ready;if(closed)failure('Connection is closed');if(inFlight.get(message.id)?.cancelled)failure('Request cancelled before execution');
|
|
88
|
+
if(message.method==='resources/list'){const r=await forward(active,message);if(r.result){if(r.result.resources.some(item=>item.uri===runtimeResource.uri))failure('Worker conflicts with supervisor resource');r.result.resources=[...r.result.resources,runtimeResource];}return r;}
|
|
89
|
+
if(message.method==='tools/list'){const r=await forward(active,message);if(r.result){if(r.result.tools.some(item=>item.name===reloadTool.name))failure('Worker conflicts with supervisor tool');r.result.tools=[...r.result.tools,reloadTool];}return r;}
|
|
90
|
+
if(message.method==='resources/read'&&message.params?.uri===runtimeResource.uri)return ok(message.id,{contents:[{...runtimeResource,text:JSON.stringify({instanceId,connectionRevision,projectRoot:root,version:current.version,generation,scope:'connection-not-chat'})}]});
|
|
91
|
+
if(message.method==='tools/call'&&message.params?.name==='refresh_connection'){
|
|
92
|
+
const target=message.params?.arguments?.target;
|
|
93
|
+
if(!target||Object.keys(target).sort().join(',')!==['agent','tokens','ui','version'].join(',')||!['version',...keys].every(k=>typeof target[k]==='string'&&target[k].length>0&&target[k].length<=214))failure('Exact target required');
|
|
94
|
+
if(!isExactVersion(target.version)||!supportedTransition(current,target))failure('Unsupported release transition or downgrade; reconnect after reviewing the installed release');
|
|
95
|
+
if(!session||!session.initialized||initializing)failure('Connection is not initialized');if(changing)failure('Connection is already switching');changing=true;
|
|
96
|
+
let replacement, lockIdentity,lockContents,cancelled=false,switched=false,finishRefresh;refreshDone=new Promise(resolve=>{finishRefresh=resolve;});const initialSession=session,abort=new AbortController(),ticket=inFlight.get(message.id);refreshAbort=abort;ticket.cancel=()=>{cancelled=true;abort.abort();replacement?.close();};const lockPath=path.join(root,'.vini-npm-install.lock'),ownerPath=path.join(lockPath,'owner.json');
|
|
97
|
+
async function ownsLock(){const now=await fs.lstat(lockPath);return now.isDirectory()&&!now.isSymbolicLink()&&now.dev===lockIdentity.dev&&now.ino===lockIdentity.ino&&same(await fs.readdir(lockPath),['owner.json'])&&(await boundedBytes(ownerPath)).equals(lockContents);}
|
|
98
|
+
try {
|
|
99
|
+
abort.signal.throwIfAborted();try {await fs.mkdir(lockPath,{mode:0o700});lockIdentity=await fs.lstat(lockPath);abort.signal.throwIfAborted();const contents=Buffer.from(JSON.stringify({version:1,nonce:randomUUID(),pid:process.pid,startedAt:new Date().toISOString(),command:'refresh_connection',recovery:null},null,2)+'\n');await fs.writeFile(ownerPath,contents,{flag:'wx',mode:0o600});lockContents=contents;} catch(e) {if(e.code==='EEXIST'&&!lockIdentity)failure('Installation is in progress or recovery needs review');throw e;}
|
|
100
|
+
abort.signal.throwIfAborted();const candidate=await inspect(root,appRoot,target,true,true,abort.signal);abort.signal.throwIfAborted();replacement=new Worker(candidate.entry,root);ownWorker(replacement);
|
|
101
|
+
const init=await replacement.request('initialize',session.params);if(init.error||!compatible(session.result,init.result))failure('MCP interface changed; reconnect this client');replacement.notify('notifications/initialized');
|
|
102
|
+
const [tools,resources,templates,baseline]=await Promise.all([replacement.request('tools/list'),replacement.request('resources/list'),replacement.request('resources/templates/list'),replacement.request('resources/read',{uri:'vini://system/current'})]);
|
|
103
|
+
if(init.error||tools.error||resources.error||templates.error||!compatible(session.result,init.result)||tools.result.tools.some(item=>item.name===reloadTool.name)||resources.result.resources.some(item=>item.uri===runtimeResource.uri))failure('MCP interface changed; reconnect this client');
|
|
104
|
+
let context;try { context=JSON.parse(baseline.result.contents[0].text); } catch { failure('Replacement context is unavailable'); }
|
|
105
|
+
if(context.version!==target.version||!keys.every(k=>context.packages?.[k]?.name===target[k]&&context.packages[k].version===target.version))failure('Replacement context does not match selected target');
|
|
106
|
+
const oldInterface=await initialSession.fingerprint;
|
|
107
|
+
if(!oldInterface||!same(oldInterface,[tools.result,resources.result,templates.result]))failure('MCP interface changed or could not be verified; reconnect this client');
|
|
108
|
+
abort.signal.throwIfAborted();const verified=await inspect(root,appRoot,target,true,true,abort.signal);
|
|
109
|
+
const lockValid=await ownsLock();if(!verified.bytes.equals(candidate.bytes)||replacement.dead||closed||cancelled||abort.signal.aborted||initializing||session!==initialSession||!lockValid)failure('Installation, connection or request changed during switch');
|
|
110
|
+
const operation=current.version===target.version&&keys.every(k=>current[k]===target[k])?'same-release-recovery':'release-change';const old=active;active=replacement;replacement=null;generation=verified.receipt.generation;current=verified.receipt.distribution;connectionRevision++;switched=true;void old.drain().finally(()=>workers.delete(old));
|
|
111
|
+
const data={status:'switched',operation,instanceId,connectionRevision,version:current.version,generation,clientVerification:'Read runtime connection before and after current, component contract and check_updates in this client; require identical non-null generation and connectionRevision.'};
|
|
112
|
+
return ok(message.id,{content:[{type:'text',text:JSON.stringify(data)}],structuredContent:data});
|
|
113
|
+
} finally {replacement?.close();try{if(lockIdentity){if(!lockContents){const now=await fs.lstat(lockPath);if(now.dev!==lockIdentity.dev||now.ino!==lockIdentity.ino||(await fs.readdir(lockPath)).length)failure('Lock ownership changed; inspect .vini-npm-install.lock');await fs.rmdir(lockPath);}else{if(!await ownsLock())failure('Lock ownership changed; inspect .vini-npm-install.lock');await fs.unlink(ownerPath);await fs.rmdir(lockPath);}}}catch(e){throw new Error(`${switched?'Connection switched, but lock cleanup failed':'Lock cleanup failed'}; inspect .vini-npm-install.lock before retrying: ${e.message}`);}finally{refreshAbort=null;changing=false;finishRefresh();refreshDone=null;}}
|
|
114
|
+
}
|
|
115
|
+
const response=await forward(active,message);
|
|
116
|
+
if(message.method==='tools/call'&&message.params?.name==='check_updates'&&response.result?.structuredContent){const data=response.result.structuredContent;if(data.installed?.mismatchKind==='mcp-context'&&data.installed.matchesReceipt===true){data.nextStep='The installed packages match the receipt but this connection is stale. Call refresh_connection in this connection with the exact selected target after reviewing it; then read current, the affected component contract and check_updates again. If the interface is incompatible, reconnect the client.';if(response.result.content?.[0]?.type==='text')response.result.content[0].text=JSON.stringify(data);}}
|
|
117
|
+
return response;
|
|
118
|
+
} catch(e){if(inFlight.get(message.id)?.cancelled&&!/lock cleanup failed/i.test(e.message))return {jsonrpc:'2.0',id:message.id,error:{code:-32800,message:'Request cancelled; outcome may be unknown'}};return rpcError(message.id,e.message);}
|
|
119
|
+
}
|
|
120
|
+
let buffer='';const ids=new Set();input.setEncoding('utf8');input.on('data',chunk=>{if(closed)return;buffer+=chunk;if(Buffer.byteLength(buffer)>maxBytes){send(rpcError(null,'Message too large'));shutdown(true);return;}let n;while((n=buffer.indexOf('\n'))>=0){const line=buffer.slice(0,n).trim();buffer=buffer.slice(n+1);if(!line)continue;let message;try{message=JSON.parse(line);}catch{send(rpcError(null,'Parse error'));continue;}const hasId=message&&Object.hasOwn(message,'id');if(hasId&&(!(['string','number'].includes(typeof message.id))||ids.has(message.id))){send(rpcError(null,'Invalid or duplicate request id'));continue;}if(hasId&&ids.size>=64){send(rpcError(message.id,'Connection is busy; request was not executed'));continue;}if(hasId){ids.add(message.id);inFlight.set(message.id,{cancelled:false});}void handle(message).then(response=>{if(response&&!closed)send(response);}).finally(()=>{if(hasId){ids.delete(message.id);inFlight.delete(message.id);}});}});
|
|
121
|
+
input.on('end',()=>{if(buffer.trim())send(rpcError(null,'Incomplete message'));shutdown(true);});input.on('error',()=>shutdown());input.on('close',()=>shutdown());const signal=()=>shutdown();process.once('SIGTERM',signal);process.once('SIGINT',signal);return {instanceId,close:shutdown};
|
|
122
|
+
}
|
|
123
|
+
if(process.argv[1]&&await fs.realpath(process.argv[1]).catch(()=>null)===fileURLToPath(import.meta.url)){
|
|
124
|
+
const args=process.argv.slice(2);if(args.length!==4||args[0]!=='--project-root'||args[2]!=='--app-root'||!path.isAbsolute(args[1])){console.error('Usage: supervisor.mjs --project-root ABS --app-root REL');process.exitCode=1;}else startPublicSupervisor({projectRoot:args[1],appRoot:args[3],standalone:true}).catch(e=>{console.error(`VINi MCP supervisor: ${e.message}`);process.exitCode=1;});
|
|
125
|
+
}
|