@craft_eco/craft-mcp 0.1.5 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/README.md +8 -8
  2. package/bin/craft-mcp.mjs +28 -2
  3. package/dist-server/engines/unreal/artifacts.mjs +7 -3
  4. package/dist-server/engines/unreal/check.mjs +56 -7
  5. package/dist-server/engines/unreal/export.mjs +3 -3
  6. package/dist-server/engines/unreal/external-environment.mjs +7 -1
  7. package/dist-server/engines/unreal/preview-project.mjs +2 -2
  8. package/dist-server/engines/unreal/project.mjs +44 -12
  9. package/dist-server/game-workflow/project-context.mjs +7 -6
  10. package/dist-server/game-workflow/project-install.mjs +2 -1
  11. package/dist-server/integrations/config.mjs +41 -18
  12. package/dist-server/integrations/connect.mjs +18 -9
  13. package/dist-server/integrations/connection-handoff.mjs +9 -8
  14. package/dist-server/integrations/dsh-config.mjs +30 -14
  15. package/dist-server/integrations/files.mjs +3 -1
  16. package/dist-server/integrations/fixed-launcher.mjs +1 -0
  17. package/dist-server/integrations/host-config-scope.mjs +4 -3
  18. package/dist-server/integrations/hosts.mjs +3 -1
  19. package/dist-server/integrations/install-source.mjs +44 -0
  20. package/dist-server/integrations/install.mjs +183 -53
  21. package/dist-server/integrations/installation-state.mjs +2 -1
  22. package/dist-server/integrations/instance-skill.mjs +26 -0
  23. package/dist-server/integrations/instance.mjs +29 -0
  24. package/dist-server/integrations/launcher-start.mjs +1 -1
  25. package/dist-server/integrations/login-task-command.mjs +3 -3
  26. package/dist-server/integrations/opencode-config.mjs +13 -6
  27. package/dist-server/integrations/project-setup.mjs +46 -18
  28. package/dist-server/integrations/runtime.mjs +2 -1
  29. package/dist-server/integrations/uninstall.mjs +160 -0
  30. package/dist-server/integrations/updates.mjs +57 -28
  31. package/dist-server/launcher.mjs +18 -2
  32. package/dist-server/mcp/server.mjs +19 -10
  33. package/dist-server/mcp/update-session.mjs +34 -12
  34. package/dist-server/upstream/craft-aigc.mjs +11 -2
  35. package/dist-server/upstream/draft-audit.mjs +52 -6
  36. package/package.json +4 -3
  37. package/resources/craft-create/SKILL.md +2 -0
  38. package/resources/craft-update/SKILL.md +2 -0
  39. package/resources/targets/claude/unreal/target.json +6 -6
  40. package/resources/targets/claude/unreal/unreal/bundle.json +10 -10
  41. package/resources/targets/claude/unreal/unreal/context/web/knowledge/WebBuild.md +6 -6
  42. package/resources/targets/codebuddy/unreal/target.json +6 -6
  43. package/resources/targets/codebuddy/unreal/unreal/bundle.json +10 -10
  44. package/resources/targets/codebuddy/unreal/unreal/context/web/knowledge/WebBuild.md +9 -7
  45. package/resources/targets/codex/unreal/target.json +6 -6
  46. package/resources/targets/codex/unreal/unreal/bundle.json +10 -10
  47. package/resources/targets/codex/unreal/unreal/context/web/knowledge/WebBuild.md +9 -7
  48. package/resources/targets/comate/unreal/target.json +6 -6
  49. package/resources/targets/comate/unreal/unreal/bundle.json +10 -10
  50. package/resources/targets/comate/unreal/unreal/context/web/knowledge/WebBuild.md +6 -6
  51. package/resources/targets/cursor/unreal/target.json +6 -6
  52. package/resources/targets/cursor/unreal/unreal/bundle.json +10 -10
  53. package/resources/targets/cursor/unreal/unreal/context/web/knowledge/WebBuild.md +6 -6
  54. package/resources/targets/dsh/unreal/target.json +6 -6
  55. package/resources/targets/dsh/unreal/unreal/bundle.json +10 -10
  56. package/resources/targets/dsh/unreal/unreal/context/web/knowledge/WebBuild.md +6 -6
  57. package/resources/targets/index.json +28 -28
  58. package/resources/targets/kimi/unreal/target.json +6 -6
  59. package/resources/targets/kimi/unreal/unreal/bundle.json +10 -10
  60. package/resources/targets/kimi/unreal/unreal/context/web/knowledge/WebBuild.md +6 -6
  61. package/resources/targets/opencode/unreal/target.json +6 -6
  62. package/resources/targets/opencode/unreal/unreal/bundle.json +10 -10
  63. package/resources/targets/opencode/unreal/unreal/context/web/knowledge/WebBuild.md +6 -6
  64. package/resources/targets/qoder/unreal/target.json +6 -6
  65. package/resources/targets/qoder/unreal/unreal/bundle.json +10 -10
  66. package/resources/targets/qoder/unreal/unreal/context/web/knowledge/WebBuild.md +6 -6
  67. package/resources/targets/qoder-cn/unreal/target.json +6 -6
  68. package/resources/targets/qoder-cn/unreal/unreal/bundle.json +10 -10
  69. package/resources/targets/qoder-cn/unreal/unreal/context/web/knowledge/WebBuild.md +6 -6
  70. package/resources/targets/qwen/unreal/target.json +6 -6
  71. package/resources/targets/qwen/unreal/unreal/bundle.json +10 -10
  72. package/resources/targets/qwen/unreal/unreal/context/web/knowledge/WebBuild.md +6 -6
  73. package/resources/targets/trae/unreal/target.json +6 -6
  74. package/resources/targets/trae/unreal/unreal/bundle.json +10 -10
  75. package/resources/targets/trae/unreal/unreal/context/web/knowledge/WebBuild.md +6 -6
  76. package/resources/targets/workbuddy/unreal/target.json +6 -6
  77. package/resources/targets/workbuddy/unreal/unreal/bundle.json +11 -11
  78. package/resources/targets/workbuddy/unreal/unreal/context/web/knowledge/WebBuild.md +7 -11
  79. package/resources/targets/workbuddy/unreal/unreal/context/web/skills/unreal-verify/SKILL.md +1 -1
  80. package/resources/targets/zcode/unreal/target.json +6 -6
  81. package/resources/targets/zcode/unreal/unreal/bundle.json +10 -10
  82. package/resources/targets/zcode/unreal/unreal/context/web/knowledge/WebBuild.md +6 -6
  83. package/resources/templates/unreal/project/Config/DefaultWebPublisher.ini +27 -21
  84. package/resources/templates/unreal/project/Config/README.md +10 -1
  85. package/resources/templates/unreal/project/Plugins/WebPublisher/Source/WebPublisher/Private/WebPublisherModule.cpp +13 -0
  86. package/resources/templates/unreal/project/template.json +33 -33
  87. package/resources/unreal-websdk/Setup-WebSDK.ps1 +2 -1
  88. package/resources/unreal-websdk/WebSDK-Packages.ps1 +143 -33
  89. package/resources/unreal-websdk/websdk-release.json +1 -5
package/README.md CHANGED
@@ -8,18 +8,18 @@ Craft MCP 是面向支持本地 stdio MCP 的 AI IDE 的游戏制作服务,包
8
8
 
9
9
  ### 按宿主安装(推荐)
10
10
 
11
- 显式选择当前宿主;只有同时接入时才用逗号列出多个宿主。安装完整 MCP 程序包、固定启动入口及全局 craft-create、craft-update Skill,保留已有平台和工作区。默认启用 stable 渠道自动检查和安装;新版在下次 MCP 启动或用户重连后加载。
11
+ 选择当前宿主;只有同时接入时才用逗号列出多个宿主。安装完整 MCP 程序包、固定启动入口及全局 craft-create、craft-update Skill,保留已有平台和工作区。
12
+
13
+ 使用本次 guide 命令中的包选择器,将 guide 换为 install --ide <当前宿主>。正式安装使用 @stable。只有用户明确给出了其他渠道时,才沿用该标签并传同名 --channel;安装器为它创建独立的命名服务、工作区和 Skill。同一标签再次安装会复用自己的实例。明确指定版本时保留版本号。
12
14
 
13
15
  ```sh
14
- # 在 Codex 中安装
15
- npx --yes --registry=https://registry.npmjs.org/ @craft_eco/craft-mcp@0.1.5 install --ide codex
16
- # 在 WorkBuddy 中安装
17
- npx --yes --registry=https://registry.npmjs.org/ @craft_eco/craft-mcp@0.1.5 install --ide workbuddy
16
+ # 正式版,在 Codex 中安装
17
+ npx --yes --registry=https://registry.npmjs.org/ @craft_eco/craft-mcp@stable install --ide codex
18
18
  ```
19
19
 
20
- 其他宿主将 --ide 改为 cursor、codebuddy、claude、dsh、zcode、kimi、trae、qoder-cn、qoder、comate、opencode 或 qwen。TRAE 与国际版 Qoder IDE 还须 --host-config <宿主设置中打开的 MCP 配置绝对路径>;TRAE CN 加 --trae-region cn,国际版默认 global。这两个选项也适用于 doctor/check/update/connect/project-setup,可由 CRAFT_HOST_CONFIG、CRAFT_TRAE_REGION 环境变量提供。kimi 指当前 Kimi Code CLI,不写旧 Python Kimi CLI 的 ~/.kimi。可用 --workspace <绝对游戏父目录> 和 --platform <HTTPS origin> 指定目录与平台;未提供时保留现有配置,新安装默认 ~/CraftGames 和本包平台。安装不创建游戏、不修改信任权限;低版本或同版不同构建不会覆盖现有新版。
20
+ 其他宿主将 --ide 改为 cursor、codebuddy、claude、dsh、zcode、kimi、trae、qoder-cn、qoder、comate、opencode 或 qwen。TRAE 与国际版 Qoder IDE 还须 --host-config <宿主设置中打开的 MCP 配置绝对路径>;TRAE CN 加 --trae-region cn,国际版默认 global。这两个选项也适用于 doctor/check/update/connect/project-setup,可由 CRAFT_HOST_CONFIG、CRAFT_TRAE_REGION 环境变量提供。kimi 指当前 Kimi Code CLI,不写旧 Python Kimi CLI 的 ~/.kimi。可用 --workspace <绝对游戏父目录> 和 --platform <HTTPS origin> 指定目录与平台;未提供时保留现有配置,新安装默认 ~/CraftGames 和本包平台。安装不创建游戏、不修改信任权限。
21
21
 
22
- Codex 配置 ~/.codex/config.toml(设置 CODEX_HOME 时使用其 config.toml),全局 Skill 在 ~/.agents/skills;WorkBuddy 配置 ~/.workbuddy/mcp.json,全局 Skill 在 ~/.workbuddy/skills。CodeBuddy 使用 ~/.codebuddy/.mcp.json 与 ~/.codebuddy/skills,已有旧 MCP 配置按官方优先级沿用。初次安装后确认宿主已连接,按宿主提示完成信任。在当前聊天调用无参数的 `craft_game_info`,核对 `runtime.version`、`host` 和 `supported_engines`,受管安装还应显示 `runtime.activation.status=active_verified`。符合预期即可报告安装验收通过。引擎列表描述此连接提供的能力;UE 指南中的 `environment.status=not_checked` 表示尚未请求 Web 诊断,属于正常结果。doctor --ide <当前宿主> 仅验证独立探测和文件,不证明当前聊天已切版或发现 Skill。
22
+ Codex 配置 ~/.codex/config.toml(设置 CODEX_HOME 时使用其 config.toml),全局 Skill 在 ~/.agents/skills;WorkBuddy 配置 ~/.workbuddy/mcp.json,全局 Skill 在 ~/.workbuddy/skills。CodeBuddy 使用 ~/.codebuddy/.mcp.json 与 ~/.codebuddy/skills,已有旧 MCP 配置按官方优先级沿用。安装或切换渠道后,在下次启动或重连时调用当前聊天的 craft_game_info,核对 server_id、update.source.channel、host、supported_engines、运行版本、build_id 和 active_verified。UE 指南中的 environment.status=not_checked 表示尚未请求 Web 诊断。doctor --ide <当前宿主> 仅验证独立探测和文件,不证明当前聊天已切版或发现 Skill。
23
23
 
24
24
  Claude Code 使用 ~/.claude.json 与 ~/.claude/skills;DSH 使用 ~/.dsh/cordis.patch.yml 与 ~/.dsh/skills;ZCode 使用 ~/.zcode/cli/config.json 的 mcp.servers 和 ~/.zcode/skills;Kimi Code CLI 使用 ~/.kimi-code/mcp.json 与 ~/.kimi-code/skills。DSH 配置是 YAML 插件 patch,ZCode 不是 mcpServers。对应目录覆盖通过 CLAUDE_CONFIG_DIR、DSH_HOME、KIMI_CODE_HOME 指定。不要把不同宿主的配置格式互换。
25
25
 
@@ -32,7 +32,7 @@ Claude Code 使用 ~/.claude.json 与 ~/.claude/skills;DSH 使用 ~/.dsh/cordi
32
32
  执行本包 guide,根据当前宿主调用上面的标准 install。十四种宿主使用同一安装流程,无需选择连接模式。当前进程不会因安装新版而切换版本;固定入口在下次启动时读取已安装目标。
33
33
 
34
34
  ```sh
35
- npx --yes --registry=https://registry.npmjs.org/ @craft_eco/craft-mcp@0.1.5 guide
35
+ npx --yes --registry=https://registry.npmjs.org/ @craft_eco/craft-mcp@stable guide
36
36
  ```
37
37
 
38
38
  专家和连接器只通过 connect --ide workbuddy 解析标准安装并启动同一受管入口,首次使用也须先执行标准 install。connect 不安装程序、不改宿主配置、不创建游戏;安装缺失、禁用或平台/工作区不一致时明确失败。不要用无参数 npx 直接启动业务包来替代标准安装。未适配宿主的原始 stdio 调试不包含自动更新和 Skill 安装。
package/bin/craft-mcp.mjs CHANGED
@@ -14,7 +14,33 @@ if (args.length === 0 || (args.length === 2 && args[0] === '--workspace' && path
14
14
  if (args.length) process.env.CLIENT_WORKSPACE_ROOT = path.resolve(args[1]);
15
15
  await import('../dist-server/mcp/start.mjs');
16
16
  } else if (args.length === 1 && args[0] === 'guide') {
17
- process.stdout.write(await readFile(new URL('../README.md', import.meta.url), 'utf8'));
17
+ let guide = await readFile(new URL('../README.md', import.meta.url), 'utf8');
18
+ if (process.env.npm_command === 'exec' && process.env.npm_lifecycle_event === 'npx') {
19
+ const { npmInstallSelector } = await import('../dist-server/integrations/install-source.mjs');
20
+ const { serverIdForChannel } = await import('../dist-server/integrations/instance.mjs');
21
+ const pkg = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8'));
22
+ const selector = await npmInstallSelector(fileURLToPath(new URL('..', import.meta.url)), pkg.name);
23
+ if (selector?.kind === 'tag' && !['stable', 'latest'].includes(selector.tag)) {
24
+ const tag = selector.tag;
25
+ const server = serverIdForChannel(tag);
26
+ guide = [
27
+ '# 安装用户指定的 Craft 实例', '',
28
+ '保留本次 npx 命令的 registry 和包选择器,将 guide 换为下列参数,并将占位符替换为当前宿主。', '',
29
+ ' install --ide <当前宿主> --channel ' + tag + ' --instance ' + server, '',
30
+ '该服务拥有独立的工作区和 Skill。同一命令再次安装时更新该实例。安装完成后等待宿主连接 ' + server +
31
+ ',在当前聊天用它的 craft_game_info 核对 server_id、channel、version、build_id、workspace 和 active_verified。',
32
+ 'TRAE 和国际版 Qoder IDE 需追加 --host-config <从该宿主设置中打开的配置绝对路径>。TRAE 国内版另加 --trae-region cn。',
33
+ '新安装默认游戏目录为 ~/CraftTestGames/' + server + ',平台为 ' + pkg.craft.platform + '。安装器会保留该实例已有的平台和工作区。',
34
+ '在 CLI 中检查、更新、诊断或卸载时传 --ide <当前宿主> --instance ' + server + '。', '',
35
+ ].join('\n');
36
+ } else if (selector?.kind === 'package') {
37
+ guide = guide.replaceAll(pkg.name + '@stable ', pkg.name + '@' + pkg.version + ' ');
38
+ }
39
+ }
40
+ process.stdout.write(guide);
41
+ } else if (args[0] === 'uninstall') {
42
+ try { const { runUninstallCommand } = await import('../dist-server/integrations/uninstall.mjs'); await runUninstallCommand(args); }
43
+ catch (error) { process.stderr.write('Craft uninstall failed: ' + error.message + '\n'); process.exitCode = 1; }
18
44
  } else if (args[0] === 'connect') {
19
45
  try { const { runConnectCommand } = await import('../dist-server/integrations/connect.mjs'); await runConnectCommand(args); }
20
46
  catch (error) { process.stderr.write('Craft connect failed: ' + error.message + '\n'); process.exitCode = 1; }
@@ -37,7 +63,7 @@ if (args.length === 0 || (args.length === 2 && args[0] === '--workspace' && path
37
63
  } else if (args.length === 1 && ['--help', '-h', 'help'].includes(args[0])) {
38
64
  process.stdout.write('Windows local login: craft-mcp login-task --setup|--remove --ide workbuddy [--host-config <absolute MCP config file>]\n');
39
65
  process.stdout.write('Windows game preview: craft-mcp preview-task --setup|--remove --ide workbuddy [--host-config <absolute MCP config file>]\n');
40
- process.stdout.write('Usage: craft-mcp [--workspace <absolute games directory>|guide|--help]\n craft-mcp install --ide <host[,host]> [--workspace <absolute games directory>] [--platform <HTTPS origin>] [--registry <HTTPS registry>] [--channel <npm tag>] [--updates auto|off]\n craft-mcp project-setup --project <absolute game directory> --ide <host> [--install]\n craft-mcp connect --ide <host>\n craft-mcp doctor --ide <host[,host]>\n craft-mcp check --ide <host[,host]>\n craft-mcp update --ide <host[,host]>\nHosts: codex, workbuddy, codebuddy, cursor, claude, dsh, zcode, kimi, trae, qoder-cn, qoder, comate, opencode, qwen.\nHost options: --host-config <absolute MCP config file> (one host only); --trae-region global|cn. TRAE and Qoder IDE require the path opened by their settings UI. Environment equivalents: CRAFT_HOST_CONFIG, CRAFT_TRAE_REGION.\n\nNo arguments: start the stdio MCP server from this package.\n--workspace: override CLIENT_WORKSPACE_ROOT; games are created under <workspace>/<name>.\nDefault workspace: ~/CraftGames. The host current directory is not used.\nguide: print AI IDE installation instructions and exit.\ninstall: install this package, verify it, merge selected host configurations and install managed Skills. Preserve existing workspace/platform and update policy; new installations use a fixed next-start launcher and automatic stable-channel installation.\nconnect: start the existing standard installation; never installs or rewrites host settings.\ncheck: inspect the configured npm channel without installing a new runtime.\nupdate: install a verified newer compatible runtime and update the host configuration, including when automatic updates are off. The current process stays on its original package. Load the target at the next MCP start or user-requested reconnect, verify its identity, then prepare the current project to update context and Skills.\nproject-setup: inspect portable project installation requirements and the selected host; --install installs only a missing registration. Verify the current host connection before resuming.\ndoctor: verify configured files and candidate MCP in an isolated process; does not confirm the current host connection.\n');
66
+ process.stdout.write('Usage: craft-mcp [--workspace <absolute games directory>|guide|--help]\n craft-mcp install --ide <host[,host]> [--workspace <absolute games directory>] [--platform <HTTPS origin>] [--registry <HTTPS registry>] [--channel <npm tag>] [--updates auto|off]\n craft-mcp project-setup --project <absolute game directory> --ide <host> [--install]\n craft-mcp connect --ide <host>\n craft-mcp doctor --ide <host[,host]>\n craft-mcp check --ide <host[,host]>\n craft-mcp update --ide <host[,host]>\nHosts: codex, workbuddy, codebuddy, cursor, claude, dsh, zcode, kimi, trae, qoder-cn, qoder, comate, opencode, qwen.\nInstance selection: --instance <registered Craft server> for install, doctor, connect, project-setup, check, update or uninstall.\n craft-mcp uninstall --ide <host> [--instance <server>]\nHost options: --host-config <absolute MCP config file> (one host only); --trae-region global|cn. TRAE and Qoder IDE require the path opened by their settings UI. Environment equivalents: CRAFT_HOST_CONFIG, CRAFT_TRAE_REGION.\n\nNo arguments: start the stdio MCP server from this package.\n--workspace: override CLIENT_WORKSPACE_ROOT; games are created under <workspace>/<name>.\nDefault workspace: ~/CraftGames. The host current directory is not used.\nguide: print AI IDE installation instructions and exit.\ninstall: install and verify Craft, merge selected host configurations and install managed Skills. The default server is craft on stable. An explicit test tag selects its separate installation. Use --instance to target a specific managed registration. Reinstalling the same channel and automatic updates retain downgrade protection. Preserve the workspace, platform and update policy; new installations enable automatic updates.\nconnect: start the existing standard installation; never installs or rewrites host settings.\ncheck: inspect the configured npm channel without installing a new runtime.\nupdate: install a verified newer compatible runtime and update the host configuration, including when automatic updates are off. The current process stays on its original package. Load the target at the next MCP start or user-requested reconnect, verify its identity, then prepare the current project to update context and Skills.\nproject-setup: inspect portable project installation requirements and the selected host; --install installs only a missing registration. Verify the current host connection before resuming.\ndoctor: verify configured files and candidate MCP in an isolated process; does not confirm the current host connection.\n');
41
67
  } else {
42
68
  process.stderr.write('Unknown command or extra arguments. Use craft-mcp --help.\n');
43
69
  process.exitCode = 1;
@@ -33,7 +33,9 @@ export async function snapshotUnrealFiles(project,artifacts) {
33
33
  const file=await regular(project,root+'/'+artifact.relativePath),stat=await lstat(file);
34
34
  if(file!==artifact.path || !stat.isFile() || stat.size!==artifact.bytes || stat.size>maxFileBytes || (total+=stat.size)>maxBytes || await hashFile(file)!==artifact.sha256) throw new Error('Unreal build changed; check again');
35
35
  const key='/'+artifact.relativePath;if(files.has(key)) throw new Error('Duplicate Unreal artifact');
36
- files.set(key,{path:file,bytes:stat.size,mtimeMs:stat.mtimeMs,ctimeMs:stat.ctimeMs,type:mime[path.extname(file)]??'application/octet-stream'});
36
+ const encoding=path.extname(file)==='.br'?'br':undefined;
37
+ files.set(key,{path:file,bytes:stat.size,mtimeMs:stat.mtimeMs,ctimeMs:stat.ctimeMs,encoding,
38
+ type:mime[path.extname(encoding?file.slice(0,-3):file)]??'application/octet-stream'});
37
39
  }
38
40
  if(!files.has('/index.html') || !files.has('/release.json')) throw new Error('Unreal package requires index.html and release.json');
39
41
  return files;
@@ -46,14 +48,16 @@ export async function serveUnrealFile(req,res,file) {
46
48
  handle=await open(file.path,'r');const stat=await handle.stat();
47
49
  if(!stat.isFile() || stat.size!==file.bytes || stat.mtimeMs!==file.mtimeMs || stat.ctimeMs!==file.ctimeMs) throw new Error('Verified build changed');
48
50
  let start=0,end=file.bytes-1,status=200;
49
- if(req.headers.range) {
51
+ // SDK range reads use raw files; serve compressed representations whole.
52
+ if(req.headers.range && !file.encoding) {
50
53
  const range=/^bytes=(\d+)-(\d*)$/.exec(req.headers.range);
51
54
  if(!range) {res.writeHead(416,{'Content-Range':'bytes */'+file.bytes}).end();return;}
52
55
  start=Number(range[1]);end=range[2]?Number(range[2]):end;
53
56
  if(!Number.isSafeInteger(start)||!Number.isSafeInteger(end)||start>end||end>=file.bytes) {res.writeHead(416,{'Content-Range':'bytes */'+file.bytes}).end();return;}
54
57
  status=206;res.setHeader('Content-Range',`bytes ${start}-${end}/${file.bytes}`);
55
58
  }
56
- res.writeHead(status,{'Content-Type':file.type,'Content-Length':Math.max(0,end-start+1),'Accept-Ranges':'bytes',
59
+ res.writeHead(status,{'Content-Type':file.type,'Content-Length':Math.max(0,end-start+1),'Accept-Ranges':file.encoding?'none':'bytes',
60
+ ...(file.encoding?{'Content-Encoding':file.encoding,'Vary':'Accept-Encoding'}:{}),
57
61
  'Cross-Origin-Opener-Policy':'same-origin','Cross-Origin-Embedder-Policy':'require-corp'});
58
62
  if(req.method==='HEAD'||file.bytes===0) {res.end();return;}
59
63
  const stream=handle.createReadStream({start,end,autoClose:true});handle=null;
@@ -19,8 +19,33 @@ function browserEnvironment(source = process.env) {
19
19
  return Object.fromEntries(Object.entries(source).map(([key,value])=>[key,environmentKeys.has(key.toUpperCase()) ? value : undefined]));
20
20
  }
21
21
 
22
+ async function readSdkReports(page) {
23
+ return Promise.all(page.frames().map(async frame=>{
24
+ const url=frame.url();
25
+ try {return {url,...await frame.evaluate(()=>({WebSDKReport:globalThis.WebSDKReport??null,UEH5Report:globalThis.UEH5Report??null}))};}
26
+ catch(error) {return {url,inspection_error:String(error.message)};}
27
+ }));
28
+ }
29
+
30
+ function sdkFailures(frames,starting=false) {
31
+ const routed=frames.some(frame=>frame.WebSDKReport),errors=[];
32
+ for(const frame of frames) {
33
+ // During startup the router may remove a failed candidate and try another.
34
+ // Judge active reports, never failed attempts or detached-frame history.
35
+ for(const report of [frame.WebSDKReport,...(starting&&routed?[]:[frame.UEH5Report])]) {
36
+ if(!report) continue;
37
+ const messages=Array.isArray(report.errors)?report.errors:[],metrics=report.startupMetrics;
38
+ if(report.status==='failed'||messages.length) errors.push('SDK '+frame.url+': '+(messages.join('; ')||'failed'));
39
+ else if(metrics?.status==='error'||(Number.isSafeInteger(metrics?.snapshot?.webgpuErrors)&&metrics.snapshot.webgpuErrors>0)) {
40
+ errors.push('SDK '+frame.url+': '+(metrics.reason||'WebGPU runtime error'));
41
+ }
42
+ }
43
+ }
44
+ return [...new Set(errors)];
45
+ }
46
+
22
47
  export async function captureUnreal(project,artifacts,run,steps,signal) {
23
- const files=await snapshotUnrealFiles(project,artifacts),capture={shots:[],errors:[],unverified:[]};
48
+ const files=await snapshotUnrealFiles(project,artifacts),capture={shots:[],errors:[],unverified:[],sdk_reports:[]};
24
49
  const server=http.createServer((req,res)=>{
25
50
  let url,pathname;try {url=new URL(req.url,'http://127.0.0.1');pathname=decodeURIComponent(url.pathname);}catch {res.writeHead(400).end();return;}
26
51
  if(!['GET','HEAD'].includes(req.method)) {res.writeHead(405).end();return;}
@@ -29,13 +54,13 @@ export async function captureUnreal(project,artifacts,run,steps,signal) {
29
54
  void serveUnrealFile(req,res,file);
30
55
  });
31
56
  await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(0,'127.0.0.1',resolve);});
32
- let browser;const abort=()=>{void browser?.close();};signal?.addEventListener('abort',abort,{once:true});
57
+ let browser,page;const abort=()=>{void browser?.close();};signal?.addEventListener('abort',abort,{once:true});
33
58
  const timer=setTimeout(abort,10*60*1000);
34
59
  try {
35
60
  const safe=browserEnvironment(),env=await prepareBrowserEnvironment({cwd:project,env:safe,signal});
36
61
  browser=await chromium.launch({headless:true,executablePath:env.CRAFT_BROWSER_EXECUTABLE,chromiumSandbox:true,
37
62
  env:Object.fromEntries(Object.entries({...safe,...env}).filter(([,value])=>value!==undefined))});signal?.throwIfAborted();
38
- const page=await browser.newPage({viewport:{width:1280,height:720}});
63
+ page=await browser.newPage({viewport:{width:1280,height:720}});
39
64
  page.on('pageerror',error=>capture.errors.push(error.message));
40
65
  page.on('console',message=>{if(message.type()==='error') capture.errors.push(message.text());});
41
66
  page.on('response',response=>{if(response.status()>=400) capture.errors.push('HTTP '+response.status()+' '+response.url());});
@@ -43,6 +68,9 @@ export async function captureUnreal(project,artifacts,run,steps,signal) {
43
68
  let frame;
44
69
  for(let i=0;i<240;i++) {
45
70
  signal?.throwIfAborted();
71
+ capture.sdk_reports=await readSdkReports(page);
72
+ const failures=sdkFailures(capture.sdk_reports,true);
73
+ if(failures.length) throw new Error('Unreal SDK startup failed: '+failures.join('; '));
46
74
  for(const candidate of page.frames()) if(await candidate.evaluate(()=>globalThis.__GAME_PROBE__?.snapshot?.().ready===true).catch(()=>false)) {frame=candidate;break;}
47
75
  if(frame) break;await page.waitForTimeout(1000);
48
76
  }
@@ -68,9 +96,30 @@ export async function captureUnreal(project,artifacts,run,steps,signal) {
68
96
  await page.waitForTimeout(100);
69
97
  const gameplay_probe=await frame.evaluate(()=>globalThis.__GAME_PROBE__.snapshot());
70
98
  const file='shot-'+i+'.jpg';await page.screenshot({path:path.join(run,file),type:'jpeg',quality:85});
71
- capture.shots.push({file,gameplay_probe});
99
+ const sdk_reports=await readSdkReports(page);capture.sdk_reports=sdk_reports;
100
+ capture.shots.push({file,gameplay_probe,sdk_reports});
101
+ }
102
+ } finally {
103
+ clearTimeout(timer);signal?.removeEventListener('abort',abort);
104
+ let diagnosticTimer;
105
+ try {
106
+ if(page) {
107
+ try {
108
+ const reports=await Promise.race([readSdkReports(page),new Promise((_,reject)=>{
109
+ diagnosticTimer=setTimeout(()=>reject(new Error('Final SDK report inspection timed out')),3000);
110
+ })]);
111
+ if(reports.some(report=>report.inspection_error)) reports.push({last_known_reports:capture.sdk_reports});
112
+ capture.sdk_reports=reports;
113
+ } catch(error) {capture.sdk_reports=[{url:page.url(),inspection_error:String(error.message),last_known_reports:capture.sdk_reports}];}
114
+ finally {clearTimeout(diagnosticTimer);}
115
+ }
116
+ await writeFile(path.join(run,'sdk-diagnostics.json'),JSON.stringify(capture.sdk_reports,null,2));
117
+ } finally {
118
+ try {await browser?.close();}
119
+ finally {server.closeAllConnections();await new Promise(resolve=>server.close(resolve));}
72
120
  }
73
- } finally {clearTimeout(timer);signal?.removeEventListener('abort',abort);await browser?.close();server.closeAllConnections();await new Promise(resolve=>server.close(resolve));}
121
+ }
122
+ capture.errors.push(...sdkFailures(capture.sdk_reports));
74
123
  return capture;
75
124
  }
76
125
 
@@ -79,13 +128,13 @@ export async function checkUnrealGame(project,resources,brief,steps,signal,evalu
79
128
  const binding=await inspectUnreal(project);
80
129
  const environment=await unrealEnvironment({templateRoot:resources.template,resources:resources.installationResources,prepare:async()=>{
81
130
  await progress({phase:'正在准备官方 Web SDK'});
82
- await prepareOfficialSdk(resources.installationResources,signal);
131
+ return prepareOfficialSdk(resources.installationResources,signal);
83
132
  }});
84
133
  if(environment.status!=='ready') throw new Error('Unreal Web build environment unavailable: '+environment.issues.join('; '));
85
134
  const variants=environment.config.variants??['WasmWebGL2=DXT'];
86
135
  if(!Array.isArray(variants)||!variants.length||variants.length>3||variants.some(v=>!/^WasmWeb(?:GL2|GPU|GPUMobile)=(DXT|ASTC|DXT\+ASTC)$/.test(v))) throw new Error('Invalid Unreal variants configuration');
87
136
  await guardWork();
88
- await bindWebBuild(project,binding,environment.identity);
137
+ await bindWebBuild(project,binding,environment.identity,{latestSdk:Boolean(environment.config.kit_version)});
89
138
  const source=await unrealFingerprint(project),id=randomUUID(),output=path.join(project,'Saved/Craft/Builds',id);
90
139
  await mkdir(output,{recursive:true});
91
140
  await progress({phase:'unreal-build',log_directory:output});
@@ -87,7 +87,7 @@ async function readRelease(output, previousReleases, project) {
87
87
  engine_version:release.engineVersion,sdk_version:release.sdkVersion};
88
88
  }
89
89
 
90
- export async function runUnrealExport({project,environment,resources,templateRoot,output,variants,lto,excludedPlugins=[],webSettings,signal,
90
+ export async function runUnrealExport({project,environment,resources,templateRoot,output,variants,lto,contentDelivery,excludedPlugins=[],webSettings,signal,
91
91
  progress=async()=>{},run=executeSdk,setup,prepare=prepareWebProject}) {
92
92
  if (environment.status !== 'ready') throw new Error('Unreal environment unavailable: '+environment.issues.join('; '));
93
93
  output = await exportDestination(project,output);
@@ -102,12 +102,12 @@ export async function runUnrealExport({project,environment,resources,templateRoo
102
102
  const unlock = await lockfile.lock(path.join(output,'.craft-export'),{...leaseOptions,onCompromised:error=>controller.abort(error)});
103
103
  try {
104
104
  buildSignal.throwIfAborted();
105
- const prepared=await prepare({project,output,config,templateRoot,variants:selection,excludedPlugins,webSettings,signal:buildSignal,progress});
105
+ const prepared=await prepare({project,output,config,templateRoot:config.web_template_root??templateRoot,variants:selection,excludedPlugins,webSettings,signal:buildSignal,progress});
106
106
  const buildProject=prepared.project;
107
107
  await ensureProjectPublisher({project:buildProject,config,resources,signal:buildSignal,progress,setup});
108
108
  buildSignal.throwIfAborted();
109
109
  const prior = await readdir(path.join(output,'Releases')).catch(error=>{if (error.code === 'ENOENT') return []; throw error;});
110
- const args = sdkBuildArgs(environment,buildProject,output,selection,lto);
110
+ const args = sdkBuildArgs(environment,buildProject,output,selection,lto,contentDelivery);
111
111
  await progress({phase:'unreal-export-build',log_directory:logs,output_dir:output});
112
112
  await run(environment,args,path.join(logs,'export.log'),buildSignal);
113
113
  buildSignal.throwIfAborted();
@@ -15,7 +15,7 @@ export async function externalUnrealEnvironment({configFile,platform=process.pla
15
15
  const config = await installedConfig(configFile,release,{build:true,prepare});
16
16
  const expected=release?.engineVersion ?? engineCatalog.unreal.compatibility.engine_version;
17
17
  if (config.engineVersion !== expected || !config.sdkVersion) throw new Error('配置的编辑器版本与 Web SDK 不匹配。');
18
- return {status:'ready',config_file,issues:[],config,identity:{engine_version:config.engineVersion,sdk_version:config.sdkVersion}};
18
+ return {status:'ready',config_file,issues:[],config,identity:{engine_version:config.engineVersion,sdk_version:config.sdkVersion,...(config.kit_version?{kit_version:config.kit_version}:{})}};
19
19
  } catch(error) {
20
20
  return {status:'unavailable',config_file,issues:[error.message]};
21
21
  }
@@ -43,6 +43,12 @@ export async function prepareOfficialSdk(resources,signal,args=['-Action','Prepa
43
43
  if (result.exitCode!==0 || result.timedOut) {
44
44
  throw new Error('官方 Web SDK '+args[1]+' 失败。'+(result.stderr || result.stdout).trim().slice(-1600));
45
45
  }
46
+ if (args[args.indexOf('-Action')+1]==='Prepare') {
47
+ const start=result.stdout.lastIndexOf('\n{');
48
+ const record=start>=0?result.stdout.slice(start+1):result.stdout.trimStart();
49
+ try { return JSON.parse(record); }
50
+ catch { throw new Error('官方 Web SDK 安装器未返回有效的 JSON 回执。'); }
51
+ }
46
52
  }
47
53
 
48
54
  async function optionalDescriptor(file) {
@@ -2,7 +2,7 @@ import path from 'node:path';
2
2
  import {readFile, readdir, realpath, stat} from 'node:fs/promises';
3
3
  import {exportProject, releaseMatchesProject, sdkBuildPassed} from './export.mjs';
4
4
  import {preparedProjectPath} from './prepare-export.mjs';
5
- import {installedConfig, regular, sdkRelease} from './project.mjs';
5
+ import {installedConfig, regular} from './project.mjs';
6
6
 
7
7
  const json = async file => JSON.parse(await readFile(file,'utf8'));
8
8
  const same = (a,b) => typeof a === 'string' && typeof b === 'string' && path.relative(a,b) === '';
@@ -16,7 +16,7 @@ async function list(dir) {
16
16
  // A preview only needs the SDK's own Python and HTTP preview command. An
17
17
  // editor installation, the authoring template and a compile toolchain are not used.
18
18
  export async function previewEnvironment(configFile,resources) {
19
- return {config:await installedConfig(configFile,await sdkRelease(resources))};
19
+ return {config:await installedConfig(configFile,undefined,{allowMissingSdk:true})};
20
20
  }
21
21
 
22
22
  function previewCandidate(job) {
@@ -30,7 +30,7 @@ async function sdkRuntime(config,release) {
30
30
  if (config.schema !== 1 || !path.isAbsolute(config.sdk_root ?? '')) throw new Error('Craft 的 Web SDK 配置无效。');
31
31
  const sdk_root = await realpath(config.sdk_root);
32
32
  const sdk = await json(await regular(sdk_root,'sdk.json'));
33
- if (release && (sdk.sdkVersion !== release.sdkVersion || sdk.sourceIdentity?.revision !== release.sourceRevision)) {
33
+ if (release && ((release.sdkVersion && sdk.sdkVersion !== release.sdkVersion) || (release.sourceRevision && sdk.sourceIdentity?.revision !== release.sourceRevision))) {
34
34
  throw Object.assign(new Error('此 SDK 与官方发行包 '+release.kitVersion+'(SDK '+release.sdkVersion+')不匹配。请核对配置中的 sdk_root。官方下载:'+release.archiveUrl),{code:'CRAFT_UNREAL_SDK_MISMATCH'});
35
35
  }
36
36
  const toolchain = await json(await regular(sdk_root,'toolchain.json'));
@@ -68,9 +68,9 @@ async function buildEditor(configured,expectedVersion) {
68
68
  }
69
69
  }
70
70
 
71
- // An explicit configuration is authoritative. A default configuration keeps the user's
72
- // editor and variants even when the SDK itself has moved or a new release is required.
73
- export async function installedConfig(configFile,release,{build=false,prepare}={}) {
71
+ // The installer resolves the latest release once per build. Read-only inspection
72
+ // and preview keep using an installed SDK without downloading or rewriting settings.
73
+ export async function installedConfig(configFile,release,{build=false,prepare,allowMissingSdk=false}={}) {
74
74
  const explicit=configFile!==undefined || Boolean(process.env.CRAFT_UNREAL_CONFIG);
75
75
  const file=configFile ?? unrealConfigFile();
76
76
  if (!path.isAbsolute(file)) throw new Error('CRAFT_UNREAL_CONFIG must be absolute');
@@ -78,17 +78,42 @@ export async function installedConfig(configFile,release,{build=false,prepare}={
78
78
  try { settings=await json(file); }
79
79
  catch(error) { if (explicit || error.code!=='ENOENT') throw error; }
80
80
  const editor=build ? {editor_root:await buildEditor(settings?.editor_root,release?.engineVersion ?? engineCatalog.unreal.compatibility.engine_version)} : {};
81
- if (settings !== undefined) {
81
+ if (release?.latestVersionUrl && prepare) {
82
+ if (settings && (settings.schema!==1 || (settings.sdk_root!==undefined && !path.isAbsolute(settings.sdk_root)))) {
83
+ throw new Error('Craft 的 Web SDK 配置无效。');
84
+ }
85
+ const selected=await prepare(editor);
86
+ if (selected?.status!=='ready' || selected.action!=='Prepare' ||
87
+ !/^\d+\.\d+\.\d+(?:\.\d+)?$/.test(selected.kitVersion??'') ||
88
+ !['packagesRoot','sdkRoot','templateRoot'].every(key=>typeof selected[key]==='string' && path.isAbsolute(selected[key])) ||
89
+ path.relative(path.join(selected.packagesRoot,'SDK'),selected.sdkRoot)!=='' ||
90
+ path.relative(path.join(selected.packagesRoot,'WebStarter'),selected.templateRoot)!=='') {
91
+ throw new Error('官方 SDK 安装器没有返回完整的配套安装回执。');
92
+ }
93
+ const runtime=await sdkRuntime({schema:1,sdk_root:selected.sdkRoot});
94
+ const templateRoot=await realpath(selected.templateRoot);
95
+ const template=await json(await regular(templateRoot,'template.json'));
96
+ if (runtime.engineVersion!==release.engineVersion || runtime.engineVersion!==selected.engineVersion ||
97
+ runtime.sdkVersion!==selected.sdkVersion || template.engineVersion!==runtime.engineVersion ||
98
+ template.templateVersion!==engineCatalog.unreal.compatibility.template_version) {
99
+ throw new Error('官方 SDK 安装回执与实际 SDK 或配套模板不匹配。');
100
+ }
101
+ return {schema:1,...settings,...editor,...runtime,kit_version:selected.kitVersion,
102
+ packages_root:selected.packagesRoot,web_template_root:templateRoot};
103
+ }
104
+ const unconfiguredSdk=allowMissingSdk && settings?.schema===1 && settings.sdk_root===undefined;
105
+ if (settings !== undefined && !unconfiguredSdk) {
82
106
  try { return {...settings,...editor,...await sdkRuntime(settings,release)}; }
83
107
  catch(error) {
84
- if (explicit || !['ENOENT','CRAFT_UNREAL_SDK_MISMATCH'].includes(error.code)) throw error;
108
+ if ((explicit && !(allowMissingSdk && error.code==='ENOENT')) ||
109
+ !['ENOENT','CRAFT_UNREAL_SDK_MISMATCH'].includes(error.code)) throw error;
85
110
  }
86
111
  }
87
112
  const receipt=path.join(process.env.LOCALAPPDATA??'', 'WXUP','WebSDK','current.json');
88
113
  async function fromReceipt() {
89
114
  const kit=await json(receipt);
90
115
  if (!path.isAbsolute(kit.packagesRoot??'')) throw new Error('Invalid packagesRoot in '+receipt);
91
- if (release && kit.kitVersion!==release.kitVersion) {
116
+ if (release?.kitVersion && kit.kitVersion!==release.kitVersion) {
92
117
  throw Object.assign(new Error('此安装记录与官方发行包 '+release.kitVersion+' 不匹配。'),{code:'CRAFT_UNREAL_SDK_MISMATCH'});
93
118
  }
94
119
  return sdkRuntime({schema:1,sdk_root:path.join(kit.packagesRoot,'SDK')},release);
@@ -119,7 +144,7 @@ export async function unrealEnvironment({configFile,templateRoot,platform=proces
119
144
  const sdk=await json(sdkFile),template=await json(templateFile);
120
145
  const expected=engineCatalog.unreal.compatibility;
121
146
  if(sdk.engineVersion!==expected.engine_version || template.engineVersion!==expected.engine_version) issues.push('Editor, SDK and template must all be UE '+expected.engine_version);
122
- if(sdk.sdkVersion!==expected.sdk_version || sdk.runtimePipelinePolicyVersion!==expected.runtime_pipeline_policy || !sdk.sourceIdentity?.digest) issues.push('SDK requires version '+expected.sdk_version+', runtimePipelinePolicyVersion='+expected.runtime_pipeline_policy+' and sourceIdentity; install a matching complete release');
147
+ if(!sdk.sdkVersion || sdk.runtimePipelinePolicyVersion!==expected.runtime_pipeline_policy || !sdk.sourceIdentity?.digest) issues.push('SDK requires runtimePipelinePolicyVersion='+expected.runtime_pipeline_policy+' and sourceIdentity; install a matching complete release');
123
148
  if(template.templateVersion!==expected.template_version || template.editorPluginSource!==true) issues.push('A complete source-distribution WebStarter template version 2 is required');
124
149
  const project=await json(await regular(config.template_root,'WebStarter.uproject'));
125
150
  if(project.Plugins?.some(plugin=>plugin.Enabled && plugin.Name==='Puerts')) issues.push('The first Craft Unreal profile uses C++; select the matching WebStarter without PuerTS. Script profiles require separate validation');
@@ -155,10 +180,12 @@ async function buildLogTail(logFile) {
155
180
  return text(createReadStream(logFile,{start:Math.max(0,size-8192),end:size-1}));
156
181
  }
157
182
 
158
- export function sdkBuildArgs(environment,project,output,variants,lto='thin') {
183
+ export function sdkBuildArgs(environment,project,output,variants,lto='thin',contentDelivery) {
184
+ if (contentDelivery!==undefined && typeof contentDelivery!=='boolean') throw new Error('content_delivery must be a boolean');
159
185
  return ['build','--sdk',environment.config.sdk_root,'--project',project,
160
186
  '--editor-version',environment.identity.engine_version,'--output',output,'--lto',lto,
161
- ...variants.flatMap(value=>['--variant',value])];
187
+ ...variants.flatMap(value=>['--variant',value]),
188
+ ...(contentDelivery===undefined ? [] : [contentDelivery ? '--content-delivery' : '--no-content-delivery'])];
162
189
  }
163
190
 
164
191
  export async function executeSdk(environment,args,logFile,signal) {
@@ -179,15 +206,20 @@ export async function executeSdk(environment,args,logFile,signal) {
179
206
 
180
207
  // Build identity is machine-independent and only bound by explicit Web work under
181
208
  // the project lease. Existing SDK-created projects retain their original identity.
182
- export async function bindWebBuild(project,binding,identity) {
209
+ export async function bindWebBuild(project,binding,identity,{latestSdk=false}={}) {
183
210
  if (binding.engine_version !== identity.engine_version || binding.profile !== identity.profile) throw new Error('Unreal Web build profile mismatch');
184
211
  if (binding.schema === 2 && !Object.hasOwn(binding,'web_build')) {
185
212
  await atomicJson(await safeProjectFile(project,bindingFile),{...binding,web_build:identity});
186
213
  return;
187
214
  }
188
215
  const pinned = binding.schema === 1 ? binding : binding.web_build;
216
+ const sdkFields = latestSdk && binding.schema===2
217
+ ? new Set(['sdk_version','sdk_manifest_sha256','sdk_source_digest','toolchain_id']) : new Set();
189
218
  for (const [key,value] of Object.entries(identity)) {
190
- if (!isDeepStrictEqual(pinned?.[key],value)) throw new Error('Unreal '+key+' changed; configure the bound release or explicitly migrate the project');
219
+ if (!sdkFields.has(key) && !isDeepStrictEqual(pinned?.[key],value)) throw new Error('Unreal '+key+' changed; configure the bound release or explicitly migrate the project');
220
+ }
221
+ if (sdkFields.size && !isDeepStrictEqual(pinned,identity)) {
222
+ await atomicJson(await safeProjectFile(project,bindingFile),{...binding,web_build:identity});
191
223
  }
192
224
  }
193
225
 
@@ -10,8 +10,9 @@ import { hosts, clientIde, projectSkillPath, hostRecoveryEntry } from '../integr
10
10
  const start = '<!-- craft-mcp:project:start -->';
11
11
  const end = '<!-- craft-mcp:project:end -->';
12
12
  // Independent of engine bundle versions: generated recovery instructions evolve too.
13
- export const entryPolicyVersion = 16;
13
+ export const entryPolicyVersion = 17;
14
14
  const hash = value => createHash('sha256').update(value).digest('hex');
15
+ const instanceGuide = '先读取已有的 `.craft/project-install.json`。若宿主暴露多组 Craft 工具,用各服务的只读 `craft_game_info` 核对工作区是当前项目父目录、平台和渠道符合清单,再按项目名核对绝对路径与引擎。记录唯一匹配的工具命名空间和 server_id;后续制作、上传、检查更新和重连核验沿用该服务。多个服务都匹配时请用户选定,缺少匹配时按项目接入指引处理。';
15
16
  const turnUpdateGuide = '进入 Craft 工作流后,每条用户消息使用新的检查 key。同一轮调用支持 `update_request_key` 的业务工具时传这个 key,工具会顺带检查;本轮仅答疑、编辑本地文件或只用轮询等工具时,补一次只读 `craft_update_check`(request_key=本轮 key,已有工程传 name)。制作时,业务回执的 update_notice 或显式检查返回 update_available=true 且 automatic_update_enabled=true,就用同一 key 调用 `craft_update`(mode=auto,已有工程传 name)。纯查看只检查,未发现更新直接继续。同一目标版本待重连时只提示一次。';
16
17
  const normalizeLines = value => value.replace(/\r\n/g,'\n');
17
18
  const jsUploadGuide = '上传游戏、更新云端版本或发布时,使用 Craft MCP。纯上传用 `craft_game_check` 的 `purpose="upload"` 构建并冻结源码和 dist,安全检查通过后用 `craft_game_upload` 上传。更新原项目时先用 `craft_game_upload_status({name})` 核对云端绑定,上传传 `expected_appid`。收到 `draft_ready` 后报告版本、appid 和项目链接,由用户进入项目页提审。遇到阻塞时报告工具名和原始错误,改用 Computer Use、GM 或网页编辑器上传须另获用户同意。';
@@ -25,10 +26,10 @@ export function projectContextPaths(project, ide = 'generic', schema = 5) {
25
26
 
26
27
  function recovery(name, engine) {
27
28
  return `Craft 工程名:\`${name}\`;引擎:\`${engine}\`。保持已有引擎与用户源码。\n\n`
28
- + turnUpdateGuide + '\n\n'
29
+ + instanceGuide + '\n\n' + turnUpdateGuide + '\n\n'
29
30
  + '先读 `SPEC/PROGRESS.md` 和已有的 SPEC 设计文件,核对已完成玩法、待办及最近验收;缺少记录时检查源码与工具回执,不根据旧聊天猜测。\n\n'
30
31
  + `继续本工程前调用 \`craft_game_info({"name":"${name}"})\`,核对返回的 project 是当前目录、context_binding.status 为 bound。读取返回的 \`context.workflow\`、\`context.engine.entrypoint\` 和 \`context.engine.skills_index\`;按索引 description 选择技能,相对于 context.engine.directory 读取 entrypoint,再按需读取引用。\n\n`
31
- + `MCP 的 workspace 是游戏父目录,工程位于 \`workspace/${name}\`,不自动跟随宿主当前目录。若不匹配,先在宿主 MCP 设置中将 \`--workspace\` 参数(优先)或 \`CLIENT_WORKSPACE_ROOT\` 指向当前游戏的父目录并重连;不要在错误目录创建同名工程。\n\n`
32
+ + `MCP 的 workspace 是游戏父目录,工程位于 \`workspace/${name}\`,不自动跟随宿主当前目录。若不匹配,先通过项目接入检查确认正确连接,保留其他工作区及其工程。\n\n`
32
33
  + `迁移目录或首次恢复时若提示尚未 prepare,确认 workspace 后调用 \`craft_game_prepare({"name":"${name}","engine":"${engine}","mode":"resume","request_key":"resume-unique-key"})\` 并轮询任务完成;已有合法工程只会被接管,不重置模板。目录更名后使用当前目录名(须符合工具的英文 name 规则)。\n\n`
33
34
  + '项目以 `.craft/context-lock.json` 绑定引擎上下文版本,随项目保存;实际路径每次通过工具查询。缺少绑定时由 prepare 核验后建立,缺包或不兼容时按诊断恢复匹配版本,不删除锁文件来绕过检查。上下文、模板和技能脚本由 Craft 版本包提供,不复制到游戏中;MCP 未连接时先连接项目使用的 Craft 服务。\n\n'
34
35
  + '验收使用 `craft_game_check` → `craft_game_review` → `craft_game_deliver`;宿主按返回命令启动预览,再核对当前快照已运行。构建成功不代表预览自动开启。\n\n'
@@ -92,11 +93,11 @@ function mergeRuleMetadata(original,prefix) {
92
93
  function projectConnectionGuide(host) {
93
94
  const target = host === 'generic' ? '<当前宿主>' : host;
94
95
  return '首次接手或切换 Agent 时,先通过当前宿主实际提供的工具发现能力查找 Craft 工具;工具可能延迟暴露或带命名空间前缀,不能因裸工具名不存在、resources 为空就判断未安装。项目文件和 Skill 可用也不代表 MCP 已连接。\n\n'
95
- + '无论是否已连接,都先读取存在的 `.craft/project-install.json` 并与实际连接核对;实际程序低于 minimum_mcp_version、平台或工作目录不符时先处理接入,不能直接开始制作。\n\n'
96
+ + instanceGuide + ' 实际程序低于 minimum_mcp_version 时先处理版本要求。\n\n'
96
97
  + '若没有可用的 Craft 连接,读取 `.craft/project-install.json`,确认 package_name、minimum_mcp_version、registry、channel、platform 和 engine。使用当前宿主终端执行下面的项目接入检查,将占位值替换为文件中的值及当前游戏绝对目录,并按终端规则引用参数:\n\n'
97
98
  + '```text\nnpx -y --registry "<registry>" "@craft_eco/craft-mcp@<minimum_mcp_version>" project-setup --project "<当前游戏绝对目录>" --ide '+target+'\n```\n\n'
98
99
  + 'TRAE 和国际版 Qoder IDE 的接入命令需加 `--host-config "<宿主 MCP 设置界面打开的配置文件绝对路径>"`;不要猜测配置路径。TRAE CN 另加 `--trae-region cn`,国际版使用 global。已有安装检查、更新及恢复沿用相同路径和地区。\n\n'
99
- + '检查命令只读;仅返回 `missing_installation` 且用户正在请求继续制作时,在同一命令末尾加 `--install`,自动下载并标准安装到当前宿主。所选包必须满足项目最低 MCP 版本;随后按已有更新策略检查渠道。安装包尚未发布或网络/终端权限不可用时报告准确原因;用户提供本地候选包时可用该包的同一 CLI,不降低项目版本。\n\n'
100
+ + '检查命令只读。返回 `instance_required` 或 `multiple_installations` 时请用户选定服务,以 `--instance <服务名>` 重新检查。仅返回 `missing_installation` 且用户正在请求继续制作时,在同一命令末尾加 `--install`;非 stable 渠道新装须由用户明确选择命名实例。所选包必须满足项目最低 MCP 版本;随后按已有更新策略检查渠道。安装包尚未发布或网络/终端权限不可用时报告准确原因;用户提供本地候选包时可用该包的同一 CLI,不降低项目版本。\n\n'
100
101
  + '已有配置被禁用、范围不匹配、旧版或连接失败时按检查结果修复,不当作缺失重复安装,不自行启用用户禁用的服务或覆盖其他工作区/平台。`--workspace` 必须是当前游戏父目录,不跟随默认目录。旧项目缺少安装信息时,先使用已连接且目录/平台明确的 Craft 完成 resume 以补齐;无可靠来源则询问缺失的平台/版本信息,不猜默认环境。\n\n'
101
102
  + '安装回执和 doctor 只证明配置及独立探测。等待宿主实际加载 Craft;需要时提示重连或重启,只有宿主提示信任/登录时由用户处理。连接后必须由当前会话调用 `craft_game_info`,核对实际 version/build_id、host、workspace、platform、project 和原引擎,标准安装确认 active_verified 后再 prepare(resume)。不要使用另一个终端探测代替当前会话验收,不重建已有工程。纯查看不安装或更新,打开文件夹本身不触发安装。\n\n';
102
103
  }
@@ -125,7 +126,7 @@ function recoveryEntries(name, engine, ide = 'generic', isolated = false) {
125
126
  + start + '\n# 继续当前 Craft 游戏\n\n'
126
127
  + '首次接手先读根 AGENTS.md 的接入流程,确认当前宿主及项目安装信息。若当前会话无法使用 Craft MCP,先运行只读 `project-setup` 检查。仅当用户要求继续制作且检查返回 `missing_installation` 时才安装 Craft MCP。核验当前会话的 Craft MCP 连接后,再调用下面的工具。不要因延迟工具尚未发现而误判未安装。\n\n'
127
128
  + (isolated ? '本入口适用于 '+host+',project-setup 使用 `--ide '+host+'`;当前 Agent 不属于该宿主时按根路由读取自身入口。\n\n' : '')
128
- + `1. 读取项目根 \`AGENTS.md\`,确认工程 \`${name}\` 和引擎 \`${engine}\`。\n`
129
+ + `1. 读取项目根 \`AGENTS.md\`,确认工程 \`${name}\` 和引擎 \`${engine}\`。` + instanceGuide + '\n'
129
130
  + turnUpdateGuide + '\n\n'
130
131
  + (isolated ? '2. 当前连接仍持有本工程有效 work 时沿用 work_id/context_revision。新会话先调用只读 `craft_game_info` 核对项目和工作区。核对实际版本后,尚无有效 work 且可继续时调用 `craft_game_prepare`(mode=resume,同一 request_key)。轮询完成并保留 work_id/context_revision,重新读取本 Skill 相邻的 [引擎入口](../../AGENTS.md)、[恢复说明](../../recovery.md)、[工作流](../../workflow.md) 和 [技能索引](../index.json),按任务读取当前宿主 skills/ 下的正文。\n' : '2. 按根 AGENTS.md 查询 `craft_game_info`,读取返回的引擎入口、工作流与技能索引。\n')
131
132
  + (isolated ? ' 新版安装后等待下次 MCP 启动或用户重连。确认实际 version、build_id、active_verified 后,prepare(resume) 按游戏原引擎更新各已绑定宿主有变化的官方 Skill。完成后重新读取本宿主的索引和正文。\n' : '')
@@ -45,11 +45,12 @@ export async function readProjectInstall(project, { required = false } = {}) {
45
45
  return manifest;
46
46
  }
47
47
 
48
- export function assertProjectInstallConnection(manifest, { engine, version, platform, registry, channel }) {
48
+ export function assertProjectInstallConnection(manifest, { engine, version, platform, registry, channel, requireKnownChannel = false }) {
49
49
  if (manifest.engine !== engine) throw new Error('Project installation engine differs from the existing game; keep its original engine');
50
50
  if (compareVersions(version, manifest.minimum_mcp_version) < 0) throw new Error('Project requires Craft MCP >= ' + manifest.minimum_mcp_version + '; the current runtime cannot downgrade its installation contract');
51
51
  if (httpsUrl(platform, { origin: true }) !== manifest.platform) throw new Error('Project installation platform differs from the current Craft connection; reconnect to the project platform before resuming');
52
52
  if (registry !== undefined && httpsUrl(registry) !== manifest.registry) throw new Error('Project installation registry differs from the current Craft installation; preserve the project source and reconnect with its registry');
53
+ if (requireKnownChannel && !channel && manifest.channel !== 'stable') throw new Error('This project requires a verified Craft installation for its configured channel: ' + manifest.channel);
53
54
  if (channel !== undefined && channel !== manifest.channel) throw new Error('Project installation channel differs from the current Craft installation; preserve the project source and reconnect with its channel');
54
55
  }
55
56
 
@@ -1,9 +1,10 @@
1
1
  import { parse, stringify } from 'smol-toml';
2
2
  import { isDeepStrictEqual } from 'node:util';
3
- import { readDshConfig, dshRegistrations, mergeDshConfig } from './dsh-config.mjs';
3
+ import { readDshConfig, dshRegistrations, mergeDshConfig, removeDshConfig } from './dsh-config.mjs';
4
4
  import { hasCraftConnectionIdentity } from './registration-identity.mjs';
5
- import { readJsonc, updateJsoncEntry } from './jsonc-config.mjs';
6
- import { readOpenCodeConfig, openCodeConfig, openCodeRegistrations, mergeOpenCodeConfig } from './opencode-config.mjs';
5
+ import { readJsonc, updateJsonc, updateJsoncEntry } from './jsonc-config.mjs';
6
+ import { readOpenCodeConfig, openCodeConfig, openCodeRegistrations, mergeOpenCodeConfig, removeOpenCodeConfig } from './opencode-config.mjs';
7
+ import { validateServerId } from './instance.mjs';
7
8
 
8
9
  function object(value) { return value !== null && typeof value === 'object' && !Array.isArray(value); }
9
10
  function serverTable(config, ide) { return ide === 'zcode' ? config.mcp?.servers : config[ide === 'codex' ? 'mcp_servers' : 'mcpServers']; }
@@ -112,11 +113,37 @@ function sections(text) {
112
113
  return found.map((section, i) => ({ ...section, end: found[i + 1]?.start ?? text.length }));
113
114
  }
114
115
 
115
- export function mergeConfig(text, ide, connection, { previousName = 'craft', enable = true } = {}) {
116
- if (ide === 'dsh') return mergeDshConfig(text, connection, { previousName, enable });
117
- if (ide === 'opencode') return mergeOpenCodeConfig(text, connection, { previousName, enable });
116
+ function withoutTomlServer(text, before, previousName) {
117
+ const owned = sections(text).filter(({ keys }) => keys[0] === 'mcp_servers' && keys[1] === previousName);
118
+ if (before.mcp_servers?.[previousName] && !owned.length) throw new Error('Inline/dotted Craft TOML entry: move it to [mcp_servers.' + previousName + '] before editing; config was preserved');
119
+ let kept = '', from = 0;
120
+ for (const section of owned) { kept += text.slice(from, section.start); from = section.end; }
121
+ return kept + text.slice(from);
122
+ }
123
+
124
+ export function removeConfig(text, ide, serverId = 'craft') {
125
+ validateServerId(serverId);
126
+ if (ide === 'dsh') return removeDshConfig(text, serverId);
127
+ if (ide === 'opencode') return removeOpenCodeConfig(text, serverId);
118
128
  const before = readConfig(text, ide), servers = serverTable(before, ide);
119
- if (previousName !== 'craft' && servers?.craft) throw new Error('Craft installation conflicts with an existing craft registration');
129
+ if (!servers || !Object.hasOwn(servers, serverId)) return text;
130
+ const remaining = { ...servers };
131
+ delete remaining[serverId];
132
+ const expected = withServerTable(before, ide, remaining);
133
+ if (ide === 'qwen') return updateJsonc(text, [{ path: ['mcpServers', serverId], value: undefined }]);
134
+ if (ide !== 'codex') return JSON.stringify(expected, null, 2) + '\n';
135
+ const output = withoutTomlServer(text, before, serverId);
136
+ if (!Object.keys(remaining).length && !parse(output).mcp_servers) delete expected.mcp_servers;
137
+ if (!isDeepStrictEqual(parse(output), parse(stringify(expected)))) throw new Error('TOML removal changed unrelated settings; config was preserved');
138
+ return output;
139
+ }
140
+
141
+ export function mergeConfig(text, ide, connection, { serverId = 'craft', previousName = serverId, enable = true } = {}) {
142
+ validateServerId(serverId);
143
+ if (ide === 'dsh') return mergeDshConfig(text, connection, { serverId, previousName, enable });
144
+ if (ide === 'opencode') return mergeOpenCodeConfig(text, connection, { serverId, previousName, enable });
145
+ const before = readConfig(text, ide), servers = serverTable(before, ide);
146
+ if (previousName !== serverId && servers?.[serverId]) throw new Error('Craft installation conflicts with an existing ' + serverId + ' registration');
120
147
  const previous = servers?.[previousName] ?? {};
121
148
  if (!object(previous)) throw new Error('Invalid craft server entry');
122
149
  // Preserve host-specific options and user environment; replace only connection identity.
@@ -128,7 +155,7 @@ export function mergeConfig(text, ide, connection, { previousName = 'craft', ena
128
155
  if (ide === 'claude') { delete next.enabled; delete next.timeoutMs; delete next.startupTimeoutMs; }
129
156
  else {
130
157
  next.enabled = true;
131
- if (ide === 'zcode') { delete next.startupTimeoutMs; next = validateZcodeServer(next, 'craft'); }
158
+ if (ide === 'zcode') { delete next.startupTimeoutMs; next = validateZcodeServer(next, serverId); }
132
159
  else { delete next.type; delete next.timeoutMs; delete next.environment_id; next.transport = 'stdio'; next.executor = 'local'; }
133
160
  }
134
161
  } else if (['qwen', 'qoder', 'qoder-cn', 'comate', 'trae'].includes(ide)) {
@@ -140,22 +167,18 @@ export function mergeConfig(text, ide, connection, { previousName = 'craft', ena
140
167
  if (Object.hasOwn(previous, key)) next[key] = previous[key]; else delete next[key];
141
168
  }
142
169
  const normalizedNext = ide === 'codex' ? parse(stringify({ value: next })).value : next;
143
- if (previousName === 'craft' && isDeepStrictEqual(previous, normalizedNext)) return text;
144
- const nextServers = { ...servers, craft: next };
145
- if (previousName !== 'craft') delete nextServers[previousName];
170
+ if (previousName === serverId && isDeepStrictEqual(previous, normalizedNext)) return text;
171
+ const nextServers = { ...servers, [serverId]: next };
172
+ if (previousName !== serverId) delete nextServers[previousName];
146
173
  const expected = withServerTable(before, ide, nextServers);
147
174
  if (ide === 'qwen') {
148
- const output = updateJsoncEntry(text, ['mcpServers'], 'craft', servers?.[previousName], next, { previousName });
175
+ const output = updateJsoncEntry(text, ['mcpServers'], serverId, servers?.[previousName], next, { previousName });
149
176
  if (!isDeepStrictEqual(readConfig(output, ide), expected)) throw new Error('Qwen merge changed unrelated settings; config was preserved');
150
177
  return output;
151
178
  }
152
179
  if (ide !== 'codex') return JSON.stringify(expected, null, 2) + '\n';
153
- const owned = sections(text).filter(({ keys }) => keys[0] === 'mcp_servers' && keys[1] === previousName);
154
- if (before.mcp_servers?.[previousName] && !owned.length) throw new Error('Inline/dotted craft TOML entry: move it to [mcp_servers.craft] before installing; config was preserved');
155
- let kept = '', from = 0;
156
- for (const section of owned) { kept += text.slice(from, section.start); from = section.end; }
157
- kept += text.slice(from);
158
- const output = kept + (kept.endsWith('\n') || !kept ? '' : '\n') + '\n' + stringify({ mcp_servers: { craft: next } });
180
+ const kept = withoutTomlServer(text, before, previousName);
181
+ const output = kept + (kept.endsWith('\n') || !kept ? '' : '\n') + '\n' + stringify({ mcp_servers: { [serverId]: next } });
159
182
  // This also rejects unsupported inline parent tables without changing the user's file.
160
183
  if (!isDeepStrictEqual(parse(output), parse(stringify(expected)))) throw new Error('TOML merge changed unrelated settings; config was preserved');
161
184
  return output;