@craft_eco/craft-mcp 0.1.34 → 0.1.35-beta.1

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 (111) hide show
  1. package/README.md +2 -2
  2. package/bin/craft-mcp.mjs +11 -2
  3. package/dist-server/core/http-utils.mjs +11 -0
  4. package/dist-server/game-workflow/asset-formats.mjs +1 -1
  5. package/dist-server/game-workflow/bundle-files.mjs +19 -0
  6. package/dist-server/game-workflow/bundle-template.mjs +5 -0
  7. package/dist-server/game-workflow/context-state.mjs +1 -1
  8. package/dist-server/game-workflow/draft-binding-migration.mjs +73 -0
  9. package/dist-server/game-workflow/draft-uploads.mjs +176 -62
  10. package/dist-server/game-workflow/native-context.mjs +4 -1
  11. package/dist-server/game-workflow/project-bundles.mjs +16 -5
  12. package/dist-server/game-workflow/projects.mjs +4 -0
  13. package/dist-server/game-workflow/template-refresh.mjs +430 -0
  14. package/dist-server/integrations/distribution-targets.mjs +2 -0
  15. package/dist-server/integrations/files.mjs +30 -2
  16. package/dist-server/integrations/fixed-launcher.mjs +4 -4
  17. package/dist-server/integrations/install.mjs +5 -5
  18. package/dist-server/integrations/installation-state.mjs +6 -7
  19. package/dist-server/integrations/launcher-start.mjs +12 -8
  20. package/dist-server/integrations/opencode-config.mjs +1 -1
  21. package/dist-server/integrations/runtime-candidate.mjs +8 -12
  22. package/dist-server/integrations/runtime-gc.mjs +20 -21
  23. package/dist-server/integrations/runtime.mjs +7 -3
  24. package/dist-server/integrations/updates.mjs +64 -27
  25. package/dist-server/launcher.mjs +39 -14
  26. package/dist-server/mcp/login-page.mjs +2 -2
  27. package/dist-server/mcp/server.mjs +9 -11
  28. package/dist-server/mcp/update-session.mjs +3 -2
  29. package/dist-server/upstream/{craft-aigc.mjs → craft-platform.mjs} +40 -115
  30. package/dist-server/upstream/draft-audit.mjs +13 -0
  31. package/dist-server/upstream/draft-transport.mjs +184 -0
  32. package/package.json +4 -3
  33. package/resources/craft-update/SKILL.md +2 -0
  34. package/resources/targets/claude/js/js/bundle.json +15 -9
  35. package/resources/targets/claude/js/target.json +8 -6
  36. package/resources/targets/claude/js3d/js3d/bundle.json +21 -10
  37. package/resources/targets/claude/js3d/target.json +14 -7
  38. package/resources/targets/codebuddy/js/js/bundle.json +15 -9
  39. package/resources/targets/codebuddy/js/target.json +8 -6
  40. package/resources/targets/codebuddy/js3d/js3d/bundle.json +21 -10
  41. package/resources/targets/codebuddy/js3d/target.json +14 -7
  42. package/resources/targets/codex/js/js/bundle.json +15 -9
  43. package/resources/targets/codex/js/target.json +8 -6
  44. package/resources/targets/codex/js3d/js3d/bundle.json +21 -10
  45. package/resources/targets/codex/js3d/target.json +14 -7
  46. package/resources/targets/comate/js/js/bundle.json +15 -9
  47. package/resources/targets/comate/js/target.json +8 -6
  48. package/resources/targets/comate/js3d/js3d/bundle.json +21 -10
  49. package/resources/targets/comate/js3d/target.json +14 -7
  50. package/resources/targets/cursor/js/js/bundle.json +15 -9
  51. package/resources/targets/cursor/js/target.json +8 -6
  52. package/resources/targets/cursor/js3d/js3d/bundle.json +21 -10
  53. package/resources/targets/cursor/js3d/target.json +14 -7
  54. package/resources/targets/dsh/js/js/bundle.json +15 -9
  55. package/resources/targets/dsh/js/target.json +8 -6
  56. package/resources/targets/dsh/js3d/js3d/bundle.json +21 -10
  57. package/resources/targets/dsh/js3d/target.json +14 -7
  58. package/resources/targets/index.json +56 -56
  59. package/resources/targets/kimi/js/js/bundle.json +15 -9
  60. package/resources/targets/kimi/js/target.json +8 -6
  61. package/resources/targets/kimi/js3d/js3d/bundle.json +21 -10
  62. package/resources/targets/kimi/js3d/target.json +14 -7
  63. package/resources/targets/opencode/js/js/bundle.json +15 -9
  64. package/resources/targets/opencode/js/target.json +8 -6
  65. package/resources/targets/opencode/js3d/js3d/bundle.json +21 -10
  66. package/resources/targets/opencode/js3d/target.json +14 -7
  67. package/resources/targets/qoder/js/js/bundle.json +15 -9
  68. package/resources/targets/qoder/js/target.json +8 -6
  69. package/resources/targets/qoder/js3d/js3d/bundle.json +21 -10
  70. package/resources/targets/qoder/js3d/target.json +14 -7
  71. package/resources/targets/qoder-cn/js/js/bundle.json +15 -9
  72. package/resources/targets/qoder-cn/js/target.json +8 -6
  73. package/resources/targets/qoder-cn/js3d/js3d/bundle.json +21 -10
  74. package/resources/targets/qoder-cn/js3d/target.json +14 -7
  75. package/resources/targets/qwen/js/js/bundle.json +15 -9
  76. package/resources/targets/qwen/js/target.json +8 -6
  77. package/resources/targets/qwen/js3d/js3d/bundle.json +21 -10
  78. package/resources/targets/qwen/js3d/target.json +14 -7
  79. package/resources/targets/trae/js/js/bundle.json +15 -9
  80. package/resources/targets/trae/js/target.json +8 -6
  81. package/resources/targets/trae/js3d/js3d/bundle.json +21 -10
  82. package/resources/targets/trae/js3d/target.json +14 -7
  83. package/resources/targets/workbuddy/js/js/bundle.json +15 -9
  84. package/resources/targets/workbuddy/js/target.json +8 -6
  85. package/resources/targets/workbuddy/js3d/js3d/bundle.json +21 -10
  86. package/resources/targets/workbuddy/js3d/target.json +14 -7
  87. package/resources/targets/zcode/js/js/bundle.json +15 -9
  88. package/resources/targets/zcode/js/target.json +8 -6
  89. package/resources/targets/zcode/js3d/js3d/bundle.json +21 -10
  90. package/resources/targets/zcode/js3d/target.json +14 -7
  91. package/resources/templates/js/materialize_paths.json +9 -0
  92. package/resources/templates/js/project/package.json +1 -0
  93. package/resources/templates/js/project/runtime/lightgame/1.1.0/platform/platform-capture-dom.mjs +176 -0
  94. package/resources/templates/js/project/runtime/lightgame/1.1.0/platform/platform.d.mts +5 -1
  95. package/resources/templates/js/project/runtime/lightgame/1.1.0/platform/platform.mjs +87 -3
  96. package/resources/templates/js/project/runtime/lightgame/1.1.0/release.json +3 -2
  97. package/resources/templates/js/project/scripts/refresh-runtime.mjs +50 -0
  98. package/resources/templates/js3d/materialize_paths.json +9 -0
  99. package/resources/templates/js3d/project/package.json +4 -2
  100. package/resources/templates/js3d/project/runtime/lightgame/1.1.0/platform/platform-capture-dom.mjs +176 -0
  101. package/resources/templates/js3d/project/runtime/lightgame/1.1.0/platform/platform.d.mts +5 -1
  102. package/resources/templates/js3d/project/runtime/lightgame/1.1.0/platform/platform.mjs +87 -3
  103. package/resources/templates/js3d/project/runtime/lightgame/1.1.0/release.json +3 -2
  104. package/resources/templates/js3d/project/scripts/refresh-runtime.mjs +50 -0
  105. package/resources/templates/js3d/project/scripts/skill-modules/gameplay-check/check.mjs +331 -0
  106. package/resources/templates/js3d/project/src/game/capability/core.ts +3 -0
  107. package/resources/templates/js3d/project/src/main.ts +23 -6
  108. package/resources/templates/js3d/project/src/skill-modules/gameplay/core/index.d.mts +92 -0
  109. package/resources/templates/js3d/project/src/skill-modules/gameplay/core/index.mjs +375 -0
  110. package/resources/templates/js3d/project/src/skill-modules/gameplay/installed.json +6 -0
  111. package/dist-server/game-workflow/local-context.mjs +0 -64
@@ -9,10 +9,12 @@ import { hosts } from '../integrations/hosts.mjs';
9
9
  import { compareVersions } from '../integrations/version-policy.mjs';
10
10
  import { copyBundleArtPreviews, previewHash } from './art-previews.mjs';
11
11
  import { projectArtPreviewsCurrent, retireArtPreviews } from './project-art-previews.mjs';
12
+ import { inspectManagedTemplatePaths, materializePathsFile, syncManagedTemplateFiles } from './template-refresh.mjs';
12
13
  import { isDeepStrictEqual } from 'node:util';
13
- import { localContextPath } from './local-context.mjs';
14
14
  import { contextLayoutSchema, schema4Hosts, nativeContextPath, nativeFileHashes, inspectNativeContext, materializeNativeContext, preflightNativeContext, recoverNativeContext, recoverLegacyNativeContexts, retireLegacyContext, resolveNativeContext } from './native-context.mjs';
15
15
 
16
+ const legacyLocalContextPath = (host,engine,id)=>`.craft/contexts/${host}/${engine}/${id}`;
17
+
16
18
  export const contextLock = '.craft/context-lock.json';
17
19
  export async function readContextLock(project, engine) {
18
20
  let lock;
@@ -28,7 +30,7 @@ export async function readContextLock(project, engine) {
28
30
  !lock.compatibility || typeof lock.compatibility !== 'object' || Array.isArray(lock.compatibility) ||
29
31
  !lock.contexts || typeof lock.contexts !== 'object' || Array.isArray(lock.contexts) || !Object.keys(lock.contexts).length ||
30
32
  Object.entries(lock.contexts).some(([host,value])=>!Object.hasOwn(hosts,host) || (lock.schema===4 && !schema4Hosts.includes(host)) || !validEntry(value) ||
31
- (value.path !== undefined && value.path !== (lock.schema >= 4 ? nativeContextPath(host,lock.schema) : localContextPath(host,engine,value.bundle_id)))) ||
33
+ (value.path !== undefined && value.path !== (lock.schema >= 4 ? nativeContextPath(host,lock.schema) : legacyLocalContextPath(host,engine,value.bundle_id)))) ||
32
34
  (lock.schema >= 3 && lock.policy !== 'follow-installed') ||
33
35
  (lock.schema >= 4 && (!lock.active_hosts || Array.isArray(lock.active_hosts) || Object.entries(lock.active_hosts).some(([directory,host])=>!Object.hasOwn(hosts,host) || nativeContextPath(host,lock.schema)!==directory || !lock.contexts[host]))))) throw new Error('Invalid project context lock or engine mismatch; restore the project lock from version control');
34
36
  return lock;
@@ -76,7 +78,10 @@ export async function planContextRelease(resources, bundle, lock, project) {
76
78
  // Regular status reads stop at the lock and release index. An explicit disk
77
79
  // check also catches edited peer files or publication interrupted before lock commit.
78
80
  const previews=new Set();
81
+ let templateRefreshPending=false, templateRefreshReason;
79
82
  if(project) {
83
+ const templateCheck=await inspectManagedTemplatePaths(project,bundle);
84
+ if(templateCheck.status!=='valid') {templateRefreshPending=true;templateRefreshReason=templateCheck.reason;}
80
85
  const names=Object.keys(targets);
81
86
  const manifests=await Promise.all(names.map(async name=>{
82
87
  const released=name===host ? bundle : JSON.parse(await readFile(path.join(resources,'targets',name,engine,engine,'bundle.json'),'utf8'));
@@ -102,9 +107,10 @@ export async function planContextRelease(resources, bundle, lock, project) {
102
107
  }
103
108
  }
104
109
  let versionStatus='unknown';
105
- if(lock?.contexts) versionStatus=pendingHosts.length ? 'update_available' : 'matches_installed';
110
+ if(lock?.contexts) versionStatus=(pendingHosts.length || templateRefreshPending) ? 'update_available' : 'matches_installed';
106
111
  if(conflictingHosts.length) versionStatus='requires_newer_runtime';
107
- return {targets,pending_hosts:pendingHosts,conflicting_hosts:conflictingHosts,version_status:versionStatus,previews:[...previews].sort()};
112
+ return {targets,pending_hosts:pendingHosts,conflicting_hosts:conflictingHosts,version_status:versionStatus,previews:[...previews].sort(),
113
+ ...(project ? {template_refresh_pending:templateRefreshPending,...(templateRefreshReason ? {template_refresh_reason:templateRefreshReason} : {})} : {})};
108
114
  }
109
115
 
110
116
  export function assertContextRelease(plan) {
@@ -143,6 +149,9 @@ export class ProjectBundles {
143
149
  const from = name.startsWith(projectPrefix) ? path.join(template,name.slice(projectPrefix.length)) : path.join(resources,name);
144
150
  await cp(from,path.join(staging,name),{dereference:false});
145
151
  }
152
+ if (bundle.template_refresh_paths?.length) {
153
+ await cp(path.join(path.dirname(template),materializePathsFile),path.join(staging,engine,materializePathsFile),{dereference:false});
154
+ }
146
155
  await copyBundleArtPreviews(resources,staging,bundle);
147
156
  await verifyBundle(staging,engine,bundle.id);
148
157
  try { await rename(staging,target); }
@@ -258,6 +267,7 @@ export class ProjectBundles {
258
267
  contexts[host]={bundle_id:peer.bundle.id,source_revision:peer.bundle.source_revision,version:peer.bundle.version,path:peerLocal.relative};
259
268
  installed[host]=peerLocal;
260
269
  }
270
+ const templateSync=await syncManagedTemplateFiles(project,current,guard);
261
271
  const local=installed[this.host];
262
272
  const orderedContexts=Object.fromEntries(Object.entries(contexts).sort(([a],[b])=>a.localeCompare(b)));
263
273
  const lock = {schema:contextLayoutSchema,policy:'follow-installed',engine,compatibility:current.bundle.compatibility,
@@ -282,9 +292,10 @@ export class ProjectBundles {
282
292
  const backup=await retireLegacyContext(project,host,engine,value.bundle_id);
283
293
  if(backup) migrated.push({host,backup});
284
294
  }
285
- const sync = {policy:'follow-installed',location:'project',status:changed || local.materialized ? 'updated' : 'current',
295
+ const sync = {policy:'follow-installed',location:'project',status:changed || local.materialized || templateSync.updated ? 'updated' : 'current',
286
296
  updated_hosts:Object.keys(installed).filter(host=>installed[host].materialized),
287
297
  version:current.bundle.version,bundle_id:current.bundle.id,directory:local.selected.resources,
298
+ ...(templateSync.updated ? {template_refresh:{paths:templateSync.paths,updated_files:templateSync.updated_files,removed_files:templateSync.removed_files,...(templateSync.backup ? {backup:templateSync.backup} : {})}} : {}),
288
299
  ...(existing?.schema===4 ? {layout_migration:{from:4,to:contextLayoutSchema,previous_active_hosts:existing.active_hosts}} : {}),
289
300
  ...(previous && previous.bundle_id !== current.bundle.id ? {previous_bundle_id:previous.bundle_id} : {}),...(local.backup ? {backup:local.backup} : {}),...(migrated.length ? {migrated} : {})};
290
301
  local.selected.context.sync = sync;
@@ -99,6 +99,10 @@ export class Projects {
99
99
  const version_status=release?.version_status??'unknown';
100
100
  const layoutSchema=lock?.schema===4 ? 4 : contextLayoutSchema;
101
101
  const native=installed.host ? await inspectNativeContext(project,this.ide,engine,{full,schema:layoutSchema}) : {integrity:'unchecked'};
102
+ if(full && release?.template_refresh_pending && native.integrity==='valid') {
103
+ native.integrity='modified';
104
+ native.reason=release.template_refresh_reason;
105
+ }
102
106
  let incompatible;
103
107
  try {await checkProjectCompatibility(project,installed.bundle);} catch(error) {incompatible=error.message;}
104
108
  if(full && installed.host && lock?.schema===contextLayoutSchema && version_status==='matches_installed' && native.integrity==='valid') {
@@ -0,0 +1,430 @@
1
+ import path from 'node:path';
2
+ import { chmod, lstat, open, readdir, readFile, realpath, rename, rm, rmdir } from 'node:fs/promises';
3
+ import { createHash, randomUUID } from 'node:crypto';
4
+ import { safeProjectFile } from './asset-import.mjs';
5
+
6
+ const digest = value => createHash('sha256').update(value).digest('hex');
7
+
8
+ export const materializePathsFile = 'materialize_paths.json';
9
+
10
+ // Never let template refresh overwrite user gameplay code, configs, progress,
11
+ // runtime/dependency contracts, or Craft/host metadata directories.
12
+ const FORBIDDEN_ROOTS = new Set([
13
+ 'SPEC', 'src', 'Content', 'configs',
14
+ 'unified_data_control_config.json', 'AGENTS.md', 'package.json', 'game-runtime.json',
15
+ '.git', '.craft', '.agents', '.cursor', '.claude', '.workbuddy', '.codebuddy',
16
+ '.dsh', '.zcode', '.kimi-code', '.trae', '.qoder', '.qoder-cn', '.comate', '.opencode', '.qwen',
17
+ 'node_modules',
18
+ ]);
19
+
20
+ function validateRelativeSegments(entry, raw) {
21
+ if (typeof entry !== 'string' || !entry || entry.includes('\\') || entry.includes('\0') || /[:*?<>"|]/.test(entry)) {
22
+ throw new Error('Invalid template refresh path: ' + raw);
23
+ }
24
+ const segments = entry.split('/');
25
+ if (FORBIDDEN_ROOTS.has(segments[0]) || segments.some(segment =>
26
+ !segment || segment === '.' || segment === '..' ||
27
+ segment === '.git' || segment === '.craft' || segment === '.claude' ||
28
+ segment === 'node_modules' || segment.startsWith('.env')
29
+ )) {
30
+ throw new Error('Forbidden template refresh path: ' + raw);
31
+ }
32
+ return entry;
33
+ }
34
+
35
+ function collapsePaths(entries) {
36
+ const unique = [...new Set(entries)].sort();
37
+ return unique.filter(entry => !unique.some(parent => parent !== entry && entry.startsWith(parent + '/')));
38
+ }
39
+
40
+ export function normalizeProjectRefreshPaths(value) {
41
+ if (value === undefined) return [];
42
+ if (!Array.isArray(value)) throw new Error('template_refresh_paths must be an array');
43
+ return collapsePaths(value.map(entry => validateRelativeSegments(entry, entry)));
44
+ }
45
+
46
+ function normalizeOmitEntries(value) {
47
+ if (value === undefined) return [];
48
+ if (!Array.isArray(value)) throw new Error('materialize_paths.json omit must be an array');
49
+ return value.map(entry => {
50
+ if (typeof entry !== 'string' || !entry || entry.includes('\\') || entry.includes('\0') || /[:*?<>"|]/.test(entry)) {
51
+ throw new Error('Invalid materialize_paths.json omit path');
52
+ }
53
+ const segments = entry.split('/');
54
+ if (segments.length < 2 || !['.agents', 'project'].includes(segments[0]) || segments.some(s => !s || s === '.' || s === '..')) {
55
+ throw new Error('Invalid materialize_paths.json omit path: ' + entry);
56
+ }
57
+ return entry;
58
+ });
59
+ }
60
+
61
+ export function parseMaterializePaths(raw, expectedEngine) {
62
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
63
+ throw new Error('Invalid materialize_paths.json: expected a JSON object');
64
+ }
65
+ if (expectedEngine && raw.engine !== expectedEngine) {
66
+ throw new Error('materialize_paths.json engine mismatch: expected ' + expectedEngine);
67
+ }
68
+ const omit = normalizeOmitEntries(raw.omit);
69
+ if (raw.refresh !== undefined && !Array.isArray(raw.refresh)) {
70
+ throw new Error('materialize_paths.json refresh must be an array');
71
+ }
72
+ const refresh = [];
73
+ for (const entry of raw.refresh ?? []) {
74
+ if (typeof entry !== 'string' || !entry.startsWith('project/')) {
75
+ throw new Error('materialize_paths.json refresh entry must start with project/: ' + entry);
76
+ }
77
+ if (omit.some(omitted => entry === omitted || entry.startsWith(omitted + '/'))) {
78
+ throw new Error('materialize_paths.json refresh entry conflicts with omit: ' + entry);
79
+ }
80
+ refresh.push(validateRelativeSegments(entry.slice('project/'.length), entry));
81
+ }
82
+ return collapsePaths(refresh);
83
+ }
84
+
85
+ export async function readTemplateRefreshPaths(templateDir, expectedEngine) {
86
+ const file = path.join(path.dirname(templateDir), materializePathsFile);
87
+ let stat;
88
+ try { stat = await lstat(file); }
89
+ catch (error) {
90
+ if (error.code === 'ENOENT') return [];
91
+ throw error;
92
+ }
93
+ if (stat.isSymbolicLink() || !stat.isFile()) {
94
+ throw new Error('materialize_paths.json must be a regular file');
95
+ }
96
+ const raw = JSON.parse(await readFile(file, 'utf8'));
97
+ return parseMaterializePaths(raw, expectedEngine);
98
+ }
99
+
100
+ export function isProjectRefreshPath(relativePath, refreshPaths) {
101
+ return refreshPaths.some(entry => relativePath === entry || relativePath.startsWith(entry + '/'));
102
+ }
103
+
104
+ export function managedTemplateFileHashes(bundle) {
105
+ const refreshPaths = normalizeProjectRefreshPaths(bundle?.template_refresh_paths);
106
+ if (!refreshPaths.length) return {};
107
+ const prefix = bundle.engine + '/project/';
108
+ const result = {};
109
+ for (const [name, hash] of Object.entries(bundle.files ?? {})) {
110
+ if (!name.startsWith(prefix)) continue;
111
+ const relative = name.slice(prefix.length);
112
+ if (isProjectRefreshPath(relative, refreshPaths)) result[relative] = hash;
113
+ }
114
+ return result;
115
+ }
116
+
117
+ async function statOptional(file) {
118
+ try { return await lstat(file); }
119
+ catch (error) {
120
+ if (error.code === 'ENOENT') return null;
121
+ throw error;
122
+ }
123
+ }
124
+
125
+ async function resolveSafeProjectEntry(project, relative) {
126
+ const root = await realpath(project);
127
+ if (root !== project) throw new Error('Project path changed');
128
+ const pieces = relative.split('/');
129
+ if (pieces.some(p => !p || p === '.' || p === '..' || p.includes('\\'))) {
130
+ throw new Error('Invalid project-relative path: ' + relative);
131
+ }
132
+ let current = root;
133
+ for (let i = 0; i < pieces.length; i++) {
134
+ current = path.join(current, pieces[i]);
135
+ const stat = await statOptional(current);
136
+ if (!stat) return { target: path.join(root, ...pieces), stat: null };
137
+ if (stat.isSymbolicLink()) {
138
+ throw new Error('Managed template path contains a symbolic link: ' + relative);
139
+ }
140
+ if (i < pieces.length - 1) {
141
+ if (!stat.isDirectory()) {
142
+ return { target: path.join(root, ...pieces), stat: null, blockedByFile: pieces.slice(0, i + 1).join('/') };
143
+ }
144
+ } else {
145
+ if (!stat.isFile() && !stat.isDirectory()) {
146
+ throw new Error('Managed template path contains an unsupported entry: ' + relative);
147
+ }
148
+ return { target: current, stat };
149
+ }
150
+ }
151
+ return { target: current, stat: null };
152
+ }
153
+
154
+ async function scanSubtree(rootDir, baseRelative) {
155
+ const files = {};
156
+ const dirs = [];
157
+ async function walk(currentDir, relative) {
158
+ const entries = (await readdir(currentDir, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name));
159
+ for (const entry of entries) {
160
+ const full = path.join(currentDir, entry.name);
161
+ const childRelative = relative + '/' + entry.name;
162
+ if (entry.isSymbolicLink()) throw new Error('Managed template path contains a symbolic link: ' + childRelative);
163
+ if (entry.isDirectory()) {
164
+ dirs.push(childRelative);
165
+ await walk(full, childRelative);
166
+ } else if (entry.isFile()) {
167
+ files[childRelative] = digest(await readFile(full));
168
+ } else {
169
+ throw new Error('Managed template path contains an unsupported entry: ' + childRelative);
170
+ }
171
+ }
172
+ }
173
+ await walk(rootDir, baseRelative);
174
+ return { files, dirs };
175
+ }
176
+
177
+ export async function inspectManagedTemplatePaths(project, bundle) {
178
+ const refreshPaths = normalizeProjectRefreshPaths(bundle?.template_refresh_paths);
179
+ if (!refreshPaths.length) return { status: 'valid', paths: [] };
180
+ const expected = managedTemplateFileHashes(bundle);
181
+ for (const entry of refreshPaths) {
182
+ const { target, stat, blockedByFile } = await resolveSafeProjectEntry(project, entry);
183
+ if (blockedByFile) return { status: 'modified', reason: blockedByFile, paths: refreshPaths };
184
+ const isFileEntry = Object.hasOwn(expected, entry);
185
+ if (isFileEntry) {
186
+ if (!stat) return { status: 'modified', reason: entry, paths: refreshPaths };
187
+ if (!stat.isFile()) return { status: 'modified', reason: entry, paths: refreshPaths };
188
+ if (digest(await readFile(target)) !== expected[entry]) {
189
+ return { status: 'modified', reason: entry, paths: refreshPaths };
190
+ }
191
+ continue;
192
+ }
193
+ const prefix = entry + '/';
194
+ const expectedSubtree = Object.fromEntries(
195
+ Object.entries(expected).filter(([name]) => name.startsWith(prefix)).sort(([a], [b]) => a.localeCompare(b))
196
+ );
197
+ if (!Object.keys(expectedSubtree).length) continue;
198
+ if (!stat) return { status: 'modified', reason: entry, paths: refreshPaths };
199
+ if (!stat.isDirectory()) return { status: 'modified', reason: entry, paths: refreshPaths };
200
+ const { files: actual, dirs } = await scanSubtree(target, entry);
201
+ const allNames = new Set([...Object.keys(expectedSubtree), ...Object.keys(actual)]);
202
+ for (const name of [...allNames].sort()) {
203
+ if (actual[name] !== expectedSubtree[name]) {
204
+ return { status: 'modified', reason: name, paths: refreshPaths };
205
+ }
206
+ }
207
+ for (const dir of dirs) {
208
+ if (!Object.keys(expectedSubtree).some(name => name.startsWith(dir + '/'))) {
209
+ return { status: 'modified', reason: dir, paths: refreshPaths };
210
+ }
211
+ }
212
+ }
213
+ return { status: 'valid', paths: refreshPaths };
214
+ }
215
+
216
+ async function ensureWritableDir(dir) {
217
+ const stat = await statOptional(dir);
218
+ if (stat?.isDirectory() && !stat.isSymbolicLink() && (stat.mode & 0o200) === 0) {
219
+ await chmod(dir, stat.mode | 0o700);
220
+ }
221
+ }
222
+
223
+ async function ensureWritableParents(project, relative) {
224
+ const parts = relative.split('/').slice(0, -1);
225
+ let current = project;
226
+ for (const part of parts) {
227
+ current = path.join(current, part);
228
+ await ensureWritableDir(current);
229
+ }
230
+ }
231
+
232
+ async function ensureWritableTree(target) {
233
+ const stat = await statOptional(target);
234
+ if (!stat || stat.isSymbolicLink()) return;
235
+ if (stat.isDirectory()) {
236
+ if ((stat.mode & 0o700) !== 0o700) await chmod(target, stat.mode | 0o700);
237
+ for (const name of await readdir(target)) {
238
+ await ensureWritableTree(path.join(target, name));
239
+ }
240
+ } else if (stat.isFile() && (stat.mode & 0o200) === 0) {
241
+ await chmod(target, stat.mode | 0o600);
242
+ }
243
+ }
244
+
245
+ async function writeAtomicFile(destination, bytes, token, guard) {
246
+ const temporary = destination + '.craft-' + token + '.tmp';
247
+ const handle = await open(temporary, 'wx');
248
+ try {
249
+ await handle.writeFile(bytes);
250
+ await handle.sync();
251
+ } catch (error) {
252
+ await handle.close();
253
+ await rm(temporary, { force: true });
254
+ throw error;
255
+ }
256
+ await handle.close();
257
+ try {
258
+ await guard();
259
+ const existing = await statOptional(destination);
260
+ if (existing?.isFile() && (existing.mode & 0o200) === 0) {
261
+ await chmod(destination, existing.mode | 0o600);
262
+ }
263
+ await rename(temporary, destination);
264
+ } finally {
265
+ await rm(temporary, { force: true });
266
+ }
267
+ }
268
+
269
+ export async function syncManagedTemplateFiles(project, current, guard = async () => {}) {
270
+ const refreshPaths = normalizeProjectRefreshPaths(current?.bundle?.template_refresh_paths);
271
+ if (!refreshPaths.length) {
272
+ return { updated: false, paths: [], updated_files: [], removed_files: [], backup: null };
273
+ }
274
+ if (!current.template) {
275
+ throw new Error('Template source is unavailable for managed template synchronization');
276
+ }
277
+ const expected = managedTemplateFileHashes(current.bundle);
278
+ const actualFiles = {};
279
+ const existingDirs = new Map();
280
+ const typeConflicts = new Set();
281
+
282
+ for (const entry of refreshPaths) {
283
+ const { target, stat, blockedByFile } = await resolveSafeProjectEntry(project, entry);
284
+ if (blockedByFile) {
285
+ throw new Error('Managed template parent path is a file instead of a directory: ' + blockedByFile);
286
+ }
287
+ const isFileEntry = Object.hasOwn(expected, entry);
288
+ if (!stat) continue;
289
+ if (isFileEntry) {
290
+ if (stat.isFile()) {
291
+ actualFiles[entry] = digest(await readFile(target));
292
+ } else if (stat.isDirectory()) {
293
+ typeConflicts.add(entry);
294
+ const { files } = await scanSubtree(target, entry);
295
+ Object.assign(actualFiles, files);
296
+ }
297
+ continue;
298
+ }
299
+ if (stat.isDirectory()) {
300
+ const { files, dirs } = await scanSubtree(target, entry);
301
+ Object.assign(actualFiles, files);
302
+ existingDirs.set(entry, dirs);
303
+ } else if (stat.isFile()) {
304
+ typeConflicts.add(entry);
305
+ actualFiles[entry] = digest(await readFile(target));
306
+ }
307
+ }
308
+
309
+ const toWrite = Object.keys(expected)
310
+ .filter(name => typeConflicts.has(name) || actualFiles[name] !== expected[name])
311
+ .sort();
312
+ const toRemove = Object.keys(actualFiles)
313
+ .filter(name => !Object.hasOwn(expected, name))
314
+ .sort();
315
+ const staleDirs = [...existingDirs.values()].flat()
316
+ .filter(dir => !Object.keys(expected).some(name => name.startsWith(dir + '/')));
317
+
318
+ if (!toWrite.length && !toRemove.length && !typeConflicts.size && !staleDirs.length) {
319
+ return { updated: false, paths: refreshPaths, updated_files: [], removed_files: [], backup: null };
320
+ }
321
+
322
+ // Verify every template source file against the bundle digest before mutating the project.
323
+ const payload = new Map();
324
+ for (const name of toWrite) {
325
+ const sourceFile = path.join(current.template, ...name.split('/'));
326
+ const stat = await lstat(sourceFile);
327
+ if (stat.isSymbolicLink() || !stat.isFile()) {
328
+ throw new Error('Template source is not a regular file: ' + name);
329
+ }
330
+ const bytes = await readFile(sourceFile);
331
+ if (digest(bytes) !== expected[name]) {
332
+ throw new Error('Template source integrity check failed: ' + name);
333
+ }
334
+ payload.set(name, bytes);
335
+ }
336
+
337
+ // Back up every overwritten or removed file before changing the project tree.
338
+ const token = randomUUID();
339
+ const filesToBackup = [...new Set([
340
+ ...toWrite.filter(name => Object.hasOwn(actualFiles, name)),
341
+ ...toRemove,
342
+ ])].sort();
343
+ let backupRoot = null;
344
+ if (filesToBackup.length) {
345
+ backupRoot = '.craft/context-backups/template/' + token;
346
+ for (const name of filesToBackup) {
347
+ await guard();
348
+ const source = await safeProjectFile(project, name);
349
+ const originalBytes = await readFile(source);
350
+ if (digest(originalBytes) !== actualFiles[name]) {
351
+ throw new Error('Project file changed during managed template backup: ' + name);
352
+ }
353
+ const backupDestination = await safeProjectFile(project, backupRoot + '/' + name, true);
354
+ await writeAtomicFile(backupDestination, originalBytes, token, guard);
355
+ if (digest(await readFile(backupDestination)) !== actualFiles[name]) {
356
+ throw new Error('Managed template backup integrity failed: ' + name);
357
+ }
358
+ }
359
+ }
360
+
361
+ // Clear any file-vs-directory type conflicts at managed roots after backup.
362
+ for (const conflict of typeConflicts) {
363
+ await guard();
364
+ await ensureWritableParents(project, conflict);
365
+ const { target } = await resolveSafeProjectEntry(project, conflict);
366
+ await ensureWritableTree(target);
367
+ await rm(target, { recursive: true, force: true });
368
+ }
369
+
370
+ // Ensure existing managed directories are writable (e.g. projects migrated from read-only Web sandboxes).
371
+ for (const entry of refreshPaths) {
372
+ const { target } = await resolveSafeProjectEntry(project, entry);
373
+ await ensureWritableParents(project, entry);
374
+ await ensureWritableTree(target);
375
+ }
376
+
377
+ // Remove retired files inside managed subtrees before writing, so file-to-dir
378
+ // transitions (e.g. a stray file blocking a new directory) resolve cleanly.
379
+ for (const name of toRemove) {
380
+ if (typeConflicts.has(name)) continue;
381
+ await guard();
382
+ const { target: destination, stat: existing } = await resolveSafeProjectEntry(project, name);
383
+ if (!existing) continue;
384
+ if (existing.isFile() && (existing.mode & 0o200) === 0) {
385
+ await chmod(destination, existing.mode | 0o600);
386
+ }
387
+ await rm(destination, { force: true });
388
+ }
389
+
390
+ // Write updated and missing managed template files with normal writable permissions.
391
+ for (const name of toWrite) {
392
+ await guard();
393
+ await ensureWritableParents(project, name);
394
+ const { target: preExistingTarget, stat: preExisting } = await resolveSafeProjectEntry(project, name);
395
+ if (preExisting?.isDirectory()) {
396
+ await ensureWritableTree(preExistingTarget);
397
+ await rm(preExistingTarget, { recursive: true, force: true });
398
+ }
399
+ const destination = await safeProjectFile(project, name, true);
400
+ await writeAtomicFile(destination, payload.get(name), token, guard);
401
+ }
402
+
403
+ // Prune empty obsolete subdirectories inside managed subtrees (deepest first).
404
+ for (const [entry, dirs] of existingDirs) {
405
+ const sorted = [...dirs].sort((a, b) => b.split('/').length - a.split('/').length || b.localeCompare(a));
406
+ for (const dir of sorted) {
407
+ const hasExpectedChild = Object.keys(expected).some(name => name.startsWith(dir + '/'));
408
+ if (hasExpectedChild) continue;
409
+ const { target: full, stat: existing } = await resolveSafeProjectEntry(project, dir);
410
+ if (existing?.isDirectory()) {
411
+ try { await rmdir(full); }
412
+ catch (error) { if (!['ENOTEMPTY', 'ENOENT'].includes(error.code)) throw error; }
413
+ }
414
+ }
415
+ void entry;
416
+ }
417
+
418
+ const verified = await inspectManagedTemplatePaths(project, current.bundle);
419
+ if (verified.status !== 'valid') {
420
+ throw new Error('Managed template synchronization integrity failed: ' + (verified.reason ?? 'unknown'));
421
+ }
422
+
423
+ return {
424
+ updated: true,
425
+ paths: refreshPaths,
426
+ updated_files: toWrite,
427
+ removed_files: toRemove,
428
+ backup: backupRoot ? path.join(project, backupRoot) : null,
429
+ };
430
+ }
@@ -3,6 +3,8 @@ export const distributionTargets = Object.freeze({
3
3
  internal: Object.freeze({ package: '@tencent/craft-mcp', registry: 'https://mirrors.tencent.com/npm/' }),
4
4
  });
5
5
 
6
+ export const publicReleaseTags = Object.freeze(['stable', 'beta']);
7
+
6
8
  // A project's @tencent:registry setting takes precedence over npx --registry.
7
9
  export function internalRegistryArgs(packageName) {
8
10
  return packageName === distributionTargets.internal.package ? ['--@tencent:registry=' + distributionTargets.internal.registry] : [];
@@ -2,17 +2,45 @@ import path from 'node:path';
2
2
  import { lstat, readFile, mkdir, writeFile, rename, unlink } from 'node:fs/promises';
3
3
  import { randomUUID } from 'node:crypto';
4
4
 
5
+ // Compare the ordinary and extended spellings of drive and UNC paths.
6
+ // Verbatim-only names (e.g. a trailing dot) may denote different files.
7
+ export function resolveFilePath(file) {
8
+ if (process.platform === 'win32' && file.startsWith('\\\\?\\')) {
9
+ const body = file.slice(4);
10
+ const drive = /^[a-z]:\\/i.test(body);
11
+ const unc = /^UNC\\[^\\]+\\[^\\]+(?:\\|$)/i.test(body);
12
+ if (drive || unc) {
13
+ const parts = body.slice(drive ? 3 : 4).split('\\');
14
+ const verbatimOnly = parts.some(part => /[ .]$|[<>:"/|?*\x00-\x1f]|^(?:CON|PRN|AUX|NUL|CONIN\$|CONOUT\$|COM[1-9¹²³]|LPT[1-9¹²³])(?:\.|$)/i.test(part));
15
+ if (!verbatimOnly) return path.resolve(drive ? body : '\\\\' + body.slice(4));
16
+ }
17
+ }
18
+ return path.resolve(file);
19
+ }
20
+
21
+ export function sameFilePath(a, b) {
22
+ if (typeof a !== 'string' || typeof b !== 'string') return false;
23
+ const left = resolveFilePath(a), right = resolveFilePath(b);
24
+ return process.platform === 'win32' ? left.toLowerCase() === right.toLowerCase() : left === right;
25
+ }
26
+
27
+ export function isPathInside(root, file) {
28
+ const relative = path.relative(resolveFilePath(root), resolveFilePath(file));
29
+ return relative !== '' && relative !== '..' && !relative.startsWith('..' + path.sep) && !path.isAbsolute(relative);
30
+ }
31
+
5
32
  export async function optionalFile(file) {
6
33
  try { return await readFile(file, 'utf8'); }
7
34
  catch (error) { if (error.code !== 'ENOENT') throw error; return null; }
8
35
  }
9
36
 
10
37
  export async function assertPlainPath(file) {
11
- let current = path.resolve(file);
38
+ const target = resolveFilePath(file);
39
+ let current = target;
12
40
  for (;;) {
13
41
  try {
14
42
  const info = await lstat(current);
15
- if (info.isSymbolicLink() || (current === path.resolve(file) ? !info.isFile() : !info.isDirectory())) throw new Error('Refusing linked or invalid install path: ' + current);
43
+ if (info.isSymbolicLink() || (current === target ? !info.isFile() : !info.isDirectory())) throw new Error('Refusing linked or invalid install path: ' + current);
16
44
  } catch (error) { if (error.code !== 'ENOENT') throw error; }
17
45
  const parent = path.dirname(current); if (parent === current) break; current = parent;
18
46
  }
@@ -1,7 +1,7 @@
1
1
  import path from 'node:path';
2
2
  import { readFile } from 'node:fs/promises';
3
3
  import { createHash } from 'node:crypto';
4
- import { optionalFile, assertPlainPath } from './files.mjs';
4
+ import { optionalFile, assertPlainPath, sameFilePath } from './files.mjs';
5
5
 
6
6
  export function launcherPath(installationFile) {
7
7
  return installationFile.replace(/\.json$/, '') + '.launcher.mjs';
@@ -11,7 +11,7 @@ export async function planLauncher(installationFile, previous, packageRoot) {
11
11
  const entry = launcherPath(installationFile);
12
12
  await assertPlainPath(entry);
13
13
  const before = await optionalFile(entry);
14
- if (before !== null && (!previous || previous.entry !== entry || createHash('sha256').update(before).digest('hex') !== previous.sha256)) {
14
+ if (before !== null && (!path.isAbsolute(previous?.entry ?? '') || !sameFilePath(previous.entry, entry) || createHash('sha256').update(before).digest('hex') !== previous.sha256)) {
15
15
  throw new Error('Craft launcher ownership or integrity mismatch; preserve the file and repair the installation');
16
16
  }
17
17
  const source = packageRoot ? path.join(packageRoot, 'dist-server/launcher.mjs') : new URL('../launcher.mjs', import.meta.url);
@@ -23,10 +23,10 @@ export async function verifyLauncher(state, installationFile, connection) {
23
23
  if (connection?.env && (connection.env.CRAFT_SERVER_ID ?? 'craft') !== state.server_id) throw new Error('Craft launcher instance differs from its registration');
24
24
  if (!state.launcher) return { mode: 'legacy_versioned_entry' };
25
25
  const expected = launcherPath(installationFile);
26
- if (state.launcher.schema !== 1 || state.launcher.entry !== expected || !/^[a-f0-9]{64}$/.test(state.launcher.sha256 ?? '')) throw new Error('Invalid Craft fixed launcher identity');
26
+ if (state.launcher.schema !== 1 || !path.isAbsolute(state.launcher.entry ?? '') || !sameFilePath(state.launcher.entry, expected) || !/^[a-f0-9]{64}$/.test(state.launcher.sha256 ?? '')) throw new Error('Invalid Craft fixed launcher identity');
27
27
  if (state.launcher.kind !== undefined) throw new Error('Unsupported Craft launcher; run the standard installer and reconnect');
28
28
  await assertPlainPath(expected);
29
29
  if (createHash('sha256').update(await readFile(expected)).digest('hex') !== state.launcher.sha256) throw new Error('Craft fixed launcher integrity mismatch');
30
- if (connection && path.resolve(connection.args?.[0] ?? '') !== path.resolve(expected)) throw new Error('Craft host configuration does not use the installed fixed launcher');
30
+ if (connection && !sameFilePath(connection.args?.[0], expected)) throw new Error('Craft host configuration does not use the installed fixed launcher');
31
31
  return { mode: 'fixed_entry', entry: expected };
32
32
  }
@@ -6,7 +6,7 @@ import { defaultProfileDataDir, getAppDataRoot } from '../core/app-paths.mjs';
6
6
  import { hostPaths, hostCommandOptions, installTargets } from './hosts.mjs';
7
7
  import { craftConfig, craftRegistrations, mergeConfig, importZcodeFallback } from './config.mjs';
8
8
  import { assertDshSharedScope } from './dsh-config.mjs';
9
- import { optionalFile, assertPlainPath, commitFiles } from './files.mjs';
9
+ import { optionalFile, assertPlainPath, commitFiles, sameFilePath, resolveFilePath } from './files.mjs';
10
10
  import { stageRuntime, stageRegistryRuntime, probeRuntime, getRuntimeIdentity } from './runtime.mjs';
11
11
  import { installationPath, readInstallation, readInstallationSnapshot, registryOrigin, installedSkillEntries, skillRuntimeIdentity, sameRuntimeIdentity, activationMode } from './installation-state.mjs';
12
12
  import { queryRegistry } from './updates.mjs';
@@ -144,7 +144,7 @@ export async function installHosts({ ide, workspace, platform, packageRoot, home
144
144
  const statePath = installationPath(stateRoot, host, paths.config, instance);
145
145
  const previousSnapshot = old?.env?.CRAFT_INSTALLATION_FILE ? await readInstallationSnapshot(old.env.CRAFT_INSTALLATION_FILE) : null;
146
146
  const previousState = previousSnapshot?.state;
147
- if (repair && (previousState?.schema !== 2 || path.relative(runtimeRoot, previousState.runtime_root) !== '')) {
147
+ if (repair && (previousState?.schema !== 2 || !sameFilePath(runtimeRoot, previousState.runtime_root))) {
148
148
  throw new Error('Repair requires the selected managed Craft installation and its original runtime root.');
149
149
  }
150
150
  if (previousState) checkInstanceBinding(previousState, host, paths, instance, old.env.CRAFT_INSTALLATION_FILE);
@@ -219,7 +219,7 @@ export async function installHosts({ ide, workspace, platform, packageRoot, home
219
219
  if (registryOrigin(target.origin.registry) !== plan.source.registry || !target.origin.integrity) throw new Error('Recorded Craft repair source or integrity is inconsistent');
220
220
  remote = { package: target.package, version: target.version, integrity: target.origin.integrity };
221
221
  } else if (selector !== 'package' || pkg.version !== target.version) {
222
- remote = await lookup({ ...plan.source, channel: target.version });
222
+ remote = await lookup(plan.source, { version: target.version });
223
223
  if (remote.package !== target.package || remote.version !== target.version || !remote.integrity) {
224
224
  throw new Error('Could not resolve the exact Craft version for repair; use the original installation package.');
225
225
  }
@@ -301,13 +301,13 @@ export async function installHosts({ ide, workspace, platform, packageRoot, home
301
301
  });
302
302
  if (verifiedExisting) for (const [host, result] of verifiedExisting) verifiedByHost.set(host, result);
303
303
  }
304
- const lockPaths = [...new Set(plans.flatMap(plan => [plan.paths.config, plan.statePath.file, craftConfig(plan.configInput, plan.host, plan.previousName)?.env?.CRAFT_INSTALLATION_FILE].filter(Boolean)).map(file => path.resolve(file)))].sort();
304
+ const lockPaths = [...new Set(plans.flatMap(plan => [plan.paths.config, plan.statePath.file, craftConfig(plan.configInput, plan.host, plan.previousName)?.env?.CRAFT_INSTALLATION_FILE].filter(Boolean)).map(resolveFilePath))].sort();
305
305
  for (const file of lockPaths) {
306
306
  await assertPlainPath(file); await mkdir(path.dirname(file), { recursive: true });
307
307
  stateLocks.push(await lockfile.lock(file, { realpath: false, stale: 120000, retries: 0 }));
308
308
  }
309
309
  // Never hold installation-state locks while waiting on launcher or GC.
310
- release = await lockfile.lock(runtimeRoot, { stale: 120000, retries: 0 });
310
+ release = await lockfile.lock(resolveFilePath(runtimeRoot), { stale: 120000, retries: 0 });
311
311
  await verifyPlans(plans);
312
312
  const published = new Map(), changes = [], results = [];
313
313
  for (const plan of plans) {