@vini-ds/agent 0.0.0-stage → 0.1.0-alpha.5
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 +61 -0
- package/SKILL.md +26 -0
- package/context/components.json +16686 -0
- package/context/current.json +918 -0
- package/context/tokens.json +28758 -0
- package/mcp.mjs +180 -0
- package/package.json +40 -4
- package/updates.mjs +245 -0
- package/README.md +0 -3
package/mcp.mjs
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Public, read-only package documentation. The internal producer Gateway is not exposed.
|
|
3
|
+
import { readFile, realpath } from 'node:fs/promises';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { checkUpdates } from './updates.mjs';
|
|
7
|
+
|
|
8
|
+
const root = path.dirname(fileURLToPath(import.meta.url));
|
|
9
|
+
const load = async (name) => JSON.parse(await readFile(path.join(root, name), 'utf8'));
|
|
10
|
+
const own = (record, key) => Object.hasOwn(record, key);
|
|
11
|
+
const maxBytes = 2 * 1024 * 1024;
|
|
12
|
+
const protocols = ['2025-06-18', '2025-03-26', '2024-11-05', '2026-07-28'];
|
|
13
|
+
const annotations = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };
|
|
14
|
+
const schema = (properties, required = []) => ({ type: 'object', additionalProperties: false, properties, required });
|
|
15
|
+
const string = { type: 'string', minLength: 1 };
|
|
16
|
+
export const toolDefinitions = [
|
|
17
|
+
{ name: 'search_ds', description: 'Find public VINi components or Foundation token names in this installed baseline.', inputSchema: schema({ query: string, kinds: { type: 'array', items: { enum: ['component', 'token'] } }, limit: { type: 'integer', minimum: 1, maximum: 50 } }, ['query']) },
|
|
18
|
+
{ 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']) },
|
|
19
|
+
{ name: 'get_package_profile', description: 'Read the matching public React DOM package setup. Other profiles are not supported here.', inputSchema: schema({ id: string }, ['id']) },
|
|
20
|
+
{ name: 'get_platform_status', description: 'Read the scope of the public React DOM distribution; other renderers are explicitly unsupported.', inputSchema: schema({ id: string }, ['id']) },
|
|
21
|
+
{ name: 'get_token', description: 'Read a Foundation token and its available modes.', inputSchema: schema({ id: string }, ['id']) },
|
|
22
|
+
{ 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']) },
|
|
23
|
+
{ 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']) }) },
|
|
24
|
+
].map((tool) => ({ ...tool, annotations: tool.name === 'check_updates' ? { ...annotations, openWorldHint: true } : annotations }));
|
|
25
|
+
|
|
26
|
+
function requiredString(value, label) {
|
|
27
|
+
if (typeof value !== 'string' || !value.trim()) throw new Error(`${label} is required`);
|
|
28
|
+
return value;
|
|
29
|
+
}
|
|
30
|
+
function object(value, label) {
|
|
31
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error(`${label} must be an object`);
|
|
32
|
+
return value;
|
|
33
|
+
}
|
|
34
|
+
function validateArguments(tool, args) {
|
|
35
|
+
object(args, 'arguments');
|
|
36
|
+
for (const key of Object.keys(args)) if (!own(tool.inputSchema.properties, key)) throw new Error(`Unknown argument ${key}`);
|
|
37
|
+
for (const key of tool.inputSchema.required) if (!own(args, key)) throw new Error(`Missing argument ${key}`);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// The resolver follows the same alias/mode/sum semantics as the internal Gateway.
|
|
41
|
+
export function resolveToken(tokens, id, modes) {
|
|
42
|
+
object(modes, 'modeByCollection');
|
|
43
|
+
for (const [collection, mode] of Object.entries(modes)) {
|
|
44
|
+
if (!own(tokens.collections, collection) || !tokens.collections[collection].modes.includes(mode)) throw new Error(`Unknown token mode ${collection}/${mode}`);
|
|
45
|
+
}
|
|
46
|
+
for (const [collection, contract] of Object.entries(tokens.collections)) {
|
|
47
|
+
if (contract.requiresExplicitMode && !own(modes, collection)) throw new Error(`Collection ${collection} requires an explicit mode`);
|
|
48
|
+
}
|
|
49
|
+
const trace = [], active = new Set();
|
|
50
|
+
function visit(name) {
|
|
51
|
+
if (active.has(name)) throw new Error(`Token alias cycle: ${name}`);
|
|
52
|
+
if (!own(tokens.tokens, name)) throw new Error(`Unknown token ${name}`);
|
|
53
|
+
const token = tokens.tokens[name], collection = tokens.collections[token.collection];
|
|
54
|
+
const mode = collection.requiresExplicitMode ? modes[token.collection] : collection.modes[0];
|
|
55
|
+
const declaration = token.values[mode];
|
|
56
|
+
if (!declaration) throw new Error(`Missing token mode ${name}/${mode}`);
|
|
57
|
+
trace.push({ id: name, collection: token.collection, mode, type: declaration.type });
|
|
58
|
+
if (declaration.type === 'alias') {
|
|
59
|
+
active.add(name); const value = visit(declaration.to); active.delete(name); return value;
|
|
60
|
+
}
|
|
61
|
+
if (declaration.type === 'derived') {
|
|
62
|
+
if (declaration.operation !== 'sum' || !Array.isArray(declaration.from)) throw new Error('Unsupported token derivation');
|
|
63
|
+
active.add(name); const values = declaration.from.map(visit); active.delete(name);
|
|
64
|
+
if (!values.every((value) => typeof value === 'number')) throw new Error('Token sum requires numeric inputs');
|
|
65
|
+
const result = values.reduce((sum, value) => sum + value, 0);
|
|
66
|
+
if (!Object.is(result, declaration.value)) throw new Error('Token sum differs from its recorded value');
|
|
67
|
+
return result;
|
|
68
|
+
}
|
|
69
|
+
if (!['float', 'color', 'string', 'boolean'].includes(declaration.type)) throw new Error('Unsupported token declaration');
|
|
70
|
+
return structuredClone(declaration.value);
|
|
71
|
+
}
|
|
72
|
+
return { value: visit(id), modeByCollection: modes, trace };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export async function createPublicService() {
|
|
76
|
+
const [metadata, components, tokens, setup] = await Promise.all([load('context/current.json'), load('context/components.json'), load('context/tokens.json'), readFile(path.join(root, 'SETUP.md'), 'utf8')]);
|
|
77
|
+
const byId = new Map(components.map((component) => [component.id, component]));
|
|
78
|
+
const current = { ...metadata, installationVerification: 'not-performed-by-context-server', nativeClientVerification: 'read-this-resource-in-your-client', scope: 'public-documentation-projection' };
|
|
79
|
+
const imports = { ui: metadata.packages?.ui?.importName ?? '@vini/ui', tokens: metadata.packages?.tokens?.importName ?? '@vini/tokens' };
|
|
80
|
+
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' };
|
|
81
|
+
const resources = [
|
|
82
|
+
{ uri: 'vini://system/current', name: 'VINi public baseline', mimeType: 'application/json' },
|
|
83
|
+
{ uri: 'vini://guidelines/setup', name: 'VINi public setup', mimeType: 'text/markdown' },
|
|
84
|
+
{ uri: 'vini://agent-kit/quickstart', name: 'VINi public quickstart', mimeType: 'text/markdown' },
|
|
85
|
+
{ uri: 'vini://components', name: 'VINi component inventory', mimeType: 'application/json' },
|
|
86
|
+
{ uri: 'vini://packages/react-dom-reference', name: 'VINi React DOM profile', mimeType: 'application/json' },
|
|
87
|
+
];
|
|
88
|
+
const envelope = (data) => ({ packageVersion: metadata.version, baseline: metadata.baseline, ...data });
|
|
89
|
+
function contract(id, platform) {
|
|
90
|
+
requiredString(id, 'id');
|
|
91
|
+
if (platform !== undefined && platform !== 'web') throw new Error('Only the public React DOM/web profile is available');
|
|
92
|
+
if (!byId.has(id)) throw new Error(`Unknown component ${id}`);
|
|
93
|
+
return byId.get(id);
|
|
94
|
+
}
|
|
95
|
+
async function call(name, args = {}) {
|
|
96
|
+
const definition = toolDefinitions.find((tool) => tool.name === name);
|
|
97
|
+
if (!definition) throw new Error(`Unknown tool ${name}`);
|
|
98
|
+
validateArguments(definition, args);
|
|
99
|
+
if (name === 'check_updates') return checkUpdates(metadata, { target: args.target });
|
|
100
|
+
if (name === 'get_component_contract') return envelope({ component: contract(args.id, args.platform) });
|
|
101
|
+
if (name === 'get_package_profile') {
|
|
102
|
+
if (args.id !== 'react-dom-reference') throw new Error('Only react-dom-reference is available in this public package');
|
|
103
|
+
return envelope({ profile });
|
|
104
|
+
}
|
|
105
|
+
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' } });
|
|
106
|
+
if (name === 'get_token' || name === 'resolve_token') {
|
|
107
|
+
const id = requiredString(args.id, 'id');
|
|
108
|
+
if (!own(tokens.tokens, id)) throw new Error(`Unknown token ${id}`);
|
|
109
|
+
const token = tokens.tokens[id];
|
|
110
|
+
if (name === 'get_token') return envelope({ token: { id, ...token }, collections: tokens.collections });
|
|
111
|
+
return envelope({ token: { id, collection: token.collection, resolvedType: token.resolvedType }, ...resolveToken(tokens, id, args.modeByCollection), units: token.resolvedType === 'FLOAT' ? 'renderer-defined' : 'not-applicable' });
|
|
112
|
+
}
|
|
113
|
+
const query = requiredString(args.query, 'query').toLocaleLowerCase();
|
|
114
|
+
const kinds = args.kinds ?? ['component', 'token'];
|
|
115
|
+
const limit = args.limit ?? 20;
|
|
116
|
+
if (!Array.isArray(kinds) || !kinds.length || !kinds.every((kind) => ['component', 'token'].includes(kind))) throw new Error('Invalid kinds');
|
|
117
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > 50) throw new Error('Limit must be 1..50');
|
|
118
|
+
const matches = [];
|
|
119
|
+
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 });
|
|
120
|
+
if (kinds.includes('token')) for (const id of Object.keys(tokens.tokens)) if (id.toLocaleLowerCase().includes(query)) matches.push({ kind: 'token', id });
|
|
121
|
+
return envelope({ results: matches.slice(0, limit), total: matches.length });
|
|
122
|
+
}
|
|
123
|
+
function readResource(uri) {
|
|
124
|
+
let data;
|
|
125
|
+
if (uri === 'vini://guidelines/setup' || uri === 'vini://agent-kit/quickstart') return { uri, mimeType: 'text/markdown', text: setup };
|
|
126
|
+
if (uri === 'vini://system/current') data = current;
|
|
127
|
+
else if (uri === 'vini://components') data = components.map(({ id, displayName, exports }) => ({ id, displayName, exports }));
|
|
128
|
+
else if (uri === 'vini://packages/react-dom-reference') data = profile;
|
|
129
|
+
else if (/^vini:\/\/components\/[a-z0-9-]+$/u.test(uri)) data = contract(uri.slice('vini://components/'.length));
|
|
130
|
+
else throw new Error(`Unknown resource ${uri}`);
|
|
131
|
+
return { uri, mimeType: 'application/json', text: JSON.stringify(data) };
|
|
132
|
+
}
|
|
133
|
+
return { current, call, readResource, resources };
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
async function main() {
|
|
137
|
+
const service = await createPublicService();
|
|
138
|
+
if (process.argv.length === 3 && process.argv[2] === '--check') {
|
|
139
|
+
const { name, version, packages, baseline, componentCount, tokenCount, scope } = service.current;
|
|
140
|
+
console.log(JSON.stringify({ ok: true, name, version, packages, baseline, componentCount, tokenCount, scope })); return;
|
|
141
|
+
}
|
|
142
|
+
if (process.argv.length > 2) throw new Error('Usage: node mcp.mjs [--check]');
|
|
143
|
+
function result(id, value) { return { jsonrpc: '2.0', id, result: value }; }
|
|
144
|
+
function error(id, code, message) { return { jsonrpc: '2.0', id, error: { code, message } }; }
|
|
145
|
+
async function handle(message) {
|
|
146
|
+
if (!message || message.jsonrpc !== '2.0' || typeof message.method !== 'string') return error(message?.id ?? null, -32600, 'Invalid JSON-RPC request');
|
|
147
|
+
if (message.id === undefined) return;
|
|
148
|
+
try {
|
|
149
|
+
if (message.method === 'initialize') return result(message.id, { protocolVersion: protocols.includes(message.params?.protocolVersion) ? message.params.protocolVersion : protocols[0], 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.' });
|
|
150
|
+
if (message.method === 'ping') return result(message.id, {});
|
|
151
|
+
if (message.method === 'tools/list') return result(message.id, { tools: toolDefinitions });
|
|
152
|
+
if (message.method === 'resources/list') return result(message.id, { resources: service.resources });
|
|
153
|
+
if (message.method === 'resources/templates/list') return result(message.id, { resourceTemplates: [{ uriTemplate: 'vini://components/{id}', name: 'VINi component', mimeType: 'application/json' }] });
|
|
154
|
+
if (message.method === 'resources/read') return result(message.id, { contents: [service.readResource(message.params?.uri)] });
|
|
155
|
+
if (message.method === 'tools/call') {
|
|
156
|
+
try { const data = await service.call(message.params?.name, message.params?.arguments); return result(message.id, { content: [{ type: 'text', text: JSON.stringify(data) }], structuredContent: data }); }
|
|
157
|
+
catch (problem) { return result(message.id, { isError: true, content: [{ type: 'text', text: problem.message }] }); }
|
|
158
|
+
}
|
|
159
|
+
return error(message.id, -32601, 'Method not found');
|
|
160
|
+
} catch (problem) { return error(message.id, -32602, problem.message); }
|
|
161
|
+
}
|
|
162
|
+
let buffer = '';
|
|
163
|
+
process.stdin.setEncoding('utf8');
|
|
164
|
+
for await (const chunk of process.stdin) {
|
|
165
|
+
buffer += chunk;
|
|
166
|
+
if (Buffer.byteLength(buffer) > maxBytes) { process.stdout.write(`${JSON.stringify(error(null, -32700, 'Message too large'))}\n`); process.exitCode = 1; return; }
|
|
167
|
+
let index;
|
|
168
|
+
while ((index = buffer.indexOf('\n')) !== -1) {
|
|
169
|
+
const line = buffer.slice(0, index).trim(); buffer = buffer.slice(index + 1);
|
|
170
|
+
if (!line) continue;
|
|
171
|
+
let message;
|
|
172
|
+
try { message = JSON.parse(line); } catch { process.stdout.write(`${JSON.stringify(error(null, -32700, 'Parse error'))}\n`); continue; }
|
|
173
|
+
const response = await handle(message);
|
|
174
|
+
if (response) process.stdout.write(`${JSON.stringify(response)}\n`);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
if (buffer.trim()) process.stdout.write(`${JSON.stringify(error(null, -32700, 'Incomplete message'))}\n`);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
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,42 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vini-ds/agent",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0-alpha.5",
|
|
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
|
+
"./skill": "./SKILL.md",
|
|
15
|
+
"./setup": "./SETUP.md"
|
|
16
|
+
},
|
|
17
|
+
"files": [
|
|
18
|
+
"mcp.mjs",
|
|
19
|
+
"updates.mjs",
|
|
20
|
+
"SKILL.md",
|
|
21
|
+
"SETUP.md",
|
|
22
|
+
"context"
|
|
23
|
+
],
|
|
24
|
+
"viniRelease": {
|
|
25
|
+
"atlas": {
|
|
26
|
+
"url": "https://vini-atlas-pilot.layero.app/",
|
|
27
|
+
"archiveSha256": "sha256:45dcc5672f36b3262e02c2913998aceb6f3fe7b66b02405a61c9128d423f745a",
|
|
28
|
+
"siteRelease": "source-snapshot-20261104-update-completion",
|
|
29
|
+
"commit": "dcd9728349c7c013fbe649e957ad0a1afdc2dc0e"
|
|
30
|
+
},
|
|
31
|
+
"delivery": {
|
|
32
|
+
"id": "candidate-c11703e55c492320",
|
|
33
|
+
"manifestSha256": "sha256:e5729abf4455120ff527f55b809b0e77daf109ad5635c073e511b1687be5a839",
|
|
34
|
+
"packageManifestSha256": "sha256:44fc4d1f985ebe9d66344ec2cdb45640023eab886028dc7bb8e0be07f8c989e7"
|
|
35
|
+
},
|
|
36
|
+
"changes": {
|
|
37
|
+
"fromVersion": "0.1.0-alpha.4",
|
|
38
|
+
"summary": "Проверка выбранной версии, установленной связки и устаревшего MCP; отдельные результаты страницы и клиента.",
|
|
39
|
+
"components": []
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
package/updates.mjs
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
// Read-only public npm update discovery. No package code is downloaded or run.
|
|
2
|
+
import { readFile, realpath } from 'node:fs/promises';
|
|
3
|
+
import { execFile } from 'node:child_process';
|
|
4
|
+
import { isDeepStrictEqual, promisify } from 'node:util';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
|
|
7
|
+
const registry = 'https://registry.npmjs.org';
|
|
8
|
+
const exactVersion = /^\d+\.\d+\.\d+(?:-[a-z0-9]+(?:[.-][a-z0-9]+)*)?$/u;
|
|
9
|
+
const packageName = /^@[a-z0-9][a-z0-9-]*\/[a-z0-9][a-z0-9-]*$/u;
|
|
10
|
+
const keys = ['ui', 'tokens', 'agent'];
|
|
11
|
+
const hash = /^sha256:[a-f0-9]{64}$/u;
|
|
12
|
+
const runFile = promisify(execFile);
|
|
13
|
+
const legacyNames = { ui: '@timelex/vini-ui', tokens: '@timelex/vini-tokens', agent: '@timelex/vini-agent' };
|
|
14
|
+
const viniNames = { ui: '@vini/ui', tokens: '@vini/tokens', agent: '@vini/agent' };
|
|
15
|
+
const directNames = { ui: '@vini-ds/ui', tokens: '@vini-ds/tokens', agent: '@vini-ds/agent' };
|
|
16
|
+
function compareVersions(a, b) {
|
|
17
|
+
function parse(version) {
|
|
18
|
+
const match = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([a-z0-9-]+(?:\.[a-z0-9-]+)*))?$/u.exec(version);
|
|
19
|
+
if (!match) throw new Error('version is not valid semver');
|
|
20
|
+
const prerelease = match[4]?.split('.') ?? null;
|
|
21
|
+
if (prerelease?.some((part) => /^\d+$/u.test(part) && part.length > 1 && part.startsWith('0'))) throw new Error('version is not valid semver');
|
|
22
|
+
return { core: match.slice(1, 4).map(BigInt), prerelease };
|
|
23
|
+
}
|
|
24
|
+
const x = parse(a), y = parse(b);
|
|
25
|
+
for (let i = 0; i < 3; i++) if (x.core[i] !== y.core[i]) return x.core[i] < y.core[i] ? -1 : 1;
|
|
26
|
+
if (!x.prerelease || !y.prerelease) return x.prerelease === y.prerelease ? 0 : x.prerelease ? -1 : 1;
|
|
27
|
+
for (let i = 0; i < Math.max(x.prerelease.length, y.prerelease.length); i++) {
|
|
28
|
+
const left = x.prerelease[i], right = y.prerelease[i];
|
|
29
|
+
if (left === undefined || right === undefined) return left === right ? 0 : left === undefined ? -1 : 1;
|
|
30
|
+
if (left === right) continue;
|
|
31
|
+
const ln = /^\d+$/u.test(left), rn = /^\d+$/u.test(right);
|
|
32
|
+
if (ln && rn) return BigInt(left) < BigInt(right) ? -1 : 1;
|
|
33
|
+
if (ln !== rn) return ln ? -1 : 1;
|
|
34
|
+
return left < right ? -1 : 1;
|
|
35
|
+
}
|
|
36
|
+
return 0;
|
|
37
|
+
}
|
|
38
|
+
function sameNames(left, right) { return keys.every(key => left?.[key] === right?.[key]); }
|
|
39
|
+
function contextDistribution(metadata) {
|
|
40
|
+
return { version: metadata.version, ...Object.fromEntries(keys.map(key => [key, metadata.packages?.[key]?.name])) };
|
|
41
|
+
}
|
|
42
|
+
function contextIsConsistent(metadata) {
|
|
43
|
+
if (!exactVersion.test(metadata?.version ?? '') || !keys.every(key => typeof metadata.packages?.[key]?.name === 'string' && packageName.test(metadata.packages[key].name) && metadata.packages[key].version === metadata.version) ||
|
|
44
|
+
new Set(keys.map(key => metadata.packages[key].name)).size !== keys.length) return false;
|
|
45
|
+
try { compareVersions(metadata.version, metadata.version); return true; } catch { return false; }
|
|
46
|
+
}
|
|
47
|
+
function targetFamily(reference, target) {
|
|
48
|
+
if (!exactVersion.test(reference?.version ?? '') || !keys.every(key => packageName.test(reference[key] ?? ''))) throw new Error('installed or context package set cannot be verified');
|
|
49
|
+
if (sameNames(reference, target)) return 'same-family';
|
|
50
|
+
if (compareVersions(reference.version, target.version) < 0) {
|
|
51
|
+
if (sameNames(reference, legacyNames) && sameNames(target, viniNames)) return 'legacy-to-native';
|
|
52
|
+
if ((sameNames(reference, legacyNames) || sameNames(reference, viniNames)) && sameNames(target, directNames)) return 'manual-import-migration';
|
|
53
|
+
}
|
|
54
|
+
throw new Error('latest CLI does not describe a compatible exact package set');
|
|
55
|
+
}
|
|
56
|
+
function validateSelectedTarget(value) {
|
|
57
|
+
if (!value || typeof value !== 'object' || Array.isArray(value) ||
|
|
58
|
+
Object.keys(value).length !== 4 || !['version', ...keys].every(key => Object.hasOwn(value, key)) ||
|
|
59
|
+
typeof value.version !== 'string' || value.version.length > 100 || !exactVersion.test(value.version) || !keys.every(key => typeof value[key] === 'string' && value[key].length <= 214 && packageName.test(value[key])) ||
|
|
60
|
+
new Set(keys.map(key => value[key])).size !== keys.length) throw new Error('target must contain an exact version and three distinct scoped package names');
|
|
61
|
+
compareVersions(value.version, value.version);
|
|
62
|
+
return { version: value.version, ui: value.ui, tokens: value.tokens, agent: value.agent };
|
|
63
|
+
}
|
|
64
|
+
function equalsRelease(left, right) { return left?.version === right?.version && sameNames(left, right); }
|
|
65
|
+
function validRelease(value) {
|
|
66
|
+
try {
|
|
67
|
+
const url = new URL(value.atlas.url);
|
|
68
|
+
return url.protocol === 'https:' && !url.username && !url.password && !url.search && !url.hash &&
|
|
69
|
+
hash.test(value.atlas.archiveSha256) && /^[a-z0-9][a-z0-9.-]{0,99}$/u.test(value.atlas.siteRelease) &&
|
|
70
|
+
/^[a-f0-9]{40}$/u.test(value.atlas.commit) && /^candidate-[a-f0-9]{16}$/u.test(value.delivery.id) &&
|
|
71
|
+
hash.test(value.delivery.manifestSha256) && hash.test(value.delivery.packageManifestSha256) && exactVersion.test(value.changes.fromVersion) &&
|
|
72
|
+
typeof value.changes.summary === 'string' && !!value.changes.summary.trim() && value.changes.summary.length <= 1000 &&
|
|
73
|
+
Array.isArray(value.changes.components) && value.changes.components.length <= 200 &&
|
|
74
|
+
value.changes.components.every((name) => typeof name === 'string' && /^[A-Za-z][A-Za-z0-9-]{0,79}$/u.test(name)) &&
|
|
75
|
+
new Set(value.changes.components).size === value.changes.components.length;
|
|
76
|
+
} catch { return false; }
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async function boundedJson(file) {
|
|
80
|
+
const data = await readFile(file);
|
|
81
|
+
if (data.length > 4 * 1024 * 1024) throw new Error('metadata exceeds size limit');
|
|
82
|
+
return JSON.parse(data.toString('utf8'));
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async function resolveEntries(app, importScope) {
|
|
86
|
+
// Resolve in a fresh Node process so an already-connected MCP does not use
|
|
87
|
+
// cached pnpm realpaths after an upgrade. require.resolve reads package
|
|
88
|
+
// metadata and paths only; it never executes a package's entry point.
|
|
89
|
+
const code = `const {createRequire}=require('node:module');const r=createRequire(process.argv[1]);const scope=process.argv[2],out={};for(const k of ['ui','tokens','agent']){try{out[k]=r.resolve(scope+'/'+k+(k==='agent'?'/mcp':''));}catch{out[k]=null;}}process.stdout.write(JSON.stringify(out));`;
|
|
90
|
+
// Do not inherit Node preload options: discovery must not execute external code.
|
|
91
|
+
const env = Object.fromEntries(['PATH', 'SystemRoot', 'SYSTEMROOT'].filter(name => process.env[name] !== undefined).map(name => [name, process.env[name]]));
|
|
92
|
+
const { stdout } = await runFile(process.execPath, ['-e', code, path.join(app, 'package.json'), importScope], { timeout: 5000, maxBuffer: 1024 * 1024, env });
|
|
93
|
+
return JSON.parse(stdout);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
async function installedPackage(app, key, importScope, resolved) {
|
|
97
|
+
// Read the currently linked manifest directly rather than using Node's
|
|
98
|
+
// cached module resolution. pnpm can replace its version symlink while this
|
|
99
|
+
// MCP remains alive; a cached realpath would describe the old package.
|
|
100
|
+
const modules = await realpath(path.join(app, 'node_modules'));
|
|
101
|
+
const directory = await realpath(path.join(modules, importScope, key));
|
|
102
|
+
if (!directory.startsWith(`${modules}${path.sep}`)) throw new Error('package points outside project node_modules');
|
|
103
|
+
if (typeof resolved !== 'string') throw new Error(`cannot resolve ${key} package export`);
|
|
104
|
+
const entry = await realpath(resolved);
|
|
105
|
+
if (!entry.startsWith(`${directory}${path.sep}`)) throw new Error('package export points outside installed package');
|
|
106
|
+
const manifest = await boundedJson(path.join(directory, 'package.json'));
|
|
107
|
+
if (typeof manifest.name !== 'string' || typeof manifest.version !== 'string') throw new Error(`cannot find ${key} package manifest`);
|
|
108
|
+
return { name: manifest.name, version: manifest.version };
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
async function installedStatus(projectRoot, metadata) {
|
|
112
|
+
let receipt;
|
|
113
|
+
try { receipt = await boundedJson(path.join(projectRoot, '.vini-ds/npm-install.json')); }
|
|
114
|
+
catch (error) {
|
|
115
|
+
if (error.code === 'ENOENT') return { status: 'not-configured', reason: 'VINi npm receipt not found' };
|
|
116
|
+
return { status: 'unknown', reason: 'VINi npm receipt could not be read' };
|
|
117
|
+
}
|
|
118
|
+
try {
|
|
119
|
+
if (receipt.installer !== 'vini-npm' || !receipt.distribution || typeof receipt.appRoot !== 'string') throw new Error('unsupported receipt');
|
|
120
|
+
const root = await realpath(projectRoot), app = await realpath(path.resolve(root, receipt.appRoot));
|
|
121
|
+
if (app !== root && !app.startsWith(`${root}${path.sep}`)) throw new Error('app root is outside project');
|
|
122
|
+
const expected = receipt.distribution;
|
|
123
|
+
// This implementation uses the receipt to select the installed paths. If
|
|
124
|
+
// its metadata is stale, it can distinguish that from a receipt mismatch.
|
|
125
|
+
// Previously published MCP implementations do not acquire this behavior.
|
|
126
|
+
const dsFamily = keys.every(key => expected[key] === `@vini-ds/${key}`);
|
|
127
|
+
if (!dsFamily && keys.some(key => expected[key] === `@vini-ds/${key}`)) throw new Error('mixed VINi package families');
|
|
128
|
+
const importScope = dsFamily ? '@vini-ds' : '@vini';
|
|
129
|
+
const resolved = await resolveEntries(app, importScope);
|
|
130
|
+
const packages = Object.fromEntries(await Promise.all(keys.map(async (key) => {
|
|
131
|
+
try { return [key, await installedPackage(app, key, importScope, resolved[key])]; }
|
|
132
|
+
catch { return [key, { error: 'not-installed-or-unreadable' }]; }
|
|
133
|
+
})));
|
|
134
|
+
const matchesReceipt = keys.every((key) => packages[key].name === expected[key] && packages[key].version === expected.version);
|
|
135
|
+
const contextKnown = contextIsConsistent(metadata);
|
|
136
|
+
const matchesContext = contextKnown && keys.every((key) => packages[key].name === metadata.packages[key].name && packages[key].version === metadata.version);
|
|
137
|
+
return { status: matchesReceipt && matchesContext ? 'matched' : 'mismatch', packages,
|
|
138
|
+
receipt: { version: expected.version, ui: expected.ui, tokens: expected.tokens, agent: expected.agent },
|
|
139
|
+
context: { ...contextDistribution(metadata), metadataStatus: contextKnown ? 'consistent' : 'incomplete-or-inconsistent', baseline: metadata.baseline, ...(metadata.viniRelease ? { viniRelease: metadata.viniRelease } : {}) },
|
|
140
|
+
matchesReceipt, matchesContext,
|
|
141
|
+
...(matchesReceipt && matchesContext ? {} : { mismatchKind: !matchesReceipt ? 'package-receipt' : contextKnown ? 'mcp-context' : 'context-unverified' }) };
|
|
142
|
+
} catch { return { status: 'unknown', reason: 'Installed package manifests or receipt could not be verified' }; }
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
async function registryJson(name, version) {
|
|
146
|
+
const response = await fetch(`${registry}/${encodeURIComponent(name)}/${encodeURIComponent(version)}`, {
|
|
147
|
+
headers: { accept: 'application/json' }, redirect: 'error', signal: AbortSignal.timeout(5000),
|
|
148
|
+
});
|
|
149
|
+
if (!response.ok) throw new Error(`registry returned ${response.status}`);
|
|
150
|
+
const length = Number(response.headers.get('content-length'));
|
|
151
|
+
if (Number.isFinite(length) && length > 2 * 1024 * 1024) throw new Error('registry metadata too large');
|
|
152
|
+
const reader = response.body.getReader(), chunks = []; let total = 0;
|
|
153
|
+
while (true) {
|
|
154
|
+
const { done, value } = await reader.read(); if (done) break;
|
|
155
|
+
total += value.length; if (total > 2 * 1024 * 1024) { await reader.cancel(); throw new Error('registry metadata too large'); }
|
|
156
|
+
chunks.push(value);
|
|
157
|
+
}
|
|
158
|
+
return JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// Optional fetchJson is a test seam; the installed server always uses npm HTTPS.
|
|
162
|
+
export async function checkUpdates(metadata, { projectRoot = process.cwd(), fetchJson = registryJson, target } = {}) {
|
|
163
|
+
const selected = target === undefined ? null : validateSelectedTarget(target);
|
|
164
|
+
const installed = await installedStatus(projectRoot, metadata);
|
|
165
|
+
let available;
|
|
166
|
+
try {
|
|
167
|
+
const cli = await fetchJson('vini-ds', 'latest'), distribution = cli.viniDistribution;
|
|
168
|
+
if (cli.name !== 'vini-ds' || !exactVersion.test(cli.version ?? '') || !/^sha512-[A-Za-z0-9+/]+={0,2}$/u.test(cli.dist?.integrity ?? '') || !distribution || distribution.version !== cli.version ||
|
|
169
|
+
!keys.every((key) => packageName.test(distribution[key] ?? ''))) {
|
|
170
|
+
throw new Error('latest CLI does not describe a compatible exact package set');
|
|
171
|
+
}
|
|
172
|
+
// A consistent installation and receipt identify the project even when
|
|
173
|
+
// this server's context is stale. Otherwise use only this server's context
|
|
174
|
+
// as the family reference; never treat a broken receipt as authoritative.
|
|
175
|
+
const reference = installed.matchesReceipt ? installed.receipt : contextDistribution(metadata);
|
|
176
|
+
const familyTransition = targetFamily(reference, distribution);
|
|
177
|
+
const manifests = Object.fromEntries(await Promise.all(keys.map(async (key) => [key, await fetchJson(distribution[key], distribution.version)])));
|
|
178
|
+
const dsFamily = keys.every(key => distribution[key] === `@vini-ds/${key}`);
|
|
179
|
+
if (!dsFamily && keys.some(key => distribution[key] === `@vini-ds/${key}`)) throw new Error('mixed VINi package families');
|
|
180
|
+
for (const key of keys) {
|
|
181
|
+
const manifest = manifests[key];
|
|
182
|
+
if (manifest.name !== distribution[key] || manifest.version !== distribution.version || !/^sha512-[A-Za-z0-9+/]+={0,2}$/u.test(manifest.dist?.integrity ?? '')) {
|
|
183
|
+
throw new Error(`registry metadata for ${key} does not match the selected release`);
|
|
184
|
+
}
|
|
185
|
+
if (dsFamily && ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies'].some(section =>
|
|
186
|
+
Object.values(manifest[section] ?? {}).some(value => typeof value === 'string' && value.trim().startsWith('npm:')))) {
|
|
187
|
+
throw new Error('native VINi DS package metadata contains an npm alias');
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
if (!isDeepStrictEqual(cli.viniRelease ?? null, manifests.agent.viniRelease ?? null)) {
|
|
191
|
+
throw new Error('agent and CLI release metadata differ');
|
|
192
|
+
}
|
|
193
|
+
if (cli.viniRelease !== undefined && !validRelease(cli.viniRelease)) throw new Error('invalid release metadata');
|
|
194
|
+
const tokenImport = dsFamily ? '@vini-ds/tokens' : '@vini/tokens';
|
|
195
|
+
if (dsFamily && ['dependencies', 'peerDependencies', 'optionalDependencies'].some(section => Object.hasOwn(manifests.ui[section] ?? {}, '@vini/tokens'))) {
|
|
196
|
+
throw new Error('UI package does not select the matching token package');
|
|
197
|
+
}
|
|
198
|
+
const tokenDependency = manifests.ui.dependencies?.[tokenImport];
|
|
199
|
+
const tokenPeer = manifests.ui.peerDependencies?.[tokenImport];
|
|
200
|
+
const tokenOptional = manifests.ui.optionalDependencies?.[tokenImport];
|
|
201
|
+
const nativeTokens = distribution.tokens === tokenImport;
|
|
202
|
+
if (tokenOptional !== undefined || manifests.ui.peerDependenciesMeta?.[tokenImport]?.optional === true || (nativeTokens
|
|
203
|
+
? tokenPeer !== distribution.version || (tokenDependency !== undefined && tokenDependency !== distribution.version)
|
|
204
|
+
: tokenDependency !== `npm:${distribution.tokens}@${distribution.version}` || (tokenPeer !== undefined && tokenPeer !== distribution.version))) {
|
|
205
|
+
throw new Error('UI package does not select the matching token package');
|
|
206
|
+
}
|
|
207
|
+
const fromVersion = installed.matchesReceipt ? installed.receipt.version : null;
|
|
208
|
+
const changes = cli.viniRelease?.changes;
|
|
209
|
+
const comparison = fromVersion === null ? null : compareVersions(fromVersion, distribution.version);
|
|
210
|
+
available = { status: 'verified-metadata', registry, version: distribution.version, packages: distribution, cliIntegrity: cli.dist.integrity,
|
|
211
|
+
integrity: Object.fromEntries(keys.map((key) => [key, manifests[key].dist.integrity])),
|
|
212
|
+
familyTransition,
|
|
213
|
+
matchesInstalled: installed.matchesReceipt ? comparison === 0 && sameNames(installed.receipt, distribution) : null,
|
|
214
|
+
matchesContext: contextIsConsistent(metadata) ? equalsRelease(contextDistribution(metadata), distribution) : null,
|
|
215
|
+
...(cli.viniRelease ? { viniRelease: cli.viniRelease } : {}),
|
|
216
|
+
changes: changes?.fromVersion === fromVersion ? changes : { status: 'not-available-for-installed-version' },
|
|
217
|
+
relation: comparison === null ? 'unknown' : comparison === 0 ? 'same' : comparison < 0 ? 'newer' : 'older' };
|
|
218
|
+
} catch (error) { available = { status: 'unavailable-or-unverified', registry, reason: error.message }; }
|
|
219
|
+
const installedKnown = installed.packages && keys.every(key => typeof installed.packages[key]?.name === 'string' && typeof installed.packages[key]?.version === 'string');
|
|
220
|
+
const selectedTarget = selected ? { status: 'provided', ...selected,
|
|
221
|
+
matchesInstalled: installedKnown ? keys.every(key => installed.packages[key].name === selected[key] && installed.packages[key].version === selected.version) : null,
|
|
222
|
+
matchesReceipt: installed.receipt ? equalsRelease(installed.receipt, selected) : null,
|
|
223
|
+
matchesContext: contextIsConsistent(metadata) ? equalsRelease(contextDistribution(metadata), selected) : null,
|
|
224
|
+
matchesLatest: available.status === 'verified-metadata' ? equalsRelease(available.packages, selected) : null,
|
|
225
|
+
verification: 'caller-supplied-not-independently-verified' } : { status: 'not-provided' };
|
|
226
|
+
const nextStep = installed.mismatchKind === 'mcp-context' ?
|
|
227
|
+
'Installed packages match the receipt, but this MCP context does not match them. Reconnect the project VINi MCP once in this client. If reconnect is unavailable or was already attempted and the context remains stale, fully quit and reopen this specific client. Then read vini://system/current and the affected component contract and run check_updates again through the same client. Do not repair packages based on the old context alone.' :
|
|
228
|
+
installed.mismatchKind === 'context-unverified' ?
|
|
229
|
+
'Installed packages match the receipt, but this MCP context metadata is incomplete or inconsistent. Reconnect the project VINi MCP once in this client. If reconnect is unavailable or was already attempted and the context remains unverified, fully quit and reopen this specific client. Then read vini://system/current and the affected component contract and run check_updates again through the same client. Do not repair packages based on this context alone.' :
|
|
230
|
+
installed.status === 'mismatch' ? 'Inspect the installed package names, versions and receipt before changing the setup; the mismatch alone does not establish which is wrong.' :
|
|
231
|
+
selected && installed.status === 'matched' && selectedTarget.matchesInstalled && selectedTarget.matchesContext ?
|
|
232
|
+
'Installed package manifests and this MCP context match the caller-selected target. Verify vini://system/current, the affected component contract and check_updates through the same client; a standalone STDIO check does not establish client verification. Registry latest is a separate result, and an unavailable registry does not mean there is no update.' :
|
|
233
|
+
selected && installed.status === 'matched' && !selectedTarget.matchesInstalled ?
|
|
234
|
+
'The caller-selected target differs from the installed package set. Verify the exact target and review the applicable update plan before any change; registry latest is a separate result.' :
|
|
235
|
+
available.status !== 'verified-metadata' ? 'Registry metadata could not be verified; retry later. This does not mean there is no update.' :
|
|
236
|
+
installed.status !== 'matched' ? 'Check the project npm setup before selecting an update.' :
|
|
237
|
+
available.relation === 'same' ? 'The installed package set matches this CLI release.' :
|
|
238
|
+
available.relation === 'older' ? 'The installed package set is newer than the latest CLI release; no downgrade is proposed.' :
|
|
239
|
+
available.familyTransition === 'manual-import-migration' ? `Review npx vini-ds@${available.version} update --plan and migrate the project imports and configuration before explicitly updating; then reconnect the project MCP in the current client.` :
|
|
240
|
+
`Review npx vini-ds@${available.version} update --plan, then run the exact update and reconnect the project MCP in the current client.`;
|
|
241
|
+
const status = installed.status === 'not-configured' ? 'not-installed' : installed.status === 'mismatch' ? 'mismatch' :
|
|
242
|
+
installed.status !== 'matched' || available.status !== 'verified-metadata' ? 'unknown' : available.relation === 'same' ? 'current' : available.relation === 'older' ? 'ahead-of-latest' : 'update-available';
|
|
243
|
+
return { status, statusScope: 'package-context-and-registry-latest', installed, available, target: selectedTarget, nextStep, readOnly: true, installationChanged: false,
|
|
244
|
+
limitations: ['npm metadata discovery does not verify tarball bytes or product behavior', 'client-session verification requires current, the affected component contract, and check_updates in that same client; standalone STDIO does not verify it'] };
|
|
245
|
+
}
|
package/README.md
DELETED