@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.
Files changed (43) hide show
  1. package/README.md +6 -17
  2. package/bin/craft-mcp.mjs +30 -2
  3. package/dist-server/core/upload-limits.mjs +11 -0
  4. package/dist-server/game-workflow/bundle-files.mjs +6 -1
  5. package/dist-server/game-workflow/engines.mjs +18 -9
  6. package/dist-server/game-workflow/project-context.mjs +11 -7
  7. package/dist-server/game-workflow/project-install.mjs +17 -8
  8. package/dist-server/game-workflow/projects.mjs +13 -3
  9. package/dist-server/integrations/config.mjs +41 -18
  10. package/dist-server/integrations/connect.mjs +18 -9
  11. package/dist-server/integrations/connection-handoff.mjs +9 -8
  12. package/dist-server/integrations/distribution-targets.mjs +9 -0
  13. package/dist-server/integrations/dsh-config.mjs +30 -14
  14. package/dist-server/integrations/fixed-launcher.mjs +1 -0
  15. package/dist-server/integrations/host-config-scope.mjs +4 -3
  16. package/dist-server/integrations/hosts.mjs +3 -1
  17. package/dist-server/integrations/install.mjs +147 -43
  18. package/dist-server/integrations/installation-state.mjs +2 -1
  19. package/dist-server/integrations/instance-skill.mjs +26 -0
  20. package/dist-server/integrations/instance.mjs +29 -0
  21. package/dist-server/integrations/launcher-start.mjs +6 -6
  22. package/dist-server/integrations/login-task-command.mjs +3 -3
  23. package/dist-server/integrations/opencode-config.mjs +13 -6
  24. package/dist-server/integrations/project-setup.mjs +48 -18
  25. package/dist-server/integrations/runtime-candidate.mjs +32 -6
  26. package/dist-server/integrations/runtime-file-diagnostics.mjs +68 -0
  27. package/dist-server/integrations/runtime-gc.mjs +8 -2
  28. package/dist-server/integrations/runtime-identity.mjs +56 -8
  29. package/dist-server/integrations/runtime.mjs +7 -3
  30. package/dist-server/integrations/uninstall.mjs +160 -0
  31. package/dist-server/integrations/updates.mjs +57 -42
  32. package/dist-server/launcher.mjs +65 -10
  33. package/dist-server/mcp/production-events.mjs +52 -29
  34. package/dist-server/mcp/server.mjs +18 -9
  35. package/dist-server/mcp/update-session.mjs +9 -6
  36. package/dist-server/preview/preview-snapshot.mjs +3 -2
  37. package/package.json +5 -3
  38. package/resources/craft-create/SKILL.md +2 -0
  39. package/resources/craft-update/SKILL.md +2 -0
  40. package/vendor/craft-runtime/NOTICE.md +1 -1
  41. package/vendor/craft-runtime/SOURCE.json +9 -5
  42. package/vendor/craft-runtime/index.js +228 -164
  43. package/vendor/craft-runtime/package.json +1 -1
@@ -1,4 +1,5 @@
1
1
  import { getRuntimeIdentity } from './runtime-identity.mjs';
2
+ import { writeRuntimeFileList } from './runtime-file-diagnostics.mjs';
2
3
  import path from 'node:path';
3
4
  import os from 'node:os';
4
5
  import { existsSync } from 'node:fs';
@@ -52,8 +53,10 @@ async function stageArchive(archive, pkg, runtimeRoot, { registry, integrity } =
52
53
  const stagedRoot = path.join(staging, 'node_modules', ...pkg.name.split('/'));
53
54
  const installed = JSON.parse(await readFile(path.join(stagedRoot, 'package.json'), 'utf8'));
54
55
  if (installed.name !== pkg.name || installed.version !== pkg.version || !installed.bin?.['craft-mcp'] || !installed.files?.includes('resources')) throw new Error('Downloaded package is not the expected Craft distribution');
55
- const identity = await getRuntimeIdentity(stagedRoot);
56
- await writeFile(path.join(staging, 'craft-runtime.json'), JSON.stringify({ version: pkg.version, package: pkg.name, sha256: hash, build_id: identity.build_id, ...(integrity ? { integrity } : {}) }) + '\n');
56
+ const files = Object.create(null);
57
+ const identity = await getRuntimeIdentity(stagedRoot, { files });
58
+ const files_sha256 = await writeRuntimeFileList(staging, identity, files);
59
+ await writeFile(path.join(staging, 'craft-runtime.json'), JSON.stringify({ version: pkg.version, package: pkg.name, sha256: hash, build_id: identity.build_id, files_sha256, ...(integrity ? { integrity } : {}) }) + '\n');
57
60
  await rename(staging, target);
58
61
  } finally { await rm(staging, { recursive: true, force: true }); }
59
62
  }
@@ -103,9 +106,10 @@ export async function probeRuntime(connection, expected = {}) {
103
106
  if (expected.version && info.version !== expected.version) throw new Error('Runtime version mismatch');
104
107
  if (expected.build_id && info.runtime?.build_id !== expected.build_id) throw new Error('Runtime build identity mismatch');
105
108
  if (expected.host && info.host !== expected.host) throw new Error('Runtime host mismatch');
109
+ if (expected.serverId && (info.server_id ?? 'craft') !== expected.serverId) throw new Error('Craft runtime does not confirm the requested MCP instance: ' + expected.serverId + '; use a channel release with named instance support');
106
110
  if (expected.workspace && path.resolve(info.workspace) !== path.resolve(expected.workspace)) throw new Error('Runtime workspace mismatch');
107
111
  if (expected.platform && info.platform !== expected.platform) throw new Error('Runtime platform mismatch');
108
112
  if (expected.host && ['js','js3d'].some(engine=>info.installed_contexts?.[engine]?.host !== expected.host)) throw new Error('Runtime context host mismatch');
109
- return { scope: 'standalone_probe', version: info.version, runtime: info.runtime, host: info.host, workspace: info.workspace, platform: info.platform, tools: listed.tools.length, engines: info.supported_engines, contexts:info.installed_contexts };
113
+ return { scope: 'standalone_probe', version: info.version, runtime: info.runtime, host: info.host, server_id: info.server_id ?? 'craft', workspace: info.workspace, platform: info.platform, tools: listed.tools.length, engines: info.supported_engines, contexts:info.installed_contexts };
110
114
  } finally { await client.close(); await rm(state, { recursive: true, force: true }); }
111
115
  }
@@ -0,0 +1,160 @@
1
+ import os from 'node:os';
2
+ import path from 'node:path';
3
+ import { createHash } from 'node:crypto';
4
+ import { readdir } from 'node:fs/promises';
5
+ import lockfile from 'proper-lockfile';
6
+ import { getAppDataRoot } from '../core/app-paths.mjs';
7
+ import { hostCommandOptions, hostEnvironment, hostPaths, installTargets } from './hosts.mjs';
8
+ import { craftConfig, craftRegistrations, removeConfig } from './config.mjs';
9
+ import { assertDshSharedScope } from './dsh-config.mjs';
10
+ import { assertHostConfigScope } from './host-config-scope.mjs';
11
+ import { assertPlainPath, commitFiles, optionalFile } from './files.mjs';
12
+ import { verifyLauncher } from './fixed-launcher.mjs';
13
+ import { validateServerId } from './instance.mjs';
14
+ import { renderInstanceSkill } from './instance-skill.mjs';
15
+ import { installationPath, installedSkillEntries, readInstallationSnapshot, sameRuntimeIdentity } from './installation-state.mjs';
16
+ import { unchangedInstallation } from './installation-transaction.mjs';
17
+ import { getRuntimeIdentity } from './runtime-identity.mjs';
18
+ import { ensureWorkBuddyLoginTask, ensureWorkBuddyPreviewTask, removeWorkBuddyLoginTask, removeWorkBuddyPreviewTask } from './workbuddy-login-task.mjs';
19
+
20
+ const samePath = (left, right) => typeof left === 'string' && path.isAbsolute(left) && path.relative(left, right) === '';
21
+
22
+ // Separate Codex configuration files can share the same user-level Skill root.
23
+ // Unknown state cannot establish exclusive ownership, so preserve the Skill.
24
+ async function sharedSkills(stateRoot, ownFile, entries) {
25
+ const shared = new Set();
26
+ for (const item of await readdir(stateRoot, { withFileTypes: true })) {
27
+ if (!/^[0-9a-f]{24}\.json$/i.test(item.name)) continue;
28
+ const file = path.join(stateRoot, item.name);
29
+ if (samePath(file, ownFile)) continue;
30
+ try {
31
+ await assertPlainPath(file);
32
+ const { state } = await readInstallationSnapshot(file);
33
+ if (!state.skills) return new Set(entries.map(entry => entry.file));
34
+ for (const { file: skill } of installedSkillEntries(state)) {
35
+ for (const entry of entries) if (samePath(skill, entry.file)) shared.add(entry.file);
36
+ }
37
+ } catch {
38
+ for (const entry of entries) shared.add(entry.file);
39
+ }
40
+ }
41
+ return shared;
42
+ }
43
+
44
+ async function verifiedTemplates(state, entries) {
45
+ const expected = new Map();
46
+ if (!entries.length || !state.skills_runtime) return expected;
47
+ const identity = state.skills_runtime;
48
+ try {
49
+ if (!sameRuntimeIdentity(await getRuntimeIdentity(identity.package_root), identity)) return expected;
50
+ for (const { name, marker } of entries) {
51
+ const template = await optionalFile(path.join(identity.package_root, 'resources', name, 'SKILL.md'));
52
+ if (template?.includes(marker)) expected.set(name, renderInstanceSkill(template, name, state.server_id));
53
+ }
54
+ } catch (error) {
55
+ if (error.code !== 'ENOENT') throw error;
56
+ }
57
+ return expected;
58
+ }
59
+
60
+ export async function uninstallHost({ ide, serverId = 'craft', home = os.homedir(), codexHome = process.env.CODEX_HOME,
61
+ hostOptions = hostEnvironment(), runtimeRoot = path.join(getAppDataRoot(), 'runtimes'),
62
+ stateRoot = path.join(path.dirname(runtimeRoot), 'installations') }) {
63
+ validateServerId(serverId);
64
+ const targets = installTargets(ide);
65
+ if (targets.length !== 1) throw new Error('Uninstall requires exactly one host');
66
+ const [host] = targets;
67
+ const paths = hostPaths(home, host, codexHome, { ...hostOptions, serverId });
68
+ const { file, id } = installationPath(stateRoot, host, paths.config, serverId);
69
+ const result = { host, server_id: serverId, config: paths.config, installation: file };
70
+ await assertPlainPath(paths.config);
71
+ await assertPlainPath(file);
72
+ const text = await optionalFile(paths.config);
73
+ const connection = craftConfig(text ?? '', host, serverId);
74
+ if (!connection && await optionalFile(file) === null) return { ...result, status: 'absent', changed: [], preserved_skills: [] };
75
+ if (!samePath(connection?.env?.CRAFT_INSTALLATION_FILE, file) || connection.env.CRAFT_CLIENT_IDE !== host ||
76
+ (connection.env.CRAFT_SERVER_ID ?? 'craft') !== serverId) {
77
+ throw new Error('Registration does not point to the selected managed Craft installation; files were preserved');
78
+ }
79
+ const { state } = await readInstallationSnapshot(file);
80
+ if (state.id !== id || state.server_id !== serverId || state.host !== host || !samePath(state.config, paths.config) ||
81
+ !samePath(state.runtime_root, runtimeRoot)) throw new Error('Installation state does not match the selected Craft instance');
82
+ const entries = installedSkillEntries(state);
83
+ for (const { name, file: skill } of entries) {
84
+ if (!samePath(skill, name === 'craft-create' ? paths.skill : paths.updateSkill)) throw new Error('Recorded Craft Skill is outside the selected installation: ' + skill);
85
+ }
86
+ // Verify the package content identity outside the state/configuration locks.
87
+ const expected = await verifiedTemplates(state, entries);
88
+ const locks = [], restoreTasks = [], tasks = [];
89
+ try {
90
+ for (const target of [paths.config, file].sort()) {
91
+ locks.push(await lockfile.lock(target, { realpath: false, stale: 120000, retries: 0 }));
92
+ }
93
+ locks.push(await lockfile.lock(runtimeRoot, { stale: 120000, retries: 0 }));
94
+ const snapshot = await unchangedInstallation(file, state);
95
+ const original = await optionalFile(paths.config);
96
+ const binding = craftConfig(original ?? '', host, serverId);
97
+ if (!samePath(binding?.env?.CRAFT_INSTALLATION_FILE, file) || binding.env.CRAFT_CLIENT_IDE !== host ||
98
+ (binding.env.CRAFT_SERVER_ID ?? 'craft') !== serverId ||
99
+ craftRegistrations(original, host).some(reg => reg.name !== serverId && samePath(reg.connection?.env?.CRAFT_INSTALLATION_FILE, file))) {
100
+ throw new Error('Craft registration ownership changed or is ambiguous; files were preserved');
101
+ }
102
+ assertDshSharedScope(paths, serverId);
103
+ await assertHostConfigScope(paths.config, host, paths.configPeers, serverId);
104
+ await verifyLauncher(state, file, binding);
105
+ const changes = [{ file: paths.config, before: original, after: removeConfig(original, host, serverId) }];
106
+ const shared = await sharedSkills(stateRoot, file, entries);
107
+ const preserved = [];
108
+ for (const entry of entries) {
109
+ await assertPlainPath(entry.file);
110
+ const before = await optionalFile(entry.file);
111
+ if (before === null) continue;
112
+ if (shared.has(entry.file) || expected.get(entry.name) !== before) {
113
+ preserved.push({ file: entry.file, reason: shared.has(entry.file) ? 'other_installation' : 'modified_or_unverified' });
114
+ } else {
115
+ changes.push({ file: entry.file, before, after: null });
116
+ }
117
+ }
118
+ if (state.launcher) {
119
+ const before = await optionalFile(state.launcher.entry);
120
+ if (before === null || createHash('sha256').update(before).digest('hex') !== state.launcher.sha256) {
121
+ throw new Error('Craft fixed launcher changed during uninstall; files were preserved');
122
+ }
123
+ changes.push({ file: state.launcher.entry, before, after: null });
124
+ }
125
+ changes.push({ file, before: snapshot.text, after: null });
126
+ // Task names include the installation file's hash. Each removal verifies
127
+ // scheduler ownership and the hidden helper before touching either.
128
+ if (host === 'workbuddy' && process.platform === 'win32' && state.launcher) {
129
+ for (const [remove, ensure] of [[removeWorkBuddyLoginTask, ensureWorkBuddyLoginTask], [removeWorkBuddyPreviewTask, ensureWorkBuddyPreviewTask]]) {
130
+ const receipt = await remove(file);
131
+ if (receipt.status === 'removed') restoreTasks.push(ensure);
132
+ tasks.push(receipt);
133
+ }
134
+ }
135
+ const written = await commitFiles(changes);
136
+ return { ...result, status: 'uninstalled', ...written, preserved_skills: preserved, ...(tasks.length ? { tasks } : {}) };
137
+ } catch (error) {
138
+ const failures = [error];
139
+ for (const ensure of restoreTasks.reverse()) {
140
+ try { await ensure(file); } catch (restoreError) { failures.push(restoreError); }
141
+ }
142
+ if (failures.length > 1) throw new AggregateError(failures, 'Craft uninstall failed and a WorkBuddy task could not be restored: ' + failures.map(e => e.message).join(', '));
143
+ throw error;
144
+ } finally {
145
+ for (const unlock of locks.reverse()) await unlock();
146
+ }
147
+ }
148
+
149
+ export async function runUninstallCommand([, ...args]) {
150
+ const options = {};
151
+ for (let i = 0; i < args.length; i += 2) {
152
+ const key = args[i], value = args[i + 1];
153
+ if (!['--ide', '--instance', '--host-config', '--trae-region'].includes(key) || !value || value.startsWith('--') || Object.hasOwn(options, key.slice(2))) {
154
+ throw new Error('Use uninstall --ide <host> [--instance <server-id>] [--host-config ABS] [--trae-region global|cn]');
155
+ }
156
+ options[key.slice(2)] = value;
157
+ }
158
+ const result = await uninstallHost({ ide: options.ide, serverId: options.instance, hostOptions: hostCommandOptions(options) });
159
+ process.stdout.write(JSON.stringify(result, null, 2) + '\n');
160
+ }
@@ -1,9 +1,11 @@
1
1
  import path from 'node:path';
2
2
  import { mkdir } from 'node:fs/promises';
3
+ import { isDeepStrictEqual } from 'node:util';
3
4
  import lockfile from 'proper-lockfile';
4
5
  import { readInstallation, readInstallationSnapshot, activationStatus, registryOrigin, installedSkillEntries, skillRuntimeIdentity, sameRuntimeIdentity, activationMode } from './installation-state.mjs';
5
6
  import { compareVersions, requireForwardVersion, parseVersion } from './version-policy.mjs';
6
7
  import { stageRegistryRuntime, getRuntimeIdentity, probeRuntime } from './runtime.mjs';
8
+ import { readRunningIdentity } from './runtime-identity.mjs';
7
9
  import { optionalFile, assertPlainPath, commitFiles } from './files.mjs';
8
10
  import { hostPaths, hostCommandOptions, installTargets } from './hosts.mjs';
9
11
  import { craftConfig, mergeConfig } from './config.mjs';
@@ -15,13 +17,15 @@ import { setTimeout as delay } from 'node:timers/promises';
15
17
  import { unchangedInstallation, installationChanged, installationBusy } from './installation-transaction.mjs';
16
18
  import { prepareRuntimeCandidate, publishRuntimeCandidate, disposeRuntimeCandidate, refreshRuntimeCandidate } from './runtime-candidate.mjs';
17
19
  import { assertHostConfigScope } from './host-config-scope.mjs';
20
+ import { validateServerId } from './instance.mjs';
21
+ import { renderInstanceSkill } from './instance-skill.mjs';
18
22
 
19
23
  export { readInstallation } from './installation-state.mjs';
20
24
  const pending = new Map();
21
25
  const receiptLifetime = 5 * 60 * 1000;
22
26
 
23
27
  function result(state, current, status, extra = {}) {
24
- return { status, installation_id: state.id, source: state.source, policy: state.policy,
28
+ return { status, installation_id: state.id, server_id: state.server_id, channel: state.source.channel, source: state.source, policy: state.policy,
25
29
  current, target: state.target, activation: activationStatus(current, state.target),
26
30
  activation_mode: state.activation_mode ?? 'legacy_front', migration_required: state.schema === 1,
27
31
  activation_required: false, reconnect_required: !sameRuntimeIdentity(current, state.target), explicitly_not_started: true, ...extra };
@@ -69,8 +73,9 @@ async function candidateSkills(state, identity) {
69
73
  const changes = [];
70
74
  for (const { name, file, marker } of installedSkillEntries(state)) {
71
75
  await assertPlainPath(file);
72
- const desired = await optionalFile(path.join(identity.package_root, 'resources', name, 'SKILL.md'));
73
- if (desired === null) throw new Error('Updated runtime is missing the managed ' + name + ' Skill');
76
+ const template = await optionalFile(path.join(identity.package_root, 'resources', name, 'SKILL.md'));
77
+ if (template === null) throw new Error('Updated runtime is missing the managed ' + name + ' Skill');
78
+ const desired = renderInstanceSkill(template, name, state.server_id);
74
79
  if (!desired.includes(marker)) throw new Error('Updated runtime has an invalid managed Skill marker');
75
80
  const before = await optionalFile(file);
76
81
  if (before && !before.includes(marker)) throw new Error('User-owned Skill preserved: ' + file);
@@ -83,7 +88,7 @@ const shortLock = { stale: 120000, retries: 0 };
83
88
 
84
89
  async function confirmationSnapshot(installationFile, current) {
85
90
  const snapshot = await readInstallationSnapshot(installationFile), { state } = snapshot;
86
- await assertHostConfigScope(state.config,state.host,state.config_peers);
91
+ await assertHostConfigScope(state.config,state.host,state.config_peers,state.server_id);
87
92
  if (state.schema !== 2 || state.activation_mode !== activationMode) throw new Error('Legacy Craft installation requires the standard installer before reconnecting');
88
93
  if (activationStatus(current, state.target).status !== 'active_verified') throw installationChanged('The current connection does not match the configured update target');
89
94
  await verifyLauncher(state, installationFile);
@@ -94,19 +99,10 @@ async function confirmationSnapshot(installationFile, current) {
94
99
 
95
100
  export async function confirmActiveInstallation({ installationFile, current }) {
96
101
  if (!current?.instance_id) throw new Error('An actual runtime instance is required to confirm the installation');
97
- // Capture small shared files consistently. Full package hashing never blocks
98
- // installers; a second short transaction detects concurrent scope/target changes.
99
- let unlock = await lockfile.lock(installationFile, shortLock), snapshot;
100
- try { snapshot = await confirmationSnapshot(installationFile, current); }
101
- finally { await unlock(); }
102
- let identity, integrityError;
103
- try { identity = await getRuntimeIdentity(current.package_root); }
104
- catch (error) { integrityError = error; }
105
- unlock = await lockfile.lock(installationFile, shortLock);
102
+ // The server captured its own package identity at startup. Compare that
103
+ // identity to the selected target and commit the receipt under one short lock.
104
+ const unlock = await lockfile.lock(installationFile, shortLock);
106
105
  try {
107
- await unchangedInstallation(installationFile, snapshot.state);
108
- if (integrityError) throw integrityError;
109
- if (!sameRuntimeIdentity(identity, snapshot.state.target)) throw new Error('The running package files do not match the configured update target');
110
106
  const { state, text: before } = await confirmationSnapshot(installationFile, current);
111
107
  const previous = state.connection_verification;
112
108
  const receipt = previous?.instance_id === current.instance_id ? previous : { version: current.version, build_id: current.build_id, instance_id: current.instance_id, confirmed_at: new Date().toISOString() };
@@ -125,24 +121,28 @@ async function saveCheckReceipt(installationFile, expected, receipt) {
125
121
  } finally { await unlock(); }
126
122
  }
127
123
 
128
- async function hostUpdate(state, installationFile, launcher, identity) {
129
- await assertHostConfigScope(state.config,state.host,state.config_peers);
130
- await assertPlainPath(state.config);
131
- if (state.host === 'dsh') assertDshSharedScope({ dshHome: path.dirname(state.config) });
132
- const before = await optionalFile(state.config);
133
- if (before === null) throw new Error('Craft host configuration is missing; run install again');
134
- const existing = craftConfig(before, state.host, state.server_id);
124
+ async function verifyRegisteredScope(existing, state, installationFile) {
135
125
  await verifyLauncher(state, installationFile, existing);
136
126
  const samePath = (a, b) => typeof a === 'string' && typeof b === 'string' && (process.platform === 'win32' ? path.resolve(a).toLowerCase() === path.resolve(b).toLowerCase() : path.resolve(a) === path.resolve(b));
137
127
  const workspaceIndex = existing?.args?.indexOf('--workspace') ?? -1;
138
- if (!existing || !samePath(existing.env?.CRAFT_INSTALLATION_FILE, installationFile) || existing.env?.CRAFT_CLIENT_IDE !== state.host ||
128
+ if (!existing || (existing.env?.CRAFT_SERVER_ID ?? 'craft') !== state.server_id || !samePath(existing.env?.CRAFT_INSTALLATION_FILE, installationFile) || existing.env?.CRAFT_CLIENT_IDE !== state.host ||
139
129
  !samePath(workspaceIndex >= 0 ? existing.args[workspaceIndex + 1] : existing.env?.CLIENT_WORKSPACE_ROOT, state.workspace) ||
140
130
  new URL(existing.env?.CRAFT_WEB_URL).origin !== new URL(state.platform).origin) throw new Error('Craft host configuration scope changed; run install with the intended scope');
131
+ }
132
+
133
+ async function hostUpdate(state, installationFile, launcher, identity) {
134
+ await assertHostConfigScope(state.config,state.host,state.config_peers,state.server_id);
135
+ await assertPlainPath(state.config);
136
+ if (state.host === 'dsh') assertDshSharedScope({ dshHome: path.dirname(state.config) }, state.server_id);
137
+ const before = await optionalFile(state.config);
138
+ if (before === null) throw new Error('Craft host configuration is missing; run install again');
139
+ const existing = craftConfig(before, state.host, state.server_id);
140
+ await verifyRegisteredScope(existing, state, installationFile);
141
141
  // Fixed-entry updates must not rewrite watched host configuration: a host
142
142
  // could otherwise restart an in-flight MCP task on an env-only change.
143
143
  if (state.launcher?.entry === launcher.entry) return { file: state.config, before, after: before };
144
- const connection = { command: existing.command, args: [launcher.entry, '--workspace', state.workspace], env: { CRAFT_CLIENT_IDE: state.host, CRAFT_WEB_URL: state.platform, CLIENT_WORKSPACE_ROOT: state.workspace, CRAFT_INSTALLATION_FILE: installationFile, CRAFT_RUNTIME_REVISION: identity.build_id } };
145
- return { file: state.config, before, after: mergeConfig(before, state.host, connection, { previousName: state.server_id, enable: false }) };
144
+ const connection = { command: existing.command, args: [launcher.entry, '--workspace', state.workspace], env: { ...existing.env, CRAFT_SERVER_ID: state.server_id, CRAFT_CLIENT_IDE: state.host, CRAFT_WEB_URL: state.platform, CLIENT_WORKSPACE_ROOT: state.workspace, CRAFT_INSTALLATION_FILE: installationFile, CRAFT_RUNTIME_REVISION: identity.build_id } };
145
+ return { file: state.config, before, after: mergeConfig(before, state.host, connection, { serverId: state.server_id, previousName: state.server_id, enable: false }) };
146
146
  }
147
147
 
148
148
  async function checkSnapshot({ installationFile, current, connectedSource, intent, requestKey, projectCompatibility, registryReceipt, lookup, materialize, probe }) {
@@ -215,7 +215,7 @@ async function checkSnapshot({ installationFile, current, connectedSource, inten
215
215
  let candidate, originalConfig;
216
216
  try {
217
217
  originalConfig = await optionalFile(state.config);
218
- candidate = await prepareRuntimeCandidate(runtimeRoot, stagingRoot => materialize(state.source, remote, stagingRoot));
218
+ candidate = await prepareRuntimeCandidate(runtimeRoot, stagingRoot => materialize(state.source, remote, stagingRoot), { repair:true, deferExisting:true });
219
219
  let identity = candidate.identity;
220
220
  if (!within(runtimeRoot, identity.package_root) || identity.package !== state.source.package || identity.version !== remote.version) throw new Error('Candidate runtime identity/path mismatch');
221
221
  requireForwardVersion(identity, state.target);
@@ -223,16 +223,23 @@ async function checkSnapshot({ installationFile, current, connectedSource, inten
223
223
  try { await projectCompatibility(identity.package_root); }
224
224
  catch (error) { return result(state, current, 'incompatible', { checked_at: checkedAt, remote, message: error.message, can_continue: false }); }
225
225
  }
226
- const verified = await probe({ command: process.execPath, args: [identity.entry, '--workspace', state.workspace], env: { CRAFT_CLIENT_IDE: state.host, CRAFT_WEB_URL: state.platform, CLIENT_WORKSPACE_ROOT: state.workspace } },
227
- { version: identity.version, build_id: identity.build_id, host: state.host, workspace: state.workspace, platform: state.platform });
228
- if (verified.runtime?.activation_mode !== activationMode) throw new Error('Candidate runtime does not support activation at the next MCP start');
226
+ const verifyRuntime = async runtime => {
227
+ const report = await probe({ command: process.execPath, args: [runtime.entry, '--workspace', state.workspace], env: { CRAFT_SERVER_ID: state.server_id, CRAFT_CLIENT_IDE: state.host, CRAFT_WEB_URL: state.platform, CLIENT_WORKSPACE_ROOT: state.workspace } },
228
+ { version: runtime.version, build_id: runtime.build_id, serverId: state.server_id, host: state.host, workspace: state.workspace, platform: state.platform });
229
+ if (report.runtime?.activation_mode !== activationMode) throw new Error('Candidate runtime does not support activation at the next MCP start');
230
+ return report;
231
+ };
232
+ const stagedProbe = await verifyRuntime(identity);
229
233
  if (!sameRuntimeIdentity(await getRuntimeIdentity(identity.package_root), identity)) throw new Error('Candidate runtime changed during startup verification');
230
234
  // Neither registry traffic nor materialization/probing owns a shared lock.
231
235
  // Re-read the authoritative state before publishing; receipt-only writes merge.
232
236
  const commitCandidate = async () => {
233
- const unlockState = await lockfile.lock(installationFile, shortLock);
237
+ const unlockScope = [];
234
238
  let unlockRuntime;
235
239
  try {
240
+ for (const file of [state.config, installationFile].map(file => path.resolve(file)).sort()) {
241
+ unlockScope.push(await lockfile.lock(file, { ...shortLock, realpath: false }));
242
+ }
236
243
  const latest = await unchangedInstallation(installationFile, state);
237
244
  state = latest.state;
238
245
  unlockRuntime = await lockfile.lock(runtimeRoot, shortLock);
@@ -246,8 +253,9 @@ async function checkSnapshot({ installationFile, current, connectedSource, inten
246
253
  await commitFiles([...skillChanges, launcherPlan.change, { file: installationFile, before: latest.text, after: JSON.stringify(after, null, 2) + '\n' }, configChange]);
247
254
  state = after;
248
255
  return result(state, current, 'pending_reconnect', { checked_at: checkedAt, remote, reconnect_required: true, can_continue: false, verified: { ...verified, scope: 'standalone_probe' } });
249
- } finally { try { await unlockRuntime?.(); } finally { await unlockState(); } }
256
+ } finally { try { await unlockRuntime?.(); } finally { for (const release of unlockScope.reverse()) await release(); } }
250
257
  };
258
+ let verified = await refreshRuntimeCandidate(candidate, verifyRuntime) ?? stagedProbe;
251
259
  for (let attempt = 0; ; attempt++) {
252
260
  try { return await commitCandidate(); }
253
261
  catch (error) {
@@ -256,7 +264,7 @@ async function checkSnapshot({ installationFile, current, connectedSource, inten
256
264
  // remains unchanged. Reuse the complete download and revalidate the
257
265
  // existing target outside locks, rather than downloading a second time.
258
266
  await unchangedInstallation(installationFile, state);
259
- if (error.code === 'INSTALLATION_CHANGED') await refreshRuntimeCandidate(candidate);
267
+ if (error.code === 'INSTALLATION_CHANGED') verified = await refreshRuntimeCandidate(candidate, verifyRuntime) ?? stagedProbe;
260
268
  await delay(100 * (attempt + 1));
261
269
  }
262
270
  }
@@ -267,11 +275,14 @@ async function checkSnapshot({ installationFile, current, connectedSource, inten
267
275
  const failure = { checked_at: checkedAt, remote, code: 'candidate_rejected', message: error.message, ...(error.npm_code?{npm_code:error.npm_code}:{}) };
268
276
  try {
269
277
  // A failed candidate must not disable a verified existing installation.
270
- // Recheck the rollback, scope and complete old package before allowing work.
278
+ // Verify rollback, scope and the installed identity of the retained package.
271
279
  if (state.schema !== 2 || activationPending || currentIncompatible) throw new Error(currentIncompatible ?? 'No compatible active installation to retain');
272
280
  await unchangedInstallation(installationFile, state);
273
- if (originalConfig === undefined || originalConfig === null || await optionalFile(state.config) !== originalConfig) throw new Error('Host configuration changed; rollback could not be verified');
274
- if (!sameRuntimeIdentity(await getRuntimeIdentity(current.package_root), state.target)) throw new Error('Existing runtime integrity check failed');
281
+ const retainedConfig = await optionalFile(state.config);
282
+ if (originalConfig == null || retainedConfig === null || !isDeepStrictEqual(
283
+ craftConfig(retainedConfig, state.host, state.server_id), craftConfig(originalConfig, state.host, state.server_id)
284
+ )) throw new Error('Host registration changed; rollback could not be verified');
285
+ if (!sameRuntimeIdentity(await readRunningIdentity(current.package_root, { managed:true }), state.target)) throw new Error('Existing runtime installation identity check failed');
275
286
  await hostUpdate(state, installationFile, state.launcher ?? { entry: current.entry }, current);
276
287
  if (!state.launcher && path.resolve(craftConfig(originalConfig, state.host, state.server_id).args[0]) !== path.resolve(current.entry)) throw new Error('Existing runtime entry differs from the configured connection');
277
288
  const skills = await candidateSkills(state, current);
@@ -313,20 +324,24 @@ export async function runUpdateCommand(args) {
313
324
  const [command, ...rest] = args, options = {};
314
325
  for (let i = 0; i < rest.length; i += 2) {
315
326
  const key = rest[i]?.replace(/^--/, '');
316
- if (!['--ide','--host-config','--trae-region'].includes(rest[i]) || !rest[i + 1] || Object.hasOwn(options, key)) throw new Error('Use craft-mcp ' + command + ' --ide <host> [--host-config ABS] [--trae-region global|cn]');
327
+ if (!['--ide','--instance','--host-config','--trae-region'].includes(rest[i]) || !rest[i + 1] || Object.hasOwn(options, key)) throw new Error('Use craft-mcp ' + command + ' --ide <host> [--instance <server-id>] [--host-config ABS] [--trae-region global|cn]');
317
328
  options[key] = rest[i + 1];
318
329
  }
319
330
  const results = [];
331
+ const serverId = validateServerId(options.instance ?? 'craft');
320
332
  const hostOptions = hostCommandOptions(options);
321
333
  for (const host of installTargets(options.ide)) {
322
- const paths = hostPaths(os.homedir(), host, process.env.CODEX_HOME, hostOptions);
334
+ const paths = hostPaths(os.homedir(), host, process.env.CODEX_HOME, { ...hostOptions, serverId });
323
335
  await assertPlainPath(paths.config);
324
- assertDshSharedScope(paths);
325
- const connection = craftConfig(await optionalFile(paths.config) ?? '', host);
336
+ assertDshSharedScope(paths,serverId);
337
+ await assertHostConfigScope(paths.config,host,paths.configPeers,serverId);
338
+ const connection = craftConfig(await optionalFile(paths.config) ?? '', host, serverId);
326
339
  const installationFile = connection?.env?.CRAFT_INSTALLATION_FILE;
327
340
  if (!installationFile) throw new Error(host + ': Install Craft once before using automatic updates');
328
341
  const state = await readInstallation(installationFile);
329
- const current = await getRuntimeIdentity(state.target.package_root);
342
+ if (state.host !== host || state.server_id !== serverId || path.relative(state.config, paths.config) !== '' || (connection.env.CRAFT_SERVER_ID ?? 'craft') !== serverId) throw new Error('Craft registration does not match the selected installation scope: ' + serverId);
343
+ await verifyRegisteredScope(connection, state, installationFile);
344
+ const current = await readRunningIdentity(state.target.package_root, { managed:Boolean(state.launcher) });
330
345
  const update = await checkForUpdate({ installationFile, current, intent: command === 'update' ? 'update' : 'inspect', requestKey: 'cli-' + Date.now() });
331
346
  if (update.status === 'installation_busy') {
332
347
  results.push({ host, ...update, scope: 'configured_runtime' });
@@ -335,7 +350,7 @@ export async function runUpdateCommand(args) {
335
350
  }
336
351
  // A CLI can inspect configured files, but cannot prove a host connection.
337
352
  results.push({ host, ...update, activation: { status: 'pending_connection_verification', expected: update.target }, can_continue: false, scope: 'configured_runtime', note: 'Call craft_game_info in the actual host connection to confirm activation.',
338
- ...(!['error','update_failed','incompatible','migration_required'].includes(update.status) ? {connection_handoff:connectionHandoff({host,target:update.target,workspace:state.workspace,platform:state.platform,intent:command==='update'?'update':'inspect'})} : {}) });
353
+ ...(!['error','update_failed','incompatible','migration_required'].includes(update.status) ? {connection_handoff:connectionHandoff({host,serverId,channel:state.source.channel,target:update.target,workspace:state.workspace,platform:state.platform,intent:command==='update'?'update':'inspect'})} : {}) });
339
354
  if (['error', 'update_failed', 'incompatible'].includes(update.status)) process.exitCode = 1;
340
355
  }
341
356
  process.stdout.write(JSON.stringify({ hosts: results }, null, 2) + '\n');
@@ -1677,6 +1677,14 @@ function requireForwardVersion(next, previous) {
1677
1677
  if (comparison === 0 && previous.build_id && next.build_id && previous.build_id !== next.build_id) throw new Error("Craft same-version build replacement refused; publish a new version");
1678
1678
  }
1679
1679
 
1680
+ // dist-server/integrations/instance.mjs
1681
+ function validateServerId(id) {
1682
+ if (typeof id !== "string" || id.length > 32 || !/^craft(?:-[a-z0-9]+(?:-[a-z0-9]+)*)?$/.test(id)) {
1683
+ throw new Error("Invalid Craft instance name; use craft or craft-<lowercase-identifier> (up to 32 characters)");
1684
+ }
1685
+ return id;
1686
+ }
1687
+
1680
1688
  // dist-server/integrations/hosts.mjs
1681
1689
  var hosts = Object.freeze({
1682
1690
  codex: { label: "Codex", config: ".codex/config.toml", skills: ".agents/skills", projectSkills: ".agents/skills", format: "toml" },
@@ -1695,6 +1703,13 @@ var hosts = Object.freeze({
1695
1703
  qwen: { label: "Qwen Code", config: ".qwen/settings.json", skills: ".qwen/skills", projectSkills: ".qwen/skills", format: "jsonc" }
1696
1704
  });
1697
1705
 
1706
+ // dist-server/integrations/instance-skill.mjs
1707
+ function instanceSkillName(logicalName, serverId = "craft") {
1708
+ validateServerId(serverId);
1709
+ if (!["craft-create", "craft-update"].includes(logicalName)) throw new Error("Unknown Craft entrypoint Skill");
1710
+ return serverId + logicalName.slice("craft".length);
1711
+ }
1712
+
1698
1713
  // dist-server/integrations/installation-state.mjs
1699
1714
  var defaultRegistry = "https://registry.npmjs.org/";
1700
1715
  var activationMode = "next_mcp_start";
@@ -1707,7 +1722,7 @@ function installedSkillEntries(state) {
1707
1722
  if (state.skills === void 0) return [];
1708
1723
  if (!state.skills || typeof state.skills !== "object" || Array.isArray(state.skills) || !state.skills["craft-create"]) throw new Error("Invalid installed Skill destinations");
1709
1724
  return Object.entries(state.skills).map(([name, file]) => {
1710
- if (!Object.hasOwn(managedSkillMarkers, name) || typeof file !== "string" || !path2.isAbsolute(file) || path2.basename(file) !== "SKILL.md" || path2.basename(path2.dirname(file)) !== name) throw new Error("Invalid installed Skill destination");
1725
+ if (!Object.hasOwn(managedSkillMarkers, name) || typeof file !== "string" || !path2.isAbsolute(file) || path2.basename(file) !== "SKILL.md" || path2.basename(path2.dirname(file)) !== instanceSkillName(name, state.server_id)) throw new Error("Invalid installed Skill destination");
1711
1726
  return { name, file, marker: managedSkillMarkers[name] };
1712
1727
  });
1713
1728
  }
@@ -1756,9 +1771,7 @@ async function readInstallation(file) {
1756
1771
  import path3 from "node:path";
1757
1772
  import { readFile as readFile2, readdir, lstat as lstat2 } from "node:fs/promises";
1758
1773
  import { createHash } from "node:crypto";
1759
- async function getRuntimeIdentity(packageRoot) {
1760
- packageRoot = path3.resolve(packageRoot);
1761
- const pkg = JSON.parse(await readFile2(path3.join(packageRoot, "package.json"), "utf8"));
1774
+ async function hashRuntimeFiles(packageRoot, files) {
1762
1775
  const hash = createHash("sha256");
1763
1776
  async function visit(relative) {
1764
1777
  const file = path3.join(packageRoot, relative);
@@ -1772,11 +1785,51 @@ async function getRuntimeIdentity(packageRoot) {
1772
1785
  if (info.isSymbolicLink()) throw new Error("Craft runtime contains a linked product file: " + relative);
1773
1786
  if (info.isDirectory()) {
1774
1787
  for (const entry of (await readdir(file)).sort()) if (entry !== "node_modules") await visit(relative + "/" + entry);
1775
- } else if (info.isFile()) hash.update(relative + "\0").update(await readFile2(file)).update("\0");
1776
- else throw new Error("Invalid Craft runtime file: " + relative);
1788
+ } else if (info.isFile()) {
1789
+ const bytes = await readFile2(file);
1790
+ hash.update(relative + "\0").update(bytes).update("\0");
1791
+ if (files) files[relative] = createHash("sha256").update(bytes).digest("hex");
1792
+ } else throw new Error("Invalid Craft runtime file: " + relative);
1777
1793
  }
1778
1794
  for (const relative of ["package.json", "bin", "dist-server", "resources", "vendor"]) await visit(relative);
1779
- return { package: pkg.name, version: pkg.version, build_id: hash.digest("hex"), package_root: packageRoot, entry: path3.join(packageRoot, "bin/craft-mcp.mjs") };
1795
+ return hash.digest("hex");
1796
+ }
1797
+ function identityForPackage(packageRoot, pkg, buildId) {
1798
+ return { package: pkg.name, version: pkg.version, build_id: buildId, package_root: packageRoot, entry: path3.join(packageRoot, "bin/craft-mcp.mjs") };
1799
+ }
1800
+ async function getRuntimeIdentity(packageRoot, { files } = {}) {
1801
+ packageRoot = path3.resolve(packageRoot);
1802
+ const pkg = JSON.parse(await readFile2(path3.join(packageRoot, "package.json"), "utf8"));
1803
+ return identityForPackage(packageRoot, pkg, await hashRuntimeFiles(packageRoot, files));
1804
+ }
1805
+ function runtimeDirectoryForPackage(packageRoot) {
1806
+ const parent = path3.dirname(path3.resolve(packageRoot));
1807
+ const modules = path3.basename(parent).startsWith("@") ? path3.dirname(parent) : parent;
1808
+ return path3.basename(modules) === "node_modules" ? path3.dirname(modules) : null;
1809
+ }
1810
+ async function readRunningIdentity(packageRoot, { managed = false } = {}) {
1811
+ packageRoot = path3.resolve(packageRoot);
1812
+ const directory = runtimeDirectoryForPackage(packageRoot);
1813
+ if (!directory) return getRuntimeIdentity(packageRoot);
1814
+ const receiptFile = path3.join(directory, "craft-runtime.json");
1815
+ await assertPlainPath(receiptFile);
1816
+ const text = await optionalFile(receiptFile);
1817
+ if (text === null) {
1818
+ if (managed) throw new Error("Craft runtime installation receipt is missing; run doctor for the selected instance");
1819
+ return getRuntimeIdentity(packageRoot);
1820
+ }
1821
+ const receipt = JSON.parse(text);
1822
+ const packageFile = path3.join(packageRoot, "package.json");
1823
+ await assertPlainPath(packageFile);
1824
+ const pkg = JSON.parse(await readFile2(packageFile, "utf8"));
1825
+ const name = path3.relative(path3.join(directory, "node_modules"), packageRoot).split(path3.sep).join("/");
1826
+ if (name !== pkg.name || receipt.package !== pkg.name || receipt.version !== pkg.version || !/^[a-f0-9]{64}$/.test(receipt.sha256 ?? "") || receipt.build_id !== void 0 && !/^[a-f0-9]{64}$/.test(receipt.build_id)) {
1827
+ throw new Error("Craft runtime package and installation receipt disagree; run doctor for the selected instance");
1828
+ }
1829
+ const identity = identityForPackage(packageRoot, pkg, receipt.build_id ?? await hashRuntimeFiles(packageRoot));
1830
+ await assertPlainPath(identity.entry);
1831
+ if (!(await lstat2(identity.entry)).isFile()) throw new Error("Craft runtime entry must be a regular file");
1832
+ return identity;
1780
1833
  }
1781
1834
 
1782
1835
  // dist-server/integrations/fixed-launcher.mjs
@@ -1787,6 +1840,7 @@ function launcherPath(installationFile) {
1787
1840
  return installationFile.replace(/\.json$/, "") + ".launcher.mjs";
1788
1841
  }
1789
1842
  async function verifyLauncher(state, installationFile, connection) {
1843
+ if (connection?.env && (connection.env.CRAFT_SERVER_ID ?? "craft") !== state.server_id) throw new Error("Craft launcher instance differs from its registration");
1790
1844
  if (!state.launcher) return { mode: "legacy_versioned_entry" };
1791
1845
  const expected = launcherPath(installationFile);
1792
1846
  if (state.launcher.schema !== 1 || state.launcher.entry !== expected || !/^[a-f0-9]{64}$/.test(state.launcher.sha256 ?? "")) throw new Error("Invalid Craft fixed launcher identity");
@@ -1818,15 +1872,15 @@ async function start() {
1818
1872
  if (state.host === "workbuddy" && state.login_data_dir && process.env.CRAFT_STANDALONE_PROBE !== "1") {
1819
1873
  process.env.CLIENT_DATA_DIR ||= state.login_data_dir;
1820
1874
  }
1821
- for (const [key, expected] of Object.entries({ CRAFT_CLIENT_IDE: state.host, CLIENT_WORKSPACE_ROOT: state.workspace, CRAFT_WEB_URL: state.platform })) {
1875
+ 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 })) {
1822
1876
  if (process.env[key] && process.env[key] !== expected) throw new Error("Craft launcher scope mismatch: " + key);
1823
1877
  process.env[key] = expected;
1824
1878
  }
1825
1879
  const relative = path5.relative(path5.resolve(state.runtime_root), state.target.package_root);
1826
1880
  if (!relative || relative === ".." || relative.startsWith(".." + path5.sep) || path5.isAbsolute(relative)) throw new Error("Craft target is outside the managed runtime root");
1827
1881
  await assertPlainPath(state.target.entry);
1828
- identity = await getRuntimeIdentity(state.target.package_root);
1829
- if (!sameRuntimeIdentity(identity, state.target)) throw new Error("Craft target package integrity mismatch");
1882
+ identity = await readRunningIdentity(state.target.package_root, { managed: true });
1883
+ if (!sameRuntimeIdentity(identity, state.target)) throw new Error("Craft target and installed runtime identity differ; run doctor for the selected instance");
1830
1884
  const leaseRoot = path5.join(state.runtime_root, ".connections");
1831
1885
  await mkdir2(leaseRoot, { recursive: true });
1832
1886
  lease = path5.join(leaseRoot, "launcher-" + randomUUID() + ".json");
@@ -1846,6 +1900,7 @@ async function start() {
1846
1900
  const targetEntry = preview ? path5.join(identity.package_root, "dist-server/preview/workbuddy-preview-task-worker.mjs") : loginPage ? path5.join(identity.package_root, "dist-server/mcp/workbuddy-login-task-worker.mjs") : identity.entry;
1847
1901
  process.argv = [process.execPath, targetEntry, ...loginPage || preview ? [installationFile] : process.argv.slice(2)];
1848
1902
  try {
1903
+ await assertPlainPath(targetEntry);
1849
1904
  await import(pathToFileURL(targetEntry).href);
1850
1905
  } catch (error) {
1851
1906
  await unlink2(lease).catch(() => {