@craft_eco/craft-mcp 0.1.34-beta.2 → 0.1.34-beta.4
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/README.md +6 -17
- package/bin/craft-mcp.mjs +30 -2
- package/dist-server/core/upload-limits.mjs +11 -0
- package/dist-server/game-workflow/bundle-files.mjs +6 -1
- package/dist-server/game-workflow/engines.mjs +18 -9
- package/dist-server/game-workflow/project-context.mjs +11 -7
- package/dist-server/game-workflow/project-install.mjs +17 -8
- package/dist-server/game-workflow/projects.mjs +13 -3
- package/dist-server/integrations/config.mjs +41 -18
- package/dist-server/integrations/connect.mjs +18 -9
- package/dist-server/integrations/connection-handoff.mjs +9 -8
- package/dist-server/integrations/distribution-targets.mjs +9 -0
- package/dist-server/integrations/dsh-config.mjs +30 -14
- package/dist-server/integrations/fixed-launcher.mjs +1 -0
- package/dist-server/integrations/host-config-scope.mjs +4 -3
- package/dist-server/integrations/hosts.mjs +3 -1
- package/dist-server/integrations/install.mjs +147 -43
- package/dist-server/integrations/installation-state.mjs +2 -1
- package/dist-server/integrations/instance-skill.mjs +26 -0
- package/dist-server/integrations/instance.mjs +29 -0
- package/dist-server/integrations/launcher-start.mjs +6 -6
- package/dist-server/integrations/login-task-command.mjs +3 -3
- package/dist-server/integrations/opencode-config.mjs +13 -6
- package/dist-server/integrations/project-setup.mjs +48 -18
- package/dist-server/integrations/runtime-candidate.mjs +32 -6
- package/dist-server/integrations/runtime-file-diagnostics.mjs +68 -0
- package/dist-server/integrations/runtime-gc.mjs +8 -2
- package/dist-server/integrations/runtime-identity.mjs +56 -8
- package/dist-server/integrations/runtime.mjs +7 -3
- package/dist-server/integrations/uninstall.mjs +160 -0
- package/dist-server/integrations/updates.mjs +57 -42
- package/dist-server/launcher.mjs +65 -10
- package/dist-server/mcp/production-events.mjs +52 -29
- package/dist-server/mcp/server.mjs +18 -9
- package/dist-server/mcp/update-session.mjs +9 -6
- package/dist-server/preview/preview-snapshot.mjs +3 -2
- package/package.json +5 -3
- package/resources/craft-create/SKILL.md +2 -0
- package/resources/craft-update/SKILL.md +2 -0
- package/vendor/craft-runtime/NOTICE.md +1 -1
- package/vendor/craft-runtime/SOURCE.json +9 -5
- package/vendor/craft-runtime/index.js +228 -164
- package/vendor/craft-runtime/package.json +1 -1
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { validateServerId } from './instance.mjs';
|
|
2
|
+
|
|
3
|
+
export function instanceSkillName(logicalName, serverId = 'craft') {
|
|
4
|
+
validateServerId(serverId);
|
|
5
|
+
if (!['craft-create', 'craft-update'].includes(logicalName)) throw new Error('Unknown Craft entrypoint Skill');
|
|
6
|
+
return serverId + logicalName.slice('craft'.length);
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
// Always render from this runtime's original template, including on update and
|
|
10
|
+
// uninstall. Default installations must still match their installed bytes.
|
|
11
|
+
export function renderInstanceSkill(content, logicalName, serverId = 'craft') {
|
|
12
|
+
const name = instanceSkillName(logicalName, serverId);
|
|
13
|
+
if (serverId === 'craft' || content == null) return content;
|
|
14
|
+
const header = /^---\r?\n([\s\S]*?)\r?\n---(?=\r?\n)/.exec(content);
|
|
15
|
+
if (!header || !header[1].split(/\r?\n/).includes('name: ' + logicalName)) {
|
|
16
|
+
throw new Error('Invalid packaged Skill frontmatter for ' + logicalName);
|
|
17
|
+
}
|
|
18
|
+
const action = logicalName === 'craft-create' ? '创建、继续或上传游戏' : '检查和更新安装';
|
|
19
|
+
const description = '仅在用户指定 ' + serverId + ',或当前项目已绑定其渠道和工作区时,使用该实例' + action + '。';
|
|
20
|
+
const frontmatter = header[1].replace(/^name: .*$/m, 'name: ' + name)
|
|
21
|
+
.replace(/^description: .*$/m, 'description: ' + description);
|
|
22
|
+
return '---\n' + frontmatter + '\n---\n\n'
|
|
23
|
+
+ '本入口对应 MCP 服务 `' + serverId + '`。发现该服务的工具,调用其 `craft_game_info` 核对 server_id、渠道和工作区。'
|
|
24
|
+
+ '后续制作、上传、轮询、更新及重连均使用这条连接。\n'
|
|
25
|
+
+ content.slice(header[0].length);
|
|
26
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
export function validateServerId(id) {
|
|
4
|
+
if (typeof id !== 'string' || id.length > 32 || !/^craft(?:-[a-z0-9]+(?:-[a-z0-9]+)*)?$/.test(id)) {
|
|
5
|
+
throw new Error('Invalid Craft instance name; use craft or craft-<lowercase-identifier> (up to 32 characters)');
|
|
6
|
+
}
|
|
7
|
+
return id;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export function serverIdForChannel(channel) {
|
|
11
|
+
if (channel === undefined || channel === 'stable' || channel === 'latest') return 'craft';
|
|
12
|
+
if (typeof channel !== 'string' || !/^[a-zA-Z][a-zA-Z0-9._-]*$/.test(channel)) throw new Error('Update channel must be an npm dist-tag');
|
|
13
|
+
const simple = 'craft-' + channel;
|
|
14
|
+
if (simple.length <= 32 && /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(channel)) return simple;
|
|
15
|
+
// Host server names (including DSH) have a common limit of 32. Retain
|
|
16
|
+
// distinct case-sensitive tags when the tag cannot be used verbatim.
|
|
17
|
+
const prefix = channel.toLowerCase().replace(/[^a-z0-9]+/g, '-').slice(0, 13).replace(/-$/, '');
|
|
18
|
+
return 'craft-' + prefix + '-' + createHash('sha256').update(channel).digest('hex').slice(0, 12);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// An unmarked renamed Craft registration belongs to the legacy default slot.
|
|
22
|
+
// Managed named instances identify themselves even when several share a host.
|
|
23
|
+
export function registrationsForInstance(registrations, serverId) {
|
|
24
|
+
return registrations.filter(({ name, connection }) => {
|
|
25
|
+
const marker = connection?.env?.CRAFT_SERVER_ID;
|
|
26
|
+
if (marker !== undefined && marker !== name && (marker === serverId || name === serverId)) throw new Error('Craft instance marker differs from its registration: ' + name);
|
|
27
|
+
return marker === undefined ? serverId === 'craft' : marker === serverId;
|
|
28
|
+
});
|
|
29
|
+
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// Bundled into a self-contained file. No versioned dependency is loaded before
|
|
2
|
-
// the installation lock is held and the selected package
|
|
2
|
+
// the installation lock is held and the selected package receipt is checked.
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
import { pathToFileURL } from 'node:url';
|
|
5
5
|
import { readFile, mkdir, writeFile, unlink } from 'node:fs/promises';
|
|
@@ -7,7 +7,7 @@ import { unlinkSync } from 'node:fs';
|
|
|
7
7
|
import { randomUUID } from 'node:crypto';
|
|
8
8
|
import lockfile from 'proper-lockfile';
|
|
9
9
|
import { readInstallation, sameRuntimeIdentity } from './installation-state.mjs';
|
|
10
|
-
import {
|
|
10
|
+
import { readRunningIdentity } from './runtime-identity.mjs';
|
|
11
11
|
import { assertPlainPath } from './files.mjs';
|
|
12
12
|
import { verifyLauncher, launcherPath } from './fixed-launcher.mjs';
|
|
13
13
|
|
|
@@ -31,15 +31,15 @@ async function start() {
|
|
|
31
31
|
if (state.host === 'workbuddy' && state.login_data_dir && process.env.CRAFT_STANDALONE_PROBE !== '1') {
|
|
32
32
|
process.env.CLIENT_DATA_DIR ||= state.login_data_dir;
|
|
33
33
|
}
|
|
34
|
-
for (const [key, expected] of Object.entries({ CRAFT_CLIENT_IDE: state.host, CLIENT_WORKSPACE_ROOT: state.workspace, CRAFT_WEB_URL: state.platform })) {
|
|
34
|
+
for (const [key, expected] of Object.entries({ CRAFT_CLIENT_IDE: state.host, CRAFT_SERVER_ID: state.server_id, CLIENT_WORKSPACE_ROOT: state.workspace, CRAFT_WEB_URL: state.platform })) {
|
|
35
35
|
if (process.env[key] && process.env[key] !== expected) throw new Error('Craft launcher scope mismatch: ' + key);
|
|
36
36
|
process.env[key] = expected;
|
|
37
37
|
}
|
|
38
38
|
const relative = path.relative(path.resolve(state.runtime_root), state.target.package_root);
|
|
39
39
|
if (!relative || relative === '..' || relative.startsWith('..' + path.sep) || path.isAbsolute(relative)) throw new Error('Craft target is outside the managed runtime root');
|
|
40
40
|
await assertPlainPath(state.target.entry);
|
|
41
|
-
identity = await
|
|
42
|
-
if (!sameRuntimeIdentity(identity, state.target)) throw new Error('Craft target
|
|
41
|
+
identity = await readRunningIdentity(state.target.package_root, { managed: true });
|
|
42
|
+
if (!sameRuntimeIdentity(identity, state.target)) throw new Error('Craft target and installed runtime identity differ; run doctor for the selected instance');
|
|
43
43
|
const leaseRoot = path.join(state.runtime_root, '.connections');
|
|
44
44
|
await mkdir(leaseRoot, { recursive: true });
|
|
45
45
|
lease = path.join(leaseRoot, 'launcher-' + randomUUID() + '.json');
|
|
@@ -53,7 +53,7 @@ async function start() {
|
|
|
53
53
|
const targetEntry = preview ? path.join(identity.package_root, 'dist-server/preview/workbuddy-preview-task-worker.mjs') :
|
|
54
54
|
loginPage ? path.join(identity.package_root, 'dist-server/mcp/workbuddy-login-task-worker.mjs') : identity.entry;
|
|
55
55
|
process.argv = [process.execPath, targetEntry, ...(loginPage || preview ? [installationFile] : process.argv.slice(2))];
|
|
56
|
-
try { await import(pathToFileURL(targetEntry).href); }
|
|
56
|
+
try { await assertPlainPath(targetEntry); await import(pathToFileURL(targetEntry).href); }
|
|
57
57
|
catch (error) { await unlink(lease).catch(() => {}); throw error; }
|
|
58
58
|
}
|
|
59
59
|
|
|
@@ -4,12 +4,12 @@ import { ensureWorkBuddyLoginTask, removeWorkBuddyLoginTask, ensureWorkBuddyPrev
|
|
|
4
4
|
|
|
5
5
|
export async function runLoginTaskCommand([command, action, ...args]) {
|
|
6
6
|
const preview = command === 'preview-task';
|
|
7
|
-
const usage = `Use ${preview ? 'preview' : 'login'}-task --setup|--remove --ide workbuddy [--host-config ABS]`;
|
|
7
|
+
const usage = `Use ${preview ? 'preview' : 'login'}-task --setup|--remove --ide workbuddy [--host-config ABS] [--instance NAME]`;
|
|
8
8
|
const options = {};
|
|
9
9
|
for (let i = 0; i < args.length; i += 2) {
|
|
10
10
|
const key = args[i];
|
|
11
11
|
const value = args[i + 1];
|
|
12
|
-
if (!['--ide', '--host-config'].includes(key) || !value || value.startsWith('--') || Object.hasOwn(options,key.slice(2))) {
|
|
12
|
+
if (!['--ide', '--host-config', '--instance'].includes(key) || !value || value.startsWith('--') || Object.hasOwn(options,key.slice(2))) {
|
|
13
13
|
throw new Error(usage);
|
|
14
14
|
}
|
|
15
15
|
options[key.slice(2)] = value;
|
|
@@ -17,7 +17,7 @@ export async function runLoginTaskCommand([command, action, ...args]) {
|
|
|
17
17
|
if (!['--setup', '--remove'].includes(action) || options.ide !== 'workbuddy') {
|
|
18
18
|
throw new Error(usage);
|
|
19
19
|
}
|
|
20
|
-
const { installation } = await installedConnection('workbuddy', {hostOptions: hostCommandOptions(options), env: {}});
|
|
20
|
+
const { installation } = await installedConnection('workbuddy', {serverId: options.instance, hostOptions: hostCommandOptions(options), env: {}});
|
|
21
21
|
const setup = preview ? ensureWorkBuddyPreviewTask : ensureWorkBuddyLoginTask;
|
|
22
22
|
const remove = preview ? removeWorkBuddyPreviewTask : removeWorkBuddyLoginTask;
|
|
23
23
|
const result = action === '--setup' ? await setup(installation) : await remove(installation);
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { isDeepStrictEqual } from 'node:util';
|
|
2
2
|
import { hasCraftConnectionIdentity } from './registration-identity.mjs';
|
|
3
|
-
import { readJsonc, updateJsoncEntry } from './jsonc-config.mjs';
|
|
3
|
+
import { readJsonc, updateJsonc, updateJsoncEntry } from './jsonc-config.mjs';
|
|
4
4
|
|
|
5
5
|
const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
6
6
|
const reserved = new Set(['servers', 'timeout']);
|
|
@@ -55,12 +55,19 @@ export function openCodeConfig(text, name = 'craft') {
|
|
|
55
55
|
return normalizeOpenCodeConnection(found[0]?.raw);
|
|
56
56
|
}
|
|
57
57
|
|
|
58
|
-
export function
|
|
58
|
+
export function removeOpenCodeConfig(text, serverId) {
|
|
59
|
+
openCodeRegistrations(text);
|
|
60
|
+
const matches = entries(readOpenCodeConfig(text)).filter(entry => entry.name === serverId);
|
|
61
|
+
if (matches.length > 1) throw new Error('Ambiguous OpenCode MCP registration: ' + serverId);
|
|
62
|
+
return matches.length ? updateJsonc(text, [{ path: [...matches[0].table, serverId], value: undefined }]) : text;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function mergeOpenCodeConfig(text, connection, { serverId = 'craft', previousName = serverId, enable = true } = {}) {
|
|
59
66
|
const config = readOpenCodeConfig(text);
|
|
60
67
|
openCodeRegistrations(text);
|
|
61
68
|
const all = entries(config), existing = all.filter(entry => entry.name === previousName);
|
|
62
69
|
if (existing.length > 1) throw new Error('Ambiguous OpenCode MCP registration: ' + previousName);
|
|
63
|
-
if (previousName !==
|
|
70
|
+
if (previousName !== serverId && all.some(entry => entry.name === serverId)) throw new Error('Craft installation conflicts with an existing ' + serverId + ' registration');
|
|
64
71
|
const entry = existing[0];
|
|
65
72
|
if (entry && !object(entry.raw)) throw new Error('Invalid craft server entry');
|
|
66
73
|
// Existing V1 files remain V1; native or empty files use V2. Never migrate
|
|
@@ -83,12 +90,12 @@ export function mergeOpenCodeConfig(text, connection, { previousName = 'craft',
|
|
|
83
90
|
if (typeof connection.timeout === 'number') next.timeout = connection.timeout;
|
|
84
91
|
else if (object(connection.timeout) && typeof connection.timeout.startup === 'number') next.timeout = connection.timeout.startup;
|
|
85
92
|
}
|
|
86
|
-
const output = updateJsoncEntry(text, table,
|
|
93
|
+
const output = updateJsoncEntry(text, table, serverId, previous, next, { previousName });
|
|
87
94
|
const after = readOpenCodeConfig(output), expected = structuredClone(config);
|
|
88
95
|
let target = expected;
|
|
89
96
|
for (const key of table) { target[key] ??= {}; target = target[key]; }
|
|
90
|
-
if (previousName !==
|
|
91
|
-
target
|
|
97
|
+
if (previousName !== serverId) delete target[previousName];
|
|
98
|
+
target[serverId] = next;
|
|
92
99
|
if (!isDeepStrictEqual(after, expected)) throw new Error('OpenCode merge changed unrelated settings; config was preserved');
|
|
93
100
|
return output;
|
|
94
101
|
}
|
|
@@ -15,15 +15,17 @@ import { safeProjectFile } from '../game-workflow/asset-import.mjs';
|
|
|
15
15
|
import { engineDefinition } from '../game-workflow/engines.mjs';
|
|
16
16
|
import { verifyBundle } from '../game-workflow/bundle-files.mjs';
|
|
17
17
|
import { assertHostConfigScope } from './host-config-scope.mjs';
|
|
18
|
+
import { registrationsForInstance, validateServerId } from './instance.mjs';
|
|
19
|
+
import { internalRegistryArgs } from './distribution-targets.mjs';
|
|
18
20
|
|
|
19
21
|
const samePath = (left, right) => typeof left === 'string' && typeof right === 'string' &&
|
|
20
22
|
(process.platform === 'win32' ? path.resolve(left).toLowerCase() === path.resolve(right).toLowerCase() : path.resolve(left) === path.resolve(right));
|
|
21
23
|
|
|
22
|
-
function connectionRequirements(project, ide, manifest) {
|
|
24
|
+
function connectionRequirements(project, ide, manifest, serverId) {
|
|
23
25
|
return {
|
|
24
26
|
status: 'unverified', trust: 'unknown', source: 'current_host_session',
|
|
25
27
|
tool: 'craft_game_info', arguments: { name: path.basename(project) },
|
|
26
|
-
expected: { host: ide, workspace: path.dirname(project), project, engine: manifest.engine,
|
|
28
|
+
expected: { host: ide, server_id: serverId, channel: manifest.channel, workspace: path.dirname(project), project, engine: manifest.engine,
|
|
27
29
|
platform: manifest.platform, minimum_version: manifest.minimum_mcp_version },
|
|
28
30
|
instructions: 'Discover Craft tools using the host tool catalog, including deferred tools and their actual names. Call craft_game_info in this host session and verify version/build_id, active_verified, host, workspace, platform and project. An installation receipt or standalone doctor does not confirm this connection. After verification call craft_game_prepare(mode=resume) with a new request_key, then reread the project entrypoints and Skill index.',
|
|
29
31
|
reconnect: hostReloadProfile(ide),
|
|
@@ -32,8 +34,10 @@ function connectionRequirements(project, ide, manifest) {
|
|
|
32
34
|
|
|
33
35
|
function bootstrapCommand(project, ide, manifest, paths, hostOptions) {
|
|
34
36
|
return { command: 'npx', args: ['-y', '--registry=' + manifest.registry,
|
|
37
|
+
...internalRegistryArgs(manifest.package_name),
|
|
35
38
|
manifest.package_name + '@' + manifest.minimum_mcp_version,
|
|
36
39
|
'project-setup', '--project', project, '--ide', ide,
|
|
40
|
+
...(hostOptions.serverId ? ['--instance', hostOptions.serverId] : []),
|
|
37
41
|
...(hosts[ide].explicitConfig || hostOptions.configPath || hostOptions.hostConfigs?.[ide] ? ['--host-config',paths.config] : []),
|
|
38
42
|
...(ide==='trae' ? ['--trae-region',hostOptions.traeRegion??'global'] : [])] };
|
|
39
43
|
}
|
|
@@ -49,8 +53,8 @@ async function validateGame(project, manifest) {
|
|
|
49
53
|
return readContextLock(project, manifest.engine);
|
|
50
54
|
}
|
|
51
55
|
|
|
52
|
-
async function readHostRegistration(paths, ide) {
|
|
53
|
-
await assertHostConfigScope(paths.config,ide,paths.configPeers);
|
|
56
|
+
async function readHostRegistration(paths, ide, serverId) {
|
|
57
|
+
await assertHostConfigScope(paths.config,ide,paths.configPeers,serverId);
|
|
54
58
|
await assertPlainPath(paths.config);
|
|
55
59
|
let content = await optionalFile(paths.config) ?? '';
|
|
56
60
|
if (paths.fallbackConfig) {
|
|
@@ -60,7 +64,7 @@ async function readHostRegistration(paths, ide) {
|
|
|
60
64
|
return craftRegistrations(content, ide);
|
|
61
65
|
}
|
|
62
66
|
|
|
63
|
-
async function projectRegistration(project, ide) {
|
|
67
|
+
async function projectRegistration(project, ide, serverId) {
|
|
64
68
|
const candidates = {
|
|
65
69
|
codex: ['.codex/config.toml'], workbuddy: ['.workbuddy/mcp.json'],
|
|
66
70
|
cursor: ['.cursor/mcp.json'], codebuddy: ['.codebuddy/.mcp.json', '.codebuddy/mcp.json'],
|
|
@@ -73,20 +77,26 @@ async function projectRegistration(project, ide) {
|
|
|
73
77
|
const config = path.join(project, relative);
|
|
74
78
|
await assertPlainPath(config);
|
|
75
79
|
const content = await optionalFile(config);
|
|
76
|
-
if (content
|
|
80
|
+
if (content === null) continue;
|
|
81
|
+
const registrations = craftRegistrations(content, ide);
|
|
82
|
+
if ((serverId === undefined ? registrations : registrationsForInstance(registrations, serverId)).length) return config;
|
|
77
83
|
}
|
|
78
84
|
return null;
|
|
79
85
|
}
|
|
80
86
|
|
|
81
87
|
// This command inspects configuration only. It cannot observe host trust,
|
|
82
88
|
// deferred-tool discovery, or the connection attached to the user's chat.
|
|
83
|
-
export async function setupProject({ project, ide, packageRoot, install = false,
|
|
89
|
+
export async function setupProject({ project, ide, packageRoot, install = false, serverId,
|
|
84
90
|
home = os.homedir(), codexHome, hostOptions = {}, runtimeRoot, stateRoot,
|
|
85
91
|
installer = installHosts } = {}) {
|
|
86
92
|
if (!Object.hasOwn(hosts, ide ?? '')) throw new Error('--ide must select exactly one supported host');
|
|
87
93
|
if (typeof project !== 'string' || !path.isAbsolute(project)) throw new Error('--project must be an absolute existing Craft game directory');
|
|
88
94
|
if (typeof packageRoot !== 'string' || !path.isAbsolute(packageRoot)) throw new Error('Craft packageRoot must be absolute');
|
|
89
95
|
if (typeof install !== 'boolean') throw new Error('--install is a boolean flag');
|
|
96
|
+
if (serverId !== undefined) {
|
|
97
|
+
validateServerId(serverId);
|
|
98
|
+
hostOptions = { ...hostOptions, serverId };
|
|
99
|
+
}
|
|
90
100
|
project = path.resolve(project);
|
|
91
101
|
const stat = await lstat(project);
|
|
92
102
|
const canonicalProject = await realpath(project);
|
|
@@ -102,19 +112,23 @@ export async function setupProject({ project, ide, packageRoot, install = false,
|
|
|
102
112
|
if (!manifest) return { ...base, status: 'missing_project_install_metadata',
|
|
103
113
|
next: 'Use the original verified Craft connection to prepare(mode=resume) and save project-install.json. If that connection is unavailable, recover the project platform and package source explicitly; do not guess a platform or install into the default workspace.' };
|
|
104
114
|
const lock = await validateGame(project, manifest);
|
|
105
|
-
const verification = connectionRequirements(project, ide, manifest);
|
|
115
|
+
const verification = connectionRequirements(project, ide, manifest, serverId);
|
|
106
116
|
const expected = { engine: manifest.engine, workspace: path.dirname(project), platform: manifest.platform,
|
|
107
117
|
registry: manifest.registry, channel: manifest.channel, minimum_version: manifest.minimum_mcp_version };
|
|
108
118
|
const response = { ...base, expected, verification };
|
|
109
|
-
const localConfig = await projectRegistration(project, ide);
|
|
119
|
+
const localConfig = await projectRegistration(project, ide, serverId);
|
|
110
120
|
if (localConfig) return { ...response, status: 'project_configuration_unverified', project_config: localConfig,
|
|
111
121
|
next: 'A project-scoped Craft registration exists. Verify its effective configuration, trust and actual connection in the host before considering a user-level installation. It was preserved and no duplicate registration was installed.' };
|
|
112
|
-
const registrations = await readHostRegistration(paths, ide);
|
|
113
|
-
|
|
114
|
-
next: 'Several Craft registrations exist. Select the intended connection without replacing other environments.' };
|
|
115
|
-
const existing = registrations[0];
|
|
116
|
-
if (existing) {
|
|
122
|
+
const registrations = await readHostRegistration(paths, ide, serverId);
|
|
123
|
+
async function inspectRegistration(existing) {
|
|
117
124
|
const connection = existing.connection;
|
|
125
|
+
const marked = connection?.env?.CRAFT_SERVER_ID;
|
|
126
|
+
// Older installations can use a user-renamed tool namespace while the
|
|
127
|
+
// runtime and installation record still identify the default Craft slot.
|
|
128
|
+
const instance = marked ?? 'craft';
|
|
129
|
+
if (serverId === undefined && instance !== 'craft') await assertHostConfigScope(paths.config, ide, paths.configPeers, instance);
|
|
130
|
+
const verification = connectionRequirements(project, ide, manifest, instance);
|
|
131
|
+
const response = { ...base, registration: existing.name, server_id: instance, expected, verification };
|
|
118
132
|
if (!connection || typeof connection !== 'object') return { ...response, status: 'invalid_configuration', next: 'Repair the existing Craft configuration; it was preserved.' };
|
|
119
133
|
if (connection.disabled === true || connection.enabled === false || connection.enable === false) return { ...response, status: 'disabled',
|
|
120
134
|
next: 'Craft is installed but explicitly disabled. Enable it through the current host only when the user intends to do so; do not reinstall to bypass this setting.' };
|
|
@@ -140,7 +154,8 @@ export async function setupProject({ project, ide, packageRoot, install = false,
|
|
|
140
154
|
await assertPlainPath(connection.env.CRAFT_INSTALLATION_FILE);
|
|
141
155
|
state = await readInstallation(connection.env.CRAFT_INSTALLATION_FILE);
|
|
142
156
|
} catch { return { ...response, status: 'invalid_installation', next: 'The existing Craft installation state is missing or invalid. Preserve the configuration and repair that installation before continuing.' }; }
|
|
143
|
-
if (state.
|
|
157
|
+
if (state.server_id !== instance || (marked !== undefined && marked !== existing.name) ||
|
|
158
|
+
state.host !== ide || !samePath(state.config, paths.config) || !samePath(state.workspace, expected.workspace) || state.platform !== expected.platform ||
|
|
144
159
|
state.source.package !== manifest.package_name || registryOrigin(state.source.registry) !== registryOrigin(manifest.registry) || state.source.channel !== manifest.channel) return { ...response, status: 'scope_mismatch',
|
|
145
160
|
next: 'The recorded installation host, project scope, platform or package source differs from this project. Preserve it and resolve the intended connection explicitly.' };
|
|
146
161
|
if (!workspace || !platform || host !== ide || !connection.command) return { ...response, status: 'invalid_configuration',
|
|
@@ -152,6 +167,21 @@ export async function setupProject({ project, ide, packageRoot, install = false,
|
|
|
152
167
|
return { ...response, status: 'configured_unverified', installed_target: target,
|
|
153
168
|
next: 'Craft is configured. Discover and call its actual tools in this host session. If tools remain unavailable, inspect connection/startup errors and host trust; do not treat this as a missing installation. Reconnect only as needed, then verify and resume.' };
|
|
154
169
|
}
|
|
170
|
+
const candidates = serverId === undefined ? registrations : registrationsForInstance(registrations, serverId);
|
|
171
|
+
const inspected = await Promise.all(candidates.map(inspectRegistration));
|
|
172
|
+
const matching = inspected.filter(item => ['configured_unverified', 'update_required'].includes(item.status));
|
|
173
|
+
if (matching.length === 1) return matching[0];
|
|
174
|
+
const unresolved = inspected.filter(item => item.status !== 'scope_mismatch');
|
|
175
|
+
if (matching.length > 1 || (!matching.length && unresolved.length && inspected.length > 1 && !serverId)) {
|
|
176
|
+
return { ...response, status: 'multiple_installations', candidates: (matching.length ? matching : inspected).map(item => item.registration),
|
|
177
|
+
next: 'Select the intended Craft registration explicitly with --instance. No installation was changed.' };
|
|
178
|
+
}
|
|
179
|
+
if (serverId && inspected.length) return inspected[0];
|
|
180
|
+
const defaultRegistration = inspected.find(item => item.server_id === 'craft');
|
|
181
|
+
if (unresolved.length || (manifest.channel === 'stable' && defaultRegistration)) return unresolved[0] ?? defaultRegistration;
|
|
182
|
+
if (manifest.channel !== 'stable' && (!serverId || serverId === 'craft')) return { ...response, status: 'instance_required',
|
|
183
|
+
next: 'This project tracks a non-stable channel. Select the intended named Craft instance explicitly with --instance before installing it.' };
|
|
184
|
+
verification.expected.server_id = serverId ?? 'craft';
|
|
155
185
|
const pkg = JSON.parse(await readFile(path.join(packageRoot, 'package.json'), 'utf8'));
|
|
156
186
|
if (pkg.name !== manifest.package_name) throw new Error('Running CLI package does not match the project installation package');
|
|
157
187
|
if (compareVersions(pkg.version, manifest.minimum_mcp_version) < 0) return { ...response, status: 'installer_update_required',
|
|
@@ -168,7 +198,7 @@ export async function setupProject({ project, ide, packageRoot, install = false,
|
|
|
168
198
|
if (!install) return { ...response, status: 'missing_installation',
|
|
169
199
|
next: 'No Craft registration exists for this host. Repeat this command with --install to install only this host using the project platform, source and actual parent directory. Host trust and connection must still be verified.' };
|
|
170
200
|
if (!isDeepStrictEqual(await readProjectInstall(project, { required: true }), manifest)) throw new Error('Project installation metadata changed during setup; retry');
|
|
171
|
-
const result = await installer({ ide, workspace: expected.workspace, platform: manifest.platform,
|
|
201
|
+
const result = await installer({ ide, serverId: serverId ?? 'craft', workspace: expected.workspace, platform: manifest.platform,
|
|
172
202
|
registry: manifest.registry, channel: manifest.channel, packageRoot, home, codexHome, hostOptions,
|
|
173
203
|
...(runtimeRoot ? { runtimeRoot } : {}), ...(stateRoot ? { stateRoot } : {}), onlyIfMissing: true });
|
|
174
204
|
const installed = result.hosts?.find(item => item.host === ide);
|
|
@@ -191,7 +221,7 @@ export function parseProjectSetupArgs(args) {
|
|
|
191
221
|
if (key === '--install') {
|
|
192
222
|
if (options.install !== undefined) throw new Error('Repeated --install option');
|
|
193
223
|
options.install = true;
|
|
194
|
-
} else if (['--project', '--ide', '--host-config', '--trae-region'].includes(key)) {
|
|
224
|
+
} else if (['--project', '--ide', '--instance', '--host-config', '--trae-region'].includes(key)) {
|
|
195
225
|
const name = key.slice(2), value = args[++i];
|
|
196
226
|
if (!value || value.startsWith('--') || Object.hasOwn(options, name)) throw new Error('Invalid or repeated ' + key);
|
|
197
227
|
options[name] = value;
|
|
@@ -203,7 +233,7 @@ export function parseProjectSetupArgs(args) {
|
|
|
203
233
|
|
|
204
234
|
export async function runProjectSetupCommand(args, packageRoot) {
|
|
205
235
|
const options = parseProjectSetupArgs(args);
|
|
206
|
-
const result = await setupProject({ ...options, packageRoot, installer: installWithLoginTask,
|
|
236
|
+
const result = await setupProject({ ...options, serverId: options.instance, packageRoot, installer: installWithLoginTask,
|
|
207
237
|
codexHome: process.env.CODEX_HOME, hostOptions: hostCommandOptions(options) });
|
|
208
238
|
process.stdout.write(JSON.stringify(result, null, 2) + '\n');
|
|
209
239
|
return result;
|
|
@@ -2,6 +2,7 @@ import path from 'node:path';
|
|
|
2
2
|
import { mkdir, mkdtemp, lstat, readFile, rename, rm } from 'node:fs/promises';
|
|
3
3
|
import { getRuntimeIdentity } from './runtime-identity.mjs';
|
|
4
4
|
import { assertPlainPath } from './files.mjs';
|
|
5
|
+
import { verifyExistingFileList } from './runtime-file-diagnostics.mjs';
|
|
5
6
|
|
|
6
7
|
const within = (root, file) => {
|
|
7
8
|
const relative = path.relative(path.resolve(root), path.resolve(file));
|
|
@@ -26,14 +27,14 @@ function relocated(candidate) {
|
|
|
26
27
|
|
|
27
28
|
// Preparation and complete content verification happen outside installation
|
|
28
29
|
// locks. GC only visits the runtime root's direct version directories.
|
|
29
|
-
export async function prepareRuntimeCandidate(runtimeRoot, materialize) {
|
|
30
|
+
export async function prepareRuntimeCandidate(runtimeRoot, materialize, { repair = false, deferExisting = false } = {}) {
|
|
30
31
|
runtimeRoot = path.resolve(runtimeRoot);
|
|
31
32
|
await assertPlainPath(path.join(runtimeRoot, '.candidate-path-check'));
|
|
32
33
|
const parent = path.join(runtimeRoot, '.candidates');
|
|
33
34
|
await mkdir(parent, { recursive: true });
|
|
34
35
|
await assertPlainPath(path.join(parent, '.candidate-path-check'));
|
|
35
36
|
const staging = await mkdtemp(path.join(parent, 'prepare-'));
|
|
36
|
-
const candidate = { runtimeRoot, staging, managed: false };
|
|
37
|
+
const candidate = { runtimeRoot, staging, managed: false, repair };
|
|
37
38
|
try {
|
|
38
39
|
candidate.runtime = await materialize(staging);
|
|
39
40
|
const runtime = candidate.runtime;
|
|
@@ -44,7 +45,7 @@ export async function prepareRuntimeCandidate(runtimeRoot, materialize) {
|
|
|
44
45
|
if (path.dirname(candidate.sourceDirectory) !== staging || !within(candidate.sourceDirectory, candidate.identity.package_root) || !within(candidate.sourceDirectory, candidate.identity.entry)) throw new Error('Candidate runtime escaped its isolated directory');
|
|
45
46
|
candidate.destination = path.join(runtimeRoot, path.basename(candidate.sourceDirectory));
|
|
46
47
|
candidate.managed = true;
|
|
47
|
-
await refreshRuntimeCandidate(candidate);
|
|
48
|
+
if (!deferExisting) await refreshRuntimeCandidate(candidate);
|
|
48
49
|
}
|
|
49
50
|
// Injectable materializers may return pre-existing fixture/runtime paths.
|
|
50
51
|
// These are never moved or removed by candidate cleanup.
|
|
@@ -54,26 +55,51 @@ export async function prepareRuntimeCandidate(runtimeRoot, materialize) {
|
|
|
54
55
|
|
|
55
56
|
// A concurrent publication may appear after preparation. Refresh its complete
|
|
56
57
|
// identity outside locks before retrying the short commit section.
|
|
57
|
-
export async function refreshRuntimeCandidate(candidate) {
|
|
58
|
+
export async function refreshRuntimeCandidate(candidate, checkExisting) {
|
|
58
59
|
if (!candidate.managed) return;
|
|
59
|
-
const before = await directoryStamp(candidate.destination);
|
|
60
60
|
candidate.existing = null;
|
|
61
|
+
const base = path.join(candidate.runtimeRoot, path.basename(candidate.sourceDirectory));
|
|
62
|
+
for (let slot = 0; ; slot++) {
|
|
63
|
+
candidate.destination = slot === 0 ? base : base + '-repair-' + slot;
|
|
64
|
+
try { return await verifyExistingRuntime(candidate, checkExisting); }
|
|
65
|
+
catch (error) {
|
|
66
|
+
// An independently verified copy can occupy a sibling slot. Never mutate
|
|
67
|
+
// or move an existing directory that another MCP process could be using.
|
|
68
|
+
if (!candidate.repair || (error.code && error.code !== 'ENOENT')) throw error;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async function verifyExistingRuntime(candidate, checkExisting) {
|
|
74
|
+
const before = await directoryStamp(candidate.destination);
|
|
61
75
|
if (before === null) return;
|
|
62
76
|
try {
|
|
63
77
|
const final = relocated(candidate);
|
|
78
|
+
await assertPlainPath(path.join(final.package_root, 'package.json'));
|
|
79
|
+
await assertPlainPath(path.join(candidate.destination, 'craft-runtime.json'));
|
|
64
80
|
const identity = await getRuntimeIdentity(final.package_root);
|
|
65
81
|
const metadataText = await readFile(path.join(candidate.destination, 'craft-runtime.json'), 'utf8');
|
|
66
82
|
const metadata = JSON.parse(metadataText);
|
|
67
83
|
if (identity.package !== final.package || identity.version !== final.version || identity.build_id !== final.build_id ||
|
|
68
84
|
metadata.package !== final.package || metadata.version !== final.version || metadata.build_id !== final.build_id || metadata.sha256 !== candidate.runtime.sha256) throw new Error('Existing Craft runtime differs from the verified candidate');
|
|
85
|
+
await verifyExistingFileList(candidate.sourceDirectory,candidate.destination,metadata);
|
|
86
|
+
let verification;
|
|
87
|
+
if (checkExisting) {
|
|
88
|
+
// A product hash excludes npm dependencies. The existing installation,
|
|
89
|
+
// including its own dependencies, must start in every requested host.
|
|
90
|
+
try { verification = await checkExisting(final); }
|
|
91
|
+
catch (error) { throw new Error('Existing Craft runtime could not start: ' + error.message, { cause: error }); }
|
|
92
|
+
if ((await getRuntimeIdentity(final.package_root)).build_id !== final.build_id) throw new Error('Existing Craft runtime changed during startup verification');
|
|
93
|
+
}
|
|
69
94
|
if (before !== await directoryStamp(candidate.destination)) throw changed('Craft runtime changed during candidate verification');
|
|
70
95
|
candidate.existing = { stamp: before, metadataText };
|
|
96
|
+
return verification;
|
|
71
97
|
} catch (error) {
|
|
72
98
|
if (error.code === 'ENOENT') {
|
|
73
99
|
// GC can remove an unreferenced former candidate while it is inspected.
|
|
74
100
|
// Our private copy is still complete and can be published on retry.
|
|
75
101
|
if (await directoryStamp(candidate.destination) === null) return;
|
|
76
|
-
throw changed('Craft runtime was removed while its existing copy was being verified');
|
|
102
|
+
if (!candidate.repair) throw changed('Craft runtime was removed while its existing copy was being verified');
|
|
77
103
|
}
|
|
78
104
|
throw error;
|
|
79
105
|
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { readFile, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
4
|
+
import { assertPlainPath, optionalFile } from './files.mjs';
|
|
5
|
+
import { hashRuntimeFiles, runtimeDirectoryForPackage } from './runtime-identity.mjs';
|
|
6
|
+
|
|
7
|
+
// Store the installed bytes (after npm's bin normalization) outside the product tree.
|
|
8
|
+
const fileListName = 'craft-runtime-files.json';
|
|
9
|
+
const digest = bytes => createHash('sha256').update(bytes).digest('hex');
|
|
10
|
+
|
|
11
|
+
export async function writeRuntimeFileList(directory, identity, files) {
|
|
12
|
+
const text = JSON.stringify({ schema: 1, build_id: identity.build_id, files }) + '\n';
|
|
13
|
+
await writeFile(path.join(directory, fileListName), text, { flag: 'wx' });
|
|
14
|
+
return digest(text);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export async function verifyExistingFileList(sourceDirectory, existingDirectory, receipt) {
|
|
18
|
+
const expected = JSON.parse(await readFile(path.join(sourceDirectory,'craft-runtime.json'),'utf8')).files_sha256;
|
|
19
|
+
if (!expected) return;
|
|
20
|
+
const file = path.join(existingDirectory,fileListName);
|
|
21
|
+
await assertPlainPath(file);
|
|
22
|
+
const text = await optionalFile(file);
|
|
23
|
+
if (receipt.files_sha256 !== expected || text === null || digest(text) !== expected) {
|
|
24
|
+
throw new Error('Existing Craft runtime file-level baseline differs from the verified candidate');
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async function describeFileChanges(candidate, runtimeRoot, actual) {
|
|
29
|
+
const directory = runtimeDirectoryForPackage(candidate.package_root);
|
|
30
|
+
const unavailable = 'No installed file-level baseline is available; compare against a clean installation of this build.';
|
|
31
|
+
if (!directory || !runtimeRoot || path.relative(runtimeRoot, path.dirname(directory)) !== '') return unavailable;
|
|
32
|
+
const receiptFile = path.join(directory, 'craft-runtime.json');
|
|
33
|
+
const listFile = path.join(directory, fileListName);
|
|
34
|
+
await assertPlainPath(receiptFile);
|
|
35
|
+
const receipt = JSON.parse(await optionalFile(receiptFile) ?? 'null');
|
|
36
|
+
if (!receipt?.files_sha256) return unavailable;
|
|
37
|
+
await assertPlainPath(listFile);
|
|
38
|
+
const text = await optionalFile(listFile);
|
|
39
|
+
if (receipt.build_id !== candidate.build_id || !text || digest(text) !== receipt.files_sha256) {
|
|
40
|
+
return 'The installed file-level baseline is missing or its checksum does not match; file differences could not be verified.';
|
|
41
|
+
}
|
|
42
|
+
const baseline = JSON.parse(text);
|
|
43
|
+
if (baseline.schema !== 1 || baseline.build_id !== candidate.build_id || !baseline.files || typeof baseline.files !== 'object' || Array.isArray(baseline.files)) {
|
|
44
|
+
return 'The installed file-level baseline is invalid; file differences could not be verified.';
|
|
45
|
+
}
|
|
46
|
+
const expected = baseline.files;
|
|
47
|
+
const differences = {
|
|
48
|
+
added: Object.keys(actual).filter(name => !Object.hasOwn(expected, name)),
|
|
49
|
+
changed: Object.keys(actual).filter(name => Object.hasOwn(expected, name) && actual[name] !== expected[name]),
|
|
50
|
+
missing: Object.keys(expected).filter(name => !Object.hasOwn(actual, name))
|
|
51
|
+
};
|
|
52
|
+
return Object.entries(differences).filter(([, names]) => names.length)
|
|
53
|
+
.map(([kind, names]) => kind + ': ' + JSON.stringify(names)).join('\n') || 'The file list has no differences; the recorded build identity disagrees.';
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export async function verifyRuntimeProductFiles(candidate, installation) {
|
|
57
|
+
const files = Object.create(null);
|
|
58
|
+
await assertPlainPath(path.join(candidate.package_root, 'package.json'));
|
|
59
|
+
const actualBuild = await hashRuntimeFiles(candidate.package_root, files);
|
|
60
|
+
if (actualBuild !== candidate.build_id) {
|
|
61
|
+
const details = await describeFileChanges(candidate, installation.runtime_root, files)
|
|
62
|
+
.catch(() => 'The installed file-level baseline could not be read or verified; the differing files are unknown.');
|
|
63
|
+
const repair = 'craft-mcp install --repair --ide ' + installation.host + ' --instance ' + installation.server_id;
|
|
64
|
+
throw new Error('Craft runtime integrity mismatch at ' + candidate.package_root + ' (expected ' + candidate.build_id + ', actual ' + actualBuild + ').\n' + details + '\nRepair: ' + repair);
|
|
65
|
+
}
|
|
66
|
+
const pkg = JSON.parse(await readFile(path.join(candidate.package_root, 'package.json'), 'utf8'));
|
|
67
|
+
if (pkg.name !== candidate.package || pkg.version !== candidate.version) throw new Error('Craft package name or version differs from its installation record');
|
|
68
|
+
}
|
|
@@ -65,6 +65,12 @@ async function safeDirectory(directory) {
|
|
|
65
65
|
await assertPlainPath(path.join(directory, '.craft-path-check'));
|
|
66
66
|
}
|
|
67
67
|
|
|
68
|
+
function managedRuntimeName(name, metadata) {
|
|
69
|
+
const base = metadata.version + '-' + metadata.sha256.slice(0, 16);
|
|
70
|
+
return typeof name === 'string' && (name === base ||
|
|
71
|
+
(name.startsWith(base) && /^-repair-[1-9]\d*$/.test(name.slice(base.length))));
|
|
72
|
+
}
|
|
73
|
+
|
|
68
74
|
async function ownedRuntimes(root, packageName) {
|
|
69
75
|
const owned = [];
|
|
70
76
|
for (const entry of await readdir(root, { withFileTypes: true })) {
|
|
@@ -74,7 +80,7 @@ async function ownedRuntimes(root, packageName) {
|
|
|
74
80
|
await safeDirectory(directory);
|
|
75
81
|
const metadataText = await readFile(path.join(directory, 'craft-runtime.json'), 'utf8');
|
|
76
82
|
const metadata = JSON.parse(metadataText);
|
|
77
|
-
if (metadata.package !== packageName || !/^[a-f0-9]{64}$/.test(metadata.sha256 ?? '') || !/^[a-f0-9]{64}$/.test(metadata.build_id ?? '') || entry.name
|
|
83
|
+
if (metadata.package !== packageName || !/^[a-f0-9]{64}$/.test(metadata.sha256 ?? '') || !/^[a-f0-9]{64}$/.test(metadata.build_id ?? '') || !managedRuntimeName(entry.name, metadata)) continue;
|
|
78
84
|
compareVersions(metadata.version, metadata.version);
|
|
79
85
|
const packageRoot = path.join(directory, 'node_modules', ...packageName.split('/'));
|
|
80
86
|
await assertPlainPath(path.join(packageRoot, 'package.json'));
|
|
@@ -106,7 +112,7 @@ async function retiredRuntimes(root, packageName) {
|
|
|
106
112
|
await assertPlainPath(manifestFile);
|
|
107
113
|
const manifestText = await readFile(manifestFile, 'utf8'), manifest = JSON.parse(manifestText);
|
|
108
114
|
if (manifest.schema !== 1 || manifest.package !== packageName || !/^[a-f0-9]{64}$/.test(manifest.sha256 ?? '') || !/^[a-f0-9]{64}$/.test(manifest.build_id ?? '') ||
|
|
109
|
-
manifest.source_name
|
|
115
|
+
!managedRuntimeName(manifest.source_name, manifest)) continue;
|
|
110
116
|
compareVersions(manifest.version, manifest.version);
|
|
111
117
|
// The manifest authorizes only this private child. It never supplies a
|
|
112
118
|
// deletion path. Keep it outside runtime/ so interrupted deletion can
|
|
@@ -1,12 +1,11 @@
|
|
|
1
1
|
import path from 'node:path';
|
|
2
2
|
import { readFile, readdir, lstat } from 'node:fs/promises';
|
|
3
3
|
import { createHash } from 'node:crypto';
|
|
4
|
+
import { assertPlainPath, optionalFile } from './files.mjs';
|
|
4
5
|
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
export async function
|
|
8
|
-
packageRoot = path.resolve(packageRoot);
|
|
9
|
-
const pkg = JSON.parse(await readFile(path.join(packageRoot, 'package.json'), 'utf8'));
|
|
6
|
+
// Installation and diagnosis use the same path ordering and bytes. Collecting
|
|
7
|
+
// individual hashes is optional and never requires reading a file twice.
|
|
8
|
+
export async function hashRuntimeFiles(packageRoot, files) {
|
|
10
9
|
const hash = createHash('sha256');
|
|
11
10
|
async function visit(relative) {
|
|
12
11
|
const file = path.join(packageRoot, relative);
|
|
@@ -14,9 +13,58 @@ export async function getRuntimeIdentity(packageRoot) {
|
|
|
14
13
|
if (info.isSymbolicLink()) throw new Error('Craft runtime contains a linked product file: ' + relative);
|
|
15
14
|
if (info.isDirectory()) {
|
|
16
15
|
for (const entry of (await readdir(file)).sort()) if (entry !== 'node_modules') await visit(relative + '/' + entry);
|
|
17
|
-
} else if (info.isFile())
|
|
18
|
-
|
|
16
|
+
} else if (info.isFile()) {
|
|
17
|
+
const bytes = await readFile(file);
|
|
18
|
+
hash.update(relative + '\0').update(bytes).update('\0');
|
|
19
|
+
if (files) files[relative] = createHash('sha256').update(bytes).digest('hex');
|
|
20
|
+
} else throw new Error('Invalid Craft runtime file: ' + relative);
|
|
19
21
|
}
|
|
20
22
|
for (const relative of ['package.json', 'bin', 'dist-server', 'resources', 'vendor']) await visit(relative);
|
|
21
|
-
return
|
|
23
|
+
return hash.digest('hex');
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function identityForPackage(packageRoot, pkg, buildId) {
|
|
27
|
+
return { package: pkg.name, version: pkg.version, build_id: buildId, package_root: packageRoot, entry: path.join(packageRoot, 'bin/craft-mcp.mjs') };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export async function getRuntimeIdentity(packageRoot, { files } = {}) {
|
|
31
|
+
packageRoot = path.resolve(packageRoot);
|
|
32
|
+
const pkg = JSON.parse(await readFile(path.join(packageRoot, 'package.json'), 'utf8'));
|
|
33
|
+
return identityForPackage(packageRoot, pkg, await hashRuntimeFiles(packageRoot, files));
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// Locate the installation receipt from the executable itself, never from the
|
|
37
|
+
// host's target pointer, which can switch while an older session is running.
|
|
38
|
+
export function runtimeDirectoryForPackage(packageRoot) {
|
|
39
|
+
const parent = path.dirname(path.resolve(packageRoot));
|
|
40
|
+
const modules = path.basename(parent).startsWith('@') ? path.dirname(parent) : parent;
|
|
41
|
+
return path.basename(modules) === 'node_modules' ? path.dirname(modules) : null;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export async function readRunningIdentity(packageRoot, { managed = false } = {}) {
|
|
45
|
+
packageRoot = path.resolve(packageRoot);
|
|
46
|
+
const directory = runtimeDirectoryForPackage(packageRoot);
|
|
47
|
+
if (!directory) return getRuntimeIdentity(packageRoot);
|
|
48
|
+
const receiptFile = path.join(directory, 'craft-runtime.json');
|
|
49
|
+
await assertPlainPath(receiptFile);
|
|
50
|
+
const text = await optionalFile(receiptFile);
|
|
51
|
+
if (text === null) {
|
|
52
|
+
if (managed) throw new Error('Craft runtime installation receipt is missing; run doctor for the selected instance');
|
|
53
|
+
return getRuntimeIdentity(packageRoot);
|
|
54
|
+
}
|
|
55
|
+
const receipt = JSON.parse(text);
|
|
56
|
+
const packageFile = path.join(packageRoot, 'package.json');
|
|
57
|
+
await assertPlainPath(packageFile);
|
|
58
|
+
const pkg = JSON.parse(await readFile(packageFile, 'utf8'));
|
|
59
|
+
const name = path.relative(path.join(directory, 'node_modules'), packageRoot).split(path.sep).join('/');
|
|
60
|
+
if (name !== pkg.name || receipt.package !== pkg.name || receipt.version !== pkg.version ||
|
|
61
|
+
!/^[a-f0-9]{64}$/.test(receipt.sha256 ?? '') || (receipt.build_id !== undefined && !/^[a-f0-9]{64}$/.test(receipt.build_id))) {
|
|
62
|
+
throw new Error('Craft runtime package and installation receipt disagree; run doctor for the selected instance');
|
|
63
|
+
}
|
|
64
|
+
// Old unmanaged distributions and pre-build-id receipts have no independent
|
|
65
|
+
// installed identity. Preserve their existing content-based identification.
|
|
66
|
+
const identity = identityForPackage(packageRoot, pkg, receipt.build_id ?? await hashRuntimeFiles(packageRoot));
|
|
67
|
+
await assertPlainPath(identity.entry);
|
|
68
|
+
if (!(await lstat(identity.entry)).isFile()) throw new Error('Craft runtime entry must be a regular file');
|
|
69
|
+
return identity;
|
|
22
70
|
}
|