@craft_eco/craft-mcp 0.1.29 → 0.1.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) hide show
  1. package/README.md +10 -55
  2. package/bin/craft-mcp.mjs +4 -1
  3. package/dist-server/game-workflow/check.mjs +3 -2
  4. package/dist-server/game-workflow/context-state.mjs +67 -67
  5. package/dist-server/game-workflow/draft-archive.mjs +147 -2
  6. package/dist-server/game-workflow/draft-upload-identity.mjs +11 -0
  7. package/dist-server/game-workflow/draft-uploads.mjs +105 -60
  8. package/dist-server/game-workflow/local-context.mjs +62 -62
  9. package/dist-server/game-workflow/native-context.mjs +289 -289
  10. package/dist-server/game-workflow/project-bundles.mjs +246 -246
  11. package/dist-server/game-workflow/project-context.mjs +8 -8
  12. package/dist-server/game-workflow/projects.mjs +6 -4
  13. package/dist-server/game-workflow/tasks.mjs +1 -1
  14. package/dist-server/game-workflow/work-scope.mjs +7 -7
  15. package/dist-server/integrations/config.mjs +145 -145
  16. package/dist-server/integrations/connect.mjs +36 -0
  17. package/dist-server/integrations/connection-handoff.mjs +36 -42
  18. package/dist-server/integrations/dsh-config.mjs +182 -182
  19. package/dist-server/integrations/files.mjs +54 -54
  20. package/dist-server/integrations/fixed-launcher.mjs +31 -0
  21. package/dist-server/integrations/host-reload.mjs +19 -0
  22. package/dist-server/integrations/hosts.mjs +55 -55
  23. package/dist-server/integrations/install.mjs +223 -205
  24. package/dist-server/integrations/installation-state.mjs +84 -84
  25. package/dist-server/integrations/launcher-start.mjs +52 -0
  26. package/dist-server/integrations/npm-diagnostics.mjs +32 -0
  27. package/dist-server/integrations/runtime-gc.mjs +191 -188
  28. package/dist-server/integrations/runtime-identity.mjs +22 -0
  29. package/dist-server/integrations/runtime.mjs +111 -126
  30. package/dist-server/integrations/updates.mjs +258 -225
  31. package/dist-server/integrations/version-policy.mjs +32 -32
  32. package/dist-server/launcher.mjs +1845 -0
  33. package/dist-server/mcp/control-panel.mjs +8 -23
  34. package/dist-server/mcp/server.mjs +31 -80
  35. package/dist-server/mcp/update-session.mjs +107 -92
  36. package/dist-server/upstream/craft-aigc.mjs +43 -16
  37. package/dist-server/upstream/draft-source.mjs +29 -0
  38. package/package.json +3 -2
  39. package/resources/context-filter-report.json +1 -1
  40. package/resources/craft-create/SKILL.md +19 -19
  41. package/resources/craft-update/SKILL.md +9 -11
  42. package/resources/targets/claude/js/bootstrap/SKILL.md +3 -1
  43. package/resources/targets/claude/js/context-filter-report.json +1 -1
  44. package/resources/targets/claude/js/craft-game-maker/SKILL.md +11 -15
  45. package/resources/targets/claude/js/js/bundle.json +7 -7
  46. package/resources/targets/claude/js/recovery.md +5 -1
  47. package/resources/targets/claude/js/target.json +1 -1
  48. package/resources/targets/claude/js3d/bootstrap/SKILL.md +3 -1
  49. package/resources/targets/claude/js3d/context-filter-report.json +1 -1
  50. package/resources/targets/claude/js3d/craft-game-maker/SKILL.md +11 -15
  51. package/resources/targets/claude/js3d/js3d/bundle.json +7 -7
  52. package/resources/targets/claude/js3d/recovery.md +5 -1
  53. package/resources/targets/claude/js3d/target.json +1 -1
  54. package/resources/targets/codebuddy/js/bootstrap/SKILL.md +3 -1
  55. package/resources/targets/codebuddy/js/context-filter-report.json +1 -1
  56. package/resources/targets/codebuddy/js/craft-game-maker/SKILL.md +11 -15
  57. package/resources/targets/codebuddy/js/js/bundle.json +7 -7
  58. package/resources/targets/codebuddy/js/recovery.md +5 -1
  59. package/resources/targets/codebuddy/js/target.json +1 -1
  60. package/resources/targets/codebuddy/js3d/bootstrap/SKILL.md +3 -1
  61. package/resources/targets/codebuddy/js3d/context-filter-report.json +1 -1
  62. package/resources/targets/codebuddy/js3d/craft-game-maker/SKILL.md +11 -15
  63. package/resources/targets/codebuddy/js3d/js3d/bundle.json +7 -7
  64. package/resources/targets/codebuddy/js3d/recovery.md +5 -1
  65. package/resources/targets/codebuddy/js3d/target.json +1 -1
  66. package/resources/targets/codex/js/bootstrap/SKILL.md +2 -4
  67. package/resources/targets/codex/js/context-filter-report.json +1 -1
  68. package/resources/targets/codex/js/craft-game-maker/SKILL.md +11 -15
  69. package/resources/targets/codex/js/js/bundle.json +7 -7
  70. package/resources/targets/codex/js/recovery.md +3 -3
  71. package/resources/targets/codex/js/target.json +1 -1
  72. package/resources/targets/codex/js3d/bootstrap/SKILL.md +2 -4
  73. package/resources/targets/codex/js3d/context-filter-report.json +1 -1
  74. package/resources/targets/codex/js3d/craft-game-maker/SKILL.md +11 -15
  75. package/resources/targets/codex/js3d/js3d/bundle.json +7 -7
  76. package/resources/targets/codex/js3d/recovery.md +3 -3
  77. package/resources/targets/codex/js3d/target.json +1 -1
  78. package/resources/targets/cursor/js/bootstrap/SKILL.md +3 -1
  79. package/resources/targets/cursor/js/context-filter-report.json +1 -1
  80. package/resources/targets/cursor/js/craft-game-maker/SKILL.md +11 -15
  81. package/resources/targets/cursor/js/js/bundle.json +7 -7
  82. package/resources/targets/cursor/js/recovery.md +5 -1
  83. package/resources/targets/cursor/js/target.json +1 -1
  84. package/resources/targets/cursor/js3d/bootstrap/SKILL.md +3 -1
  85. package/resources/targets/cursor/js3d/context-filter-report.json +1 -1
  86. package/resources/targets/cursor/js3d/craft-game-maker/SKILL.md +11 -15
  87. package/resources/targets/cursor/js3d/js3d/bundle.json +7 -7
  88. package/resources/targets/cursor/js3d/recovery.md +5 -1
  89. package/resources/targets/cursor/js3d/target.json +1 -1
  90. package/resources/targets/dsh/js/bootstrap/SKILL.md +3 -1
  91. package/resources/targets/dsh/js/context-filter-report.json +1 -1
  92. package/resources/targets/dsh/js/craft-game-maker/SKILL.md +11 -15
  93. package/resources/targets/dsh/js/js/bundle.json +7 -7
  94. package/resources/targets/dsh/js/recovery.md +5 -1
  95. package/resources/targets/dsh/js/target.json +1 -1
  96. package/resources/targets/dsh/js3d/bootstrap/SKILL.md +3 -1
  97. package/resources/targets/dsh/js3d/context-filter-report.json +1 -1
  98. package/resources/targets/dsh/js3d/craft-game-maker/SKILL.md +11 -15
  99. package/resources/targets/dsh/js3d/js3d/bundle.json +7 -7
  100. package/resources/targets/dsh/js3d/recovery.md +5 -1
  101. package/resources/targets/dsh/js3d/target.json +1 -1
  102. package/resources/targets/index.json +32 -32
  103. package/resources/targets/kimi/js/bootstrap/SKILL.md +3 -1
  104. package/resources/targets/kimi/js/context-filter-report.json +1 -1
  105. package/resources/targets/kimi/js/craft-game-maker/SKILL.md +11 -15
  106. package/resources/targets/kimi/js/js/bundle.json +7 -7
  107. package/resources/targets/kimi/js/recovery.md +5 -1
  108. package/resources/targets/kimi/js/target.json +1 -1
  109. package/resources/targets/kimi/js3d/bootstrap/SKILL.md +3 -1
  110. package/resources/targets/kimi/js3d/context-filter-report.json +1 -1
  111. package/resources/targets/kimi/js3d/craft-game-maker/SKILL.md +11 -15
  112. package/resources/targets/kimi/js3d/js3d/bundle.json +7 -7
  113. package/resources/targets/kimi/js3d/recovery.md +5 -1
  114. package/resources/targets/kimi/js3d/target.json +1 -1
  115. package/resources/targets/workbuddy/js/bootstrap/SKILL.md +22 -24
  116. package/resources/targets/workbuddy/js/context-filter-report.json +1 -1
  117. package/resources/targets/workbuddy/js/craft-game-maker/SKILL.md +11 -15
  118. package/resources/targets/workbuddy/js/js/bundle.json +8 -8
  119. package/resources/targets/workbuddy/js/js/context/AGENTS.md +29 -29
  120. package/resources/targets/workbuddy/js/recovery.md +19 -19
  121. package/resources/targets/workbuddy/js/target.json +1 -1
  122. package/resources/targets/workbuddy/js3d/bootstrap/SKILL.md +22 -24
  123. package/resources/targets/workbuddy/js3d/context-filter-report.json +1 -1
  124. package/resources/targets/workbuddy/js3d/craft-game-maker/SKILL.md +11 -15
  125. package/resources/targets/workbuddy/js3d/js3d/bundle.json +8 -8
  126. package/resources/targets/workbuddy/js3d/js3d/context/AGENTS.md +30 -30
  127. package/resources/targets/workbuddy/js3d/recovery.md +19 -19
  128. package/resources/targets/workbuddy/js3d/target.json +1 -1
  129. package/resources/targets/zcode/js/bootstrap/SKILL.md +3 -1
  130. package/resources/targets/zcode/js/context-filter-report.json +1 -1
  131. package/resources/targets/zcode/js/craft-game-maker/SKILL.md +11 -15
  132. package/resources/targets/zcode/js/js/bundle.json +7 -7
  133. package/resources/targets/zcode/js/recovery.md +5 -1
  134. package/resources/targets/zcode/js/target.json +1 -1
  135. package/resources/targets/zcode/js3d/bootstrap/SKILL.md +3 -1
  136. package/resources/targets/zcode/js3d/context-filter-report.json +1 -1
  137. package/resources/targets/zcode/js3d/craft-game-maker/SKILL.md +11 -15
  138. package/resources/targets/zcode/js3d/js3d/bundle.json +7 -7
  139. package/resources/targets/zcode/js3d/recovery.md +5 -1
  140. package/resources/targets/zcode/js3d/target.json +1 -1
  141. package/vendor/craft-runtime/SOURCE.json +4 -4
  142. package/vendor/craft-runtime/package.json +1 -1
  143. package/dist-server/game-workflow/publication-materials.mjs +0 -92
  144. package/dist-server/game-workflow/publications.mjs +0 -168
  145. package/dist-server/game-workflow/publish-capture-worker.mjs +0 -57
  146. package/dist-server/game-workflow/publish-capture.mjs +0 -75
  147. package/dist-server/mcp/publication-page.html +0 -86
  148. package/dist-server/mcp/publication-page.mjs +0 -375
  149. package/dist-server/mcp/publication-preview.mjs +0 -63
  150. package/dist-server/mcp/publication-tools.mjs +0 -22
  151. package/dist-server/mcp/publish-panel.mjs +0 -210
  152. package/dist-server/upstream/publication-transport.mjs +0 -101
@@ -3,12 +3,12 @@ import { randomBytes } from 'node:crypto';
3
3
  import { readFile } from 'node:fs/promises';
4
4
  import { sendJson, parseJsonBody } from '../core/http-utils.mjs';
5
5
 
6
- export async function openControlPanel(platform,{ allowLocalAuth=true,publishPanel,publicationDirectory=new URL('./',import.meta.url) }={}) {
6
+ export async function openControlPanel(platform,{ allowLocalAuth=true }={}) {
7
7
  const csrf=randomBytes(32).toString('hex');
8
8
  const template=await readFile(new URL('./control-panel.html',import.meta.url),'utf8');
9
9
  let port,origin,activeRequests=0;
10
- const secure=(res,frameOrigin)=>{
11
- res.setHeader('Content-Security-Policy',`default-src 'none'; script-src 'nonce-${csrf}'; style-src 'unsafe-inline'; connect-src 'self'; img-src 'self' data: blob:; frame-src ${frameOrigin || "'none'"}; frame-ancestors 'none'; base-uri 'none'; form-action 'self'`);
10
+ const secure=res=>{
11
+ res.setHeader('Content-Security-Policy',`default-src 'none'; script-src 'nonce-${csrf}'; style-src 'unsafe-inline'; connect-src 'self'; img-src 'self' data: blob:; frame-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'`);
12
12
  };
13
13
  const server=http.createServer(async(req,res)=>{
14
14
  activeRequests++;
@@ -19,36 +19,21 @@ export async function openControlPanel(platform,{ allowLocalAuth=true,publishPan
19
19
  }
20
20
  try {
21
21
  const url=new URL(req.url,origin);
22
- const page=/^\/publish\/([A-Za-z0-9_-]{43})$/.exec(url.pathname);
23
- if(publishPanel && req.method==='GET' && page) {
24
- const data=await publishPanel.document(page[1]);
25
- const html=await readFile(new URL('publication-page.html',publicationDirectory),'utf8');
26
- secure(res,data.runtime_url ? new URL(data.runtime_url).origin : undefined);
27
- res.writeHead(200,{'Content-Type':'text/html; charset=utf-8'});
28
- res.end(html.replaceAll('__CSRF__',csrf).replaceAll('__PUBLISH_CAP__',page[1]));return;
29
- }
30
- if(publishPanel && req.method==='GET' && url.pathname==='/publication-page.mjs') {
31
- const script=await readFile(new URL('publication-page.mjs',publicationDirectory));
32
- res.writeHead(200,{'Content-Type':'text/javascript; charset=utf-8'});res.end(script);return;
33
- }
34
22
  if(req.method==='GET' && url.pathname==='/') {
35
23
  if(!allowLocalAuth) {sendJson(res,404,{error:'Update credentials in the host AI IDE Craft MCP settings and reconnect'});return;}
36
24
  secure(res);res.writeHead(200,{'Content-Type':'text/html; charset=utf-8'});res.end(template.replaceAll('__CSRF__',csrf));return;
37
25
  }
38
26
  if(req.method==='GET' && url.pathname==='/data') {sendJson(res,200,await platform.status());return;}
39
- const api=/^\/api\/publish\/([A-Za-z0-9_-]{43})\/(state|cover|prepare|review|submit|status|task)$/.exec(url.pathname);
40
27
  const auth=allowLocalAuth && ['/login','/logout'].includes(url.pathname);
41
28
  if(req.method==='POST') {
42
- if((!api || !publishPanel) && !auth) {req.resume();sendJson(res,404,{error:'Not found'});return;}
29
+ if(!auth) {req.resume();sendJson(res,404,{error:'Not found'});return;}
43
30
  if(req.headers.origin!==origin || req.headers['x-craft-csrf']!==csrf || req.headers['content-type']!=='application/json') {
44
31
  req.resume();sendJson(res,403,{error:'Invalid local control request'});return;
45
32
  }
46
- const body=await parseJsonBody(req,api?.[2] === 'cover' ? 3*1024*1024 : api ? 64*1024 : 8192);
47
- const result=api ? await publishPanel.handle(api[1],api[2],req.method,url.searchParams,body) :
48
- url.pathname==='/login' ? await platform.login(body.token) : platform.logout();
33
+ const body=await parseJsonBody(req,8192);
34
+ const result=url.pathname==='/login' ? await platform.login(body.token) : platform.logout();
49
35
  sendJson(res,200,result);return;
50
36
  }
51
- if(publishPanel && api) {sendJson(res,200,await publishPanel.handle(api[1],api[2],req.method,url.searchParams));return;}
52
37
  req.resume();sendJson(res,404,{error:'Not found'});
53
38
  } catch(error) {
54
39
  sendJson(res,Number.isInteger(error.status) && error.status>=400 && error.status<600 ? error.status : 400,
@@ -57,6 +42,6 @@ export async function openControlPanel(platform,{ allowLocalAuth=true,publishPan
57
42
  } finally { activeRequests--; }
58
43
  });
59
44
  await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(0,'127.0.0.1',resolve);});
60
- port=server.address().port;origin=`http://127.0.0.1:${port}`;publishPanel?.bindOrigin(origin);
61
- return {url:origin,get activeRequests(){return activeRequests;},close:async()=>{await publishPanel?.close();server.closeAllConnections();await new Promise(resolve=>server.close(resolve));}};
45
+ port=server.address().port;origin=`http://127.0.0.1:${port}`;
46
+ return {url:origin,get activeRequests(){return activeRequests;},close:async()=>{server.closeAllConnections();await new Promise(resolve=>server.close(resolve));}};
62
47
  }
@@ -18,16 +18,12 @@ import { libraryCapabilities } from '../game-workflow/library-catalog.mjs';
18
18
  import { checkGame, validateSteps } from '../game-workflow/check.mjs';
19
19
  import { DraftUploads, draftUploadView } from '../game-workflow/draft-uploads.mjs';
20
20
  import { DraftBindings } from '../game-workflow/draft-bindings.mjs';
21
- import { Publications } from '../game-workflow/publications.mjs';
22
21
  import { Previews } from '../preview/local-static-preview.mjs';
23
22
  import { openControlPanel } from './control-panel.mjs';
24
- import { createPublishPanel } from './publish-panel.mjs';
25
- import { openPublicationPreview } from './publication-preview.mjs';
26
23
  import { loadEngineResources, loadEngineResource } from '../game-workflow/engines.mjs';
27
24
  import { assetCapabilities } from '../game-workflow/resource-catalog.mjs';
28
25
  import { takeConnectorToken, ConnectorAuthStore, connectorLoginAction } from '../core/connector-auth.mjs';
29
26
  import { generationFields, importFields, generationInputs, searchFields, importSource } from './asset-tools.mjs';
30
- import { publicationTools } from './publication-tools.mjs';
31
27
  import { clientIde } from '../integrations/hosts.mjs';
32
28
  import { currentWork, withWork, guardWork } from '../game-workflow/work-scope.mjs';
33
29
  import { getRuntimeIdentity } from '../integrations/runtime.mjs';
@@ -61,8 +57,6 @@ const reviewed = new Set();
61
57
  const uploadStore = new RequestStore(path.join(state,'uploads'),root); await uploadStore.init();
62
58
  const resourcePaths = { capture:path.join(resources,'game_visual_qa.mjs'), evidence:path.join(path.dirname(uploadStore.directory),'checks') };
63
59
  const drafts = new DraftUploads(platform,uploadStore,resourcePaths.evidence,new DraftBindings(getProjectBindingsDir(),root));
64
- const publicationStore = new RequestStore(path.join(state,'publications'),root); await publicationStore.init();
65
- const publications = new Publications(platform,publicationStore,drafts,resourcePaths.evidence);
66
60
  const mutations = new Set();
67
61
  let closing = false;
68
62
  let authInteraction=false;
@@ -70,24 +64,11 @@ async function validateWork(work,{preparing=false}={}) {
70
64
  await leases.assert(work.name,work.work_id,{ready:!preparing,context_revision:work.context_revision});
71
65
  if(!preparing) await projects.assertRevision(work.name,work.context_revision);
72
66
  }
73
- async function mutateProject(name,operation,work) {
74
- projects.file(name);
75
- if (closing || mutations.has(name) || tasks.busy(name)) throw new Error('Project has a running operation');
76
- mutations.add(name);
77
- try {
78
- if(!work || work.name!==name) throw new Error('Publication page requires its original prepared work; reopen after preparing a new work');
79
- await validateWork(work);
80
- return await withWork(work,()=>validateWork(work),async()=>{const result=await operation(); await guardWork(); return result;});
81
- }
82
- finally { mutations.delete(name); }
83
- }
84
- const publishPanel=createPublishPanel({ platform,projects,tasks,drafts,publications,checkedTask,mutate:mutateProject,viewTask,
85
- coverDirectory:path.join(state,'publication-covers'),preview:async check=>openPublicationPreview(check,resourcePaths.evidence,undefined,{ assetOrigins:await assets.approvedResourceOrigins(check.name),platformOrigin:platform.base }) });
86
- const panel=await openControlPanel(platform,{ allowLocalAuth:!connectorAuth,publishPanel });
67
+ const panel=await openControlPanel(platform,{ allowLocalAuth:!connectorAuth });
87
68
  function runtimeBusy({excludeUpdate=false}={}) {
88
69
  if(platform.store.getSession().loggedIn) authInteraction=false;
89
70
  const busy={work_count:leases.activeCount,task_count:tasks.activeCount,mutation_count:mutations.size,
90
- interaction_count:panel.activeRequests+publishPanel.activeCount+Number(authInteraction),
71
+ interaction_count:panel.activeRequests+Number(authInteraction),
91
72
  update_count:Math.max(0,updates.activeOperations-Number(excludeUpdate))};
92
73
  return {...busy,can_reconnect:!closing && Object.values(busy).every(count=>count===0)};
93
74
  }
@@ -108,11 +89,14 @@ const nameField = { name:{ type:'string', pattern:'^[a-z][a-z0-9-]{0,47}$', desc
108
89
  const engineField = { engine:{ type:'string',enum:['js','js3d'],description:'Choose js for 2D/Phaser, js3d for 3D/Three.js. New games default to js; existing games keep their saved engine. Never change an existing game engine.' } };
109
90
  const taskField = { task_id:{ type:'string' } };
110
91
  const workField = {work_id:{type:'string',description:'Exact work_id from the completed prepare. Keep it for this editing work; release when finished.'}};
111
- const workTools=new Set(['craft_assets_generate','craft_assets_search','craft_assets_import','craft_game_check','craft_game_review','craft_game_deliver','craft_game_upload','craft_game_publish_prepare','craft_game_publish_review','craft_game_publish_submit','craft_game_publish_open','craft_preview_stop','craft_task_cancel']);
112
- const draftFields = { ...nameField, check_task_id:{ type:'string', description:'ID of the passing check for this exact draft build. Reuse the same ID to recover an upload.' } };
113
- const tool = (name,description,properties={},required=[])=>({ name,description,inputSchema:{ type:'object',properties:{...properties,...(workTools.has(name)?workField:{})},required:[...required,...(workTools.has(name)?['work_id']:[])],additionalProperties:false },...(name==='craft_game_info'?{annotations:{readOnlyHint:true,destructiveHint:false,idempotentHint:true}}:{}) });
92
+ const workTools=new Set(['craft_assets_generate','craft_assets_search','craft_assets_import','craft_game_check','craft_game_review','craft_game_deliver','craft_game_upload','craft_preview_stop','craft_task_cancel']);
93
+ const draftFields = { ...nameField, check_task_id:{ type:'string', description:'ID of the passing check for this exact draft build. Reuse the same ID to recover an upload.' },
94
+ upload_mode:{type:'string',enum:['current_project','new_project'],description:'Defaults to current_project: append a version using local source/dist and make it current, without merging Web edits. Use new_project only when the user explicitly asks for a new cloud project; success switches the local binding.'},
95
+ request_key:{type:'string',pattern:'^[A-Za-z0-9_-]{1,80}$',description:'Required for new_project. Create a new key for an explicitly new upload operation; reuse the exact key, mode and check_task_id on retry or status queries.'} };
96
+ const tool = (name,description,properties={},required=[])=>({ name,description,inputSchema:{ type:'object',properties:{...properties,...(workTools.has(name)?workField:{})},required:[...required,...(workTools.has(name)?['work_id']:[])],additionalProperties:false },...(['craft_game_info','craft_update_check'].includes(name)?{annotations:{readOnlyHint:true,destructiveHint:false,idempotentHint:true}}:name==='craft_update'?{annotations:{readOnlyHint:false,destructiveHint:false}}:{}) });
114
97
  const tools = [
115
- tool('craft_update_check','Check the configured npm channel at the first Craft request of a new session. inspect only checks and may save a private check receipt; it never installs, reconnects or changes global Skills or projects. create/resume/update install compatible newer releases when enabled. pending_reconnect means the new package is installed but this connection remains on its original package; no requested game operation has started. Follow connection_handoff after this call returns: recheck current busy state and host rules, use a real available Codex host reload capability once, otherwise prompt for reconnect/restart. WorkBuddy may require full tray exit; request trust only if the host actually prompts. Verify current-chat version/build_id/instance_id/active_verified and host scope, then retry only unstarted prepare with the same request_key and reread local context. Never replay paid operations.',{...nameField,intent:{type:'string',enum:['inspect','create','resume','update']},request_key:{type:'string'}},['intent']),
98
+ tool('craft_update_check','Read-only check of the configured npm channel, actual running version, installed target and optional existing project compatibility. Never installs, writes receipts or updates project files. At the first Craft task in a session, check with its request_key. If update_available and automatic_update_enabled, call craft_update with the same key. A newer installed target takes effect at the next MCP start or user reconnect.',{...nameField,request_key:{type:'string'}}),
99
+ tool('craft_update','Download, verify and install a compatible newer release, preserving the running process and current work. mode=auto (default) respects the configured policy; manual is only for an explicit user update request. Pass an existing project name for compatibility checking and reuse the check request_key. pending_reconnect means installed, not running: wait for next MCP start or user reconnect, then verify actual version/build_id/active_verified and host scope with craft_game_info before new preparation. Do not reload automatically or replay paid operations. prepare(resume) then refreshes the project context and Skills.',{...nameField,request_key:{type:'string'},mode:{type:'string',enum:['auto','manual']}},['request_key']),
116
100
  tool('craft_game_info','Read-only inspection of installed or project context, versions, integrity, preparation, occupancy and preview. Never updates or registers a project and never acquires editing ownership. full_integrity=true checks managed files without repairing. To edit, call prepare mode=create/resume; to inspect only, read existing files without prepare.',{...nameField,...engineField,full_integrity:{type:'boolean'}}),
117
101
  tool('craft_game_prepare','Begin an editing work. create requires a new directory and installs dependencies; resume requires an existing Craft game, synchronizes compatible installed context and recovery entries without reseeding, installing dependencies or building. Reuse request_key for retries; pass work_id to inspect the same active work without upgrading it. Poll prepare completion, retain work_id/context_revision, and reread returned local context before editing. Release when finished.',{...nameField,...engineField,...workField,mode:{type:'string',enum:['create','resume']},request_key:{type:'string'}},['name','mode','request_key']),
118
102
  tool('craft_game_release','Finish this editing work after all background tasks complete or are cancelled and cleaned up. Releases ownership without disconnecting MCP or stopping a preview. Does not accept or publish a game. Idempotent for the exact ended work_id.',{...nameField,...workField},['name','work_id']),
@@ -133,11 +117,8 @@ const tools = [
133
117
  tool('craft_game_deliver','Prepare a verified preview after a current passing check and visual review. Craft does not launch the process. Run result.start.script with the external host terminal tool in the background, then poll craft_game_info(name).preview until running=true and snapshot matches this delivery. Verify the page before reporting its URL. The host or OS may reclaim it; restart using the returned command.',{
134
118
  ...taskField,visual_passed:{ type:'boolean' },visual_notes:{ type:'string',minLength:10,maxLength:2000 },
135
119
  },['task_id','visual_passed','visual_notes']),
136
- tool('craft_game_upload','When the user asks to upload, transfer the frozen build from a current passing check to a private Craft draft. The same local project, account and platform automatically reuse the saved app ID and append a version. Poll craft_task_status. Reuse the same check_task_id after interruption. draft_ready means the private upload is complete, not published. Use craft_game_deliver and the IDE terminal for local preview.',draftFields,['name','check_task_id']),
137
- tool('craft_game_publish_status','Query publication review with publication_id, or private upload status with check_task_id. Supply exactly one ID. Only report public publication after this specific version reaches share_completed and returns its verified public_url.',{
138
- ...draftFields,publication_id:{ type:'string' },
139
- },['name']),
140
- ...publicationTools(nameField,tool),
120
+ tool('craft_game_upload','Before uploading, tell the user that local source/dist will become the current cloud version and Web edits not synced locally are not included; history remains available for rollback. Default: append to the bound project (create on first upload). Only explicit user requests select new_project. Poll craft_task_status; retry with the same check_task_id, upload_mode and request_key. On success report version_number (vN), appid and project_url; publication remains in Craft Web.',draftFields,['name','check_task_id']),
121
+ tool('craft_game_upload_status','Read the private upload receipt for this check, including the Craft Web project link when complete.',draftFields,['name','check_task_id']),
141
122
  tool('craft_preview_stop','Stop this project host-launched preview and cancel pending starts, including an earlier session preview.',nameField,['name']),
142
123
  tool('craft_auth_open','Check login first. Return a login URL only when unauthenticated; an authenticated account continues without a login URL. Image generation uses automatic platform billing. Never read credentials or automate login.'),
143
124
  tool('craft_auth_status','Check the Craft account without exposing credentials.'),
@@ -158,13 +139,13 @@ server.oninitialized=()=>{
158
139
  };
159
140
  server.setRequestHandler(ListToolsRequestSchema,async()=>({ tools }));
160
141
  function viewTask(task) {
161
- if (['upload','publish_prepare','publish_submit'].includes(task.kind)) {
142
+ if (task.kind === 'upload') {
162
143
  if (task.owner !== platform.account().user_id || task.platform !== platform.base) throw new Error('Draft task belongs to a different account or platform');
163
144
  const { owner, platform:target, ...view } = task;
164
- return task.kind === 'upload' && view.result ? { ...view,result:draftUploadView(view.result) } : view;
145
+ return view.result ? { ...view,result:draftUploadView({ ...view.result,platform:target }) } : view;
165
146
  }
166
147
  if (!task.result?.artifacts) return task;
167
- const { artifacts,snapshot_id,...result } = task.result;
148
+ const { artifacts,snapshot_id,source_snapshot,...result } = task.result;
168
149
  return { ...task,result };
169
150
  }
170
151
  async function checkedTask(id, name, resumeUpload = false) {
@@ -191,11 +172,13 @@ server.setRequestHandler(CallToolRequestSchema,async request=>{
191
172
  if (!field || (field.type === 'integer' ? !Number.isSafeInteger(value) : field.type === 'array' ? !Array.isArray(value) : typeof value !== field.type) || (field.enum && !field.enum.includes(value))) throw new Error('Invalid argument: ' + key);
192
173
  }
193
174
  for (const key of definition.inputSchema.required) if (args[key] === undefined) throw new Error('Missing argument: ' + key);
194
- let work;
175
+ let work, updateWarning;
195
176
  const preparing=definition.name==='craft_game_prepare';
196
177
  if(preparing) {
197
178
  projects.file(args.name);
198
179
  if(!args.work_id && !leases.hasRequest(args.name,args.request_key)) {
180
+ // Another work may still be creating the files inspected by the update check.
181
+ if((await leases.observe(args.name)).occupied) throw Object.assign(new Error('This project has an active work. Wait for it to finish and release before preparing another work.'),{detail:{code:'CRAFT_PROJECT_IN_USE'}});
199
182
  const update=await updates.check({name:args.name,intent:args.mode,request_key:args.request_key});
200
183
  if(closing) throw new Error('Craft is shutting down; project work was not started');
201
184
  if(update.can_continue===false || ['pending_reconnect','incompatible','error'].includes(update.status)) {
@@ -204,6 +187,7 @@ server.setRequestHandler(CallToolRequestSchema,async request=>{
204
187
  next:update.next ?? 'Resolve the update diagnostic, then retry this prepare with the same request_key. No project work was acquired.'};
205
188
  return {content:[{type:'text',text:JSON.stringify(blocked)}]};
206
189
  }
190
+ if (['update_failed','offline'].includes(update.status)) updateWarning=update;
207
191
  }
208
192
  work=await leases.acquire(args.name,{...args,host});
209
193
  if(work.task_id) {
@@ -224,7 +208,8 @@ server.setRequestHandler(CallToolRequestSchema,async request=>{
224
208
  return await withWork(work,work ? ()=>validateWork(work,{preparing:preparing || definition.name==='craft_task_cancel'}) : undefined,async()=>{
225
209
  let result;
226
210
  switch (definition.name) {
227
- case 'craft_update_check': result=await updates.check(args); break;
211
+ case 'craft_update_check': result=await updates.inspect(args); break;
212
+ case 'craft_update': result=await updates.install(args); break;
228
213
  case 'craft_game_info': {
229
214
  const occupancy=args.name ? await leases.observe(args.name) : undefined;
230
215
  const project = args.name ? await projects.inspect(args.name,{full:args.full_integrity===true}) : undefined;
@@ -242,8 +227,7 @@ server.setRequestHandler(CallToolRequestSchema,async request=>{
242
227
  context_binding:project?.context_binding,
243
228
  version_status:project?.version_status,integrity:project?.integrity,preparation:project?.preparation,registration_required:project?.registration_required,occupancy,project_context:project?.project_context,
244
229
  project:project?.project, preview:project ? await previews.status(project.project) : undefined,
245
- llm:'external AI IDE host', images:'Craft platform', aigc:assetCapabilities(selected?.engine),library:libraryCapabilities(selected?.engine),publishing:true,draft_upload:true,
246
- publication:{ local_page:true,open_tool:'craft_game_publish_open',requires:'Open the independent local page to preview the frozen build and confirm its exact reviewed materials; platform publish_enabled and ACE gates',material_visibility:'public_on_upload' },
230
+ llm:'external AI IDE host', images:'Craft platform', aigc:assetCapabilities(selected?.engine),library:libraryCapabilities(selected?.engine),draft_upload:true,publish_in_web:true,
247
231
  concurrency:{workspace_sessions:'multiple',project_works:1,readonly_queries:'unlocked',release:'craft_game_release(name, work_id); abnormal process exit expires within 30 seconds'},
248
232
  lifecycle:{version:1,prepare_modes:['create','resume'],request_key_required:true,work_id_required:true,query_updates_context:false},
249
233
  instructions:project ? 'Read-only query. For editing, prepare mode=resume, poll to completion, then read the returned local context and keep work_id until release. An inspection alone does not authorize editing.' : selected?.instructions ?? guide, context:project?.context ?? selected?.context ?? {workflow:bootstrapWorkflow,target:{host,scope:'bootstrap'}},
@@ -257,15 +241,16 @@ server.setRequestHandler(CallToolRequestSchema,async request=>{
257
241
  if(project.created) await installProjectDependencies(project.project,undefined,signal);
258
242
  const selected=await projects.resourcesFor(project);
259
243
  await leases.update(args.name,work.work_id,{status:'active',context_revision:project.context_revision});
260
- return {...project,work_id:work.work_id,workspace:root,instructions:selected.instructions,context:{...selected.context,...(project.context_sync?{sync:project.context_sync}:{})},next:'Read the returned project-local workflow, engine entrypoint and skill index now. Retain work_id/context_revision throughout editing and pass work_id to workflow tools. After completing or pausing edits, record progress and call craft_game_release. A later editing task must prepare mode=resume again; an info query never updates context.'};
244
+ return {...project,...(updateWarning?{update_warning:updateWarning}:{}),work_id:work.work_id,workspace:root,instructions:selected.instructions,context:{...selected.context,...(project.context_sync?{sync:project.context_sync}:{})},next:'Read the returned project-local workflow, engine entrypoint and skill index now. Retain work_id/context_revision throughout editing and pass work_id to workflow tools. After completing or pausing edits, record progress and call craft_game_release. A later editing task must prepare mode=resume again; an info query never updates context.'};
261
245
  } catch(error) {await leases.release(args.name,work.work_id,'failed').catch(()=>{}); throw error;}
262
246
  });
263
247
  await leases.update(args.name,work.work_id,{task_id:result.task_id});
248
+ if(updateWarning) result={...result,update_warning:updateWarning};
264
249
  break;
265
250
  }
266
251
  case 'craft_game_release': {
267
252
  if(mutations.has(args.name) || tasks.busy(args.name)) throw new Error('Background work is running; wait or cancel and wait for cleanup before release');
268
- result=await leases.release(args.name,args.work_id); await publishPanel.releaseWork(args.work_id); break;
253
+ result=await leases.release(args.name,args.work_id); break;
269
254
  }
270
255
  case 'craft_assets_generate': {
271
256
  const inputs=generationInputs(args);
@@ -307,7 +292,7 @@ server.setRequestHandler(CallToolRequestSchema,async request=>{
307
292
  case 'craft_task_status': result = viewTask(await tasks.get(args.task_id,args.wait_ms ?? 15000)); break;
308
293
  case 'craft_task_cancel': {
309
294
  const current = await tasks.get(args.task_id);
310
- if (['upload','publish_prepare','publish_submit'].includes(current.kind)) viewTask(current);
295
+ if (current.kind === 'upload') viewTask(current);
311
296
  await leases.assert(current.name,args.work_id,{ready:false});
312
297
  const task = await tasks.cancel(args.task_id);
313
298
  result = viewTask(task);
@@ -315,8 +300,7 @@ server.setRequestHandler(CallToolRequestSchema,async request=>{
315
300
  try { result.remote = await assets.cancelRemote(task.name,task.request_keys); }
316
301
  catch (error) { result.remote_cancellation_confirmed = false; result.remote_error = error.message; }
317
302
  }
318
- if (task.kind === 'upload') result.next = 'Check craft_game_publish_status before retrying. A remote draft may already exist.';
319
- if (task.kind === 'publish_submit') result.next = 'Query craft_game_publish_status with the original publication_id. Cancellation does not retract a remote review or public version.';
303
+ if (task.kind === 'upload') result.next = 'Check craft_game_upload_status before retrying. A remote draft may already exist.';
320
304
  break;
321
305
  }
322
306
  case 'craft_game_review': {
@@ -337,49 +321,16 @@ server.setRequestHandler(CallToolRequestSchema,async request=>{
337
321
  const status = await platform.status();
338
322
  if (!status.authenticated) { result = loginAction(); break; }
339
323
  // An already authorized upload resumes its frozen check, even after later source edits.
340
- const resume = await drafts.hasRequest(args.name,args.check_task_id,status.user_id);
324
+ const resume = await drafts.hasRequest(args.name,args.check_task_id,status.user_id,args);
341
325
  const { task } = await checkedTask(args.check_task_id,args.name,resume);
342
- result = viewTask(await tasks.start(args.name,'upload',signal=>drafts.upload(task,status.user_id,signal),
343
- { owner:status.user_id, platform:platform.base, check_task_id:args.check_task_id }));
326
+ result = viewTask(await tasks.start(args.name,'upload',signal=>drafts.upload(task,status.user_id,signal,args),
327
+ { owner:status.user_id, platform:platform.base, check_task_id:args.check_task_id,upload_mode:args.upload_mode ?? 'current_project',request_key:args.request_key }));
344
328
  break;
345
329
  }
346
- case 'craft_game_publish_status': {
330
+ case 'craft_game_upload_status': {
347
331
  projects.file(args.name);
348
- if (Boolean(args.check_task_id) === Boolean(args.publication_id)) throw new Error('Supply exactly one of check_task_id or publication_id');
349
- const status = await platform.status();
350
- result = status.authenticated ? args.publication_id
351
- ? await publications.status(args.name,args.publication_id,status.user_id)
352
- : await drafts.status(args.name,args.check_task_id,status.user_id) : loginAction();
353
- break;
354
- }
355
- case 'craft_game_publish_open': {
356
- const status=await platform.status();
357
- result=status.authenticated ? await publishPanel.open(args.name,args.check_task_id,args.publication_id) : loginAction(); break;
358
- }
359
- case 'craft_game_publish_options': {
360
- const status = await platform.status();
361
- result = status.authenticated ? { ...await platform.publicationSession(status.user_id)('options'),
362
- minimum_playtest_seconds:30,display_screenshots:{ minimum:1,maximum:5 },material_visibility:'public_on_upload' } : loginAction();
363
- break;
364
- }
365
- case 'craft_game_publish_prepare': {
366
- const status = await platform.status();
367
- if (!status.authenticated) { result = loginAction(); break; }
368
- const { task,project } = await checkedTask(args.check_task_id,args.name,await drafts.hasRequest(args.name,args.check_task_id,status.user_id));
369
- result = viewTask(await tasks.start(args.name,'publish_prepare',signal=>publications.prepare(task,project,args.materials,status.user_id,signal),
370
- { owner:status.user_id,platform:platform.base,check_task_id:args.check_task_id }));
371
- break;
372
- }
373
- case 'craft_game_publish_review': {
374
332
  const status = await platform.status();
375
- if (!status.authenticated) { result = loginAction(); break; }
376
- return await publications.review(args.name,args.publication_id,status.user_id);
377
- }
378
- case 'craft_game_publish_submit': {
379
- const status = await platform.status();
380
- if (!status.authenticated) { result = loginAction(); break; }
381
- result = viewTask(await tasks.start(args.name,'publish_submit',signal=>publications.submit(args.name,args.publication_id,args.revision,args.confirmed,status.user_id,signal),
382
- { owner:status.user_id,platform:platform.base,publication_id:args.publication_id }));
333
+ result = status.authenticated ? await drafts.status(args.name,args.check_task_id,status.user_id,undefined,args) : loginAction();
383
334
  break;
384
335
  }
385
336
  case 'craft_preview_stop': await guardWork(); result = await previews.stop(await projects.owned(args.name)); break;
@@ -1,92 +1,107 @@
1
- import path from 'node:path';
2
- import { isDeepStrictEqual } from 'node:util';
3
- import { loadEngineResources } from '../game-workflow/engines.mjs';
4
- import { readContextLock, checkProjectCompatibility } from '../game-workflow/project-bundles.mjs';
5
- import { checkForUpdate, readUpdateStatus, readInstallation, confirmActiveInstallation } from '../integrations/updates.mjs';
6
- import { connectionHandoff } from '../integrations/connection-handoff.mjs';
7
-
8
- // This connection owns one complete package for its entire lifetime. An
9
- // installer probe or another connection can never replace its runtime identity.
10
- export class UpdateSession {
11
- constructor({installationFile, current, projects, host, workspace, platform, busy}) {
12
- Object.assign(this,{installationFile,current,projects,host,workspace,platform,busy});
13
- this.operations=new Set();
14
- this.closing=false;
15
- }
16
- get activeOperations() { return this.operations.size; }
17
- run(operation) {
18
- if(this.closing) return Promise.resolve({status:'error',code:'connection_closing',message:'Craft is shutting down; reconnect before starting new work',
19
- current:this.current,can_continue:false,activation_required:false,explicitly_not_started:true});
20
- const pending=Promise.resolve().then(operation);
21
- this.operations.add(pending);
22
- return pending.finally(()=>this.operations.delete(pending));
23
- }
24
- async close() {
25
- this.closing=true;
26
- // Installation/Skill/config commits and connection receipts must finish or
27
- // roll back before the process acknowledges a graceful shutdown.
28
- await Promise.allSettled([...this.operations]);
29
- }
30
- async scopeError() {
31
- if(!this.installationFile) return null;
32
- try {
33
- const state=await readInstallation(this.installationFile);
34
- const normalize=value=>{const resolved=path.resolve(value);return process.platform==='win32'?resolved.toLowerCase():resolved;};
35
- if(state.host!==this.host || normalize(state.workspace)!==normalize(this.workspace) || new URL(state.platform).origin!==new URL(this.platform).origin) throw new Error('Craft installation host, workspace or platform differs from this connection; run install with the intended scope and reconnect');
36
- return null;
37
- } catch(error) {return {status:'error',code:'installation_scope_mismatch',message:error.message,current:this.current,can_continue:false,activation_required:false};}
38
- }
39
- async status() {
40
- const error=await this.scopeError();if(error) return error;
41
- if(this.connectionError) return this.connectionError;
42
- return this.withHandoff({...await readUpdateStatus({installationFile:this.installationFile,current:this.current}),
43
- ...(this.last ? {last_check:this.last} : {})},{intent:'inspect'});
44
- }
45
- withHandoff(result,{intent='inspect',name,request_key,excludeUpdate=false}={}) {
46
- if(!result.reconnect_required || !result.target || ['error','incompatible','migration_required'].includes(result.status)) return result;
47
- const busy=this.busy?.({excludeUpdate});
48
- const handoff=connectionHandoff({host:this.host,target:result.target,current:this.current,workspace:this.workspace,platform:this.platform,
49
- busy,intent,name,requestKey:request_key});
50
- return {...result,...(busy?{busy}:{}),connection_handoff:handoff,next:handoff.next};
51
- }
52
- connected() { return this.run(()=>this.confirmConnection()); }
53
- async confirmConnection() {
54
- if(!this.installationFile) return {status:'unmanaged'};
55
- const error=await this.scopeError();if(error) return this.connectionError=error;
56
- try {
57
- const status=await readUpdateStatus({installationFile:this.installationFile,current:this.current});
58
- if(status.status==='error') return this.connectionError=status;
59
- if(status.activation?.status!=='active_verified') return this.withHandoff(status,{excludeUpdate:true});
60
- return await confirmActiveInstallation({installationFile:this.installationFile,current:this.current});
61
- }
62
- catch(error) {
63
- return this.connectionError={status:'error',code:'connection_verification_failed',message:error.message,current:this.current,
64
- can_continue:false,activation_required:false,reconnect_required:true,explicitly_not_started:true};
65
- }
66
- }
67
- check(args={}) { return this.run(()=>this.checkCurrent(args)); }
68
- async checkCurrent({name,intent='inspect',request_key}={}) {
69
- const error=await this.scopeError();if(error) return error;
70
- if(this.connectionError) return this.connectionError;
71
- if(name!==undefined) this.projects.file(name);
72
- if(intent==='resume' && !name) throw new Error('Project name is required when checking a resume');
73
- if(request_key!==undefined && !/^[a-zA-Z0-9._:-]{1,128}$/.test(request_key)) throw new Error('Invalid update request_key');
74
- const project=name && ['inspect','resume','update'].includes(intent) ? await this.projects.inspect(name) : null;
75
- const projectCompatibility=project ? async packageRoot=>{
76
- const {engines}=await loadEngineResources(path.join(packageRoot,'resources'),this.host);
77
- const candidate=engines[project.engine];
78
- await checkProjectCompatibility(project.project,candidate.bundle);
79
- const lock=await readContextLock(project.project,project.engine);
80
- if(lock?.schema>=2 && !isDeepStrictEqual(lock.compatibility,candidate.bundle.compatibility)) throw new Error('New Craft context is incompatible with this project; keep its engine and migrate explicitly');
81
- const previous=lock?.contexts?.[this.host];
82
- if(previous && previous.bundle_id!==candidate.bundle.id) {
83
- const difference=candidate.bundle.version.split('.').map((value,i)=>Number(value)-Number(previous.version?.split('.')[i])).find(value=>value!==0)??0;
84
- if(!Number.isFinite(difference)||difference<=0) throw new Error('Candidate context is older or has a conflicting version for this project');
85
- }
86
- } : undefined;
87
- const result=await checkForUpdate({installationFile:this.installationFile,current:this.current,intent,
88
- requestKey:request_key ? `${intent==='create'?'create':`${name??'global'}:${intent}`}:${request_key}` : undefined,projectCompatibility});
89
- this.last=this.withHandoff(result,{intent,name,request_key,excludeUpdate:true});
90
- return this.last;
91
- }
92
- }
1
+ import path from 'node:path';
2
+ import { isDeepStrictEqual } from 'node:util';
3
+ import { loadEngineResources } from '../game-workflow/engines.mjs';
4
+ import { readContextLock, checkProjectCompatibility } from '../game-workflow/project-bundles.mjs';
5
+ import { checkForUpdate, readUpdateStatus, readInstallation, confirmActiveInstallation } from '../integrations/updates.mjs';
6
+ import { connectionHandoff } from '../integrations/connection-handoff.mjs';
7
+
8
+ // This connection owns one complete package for its entire lifetime. An
9
+ // installer probe or another connection can never replace its runtime identity.
10
+ export class UpdateSession {
11
+ constructor({installationFile, current, projects, host, workspace, platform, busy}) {
12
+ Object.assign(this,{installationFile,current,projects,host,workspace,platform,busy});
13
+ this.operations=new Set();
14
+ this.receipts=new Map();
15
+ this.closing=false;
16
+ }
17
+ get activeOperations() { return this.operations.size; }
18
+ run(operation) {
19
+ if(this.closing) return Promise.resolve({status:'error',code:'connection_closing',message:'Craft is shutting down; reconnect before starting new work',
20
+ current:this.current,can_continue:false,activation_required:false,explicitly_not_started:true});
21
+ const pending=Promise.resolve().then(operation);
22
+ this.operations.add(pending);
23
+ return pending.finally(()=>this.operations.delete(pending));
24
+ }
25
+ async close() {
26
+ this.closing=true;
27
+ // Installation/Skill/config commits and connection receipts must finish or
28
+ // roll back before the process acknowledges a graceful shutdown.
29
+ await Promise.allSettled([...this.operations]);
30
+ }
31
+ async scopeError() {
32
+ if(!this.installationFile) return null;
33
+ try {
34
+ const state=await readInstallation(this.installationFile);
35
+ const normalize=value=>{const resolved=path.resolve(value);return process.platform==='win32'?resolved.toLowerCase():resolved;};
36
+ if(state.host!==this.host || normalize(state.workspace)!==normalize(this.workspace) || new URL(state.platform).origin!==new URL(this.platform).origin) throw new Error('Craft installation host, workspace or platform differs from this connection; run install with the intended scope and reconnect');
37
+ return null;
38
+ } catch(error) {return {status:'error',code:'installation_scope_mismatch',message:error.message,current:this.current,can_continue:false,activation_required:false};}
39
+ }
40
+ async status() {
41
+ const error=await this.scopeError();if(error) return error;
42
+ if(this.connectionError) return this.connectionError;
43
+ return this.withHandoff({...await readUpdateStatus({installationFile:this.installationFile,current:this.current}),
44
+ ...(this.last ? {last_check:this.last} : {})},{intent:'inspect'});
45
+ }
46
+ withHandoff(result,{intent='inspect',name,request_key,excludeUpdate=false}={}) {
47
+ if(!result.reconnect_required || !result.target || ['error','incompatible','migration_required'].includes(result.status)) return result;
48
+ const busy=this.busy?.({excludeUpdate});
49
+ const handoff=connectionHandoff({host:this.host,target:result.target,current:this.current,workspace:this.workspace,platform:this.platform,
50
+ busy,intent,name,requestKey:request_key});
51
+ return {...result,...(busy?{busy}:{}),connection_handoff:handoff,next:handoff.next};
52
+ }
53
+ connected() { return this.run(()=>this.confirmConnection()); }
54
+ async confirmConnection() {
55
+ if(!this.installationFile) return {status:'unmanaged'};
56
+ const error=await this.scopeError();if(error) return this.connectionError=error;
57
+ try {
58
+ const status=await readUpdateStatus({installationFile:this.installationFile,current:this.current});
59
+ if(status.status==='error') return this.connectionError=status;
60
+ if(status.activation?.status!=='active_verified') return this.withHandoff(status,{excludeUpdate:true});
61
+ return await confirmActiveInstallation({installationFile:this.installationFile,current:this.current});
62
+ }
63
+ catch(error) {
64
+ return this.connectionError={status:'error',code:'connection_verification_failed',message:error.message,current:this.current,
65
+ can_continue:false,activation_required:false,reconnect_required:true,explicitly_not_started:true};
66
+ }
67
+ }
68
+ check(args={}) { return this.run(()=>this.checkCurrent(args)); }
69
+ inspect({name,request_key}={}) { return this.check({name,request_key,intent:'inspect'}); }
70
+ install({name,request_key,mode='auto'}={}) {
71
+ if(!request_key) throw new Error('Update request_key is required');
72
+ if(!['auto','manual'].includes(mode)) throw new Error('Invalid update mode');
73
+ return this.check({name,request_key,intent:mode==='manual'?'update':'auto'});
74
+ }
75
+ async checkCurrent({name,intent='inspect',request_key}={}) {
76
+ const error=await this.scopeError();if(error) return error;
77
+ if(this.connectionError) return this.connectionError;
78
+ if(name!==undefined) this.projects.file(name);
79
+ if(intent==='resume' && !name) throw new Error('Project name is required when checking a resume');
80
+ if(request_key!==undefined && !/^[a-zA-Z0-9._:-]{1,128}$/.test(request_key)) throw new Error('Invalid update request_key');
81
+ const project=name && ['inspect','resume','auto','update'].includes(intent) ? await this.projects.inspect(name) : null;
82
+ const projectCompatibility=project ? async packageRoot=>{
83
+ const {engines}=await loadEngineResources(path.join(packageRoot,'resources'),this.host);
84
+ const candidate=engines[project.engine];
85
+ await checkProjectCompatibility(project.project,candidate.bundle);
86
+ const lock=await readContextLock(project.project,project.engine);
87
+ if(lock?.schema>=2 && !isDeepStrictEqual(lock.compatibility,candidate.bundle.compatibility)) throw new Error('New Craft context is incompatible with this project; keep its engine and migrate explicitly');
88
+ const previous=lock?.contexts?.[this.host];
89
+ if(previous && previous.bundle_id!==candidate.bundle.id) {
90
+ const difference=candidate.bundle.version.split('.').map((value,i)=>Number(value)-Number(previous.version?.split('.')[i])).find(value=>value!==0)??0;
91
+ if(!Number.isFinite(difference)||difference<=0) throw new Error('Candidate context is older or has a conflicting version for this project');
92
+ }
93
+ } : undefined;
94
+ const result=await checkForUpdate({installationFile:this.installationFile,current:this.current,intent,
95
+ requestKey:request_key ? `${intent==='create'?'create':`${name??'global'}:${intent}`}:${request_key}` : undefined,projectCompatibility,
96
+ registryReceipt:request_key ? this.receipts.get(request_key) : undefined});
97
+ if(request_key && result.remote && result.source && result.checked_at) {
98
+ // Cache metadata, never a project's compatibility verdict. Different
99
+ // projects and preparation retries must be validated independently.
100
+ this.receipts.set(request_key,{source_key:JSON.stringify(result.source),remote:result.remote,checked_at:result.checked_at});
101
+ for(const [key,value] of this.receipts) if(Date.now()-Date.parse(value.checked_at)>=300000) this.receipts.delete(key);
102
+ while(this.receipts.size>128) this.receipts.delete(this.receipts.keys().next().value);
103
+ }
104
+ this.last=this.withHandoff(result,{intent,name,request_key,excludeUpdate:true});
105
+ return this.last;
106
+ }
107
+ }