@craft_eco/craft-mcp 0.1.29 → 0.1.30

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 (152) hide show
  1. package/README.md +10 -55
  2. package/bin/craft-mcp.mjs +4 -1
  3. package/dist-server/game-workflow/check.mjs +3 -2
  4. package/dist-server/game-workflow/context-state.mjs +67 -67
  5. package/dist-server/game-workflow/draft-archive.mjs +147 -2
  6. package/dist-server/game-workflow/draft-upload-identity.mjs +11 -0
  7. package/dist-server/game-workflow/draft-uploads.mjs +105 -60
  8. package/dist-server/game-workflow/local-context.mjs +62 -62
  9. package/dist-server/game-workflow/native-context.mjs +289 -289
  10. package/dist-server/game-workflow/project-bundles.mjs +246 -246
  11. package/dist-server/game-workflow/project-context.mjs +8 -8
  12. package/dist-server/game-workflow/projects.mjs +6 -4
  13. package/dist-server/game-workflow/tasks.mjs +1 -1
  14. package/dist-server/game-workflow/work-scope.mjs +7 -7
  15. package/dist-server/integrations/config.mjs +145 -145
  16. package/dist-server/integrations/connect.mjs +36 -0
  17. package/dist-server/integrations/connection-handoff.mjs +36 -42
  18. package/dist-server/integrations/dsh-config.mjs +182 -182
  19. package/dist-server/integrations/files.mjs +54 -54
  20. package/dist-server/integrations/fixed-launcher.mjs +31 -0
  21. package/dist-server/integrations/host-reload.mjs +19 -0
  22. package/dist-server/integrations/hosts.mjs +55 -55
  23. package/dist-server/integrations/install.mjs +223 -205
  24. package/dist-server/integrations/installation-state.mjs +84 -84
  25. package/dist-server/integrations/launcher-start.mjs +52 -0
  26. package/dist-server/integrations/npm-diagnostics.mjs +32 -0
  27. package/dist-server/integrations/runtime-gc.mjs +191 -188
  28. package/dist-server/integrations/runtime-identity.mjs +22 -0
  29. package/dist-server/integrations/runtime.mjs +111 -126
  30. package/dist-server/integrations/updates.mjs +258 -225
  31. package/dist-server/integrations/version-policy.mjs +32 -32
  32. package/dist-server/launcher.mjs +1845 -0
  33. package/dist-server/mcp/control-panel.mjs +8 -23
  34. package/dist-server/mcp/server.mjs +31 -80
  35. package/dist-server/mcp/update-session.mjs +107 -92
  36. package/dist-server/upstream/craft-aigc.mjs +43 -16
  37. package/dist-server/upstream/draft-source.mjs +29 -0
  38. package/package.json +3 -2
  39. package/resources/context-filter-report.json +1 -1
  40. package/resources/craft-create/SKILL.md +19 -19
  41. package/resources/craft-update/SKILL.md +9 -11
  42. package/resources/targets/claude/js/bootstrap/SKILL.md +3 -1
  43. package/resources/targets/claude/js/context-filter-report.json +1 -1
  44. package/resources/targets/claude/js/craft-game-maker/SKILL.md +11 -15
  45. package/resources/targets/claude/js/js/bundle.json +7 -7
  46. package/resources/targets/claude/js/recovery.md +5 -1
  47. package/resources/targets/claude/js/target.json +1 -1
  48. package/resources/targets/claude/js3d/bootstrap/SKILL.md +3 -1
  49. package/resources/targets/claude/js3d/context-filter-report.json +1 -1
  50. package/resources/targets/claude/js3d/craft-game-maker/SKILL.md +11 -15
  51. package/resources/targets/claude/js3d/js3d/bundle.json +7 -7
  52. package/resources/targets/claude/js3d/recovery.md +5 -1
  53. package/resources/targets/claude/js3d/target.json +1 -1
  54. package/resources/targets/codebuddy/js/bootstrap/SKILL.md +3 -1
  55. package/resources/targets/codebuddy/js/context-filter-report.json +1 -1
  56. package/resources/targets/codebuddy/js/craft-game-maker/SKILL.md +11 -15
  57. package/resources/targets/codebuddy/js/js/bundle.json +7 -7
  58. package/resources/targets/codebuddy/js/recovery.md +5 -1
  59. package/resources/targets/codebuddy/js/target.json +1 -1
  60. package/resources/targets/codebuddy/js3d/bootstrap/SKILL.md +3 -1
  61. package/resources/targets/codebuddy/js3d/context-filter-report.json +1 -1
  62. package/resources/targets/codebuddy/js3d/craft-game-maker/SKILL.md +11 -15
  63. package/resources/targets/codebuddy/js3d/js3d/bundle.json +7 -7
  64. package/resources/targets/codebuddy/js3d/recovery.md +5 -1
  65. package/resources/targets/codebuddy/js3d/target.json +1 -1
  66. package/resources/targets/codex/js/bootstrap/SKILL.md +2 -4
  67. package/resources/targets/codex/js/context-filter-report.json +1 -1
  68. package/resources/targets/codex/js/craft-game-maker/SKILL.md +11 -15
  69. package/resources/targets/codex/js/js/bundle.json +7 -7
  70. package/resources/targets/codex/js/recovery.md +3 -3
  71. package/resources/targets/codex/js/target.json +1 -1
  72. package/resources/targets/codex/js3d/bootstrap/SKILL.md +2 -4
  73. package/resources/targets/codex/js3d/context-filter-report.json +1 -1
  74. package/resources/targets/codex/js3d/craft-game-maker/SKILL.md +11 -15
  75. package/resources/targets/codex/js3d/js3d/bundle.json +7 -7
  76. package/resources/targets/codex/js3d/recovery.md +3 -3
  77. package/resources/targets/codex/js3d/target.json +1 -1
  78. package/resources/targets/cursor/js/bootstrap/SKILL.md +3 -1
  79. package/resources/targets/cursor/js/context-filter-report.json +1 -1
  80. package/resources/targets/cursor/js/craft-game-maker/SKILL.md +11 -15
  81. package/resources/targets/cursor/js/js/bundle.json +7 -7
  82. package/resources/targets/cursor/js/recovery.md +5 -1
  83. package/resources/targets/cursor/js/target.json +1 -1
  84. package/resources/targets/cursor/js3d/bootstrap/SKILL.md +3 -1
  85. package/resources/targets/cursor/js3d/context-filter-report.json +1 -1
  86. package/resources/targets/cursor/js3d/craft-game-maker/SKILL.md +11 -15
  87. package/resources/targets/cursor/js3d/js3d/bundle.json +7 -7
  88. package/resources/targets/cursor/js3d/recovery.md +5 -1
  89. package/resources/targets/cursor/js3d/target.json +1 -1
  90. package/resources/targets/dsh/js/bootstrap/SKILL.md +3 -1
  91. package/resources/targets/dsh/js/context-filter-report.json +1 -1
  92. package/resources/targets/dsh/js/craft-game-maker/SKILL.md +11 -15
  93. package/resources/targets/dsh/js/js/bundle.json +7 -7
  94. package/resources/targets/dsh/js/recovery.md +5 -1
  95. package/resources/targets/dsh/js/target.json +1 -1
  96. package/resources/targets/dsh/js3d/bootstrap/SKILL.md +3 -1
  97. package/resources/targets/dsh/js3d/context-filter-report.json +1 -1
  98. package/resources/targets/dsh/js3d/craft-game-maker/SKILL.md +11 -15
  99. package/resources/targets/dsh/js3d/js3d/bundle.json +7 -7
  100. package/resources/targets/dsh/js3d/recovery.md +5 -1
  101. package/resources/targets/dsh/js3d/target.json +1 -1
  102. package/resources/targets/index.json +32 -32
  103. package/resources/targets/kimi/js/bootstrap/SKILL.md +3 -1
  104. package/resources/targets/kimi/js/context-filter-report.json +1 -1
  105. package/resources/targets/kimi/js/craft-game-maker/SKILL.md +11 -15
  106. package/resources/targets/kimi/js/js/bundle.json +7 -7
  107. package/resources/targets/kimi/js/recovery.md +5 -1
  108. package/resources/targets/kimi/js/target.json +1 -1
  109. package/resources/targets/kimi/js3d/bootstrap/SKILL.md +3 -1
  110. package/resources/targets/kimi/js3d/context-filter-report.json +1 -1
  111. package/resources/targets/kimi/js3d/craft-game-maker/SKILL.md +11 -15
  112. package/resources/targets/kimi/js3d/js3d/bundle.json +7 -7
  113. package/resources/targets/kimi/js3d/recovery.md +5 -1
  114. package/resources/targets/kimi/js3d/target.json +1 -1
  115. package/resources/targets/workbuddy/js/bootstrap/SKILL.md +22 -24
  116. package/resources/targets/workbuddy/js/context-filter-report.json +1 -1
  117. package/resources/targets/workbuddy/js/craft-game-maker/SKILL.md +11 -15
  118. package/resources/targets/workbuddy/js/js/bundle.json +8 -8
  119. package/resources/targets/workbuddy/js/js/context/AGENTS.md +29 -29
  120. package/resources/targets/workbuddy/js/recovery.md +19 -19
  121. package/resources/targets/workbuddy/js/target.json +1 -1
  122. package/resources/targets/workbuddy/js3d/bootstrap/SKILL.md +22 -24
  123. package/resources/targets/workbuddy/js3d/context-filter-report.json +1 -1
  124. package/resources/targets/workbuddy/js3d/craft-game-maker/SKILL.md +11 -15
  125. package/resources/targets/workbuddy/js3d/js3d/bundle.json +8 -8
  126. package/resources/targets/workbuddy/js3d/js3d/context/AGENTS.md +30 -30
  127. package/resources/targets/workbuddy/js3d/recovery.md +19 -19
  128. package/resources/targets/workbuddy/js3d/target.json +1 -1
  129. package/resources/targets/zcode/js/bootstrap/SKILL.md +3 -1
  130. package/resources/targets/zcode/js/context-filter-report.json +1 -1
  131. package/resources/targets/zcode/js/craft-game-maker/SKILL.md +11 -15
  132. package/resources/targets/zcode/js/js/bundle.json +7 -7
  133. package/resources/targets/zcode/js/recovery.md +5 -1
  134. package/resources/targets/zcode/js/target.json +1 -1
  135. package/resources/targets/zcode/js3d/bootstrap/SKILL.md +3 -1
  136. package/resources/targets/zcode/js3d/context-filter-report.json +1 -1
  137. package/resources/targets/zcode/js3d/craft-game-maker/SKILL.md +11 -15
  138. package/resources/targets/zcode/js3d/js3d/bundle.json +7 -7
  139. package/resources/targets/zcode/js3d/recovery.md +5 -1
  140. package/resources/targets/zcode/js3d/target.json +1 -1
  141. package/vendor/craft-runtime/SOURCE.json +4 -4
  142. package/vendor/craft-runtime/package.json +1 -1
  143. package/dist-server/game-workflow/publication-materials.mjs +0 -92
  144. package/dist-server/game-workflow/publications.mjs +0 -168
  145. package/dist-server/game-workflow/publish-capture-worker.mjs +0 -57
  146. package/dist-server/game-workflow/publish-capture.mjs +0 -75
  147. package/dist-server/mcp/publication-page.html +0 -86
  148. package/dist-server/mcp/publication-page.mjs +0 -375
  149. package/dist-server/mcp/publication-preview.mjs +0 -63
  150. package/dist-server/mcp/publication-tools.mjs +0 -22
  151. package/dist-server/mcp/publish-panel.mjs +0 -210
  152. package/dist-server/upstream/publication-transport.mjs +0 -101
@@ -1,225 +1,258 @@
1
- import path from 'node:path';
2
- import { mkdir } from 'node:fs/promises';
3
- import lockfile from 'proper-lockfile';
4
- import { readInstallation, readInstallationSnapshot, activationStatus, registryOrigin, installedSkillEntries, skillRuntimeIdentity, sameRuntimeIdentity, activationMode } from './installation-state.mjs';
5
- import { compareVersions, requireForwardVersion, parseVersion } from './version-policy.mjs';
6
- import { stageRegistryRuntime, getRuntimeIdentity, probeRuntime } from './runtime.mjs';
7
- import { optionalFile, assertPlainPath, commitFiles } from './files.mjs';
8
- import { hostPaths, hostEnvironment, installTargets } from './hosts.mjs';
9
- import { craftConfig, mergeConfig } from './config.mjs';
10
- import { assertDshSharedScope } from './dsh-config.mjs';
11
- import { connectionHandoff } from './connection-handoff.mjs';
12
- import os from 'node:os';
13
-
14
- export { readInstallation } from './installation-state.mjs';
15
- const pending = new Map();
16
- const receiptLifetime = 5 * 60 * 1000;
17
-
18
- function result(state, current, status, extra = {}) {
19
- return { status, installation_id: state.id, source: state.source, policy: state.policy,
20
- current, target: state.target, activation: activationStatus(current, state.target),
21
- activation_mode: state.activation_mode ?? 'legacy_front', migration_required: state.schema === 1,
22
- activation_required: false, reconnect_required: !sameRuntimeIdentity(current, state.target), explicitly_not_started: true, ...extra };
23
- }
24
-
25
- export async function readUpdateStatus({ installationFile, current }) {
26
- if (!installationFile) return { status: 'unmanaged', current, activation_required: false, note: 'Run the standard Craft installer once to enable automatic updates.' };
27
- try {
28
- const state = await readInstallation(installationFile);
29
- const activation = activationStatus(current, state.target);
30
- return result(state, current, state.schema === 1 ? 'migration_required' : activation.status === 'active_verified' ? 'current' : activation.status, { last_check: state.last_check, can_continue: state.schema === 2 && activation.status === 'active_verified' });
31
- } catch (error) { return { status: 'error', code: 'invalid_installation', message: error.message, current, can_continue: false, activation_required: false }; }
32
- }
33
-
34
- export async function queryRegistry(source, { fetchImpl = fetch, timeoutMs = 15000 } = {}) {
35
- const registry = registryOrigin(source.registry);
36
- const url = new URL(encodeURIComponent(source.package) + '/' + encodeURIComponent(source.channel), registry);
37
- const response = await fetchImpl(url, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(timeoutMs) });
38
- if (!response.ok) throw Object.assign(new Error('npm version check failed (HTTP ' + response.status + ')'), { code: response.status >= 400 && response.status < 500 && ![408, 429].includes(response.status) ? 'INVALID_REGISTRY_METADATA' : 'REGISTRY_UNAVAILABLE' });
39
- let data;
40
- try { data = await response.json(); if (data.name !== source.package) throw new Error('npm returned a different package identity'); parseVersion(data.version); }
41
- catch { throw Object.assign(new Error('npm returned invalid package identity metadata'), { code: 'INVALID_REGISTRY_METADATA' }); }
42
- const integrity = data.dist?.integrity ?? (data.dist?.shasum && /^[a-f0-9]{40}$/.test(data.dist.shasum) ? 'sha1-' + Buffer.from(data.dist.shasum, 'hex').toString('base64') : undefined);
43
- if (!integrity || !String(integrity).split(/\s+/).some(value => /^(sha512|sha384|sha256|sha1)-[A-Za-z0-9+/]+={0,2}$/.test(value))) throw Object.assign(new Error('npm package integrity metadata is missing or invalid'), { code: 'INVALID_REGISTRY_METADATA' });
44
- return { package: data.name, version: data.version, integrity, node: data.engines?.node ?? null };
45
- }
46
-
47
- function within(root, file) {
48
- const relative = path.relative(path.resolve(root), path.resolve(file));
49
- return relative === '' || (!relative.startsWith('..' + path.sep) && relative !== '..' && !path.isAbsolute(relative));
50
- }
51
-
52
- async function candidateSkills(state, identity) {
53
- // Skill locations are explicit installer-owned destinations. Do not infer a
54
- // user's home from a custom CODEX_HOME or rewrite unrelated host directories.
55
- const changes = [];
56
- for (const { name, file, marker } of installedSkillEntries(state)) {
57
- await assertPlainPath(file);
58
- const desired = await optionalFile(path.join(identity.package_root, 'resources', name, 'SKILL.md'));
59
- if (desired === null) throw new Error('Updated runtime is missing the managed ' + name + ' Skill');
60
- if (!desired.includes(marker)) throw new Error('Updated runtime has an invalid managed Skill marker');
61
- const before = await optionalFile(file);
62
- if (before && !before.includes(marker)) throw new Error('User-owned Skill preserved: ' + file);
63
- changes.push({ file, before, after: desired });
64
- }
65
- return changes;
66
- }
67
-
68
- export async function confirmActiveInstallation({ installationFile, current }) {
69
- if (!current?.instance_id) throw new Error('An actual runtime instance is required to confirm the installation');
70
- const unlock = await lockfile.lock(installationFile, { stale: 120000, retries: { retries: 30, minTimeout: 100, maxTimeout: 500 } });
71
- try {
72
- const { state, text: before } = await readInstallationSnapshot(installationFile);
73
- if (state.schema !== 2 || state.activation_mode !== activationMode) throw new Error('Legacy Craft installation requires the standard installer before reconnecting');
74
- if (activationStatus(current, state.target).status !== 'active_verified') throw new Error('The current connection does not match the configured update target');
75
- if (!sameRuntimeIdentity(await getRuntimeIdentity(current.package_root), state.target)) throw new Error('The running package files do not match the configured update target');
76
- const skills = await candidateSkills(state, current);
77
- if (skills.some(change => change.before !== change.after)) throw new Error('Installed global Skills differ from the configured runtime; run install again');
78
- const previous = state.connection_verification;
79
- const receipt = previous?.instance_id === current.instance_id ? previous : { version: current.version, build_id: current.build_id, instance_id: current.instance_id, confirmed_at: new Date().toISOString() };
80
- const written = await commitFiles([{ file: installationFile, before, after: receipt === previous ? before : JSON.stringify({ ...state, connection_verification: receipt }, null, 2) + '\n' }]);
81
- return { status: 'active_verified', ...receipt, ...written, scope: 'current_connection' };
82
- } finally { await unlock(); }
83
- }
84
-
85
- async function hostUpdate(state, installationFile, identity) {
86
- await assertPlainPath(state.config);
87
- if (state.host === 'dsh') assertDshSharedScope({ dshHome: path.dirname(state.config) });
88
- const before = await optionalFile(state.config);
89
- if (before === null) throw new Error('Craft host configuration is missing; run install again');
90
- const existing = craftConfig(before, state.host, state.server_id);
91
- 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));
92
- const workspaceIndex = existing?.args?.indexOf('--workspace') ?? -1;
93
- if (!existing || !samePath(existing.env?.CRAFT_INSTALLATION_FILE, installationFile) || existing.env?.CRAFT_CLIENT_IDE !== state.host ||
94
- !samePath(workspaceIndex >= 0 ? existing.args[workspaceIndex + 1] : existing.env?.CLIENT_WORKSPACE_ROOT, state.workspace) ||
95
- 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');
96
- const connection = { 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, CRAFT_INSTALLATION_FILE: installationFile } };
97
- return { file: state.config, before, after: mergeConfig(before, state.host, connection, { previousName: state.server_id, enable: false }) };
98
- }
99
-
100
- async function checkLocked({ installationFile, current, intent, requestKey, projectCompatibility, lookup, materialize, probe }) {
101
- const snapshot = await readInstallationSnapshot(installationFile), before = snapshot.text;
102
- let state = snapshot.state;
103
- if (current.package !== state.source.package) return result(state, current, 'error', { code: 'package_mismatch', can_continue: false });
104
- try { requireForwardVersion(state.target, current); }
105
- catch (error) { return result(state, current, 'error', { code: 'target_not_forward', message: error.message, can_continue: false }); }
106
- let pendingIncompatible;
107
- const activationPending = !sameRuntimeIdentity(current, state.target);
108
- if (activationPending) {
109
- try { if (projectCompatibility) await projectCompatibility(state.target.package_root); }
110
- catch (error) { pendingIncompatible = error.message; }
111
- if (!pendingIncompatible && intent !== 'inspect') return result(state, current, 'pending_reconnect', { reconnect_required: true, can_continue: false });
112
- }
113
- let currentIncompatible = pendingIncompatible;
114
- if (!currentIncompatible) {
115
- try { if (projectCompatibility) await projectCompatibility(current.package_root); }
116
- catch (error) { currentIncompatible = error.message; }
117
- }
118
- const keepCurrent = (status, extra = {}) => result(state, current, currentIncompatible ? 'incompatible' : status,
119
- { ...extra, can_continue: state.schema === 2 && !activationPending && !currentIncompatible && extra.can_continue !== false, ...(currentIncompatible ? { underlying_status: status, message: currentIncompatible } : {}) });
120
- if (state.policy.mode === 'off' && !['inspect', 'update'].includes(intent)) return keepCurrent('disabled');
121
- let remote, checkedAt;
122
- const last = state.last_check;
123
- if (requestKey && last?.request_key === requestKey && last.remote && Date.now() - Date.parse(last.checked_at) < receiptLifetime && last.source_key === JSON.stringify(state.source)) {
124
- remote = last.remote; checkedAt = last.checked_at;
125
- } else {
126
- try { remote = await lookup(state.source); checkedAt = new Date().toISOString(); }
127
- catch (error) {
128
- if (error.code === 'INVALID_REGISTRY_METADATA') return result(state, current, 'error', { code: 'invalid_registry_metadata', message: error.message, can_continue: false });
129
- // Network failure is an unknown remote state, never proof of latest.
130
- return keepCurrent('offline', { checked_at: new Date().toISOString(), remote_status: 'unknown', message: error.message, can_continue: state.schema === 2 && !currentIncompatible && !activationPending && state.policy.offline === 'allow-existing' });
131
- }
132
- }
133
- try {
134
- if (remote.package !== state.source.package) throw new Error('npm package identity mismatch');
135
- parseVersion(remote.version);
136
- } catch (error) { return result(state, current, 'error', { code: 'invalid_registry_identity', message: error.message, can_continue: false }); }
137
- const receipt = { checked_at: checkedAt, ...(requestKey ? { request_key: requestKey } : {}), source_key: JSON.stringify(state.source), remote };
138
- // A staged target can be unsuitable for this particular project. Keep it as
139
- // the minimum version while looking for a newer compatible replacement.
140
- const comparison = compareVersions(remote.version, state.target.version);
141
- if (comparison === 0 && state.target.origin?.kind === 'npm' && state.target.origin.registry === state.source.registry && state.target.origin.integrity !== remote.integrity) {
142
- return result(state, current, 'error', { code: 'same_version_integrity_changed', checked_at: checkedAt, remote, message: 'The registry reports different bytes for an installed package version; automatic replacement refused', can_continue: false });
143
- }
144
- if (comparison <= 0 || intent === 'inspect') {
145
- const after = { ...state, last_check: receipt };
146
- await commitFiles([{ file: installationFile, before, after: JSON.stringify(after, null, 2) + '\n' }]);
147
- state = after;
148
- if (currentIncompatible && comparison <= 0) return keepCurrent(comparison < 0 ? 'local_ahead' : 'current', { checked_at: checkedAt, remote });
149
- const remoteStatus = comparison < 0 ? 'local_ahead' : comparison === 0 ? 'current' : 'available';
150
- return result(after, current, state.schema === 1 && comparison <= 0 ? 'migration_required' : activationPending && comparison <= 0 ? 'pending_reconnect' : remoteStatus, { checked_at: checkedAt, remote,
151
- ...(activationPending ? { remote_status: remoteStatus } : {}),
152
- ...(comparison === 0 ? { remote_build_status: state.target.origin?.integrity === remote.integrity ? 'integrity_matches' : 'not_compared_local_install' } : {}),
153
- ...(currentIncompatible ? { current_compatibility: { status: 'incompatible', message: currentIncompatible } } : {}), can_continue: state.schema === 2 && !currentIncompatible && !activationPending });
154
- }
155
- const runtimeRoot = state.runtime_root;
156
- if (!path.isAbsolute(runtimeRoot ?? '')) return result(state, current, 'error', { code: 'invalid_runtime_root', can_continue: false });
157
- await mkdir(runtimeRoot, { recursive: true });
158
- const unlock = await lockfile.lock(runtimeRoot, { stale: 120000, retries: { retries: 20, minTimeout: 250, maxTimeout: 1000 } });
159
- try {
160
- const runtime = await materialize(state.source, remote, runtimeRoot);
161
- const identity = await getRuntimeIdentity(runtime.package_root ?? path.resolve(path.dirname(runtime.entry), '..'));
162
- if (!within(runtimeRoot, identity.package_root) || identity.package !== state.source.package || identity.version !== remote.version) throw new Error('Candidate runtime identity/path mismatch');
163
- requireForwardVersion(identity, state.target);
164
- if (projectCompatibility) {
165
- try { await projectCompatibility(identity.package_root); }
166
- catch (error) { return result(state, current, 'incompatible', { checked_at: checkedAt, remote, message: error.message, can_continue: false }); }
167
- }
168
- 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 } },
169
- { version: identity.version, build_id: identity.build_id, host: state.host, workspace: state.workspace, platform: state.platform });
170
- if (verified.runtime?.activation_mode !== activationMode) throw new Error('Candidate runtime does not support activation at the next MCP start');
171
- const skillChanges = await candidateSkills(state, identity), configChange = await hostUpdate(state, installationFile, identity);
172
- const target = { ...identity, origin: { kind: 'npm', registry: state.source.registry, integrity: remote.integrity } };
173
- const after = { ...state, schema: 2, activation_mode: activationMode, anchor: identity, target, skills_runtime: skillRuntimeIdentity(identity), last_check: receipt, updated_at: new Date().toISOString() };
174
- delete after.connection_verification;
175
- await commitFiles([...skillChanges, { file: installationFile, before, after: JSON.stringify(after, null, 2) + '\n' }, configChange]);
176
- state = after;
177
- return result(state, current, 'pending_reconnect', { checked_at: checkedAt, remote, reconnect_required: true, can_continue: false, verified: { ...verified, scope: 'standalone_probe' } });
178
- } catch (error) { return result(state, current, 'error', { checked_at: checkedAt, remote, code: 'candidate_rejected', message: error.message, can_continue: false }); }
179
- finally { await unlock(); }
180
- }
181
-
182
- export async function checkForUpdate({ installationFile, current, intent = 'inspect', requestKey, projectCompatibility, lookup = queryRegistry, materialize = stageRegistryRuntime, probe = probeRuntime }) {
183
- if (!installationFile) return { status: 'unmanaged', current, can_continue: true, activation_required: false, note: 'Install Craft once to enable automatic updates.' };
184
- if (!['inspect', 'create', 'resume', 'update'].includes(intent)) throw new Error('Invalid update intent');
185
- // Serialize per installation across processes. A shared promise only merges
186
- // the same logical request in this process; a later work still checks npm.
187
- const key = requestKey ? JSON.stringify([installationFile, current.build_id, current.instance_id, intent, requestKey]) : Symbol('unkeyed update');
188
- if (pending.has(key)) return pending.get(key);
189
- const operation = (async () => {
190
- let unlock;
191
- try {
192
- unlock = await lockfile.lock(installationFile, { stale: 120000, retries: { retries: 30, minTimeout: 100, maxTimeout: 500 } });
193
- return await checkLocked({ installationFile, current, intent, requestKey, projectCompatibility, lookup, materialize, probe });
194
- } catch (error) { return { status: 'error', code: 'update_failed', message: error.message, current, can_continue: false, activation_required: false }; }
195
- finally { await unlock?.(); }
196
- })();
197
- pending.set(key, operation);
198
- try { return await operation; } finally { if (pending.get(key) === operation) pending.delete(key); }
199
- }
200
-
201
- export async function runUpdateCommand(args) {
202
- const [command, ...rest] = args, options = {};
203
- for (let i = 0; i < rest.length; i += 2) {
204
- const key = rest[i]?.replace(/^--/, '');
205
- if (rest[i] !== '--ide' || !rest[i + 1] || Object.hasOwn(options, key)) throw new Error('Use craft-mcp ' + command + ' --ide <host>');
206
- options[key] = rest[i + 1];
207
- }
208
- const results = [];
209
- for (const host of installTargets(options.ide)) {
210
- const paths = hostPaths(os.homedir(), host, process.env.CODEX_HOME, hostEnvironment());
211
- await assertPlainPath(paths.config);
212
- assertDshSharedScope(paths);
213
- const connection = craftConfig(await optionalFile(paths.config) ?? '', host);
214
- const installationFile = connection?.env?.CRAFT_INSTALLATION_FILE;
215
- if (!installationFile) throw new Error(host + ': Install Craft once before using automatic updates');
216
- const state = await readInstallation(installationFile);
217
- const current = await getRuntimeIdentity(state.target.package_root);
218
- const update = await checkForUpdate({ installationFile, current, intent: command === 'update' ? 'update' : 'inspect', requestKey: 'cli-' + Date.now() });
219
- // A CLI can inspect configured files, but cannot prove a host connection.
220
- 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.',
221
- ...(!['error','incompatible','migration_required'].includes(update.status) ? {connection_handoff:connectionHandoff({host,target:update.target,workspace:state.workspace,platform:state.platform,intent:command==='update'?'update':'inspect'})} : {}) });
222
- if (['error', 'incompatible'].includes(update.status)) process.exitCode = 1;
223
- }
224
- process.stdout.write(JSON.stringify({ hosts: results }, null, 2) + '\n');
225
- }
1
+ import path from 'node:path';
2
+ import { mkdir } from 'node:fs/promises';
3
+ import lockfile from 'proper-lockfile';
4
+ import { readInstallation, readInstallationSnapshot, activationStatus, registryOrigin, installedSkillEntries, skillRuntimeIdentity, sameRuntimeIdentity, activationMode } from './installation-state.mjs';
5
+ import { compareVersions, requireForwardVersion, parseVersion } from './version-policy.mjs';
6
+ import { stageRegistryRuntime, getRuntimeIdentity, probeRuntime } from './runtime.mjs';
7
+ import { optionalFile, assertPlainPath, commitFiles } from './files.mjs';
8
+ import { hostPaths, hostEnvironment, installTargets } from './hosts.mjs';
9
+ import { craftConfig, mergeConfig } from './config.mjs';
10
+ import { assertDshSharedScope } from './dsh-config.mjs';
11
+ import { connectionHandoff } from './connection-handoff.mjs';
12
+ import { planLauncher, verifyLauncher } from './fixed-launcher.mjs';
13
+ import os from 'node:os';
14
+
15
+ export { readInstallation } from './installation-state.mjs';
16
+ const pending = new Map();
17
+ const receiptLifetime = 5 * 60 * 1000;
18
+
19
+ function result(state, current, status, extra = {}) {
20
+ return { status, installation_id: state.id, source: state.source, policy: state.policy,
21
+ current, target: state.target, activation: activationStatus(current, state.target),
22
+ activation_mode: state.activation_mode ?? 'legacy_front', migration_required: state.schema === 1,
23
+ activation_required: false, reconnect_required: !sameRuntimeIdentity(current, state.target), explicitly_not_started: true, ...extra };
24
+ }
25
+
26
+ export async function readUpdateStatus({ installationFile, current }) {
27
+ if (!installationFile) return { status: 'unmanaged', current, activation_required: false, note: 'Run the standard Craft installer once to enable automatic updates.' };
28
+ try {
29
+ const state = await readInstallation(installationFile);
30
+ const activation = activationStatus(current, state.target);
31
+ return result(state, current, state.schema === 1 ? 'migration_required' : activation.status === 'active_verified' ? 'current' : activation.status, { last_check: state.last_check, can_continue: state.schema === 2 && activation.status === 'active_verified' });
32
+ } catch (error) { return { status: 'error', code: 'invalid_installation', message: error.message, current, can_continue: false, activation_required: false }; }
33
+ }
34
+
35
+ export async function queryRegistry(source, { fetchImpl = fetch, timeoutMs = 15000 } = {}) {
36
+ const registry = registryOrigin(source.registry);
37
+ const url = new URL(encodeURIComponent(source.package) + '/' + encodeURIComponent(source.channel), registry);
38
+ const response = await fetchImpl(url, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(timeoutMs) });
39
+ if (!response.ok) throw Object.assign(new Error('npm version check failed (HTTP ' + response.status + ')'), { code: response.status >= 400 && response.status < 500 && ![408, 429].includes(response.status) ? 'INVALID_REGISTRY_METADATA' : 'REGISTRY_UNAVAILABLE' });
40
+ let data;
41
+ try { data = await response.json(); if (data.name !== source.package) throw new Error('npm returned a different package identity'); parseVersion(data.version); }
42
+ catch { throw Object.assign(new Error('npm returned invalid package identity metadata'), { code: 'INVALID_REGISTRY_METADATA' }); }
43
+ const integrity = data.dist?.integrity ?? (data.dist?.shasum && /^[a-f0-9]{40}$/.test(data.dist.shasum) ? 'sha1-' + Buffer.from(data.dist.shasum, 'hex').toString('base64') : undefined);
44
+ if (!integrity || !String(integrity).split(/\s+/).some(value => /^(sha512|sha384|sha256|sha1)-[A-Za-z0-9+/]+={0,2}$/.test(value))) throw Object.assign(new Error('npm package integrity metadata is missing or invalid'), { code: 'INVALID_REGISTRY_METADATA' });
45
+ return { package: data.name, version: data.version, integrity, node: data.engines?.node ?? null };
46
+ }
47
+
48
+ function within(root, file) {
49
+ const relative = path.relative(path.resolve(root), path.resolve(file));
50
+ return relative === '' || (!relative.startsWith('..' + path.sep) && relative !== '..' && !path.isAbsolute(relative));
51
+ }
52
+
53
+ async function candidateSkills(state, identity) {
54
+ // Skill locations are explicit installer-owned destinations. Do not infer a
55
+ // user's home from a custom CODEX_HOME or rewrite unrelated host directories.
56
+ const changes = [];
57
+ for (const { name, file, marker } of installedSkillEntries(state)) {
58
+ await assertPlainPath(file);
59
+ const desired = await optionalFile(path.join(identity.package_root, 'resources', name, 'SKILL.md'));
60
+ if (desired === null) throw new Error('Updated runtime is missing the managed ' + name + ' Skill');
61
+ if (!desired.includes(marker)) throw new Error('Updated runtime has an invalid managed Skill marker');
62
+ const before = await optionalFile(file);
63
+ if (before && !before.includes(marker)) throw new Error('User-owned Skill preserved: ' + file);
64
+ changes.push({ file, before, after: desired });
65
+ }
66
+ return changes;
67
+ }
68
+
69
+ export async function confirmActiveInstallation({ installationFile, current }) {
70
+ if (!current?.instance_id) throw new Error('An actual runtime instance is required to confirm the installation');
71
+ const unlock = await lockfile.lock(installationFile, { stale: 120000, retries: { retries: 30, minTimeout: 100, maxTimeout: 500 } });
72
+ try {
73
+ const { state, text: before } = await readInstallationSnapshot(installationFile);
74
+ if (state.schema !== 2 || state.activation_mode !== activationMode) throw new Error('Legacy Craft installation requires the standard installer before reconnecting');
75
+ if (activationStatus(current, state.target).status !== 'active_verified') throw new Error('The current connection does not match the configured update target');
76
+ if (!sameRuntimeIdentity(await getRuntimeIdentity(current.package_root), state.target)) throw new Error('The running package files do not match the configured update target');
77
+ await verifyLauncher(state, installationFile);
78
+ const skills = await candidateSkills(state, current);
79
+ if (skills.some(change => change.before !== change.after)) throw new Error('Installed global Skills differ from the configured runtime; run install again');
80
+ const previous = state.connection_verification;
81
+ const receipt = previous?.instance_id === current.instance_id ? previous : { version: current.version, build_id: current.build_id, instance_id: current.instance_id, confirmed_at: new Date().toISOString() };
82
+ const written = await commitFiles([{ file: installationFile, before, after: receipt === previous ? before : JSON.stringify({ ...state, connection_verification: receipt }, null, 2) + '\n' }]);
83
+ return { status: 'active_verified', ...receipt, ...written, scope: 'current_connection' };
84
+ } finally { await unlock(); }
85
+ }
86
+
87
+ async function hostUpdate(state, installationFile, launcher, identity) {
88
+ await assertPlainPath(state.config);
89
+ if (state.host === 'dsh') assertDshSharedScope({ dshHome: path.dirname(state.config) });
90
+ const before = await optionalFile(state.config);
91
+ if (before === null) throw new Error('Craft host configuration is missing; run install again');
92
+ const existing = craftConfig(before, state.host, state.server_id);
93
+ await verifyLauncher(state, installationFile, existing);
94
+ 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));
95
+ const workspaceIndex = existing?.args?.indexOf('--workspace') ?? -1;
96
+ if (!existing || !samePath(existing.env?.CRAFT_INSTALLATION_FILE, installationFile) || existing.env?.CRAFT_CLIENT_IDE !== state.host ||
97
+ !samePath(workspaceIndex >= 0 ? existing.args[workspaceIndex + 1] : existing.env?.CLIENT_WORKSPACE_ROOT, state.workspace) ||
98
+ 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');
99
+ // Fixed-entry updates must not rewrite watched host configuration: a host
100
+ // could otherwise restart an in-flight MCP task on an env-only change.
101
+ if (state.launcher?.entry === launcher.entry) return { file: state.config, before, after: before };
102
+ 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 } };
103
+ return { file: state.config, before, after: mergeConfig(before, state.host, connection, { previousName: state.server_id, enable: false }) };
104
+ }
105
+
106
+ async function checkLocked({ installationFile, current, intent, requestKey, projectCompatibility, registryReceipt, lookup, materialize, probe }) {
107
+ const snapshot = await readInstallationSnapshot(installationFile), before = snapshot.text;
108
+ let state = snapshot.state;
109
+ if (current.package !== state.source.package) return result(state, current, 'error', { code: 'package_mismatch', can_continue: false });
110
+ try { requireForwardVersion(state.target, current); }
111
+ catch (error) { return result(state, current, 'error', { code: 'target_not_forward', message: error.message, can_continue: false }); }
112
+ let pendingIncompatible;
113
+ const activationPending = !sameRuntimeIdentity(current, state.target);
114
+ if (activationPending) {
115
+ try { if (projectCompatibility) await projectCompatibility(state.target.package_root); }
116
+ catch (error) { pendingIncompatible = error.message; }
117
+ if (!pendingIncompatible && intent !== 'inspect') return result(state, current, 'pending_reconnect', { reconnect_required: true, can_continue: false });
118
+ }
119
+ let currentIncompatible = pendingIncompatible;
120
+ if (!currentIncompatible) {
121
+ try { if (projectCompatibility) await projectCompatibility(current.package_root); }
122
+ catch (error) { currentIncompatible = error.message; }
123
+ }
124
+ const keepCurrent = (status, extra = {}) => result(state, current, currentIncompatible ? 'incompatible' : status,
125
+ { ...extra, can_continue: state.schema === 2 && !activationPending && !currentIncompatible && extra.can_continue !== false, ...(currentIncompatible ? { underlying_status: status, message: currentIncompatible } : {}) });
126
+ if (state.policy.mode === 'off' && !['inspect', 'update'].includes(intent)) return keepCurrent('disabled');
127
+ let remote, checkedAt;
128
+ const last = registryReceipt ?? state.last_check;
129
+ const age = Date.now() - Date.parse(last?.checked_at);
130
+ if ((registryReceipt || (requestKey && last?.request_key === requestKey)) && last?.remote && age >= 0 && age < receiptLifetime && last.source_key === JSON.stringify(state.source)) {
131
+ remote = last.remote; checkedAt = last.checked_at;
132
+ } else {
133
+ try { remote = await lookup(state.source); checkedAt = new Date().toISOString(); }
134
+ catch (error) {
135
+ if (error.code === 'INVALID_REGISTRY_METADATA') return result(state, current, 'error', { code: 'invalid_registry_metadata', message: error.message, can_continue: false });
136
+ // Network failure is an unknown remote state, never proof of latest.
137
+ return keepCurrent('offline', { checked_at: new Date().toISOString(), remote_status: 'unknown', message: error.message, can_continue: state.schema === 2 && !currentIncompatible && !activationPending && state.policy.offline === 'allow-existing' });
138
+ }
139
+ }
140
+ try {
141
+ if (remote.package !== state.source.package) throw new Error('npm package identity mismatch');
142
+ parseVersion(remote.version);
143
+ } catch (error) { return result(state, current, 'error', { code: 'invalid_registry_identity', message: error.message, can_continue: false }); }
144
+ const receipt = { checked_at: checkedAt, ...(requestKey ? { request_key: requestKey } : {}), source_key: JSON.stringify(state.source), remote };
145
+ // A staged target can be unsuitable for this particular project. Keep it as
146
+ // the minimum version while looking for a newer compatible replacement.
147
+ const comparison = compareVersions(remote.version, state.target.version);
148
+ if (comparison === 0 && state.target.origin?.kind === 'npm' && state.target.origin.registry === state.source.registry && state.target.origin.integrity !== remote.integrity) {
149
+ return result(state, current, 'error', { code: 'same_version_integrity_changed', checked_at: checkedAt, remote, message: 'The registry reports different bytes for an installed package version; automatic replacement refused', can_continue: false });
150
+ }
151
+ if (comparison <= 0 || intent === 'inspect') {
152
+ // Public version checks are read-only. Their receipts live in the MCP
153
+ // connection; only an installer/preparation may persist a receipt.
154
+ if (intent !== 'inspect') {
155
+ const after = { ...state, last_check: receipt };
156
+ await commitFiles([{ file: installationFile, before, after: JSON.stringify(after, null, 2) + '\n' }]);
157
+ state = after;
158
+ }
159
+ if (currentIncompatible && comparison <= 0) return keepCurrent(comparison < 0 ? 'local_ahead' : 'current', { checked_at: checkedAt, remote });
160
+ const remoteStatus = comparison < 0 ? 'local_ahead' : comparison === 0 ? 'current' : 'available';
161
+ return result(state, current, state.schema === 1 && comparison <= 0 ? 'migration_required' : activationPending && comparison <= 0 ? 'pending_reconnect' : remoteStatus, { checked_at: checkedAt, remote,
162
+ update_available: comparison > 0, automatic_update_enabled: state.policy.mode !== 'off',
163
+ ...(activationPending ? { remote_status: remoteStatus } : {}),
164
+ ...(comparison === 0 ? { remote_build_status: state.target.origin?.integrity === remote.integrity ? 'integrity_matches' : 'not_compared_local_install' } : {}),
165
+ ...(currentIncompatible ? { current_compatibility: { status: 'incompatible', message: currentIncompatible } } : {}), can_continue: state.schema === 2 && !currentIncompatible && !activationPending });
166
+ }
167
+ const runtimeRoot = state.runtime_root;
168
+ if (!path.isAbsolute(runtimeRoot ?? '')) return result(state, current, 'error', { code: 'invalid_runtime_root', can_continue: false });
169
+ await mkdir(runtimeRoot, { recursive: true });
170
+ const unlock = await lockfile.lock(runtimeRoot, { stale: 120000, retries: { retries: 20, minTimeout: 250, maxTimeout: 1000 } });
171
+ let originalConfig;
172
+ try {
173
+ originalConfig = await optionalFile(state.config);
174
+ const runtime = await materialize(state.source, remote, runtimeRoot);
175
+ const identity = await getRuntimeIdentity(runtime.package_root ?? path.resolve(path.dirname(runtime.entry), '..'));
176
+ if (!within(runtimeRoot, identity.package_root) || identity.package !== state.source.package || identity.version !== remote.version) throw new Error('Candidate runtime identity/path mismatch');
177
+ requireForwardVersion(identity, state.target);
178
+ if (projectCompatibility) {
179
+ try { await projectCompatibility(identity.package_root); }
180
+ catch (error) { return result(state, current, 'incompatible', { checked_at: checkedAt, remote, message: error.message, can_continue: false }); }
181
+ }
182
+ 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 } },
183
+ { version: identity.version, build_id: identity.build_id, host: state.host, workspace: state.workspace, platform: state.platform });
184
+ if (verified.runtime?.activation_mode !== activationMode) throw new Error('Candidate runtime does not support activation at the next MCP start');
185
+ const launcherPlan = await planLauncher(installationFile, state.launcher, identity.package_root);
186
+ const skillChanges = await candidateSkills(state, identity), configChange = await hostUpdate(state, installationFile, launcherPlan.launcher, identity);
187
+ const target = { ...identity, origin: { kind: 'npm', registry: state.source.registry, integrity: remote.integrity } };
188
+ const after = { ...state, schema: 2, activation_mode: activationMode, launcher: launcherPlan.launcher, anchor: identity, target, skills_runtime: skillRuntimeIdentity(identity), last_check: receipt, updated_at: new Date().toISOString() };
189
+ delete after.connection_verification;
190
+ await commitFiles([...skillChanges, launcherPlan.change, { file: installationFile, before, after: JSON.stringify(after, null, 2) + '\n' }, configChange]);
191
+ state = after;
192
+ return result(state, current, 'pending_reconnect', { checked_at: checkedAt, remote, reconnect_required: true, can_continue: false, verified: { ...verified, scope: 'standalone_probe' } });
193
+ } catch (error) {
194
+ const failure = { checked_at: checkedAt, remote, code: 'candidate_rejected', message: error.message, ...(error.npm_code?{npm_code:error.npm_code}:{}) };
195
+ try {
196
+ // A failed candidate must not disable a verified existing installation.
197
+ // Recheck the rollback, scope and complete old package before allowing work.
198
+ if (state.schema !== 2 || activationPending || currentIncompatible) throw new Error(currentIncompatible ?? 'No compatible active installation to retain');
199
+ if (await optionalFile(installationFile) !== before) throw new Error('Installation state changed; rollback could not be verified');
200
+ if (originalConfig === undefined || originalConfig === null || await optionalFile(state.config) !== originalConfig) throw new Error('Host configuration changed; rollback could not be verified');
201
+ if (!sameRuntimeIdentity(await getRuntimeIdentity(current.package_root), state.target)) throw new Error('Existing runtime integrity check failed');
202
+ await hostUpdate(state, installationFile, state.launcher ?? { entry: current.entry }, current);
203
+ 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');
204
+ const skills = await candidateSkills(state, current);
205
+ if (skills.some(change => change.before !== change.after)) throw new Error('Existing managed Skills differ from the current runtime');
206
+ return result(state, current, 'update_failed', { ...failure, can_continue: true, retained_version: current.version,
207
+ next: 'Report the update failure and continue with the verified existing version. A later new work can retry the update; do not claim the newest version is running.' });
208
+ } catch (fallbackError) {
209
+ return result(state, current, 'error', { ...failure, can_continue: false, fallback_error: fallbackError.message });
210
+ }
211
+ }
212
+ finally { await unlock(); }
213
+ }
214
+
215
+ export async function checkForUpdate({ installationFile, current, intent = 'inspect', requestKey, projectCompatibility, registryReceipt, lookup = queryRegistry, materialize = stageRegistryRuntime, probe = probeRuntime }) {
216
+ if (!installationFile) return { status: 'unmanaged', current, can_continue: true, activation_required: false, note: 'Install Craft once to enable automatic updates.' };
217
+ if (!['inspect', 'auto', 'create', 'resume', 'update'].includes(intent)) throw new Error('Invalid update intent');
218
+ // Serialize per installation across processes. A shared promise only merges
219
+ // the same logical request in this process; a later work still checks npm.
220
+ const key = requestKey ? JSON.stringify([installationFile, current.build_id, current.instance_id, intent, requestKey]) : Symbol('unkeyed update');
221
+ if (pending.has(key)) return pending.get(key);
222
+ const operation = (async () => {
223
+ let unlock;
224
+ try {
225
+ unlock = await lockfile.lock(installationFile, { stale: 120000, retries: { retries: 30, minTimeout: 100, maxTimeout: 500 } });
226
+ return await checkLocked({ installationFile, current, intent, requestKey, projectCompatibility, registryReceipt, lookup, materialize, probe });
227
+ } catch (error) { return { status: 'error', code: 'update_failed', message: error.message, current, can_continue: false, activation_required: false }; }
228
+ finally { await unlock?.(); }
229
+ })();
230
+ pending.set(key, operation);
231
+ try { return await operation; } finally { if (pending.get(key) === operation) pending.delete(key); }
232
+ }
233
+
234
+ export async function runUpdateCommand(args) {
235
+ const [command, ...rest] = args, options = {};
236
+ for (let i = 0; i < rest.length; i += 2) {
237
+ const key = rest[i]?.replace(/^--/, '');
238
+ if (rest[i] !== '--ide' || !rest[i + 1] || Object.hasOwn(options, key)) throw new Error('Use craft-mcp ' + command + ' --ide <host>');
239
+ options[key] = rest[i + 1];
240
+ }
241
+ const results = [];
242
+ for (const host of installTargets(options.ide)) {
243
+ const paths = hostPaths(os.homedir(), host, process.env.CODEX_HOME, hostEnvironment());
244
+ await assertPlainPath(paths.config);
245
+ assertDshSharedScope(paths);
246
+ const connection = craftConfig(await optionalFile(paths.config) ?? '', host);
247
+ const installationFile = connection?.env?.CRAFT_INSTALLATION_FILE;
248
+ if (!installationFile) throw new Error(host + ': Install Craft once before using automatic updates');
249
+ const state = await readInstallation(installationFile);
250
+ const current = await getRuntimeIdentity(state.target.package_root);
251
+ const update = await checkForUpdate({ installationFile, current, intent: command === 'update' ? 'update' : 'inspect', requestKey: 'cli-' + Date.now() });
252
+ // A CLI can inspect configured files, but cannot prove a host connection.
253
+ 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.',
254
+ ...(!['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'})} : {}) });
255
+ if (['error', 'update_failed', 'incompatible'].includes(update.status)) process.exitCode = 1;
256
+ }
257
+ process.stdout.write(JSON.stringify({ hosts: results }, null, 2) + '\n');
258
+ }