@craft_eco/craft-mcp 0.1.34-beta.3 → 0.1.34

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 (64) hide show
  1. package/README.md +5 -3
  2. package/bin/craft-mcp.mjs +3 -1
  3. package/dist-server/core/upload-limits.mjs +11 -0
  4. package/dist-server/game-workflow/art-previews.mjs +71 -71
  5. package/dist-server/game-workflow/bundle-files.mjs +6 -1
  6. package/dist-server/game-workflow/engines.mjs +18 -9
  7. package/dist-server/game-workflow/local-context.mjs +64 -64
  8. package/dist-server/game-workflow/project-art-previews.mjs +63 -63
  9. package/dist-server/game-workflow/project-context.mjs +4 -1
  10. package/dist-server/game-workflow/project-install.mjs +15 -7
  11. package/dist-server/game-workflow/projects.mjs +13 -3
  12. package/dist-server/integrations/distribution-targets.mjs +9 -0
  13. package/dist-server/integrations/install.mjs +49 -11
  14. package/dist-server/integrations/instance-skill.mjs +26 -26
  15. package/dist-server/integrations/instance.mjs +29 -29
  16. package/dist-server/integrations/launcher-start.mjs +5 -5
  17. package/dist-server/integrations/project-setup.mjs +2 -0
  18. package/dist-server/integrations/runtime-candidate.mjs +32 -6
  19. package/dist-server/integrations/runtime-file-diagnostics.mjs +68 -0
  20. package/dist-server/integrations/runtime-gc.mjs +8 -2
  21. package/dist-server/integrations/runtime-identity.mjs +56 -8
  22. package/dist-server/integrations/runtime.mjs +5 -2
  23. package/dist-server/integrations/uninstall.mjs +160 -160
  24. package/dist-server/integrations/updates.mjs +17 -20
  25. package/dist-server/launcher.mjs +47 -8
  26. package/dist-server/mcp/production-events.mjs +52 -29
  27. package/dist-server/mcp/server.mjs +5 -4
  28. package/dist-server/preview/preview-snapshot.mjs +3 -2
  29. package/package.json +5 -5
  30. package/resources/context-filter-report.json +1 -1
  31. package/resources/craft-create/SKILL.md +25 -25
  32. package/resources/craft-update/SKILL.md +27 -27
  33. package/resources/targets/claude/js/context-filter-report.json +1 -1
  34. package/resources/targets/claude/js3d/context-filter-report.json +1 -1
  35. package/resources/targets/codebuddy/js/context-filter-report.json +1 -1
  36. package/resources/targets/codebuddy/js3d/context-filter-report.json +1 -1
  37. package/resources/targets/codex/js/context-filter-report.json +1 -1
  38. package/resources/targets/codex/js3d/context-filter-report.json +1 -1
  39. package/resources/targets/comate/js/context-filter-report.json +1 -1
  40. package/resources/targets/comate/js3d/context-filter-report.json +1 -1
  41. package/resources/targets/cursor/js/context-filter-report.json +1 -1
  42. package/resources/targets/cursor/js3d/context-filter-report.json +1 -1
  43. package/resources/targets/dsh/js/context-filter-report.json +1 -1
  44. package/resources/targets/dsh/js3d/context-filter-report.json +1 -1
  45. package/resources/targets/kimi/js/context-filter-report.json +1 -1
  46. package/resources/targets/kimi/js3d/context-filter-report.json +1 -1
  47. package/resources/targets/opencode/js/context-filter-report.json +1 -1
  48. package/resources/targets/opencode/js3d/context-filter-report.json +1 -1
  49. package/resources/targets/qoder/js/context-filter-report.json +1 -1
  50. package/resources/targets/qoder/js3d/context-filter-report.json +1 -1
  51. package/resources/targets/qoder-cn/js/context-filter-report.json +1 -1
  52. package/resources/targets/qoder-cn/js3d/context-filter-report.json +1 -1
  53. package/resources/targets/qwen/js/context-filter-report.json +1 -1
  54. package/resources/targets/qwen/js3d/context-filter-report.json +1 -1
  55. package/resources/targets/trae/js/context-filter-report.json +1 -1
  56. package/resources/targets/trae/js3d/context-filter-report.json +1 -1
  57. package/resources/targets/workbuddy/js/context-filter-report.json +1 -1
  58. package/resources/targets/workbuddy/js3d/context-filter-report.json +1 -1
  59. package/resources/targets/zcode/js/context-filter-report.json +1 -1
  60. package/resources/targets/zcode/js3d/context-filter-report.json +1 -1
  61. package/vendor/craft-runtime/NOTICE.md +1 -1
  62. package/vendor/craft-runtime/SOURCE.json +10 -6
  63. package/vendor/craft-runtime/index.js +228 -164
  64. package/vendor/craft-runtime/package.json +1 -1
@@ -1,12 +1,11 @@
1
1
  import path from 'node:path';
2
2
  import { readFile, readdir, lstat } from 'node:fs/promises';
3
3
  import { createHash } from 'node:crypto';
4
+ import { assertPlainPath, optionalFile } from './files.mjs';
4
5
 
5
- // The content identity is independent of tarball repacking and is read from the
6
- // running package, never from a host-provided version environment variable.
7
- export async function getRuntimeIdentity(packageRoot) {
8
- packageRoot = path.resolve(packageRoot);
9
- const pkg = JSON.parse(await readFile(path.join(packageRoot, 'package.json'), 'utf8'));
6
+ // Installation and diagnosis use the same path ordering and bytes. Collecting
7
+ // individual hashes is optional and never requires reading a file twice.
8
+ export async function hashRuntimeFiles(packageRoot, files) {
10
9
  const hash = createHash('sha256');
11
10
  async function visit(relative) {
12
11
  const file = path.join(packageRoot, relative);
@@ -14,9 +13,58 @@ export async function getRuntimeIdentity(packageRoot) {
14
13
  if (info.isSymbolicLink()) throw new Error('Craft runtime contains a linked product file: ' + relative);
15
14
  if (info.isDirectory()) {
16
15
  for (const entry of (await readdir(file)).sort()) if (entry !== 'node_modules') await visit(relative + '/' + entry);
17
- } else if (info.isFile()) hash.update(relative + '\0').update(await readFile(file)).update('\0');
18
- else throw new Error('Invalid Craft runtime file: ' + relative);
16
+ } else if (info.isFile()) {
17
+ const bytes = await readFile(file);
18
+ hash.update(relative + '\0').update(bytes).update('\0');
19
+ if (files) files[relative] = createHash('sha256').update(bytes).digest('hex');
20
+ } else throw new Error('Invalid Craft runtime file: ' + relative);
19
21
  }
20
22
  for (const relative of ['package.json', 'bin', 'dist-server', 'resources', 'vendor']) await visit(relative);
21
- return { package: pkg.name, version: pkg.version, build_id: hash.digest('hex'), package_root: packageRoot, entry: path.join(packageRoot, 'bin/craft-mcp.mjs') };
23
+ return hash.digest('hex');
24
+ }
25
+
26
+ function identityForPackage(packageRoot, pkg, buildId) {
27
+ return { package: pkg.name, version: pkg.version, build_id: buildId, package_root: packageRoot, entry: path.join(packageRoot, 'bin/craft-mcp.mjs') };
28
+ }
29
+
30
+ export async function getRuntimeIdentity(packageRoot, { files } = {}) {
31
+ packageRoot = path.resolve(packageRoot);
32
+ const pkg = JSON.parse(await readFile(path.join(packageRoot, 'package.json'), 'utf8'));
33
+ return identityForPackage(packageRoot, pkg, await hashRuntimeFiles(packageRoot, files));
34
+ }
35
+
36
+ // Locate the installation receipt from the executable itself, never from the
37
+ // host's target pointer, which can switch while an older session is running.
38
+ export function runtimeDirectoryForPackage(packageRoot) {
39
+ const parent = path.dirname(path.resolve(packageRoot));
40
+ const modules = path.basename(parent).startsWith('@') ? path.dirname(parent) : parent;
41
+ return path.basename(modules) === 'node_modules' ? path.dirname(modules) : null;
42
+ }
43
+
44
+ export async function readRunningIdentity(packageRoot, { managed = false } = {}) {
45
+ packageRoot = path.resolve(packageRoot);
46
+ const directory = runtimeDirectoryForPackage(packageRoot);
47
+ if (!directory) return getRuntimeIdentity(packageRoot);
48
+ const receiptFile = path.join(directory, 'craft-runtime.json');
49
+ await assertPlainPath(receiptFile);
50
+ const text = await optionalFile(receiptFile);
51
+ if (text === null) {
52
+ if (managed) throw new Error('Craft runtime installation receipt is missing; run doctor for the selected instance');
53
+ return getRuntimeIdentity(packageRoot);
54
+ }
55
+ const receipt = JSON.parse(text);
56
+ const packageFile = path.join(packageRoot, 'package.json');
57
+ await assertPlainPath(packageFile);
58
+ const pkg = JSON.parse(await readFile(packageFile, 'utf8'));
59
+ const name = path.relative(path.join(directory, 'node_modules'), packageRoot).split(path.sep).join('/');
60
+ if (name !== pkg.name || receipt.package !== pkg.name || receipt.version !== pkg.version ||
61
+ !/^[a-f0-9]{64}$/.test(receipt.sha256 ?? '') || (receipt.build_id !== undefined && !/^[a-f0-9]{64}$/.test(receipt.build_id))) {
62
+ throw new Error('Craft runtime package and installation receipt disagree; run doctor for the selected instance');
63
+ }
64
+ // Old unmanaged distributions and pre-build-id receipts have no independent
65
+ // installed identity. Preserve their existing content-based identification.
66
+ const identity = identityForPackage(packageRoot, pkg, receipt.build_id ?? await hashRuntimeFiles(packageRoot));
67
+ await assertPlainPath(identity.entry);
68
+ if (!(await lstat(identity.entry)).isFile()) throw new Error('Craft runtime entry must be a regular file');
69
+ return identity;
22
70
  }
@@ -1,4 +1,5 @@
1
1
  import { getRuntimeIdentity } from './runtime-identity.mjs';
2
+ import { writeRuntimeFileList } from './runtime-file-diagnostics.mjs';
2
3
  import path from 'node:path';
3
4
  import os from 'node:os';
4
5
  import { existsSync } from 'node:fs';
@@ -52,8 +53,10 @@ async function stageArchive(archive, pkg, runtimeRoot, { registry, integrity } =
52
53
  const stagedRoot = path.join(staging, 'node_modules', ...pkg.name.split('/'));
53
54
  const installed = JSON.parse(await readFile(path.join(stagedRoot, 'package.json'), 'utf8'));
54
55
  if (installed.name !== pkg.name || installed.version !== pkg.version || !installed.bin?.['craft-mcp'] || !installed.files?.includes('resources')) throw new Error('Downloaded package is not the expected Craft distribution');
55
- const identity = await getRuntimeIdentity(stagedRoot);
56
- await writeFile(path.join(staging, 'craft-runtime.json'), JSON.stringify({ version: pkg.version, package: pkg.name, sha256: hash, build_id: identity.build_id, ...(integrity ? { integrity } : {}) }) + '\n');
56
+ const files = Object.create(null);
57
+ const identity = await getRuntimeIdentity(stagedRoot, { files });
58
+ const files_sha256 = await writeRuntimeFileList(staging, identity, files);
59
+ await writeFile(path.join(staging, 'craft-runtime.json'), JSON.stringify({ version: pkg.version, package: pkg.name, sha256: hash, build_id: identity.build_id, files_sha256, ...(integrity ? { integrity } : {}) }) + '\n');
57
60
  await rename(staging, target);
58
61
  } finally { await rm(staging, { recursive: true, force: true }); }
59
62
  }
@@ -1,160 +1,160 @@
1
- import os from 'node:os';
2
- import path from 'node:path';
3
- import { createHash } from 'node:crypto';
4
- import { readdir } from 'node:fs/promises';
5
- import lockfile from 'proper-lockfile';
6
- import { getAppDataRoot } from '../core/app-paths.mjs';
7
- import { hostCommandOptions, hostEnvironment, hostPaths, installTargets } from './hosts.mjs';
8
- import { craftConfig, craftRegistrations, removeConfig } from './config.mjs';
9
- import { assertDshSharedScope } from './dsh-config.mjs';
10
- import { assertHostConfigScope } from './host-config-scope.mjs';
11
- import { assertPlainPath, commitFiles, optionalFile } from './files.mjs';
12
- import { verifyLauncher } from './fixed-launcher.mjs';
13
- import { validateServerId } from './instance.mjs';
14
- import { renderInstanceSkill } from './instance-skill.mjs';
15
- import { installationPath, installedSkillEntries, readInstallationSnapshot, sameRuntimeIdentity } from './installation-state.mjs';
16
- import { unchangedInstallation } from './installation-transaction.mjs';
17
- import { getRuntimeIdentity } from './runtime-identity.mjs';
18
- import { ensureWorkBuddyLoginTask, ensureWorkBuddyPreviewTask, removeWorkBuddyLoginTask, removeWorkBuddyPreviewTask } from './workbuddy-login-task.mjs';
19
-
20
- const samePath = (left, right) => typeof left === 'string' && path.isAbsolute(left) && path.relative(left, right) === '';
21
-
22
- // Separate Codex configuration files can share the same user-level Skill root.
23
- // Unknown state cannot establish exclusive ownership, so preserve the Skill.
24
- async function sharedSkills(stateRoot, ownFile, entries) {
25
- const shared = new Set();
26
- for (const item of await readdir(stateRoot, { withFileTypes: true })) {
27
- if (!/^[0-9a-f]{24}\.json$/i.test(item.name)) continue;
28
- const file = path.join(stateRoot, item.name);
29
- if (samePath(file, ownFile)) continue;
30
- try {
31
- await assertPlainPath(file);
32
- const { state } = await readInstallationSnapshot(file);
33
- if (!state.skills) return new Set(entries.map(entry => entry.file));
34
- for (const { file: skill } of installedSkillEntries(state)) {
35
- for (const entry of entries) if (samePath(skill, entry.file)) shared.add(entry.file);
36
- }
37
- } catch {
38
- for (const entry of entries) shared.add(entry.file);
39
- }
40
- }
41
- return shared;
42
- }
43
-
44
- async function verifiedTemplates(state, entries) {
45
- const expected = new Map();
46
- if (!entries.length || !state.skills_runtime) return expected;
47
- const identity = state.skills_runtime;
48
- try {
49
- if (!sameRuntimeIdentity(await getRuntimeIdentity(identity.package_root), identity)) return expected;
50
- for (const { name, marker } of entries) {
51
- const template = await optionalFile(path.join(identity.package_root, 'resources', name, 'SKILL.md'));
52
- if (template?.includes(marker)) expected.set(name, renderInstanceSkill(template, name, state.server_id));
53
- }
54
- } catch (error) {
55
- if (error.code !== 'ENOENT') throw error;
56
- }
57
- return expected;
58
- }
59
-
60
- export async function uninstallHost({ ide, serverId = 'craft', home = os.homedir(), codexHome = process.env.CODEX_HOME,
61
- hostOptions = hostEnvironment(), runtimeRoot = path.join(getAppDataRoot(), 'runtimes'),
62
- stateRoot = path.join(path.dirname(runtimeRoot), 'installations') }) {
63
- validateServerId(serverId);
64
- const targets = installTargets(ide);
65
- if (targets.length !== 1) throw new Error('Uninstall requires exactly one host');
66
- const [host] = targets;
67
- const paths = hostPaths(home, host, codexHome, { ...hostOptions, serverId });
68
- const { file, id } = installationPath(stateRoot, host, paths.config, serverId);
69
- const result = { host, server_id: serverId, config: paths.config, installation: file };
70
- await assertPlainPath(paths.config);
71
- await assertPlainPath(file);
72
- const text = await optionalFile(paths.config);
73
- const connection = craftConfig(text ?? '', host, serverId);
74
- if (!connection && await optionalFile(file) === null) return { ...result, status: 'absent', changed: [], preserved_skills: [] };
75
- if (!samePath(connection?.env?.CRAFT_INSTALLATION_FILE, file) || connection.env.CRAFT_CLIENT_IDE !== host ||
76
- (connection.env.CRAFT_SERVER_ID ?? 'craft') !== serverId) {
77
- throw new Error('Registration does not point to the selected managed Craft installation; files were preserved');
78
- }
79
- const { state } = await readInstallationSnapshot(file);
80
- if (state.id !== id || state.server_id !== serverId || state.host !== host || !samePath(state.config, paths.config) ||
81
- !samePath(state.runtime_root, runtimeRoot)) throw new Error('Installation state does not match the selected Craft instance');
82
- const entries = installedSkillEntries(state);
83
- for (const { name, file: skill } of entries) {
84
- if (!samePath(skill, name === 'craft-create' ? paths.skill : paths.updateSkill)) throw new Error('Recorded Craft Skill is outside the selected installation: ' + skill);
85
- }
86
- // Verify the package content identity outside the state/configuration locks.
87
- const expected = await verifiedTemplates(state, entries);
88
- const locks = [], restoreTasks = [], tasks = [];
89
- try {
90
- for (const target of [paths.config, file].sort()) {
91
- locks.push(await lockfile.lock(target, { realpath: false, stale: 120000, retries: 0 }));
92
- }
93
- locks.push(await lockfile.lock(runtimeRoot, { stale: 120000, retries: 0 }));
94
- const snapshot = await unchangedInstallation(file, state);
95
- const original = await optionalFile(paths.config);
96
- const binding = craftConfig(original ?? '', host, serverId);
97
- if (!samePath(binding?.env?.CRAFT_INSTALLATION_FILE, file) || binding.env.CRAFT_CLIENT_IDE !== host ||
98
- (binding.env.CRAFT_SERVER_ID ?? 'craft') !== serverId ||
99
- craftRegistrations(original, host).some(reg => reg.name !== serverId && samePath(reg.connection?.env?.CRAFT_INSTALLATION_FILE, file))) {
100
- throw new Error('Craft registration ownership changed or is ambiguous; files were preserved');
101
- }
102
- assertDshSharedScope(paths, serverId);
103
- await assertHostConfigScope(paths.config, host, paths.configPeers, serverId);
104
- await verifyLauncher(state, file, binding);
105
- const changes = [{ file: paths.config, before: original, after: removeConfig(original, host, serverId) }];
106
- const shared = await sharedSkills(stateRoot, file, entries);
107
- const preserved = [];
108
- for (const entry of entries) {
109
- await assertPlainPath(entry.file);
110
- const before = await optionalFile(entry.file);
111
- if (before === null) continue;
112
- if (shared.has(entry.file) || expected.get(entry.name) !== before) {
113
- preserved.push({ file: entry.file, reason: shared.has(entry.file) ? 'other_installation' : 'modified_or_unverified' });
114
- } else {
115
- changes.push({ file: entry.file, before, after: null });
116
- }
117
- }
118
- if (state.launcher) {
119
- const before = await optionalFile(state.launcher.entry);
120
- if (before === null || createHash('sha256').update(before).digest('hex') !== state.launcher.sha256) {
121
- throw new Error('Craft fixed launcher changed during uninstall; files were preserved');
122
- }
123
- changes.push({ file: state.launcher.entry, before, after: null });
124
- }
125
- changes.push({ file, before: snapshot.text, after: null });
126
- // Task names include the installation file's hash. Each removal verifies
127
- // scheduler ownership and the hidden helper before touching either.
128
- if (host === 'workbuddy' && process.platform === 'win32' && state.launcher) {
129
- for (const [remove, ensure] of [[removeWorkBuddyLoginTask, ensureWorkBuddyLoginTask], [removeWorkBuddyPreviewTask, ensureWorkBuddyPreviewTask]]) {
130
- const receipt = await remove(file);
131
- if (receipt.status === 'removed') restoreTasks.push(ensure);
132
- tasks.push(receipt);
133
- }
134
- }
135
- const written = await commitFiles(changes);
136
- return { ...result, status: 'uninstalled', ...written, preserved_skills: preserved, ...(tasks.length ? { tasks } : {}) };
137
- } catch (error) {
138
- const failures = [error];
139
- for (const ensure of restoreTasks.reverse()) {
140
- try { await ensure(file); } catch (restoreError) { failures.push(restoreError); }
141
- }
142
- if (failures.length > 1) throw new AggregateError(failures, 'Craft uninstall failed and a WorkBuddy task could not be restored: ' + failures.map(e => e.message).join(', '));
143
- throw error;
144
- } finally {
145
- for (const unlock of locks.reverse()) await unlock();
146
- }
147
- }
148
-
149
- export async function runUninstallCommand([, ...args]) {
150
- const options = {};
151
- for (let i = 0; i < args.length; i += 2) {
152
- const key = args[i], value = args[i + 1];
153
- if (!['--ide', '--instance', '--host-config', '--trae-region'].includes(key) || !value || value.startsWith('--') || Object.hasOwn(options, key.slice(2))) {
154
- throw new Error('Use uninstall --ide <host> [--instance <server-id>] [--host-config ABS] [--trae-region global|cn]');
155
- }
156
- options[key.slice(2)] = value;
157
- }
158
- const result = await uninstallHost({ ide: options.ide, serverId: options.instance, hostOptions: hostCommandOptions(options) });
159
- process.stdout.write(JSON.stringify(result, null, 2) + '\n');
160
- }
1
+ import os from 'node:os';
2
+ import path from 'node:path';
3
+ import { createHash } from 'node:crypto';
4
+ import { readdir } from 'node:fs/promises';
5
+ import lockfile from 'proper-lockfile';
6
+ import { getAppDataRoot } from '../core/app-paths.mjs';
7
+ import { hostCommandOptions, hostEnvironment, hostPaths, installTargets } from './hosts.mjs';
8
+ import { craftConfig, craftRegistrations, removeConfig } from './config.mjs';
9
+ import { assertDshSharedScope } from './dsh-config.mjs';
10
+ import { assertHostConfigScope } from './host-config-scope.mjs';
11
+ import { assertPlainPath, commitFiles, optionalFile } from './files.mjs';
12
+ import { verifyLauncher } from './fixed-launcher.mjs';
13
+ import { validateServerId } from './instance.mjs';
14
+ import { renderInstanceSkill } from './instance-skill.mjs';
15
+ import { installationPath, installedSkillEntries, readInstallationSnapshot, sameRuntimeIdentity } from './installation-state.mjs';
16
+ import { unchangedInstallation } from './installation-transaction.mjs';
17
+ import { getRuntimeIdentity } from './runtime-identity.mjs';
18
+ import { ensureWorkBuddyLoginTask, ensureWorkBuddyPreviewTask, removeWorkBuddyLoginTask, removeWorkBuddyPreviewTask } from './workbuddy-login-task.mjs';
19
+
20
+ const samePath = (left, right) => typeof left === 'string' && path.isAbsolute(left) && path.relative(left, right) === '';
21
+
22
+ // Separate Codex configuration files can share the same user-level Skill root.
23
+ // Unknown state cannot establish exclusive ownership, so preserve the Skill.
24
+ async function sharedSkills(stateRoot, ownFile, entries) {
25
+ const shared = new Set();
26
+ for (const item of await readdir(stateRoot, { withFileTypes: true })) {
27
+ if (!/^[0-9a-f]{24}\.json$/i.test(item.name)) continue;
28
+ const file = path.join(stateRoot, item.name);
29
+ if (samePath(file, ownFile)) continue;
30
+ try {
31
+ await assertPlainPath(file);
32
+ const { state } = await readInstallationSnapshot(file);
33
+ if (!state.skills) return new Set(entries.map(entry => entry.file));
34
+ for (const { file: skill } of installedSkillEntries(state)) {
35
+ for (const entry of entries) if (samePath(skill, entry.file)) shared.add(entry.file);
36
+ }
37
+ } catch {
38
+ for (const entry of entries) shared.add(entry.file);
39
+ }
40
+ }
41
+ return shared;
42
+ }
43
+
44
+ async function verifiedTemplates(state, entries) {
45
+ const expected = new Map();
46
+ if (!entries.length || !state.skills_runtime) return expected;
47
+ const identity = state.skills_runtime;
48
+ try {
49
+ if (!sameRuntimeIdentity(await getRuntimeIdentity(identity.package_root), identity)) return expected;
50
+ for (const { name, marker } of entries) {
51
+ const template = await optionalFile(path.join(identity.package_root, 'resources', name, 'SKILL.md'));
52
+ if (template?.includes(marker)) expected.set(name, renderInstanceSkill(template, name, state.server_id));
53
+ }
54
+ } catch (error) {
55
+ if (error.code !== 'ENOENT') throw error;
56
+ }
57
+ return expected;
58
+ }
59
+
60
+ export async function uninstallHost({ ide, serverId = 'craft', home = os.homedir(), codexHome = process.env.CODEX_HOME,
61
+ hostOptions = hostEnvironment(), runtimeRoot = path.join(getAppDataRoot(), 'runtimes'),
62
+ stateRoot = path.join(path.dirname(runtimeRoot), 'installations') }) {
63
+ validateServerId(serverId);
64
+ const targets = installTargets(ide);
65
+ if (targets.length !== 1) throw new Error('Uninstall requires exactly one host');
66
+ const [host] = targets;
67
+ const paths = hostPaths(home, host, codexHome, { ...hostOptions, serverId });
68
+ const { file, id } = installationPath(stateRoot, host, paths.config, serverId);
69
+ const result = { host, server_id: serverId, config: paths.config, installation: file };
70
+ await assertPlainPath(paths.config);
71
+ await assertPlainPath(file);
72
+ const text = await optionalFile(paths.config);
73
+ const connection = craftConfig(text ?? '', host, serverId);
74
+ if (!connection && await optionalFile(file) === null) return { ...result, status: 'absent', changed: [], preserved_skills: [] };
75
+ if (!samePath(connection?.env?.CRAFT_INSTALLATION_FILE, file) || connection.env.CRAFT_CLIENT_IDE !== host ||
76
+ (connection.env.CRAFT_SERVER_ID ?? 'craft') !== serverId) {
77
+ throw new Error('Registration does not point to the selected managed Craft installation; files were preserved');
78
+ }
79
+ const { state } = await readInstallationSnapshot(file);
80
+ if (state.id !== id || state.server_id !== serverId || state.host !== host || !samePath(state.config, paths.config) ||
81
+ !samePath(state.runtime_root, runtimeRoot)) throw new Error('Installation state does not match the selected Craft instance');
82
+ const entries = installedSkillEntries(state);
83
+ for (const { name, file: skill } of entries) {
84
+ if (!samePath(skill, name === 'craft-create' ? paths.skill : paths.updateSkill)) throw new Error('Recorded Craft Skill is outside the selected installation: ' + skill);
85
+ }
86
+ // Verify the package content identity outside the state/configuration locks.
87
+ const expected = await verifiedTemplates(state, entries);
88
+ const locks = [], restoreTasks = [], tasks = [];
89
+ try {
90
+ for (const target of [paths.config, file].sort()) {
91
+ locks.push(await lockfile.lock(target, { realpath: false, stale: 120000, retries: 0 }));
92
+ }
93
+ locks.push(await lockfile.lock(runtimeRoot, { stale: 120000, retries: 0 }));
94
+ const snapshot = await unchangedInstallation(file, state);
95
+ const original = await optionalFile(paths.config);
96
+ const binding = craftConfig(original ?? '', host, serverId);
97
+ if (!samePath(binding?.env?.CRAFT_INSTALLATION_FILE, file) || binding.env.CRAFT_CLIENT_IDE !== host ||
98
+ (binding.env.CRAFT_SERVER_ID ?? 'craft') !== serverId ||
99
+ craftRegistrations(original, host).some(reg => reg.name !== serverId && samePath(reg.connection?.env?.CRAFT_INSTALLATION_FILE, file))) {
100
+ throw new Error('Craft registration ownership changed or is ambiguous; files were preserved');
101
+ }
102
+ assertDshSharedScope(paths, serverId);
103
+ await assertHostConfigScope(paths.config, host, paths.configPeers, serverId);
104
+ await verifyLauncher(state, file, binding);
105
+ const changes = [{ file: paths.config, before: original, after: removeConfig(original, host, serverId) }];
106
+ const shared = await sharedSkills(stateRoot, file, entries);
107
+ const preserved = [];
108
+ for (const entry of entries) {
109
+ await assertPlainPath(entry.file);
110
+ const before = await optionalFile(entry.file);
111
+ if (before === null) continue;
112
+ if (shared.has(entry.file) || expected.get(entry.name) !== before) {
113
+ preserved.push({ file: entry.file, reason: shared.has(entry.file) ? 'other_installation' : 'modified_or_unverified' });
114
+ } else {
115
+ changes.push({ file: entry.file, before, after: null });
116
+ }
117
+ }
118
+ if (state.launcher) {
119
+ const before = await optionalFile(state.launcher.entry);
120
+ if (before === null || createHash('sha256').update(before).digest('hex') !== state.launcher.sha256) {
121
+ throw new Error('Craft fixed launcher changed during uninstall; files were preserved');
122
+ }
123
+ changes.push({ file: state.launcher.entry, before, after: null });
124
+ }
125
+ changes.push({ file, before: snapshot.text, after: null });
126
+ // Task names include the installation file's hash. Each removal verifies
127
+ // scheduler ownership and the hidden helper before touching either.
128
+ if (host === 'workbuddy' && process.platform === 'win32' && state.launcher) {
129
+ for (const [remove, ensure] of [[removeWorkBuddyLoginTask, ensureWorkBuddyLoginTask], [removeWorkBuddyPreviewTask, ensureWorkBuddyPreviewTask]]) {
130
+ const receipt = await remove(file);
131
+ if (receipt.status === 'removed') restoreTasks.push(ensure);
132
+ tasks.push(receipt);
133
+ }
134
+ }
135
+ const written = await commitFiles(changes);
136
+ return { ...result, status: 'uninstalled', ...written, preserved_skills: preserved, ...(tasks.length ? { tasks } : {}) };
137
+ } catch (error) {
138
+ const failures = [error];
139
+ for (const ensure of restoreTasks.reverse()) {
140
+ try { await ensure(file); } catch (restoreError) { failures.push(restoreError); }
141
+ }
142
+ if (failures.length > 1) throw new AggregateError(failures, 'Craft uninstall failed and a WorkBuddy task could not be restored: ' + failures.map(e => e.message).join(', '));
143
+ throw error;
144
+ } finally {
145
+ for (const unlock of locks.reverse()) await unlock();
146
+ }
147
+ }
148
+
149
+ export async function runUninstallCommand([, ...args]) {
150
+ const options = {};
151
+ for (let i = 0; i < args.length; i += 2) {
152
+ const key = args[i], value = args[i + 1];
153
+ if (!['--ide', '--instance', '--host-config', '--trae-region'].includes(key) || !value || value.startsWith('--') || Object.hasOwn(options, key.slice(2))) {
154
+ throw new Error('Use uninstall --ide <host> [--instance <server-id>] [--host-config ABS] [--trae-region global|cn]');
155
+ }
156
+ options[key.slice(2)] = value;
157
+ }
158
+ const result = await uninstallHost({ ide: options.ide, serverId: options.instance, hostOptions: hostCommandOptions(options) });
159
+ process.stdout.write(JSON.stringify(result, null, 2) + '\n');
160
+ }
@@ -5,6 +5,7 @@ import lockfile from 'proper-lockfile';
5
5
  import { readInstallation, readInstallationSnapshot, activationStatus, registryOrigin, installedSkillEntries, skillRuntimeIdentity, sameRuntimeIdentity, activationMode } from './installation-state.mjs';
6
6
  import { compareVersions, requireForwardVersion, parseVersion } from './version-policy.mjs';
7
7
  import { stageRegistryRuntime, getRuntimeIdentity, probeRuntime } from './runtime.mjs';
8
+ import { readRunningIdentity } from './runtime-identity.mjs';
8
9
  import { optionalFile, assertPlainPath, commitFiles } from './files.mjs';
9
10
  import { hostPaths, hostCommandOptions, installTargets } from './hosts.mjs';
10
11
  import { craftConfig, mergeConfig } from './config.mjs';
@@ -98,19 +99,10 @@ async function confirmationSnapshot(installationFile, current) {
98
99
 
99
100
  export async function confirmActiveInstallation({ installationFile, current }) {
100
101
  if (!current?.instance_id) throw new Error('An actual runtime instance is required to confirm the installation');
101
- // Capture small shared files consistently. Full package hashing never blocks
102
- // installers; a second short transaction detects concurrent scope/target changes.
103
- let unlock = await lockfile.lock(installationFile, shortLock), snapshot;
104
- try { snapshot = await confirmationSnapshot(installationFile, current); }
105
- finally { await unlock(); }
106
- let identity, integrityError;
107
- try { identity = await getRuntimeIdentity(current.package_root); }
108
- catch (error) { integrityError = error; }
109
- unlock = await lockfile.lock(installationFile, shortLock);
102
+ // The server captured its own package identity at startup. Compare that
103
+ // identity to the selected target and commit the receipt under one short lock.
104
+ const unlock = await lockfile.lock(installationFile, shortLock);
110
105
  try {
111
- await unchangedInstallation(installationFile, snapshot.state);
112
- if (integrityError) throw integrityError;
113
- if (!sameRuntimeIdentity(identity, snapshot.state.target)) throw new Error('The running package files do not match the configured update target');
114
106
  const { state, text: before } = await confirmationSnapshot(installationFile, current);
115
107
  const previous = state.connection_verification;
116
108
  const receipt = previous?.instance_id === current.instance_id ? previous : { version: current.version, build_id: current.build_id, instance_id: current.instance_id, confirmed_at: new Date().toISOString() };
@@ -223,7 +215,7 @@ async function checkSnapshot({ installationFile, current, connectedSource, inten
223
215
  let candidate, originalConfig;
224
216
  try {
225
217
  originalConfig = await optionalFile(state.config);
226
- candidate = await prepareRuntimeCandidate(runtimeRoot, stagingRoot => materialize(state.source, remote, stagingRoot));
218
+ candidate = await prepareRuntimeCandidate(runtimeRoot, stagingRoot => materialize(state.source, remote, stagingRoot), { repair:true, deferExisting:true });
227
219
  let identity = candidate.identity;
228
220
  if (!within(runtimeRoot, identity.package_root) || identity.package !== state.source.package || identity.version !== remote.version) throw new Error('Candidate runtime identity/path mismatch');
229
221
  requireForwardVersion(identity, state.target);
@@ -231,9 +223,13 @@ async function checkSnapshot({ installationFile, current, connectedSource, inten
231
223
  try { await projectCompatibility(identity.package_root); }
232
224
  catch (error) { return result(state, current, 'incompatible', { checked_at: checkedAt, remote, message: error.message, can_continue: false }); }
233
225
  }
234
- const verified = await probe({ command: process.execPath, args: [identity.entry, '--workspace', state.workspace], env: { CRAFT_SERVER_ID: state.server_id, CRAFT_CLIENT_IDE: state.host, CRAFT_WEB_URL: state.platform, CLIENT_WORKSPACE_ROOT: state.workspace } },
235
- { version: identity.version, build_id: identity.build_id, serverId: state.server_id, host: state.host, workspace: state.workspace, platform: state.platform });
236
- if (verified.runtime?.activation_mode !== activationMode) throw new Error('Candidate runtime does not support activation at the next MCP start');
226
+ const verifyRuntime = async runtime => {
227
+ const report = await probe({ command: process.execPath, args: [runtime.entry, '--workspace', state.workspace], env: { CRAFT_SERVER_ID: state.server_id, CRAFT_CLIENT_IDE: state.host, CRAFT_WEB_URL: state.platform, CLIENT_WORKSPACE_ROOT: state.workspace } },
228
+ { version: runtime.version, build_id: runtime.build_id, serverId: state.server_id, host: state.host, workspace: state.workspace, platform: state.platform });
229
+ if (report.runtime?.activation_mode !== activationMode) throw new Error('Candidate runtime does not support activation at the next MCP start');
230
+ return report;
231
+ };
232
+ const stagedProbe = await verifyRuntime(identity);
237
233
  if (!sameRuntimeIdentity(await getRuntimeIdentity(identity.package_root), identity)) throw new Error('Candidate runtime changed during startup verification');
238
234
  // Neither registry traffic nor materialization/probing owns a shared lock.
239
235
  // Re-read the authoritative state before publishing; receipt-only writes merge.
@@ -259,6 +255,7 @@ async function checkSnapshot({ installationFile, current, connectedSource, inten
259
255
  return result(state, current, 'pending_reconnect', { checked_at: checkedAt, remote, reconnect_required: true, can_continue: false, verified: { ...verified, scope: 'standalone_probe' } });
260
256
  } finally { try { await unlockRuntime?.(); } finally { for (const release of unlockScope.reverse()) await release(); } }
261
257
  };
258
+ let verified = await refreshRuntimeCandidate(candidate, verifyRuntime) ?? stagedProbe;
262
259
  for (let attempt = 0; ; attempt++) {
263
260
  try { return await commitCandidate(); }
264
261
  catch (error) {
@@ -267,7 +264,7 @@ async function checkSnapshot({ installationFile, current, connectedSource, inten
267
264
  // remains unchanged. Reuse the complete download and revalidate the
268
265
  // existing target outside locks, rather than downloading a second time.
269
266
  await unchangedInstallation(installationFile, state);
270
- if (error.code === 'INSTALLATION_CHANGED') await refreshRuntimeCandidate(candidate);
267
+ if (error.code === 'INSTALLATION_CHANGED') verified = await refreshRuntimeCandidate(candidate, verifyRuntime) ?? stagedProbe;
271
268
  await delay(100 * (attempt + 1));
272
269
  }
273
270
  }
@@ -278,14 +275,14 @@ async function checkSnapshot({ installationFile, current, connectedSource, inten
278
275
  const failure = { checked_at: checkedAt, remote, code: 'candidate_rejected', message: error.message, ...(error.npm_code?{npm_code:error.npm_code}:{}) };
279
276
  try {
280
277
  // A failed candidate must not disable a verified existing installation.
281
- // Recheck the rollback, scope and complete old package before allowing work.
278
+ // Verify rollback, scope and the installed identity of the retained package.
282
279
  if (state.schema !== 2 || activationPending || currentIncompatible) throw new Error(currentIncompatible ?? 'No compatible active installation to retain');
283
280
  await unchangedInstallation(installationFile, state);
284
281
  const retainedConfig = await optionalFile(state.config);
285
282
  if (originalConfig == null || retainedConfig === null || !isDeepStrictEqual(
286
283
  craftConfig(retainedConfig, state.host, state.server_id), craftConfig(originalConfig, state.host, state.server_id)
287
284
  )) throw new Error('Host registration changed; rollback could not be verified');
288
- if (!sameRuntimeIdentity(await getRuntimeIdentity(current.package_root), state.target)) throw new Error('Existing runtime integrity check failed');
285
+ if (!sameRuntimeIdentity(await readRunningIdentity(current.package_root, { managed:true }), state.target)) throw new Error('Existing runtime installation identity check failed');
289
286
  await hostUpdate(state, installationFile, state.launcher ?? { entry: current.entry }, current);
290
287
  if (!state.launcher && path.resolve(craftConfig(originalConfig, state.host, state.server_id).args[0]) !== path.resolve(current.entry)) throw new Error('Existing runtime entry differs from the configured connection');
291
288
  const skills = await candidateSkills(state, current);
@@ -344,7 +341,7 @@ export async function runUpdateCommand(args) {
344
341
  const state = await readInstallation(installationFile);
345
342
  if (state.host !== host || state.server_id !== serverId || path.relative(state.config, paths.config) !== '' || (connection.env.CRAFT_SERVER_ID ?? 'craft') !== serverId) throw new Error('Craft registration does not match the selected installation scope: ' + serverId);
346
343
  await verifyRegisteredScope(connection, state, installationFile);
347
- const current = await getRuntimeIdentity(state.target.package_root);
344
+ const current = await readRunningIdentity(state.target.package_root, { managed:Boolean(state.launcher) });
348
345
  const update = await checkForUpdate({ installationFile, current, intent: command === 'update' ? 'update' : 'inspect', requestKey: 'cli-' + Date.now() });
349
346
  if (update.status === 'installation_busy') {
350
347
  results.push({ host, ...update, scope: 'configured_runtime' });
@@ -1771,9 +1771,7 @@ async function readInstallation(file) {
1771
1771
  import path3 from "node:path";
1772
1772
  import { readFile as readFile2, readdir, lstat as lstat2 } from "node:fs/promises";
1773
1773
  import { createHash } from "node:crypto";
1774
- async function getRuntimeIdentity(packageRoot) {
1775
- packageRoot = path3.resolve(packageRoot);
1776
- const pkg = JSON.parse(await readFile2(path3.join(packageRoot, "package.json"), "utf8"));
1774
+ async function hashRuntimeFiles(packageRoot, files) {
1777
1775
  const hash = createHash("sha256");
1778
1776
  async function visit(relative) {
1779
1777
  const file = path3.join(packageRoot, relative);
@@ -1787,11 +1785,51 @@ async function getRuntimeIdentity(packageRoot) {
1787
1785
  if (info.isSymbolicLink()) throw new Error("Craft runtime contains a linked product file: " + relative);
1788
1786
  if (info.isDirectory()) {
1789
1787
  for (const entry of (await readdir(file)).sort()) if (entry !== "node_modules") await visit(relative + "/" + entry);
1790
- } else if (info.isFile()) hash.update(relative + "\0").update(await readFile2(file)).update("\0");
1791
- else throw new Error("Invalid Craft runtime file: " + relative);
1788
+ } else if (info.isFile()) {
1789
+ const bytes = await readFile2(file);
1790
+ hash.update(relative + "\0").update(bytes).update("\0");
1791
+ if (files) files[relative] = createHash("sha256").update(bytes).digest("hex");
1792
+ } else throw new Error("Invalid Craft runtime file: " + relative);
1792
1793
  }
1793
1794
  for (const relative of ["package.json", "bin", "dist-server", "resources", "vendor"]) await visit(relative);
1794
- return { package: pkg.name, version: pkg.version, build_id: hash.digest("hex"), package_root: packageRoot, entry: path3.join(packageRoot, "bin/craft-mcp.mjs") };
1795
+ return hash.digest("hex");
1796
+ }
1797
+ function identityForPackage(packageRoot, pkg, buildId) {
1798
+ return { package: pkg.name, version: pkg.version, build_id: buildId, package_root: packageRoot, entry: path3.join(packageRoot, "bin/craft-mcp.mjs") };
1799
+ }
1800
+ async function getRuntimeIdentity(packageRoot, { files } = {}) {
1801
+ packageRoot = path3.resolve(packageRoot);
1802
+ const pkg = JSON.parse(await readFile2(path3.join(packageRoot, "package.json"), "utf8"));
1803
+ return identityForPackage(packageRoot, pkg, await hashRuntimeFiles(packageRoot, files));
1804
+ }
1805
+ function runtimeDirectoryForPackage(packageRoot) {
1806
+ const parent = path3.dirname(path3.resolve(packageRoot));
1807
+ const modules = path3.basename(parent).startsWith("@") ? path3.dirname(parent) : parent;
1808
+ return path3.basename(modules) === "node_modules" ? path3.dirname(modules) : null;
1809
+ }
1810
+ async function readRunningIdentity(packageRoot, { managed = false } = {}) {
1811
+ packageRoot = path3.resolve(packageRoot);
1812
+ const directory = runtimeDirectoryForPackage(packageRoot);
1813
+ if (!directory) return getRuntimeIdentity(packageRoot);
1814
+ const receiptFile = path3.join(directory, "craft-runtime.json");
1815
+ await assertPlainPath(receiptFile);
1816
+ const text = await optionalFile(receiptFile);
1817
+ if (text === null) {
1818
+ if (managed) throw new Error("Craft runtime installation receipt is missing; run doctor for the selected instance");
1819
+ return getRuntimeIdentity(packageRoot);
1820
+ }
1821
+ const receipt = JSON.parse(text);
1822
+ const packageFile = path3.join(packageRoot, "package.json");
1823
+ await assertPlainPath(packageFile);
1824
+ const pkg = JSON.parse(await readFile2(packageFile, "utf8"));
1825
+ const name = path3.relative(path3.join(directory, "node_modules"), packageRoot).split(path3.sep).join("/");
1826
+ if (name !== pkg.name || receipt.package !== pkg.name || receipt.version !== pkg.version || !/^[a-f0-9]{64}$/.test(receipt.sha256 ?? "") || receipt.build_id !== void 0 && !/^[a-f0-9]{64}$/.test(receipt.build_id)) {
1827
+ throw new Error("Craft runtime package and installation receipt disagree; run doctor for the selected instance");
1828
+ }
1829
+ const identity = identityForPackage(packageRoot, pkg, receipt.build_id ?? await hashRuntimeFiles(packageRoot));
1830
+ await assertPlainPath(identity.entry);
1831
+ if (!(await lstat2(identity.entry)).isFile()) throw new Error("Craft runtime entry must be a regular file");
1832
+ return identity;
1795
1833
  }
1796
1834
 
1797
1835
  // dist-server/integrations/fixed-launcher.mjs
@@ -1841,8 +1879,8 @@ async function start() {
1841
1879
  const relative = path5.relative(path5.resolve(state.runtime_root), state.target.package_root);
1842
1880
  if (!relative || relative === ".." || relative.startsWith(".." + path5.sep) || path5.isAbsolute(relative)) throw new Error("Craft target is outside the managed runtime root");
1843
1881
  await assertPlainPath(state.target.entry);
1844
- identity = await getRuntimeIdentity(state.target.package_root);
1845
- if (!sameRuntimeIdentity(identity, state.target)) throw new Error("Craft target package integrity mismatch");
1882
+ identity = await readRunningIdentity(state.target.package_root, { managed: true });
1883
+ if (!sameRuntimeIdentity(identity, state.target)) throw new Error("Craft target and installed runtime identity differ; run doctor for the selected instance");
1846
1884
  const leaseRoot = path5.join(state.runtime_root, ".connections");
1847
1885
  await mkdir2(leaseRoot, { recursive: true });
1848
1886
  lease = path5.join(leaseRoot, "launcher-" + randomUUID() + ".json");
@@ -1862,6 +1900,7 @@ async function start() {
1862
1900
  const targetEntry = preview ? path5.join(identity.package_root, "dist-server/preview/workbuddy-preview-task-worker.mjs") : loginPage ? path5.join(identity.package_root, "dist-server/mcp/workbuddy-login-task-worker.mjs") : identity.entry;
1863
1901
  process.argv = [process.execPath, targetEntry, ...loginPage || preview ? [installationFile] : process.argv.slice(2)];
1864
1902
  try {
1903
+ await assertPlainPath(targetEntry);
1865
1904
  await import(pathToFileURL(targetEntry).href);
1866
1905
  } catch (error) {
1867
1906
  await unlink2(lease).catch(() => {