@craft_eco/craft-mcp 0.1.5 → 0.1.7

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 (89) hide show
  1. package/README.md +8 -8
  2. package/bin/craft-mcp.mjs +28 -2
  3. package/dist-server/engines/unreal/artifacts.mjs +7 -3
  4. package/dist-server/engines/unreal/check.mjs +56 -7
  5. package/dist-server/engines/unreal/export.mjs +3 -3
  6. package/dist-server/engines/unreal/external-environment.mjs +7 -1
  7. package/dist-server/engines/unreal/preview-project.mjs +2 -2
  8. package/dist-server/engines/unreal/project.mjs +44 -12
  9. package/dist-server/game-workflow/project-context.mjs +7 -6
  10. package/dist-server/game-workflow/project-install.mjs +2 -1
  11. package/dist-server/integrations/config.mjs +41 -18
  12. package/dist-server/integrations/connect.mjs +18 -9
  13. package/dist-server/integrations/connection-handoff.mjs +9 -8
  14. package/dist-server/integrations/dsh-config.mjs +30 -14
  15. package/dist-server/integrations/files.mjs +3 -1
  16. package/dist-server/integrations/fixed-launcher.mjs +1 -0
  17. package/dist-server/integrations/host-config-scope.mjs +4 -3
  18. package/dist-server/integrations/hosts.mjs +3 -1
  19. package/dist-server/integrations/install-source.mjs +44 -0
  20. package/dist-server/integrations/install.mjs +183 -53
  21. package/dist-server/integrations/installation-state.mjs +2 -1
  22. package/dist-server/integrations/instance-skill.mjs +26 -0
  23. package/dist-server/integrations/instance.mjs +29 -0
  24. package/dist-server/integrations/launcher-start.mjs +1 -1
  25. package/dist-server/integrations/login-task-command.mjs +3 -3
  26. package/dist-server/integrations/opencode-config.mjs +13 -6
  27. package/dist-server/integrations/project-setup.mjs +46 -18
  28. package/dist-server/integrations/runtime.mjs +2 -1
  29. package/dist-server/integrations/uninstall.mjs +160 -0
  30. package/dist-server/integrations/updates.mjs +57 -28
  31. package/dist-server/launcher.mjs +18 -2
  32. package/dist-server/mcp/server.mjs +19 -10
  33. package/dist-server/mcp/update-session.mjs +34 -12
  34. package/dist-server/upstream/craft-aigc.mjs +11 -2
  35. package/dist-server/upstream/draft-audit.mjs +52 -6
  36. package/package.json +4 -3
  37. package/resources/craft-create/SKILL.md +2 -0
  38. package/resources/craft-update/SKILL.md +2 -0
  39. package/resources/targets/claude/unreal/target.json +6 -6
  40. package/resources/targets/claude/unreal/unreal/bundle.json +10 -10
  41. package/resources/targets/claude/unreal/unreal/context/web/knowledge/WebBuild.md +6 -6
  42. package/resources/targets/codebuddy/unreal/target.json +6 -6
  43. package/resources/targets/codebuddy/unreal/unreal/bundle.json +10 -10
  44. package/resources/targets/codebuddy/unreal/unreal/context/web/knowledge/WebBuild.md +9 -7
  45. package/resources/targets/codex/unreal/target.json +6 -6
  46. package/resources/targets/codex/unreal/unreal/bundle.json +10 -10
  47. package/resources/targets/codex/unreal/unreal/context/web/knowledge/WebBuild.md +9 -7
  48. package/resources/targets/comate/unreal/target.json +6 -6
  49. package/resources/targets/comate/unreal/unreal/bundle.json +10 -10
  50. package/resources/targets/comate/unreal/unreal/context/web/knowledge/WebBuild.md +6 -6
  51. package/resources/targets/cursor/unreal/target.json +6 -6
  52. package/resources/targets/cursor/unreal/unreal/bundle.json +10 -10
  53. package/resources/targets/cursor/unreal/unreal/context/web/knowledge/WebBuild.md +6 -6
  54. package/resources/targets/dsh/unreal/target.json +6 -6
  55. package/resources/targets/dsh/unreal/unreal/bundle.json +10 -10
  56. package/resources/targets/dsh/unreal/unreal/context/web/knowledge/WebBuild.md +6 -6
  57. package/resources/targets/index.json +28 -28
  58. package/resources/targets/kimi/unreal/target.json +6 -6
  59. package/resources/targets/kimi/unreal/unreal/bundle.json +10 -10
  60. package/resources/targets/kimi/unreal/unreal/context/web/knowledge/WebBuild.md +6 -6
  61. package/resources/targets/opencode/unreal/target.json +6 -6
  62. package/resources/targets/opencode/unreal/unreal/bundle.json +10 -10
  63. package/resources/targets/opencode/unreal/unreal/context/web/knowledge/WebBuild.md +6 -6
  64. package/resources/targets/qoder/unreal/target.json +6 -6
  65. package/resources/targets/qoder/unreal/unreal/bundle.json +10 -10
  66. package/resources/targets/qoder/unreal/unreal/context/web/knowledge/WebBuild.md +6 -6
  67. package/resources/targets/qoder-cn/unreal/target.json +6 -6
  68. package/resources/targets/qoder-cn/unreal/unreal/bundle.json +10 -10
  69. package/resources/targets/qoder-cn/unreal/unreal/context/web/knowledge/WebBuild.md +6 -6
  70. package/resources/targets/qwen/unreal/target.json +6 -6
  71. package/resources/targets/qwen/unreal/unreal/bundle.json +10 -10
  72. package/resources/targets/qwen/unreal/unreal/context/web/knowledge/WebBuild.md +6 -6
  73. package/resources/targets/trae/unreal/target.json +6 -6
  74. package/resources/targets/trae/unreal/unreal/bundle.json +10 -10
  75. package/resources/targets/trae/unreal/unreal/context/web/knowledge/WebBuild.md +6 -6
  76. package/resources/targets/workbuddy/unreal/target.json +6 -6
  77. package/resources/targets/workbuddy/unreal/unreal/bundle.json +11 -11
  78. package/resources/targets/workbuddy/unreal/unreal/context/web/knowledge/WebBuild.md +7 -11
  79. package/resources/targets/workbuddy/unreal/unreal/context/web/skills/unreal-verify/SKILL.md +1 -1
  80. package/resources/targets/zcode/unreal/target.json +6 -6
  81. package/resources/targets/zcode/unreal/unreal/bundle.json +10 -10
  82. package/resources/targets/zcode/unreal/unreal/context/web/knowledge/WebBuild.md +6 -6
  83. package/resources/templates/unreal/project/Config/DefaultWebPublisher.ini +27 -21
  84. package/resources/templates/unreal/project/Config/README.md +10 -1
  85. package/resources/templates/unreal/project/Plugins/WebPublisher/Source/WebPublisher/Private/WebPublisherModule.cpp +13 -0
  86. package/resources/templates/unreal/project/template.json +33 -33
  87. package/resources/unreal-websdk/Setup-WebSDK.ps1 +2 -1
  88. package/resources/unreal-websdk/WebSDK-Packages.ps1 +143 -33
  89. package/resources/unreal-websdk/websdk-release.json +1 -5
@@ -17,15 +17,16 @@ import { inspectUnreal } from '../engines/unreal/project.mjs';
17
17
  import { engineDefinition } from '../game-workflow/engines.mjs';
18
18
  import { verifyBundle } from '../game-workflow/bundle-files.mjs';
19
19
  import { assertHostConfigScope } from './host-config-scope.mjs';
20
+ import { registrationsForInstance, validateServerId } from './instance.mjs';
20
21
 
21
22
  const samePath = (left, right) => typeof left === 'string' && typeof right === 'string' &&
22
23
  (process.platform === 'win32' ? path.resolve(left).toLowerCase() === path.resolve(right).toLowerCase() : path.resolve(left) === path.resolve(right));
23
24
 
24
- function connectionRequirements(project, ide, manifest) {
25
+ function connectionRequirements(project, ide, manifest, serverId) {
25
26
  return {
26
27
  status: 'unverified', trust: 'unknown', source: 'current_host_session',
27
28
  tool: 'craft_game_info', arguments: { name: path.basename(project) },
28
- expected: { host: ide, workspace: path.dirname(project), project, engine: manifest.engine,
29
+ expected: { host: ide, server_id: serverId, channel: manifest.channel, workspace: path.dirname(project), project, engine: manifest.engine,
29
30
  platform: manifest.platform, minimum_version: manifest.minimum_mcp_version },
30
31
  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.',
31
32
  reconnect: hostReloadProfile(ide),
@@ -36,6 +37,7 @@ function bootstrapCommand(project, ide, manifest, paths, hostOptions) {
36
37
  return { command: 'npx', args: ['-y', '--registry=' + manifest.registry,
37
38
  manifest.package_name + '@' + manifest.minimum_mcp_version,
38
39
  'project-setup', '--project', project, '--ide', ide,
40
+ ...(hostOptions.serverId ? ['--instance', hostOptions.serverId] : []),
39
41
  ...(hosts[ide].explicitConfig || hostOptions.configPath || hostOptions.hostConfigs?.[ide] ? ['--host-config',paths.config] : []),
40
42
  ...(ide==='trae' ? ['--trae-region',hostOptions.traeRegion??'global'] : [])] };
41
43
  }
@@ -55,8 +57,8 @@ async function validateGame(project, manifest, host) {
55
57
  return readContextLock(project, manifest.engine);
56
58
  }
57
59
 
58
- async function readHostRegistration(paths, ide) {
59
- await assertHostConfigScope(paths.config,ide,paths.configPeers);
60
+ async function readHostRegistration(paths, ide, serverId) {
61
+ await assertHostConfigScope(paths.config,ide,paths.configPeers,serverId);
60
62
  await assertPlainPath(paths.config);
61
63
  let content = await optionalFile(paths.config) ?? '';
62
64
  if (paths.fallbackConfig) {
@@ -66,7 +68,7 @@ async function readHostRegistration(paths, ide) {
66
68
  return craftRegistrations(content, ide);
67
69
  }
68
70
 
69
- async function projectRegistration(project, ide) {
71
+ async function projectRegistration(project, ide, serverId) {
70
72
  const candidates = {
71
73
  codex: ['.codex/config.toml'], workbuddy: ['.workbuddy/mcp.json'],
72
74
  cursor: ['.cursor/mcp.json'], codebuddy: ['.codebuddy/.mcp.json', '.codebuddy/mcp.json'],
@@ -79,20 +81,26 @@ async function projectRegistration(project, ide) {
79
81
  const config = path.join(project, relative);
80
82
  await assertPlainPath(config);
81
83
  const content = await optionalFile(config);
82
- if (content !== null && craftRegistrations(content, ide).length) return config;
84
+ if (content === null) continue;
85
+ const registrations = craftRegistrations(content, ide);
86
+ if ((serverId === undefined ? registrations : registrationsForInstance(registrations, serverId)).length) return config;
83
87
  }
84
88
  return null;
85
89
  }
86
90
 
87
91
  // This command inspects configuration only. It cannot observe host trust,
88
92
  // deferred-tool discovery, or the connection attached to the user's chat.
89
- export async function setupProject({ project, ide, packageRoot, install = false,
93
+ export async function setupProject({ project, ide, packageRoot, install = false, serverId,
90
94
  home = os.homedir(), codexHome, hostOptions = {}, runtimeRoot, stateRoot,
91
95
  installer = installHosts } = {}) {
92
96
  if (!Object.hasOwn(hosts, ide ?? '')) throw new Error('--ide must select exactly one supported host');
93
97
  if (typeof project !== 'string' || !path.isAbsolute(project)) throw new Error('--project must be an absolute existing Craft game directory');
94
98
  if (typeof packageRoot !== 'string' || !path.isAbsolute(packageRoot)) throw new Error('Craft packageRoot must be absolute');
95
99
  if (typeof install !== 'boolean') throw new Error('--install is a boolean flag');
100
+ if (serverId !== undefined) {
101
+ validateServerId(serverId);
102
+ hostOptions = { ...hostOptions, serverId };
103
+ }
96
104
  project = path.resolve(project);
97
105
  const stat = await lstat(project);
98
106
  const canonicalProject = await realpath(project);
@@ -108,19 +116,23 @@ export async function setupProject({ project, ide, packageRoot, install = false,
108
116
  if (!manifest) return { ...base, status: 'missing_project_install_metadata',
109
117
  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.' };
110
118
  const lock = await validateGame(project, manifest, ide);
111
- const verification = connectionRequirements(project, ide, manifest);
119
+ const verification = connectionRequirements(project, ide, manifest, serverId);
112
120
  const expected = { engine: manifest.engine, workspace: path.dirname(project), platform: manifest.platform,
113
121
  registry: manifest.registry, channel: manifest.channel, minimum_version: manifest.minimum_mcp_version };
114
122
  const response = { ...base, expected, verification };
115
- const localConfig = await projectRegistration(project, ide);
123
+ const localConfig = await projectRegistration(project, ide, serverId);
116
124
  if (localConfig) return { ...response, status: 'project_configuration_unverified', project_config: localConfig,
117
125
  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.' };
118
- const registrations = await readHostRegistration(paths, ide);
119
- if (registrations.length > 1) return { ...response, status: 'multiple_installations',
120
- next: 'Several Craft registrations exist. Select the intended connection without replacing other environments.' };
121
- const existing = registrations[0];
122
- if (existing) {
126
+ const registrations = await readHostRegistration(paths, ide, serverId);
127
+ async function inspectRegistration(existing) {
123
128
  const connection = existing.connection;
129
+ const marked = connection?.env?.CRAFT_SERVER_ID;
130
+ // Older installations can use a user-renamed tool namespace while the
131
+ // runtime and installation record still identify the default Craft slot.
132
+ const instance = marked ?? 'craft';
133
+ if (serverId === undefined && instance !== 'craft') await assertHostConfigScope(paths.config, ide, paths.configPeers, instance);
134
+ const verification = connectionRequirements(project, ide, manifest, instance);
135
+ const response = { ...base, registration: existing.name, server_id: instance, expected, verification };
124
136
  if (!connection || typeof connection !== 'object') return { ...response, status: 'invalid_configuration', next: 'Repair the existing Craft configuration; it was preserved.' };
125
137
  if (connection.disabled === true || connection.enabled === false || connection.enable === false) return { ...response, status: 'disabled',
126
138
  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.' };
@@ -146,7 +158,8 @@ export async function setupProject({ project, ide, packageRoot, install = false,
146
158
  await assertPlainPath(connection.env.CRAFT_INSTALLATION_FILE);
147
159
  state = await readInstallation(connection.env.CRAFT_INSTALLATION_FILE);
148
160
  } 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.' }; }
149
- if (state.host !== ide || !samePath(state.config, paths.config) || !samePath(state.workspace, expected.workspace) || state.platform !== expected.platform ||
161
+ if (state.server_id !== instance || (marked !== undefined && marked !== existing.name) ||
162
+ state.host !== ide || !samePath(state.config, paths.config) || !samePath(state.workspace, expected.workspace) || state.platform !== expected.platform ||
150
163
  state.source.package !== manifest.package_name || registryOrigin(state.source.registry) !== registryOrigin(manifest.registry) || state.source.channel !== manifest.channel) return { ...response, status: 'scope_mismatch',
151
164
  next: 'The recorded installation host, project scope, platform or package source differs from this project. Preserve it and resolve the intended connection explicitly.' };
152
165
  if (!workspace || !platform || host !== ide || !connection.command) return { ...response, status: 'invalid_configuration',
@@ -158,6 +171,21 @@ export async function setupProject({ project, ide, packageRoot, install = false,
158
171
  return { ...response, status: 'configured_unverified', installed_target: target,
159
172
  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.' };
160
173
  }
174
+ const candidates = serverId === undefined ? registrations : registrationsForInstance(registrations, serverId);
175
+ const inspected = await Promise.all(candidates.map(inspectRegistration));
176
+ const matching = inspected.filter(item => ['configured_unverified', 'update_required'].includes(item.status));
177
+ if (matching.length === 1) return matching[0];
178
+ const unresolved = inspected.filter(item => item.status !== 'scope_mismatch');
179
+ if (matching.length > 1 || (!matching.length && unresolved.length && inspected.length > 1 && !serverId)) {
180
+ return { ...response, status: 'multiple_installations', candidates: (matching.length ? matching : inspected).map(item => item.registration),
181
+ next: 'Select the intended Craft registration explicitly with --instance. No installation was changed.' };
182
+ }
183
+ if (serverId && inspected.length) return inspected[0];
184
+ const defaultRegistration = inspected.find(item => item.server_id === 'craft');
185
+ if (unresolved.length || (manifest.channel === 'stable' && defaultRegistration)) return unresolved[0] ?? defaultRegistration;
186
+ if (manifest.channel !== 'stable' && (!serverId || serverId === 'craft')) return { ...response, status: 'instance_required',
187
+ next: 'This project tracks a non-stable channel. Select the intended named Craft instance explicitly with --instance before installing it.' };
188
+ verification.expected.server_id = serverId ?? 'craft';
161
189
  const pkg = JSON.parse(await readFile(path.join(packageRoot, 'package.json'), 'utf8'));
162
190
  if (pkg.name !== manifest.package_name) throw new Error('Running CLI package does not match the project installation package');
163
191
  if (compareVersions(pkg.version, manifest.minimum_mcp_version) < 0) return { ...response, status: 'installer_update_required',
@@ -174,7 +202,7 @@ export async function setupProject({ project, ide, packageRoot, install = false,
174
202
  if (!install) return { ...response, status: 'missing_installation',
175
203
  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.' };
176
204
  if (!isDeepStrictEqual(await readProjectInstall(project, { required: true }), manifest)) throw new Error('Project installation metadata changed during setup; retry');
177
- const result = await installer({ ide, workspace: expected.workspace, platform: manifest.platform,
205
+ const result = await installer({ ide, serverId: serverId ?? 'craft', workspace: expected.workspace, platform: manifest.platform,
178
206
  registry: manifest.registry, channel: manifest.channel, packageRoot, home, codexHome, hostOptions,
179
207
  ...(runtimeRoot ? { runtimeRoot } : {}), ...(stateRoot ? { stateRoot } : {}), onlyIfMissing: true });
180
208
  const installed = result.hosts?.find(item => item.host === ide);
@@ -197,7 +225,7 @@ export function parseProjectSetupArgs(args) {
197
225
  if (key === '--install') {
198
226
  if (options.install !== undefined) throw new Error('Repeated --install option');
199
227
  options.install = true;
200
- } else if (['--project', '--ide', '--host-config', '--trae-region'].includes(key)) {
228
+ } else if (['--project', '--ide', '--instance', '--host-config', '--trae-region'].includes(key)) {
201
229
  const name = key.slice(2), value = args[++i];
202
230
  if (!value || value.startsWith('--') || Object.hasOwn(options, name)) throw new Error('Invalid or repeated ' + key);
203
231
  options[name] = value;
@@ -209,7 +237,7 @@ export function parseProjectSetupArgs(args) {
209
237
 
210
238
  export async function runProjectSetupCommand(args, packageRoot) {
211
239
  const options = parseProjectSetupArgs(args);
212
- const result = await setupProject({ ...options, packageRoot, installer: installWithLoginTask,
240
+ const result = await setupProject({ ...options, serverId: options.instance, packageRoot, installer: installWithLoginTask,
213
241
  codexHome: process.env.CODEX_HOME, hostOptions: hostCommandOptions(options) });
214
242
  process.stdout.write(JSON.stringify(result, null, 2) + '\n');
215
243
  return result;
@@ -103,6 +103,7 @@ export async function probeRuntime(connection, expected = {}) {
103
103
  if (expected.version && info.version !== expected.version) throw new Error('Runtime version mismatch');
104
104
  if (expected.build_id && info.runtime?.build_id !== expected.build_id) throw new Error('Runtime build identity mismatch');
105
105
  if (expected.host && info.host !== expected.host) throw new Error('Runtime host mismatch');
106
+ 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
107
  if (expected.workspace && path.resolve(info.workspace) !== path.resolve(expected.workspace)) throw new Error('Runtime workspace mismatch');
107
108
  if (expected.platform && info.platform !== expected.platform) throw new Error('Runtime platform mismatch');
108
109
  if (expected.host) {
@@ -110,6 +111,6 @@ export async function probeRuntime(connection, expected = {}) {
110
111
  if (!Array.isArray(engines) || !['js','js3d'].every(engine=>engines.includes(engine)) ||
111
112
  engines.some(engine=>info.installed_contexts?.[engine]?.host !== expected.host)) throw new Error('Runtime context host mismatch');
112
113
  }
113
- 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 };
114
+ 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 };
114
115
  } finally { await client.close(); await rm(state, { recursive: true, force: true }); }
115
116
  }
@@ -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,5 +1,6 @@
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';
@@ -15,18 +16,29 @@ import { setTimeout as delay } from 'node:timers/promises';
15
16
  import { unchangedInstallation, installationChanged, installationBusy } from './installation-transaction.mjs';
16
17
  import { prepareRuntimeCandidate, publishRuntimeCandidate, disposeRuntimeCandidate, refreshRuntimeCandidate } from './runtime-candidate.mjs';
17
18
  import { assertHostConfigScope } from './host-config-scope.mjs';
19
+ import { validateServerId } from './instance.mjs';
20
+ import { renderInstanceSkill } from './instance-skill.mjs';
18
21
 
19
22
  export { readInstallation } from './installation-state.mjs';
20
23
  const pending = new Map();
21
24
  const receiptLifetime = 5 * 60 * 1000;
22
25
 
23
26
  function result(state, current, status, extra = {}) {
24
- return { status, installation_id: state.id, source: state.source, policy: state.policy,
27
+ return { status, installation_id: state.id, server_id: state.server_id, channel: state.source.channel, source: state.source, policy: state.policy,
25
28
  current, target: state.target, activation: activationStatus(current, state.target),
26
29
  activation_mode: state.activation_mode ?? 'legacy_front', migration_required: state.schema === 1,
27
30
  activation_required: false, reconnect_required: !sameRuntimeIdentity(current, state.target), explicitly_not_started: true, ...extra };
28
31
  }
29
32
 
33
+ // A still-running MCP may have been launched from a different channel. Only
34
+ // compare package versions once it is operating on its own installed channel.
35
+ export function pendingChannelSwitch(state, current, connectedSource) {
36
+ if (connectedSource?.package === state.source.package && connectedSource.registry === state.source.registry &&
37
+ connectedSource.channel !== state.source.channel && compareVersions(state.target.version, current.version) !== 0) {
38
+ return result(state, current, 'pending_reconnect', { can_continue: false });
39
+ }
40
+ }
41
+
30
42
  export async function readUpdateStatus({ installationFile, current }) {
31
43
  if (!installationFile) return { status: 'unmanaged', current, activation_required: false, note: 'Run the standard Craft installer once to enable automatic updates.' };
32
44
  try {
@@ -60,8 +72,9 @@ async function candidateSkills(state, identity) {
60
72
  const changes = [];
61
73
  for (const { name, file, marker } of installedSkillEntries(state)) {
62
74
  await assertPlainPath(file);
63
- const desired = await optionalFile(path.join(identity.package_root, 'resources', name, 'SKILL.md'));
64
- if (desired === null) throw new Error('Updated runtime is missing the managed ' + name + ' Skill');
75
+ const template = await optionalFile(path.join(identity.package_root, 'resources', name, 'SKILL.md'));
76
+ if (template === null) throw new Error('Updated runtime is missing the managed ' + name + ' Skill');
77
+ const desired = renderInstanceSkill(template, name, state.server_id);
65
78
  if (!desired.includes(marker)) throw new Error('Updated runtime has an invalid managed Skill marker');
66
79
  const before = await optionalFile(file);
67
80
  if (before && !before.includes(marker)) throw new Error('User-owned Skill preserved: ' + file);
@@ -74,7 +87,7 @@ const shortLock = { stale: 120000, retries: 0 };
74
87
 
75
88
  async function confirmationSnapshot(installationFile, current) {
76
89
  const snapshot = await readInstallationSnapshot(installationFile), { state } = snapshot;
77
- await assertHostConfigScope(state.config,state.host,state.config_peers);
90
+ await assertHostConfigScope(state.config,state.host,state.config_peers,state.server_id);
78
91
  if (state.schema !== 2 || state.activation_mode !== activationMode) throw new Error('Legacy Craft installation requires the standard installer before reconnecting');
79
92
  if (activationStatus(current, state.target).status !== 'active_verified') throw installationChanged('The current connection does not match the configured update target');
80
93
  await verifyLauncher(state, installationFile);
@@ -116,29 +129,35 @@ async function saveCheckReceipt(installationFile, expected, receipt) {
116
129
  } finally { await unlock(); }
117
130
  }
118
131
 
119
- async function hostUpdate(state, installationFile, launcher, identity) {
120
- await assertHostConfigScope(state.config,state.host,state.config_peers);
121
- await assertPlainPath(state.config);
122
- if (state.host === 'dsh') assertDshSharedScope({ dshHome: path.dirname(state.config) });
123
- const before = await optionalFile(state.config);
124
- if (before === null) throw new Error('Craft host configuration is missing; run install again');
125
- const existing = craftConfig(before, state.host, state.server_id);
132
+ async function verifyRegisteredScope(existing, state, installationFile) {
126
133
  await verifyLauncher(state, installationFile, existing);
127
134
  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));
128
135
  const workspaceIndex = existing?.args?.indexOf('--workspace') ?? -1;
129
- if (!existing || !samePath(existing.env?.CRAFT_INSTALLATION_FILE, installationFile) || existing.env?.CRAFT_CLIENT_IDE !== state.host ||
136
+ 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 ||
130
137
  !samePath(workspaceIndex >= 0 ? existing.args[workspaceIndex + 1] : existing.env?.CLIENT_WORKSPACE_ROOT, state.workspace) ||
131
138
  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');
139
+ }
140
+
141
+ async function hostUpdate(state, installationFile, launcher, identity) {
142
+ await assertHostConfigScope(state.config,state.host,state.config_peers,state.server_id);
143
+ await assertPlainPath(state.config);
144
+ if (state.host === 'dsh') assertDshSharedScope({ dshHome: path.dirname(state.config) }, state.server_id);
145
+ const before = await optionalFile(state.config);
146
+ if (before === null) throw new Error('Craft host configuration is missing; run install again');
147
+ const existing = craftConfig(before, state.host, state.server_id);
148
+ await verifyRegisteredScope(existing, state, installationFile);
132
149
  // Fixed-entry updates must not rewrite watched host configuration: a host
133
150
  // could otherwise restart an in-flight MCP task on an env-only change.
134
151
  if (state.launcher?.entry === launcher.entry) return { file: state.config, before, after: before };
135
- 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 } };
136
- return { file: state.config, before, after: mergeConfig(before, state.host, connection, { previousName: state.server_id, enable: false }) };
152
+ 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 } };
153
+ return { file: state.config, before, after: mergeConfig(before, state.host, connection, { serverId: state.server_id, previousName: state.server_id, enable: false }) };
137
154
  }
138
155
 
139
- async function checkSnapshot({ installationFile, current, intent, requestKey, projectCompatibility, registryReceipt, lookup, materialize, probe }) {
156
+ async function checkSnapshot({ installationFile, current, connectedSource, intent, requestKey, projectCompatibility, registryReceipt, lookup, materialize, probe }) {
140
157
  let state = (await readInstallationSnapshot(installationFile)).state;
141
158
  if (current.package !== state.source.package) return result(state, current, 'error', { code: 'package_mismatch', can_continue: false });
159
+ const switched = pendingChannelSwitch(state, current, connectedSource);
160
+ if (switched) return switched;
142
161
  try { requireForwardVersion(state.target, current); }
143
162
  catch (error) { return result(state, current, 'error', { code: 'target_not_forward', message: error.message, can_continue: false }); }
144
163
  let pendingIncompatible;
@@ -212,16 +231,19 @@ async function checkSnapshot({ installationFile, current, intent, requestKey, pr
212
231
  try { await projectCompatibility(identity.package_root); }
213
232
  catch (error) { return result(state, current, 'incompatible', { checked_at: checkedAt, remote, message: error.message, can_continue: false }); }
214
233
  }
215
- 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 } },
216
- { version: identity.version, build_id: identity.build_id, host: state.host, workspace: state.workspace, platform: state.platform });
234
+ const verified = await probe({ command: process.execPath, args: [identity.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 } },
235
+ { version: identity.version, build_id: identity.build_id, serverId: state.server_id, host: state.host, workspace: state.workspace, platform: state.platform });
217
236
  if (verified.runtime?.activation_mode !== activationMode) throw new Error('Candidate runtime does not support activation at the next MCP start');
218
237
  if (!sameRuntimeIdentity(await getRuntimeIdentity(identity.package_root), identity)) throw new Error('Candidate runtime changed during startup verification');
219
238
  // Neither registry traffic nor materialization/probing owns a shared lock.
220
239
  // Re-read the authoritative state before publishing; receipt-only writes merge.
221
240
  const commitCandidate = async () => {
222
- const unlockState = await lockfile.lock(installationFile, shortLock);
241
+ const unlockScope = [];
223
242
  let unlockRuntime;
224
243
  try {
244
+ for (const file of [state.config, installationFile].map(file => path.resolve(file)).sort()) {
245
+ unlockScope.push(await lockfile.lock(file, { ...shortLock, realpath: false }));
246
+ }
225
247
  const latest = await unchangedInstallation(installationFile, state);
226
248
  state = latest.state;
227
249
  unlockRuntime = await lockfile.lock(runtimeRoot, shortLock);
@@ -235,7 +257,7 @@ async function checkSnapshot({ installationFile, current, intent, requestKey, pr
235
257
  await commitFiles([...skillChanges, launcherPlan.change, { file: installationFile, before: latest.text, after: JSON.stringify(after, null, 2) + '\n' }, configChange]);
236
258
  state = after;
237
259
  return result(state, current, 'pending_reconnect', { checked_at: checkedAt, remote, reconnect_required: true, can_continue: false, verified: { ...verified, scope: 'standalone_probe' } });
238
- } finally { try { await unlockRuntime?.(); } finally { await unlockState(); } }
260
+ } finally { try { await unlockRuntime?.(); } finally { for (const release of unlockScope.reverse()) await release(); } }
239
261
  };
240
262
  for (let attempt = 0; ; attempt++) {
241
263
  try { return await commitCandidate(); }
@@ -259,7 +281,10 @@ async function checkSnapshot({ installationFile, current, intent, requestKey, pr
259
281
  // Recheck the rollback, scope and complete old package before allowing work.
260
282
  if (state.schema !== 2 || activationPending || currentIncompatible) throw new Error(currentIncompatible ?? 'No compatible active installation to retain');
261
283
  await unchangedInstallation(installationFile, state);
262
- if (originalConfig === undefined || originalConfig === null || await optionalFile(state.config) !== originalConfig) throw new Error('Host configuration changed; rollback could not be verified');
284
+ const retainedConfig = await optionalFile(state.config);
285
+ if (originalConfig == null || retainedConfig === null || !isDeepStrictEqual(
286
+ craftConfig(retainedConfig, state.host, state.server_id), craftConfig(originalConfig, state.host, state.server_id)
287
+ )) throw new Error('Host registration changed; rollback could not be verified');
263
288
  if (!sameRuntimeIdentity(await getRuntimeIdentity(current.package_root), state.target)) throw new Error('Existing runtime integrity check failed');
264
289
  await hostUpdate(state, installationFile, state.launcher ?? { entry: current.entry }, current);
265
290
  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');
@@ -276,17 +301,17 @@ async function checkSnapshot({ installationFile, current, intent, requestKey, pr
276
301
  finally { if (candidate) await disposeRuntimeCandidate(candidate); }
277
302
  }
278
303
 
279
- export async function checkForUpdate({ installationFile, current, intent = 'inspect', requestKey, projectCompatibility, registryReceipt, lookup = queryRegistry, materialize = stageRegistryRuntime, probe = probeRuntime }) {
304
+ export async function checkForUpdate({ installationFile, current, connectedSource, intent = 'inspect', requestKey, projectCompatibility, registryReceipt, lookup = queryRegistry, materialize = stageRegistryRuntime, probe = probeRuntime }) {
280
305
  if (!installationFile) return { status: 'unmanaged', current, can_continue: true, activation_required: false, note: 'Install Craft once to enable automatic updates.' };
281
306
  if (!['inspect', 'auto', 'create', 'resume', 'update'].includes(intent)) throw new Error('Invalid update intent');
282
307
  // Deduplicate only the same logical request. Other readers and downloads
283
308
  // proceed independently; the short commit compares their installation snapshot.
284
- const key = requestKey ? JSON.stringify([installationFile, current.build_id, current.instance_id, intent, requestKey]) : Symbol('unkeyed update');
309
+ const key = requestKey ? JSON.stringify([installationFile, current.build_id, current.instance_id, connectedSource?.channel, intent, requestKey]) : Symbol('unkeyed update');
285
310
  if (pending.has(key)) return pending.get(key);
286
311
  const operation = (async () => {
287
312
  for (let attempt = 0; attempt < 3; attempt++) {
288
313
  try {
289
- return await checkSnapshot({ installationFile, current, intent, requestKey, projectCompatibility, registryReceipt, lookup, materialize, probe });
314
+ return await checkSnapshot({ installationFile, current, connectedSource, intent, requestKey, projectCompatibility, registryReceipt, lookup, materialize, probe });
290
315
  } catch (error) {
291
316
  if (error.code === 'INSTALLATION_CHANGED' && attempt < 2) continue;
292
317
  if (['ELOCKED', 'INSTALLATION_CHANGED'].includes(error.code)) return installationBusy(error, current);
@@ -302,19 +327,23 @@ export async function runUpdateCommand(args) {
302
327
  const [command, ...rest] = args, options = {};
303
328
  for (let i = 0; i < rest.length; i += 2) {
304
329
  const key = rest[i]?.replace(/^--/, '');
305
- 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]');
330
+ 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]');
306
331
  options[key] = rest[i + 1];
307
332
  }
308
333
  const results = [];
334
+ const serverId = validateServerId(options.instance ?? 'craft');
309
335
  const hostOptions = hostCommandOptions(options);
310
336
  for (const host of installTargets(options.ide)) {
311
- const paths = hostPaths(os.homedir(), host, process.env.CODEX_HOME, hostOptions);
337
+ const paths = hostPaths(os.homedir(), host, process.env.CODEX_HOME, { ...hostOptions, serverId });
312
338
  await assertPlainPath(paths.config);
313
- assertDshSharedScope(paths);
314
- const connection = craftConfig(await optionalFile(paths.config) ?? '', host);
339
+ assertDshSharedScope(paths,serverId);
340
+ await assertHostConfigScope(paths.config,host,paths.configPeers,serverId);
341
+ const connection = craftConfig(await optionalFile(paths.config) ?? '', host, serverId);
315
342
  const installationFile = connection?.env?.CRAFT_INSTALLATION_FILE;
316
343
  if (!installationFile) throw new Error(host + ': Install Craft once before using automatic updates');
317
344
  const state = await readInstallation(installationFile);
345
+ 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);
346
+ await verifyRegisteredScope(connection, state, installationFile);
318
347
  const current = await getRuntimeIdentity(state.target.package_root);
319
348
  const update = await checkForUpdate({ installationFile, current, intent: command === 'update' ? 'update' : 'inspect', requestKey: 'cli-' + Date.now() });
320
349
  if (update.status === 'installation_busy') {
@@ -324,7 +353,7 @@ export async function runUpdateCommand(args) {
324
353
  }
325
354
  // A CLI can inspect configured files, but cannot prove a host connection.
326
355
  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.',
327
- ...(!['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'})} : {}) });
356
+ ...(!['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'})} : {}) });
328
357
  if (['error', 'update_failed', 'incompatible'].includes(update.status)) process.exitCode = 1;
329
358
  }
330
359
  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
  }
@@ -1787,6 +1802,7 @@ function launcherPath(installationFile) {
1787
1802
  return installationFile.replace(/\.json$/, "") + ".launcher.mjs";
1788
1803
  }
1789
1804
  async function verifyLauncher(state, installationFile, connection) {
1805
+ if (connection?.env && (connection.env.CRAFT_SERVER_ID ?? "craft") !== state.server_id) throw new Error("Craft launcher instance differs from its registration");
1790
1806
  if (!state.launcher) return { mode: "legacy_versioned_entry" };
1791
1807
  const expected = launcherPath(installationFile);
1792
1808
  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,7 +1834,7 @@ async function start() {
1818
1834
  if (state.host === "workbuddy" && state.login_data_dir && process.env.CRAFT_STANDALONE_PROBE !== "1") {
1819
1835
  process.env.CLIENT_DATA_DIR ||= state.login_data_dir;
1820
1836
  }
1821
- for (const [key, expected] of Object.entries({ CRAFT_CLIENT_IDE: state.host, CLIENT_WORKSPACE_ROOT: state.workspace, CRAFT_WEB_URL: state.platform })) {
1837
+ 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
1838
  if (process.env[key] && process.env[key] !== expected) throw new Error("Craft launcher scope mismatch: " + key);
1823
1839
  process.env[key] = expected;
1824
1840
  }