@craft_eco/craft-mcp 0.1.6 → 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 (32) hide show
  1. package/README.md +8 -8
  2. package/bin/craft-mcp.mjs +28 -2
  3. package/dist-server/game-workflow/project-context.mjs +7 -6
  4. package/dist-server/game-workflow/project-install.mjs +2 -1
  5. package/dist-server/integrations/config.mjs +41 -18
  6. package/dist-server/integrations/connect.mjs +18 -9
  7. package/dist-server/integrations/connection-handoff.mjs +9 -8
  8. package/dist-server/integrations/dsh-config.mjs +30 -14
  9. package/dist-server/integrations/files.mjs +3 -1
  10. package/dist-server/integrations/fixed-launcher.mjs +1 -0
  11. package/dist-server/integrations/host-config-scope.mjs +4 -3
  12. package/dist-server/integrations/hosts.mjs +3 -1
  13. package/dist-server/integrations/install-source.mjs +44 -0
  14. package/dist-server/integrations/install.mjs +183 -53
  15. package/dist-server/integrations/installation-state.mjs +2 -1
  16. package/dist-server/integrations/instance-skill.mjs +26 -0
  17. package/dist-server/integrations/instance.mjs +29 -0
  18. package/dist-server/integrations/launcher-start.mjs +1 -1
  19. package/dist-server/integrations/login-task-command.mjs +3 -3
  20. package/dist-server/integrations/opencode-config.mjs +13 -6
  21. package/dist-server/integrations/project-setup.mjs +46 -18
  22. package/dist-server/integrations/runtime.mjs +2 -1
  23. package/dist-server/integrations/uninstall.mjs +160 -0
  24. package/dist-server/integrations/updates.mjs +57 -28
  25. package/dist-server/launcher.mjs +18 -2
  26. package/dist-server/mcp/server.mjs +16 -8
  27. package/dist-server/mcp/update-session.mjs +34 -12
  28. package/dist-server/upstream/craft-aigc.mjs +11 -2
  29. package/dist-server/upstream/draft-audit.mjs +52 -6
  30. package/package.json +4 -3
  31. package/resources/craft-create/SKILL.md +2 -0
  32. package/resources/craft-update/SKILL.md +2 -0
@@ -0,0 +1,44 @@
1
+ import path from 'node:path';
2
+ import { optionalFile } from './files.mjs';
3
+ import { registryOrigin, updateSource } from './installation-state.mjs';
4
+ import { compareVersions, requireForwardVersion } from './version-policy.mjs';
5
+
6
+ // npm exec can record the original package spec on its own cache entry. Never
7
+ // infer a channel from a resolved version, a cwd manifest or the npm default tag.
8
+ export async function npmInstallSelector(packageRoot, name, env = process.env) {
9
+ if (env.npm_command !== 'exec' || env.npm_lifecycle_event !== 'npx') return null;
10
+ const cache = path.resolve(packageRoot, ...name.split('/').map(() => '..'), '..');
11
+ if (path.basename(path.dirname(cache)) !== '_npx' ||
12
+ path.relative(cache, packageRoot) !== path.join('node_modules', ...name.split('/'))) return null;
13
+ const metadata = await optionalFile(path.join(cache, 'package.json'));
14
+ let specs;
15
+ try { specs = metadata && JSON.parse(metadata)._npx?.packages; }
16
+ catch (error) { if (error instanceof SyntaxError) return null; throw error; }
17
+ if (!Array.isArray(specs) || specs.length !== 1 || typeof specs[0] !== 'string') return null;
18
+ if (specs[0] === name) return { kind: 'bare' };
19
+ if (!specs[0].startsWith(name + '@')) return { kind: 'package' };
20
+ const tag = specs[0].slice(name.length + 1);
21
+ const isTag = /^[a-zA-Z][a-zA-Z0-9._-]*$/.test(tag) && !/^(?:v\d+(?:\.|$)|x(?:\.|$))/i.test(tag);
22
+ return isTag ? { kind: 'tag', tag } : { kind: 'package' };
23
+ }
24
+
25
+ export function installSource(pkg, { registry, channel, selector }, state, legacy) {
26
+ const previous = state?.source ?? legacy;
27
+ const source = updateSource(pkg, { registry: registry ?? previous?.registry, channel: channel ?? previous?.channel }, state?.source);
28
+ const switching = Boolean(channel && previous?.channel && channel !== previous.channel);
29
+ // A pinned version or local archive remains the payload on a normal install.
30
+ // A bare/management reinstall instead resolves the user's existing channel.
31
+ const followTag = Boolean(channel && previous?.channel) || selector === 'tag' ||
32
+ (['bare', 'management'].includes(selector) && Boolean(channel || previous?.channel));
33
+ return { source, followTag, allowLower: switching && registryOrigin(previous.registry) === source.registry };
34
+ }
35
+
36
+ export function checkInstallVersion(identity, plan, integrity) {
37
+ const previous = plan.previousRuntime;
38
+ if (previous && previous.version === identity.version && previous.origin?.kind === 'npm' &&
39
+ previous.origin.registry === plan.source.registry && integrity && previous.origin.integrity !== integrity) {
40
+ throw new Error('Craft same-version registry integrity changed; installation refused');
41
+ }
42
+ if (plan.allowLower && previous && compareVersions(identity.version, previous.version) < 0) return;
43
+ requireForwardVersion(identity, previous);
44
+ }
@@ -1,22 +1,65 @@
1
1
  import path from 'node:path';
2
2
  import os from 'node:os';
3
- import { readFile, mkdir } from 'node:fs/promises';
3
+ import { readFile, mkdir, realpath } from 'node:fs/promises';
4
4
  import lockfile from 'proper-lockfile';
5
5
  import { defaultProfileDataDir, getAppDataRoot } from '../core/app-paths.mjs';
6
6
  import { hostPaths, hostCommandOptions, installTargets } from './hosts.mjs';
7
7
  import { craftConfig, craftRegistrations, mergeConfig, importZcodeFallback } from './config.mjs';
8
8
  import { assertDshSharedScope } from './dsh-config.mjs';
9
9
  import { optionalFile, assertPlainPath, commitFiles } from './files.mjs';
10
- import { stageRuntime, probeRuntime, getRuntimeIdentity } from './runtime.mjs';
11
- import { installationPath, readInstallation, readInstallationSnapshot, registryOrigin, updateSource, installedSkillEntries, skillRuntimeIdentity, sameRuntimeIdentity, activationMode } from './installation-state.mjs';
12
- import { requireForwardVersion } from './version-policy.mjs';
10
+ import { stageRuntime, stageRegistryRuntime, probeRuntime, getRuntimeIdentity } from './runtime.mjs';
11
+ import { installationPath, readInstallation, readInstallationSnapshot, registryOrigin, installedSkillEntries, skillRuntimeIdentity, sameRuntimeIdentity, activationMode } from './installation-state.mjs';
12
+ import { queryRegistry } from './updates.mjs';
13
+ import { npmInstallSelector, installSource, checkInstallVersion } from './install-source.mjs';
13
14
  import { connectionHandoff } from './connection-handoff.mjs';
14
15
  import { planLauncher, verifyLauncher } from './fixed-launcher.mjs';
15
16
  import { prepareRuntimeCandidate, refreshRuntimeCandidate, publishRuntimeCandidate, disposeRuntimeCandidate } from './runtime-candidate.mjs';
16
17
  import { sameInstallation, installationChanged } from './installation-transaction.mjs';
17
18
  import { assertHostConfigScope } from './host-config-scope.mjs';
19
+ import { registrationsForInstance, serverIdForChannel, validateServerId } from './instance.mjs';
20
+ import { renderInstanceSkill } from './instance-skill.mjs';
18
21
 
19
22
  const bootstrapMarker = '<!-- craft-mcp:bootstrap:v1 -->';
23
+
24
+ async function canonicalWorkspace(directory) {
25
+ try { return await realpath(directory); }
26
+ catch (error) {
27
+ const parent = path.dirname(directory);
28
+ if (error.code !== 'ENOENT' || parent === directory) throw error;
29
+ return path.join(await canonicalWorkspace(parent), path.basename(directory));
30
+ }
31
+ }
32
+
33
+ async function checkSiblingWorkspaces(registrations, previousName, host, workspace) {
34
+ const siblings = registrations.filter(({ name, connection }) => name !== previousName &&
35
+ connection?.env?.CRAFT_INSTALLATION_FILE && connection.env.CRAFT_CLIENT_IDE === host);
36
+ if (!siblings.length) return;
37
+ const selected = await canonicalWorkspace(workspace);
38
+ for (const { name, connection } of siblings) {
39
+ const args = connection.args ?? [], index = args.indexOf('--workspace');
40
+ const roots = [connection.env.CLIENT_WORKSPACE_ROOT, index >= 0 ? args[index + 1] : undefined];
41
+ for (const root of new Set(roots.filter(value => typeof value === 'string' && path.isAbsolute(value)))) {
42
+ if (path.relative(selected, await canonicalWorkspace(root)) === '') {
43
+ throw new Error('Craft workspace already belongs to another instance in ' + host + ': ' + name + '. Select a separate game directory.');
44
+ }
45
+ }
46
+ }
47
+ }
48
+
49
+ function checkInstanceBinding(state, host, paths, serverId, installationFile) {
50
+ if (state.host !== host || path.relative(state.config, paths.config) !== '' || state.server_id !== serverId) {
51
+ throw new Error('Craft installation state belongs to another host configuration or instance');
52
+ }
53
+ const expected = installationPath(path.dirname(installationFile), host, paths.config, serverId);
54
+ if (serverId !== 'craft' && (state.id !== expected.id || path.relative(installationFile, expected.file) !== '')) {
55
+ throw new Error('Craft instance installation path differs from its registration');
56
+ }
57
+ if (serverId !== 'craft' && state.skills && (path.relative(state.skills['craft-create'], paths.skill) !== '' ||
58
+ (state.skills['craft-update'] && path.relative(state.skills['craft-update'], paths.updateSkill) !== ''))) {
59
+ throw new Error('Craft installation Skill paths differ from the selected host configuration');
60
+ }
61
+ }
62
+
20
63
  function legacyNpmSource(connection, packageName) {
21
64
  const args = connection?.args ?? [];
22
65
  const spec = args.find(value => typeof value === 'string' && (value === packageName || value.startsWith(packageName + '@')));
@@ -56,27 +99,25 @@ function hostRuntimeEnvironment(host, existing = {}) {
56
99
 
57
100
  export async function installHosts({ ide, workspace, platform, packageRoot, home = os.homedir(), codexHome, hostOptions = {},
58
101
  runtimeRoot = path.join(getAppDataRoot(), 'runtimes'), stateRoot = path.join(path.dirname(runtimeRoot), 'installations'),
59
- registry, channel, updates, onlyIfMissing = false, materialize = stageRuntime, probe = probeRuntime }) {
102
+ registry, channel, updates, serverId, selector = 'package', onlyIfMissing = false, materialize = stageRuntime, probe = probeRuntime,
103
+ lookup = queryRegistry, materializeRegistry = stageRegistryRuntime }) {
60
104
  const targets = installTargets(ide);
105
+ const instance = validateServerId(serverId ?? 'craft');
61
106
  if (hostOptions.configPath && targets.length !== 1) throw new Error('--host-config requires exactly one --ide');
62
107
  if (workspace !== undefined && !path.isAbsolute(workspace)) throw new Error('--workspace must be absolute');
63
108
  if (platform !== undefined) platform = platformOrigin(platform);
64
109
  if (registry != null) registry = registryOrigin(registry);
65
110
  if (updates !== undefined && !['auto', 'off'].includes(updates)) throw new Error('--updates must be auto or off');
66
111
  const pkg = JSON.parse(await readFile(path.join(packageRoot, 'package.json'), 'utf8'));
67
- const desiredSkill = await readFile(path.join(packageRoot, 'resources/craft-create/SKILL.md'), 'utf8');
68
- const desiredUpdateSkill = await optionalFile(path.join(packageRoot, 'resources/craft-update/SKILL.md'));
69
- if (!desiredSkill.includes(bootstrapMarker)) throw new Error('Craft bootstrap Skill missing from distribution');
70
- if (desiredUpdateSkill !== null && !desiredUpdateSkill.includes('<!-- craft-mcp:update:v1 -->')) throw new Error('Craft update Skill has an invalid distribution marker');
71
112
  await mkdir(runtimeRoot, { recursive: true });
72
- const targetPaths = new Map(targets.map(host => [host, hostPaths(home, host, codexHome, hostOptions)]));
113
+ const targetPaths = new Map(targets.map(host => [host, hostPaths(home, host, codexHome, { ...hostOptions, serverId: instance })]));
73
114
  async function readPlans() {
74
115
  const plans = [];
75
116
  for (const host of targets) {
76
117
  const paths = targetPaths.get(host);
77
118
  await assertPlainPath(paths.config); await assertPlainPath(paths.skill); await assertPlainPath(paths.updateSkill);
78
- assertDshSharedScope(paths);
79
- await assertHostConfigScope(paths.config,host,paths.configPeers);
119
+ assertDshSharedScope(paths, instance);
120
+ await assertHostConfigScope(paths.config,host,paths.configPeers,instance);
80
121
  const original = await optionalFile(paths.config), existingSkill = await optionalFile(paths.skill);
81
122
  let configInput = original ?? '', fallbackSnapshot;
82
123
  if (paths.fallbackConfig) {
@@ -87,16 +128,24 @@ export async function installHosts({ ide, workspace, platform, packageRoot, home
87
128
  }
88
129
  const existingUpdateSkill = await optionalFile(paths.updateSkill);
89
130
  if (existingSkill && !existingSkill.includes(bootstrapMarker)) throw new Error('User-owned craft-create Skill preserved; rename it before installing: ' + paths.skill);
90
- if (desiredUpdateSkill && existingUpdateSkill && !existingUpdateSkill.includes('<!-- craft-mcp:update:v1 -->')) throw new Error('User-owned craft-update Skill preserved; rename it before installing: ' + paths.updateSkill);
91
- const registrations = craftRegistrations(configInput, host);
131
+ const hostRegistrations = craftRegistrations(configInput, host);
132
+ const registrations = registrationsForInstance(hostRegistrations, instance);
133
+ if (instance !== 'craft' && craftConfig(configInput, host, instance) !== undefined && !registrations.some(entry => entry.name === instance)) {
134
+ throw new Error('The requested Craft instance name is already used by another registration: ' + instance);
135
+ }
92
136
  if (onlyIfMissing && registrations.length) throw new Error(host + ': Craft was configured while project setup was running; preserve the registration and inspect it again');
93
137
  if (registrations.length > 1) throw new Error(host + ': Multiple Craft registrations found; preserve separate environments and select one installation before updating');
94
- const previousName = registrations[0]?.name ?? 'craft', old = registrations[0]?.connection;
138
+ const previousName = registrations[0]?.name ?? instance, old = registrations[0]?.connection;
95
139
  const legacySource = legacyNpmSource(old, pkg.name);
96
- const statePath = installationPath(stateRoot, host, paths.config);
140
+ const statePath = installationPath(stateRoot, host, paths.config, instance);
97
141
  const previousSnapshot = old?.env?.CRAFT_INSTALLATION_FILE ? await readInstallationSnapshot(old.env.CRAFT_INSTALLATION_FILE) : null;
98
142
  const previousState = previousSnapshot?.state;
99
- if (previousState && (previousState.host !== host || path.resolve(previousState.config) !== path.resolve(paths.config))) throw new Error('Craft installation state belongs to another host configuration');
143
+ if (previousState) checkInstanceBinding(previousState, host, paths, instance, old.env.CRAFT_INSTALLATION_FILE);
144
+ if (instance !== 'craft' && previousState && path.relative(old.env.CRAFT_INSTALLATION_FILE, statePath.file) !== '') throw new Error('Craft instance installation root differs from its registration');
145
+ const previousChannel = previousState?.source.channel ?? legacySource?.channel;
146
+ if (serverId !== undefined && previousChannel && channel && previousChannel !== channel) {
147
+ throw new Error('Craft instance ' + instance + ' already tracks ' + previousChannel + '; preserve that installation and use a different instance for ' + channel);
148
+ }
100
149
  const stateBefore = previousSnapshot && path.resolve(old.env.CRAFT_INSTALLATION_FILE) === path.resolve(statePath.file) ? previousSnapshot.text : await optionalFile(statePath.file);
101
150
  let previousRuntime = previousState?.target;
102
151
  if (!previousRuntime && old?.args?.[0] && path.isAbsolute(old.args[0])) {
@@ -109,10 +158,19 @@ export async function installHosts({ ide, workspace, platform, packageRoot, home
109
158
  if (pinned) previousRuntime = { version: pinned.slice('@craft_eco/craft-mcp@'.length) };
110
159
  }
111
160
  const workspaceIndex = old?.args?.indexOf('--workspace') ?? -1;
112
- const games = workspace ?? (workspaceIndex >= 0 ? old.args[workspaceIndex + 1] : old?.env?.CLIENT_WORKSPACE_ROOT) ?? path.join(home, 'CraftGames');
161
+ const defaultGames = instance === 'craft' ? path.join(home, 'CraftGames') : path.join(home, 'CraftTestGames', instance);
162
+ const games = workspace ?? (workspaceIndex >= 0 ? old.args[workspaceIndex + 1] : old?.env?.CLIENT_WORKSPACE_ROOT) ?? defaultGames;
113
163
  if (!path.isAbsolute(games)) throw new Error('Configured Craft workspace must be absolute');
164
+ await checkSiblingWorkspaces(hostRegistrations, previousName, host, path.resolve(games));
114
165
  const origin = platformOrigin(platform ?? old?.env?.CRAFT_WEB_URL ?? pkg.craft?.platform);
115
- plans.push({ host, paths, original, configInput, fallbackSnapshot, existingSkill, existingUpdateSkill, previousName, previousRuntime, previousState, legacySource, statePath, stateBefore, workspace: path.resolve(games), platform: origin });
166
+ // A bare npx bootstrap can come from npm's latest tag. For a new primary
167
+ // installation the product follows stable; a legacy installation keeps its channel.
168
+ const selectedChannel = channel ?? (serverId === 'craft' && selector === 'bare' && !previousChannel ? 'stable' : undefined);
169
+ const selection = installSource(pkg, { registry, channel: selectedChannel, selector }, previousState, legacySource);
170
+ plans.push({ host, paths, original, configInput, fallbackSnapshot, existingSkill, existingUpdateSkill, previousName, previousRuntime, previousState, legacySource, statePath, stateBefore, workspace: path.resolve(games), platform: origin, ...selection });
171
+ }
172
+ if (channel && plans.some(plan => plan.followTag)) {
173
+ for (const plan of plans) plan.followTag = true;
116
174
  }
117
175
  return plans;
118
176
  }
@@ -124,8 +182,9 @@ export async function installHosts({ ide, workspace, platform, packageRoot, home
124
182
  await assertPlainPath(file);
125
183
  if (await optionalFile(file) !== expected) throw installationChanged('Craft host files changed while the candidate was prepared');
126
184
  }
127
- assertDshSharedScope(plan.paths);
128
- await assertHostConfigScope(plan.paths.config,plan.host,plan.paths.configPeers);
185
+ assertDshSharedScope(plan.paths, instance);
186
+ await assertHostConfigScope(plan.paths.config,plan.host,plan.paths.configPeers,instance);
187
+ await checkSiblingWorkspaces(craftRegistrations(plan.configInput, plan.host), plan.previousName, plan.host, plan.workspace);
129
188
  if (plan.fallbackSnapshot && await optionalFile(plan.fallbackSnapshot.file) !== plan.fallbackSnapshot.text) throw new Error('ZCode fallback MCP configuration changed during installation; retry without changing the fallback');
130
189
  const text = await optionalFile(plan.statePath.file);
131
190
  if (text !== plan.stateBefore) {
@@ -144,30 +203,72 @@ export async function installHosts({ ide, workspace, platform, packageRoot, home
144
203
  }
145
204
  }
146
205
  const initialPlans = await readPlans();
147
- const candidate = await prepareRuntimeCandidate(runtimeRoot, staging => materialize(packageRoot, staging, { registry }));
206
+ const candidates = new Map(), releases = new Map();
207
+ async function preparePlan(plan) {
208
+ let remote;
209
+ if (plan.followTag) {
210
+ const key = JSON.stringify(plan.source);
211
+ if (!releases.has(key)) releases.set(key, await lookup(plan.source));
212
+ remote = releases.get(key);
213
+ if (remote.package !== pkg.name || !remote.integrity) throw new Error('Invalid Craft channel package or integrity');
214
+ checkInstallVersion({ version: remote.version }, plan, remote.integrity);
215
+ }
216
+ const key = remote ? JSON.stringify([remote.version, remote.integrity]) : 'package';
217
+ if (!candidates.has(key)) {
218
+ const candidate = await prepareRuntimeCandidate(runtimeRoot, staging => remote
219
+ ? materializeRegistry(plan.source, remote, staging)
220
+ : materialize(packageRoot, staging, { registry }));
221
+ candidates.set(key, candidate);
222
+ const resources = path.join(candidate.identity.package_root, 'resources');
223
+ candidate.createSkill = await readFile(path.join(resources,'craft-create/SKILL.md'),'utf8');
224
+ candidate.updateSkill = await optionalFile(path.join(resources,'craft-update/SKILL.md'));
225
+ if (!candidate.createSkill.includes(bootstrapMarker)) throw new Error('Craft bootstrap Skill missing from distribution');
226
+ if (candidate.updateSkill !== null && !candidate.updateSkill.includes('<!-- craft-mcp:update:v1 -->')) throw new Error('Craft update Skill has an invalid distribution marker');
227
+ }
228
+ const candidate = candidates.get(key);
229
+ if (candidate.identity.package !== pkg.name || (remote && candidate.identity.version !== remote.version)) throw new Error('Craft channel package does not match the resolved release');
230
+ const managedUpdateSkill = plan.previousState?.skills?.['craft-update'] === plan.paths.updateSkill;
231
+ plan.writeUpdateSkill = candidate.updateSkill !== null || managedUpdateSkill;
232
+ if (plan.writeUpdateSkill && plan.existingUpdateSkill !== null && !plan.existingUpdateSkill.includes('<!-- craft-mcp:update:v1 -->')) throw new Error('User-owned craft-update Skill preserved; rename it before installing: ' + plan.paths.updateSkill);
233
+ plan.candidate = candidate;
234
+ plan.integrity = remote?.integrity;
235
+ }
148
236
  const verifiedCache = new Map();
149
237
  try {
150
238
  for (let attempt = 0; attempt < 4; attempt++) {
151
239
  let plans, stateLocks = [], release;
240
+ const movedCandidates = new Set();
152
241
  try {
153
242
  plans = attempt === 0 ? initialPlans : await readPlans();
154
243
  const verifiedByHost = new Map();
155
244
  for (const plan of plans) {
156
- requireForwardVersion(candidate.identity, plan.previousRuntime);
245
+ if (attempt > 0) {
246
+ const original = initialPlans.find(initial => initial.host === plan.host);
247
+ const before = original.previousState?.source ?? original.legacySource ?? original.source;
248
+ const after = plan.previousState?.source ?? plan.legacySource;
249
+ if (after?.channel && (after.channel !== before.channel || (before.registry && before.registry !== after.registry))) {
250
+ throw new Error('Craft installation channel or registry changed during install; retry using its current binding');
251
+ }
252
+ }
253
+ await preparePlan(plan);
254
+ const candidate = plan.candidate;
255
+ checkInstallVersion(candidate.identity, plan, plan.integrity);
157
256
  const old = craftConfig(plan.configInput, plan.host, plan.previousName);
158
257
  const connection = { ...old, command: process.execPath, args: [candidate.identity.entry, '--workspace', plan.workspace],
159
- env: { ...old?.env, ...hostRuntimeEnvironment(plan.host,old?.env), CRAFT_CLIENT_IDE: plan.host, CRAFT_WEB_URL: plan.platform, CLIENT_WORKSPACE_ROOT: plan.workspace,
258
+ env: { ...old?.env, ...hostRuntimeEnvironment(plan.host,old?.env), CRAFT_CLIENT_IDE: plan.host, CRAFT_SERVER_ID: instance, CRAFT_WEB_URL: plan.platform, CLIENT_WORKSPACE_ROOT: plan.workspace,
160
259
  CRAFT_INSTALLATION_FILE: plan.statePath.file, CRAFT_RUNTIME_REVISION: candidate.identity.build_id }, ...hostConnectionOptions(plan.host) };
161
- const expected = { version: candidate.identity.version, build_id: candidate.identity.build_id, host: plan.host, workspace: plan.workspace, platform: plan.platform };
260
+ const expected = { version: candidate.identity.version, build_id: candidate.identity.build_id, host: plan.host, serverId: instance, workspace: plan.workspace, platform: plan.platform };
162
261
  const key = JSON.stringify({ connection, expected });
163
262
  const verified = verifiedCache.get(key) ?? await probe(connection, expected);
164
263
  if (verified.runtime?.activation_mode !== activationMode) throw new Error('Craft runtime requires a legacy frontend; install a next_mcp_start distribution');
165
264
  verifiedCache.set(key, verified);
166
265
  verifiedByHost.set(plan.host, verified);
167
266
  }
168
- if (!sameRuntimeIdentity(await getRuntimeIdentity(candidate.identity.package_root), candidate.identity)) throw new Error('Craft candidate changed during verification; installation refused');
169
- await refreshRuntimeCandidate(candidate);
170
- const lockPaths = [...new Set(plans.flatMap(plan => [plan.statePath.file, craftConfig(plan.configInput, plan.host, plan.previousName)?.env?.CRAFT_INSTALLATION_FILE].filter(Boolean)).map(file => path.resolve(file)))].sort();
267
+ for (const candidate of new Set(plans.map(plan => plan.candidate))) {
268
+ if (!sameRuntimeIdentity(await getRuntimeIdentity(candidate.identity.package_root), candidate.identity)) throw new Error('Craft candidate changed during verification; installation refused');
269
+ await refreshRuntimeCandidate(candidate);
270
+ }
271
+ const lockPaths = [...new Set(plans.flatMap(plan => [plan.paths.config, plan.statePath.file, craftConfig(plan.configInput, plan.host, plan.previousName)?.env?.CRAFT_INSTALLATION_FILE].filter(Boolean)).map(file => path.resolve(file)))].sort();
171
272
  for (const file of lockPaths) {
172
273
  await assertPlainPath(file); await mkdir(path.dirname(file), { recursive: true });
173
274
  stateLocks.push(await lockfile.lock(file, { realpath: false, stale: 120000, retries: 0 }));
@@ -175,26 +276,36 @@ export async function installHosts({ ide, workspace, platform, packageRoot, home
175
276
  // Never hold installation-state locks while waiting on launcher or GC.
176
277
  release = await lockfile.lock(runtimeRoot, { stale: 120000, retries: 0 });
177
278
  await verifyPlans(plans);
178
- const runtime = await publishRuntimeCandidate(candidate);
179
- const identity = { package: runtime.package, version: runtime.version, build_id: runtime.build_id, package_root: runtime.package_root, entry: runtime.entry };
180
- const changes = [], results = [];
279
+ const published = new Map(), changes = [], results = [];
181
280
  for (const plan of plans) {
182
- requireForwardVersion(identity, plan.previousRuntime);
183
- const source = updateSource(pkg, { registry: registry ?? (!plan.previousState ? plan.legacySource?.registry : undefined), channel: channel ?? (!plan.previousState ? plan.legacySource?.channel : undefined) }, plan.previousState?.source);
281
+ const { candidate, source } = plan;
282
+ const destination = candidate.destination ?? candidate.identity.package_root;
283
+ if (!published.has(destination)) {
284
+ published.set(destination, await publishRuntimeCandidate(candidate));
285
+ if (candidate.managed && !candidate.existing) movedCandidates.add(candidate);
286
+ }
287
+ const runtime = published.get(destination);
288
+ const identity = skillRuntimeIdentity(runtime);
289
+ checkInstallVersion(identity, plan, plan.integrity);
290
+ const origin = plan.integrity ? { kind:'npm', registry:source.registry, integrity:plan.integrity }
291
+ : identity.build_id === plan.previousRuntime?.build_id && plan.previousRuntime.origin?.registry === source.registry ? plan.previousRuntime.origin : undefined;
292
+ const target = origin ? { ...identity, origin } : identity;
293
+ const desiredSkill = renderInstanceSkill(candidate.createSkill, 'craft-create', instance);
294
+ const desiredUpdateSkill = candidate.updateSkill === null ? null : renderInstanceSkill(candidate.updateSkill, 'craft-update', instance);
184
295
  const migration = plan.previousState?.migration ?? (plan.legacySource ? { from_server: plan.previousName, ...plan.legacySource } : undefined);
185
296
  const launcherPlan = await planLauncher(plan.statePath.file, plan.previousState?.launcher, identity.package_root);
186
297
  const loginDir = plan.host === 'workbuddy' && process.platform === 'win32'
187
298
  ? craftConfig(plan.configInput, plan.host, plan.previousName)?.env?.CLIENT_DATA_DIR || process.env.CLIENT_DATA_DIR || defaultProfileDataDir(plan.workspace, plan.platform)
188
299
  : undefined;
189
300
  if (loginDir && !path.isAbsolute(loginDir)) throw new Error('WorkBuddy CLIENT_DATA_DIR must be absolute');
190
- const state = { schema: 2, activation_mode: activationMode, id: plan.statePath.id, host: plan.host, server_id: 'craft', config: plan.paths.config,
301
+ const state = { schema: 2, activation_mode: activationMode, id: plan.statePath.id, host: plan.host, server_id: instance, config: plan.paths.config,
191
302
  launcher: launcherPlan.launcher,
192
303
  ...(loginDir ? {login_data_dir: path.resolve(loginDir)} : {}),
193
304
  workspace: plan.workspace, platform: plan.platform, runtime_root: runtimeRoot, source,
194
305
  ...(plan.paths.configPeers?{config_peers:plan.paths.configPeers}:{}),
195
306
  ...(migration ? { migration } : {}),
196
307
  skills: { 'craft-create': plan.paths.skill, ...(desiredUpdateSkill ? { 'craft-update': plan.paths.updateSkill } : {}) },
197
- policy: { mode: updates ?? plan.previousState?.policy.mode ?? 'auto', offline: 'allow-existing' }, anchor: identity, target: identity, skills_runtime: skillRuntimeIdentity(identity) };
308
+ policy: { mode: updates ?? plan.previousState?.policy.mode ?? 'auto', offline: 'allow-existing' }, anchor: identity, target, skills_runtime: skillRuntimeIdentity(identity) };
198
309
  if (plan.previousState?.connection_verification && sameRuntimeIdentity(identity, plan.previousState.target) && plan.workspace === plan.previousState.workspace && plan.platform === plan.previousState.platform) state.connection_verification = plan.previousState.connection_verification;
199
310
  // Reinstalling the same build must not reset check receipts or touch files.
200
311
  const priorComparable = plan.previousState && { ...plan.previousState };
@@ -202,35 +313,41 @@ export async function installHosts({ ide, workspace, platform, packageRoot, home
202
313
  const same = priorComparable && JSON.stringify(priorComparable) === JSON.stringify(state);
203
314
  const desiredState = same ? plan.previousState : { ...state, updated_at: new Date().toISOString() };
204
315
  const connection = { command: process.execPath, args: [launcherPlan.launcher.entry, '--workspace', plan.workspace],
205
- env: { ...hostRuntimeEnvironment(plan.host,craftConfig(plan.configInput,plan.host,plan.previousName)?.env), CRAFT_CLIENT_IDE: plan.host, CRAFT_WEB_URL: plan.platform, CLIENT_WORKSPACE_ROOT: plan.workspace, CRAFT_INSTALLATION_FILE: plan.statePath.file, CRAFT_RUNTIME_REVISION: identity.build_id },
316
+ env: { ...hostRuntimeEnvironment(plan.host,craftConfig(plan.configInput,plan.host,plan.previousName)?.env), CRAFT_CLIENT_IDE: plan.host, CRAFT_SERVER_ID: instance, CRAFT_WEB_URL: plan.platform, CLIENT_WORKSPACE_ROOT: plan.workspace, CRAFT_INSTALLATION_FILE: plan.statePath.file, CRAFT_RUNTIME_REVISION: identity.build_id },
206
317
  ...hostConnectionOptions(plan.host) };
207
318
  const configured = craftConfig(plan.configInput, plan.host, plan.previousName);
208
319
  // Some hosts omit an enabled flag when saving their configuration. Do not
209
320
  // reinsert defaults into an already enabled registration.
210
321
  const alreadyEnabled = configured && configured.disabled !== true && configured.enabled !== false && configured.enable !== false;
211
- const updated = mergeConfig(plan.configInput, plan.host, connection, { previousName: plan.previousName, enable: !alreadyEnabled });
322
+ const updated = mergeConfig(plan.configInput, plan.host, connection, { serverId: instance, previousName: plan.previousName, enable: !alreadyEnabled });
212
323
  const verified = verifiedByHost.get(plan.host);
213
324
  changes.push({ file: plan.paths.skill, before: plan.existingSkill, after: desiredSkill });
214
- if (desiredUpdateSkill) changes.push({ file: plan.paths.updateSkill, before: plan.existingUpdateSkill, after: desiredUpdateSkill });
325
+ if (plan.writeUpdateSkill) changes.push({ file: plan.paths.updateSkill, before: plan.existingUpdateSkill, after: desiredUpdateSkill });
215
326
  // A host may react as soon as its config changes. Make the state and
216
327
  // managed entrypoints available before exposing the new launch command.
217
328
  changes.push(launcherPlan.change, { file: plan.statePath.file, before: plan.stateBefore, after: same ? plan.stateBefore : JSON.stringify(desiredState, null, 2) + '\n' },
218
329
  { file: plan.paths.config, before: plan.original, after: updated });
219
- results.push({ host: plan.host, ...plan.paths, installation: plan.statePath.file, launcher: state.launcher, source, policy: state.policy, ...(migration ? { migration } : {}), ...(plan.previousName !== 'craft' ? { migrated_from: plan.previousName } : {}), ...(plan.fallbackSnapshot ? { imported_from: plan.fallbackSnapshot.file } : {}), verified,
330
+ results.push({ host: plan.host, server_id: instance, ...plan.paths, installation: plan.statePath.file, launcher: state.launcher, source, policy: state.policy, ...(migration ? { migration } : {}), ...(plan.previousName !== instance ? { migrated_from: plan.previousName } : {}), ...(plan.fallbackSnapshot ? { imported_from: plan.fallbackSnapshot.file } : {}), verified,
220
331
  activation_mode: activationMode, reconnect_required: true, activation: { status: 'pending_connection_verification', expected: identity },
221
- connection_handoff: connectionHandoff({host:plan.host,target:identity,workspace:plan.workspace,platform:plan.platform,intent:'install'}) });
332
+ connection_handoff: connectionHandoff({host:plan.host,serverId:instance,channel:source.channel,target:identity,workspace:plan.workspace,platform:plan.platform,intent:'install'}) });
222
333
  }
223
334
  const written = await commitFiles(changes);
224
- return { runtime, hosts: results, ...written,
335
+ return { ...(published.size === 1 ? {runtime:published.values().next().value} : {runtimes:[...published.values()]}), hosts: results, ...written,
225
336
  next: 'The installed package loads at the next MCP start or user-requested reconnect. Verify the actual runtime version/build_id, then prepare the current project to update its context and Skills. Standalone probes do not confirm host activation.' };
226
337
  } catch (error) {
227
338
  if (!['ELOCKED', 'INSTALLATION_CHANGED'].includes(error.code) || attempt === 3) throw error;
228
339
  } finally {
229
340
  try { await release?.(); } finally { for (const unlock of stateLocks.reverse()) await unlock(); }
230
341
  }
342
+ // A different target in a multi-host install may have raced after this
343
+ // candidate was moved. Re-stage its private copy before the next probe.
344
+ for (const [key, candidate] of candidates) if (movedCandidates.has(candidate)) {
345
+ await disposeRuntimeCandidate(candidate);
346
+ candidates.delete(key);
347
+ }
231
348
  await new Promise(resolve => setTimeout(resolve, 100 * (attempt + 1)));
232
349
  }
233
- } finally { await disposeRuntimeCandidate(candidate); }
350
+ } finally { await Promise.all([...candidates.values()].map(disposeRuntimeCandidate)); }
234
351
  }
235
352
 
236
353
  async function verifyInstalledSkills(installation, paths, connection, snapshot) {
@@ -249,7 +366,7 @@ async function verifyInstalledSkills(installation, paths, connection, snapshot)
249
366
  let matches = true;
250
367
  for (const { name, marker } of entries) {
251
368
  const expected = await optionalFile(path.join(candidate.package_root, 'resources', name, 'SKILL.md'));
252
- if (!expected?.includes(marker) || contents.get(name) !== expected) { matches = false; break; }
369
+ if (!expected?.includes(marker) || contents.get(name) !== renderInstanceSkill(expected, name, installation?.server_id ?? 'craft')) { matches = false; break; }
253
370
  }
254
371
  if (matches) return { status: 'verified', runtime: skillRuntimeIdentity(candidate), managed: entries.map(entry => entry.name) };
255
372
  }
@@ -259,18 +376,20 @@ async function verifyInstalledSkills(installation, paths, connection, snapshot)
259
376
  throw new Error('Craft managed Skills differ from the recorded installed Skill runtime; run install again');
260
377
  }
261
378
 
262
- export async function doctorHosts({ ide, home = os.homedir(), codexHome, hostOptions = {}, probe = probeRuntime }) {
379
+ export async function doctorHosts({ ide, home = os.homedir(), codexHome, hostOptions = {}, serverId = 'craft', probe = probeRuntime }) {
380
+ validateServerId(serverId);
263
381
  const results = [];
264
382
  for (const host of installTargets(ide)) {
265
383
  for (let attempt = 0; attempt < 4; attempt++) {
266
384
  try {
267
- const paths = hostPaths(home, host, codexHome, hostOptions);
268
- await assertHostConfigScope(paths.config,host,paths.configPeers);
385
+ const paths = hostPaths(home, host, codexHome, { ...hostOptions, serverId });
386
+ await assertHostConfigScope(paths.config,host,paths.configPeers,serverId);
269
387
  await assertPlainPath(paths.config);
270
- assertDshSharedScope(paths);
388
+ assertDshSharedScope(paths,serverId);
271
389
  const configText = await optionalFile(paths.config) ?? '';
272
- const connection = craftConfig(configText, host);
390
+ const connection = craftConfig(configText, host, serverId);
273
391
  if (!connection?.command || connection.env?.CRAFT_CLIENT_IDE !== host) throw new Error(host + ': Craft installation missing or host marker incorrect; run install --ide ' + host);
392
+ if ((connection.env.CRAFT_SERVER_ID ?? 'craft') !== serverId) throw new Error('Craft instance marker differs from its registration: ' + serverId);
274
393
  if (connection.disabled === true || connection.enabled === false || connection.enable === false) throw new Error(host + ': Craft MCP is disabled');
275
394
  let installation = null, skillsVerification, verificationError;
276
395
  const file = connection.env.CRAFT_INSTALLATION_FILE, skillSnapshots = new Map();
@@ -279,6 +398,7 @@ export async function doctorHosts({ ide, home = os.homedir(), codexHome, hostOpt
279
398
  try {
280
399
  if (await optionalFile(paths.config) !== configText) throw installationChanged();
281
400
  installation = await readInstallation(file);
401
+ checkInstanceBinding(installation, host, paths, serverId, file);
282
402
  const entries = installation.skills ? installedSkillEntries(installation) : [{ file: paths.skill }];
283
403
  for (const entry of entries) {
284
404
  await assertPlainPath(entry.file);
@@ -310,13 +430,13 @@ export async function doctorHosts({ ide, home = os.homedir(), codexHome, hostOpt
310
430
  const skillsPending = Boolean(installation && skillsVerification.runtime?.build_id !== installation.target.build_id);
311
431
  const checkConnection = installation && !installation.launcher ? { ...connection, args: [installation.target.entry, '--workspace', installation.workspace] } : connection;
312
432
  let verified, probeError;
313
- try { verified = await probe(checkConnection, { host, ...(installation ? { version: installation.target.version, build_id: installation.target.build_id, workspace: installation.workspace, platform: installation.platform } : {}) }); }
433
+ try { verified = await probe(checkConnection, { host, serverId, ...(installation ? { version: installation.target.version, build_id: installation.target.build_id, workspace: installation.workspace, platform: installation.platform } : {}) }); }
314
434
  catch (error) { probeError = error; }
315
435
  // The launcher may observe a newer target while a diagnostic probe is
316
436
  // starting. Re-read all scope/config fields on the next bounded attempt.
317
437
  await stableSnapshot();
318
438
  if (probeError) throw probeError;
319
- results.push({ host, ...paths, entry: connection.args[0], target: installation?.target, skills_pending_activation: skillsPending, skills_verification: skillsVerification, verified });
439
+ results.push({ host, server_id: serverId, ...paths, entry: connection.args[0], target: installation?.target, skills_pending_activation: skillsPending, skills_verification: skillsVerification, verified });
320
440
  break;
321
441
  } catch (error) {
322
442
  if (!['ELOCKED', 'INSTALLATION_CHANGED'].includes(error.code) || attempt === 3) throw error;
@@ -336,19 +456,20 @@ export async function installWithLoginTask(options) {
336
456
  if (process.platform === 'win32') {
337
457
  const workbuddy = result.hosts.find(host => host.host === 'workbuddy');
338
458
  if (workbuddy) {
459
+ const instanceOption = workbuddy.server_id === 'craft' ? '' : ' --instance ' + workbuddy.server_id;
339
460
  try {
340
461
  const { ensureWorkBuddyLoginTask } = await import('./workbuddy-login-task.mjs');
341
462
  workbuddy.login_task = await ensureWorkBuddyLoginTask(workbuddy.installation);
342
463
  } catch (error) {
343
464
  workbuddy.login_task = {status: 'unavailable', reason: error.message,
344
- next: 'Windows local-page login requires the on-demand task. Retry install --ide workbuddy after resolving the reported error.'};
465
+ next: 'Windows local-page login requires the on-demand task. Run login-task --setup --ide workbuddy' + instanceOption + ' after resolving the reported error.'};
345
466
  }
346
467
  try {
347
468
  const { ensureWorkBuddyPreviewTask } = await import('./workbuddy-login-task.mjs');
348
469
  workbuddy.preview_task = await ensureWorkBuddyPreviewTask(workbuddy.installation);
349
470
  } catch (error) {
350
471
  workbuddy.preview_task = {status:'unavailable',reason:error.message,
351
- next:'Windows WorkBuddy preview requires the on-demand task. Run preview-task --setup --ide workbuddy after resolving the reported error.'};
472
+ next:'Windows WorkBuddy preview requires the on-demand task. Run preview-task --setup --ide workbuddy' + instanceOption + ' after resolving the reported error.'};
352
473
  }
353
474
  }
354
475
  }
@@ -359,11 +480,20 @@ export async function runIntegrationCommand(args, packageRoot) {
359
480
  const [command, ...rest] = args, options = {};
360
481
  for (let i = 0; i < rest.length; i += 2) {
361
482
  const name = rest[i].replace(/^--/, '');
362
- if (!rest[i].startsWith('--') || !['ide', 'host-config', 'trae-region', ...(command === 'install' ? ['workspace', 'platform', 'registry', 'channel', 'updates'] : [])].includes(name) || !rest[i + 1] || Object.hasOwn(options, name)) throw new Error('Invalid or repeated option. Use craft-mcp --help.');
483
+ if (!rest[i].startsWith('--') || !['ide', 'instance', 'host-config', 'trae-region', ...(command === 'install' ? ['workspace', 'platform', 'registry', 'channel', 'updates'] : [])].includes(name) || !rest[i + 1] || Object.hasOwn(options, name)) throw new Error('Invalid or repeated option. Use craft-mcp --help.');
363
484
  options[name] = rest[i + 1];
364
485
  }
365
486
  options.codexHome = process.env.CODEX_HOME;
366
487
  options.hostOptions = hostCommandOptions(options);
488
+ if (command === 'install') {
489
+ const { name } = JSON.parse(await readFile(path.join(packageRoot,'package.json'),'utf8'));
490
+ const request = await npmInstallSelector(packageRoot, name);
491
+ options.selector = request?.kind ?? 'management';
492
+ options.channel ??= request?.tag;
493
+ if (options.channel === 'latest') options.channel = 'stable';
494
+ }
495
+ options.serverId = validateServerId(options.instance ?? serverIdForChannel(options.channel));
496
+ if (command === 'install' && options.serverId === 'craft' && options.channel && options.channel !== 'stable') throw new Error('The craft instance tracks stable; select a named test instance for ' + options.channel);
367
497
  const result = command === 'install' ? await installWithLoginTask({ ...options, packageRoot }) : await doctorHosts(options);
368
498
  process.stdout.write(JSON.stringify(result, null, 2) + '\n');
369
499
  }
@@ -3,6 +3,7 @@ import { createHash } from 'node:crypto';
3
3
  import { optionalFile } from './files.mjs';
4
4
  import { parseVersion, requireForwardVersion } from './version-policy.mjs';
5
5
  import { hosts } from './hosts.mjs';
6
+ import { instanceSkillName } from './instance-skill.mjs';
6
7
 
7
8
  export const defaultRegistry = 'https://registry.npmjs.org/';
8
9
  export const activationMode = 'next_mcp_start';
@@ -15,7 +16,7 @@ export function installedSkillEntries(state) {
15
16
  if (state.skills === undefined) return [];
16
17
  if (!state.skills || typeof state.skills !== 'object' || Array.isArray(state.skills) || !state.skills['craft-create']) throw new Error('Invalid installed Skill destinations');
17
18
  return Object.entries(state.skills).map(([name, file]) => {
18
- if (!Object.hasOwn(managedSkillMarkers, name) || typeof file !== 'string' || !path.isAbsolute(file) || path.basename(file) !== 'SKILL.md' || path.basename(path.dirname(file)) !== name) throw new Error('Invalid installed Skill destination');
19
+ if (!Object.hasOwn(managedSkillMarkers, name) || typeof file !== 'string' || !path.isAbsolute(file) || path.basename(file) !== 'SKILL.md' || path.basename(path.dirname(file)) !== instanceSkillName(name, state.server_id)) throw new Error('Invalid installed Skill destination');
19
20
  return { name, file, marker: managedSkillMarkers[name] };
20
21
  });
21
22
  }
@@ -0,0 +1,26 @@
1
+ import { validateServerId } from './instance.mjs';
2
+
3
+ export function instanceSkillName(logicalName, serverId = 'craft') {
4
+ validateServerId(serverId);
5
+ if (!['craft-create', 'craft-update'].includes(logicalName)) throw new Error('Unknown Craft entrypoint Skill');
6
+ return serverId + logicalName.slice('craft'.length);
7
+ }
8
+
9
+ // Always render from this runtime's original template, including on update and
10
+ // uninstall. Default installations must still match their installed bytes.
11
+ export function renderInstanceSkill(content, logicalName, serverId = 'craft') {
12
+ const name = instanceSkillName(logicalName, serverId);
13
+ if (serverId === 'craft' || content == null) return content;
14
+ const header = /^---\r?\n([\s\S]*?)\r?\n---(?=\r?\n)/.exec(content);
15
+ if (!header || !header[1].split(/\r?\n/).includes('name: ' + logicalName)) {
16
+ throw new Error('Invalid packaged Skill frontmatter for ' + logicalName);
17
+ }
18
+ const action = logicalName === 'craft-create' ? '创建、继续或上传游戏' : '检查和更新安装';
19
+ const description = '仅在用户指定 ' + serverId + ',或当前项目已绑定其渠道和工作区时,使用该实例' + action + '。';
20
+ const frontmatter = header[1].replace(/^name: .*$/m, 'name: ' + name)
21
+ .replace(/^description: .*$/m, 'description: ' + description);
22
+ return '---\n' + frontmatter + '\n---\n\n'
23
+ + '本入口对应 MCP 服务 `' + serverId + '`。发现该服务的工具,调用其 `craft_game_info` 核对 server_id、渠道和工作区。'
24
+ + '后续制作、上传、轮询、更新及重连均使用这条连接。\n'
25
+ + content.slice(header[0].length);
26
+ }
@@ -0,0 +1,29 @@
1
+ import { createHash } from 'node:crypto';
2
+
3
+ export function validateServerId(id) {
4
+ if (typeof id !== 'string' || id.length > 32 || !/^craft(?:-[a-z0-9]+(?:-[a-z0-9]+)*)?$/.test(id)) {
5
+ throw new Error('Invalid Craft instance name; use craft or craft-<lowercase-identifier> (up to 32 characters)');
6
+ }
7
+ return id;
8
+ }
9
+
10
+ export function serverIdForChannel(channel) {
11
+ if (channel === undefined || channel === 'stable' || channel === 'latest') return 'craft';
12
+ if (typeof channel !== 'string' || !/^[a-zA-Z][a-zA-Z0-9._-]*$/.test(channel)) throw new Error('Update channel must be an npm dist-tag');
13
+ const simple = 'craft-' + channel;
14
+ if (simple.length <= 32 && /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(channel)) return simple;
15
+ // Host server names (including DSH) have a common limit of 32. Retain
16
+ // distinct case-sensitive tags when the tag cannot be used verbatim.
17
+ const prefix = channel.toLowerCase().replace(/[^a-z0-9]+/g, '-').slice(0, 13).replace(/-$/, '');
18
+ return 'craft-' + prefix + '-' + createHash('sha256').update(channel).digest('hex').slice(0, 12);
19
+ }
20
+
21
+ // An unmarked renamed Craft registration belongs to the legacy default slot.
22
+ // Managed named instances identify themselves even when several share a host.
23
+ export function registrationsForInstance(registrations, serverId) {
24
+ return registrations.filter(({ name, connection }) => {
25
+ const marker = connection?.env?.CRAFT_SERVER_ID;
26
+ if (marker !== undefined && marker !== name && (marker === serverId || name === serverId)) throw new Error('Craft instance marker differs from its registration: ' + name);
27
+ return marker === undefined ? serverId === 'craft' : marker === serverId;
28
+ });
29
+ }
@@ -31,7 +31,7 @@ async function start() {
31
31
  if (state.host === 'workbuddy' && state.login_data_dir && process.env.CRAFT_STANDALONE_PROBE !== '1') {
32
32
  process.env.CLIENT_DATA_DIR ||= state.login_data_dir;
33
33
  }
34
- for (const [key, expected] of Object.entries({ CRAFT_CLIENT_IDE: state.host, CLIENT_WORKSPACE_ROOT: state.workspace, CRAFT_WEB_URL: state.platform })) {
34
+ for (const [key, expected] of Object.entries({ CRAFT_CLIENT_IDE: state.host, CRAFT_SERVER_ID: state.server_id, CLIENT_WORKSPACE_ROOT: state.workspace, CRAFT_WEB_URL: state.platform })) {
35
35
  if (process.env[key] && process.env[key] !== expected) throw new Error('Craft launcher scope mismatch: ' + key);
36
36
  process.env[key] = expected;
37
37
  }
@@ -4,12 +4,12 @@ import { ensureWorkBuddyLoginTask, removeWorkBuddyLoginTask, ensureWorkBuddyPrev
4
4
 
5
5
  export async function runLoginTaskCommand([command, action, ...args]) {
6
6
  const preview = command === 'preview-task';
7
- const usage = `Use ${preview ? 'preview' : 'login'}-task --setup|--remove --ide workbuddy [--host-config ABS]`;
7
+ const usage = `Use ${preview ? 'preview' : 'login'}-task --setup|--remove --ide workbuddy [--host-config ABS] [--instance NAME]`;
8
8
  const options = {};
9
9
  for (let i = 0; i < args.length; i += 2) {
10
10
  const key = args[i];
11
11
  const value = args[i + 1];
12
- if (!['--ide', '--host-config'].includes(key) || !value || value.startsWith('--') || Object.hasOwn(options,key.slice(2))) {
12
+ if (!['--ide', '--host-config', '--instance'].includes(key) || !value || value.startsWith('--') || Object.hasOwn(options,key.slice(2))) {
13
13
  throw new Error(usage);
14
14
  }
15
15
  options[key.slice(2)] = value;
@@ -17,7 +17,7 @@ export async function runLoginTaskCommand([command, action, ...args]) {
17
17
  if (!['--setup', '--remove'].includes(action) || options.ide !== 'workbuddy') {
18
18
  throw new Error(usage);
19
19
  }
20
- const { installation } = await installedConnection('workbuddy', {hostOptions: hostCommandOptions(options), env: {}});
20
+ const { installation } = await installedConnection('workbuddy', {serverId: options.instance, hostOptions: hostCommandOptions(options), env: {}});
21
21
  const setup = preview ? ensureWorkBuddyPreviewTask : ensureWorkBuddyLoginTask;
22
22
  const remove = preview ? removeWorkBuddyPreviewTask : removeWorkBuddyLoginTask;
23
23
  const result = action === '--setup' ? await setup(installation) : await remove(installation);