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

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 (113) hide show
  1. package/README.md +2 -2
  2. package/bin/craft-mcp.mjs +11 -2
  3. package/dist-server/core/http-utils.mjs +11 -0
  4. package/dist-server/game-workflow/asset-formats.mjs +1 -1
  5. package/dist-server/game-workflow/bundle-files.mjs +19 -0
  6. package/dist-server/game-workflow/bundle-template.mjs +5 -0
  7. package/dist-server/game-workflow/context-state.mjs +1 -1
  8. package/dist-server/game-workflow/draft-archive.mjs +61 -0
  9. package/dist-server/game-workflow/draft-binding-migration.mjs +73 -0
  10. package/dist-server/game-workflow/draft-uploads.mjs +258 -75
  11. package/dist-server/game-workflow/native-context.mjs +4 -1
  12. package/dist-server/game-workflow/project-bundles.mjs +17 -6
  13. package/dist-server/game-workflow/projects.mjs +4 -0
  14. package/dist-server/game-workflow/template-refresh.mjs +430 -0
  15. package/dist-server/integrations/distribution-targets.mjs +2 -0
  16. package/dist-server/integrations/files.mjs +30 -2
  17. package/dist-server/integrations/fixed-launcher.mjs +4 -4
  18. package/dist-server/integrations/install.mjs +5 -5
  19. package/dist-server/integrations/installation-state.mjs +6 -7
  20. package/dist-server/integrations/launcher-start.mjs +12 -8
  21. package/dist-server/integrations/opencode-config.mjs +1 -1
  22. package/dist-server/integrations/project-setup.mjs +0 -1
  23. package/dist-server/integrations/runtime-candidate.mjs +8 -12
  24. package/dist-server/integrations/runtime-gc.mjs +20 -21
  25. package/dist-server/integrations/runtime.mjs +7 -3
  26. package/dist-server/integrations/updates.mjs +64 -27
  27. package/dist-server/launcher.mjs +39 -14
  28. package/dist-server/mcp/login-page.mjs +2 -2
  29. package/dist-server/mcp/server.mjs +10 -12
  30. package/dist-server/mcp/update-session.mjs +3 -3
  31. package/dist-server/upstream/{craft-aigc.mjs → craft-platform.mjs} +40 -115
  32. package/dist-server/upstream/draft-audit.mjs +51 -0
  33. package/dist-server/upstream/draft-transport.mjs +184 -0
  34. package/package.json +3 -3
  35. package/resources/craft-update/SKILL.md +2 -0
  36. package/resources/targets/claude/js/js/bundle.json +15 -9
  37. package/resources/targets/claude/js/target.json +8 -6
  38. package/resources/targets/claude/js3d/js3d/bundle.json +21 -10
  39. package/resources/targets/claude/js3d/target.json +14 -7
  40. package/resources/targets/codebuddy/js/js/bundle.json +15 -9
  41. package/resources/targets/codebuddy/js/target.json +8 -6
  42. package/resources/targets/codebuddy/js3d/js3d/bundle.json +21 -10
  43. package/resources/targets/codebuddy/js3d/target.json +14 -7
  44. package/resources/targets/codex/js/js/bundle.json +15 -9
  45. package/resources/targets/codex/js/target.json +8 -6
  46. package/resources/targets/codex/js3d/js3d/bundle.json +21 -10
  47. package/resources/targets/codex/js3d/target.json +14 -7
  48. package/resources/targets/comate/js/js/bundle.json +15 -9
  49. package/resources/targets/comate/js/target.json +8 -6
  50. package/resources/targets/comate/js3d/js3d/bundle.json +21 -10
  51. package/resources/targets/comate/js3d/target.json +14 -7
  52. package/resources/targets/cursor/js/js/bundle.json +15 -9
  53. package/resources/targets/cursor/js/target.json +8 -6
  54. package/resources/targets/cursor/js3d/js3d/bundle.json +21 -10
  55. package/resources/targets/cursor/js3d/target.json +14 -7
  56. package/resources/targets/dsh/js/js/bundle.json +15 -9
  57. package/resources/targets/dsh/js/target.json +8 -6
  58. package/resources/targets/dsh/js3d/js3d/bundle.json +21 -10
  59. package/resources/targets/dsh/js3d/target.json +14 -7
  60. package/resources/targets/index.json +56 -56
  61. package/resources/targets/kimi/js/js/bundle.json +15 -9
  62. package/resources/targets/kimi/js/target.json +8 -6
  63. package/resources/targets/kimi/js3d/js3d/bundle.json +21 -10
  64. package/resources/targets/kimi/js3d/target.json +14 -7
  65. package/resources/targets/opencode/js/js/bundle.json +15 -9
  66. package/resources/targets/opencode/js/target.json +8 -6
  67. package/resources/targets/opencode/js3d/js3d/bundle.json +21 -10
  68. package/resources/targets/opencode/js3d/target.json +14 -7
  69. package/resources/targets/qoder/js/js/bundle.json +15 -9
  70. package/resources/targets/qoder/js/target.json +8 -6
  71. package/resources/targets/qoder/js3d/js3d/bundle.json +21 -10
  72. package/resources/targets/qoder/js3d/target.json +14 -7
  73. package/resources/targets/qoder-cn/js/js/bundle.json +15 -9
  74. package/resources/targets/qoder-cn/js/target.json +8 -6
  75. package/resources/targets/qoder-cn/js3d/js3d/bundle.json +21 -10
  76. package/resources/targets/qoder-cn/js3d/target.json +14 -7
  77. package/resources/targets/qwen/js/js/bundle.json +15 -9
  78. package/resources/targets/qwen/js/target.json +8 -6
  79. package/resources/targets/qwen/js3d/js3d/bundle.json +21 -10
  80. package/resources/targets/qwen/js3d/target.json +14 -7
  81. package/resources/targets/trae/js/js/bundle.json +15 -9
  82. package/resources/targets/trae/js/target.json +8 -6
  83. package/resources/targets/trae/js3d/js3d/bundle.json +21 -10
  84. package/resources/targets/trae/js3d/target.json +14 -7
  85. package/resources/targets/workbuddy/js/js/bundle.json +15 -9
  86. package/resources/targets/workbuddy/js/target.json +8 -6
  87. package/resources/targets/workbuddy/js3d/js3d/bundle.json +21 -10
  88. package/resources/targets/workbuddy/js3d/target.json +14 -7
  89. package/resources/targets/zcode/js/js/bundle.json +15 -9
  90. package/resources/targets/zcode/js/target.json +8 -6
  91. package/resources/targets/zcode/js3d/js3d/bundle.json +21 -10
  92. package/resources/targets/zcode/js3d/target.json +14 -7
  93. package/resources/templates/js/materialize_paths.json +9 -0
  94. package/resources/templates/js/project/package.json +1 -0
  95. package/resources/templates/js/project/runtime/lightgame/1.1.0/platform/platform-capture-dom.mjs +176 -0
  96. package/resources/templates/js/project/runtime/lightgame/1.1.0/platform/platform.d.mts +5 -1
  97. package/resources/templates/js/project/runtime/lightgame/1.1.0/platform/platform.mjs +87 -3
  98. package/resources/templates/js/project/runtime/lightgame/1.1.0/release.json +3 -2
  99. package/resources/templates/js/project/scripts/refresh-runtime.mjs +50 -0
  100. package/resources/templates/js3d/materialize_paths.json +9 -0
  101. package/resources/templates/js3d/project/package.json +4 -2
  102. package/resources/templates/js3d/project/runtime/lightgame/1.1.0/platform/platform-capture-dom.mjs +176 -0
  103. package/resources/templates/js3d/project/runtime/lightgame/1.1.0/platform/platform.d.mts +5 -1
  104. package/resources/templates/js3d/project/runtime/lightgame/1.1.0/platform/platform.mjs +87 -3
  105. package/resources/templates/js3d/project/runtime/lightgame/1.1.0/release.json +3 -2
  106. package/resources/templates/js3d/project/scripts/refresh-runtime.mjs +50 -0
  107. package/resources/templates/js3d/project/scripts/skill-modules/gameplay-check/check.mjs +331 -0
  108. package/resources/templates/js3d/project/src/game/capability/core.ts +3 -0
  109. package/resources/templates/js3d/project/src/main.ts +23 -6
  110. package/resources/templates/js3d/project/src/skill-modules/gameplay/core/index.d.mts +92 -0
  111. package/resources/templates/js3d/project/src/skill-modules/gameplay/core/index.mjs +375 -0
  112. package/resources/templates/js3d/project/src/skill-modules/gameplay/installed.json +6 -0
  113. package/dist-server/game-workflow/local-context.mjs +0 -64
@@ -189,7 +189,6 @@ export async function setupProject({ project, ide, packageRoot, install = false,
189
189
  const bundle = await verifyBundle(path.join(packageRoot, 'resources/targets', ide, manifest.engine), manifest.engine);
190
190
  if (bundle.host !== ide) throw new Error('Installer context belongs to another host');
191
191
  await checkProjectCompatibility(project, bundle);
192
- if (lock?.compatibility && !isDeepStrictEqual(lock.compatibility, bundle.compatibility)) throw new Error('Installer engine compatibility differs from the project binding');
193
192
  if (lock?.contexts) {
194
193
  const plan=await planContextRelease(path.join(packageRoot,'resources'),bundle,lock);
195
194
  if (plan.conflicting_hosts.length) return { ...response, status: 'installer_update_required', conflicting_hosts:plan.conflicting_hosts,
@@ -1,13 +1,9 @@
1
1
  import path from 'node:path';
2
2
  import { mkdir, mkdtemp, lstat, readFile, rename, rm } from 'node:fs/promises';
3
3
  import { getRuntimeIdentity } from './runtime-identity.mjs';
4
- import { assertPlainPath } from './files.mjs';
4
+ import { assertPlainPath, isPathInside, resolveFilePath, sameFilePath } from './files.mjs';
5
5
  import { verifyExistingFileList } from './runtime-file-diagnostics.mjs';
6
6
 
7
- const within = (root, file) => {
8
- const relative = path.relative(path.resolve(root), path.resolve(file));
9
- return relative !== '' && relative !== '..' && !relative.startsWith('..' + path.sep) && !path.isAbsolute(relative);
10
- };
11
7
  const changed = message => Object.assign(new Error(message), { code: 'INSTALLATION_CHANGED' });
12
8
  const signature = info => [info.dev, info.ino, info.birthtimeMs, info.mtimeMs].map(String).join(':');
13
9
  async function directoryStamp(directory) {
@@ -21,14 +17,14 @@ function relocated(candidate) {
21
17
  const { runtime, identity, destination, sourceDirectory } = candidate;
22
18
  return { ...runtime, ...identity,
23
19
  directory: destination,
24
- package_root: path.join(destination, path.relative(sourceDirectory, identity.package_root)),
25
- entry: path.join(destination, path.relative(sourceDirectory, identity.entry)) };
20
+ package_root: path.join(destination, path.relative(sourceDirectory, resolveFilePath(identity.package_root))),
21
+ entry: path.join(destination, path.relative(sourceDirectory, resolveFilePath(identity.entry))) };
26
22
  }
27
23
 
28
24
  // Preparation and complete content verification happen outside installation
29
25
  // locks. GC only visits the runtime root's direct version directories.
30
26
  export async function prepareRuntimeCandidate(runtimeRoot, materialize, { repair = false, deferExisting = false } = {}) {
31
- runtimeRoot = path.resolve(runtimeRoot);
27
+ runtimeRoot = resolveFilePath(runtimeRoot);
32
28
  await assertPlainPath(path.join(runtimeRoot, '.candidate-path-check'));
33
29
  const parent = path.join(runtimeRoot, '.candidates');
34
30
  await mkdir(parent, { recursive: true });
@@ -39,10 +35,10 @@ export async function prepareRuntimeCandidate(runtimeRoot, materialize, { repair
39
35
  candidate.runtime = await materialize(staging);
40
36
  const runtime = candidate.runtime;
41
37
  candidate.identity = await getRuntimeIdentity(runtime.package_root ?? path.resolve(path.dirname(runtime.entry), '..'));
42
- if (path.resolve(runtime.entry) !== candidate.identity.entry) throw new Error('Candidate runtime entry differs from its verified package');
43
- if (runtime.directory && within(staging, runtime.directory)) {
44
- candidate.sourceDirectory = path.resolve(runtime.directory);
45
- if (path.dirname(candidate.sourceDirectory) !== staging || !within(candidate.sourceDirectory, candidate.identity.package_root) || !within(candidate.sourceDirectory, candidate.identity.entry)) throw new Error('Candidate runtime escaped its isolated directory');
38
+ if (!sameFilePath(runtime.entry, candidate.identity.entry)) throw new Error('Candidate runtime entry differs from its verified package');
39
+ if (runtime.directory && isPathInside(staging, runtime.directory)) {
40
+ candidate.sourceDirectory = resolveFilePath(runtime.directory);
41
+ if (!sameFilePath(path.dirname(candidate.sourceDirectory), staging) || !isPathInside(candidate.sourceDirectory, candidate.identity.package_root) || !isPathInside(candidate.sourceDirectory, candidate.identity.entry)) throw new Error('Candidate runtime escaped its isolated directory');
46
42
  candidate.destination = path.join(runtimeRoot, path.basename(candidate.sourceDirectory));
47
43
  candidate.managed = true;
48
44
  if (!deferExisting) await refreshRuntimeCandidate(candidate);
@@ -6,25 +6,24 @@ import { promisify } from 'node:util';
6
6
  import lockfile from 'proper-lockfile';
7
7
  import { readInstallation, activationStatus } from './installation-state.mjs';
8
8
  import { readConfig } from './config.mjs';
9
- import { assertPlainPath } from './files.mjs';
9
+ import { assertPlainPath, sameFilePath, isPathInside, resolveFilePath } from './files.mjs';
10
10
  import { compareVersions } from './version-policy.mjs';
11
11
 
12
12
  const execute = promisify(execFile);
13
- const canonical = value => process.platform === 'win32' ? path.resolve(value).toLowerCase() : path.resolve(value);
14
- const samePath = (a, b) => canonical(a) === canonical(b);
15
- const within = (root, file) => {
16
- const relative = path.relative(canonical(root), canonical(file));
17
- return relative !== '' && relative !== '..' && !relative.startsWith('..' + path.sep) && !path.isAbsolute(relative);
18
- };
19
13
  const pidAlive = pid => {
20
14
  try { process.kill(pid, 0); return true; }
21
15
  catch (error) { return error.code !== 'ESRCH'; }
22
16
  };
17
+ // References can be embedded in a full command line, including quoted UNC paths.
18
+ function referenceText(value) {
19
+ const text = value.replaceAll('\\', '/');
20
+ if (process.platform !== 'win32') return text;
21
+ return text.toLowerCase().replaceAll('//?/unc/', '//').replace(/\/\/\?\/(?=[a-z]:\/)/g, '');
22
+ }
23
+
23
24
  function referencesDirectory(value, directory) {
24
25
  if (typeof value === 'string') {
25
- const normalized = value.replaceAll('\\', '/');
26
- const target = directory.replaceAll('\\', '/');
27
- const [text, root] = process.platform === 'win32' ? [normalized.toLowerCase(), target.toLowerCase()] : [normalized, target];
26
+ const text = referenceText(value), root = referenceText(directory);
28
27
  return text === root || text.includes(root + '/');
29
28
  }
30
29
  return value && typeof value === 'object' && Object.values(value).some(item => referencesDirectory(item, directory));
@@ -61,7 +60,7 @@ export async function runtimeProcessReferences(directories) {
61
60
 
62
61
  async function safeDirectory(directory) {
63
62
  const info = await lstat(directory);
64
- if (!info.isDirectory() || info.isSymbolicLink() || !samePath(await realpath(directory), directory)) throw new Error('Runtime cleanup requires a plain canonical directory');
63
+ if (!info.isDirectory() || info.isSymbolicLink() || !sameFilePath(await realpath(directory), directory)) throw new Error('Runtime cleanup requires a plain canonical directory');
65
64
  await assertPlainPath(path.join(directory, '.craft-path-check'));
66
65
  }
67
66
 
@@ -180,7 +179,7 @@ export async function collectRetiredRuntimes({ installationFile, current, proces
180
179
  const skipped = reason => ({ status: 'deferred', reason, removed: [] });
181
180
  try {
182
181
  let state = await scopedState(installationFile, current);
183
- const root = state.runtime_root;
182
+ const root = resolveFilePath(state.runtime_root);
184
183
  const receipt = state.connection_verification;
185
184
  if (state.schema !== 2 || activationStatus(current, state.target).status !== 'active_verified' || !receipt || receipt.instance_id !== current.instance_id || receipt.version !== current.version || receipt.build_id !== current.build_id) return skipped('connection_not_verified');
186
185
  // Maintenance is never part of connection initialization. Enumeration,
@@ -189,8 +188,8 @@ export async function collectRetiredRuntimes({ installationFile, current, proces
189
188
  const candidates = await ownedRuntimes(root, state.source.package);
190
189
  const previousRetirements = await retiredRuntimes(root, state.source.package);
191
190
  const references = [...candidates, ...previousRetirements];
192
- const protectedPaths = new Set(), preserve = value => {
193
- for (const candidate of references) if (referencesDirectory(value, candidate.container ?? candidate.directory)) protectedPaths.add(canonical(candidate.directory));
191
+ const protectedRuntimes = new Set(), preserve = value => {
192
+ for (const candidate of references) if (referencesDirectory(value, candidate.container ?? candidate.directory)) protectedRuntimes.add(candidate);
194
193
  };
195
194
  preserve(current);
196
195
  const stateRoot = path.dirname(installationFile);
@@ -213,7 +212,7 @@ export async function collectRetiredRuntimes({ installationFile, current, proces
213
212
  // Retain the legacy-process recheck, outside the shared lock. A legacy
214
213
  // direct launch does not participate in leases; process inventory is a
215
214
  // conservative check, not a claim that all external launch races vanish.
216
- const recheck = references.filter(candidate => !protectedPaths.has(canonical(candidate.directory))).map(candidate => candidate.container ?? candidate.directory);
215
+ const recheck = references.filter(candidate => !protectedRuntimes.has(candidate)).map(candidate => candidate.container ?? candidate.directory);
217
216
  if (recheck.length) {
218
217
  const latestProcesses = await processReferences(recheck);
219
218
  if (!latestProcesses.complete) return skipped('process_inventory_unavailable');
@@ -223,9 +222,9 @@ export async function collectRetiredRuntimes({ installationFile, current, proces
223
222
  if (JSON.stringify(await installationNames(stateRoot)) !== JSON.stringify(names)) return skipped('references_changed');
224
223
  for (const snapshot of snapshots) if (await readFile(snapshot.file, 'utf8') !== snapshot.text) return skipped('references_changed');
225
224
  state = await readInstallation(installationFile);
226
- if (!samePath(root, state.runtime_root)) return skipped('installation_changed');
225
+ if (!sameFilePath(root, state.runtime_root)) return skipped('installation_changed');
227
226
  await preserveConnectionLeases(root, preserve, isAlive);
228
- const retired = candidates.filter(candidate => !protectedPaths.has(canonical(candidate.directory)));
227
+ const retired = candidates.filter(candidate => !protectedRuntimes.has(candidate));
229
228
  // A higher unreferenced candidate may belong to an interrupted update; do
230
229
  // not remove it as an old release. Keep one previous build for recovery.
231
230
  const older = retired.filter(candidate => compareVersions(candidate.metadata.version, current.version) <= 0)
@@ -234,7 +233,7 @@ export async function collectRetiredRuntimes({ installationFile, current, proces
234
233
  const removed = [], failures = [], moved = [];
235
234
  for (const candidate of older.slice(keep.length)) {
236
235
  const directory = path.resolve(candidate.directory);
237
- if (!within(root, directory) || !samePath(path.dirname(directory), root)) throw new Error('Runtime cleanup escaped its managed root');
236
+ if (!isPathInside(root, directory) || !sameFilePath(path.dirname(directory), root)) throw new Error('Runtime cleanup escaped its managed root');
238
237
  await safeDirectory(directory);
239
238
  if (await directoryStamp(directory) !== candidate.stamp || await readFile(path.join(directory, 'craft-runtime.json'), 'utf8') !== candidate.metadataText) return skipped('runtime_changed');
240
239
  const retiredRoot = path.join(root, '.retired');
@@ -254,7 +253,7 @@ export async function collectRetiredRuntimes({ installationFile, current, proces
254
253
  // path without the slow removal below touching that new package.
255
254
  await unlock(); unlock = undefined;
256
255
  const reaped = [];
257
- for (const item of [...previousRetirements.filter(item => !protectedPaths.has(canonical(item.directory)) && compareVersions(item.metadata.version, current.version) <= 0), ...moved]) {
256
+ for (const item of [...previousRetirements.filter(item => !protectedRuntimes.has(item) && compareVersions(item.metadata.version, current.version) <= 0), ...moved]) {
258
257
  try {
259
258
  await removeRetired(root, item, removeDirectory);
260
259
  if (item.source) removed.push(item.source); else reaped.push(item.container);
@@ -269,8 +268,8 @@ export async function collectRetiredRuntimes({ installationFile, current, proces
269
268
  export async function registerRuntimeConnection({ installationFile, current }) {
270
269
  if (!current?.instance_id) throw new Error('Runtime connection requires its actual instance identity');
271
270
  const state = await scopedState(installationFile, current);
272
- if (!within(state.runtime_root, current.package_root)) throw new Error('Runtime connection is outside the managed installation');
273
- const unlock = await lockfile.lock(state.runtime_root, { stale: 120000, retries: { retries: 20, minTimeout: 50, maxTimeout: 250 } });
271
+ if (!isPathInside(state.runtime_root, current.package_root)) throw new Error('Runtime connection is outside the managed installation');
272
+ const unlock = await lockfile.lock(resolveFilePath(state.runtime_root), { stale: 120000, retries: { retries: 20, minTimeout: 50, maxTimeout: 250 } });
274
273
  let leaseFile;
275
274
  try {
276
275
  const directory = path.join(state.runtime_root, '.connections');
@@ -10,9 +10,10 @@ import { promisify } from 'node:util';
10
10
  import { Client } from '@modelcontextprotocol/sdk/client/index.js';
11
11
  import { StdioClientTransport, getDefaultEnvironment } from '@modelcontextprotocol/sdk/client/stdio.js';
12
12
  import { npmFailure } from './npm-diagnostics.mjs';
13
+ import { sameFilePath } from './files.mjs';
13
14
 
14
15
  const execute = promisify(execFile);
15
- export function npmEntry() {
16
+ function npmEntry() {
16
17
  for (const dir of [path.dirname(process.execPath), ...(process.env.PATH || process.env.Path || '').split(path.delimiter)]) {
17
18
  for (const candidate of ['node_modules/npm/bin/npm-cli.js', '../lib/node_modules/npm/bin/npm-cli.js', '../share/nodejs/npm/bin/npm-cli.js']) {
18
19
  const file = path.resolve(dir, candidate); if (existsSync(file)) return file;
@@ -80,7 +81,10 @@ export async function stageRuntime(packageRoot, runtimeRoot, { registry } = {})
80
81
  export async function stageRegistryRuntime(source, metadata, runtimeRoot) {
81
82
  const temp = await mkdtemp(path.join(os.tmpdir(), 'craft-update-package-'));
82
83
  try {
83
- const packed = JSON.parse((await runNpm(['pack', source.package + '@' + metadata.version, '--ignore-scripts', '--json', '--registry=' + source.registry, '--pack-destination', temp], temp)).stdout);
84
+ const registryArgs = ['--registry=' + source.registry];
85
+ // Scoped npm configuration takes precedence over --registry.
86
+ if (source.package.startsWith('@')) registryArgs.push('--' + source.package.split('/')[0] + ':registry=' + source.registry);
87
+ const packed = JSON.parse((await runNpm(['pack', source.package + '@' + metadata.version, '--ignore-scripts', '--json', ...registryArgs, '--pack-destination', temp], temp)).stdout);
84
88
  if (!Array.isArray(packed) || packed.length !== 1 || path.basename(packed[0].filename) !== packed[0].filename) throw new Error('Unexpected npm package archive');
85
89
  return await stageArchive(path.join(temp, packed[0].filename), { name: source.package, version: metadata.version }, runtimeRoot, { registry: source.registry, integrity: metadata.integrity });
86
90
  } finally { await rm(temp, { recursive: true, force: true }); }
@@ -107,7 +111,7 @@ export async function probeRuntime(connection, expected = {}) {
107
111
  if (expected.build_id && info.runtime?.build_id !== expected.build_id) throw new Error('Runtime build identity mismatch');
108
112
  if (expected.host && info.host !== expected.host) throw new Error('Runtime host mismatch');
109
113
  if (expected.serverId && (info.server_id ?? 'craft') !== expected.serverId) throw new Error('Craft runtime does not confirm the requested MCP instance: ' + expected.serverId + '; use a channel release with named instance support');
110
- if (expected.workspace && path.resolve(info.workspace) !== path.resolve(expected.workspace)) throw new Error('Runtime workspace mismatch');
114
+ if (expected.workspace && !sameFilePath(info.workspace, expected.workspace)) throw new Error('Runtime workspace mismatch');
111
115
  if (expected.platform && info.platform !== expected.platform) throw new Error('Runtime platform mismatch');
112
116
  if (expected.host && ['js','js3d'].some(engine=>info.installed_contexts?.[engine]?.host !== expected.host)) throw new Error('Runtime context host mismatch');
113
117
  return { scope: 'standalone_probe', version: info.version, runtime: info.runtime, host: info.host, server_id: info.server_id ?? 'craft', workspace: info.workspace, platform: info.platform, tools: listed.tools.length, engines: info.supported_engines, contexts:info.installed_contexts };
@@ -6,7 +6,7 @@ import { readInstallation, readInstallationSnapshot, activationStatus, registryO
6
6
  import { compareVersions, requireForwardVersion, parseVersion } from './version-policy.mjs';
7
7
  import { stageRegistryRuntime, getRuntimeIdentity, probeRuntime } from './runtime.mjs';
8
8
  import { readRunningIdentity } from './runtime-identity.mjs';
9
- import { optionalFile, assertPlainPath, commitFiles } from './files.mjs';
9
+ import { optionalFile, assertPlainPath, commitFiles, sameFilePath, isPathInside, resolveFilePath } from './files.mjs';
10
10
  import { hostPaths, hostCommandOptions, installTargets } from './hosts.mjs';
11
11
  import { craftConfig, mergeConfig } from './config.mjs';
12
12
  import { assertDshSharedScope } from './dsh-config.mjs';
@@ -49,22 +49,49 @@ export async function readUpdateStatus({ installationFile, current }) {
49
49
  } catch (error) { return { status: 'error', code: 'invalid_installation', message: error.message, current, can_continue: false, activation_required: false }; }
50
50
  }
51
51
 
52
- export async function queryRegistry(source, { fetchImpl = fetch, timeoutMs = 15000 } = {}) {
53
- const registry = registryOrigin(source.registry);
54
- const url = new URL(encodeURIComponent(source.package) + '/' + encodeURIComponent(source.channel), registry);
55
- const response = await fetchImpl(url, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(timeoutMs) });
56
- if (!response.ok) throw Object.assign(new Error('npm version check failed (HTTP ' + response.status + ')'), { code: response.status >= 400 && response.status < 500 && ![408, 429].includes(response.status) ? 'INVALID_REGISTRY_METADATA' : 'REGISTRY_UNAVAILABLE' });
57
- let data;
58
- try { data = await response.json(); if (data.name !== source.package) throw new Error('npm returned a different package identity'); parseVersion(data.version); }
59
- catch { throw Object.assign(new Error('npm returned invalid package identity metadata'), { code: 'INVALID_REGISTRY_METADATA' }); }
60
- const integrity = data.dist?.integrity ?? (data.dist?.shasum && /^[a-f0-9]{40}$/.test(data.dist.shasum) ? 'sha1-' + Buffer.from(data.dist.shasum, 'hex').toString('base64') : undefined);
61
- if (!integrity || !String(integrity).split(/\s+/).some(value => /^(sha512|sha384|sha256|sha1)-[A-Za-z0-9+/]+={0,2}$/.test(value))) throw Object.assign(new Error('npm package integrity metadata is missing or invalid'), { code: 'INVALID_REGISTRY_METADATA' });
62
- return { package: data.name, version: data.version, integrity, node: data.engines?.node ?? null };
52
+ function invalidRegistryMetadata(message) {
53
+ return Object.assign(new Error(message), { code: 'INVALID_REGISTRY_METADATA' });
63
54
  }
64
55
 
65
- function within(root, file) {
66
- const relative = path.relative(path.resolve(root), path.resolve(file));
67
- return relative === '' || (!relative.startsWith('..' + path.sep) && relative !== '..' && !path.isAbsolute(relative));
56
+ export async function queryRegistry(source, { version, fetchImpl = fetch, timeoutMs = 15000 } = {}) {
57
+ const registry = registryOrigin(source.registry);
58
+ if (version !== undefined) parseVersion(version);
59
+ const resource = encodeURIComponent(source.package) + (version === undefined ? '' : '/' + encodeURIComponent(version));
60
+ const url = new URL(resource, registry);
61
+ const response = await fetchImpl(url, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(timeoutMs) });
62
+ if (!response.ok) {
63
+ const message = 'npm metadata lookup for ' + url + ' failed (HTTP ' + response.status + ')';
64
+ if (response.status >= 400 && response.status < 500 && ![408, 429].includes(response.status)) throw invalidRegistryMetadata(message);
65
+ throw Object.assign(new Error(message), { code: 'REGISTRY_UNAVAILABLE' });
66
+ }
67
+ let metadata;
68
+ try { metadata = await response.json(); }
69
+ catch (error) {
70
+ if (error instanceof SyntaxError) throw invalidRegistryMetadata('npm returned invalid JSON for ' + source.package);
71
+ throw error;
72
+ }
73
+ if (metadata?.name !== source.package) throw invalidRegistryMetadata('npm returned a different package identity for ' + source.package);
74
+ let manifest = metadata;
75
+ if (version === undefined) {
76
+ const tags = metadata['dist-tags'], versions = metadata.versions;
77
+ if (!tags || typeof tags !== 'object' || Array.isArray(tags) || !versions || typeof versions !== 'object' || Array.isArray(versions)) {
78
+ throw invalidRegistryMetadata('npm package metadata is missing a valid dist-tags or versions map for ' + source.package);
79
+ }
80
+ if (!Object.hasOwn(tags, source.channel)) {
81
+ throw Object.assign(new Error('Configured npm source ' + registry + ' has no dist-tag for ' + source.package + '@' + source.channel), { code: 'REGISTRY_CHANNEL_NOT_FOUND' });
82
+ }
83
+ version = tags[source.channel];
84
+ try { parseVersion(version); }
85
+ catch { throw invalidRegistryMetadata('npm dist-tag ' + source.channel + ' refers to an invalid version'); }
86
+ manifest = Object.hasOwn(versions, version) ? versions[version] : undefined;
87
+ }
88
+ if (manifest?.name !== source.package || manifest.version !== version) {
89
+ throw invalidRegistryMetadata('npm metadata lacks a matching version record for ' + source.package + '@' + version);
90
+ }
91
+ const dist = manifest.dist;
92
+ const integrity = dist?.integrity ?? (dist?.shasum && /^[a-f0-9]{40}$/.test(dist.shasum) ? 'sha1-' + Buffer.from(dist.shasum, 'hex').toString('base64') : undefined);
93
+ if (typeof integrity !== 'string' || !integrity.split(/\s+/).some(value => /^(sha512|sha384|sha256|sha1)-[A-Za-z0-9+/]+={0,2}$/.test(value))) throw invalidRegistryMetadata('npm package integrity metadata is missing or invalid');
94
+ return { package: manifest.name, version, integrity, node: manifest.engines?.node ?? null };
68
95
  }
69
96
 
70
97
  async function candidateSkills(state, identity) {
@@ -101,7 +128,7 @@ export async function confirmActiveInstallation({ installationFile, current }) {
101
128
  if (!current?.instance_id) throw new Error('An actual runtime instance is required to confirm the installation');
102
129
  // The server captured its own package identity at startup. Compare that
103
130
  // identity to the selected target and commit the receipt under one short lock.
104
- const unlock = await lockfile.lock(installationFile, shortLock);
131
+ const unlock = await lockfile.lock(resolveFilePath(installationFile), shortLock);
105
132
  try {
106
133
  const { state, text: before } = await confirmationSnapshot(installationFile, current);
107
134
  const previous = state.connection_verification;
@@ -112,7 +139,7 @@ export async function confirmActiveInstallation({ installationFile, current }) {
112
139
  }
113
140
 
114
141
  async function saveCheckReceipt(installationFile, expected, receipt) {
115
- const unlock = await lockfile.lock(installationFile, { ...shortLock, retries: { retries: 3, minTimeout: 25, maxTimeout: 100 } });
142
+ const unlock = await lockfile.lock(resolveFilePath(installationFile), { ...shortLock, retries: { retries: 3, minTimeout: 25, maxTimeout: 100 } });
116
143
  try {
117
144
  const { state, text: before } = await unchangedInstallation(installationFile, expected);
118
145
  const after = { ...state, last_check: receipt };
@@ -123,10 +150,9 @@ async function saveCheckReceipt(installationFile, expected, receipt) {
123
150
 
124
151
  async function verifyRegisteredScope(existing, state, installationFile) {
125
152
  await verifyLauncher(state, installationFile, existing);
126
- const samePath = (a, b) => typeof a === 'string' && typeof b === 'string' && (process.platform === 'win32' ? path.resolve(a).toLowerCase() === path.resolve(b).toLowerCase() : path.resolve(a) === path.resolve(b));
127
153
  const workspaceIndex = existing?.args?.indexOf('--workspace') ?? -1;
128
- if (!existing || (existing.env?.CRAFT_SERVER_ID ?? 'craft') !== state.server_id || !samePath(existing.env?.CRAFT_INSTALLATION_FILE, installationFile) || existing.env?.CRAFT_CLIENT_IDE !== state.host ||
129
- !samePath(workspaceIndex >= 0 ? existing.args[workspaceIndex + 1] : existing.env?.CLIENT_WORKSPACE_ROOT, state.workspace) ||
154
+ if (!existing || (existing.env?.CRAFT_SERVER_ID ?? 'craft') !== state.server_id || !sameFilePath(existing.env?.CRAFT_INSTALLATION_FILE, installationFile) || existing.env?.CRAFT_CLIENT_IDE !== state.host ||
155
+ !sameFilePath(workspaceIndex >= 0 ? existing.args[workspaceIndex + 1] : existing.env?.CLIENT_WORKSPACE_ROOT, state.workspace) ||
130
156
  new URL(existing.env?.CRAFT_WEB_URL).origin !== new URL(state.platform).origin) throw new Error('Craft host configuration scope changed; run install with the intended scope');
131
157
  }
132
158
 
@@ -178,6 +204,17 @@ async function checkSnapshot({ installationFile, current, connectedSource, inten
178
204
  } else {
179
205
  try { remote = await lookup(state.source); checkedAt = new Date().toISOString(); }
180
206
  catch (error) {
207
+ if (error.code === 'REGISTRY_CHANNEL_NOT_FOUND') {
208
+ // Concurrent verified connections may share a target. The persisted receipt
209
+ // names the last connection, while each MCP checks its own identity at startup.
210
+ const canResume = Boolean(projectCompatibility && ['inspect', 'auto', 'resume'].includes(intent)
211
+ && state.schema === 2 && state.policy.offline === 'allow-existing' && state.connection_verification
212
+ && activationStatus(current, state.target).status === 'active_verified' && !currentIncompatible);
213
+ return keepCurrent(activationPending ? 'pending_reconnect' : 'channel_not_found', {
214
+ remote_status: 'channel_not_found', checked_at: new Date().toISOString(), message: error.message,
215
+ update_available: false, can_continue: canResume, ...(canResume ? { retained_version: current.version } : {}),
216
+ });
217
+ }
181
218
  if (error.code === 'INVALID_REGISTRY_METADATA') return result(state, current, 'error', { code: 'invalid_registry_metadata', message: error.message, can_continue: false });
182
219
  // Network failure is an unknown remote state, never proof of latest.
183
220
  return keepCurrent('offline', { checked_at: new Date().toISOString(), remote_status: 'unknown', message: error.message, can_continue: state.schema === 2 && !currentIncompatible && !activationPending && state.policy.offline === 'allow-existing' });
@@ -217,7 +254,7 @@ async function checkSnapshot({ installationFile, current, connectedSource, inten
217
254
  originalConfig = await optionalFile(state.config);
218
255
  candidate = await prepareRuntimeCandidate(runtimeRoot, stagingRoot => materialize(state.source, remote, stagingRoot), { repair:true, deferExisting:true });
219
256
  let identity = candidate.identity;
220
- if (!within(runtimeRoot, identity.package_root) || identity.package !== state.source.package || identity.version !== remote.version) throw new Error('Candidate runtime identity/path mismatch');
257
+ if (!isPathInside(runtimeRoot, identity.package_root) || identity.package !== state.source.package || identity.version !== remote.version) throw new Error('Candidate runtime identity/path mismatch');
221
258
  requireForwardVersion(identity, state.target);
222
259
  if (projectCompatibility) {
223
260
  try { await projectCompatibility(identity.package_root); }
@@ -237,12 +274,12 @@ async function checkSnapshot({ installationFile, current, connectedSource, inten
237
274
  const unlockScope = [];
238
275
  let unlockRuntime;
239
276
  try {
240
- for (const file of [state.config, installationFile].map(file => path.resolve(file)).sort()) {
277
+ for (const file of [state.config, installationFile].map(resolveFilePath).sort()) {
241
278
  unlockScope.push(await lockfile.lock(file, { ...shortLock, realpath: false }));
242
279
  }
243
280
  const latest = await unchangedInstallation(installationFile, state);
244
281
  state = latest.state;
245
- unlockRuntime = await lockfile.lock(runtimeRoot, shortLock);
282
+ unlockRuntime = await lockfile.lock(resolveFilePath(runtimeRoot), shortLock);
246
283
  identity = await publishRuntimeCandidate(candidate);
247
284
  requireForwardVersion(identity, state.target);
248
285
  const launcherPlan = await planLauncher(installationFile, state.launcher, identity.package_root);
@@ -284,7 +321,7 @@ async function checkSnapshot({ installationFile, current, connectedSource, inten
284
321
  )) throw new Error('Host registration changed; rollback could not be verified');
285
322
  if (!sameRuntimeIdentity(await readRunningIdentity(current.package_root, { managed:true }), state.target)) throw new Error('Existing runtime installation identity check failed');
286
323
  await hostUpdate(state, installationFile, state.launcher ?? { entry: current.entry }, current);
287
- if (!state.launcher && path.resolve(craftConfig(originalConfig, state.host, state.server_id).args[0]) !== path.resolve(current.entry)) throw new Error('Existing runtime entry differs from the configured connection');
324
+ if (!state.launcher && !sameFilePath(craftConfig(originalConfig, state.host, state.server_id).args[0], current.entry)) throw new Error('Existing runtime entry differs from the configured connection');
288
325
  const skills = await candidateSkills(state, current);
289
326
  if (skills.some(change => change.before !== change.after)) throw new Error('Existing managed Skills differ from the current runtime');
290
327
  await unchangedInstallation(installationFile, state);
@@ -339,7 +376,7 @@ export async function runUpdateCommand(args) {
339
376
  const installationFile = connection?.env?.CRAFT_INSTALLATION_FILE;
340
377
  if (!installationFile) throw new Error(host + ': Install Craft once before using automatic updates');
341
378
  const state = await readInstallation(installationFile);
342
- if (state.host !== host || state.server_id !== serverId || path.relative(state.config, paths.config) !== '' || (connection.env.CRAFT_SERVER_ID ?? 'craft') !== serverId) throw new Error('Craft registration does not match the selected installation scope: ' + serverId);
379
+ if (state.host !== host || state.server_id !== serverId || !sameFilePath(state.config, paths.config) || (connection.env.CRAFT_SERVER_ID ?? 'craft') !== serverId) throw new Error('Craft registration does not match the selected installation scope: ' + serverId);
343
380
  await verifyRegisteredScope(connection, state, installationFile);
344
381
  const current = await readRunningIdentity(state.target.package_root, { managed:Boolean(state.launcher) });
345
382
  const update = await checkForUpdate({ installationFile, current, intent: command === 'update' ? 'update' : 'inspect', requestKey: 'cli-' + Date.now() });
@@ -350,8 +387,8 @@ export async function runUpdateCommand(args) {
350
387
  }
351
388
  // A CLI can inspect configured files, but cannot prove a host connection.
352
389
  results.push({ host, ...update, activation: { status: 'pending_connection_verification', expected: update.target }, can_continue: false, scope: 'configured_runtime', note: 'Call craft_game_info in the actual host connection to confirm activation.',
353
- ...(!['error','update_failed','incompatible','migration_required'].includes(update.status) ? {connection_handoff:connectionHandoff({host,serverId,channel:state.source.channel,target:update.target,workspace:state.workspace,platform:state.platform,intent:command==='update'?'update':'inspect'})} : {}) });
354
- if (['error', 'update_failed', 'incompatible'].includes(update.status)) process.exitCode = 1;
390
+ ...(!['error','update_failed','incompatible','migration_required','channel_not_found'].includes(update.status) ? {connection_handoff:connectionHandoff({host,serverId,channel:state.source.channel,target:update.target,workspace:state.workspace,platform:state.platform,intent:command==='update'?'update':'inspect'})} : {}) });
391
+ if (['error', 'update_failed', 'incompatible', 'channel_not_found'].includes(update.status)) process.exitCode = 1;
355
392
  }
356
393
  process.stdout.write(JSON.stringify({ hosts: results }, null, 2) + '\n');
357
394
  }
@@ -1623,6 +1623,28 @@ import path2 from "node:path";
1623
1623
  // dist-server/integrations/files.mjs
1624
1624
  import path from "node:path";
1625
1625
  import { lstat, readFile, mkdir, writeFile, rename, unlink } from "node:fs/promises";
1626
+ function resolveFilePath(file) {
1627
+ if (process.platform === "win32" && file.startsWith("\\\\?\\")) {
1628
+ const body = file.slice(4);
1629
+ const drive = /^[a-z]:\\/i.test(body);
1630
+ const unc = /^UNC\\[^\\]+\\[^\\]+(?:\\|$)/i.test(body);
1631
+ if (drive || unc) {
1632
+ const parts = body.slice(drive ? 3 : 4).split("\\");
1633
+ const verbatimOnly = parts.some((part) => /[ .]$|[<>:"/|?*\x00-\x1f]|^(?:CON|PRN|AUX|NUL|CONIN\$|CONOUT\$|COM[1-9¹²³]|LPT[1-9¹²³])(?:\.|$)/i.test(part));
1634
+ if (!verbatimOnly) return path.resolve(drive ? body : "\\\\" + body.slice(4));
1635
+ }
1636
+ }
1637
+ return path.resolve(file);
1638
+ }
1639
+ function sameFilePath(a, b) {
1640
+ if (typeof a !== "string" || typeof b !== "string") return false;
1641
+ const left = resolveFilePath(a), right = resolveFilePath(b);
1642
+ return process.platform === "win32" ? left.toLowerCase() === right.toLowerCase() : left === right;
1643
+ }
1644
+ function isPathInside(root, file) {
1645
+ const relative = path.relative(resolveFilePath(root), resolveFilePath(file));
1646
+ return relative !== "" && relative !== ".." && !relative.startsWith(".." + path.sep) && !path.isAbsolute(relative);
1647
+ }
1626
1648
  async function optionalFile(file) {
1627
1649
  try {
1628
1650
  return await readFile(file, "utf8");
@@ -1632,11 +1654,12 @@ async function optionalFile(file) {
1632
1654
  }
1633
1655
  }
1634
1656
  async function assertPlainPath(file) {
1635
- let current = path.resolve(file);
1657
+ const target = resolveFilePath(file);
1658
+ let current = target;
1636
1659
  for (; ; ) {
1637
1660
  try {
1638
1661
  const info = await lstat(current);
1639
- if (info.isSymbolicLink() || (current === path.resolve(file) ? !info.isFile() : !info.isDirectory())) throw new Error("Refusing linked or invalid install path: " + current);
1662
+ if (info.isSymbolicLink() || (current === target ? !info.isFile() : !info.isDirectory())) throw new Error("Refusing linked or invalid install path: " + current);
1640
1663
  } catch (error) {
1641
1664
  if (error.code !== "ENOENT") throw error;
1642
1665
  }
@@ -1714,8 +1737,7 @@ function instanceSkillName(logicalName, serverId = "craft") {
1714
1737
  var defaultRegistry = "https://registry.npmjs.org/";
1715
1738
  var activationMode = "next_mcp_start";
1716
1739
  function sameRuntimeIdentity(left, right) {
1717
- const samePath = (a, b) => typeof a === "string" && typeof b === "string" && (process.platform === "win32" ? path2.resolve(a).toLowerCase() === path2.resolve(b).toLowerCase() : path2.resolve(a) === path2.resolve(b));
1718
- return Boolean(left && right && left.package === right.package && left.version === right.version && left.build_id === right.build_id && samePath(left.package_root, right.package_root) && samePath(left.entry, right.entry));
1740
+ return Boolean(left && right && left.package === right.package && left.version === right.version && left.build_id === right.build_id && sameFilePath(left.package_root, right.package_root) && sameFilePath(left.entry, right.entry));
1719
1741
  }
1720
1742
  var managedSkillMarkers = Object.freeze({ "craft-create": "<!-- craft-mcp:bootstrap:v1 -->", "craft-update": "<!-- craft-mcp:update:v1 -->" });
1721
1743
  function installedSkillEntries(state) {
@@ -1735,7 +1757,7 @@ function validateIdentity(identity) {
1735
1757
  if (!identity || typeof identity !== "object") throw new Error("Missing Craft runtime identity");
1736
1758
  parseVersion(identity.version);
1737
1759
  if (!identity.package || !/^[a-f0-9]{64}$/.test(identity.build_id ?? "") || !path2.isAbsolute(identity.package_root ?? "") || !path2.isAbsolute(identity.entry ?? "")) throw new Error("Invalid Craft runtime identity");
1738
- if (path2.resolve(identity.entry) !== path2.join(path2.resolve(identity.package_root), "bin", "craft-mcp.mjs")) throw new Error("Craft entry is outside its runtime package");
1760
+ if (!sameFilePath(identity.entry, path2.join(identity.package_root, "bin", "craft-mcp.mjs"))) throw new Error("Craft entry is outside its runtime package");
1739
1761
  return identity;
1740
1762
  }
1741
1763
  async function readInstallationSnapshot(file) {
@@ -1843,17 +1865,17 @@ async function verifyLauncher(state, installationFile, connection) {
1843
1865
  if (connection?.env && (connection.env.CRAFT_SERVER_ID ?? "craft") !== state.server_id) throw new Error("Craft launcher instance differs from its registration");
1844
1866
  if (!state.launcher) return { mode: "legacy_versioned_entry" };
1845
1867
  const expected = launcherPath(installationFile);
1846
- if (state.launcher.schema !== 1 || state.launcher.entry !== expected || !/^[a-f0-9]{64}$/.test(state.launcher.sha256 ?? "")) throw new Error("Invalid Craft fixed launcher identity");
1868
+ if (state.launcher.schema !== 1 || !path4.isAbsolute(state.launcher.entry ?? "") || !sameFilePath(state.launcher.entry, expected) || !/^[a-f0-9]{64}$/.test(state.launcher.sha256 ?? "")) throw new Error("Invalid Craft fixed launcher identity");
1847
1869
  if (state.launcher.kind !== void 0) throw new Error("Unsupported Craft launcher; run the standard installer and reconnect");
1848
1870
  await assertPlainPath(expected);
1849
1871
  if (createHash2("sha256").update(await readFile3(expected)).digest("hex") !== state.launcher.sha256) throw new Error("Craft fixed launcher integrity mismatch");
1850
- if (connection && path4.resolve(connection.args?.[0] ?? "") !== path4.resolve(expected)) throw new Error("Craft host configuration does not use the installed fixed launcher");
1872
+ if (connection && !sameFilePath(connection.args?.[0], expected)) throw new Error("Craft host configuration does not use the installed fixed launcher");
1851
1873
  return { mode: "fixed_entry", entry: expected };
1852
1874
  }
1853
1875
 
1854
1876
  // dist-server/integrations/launcher-start.mjs
1855
1877
  async function start() {
1856
- const entry = path5.resolve(process.argv[1]);
1878
+ const entry = resolveFilePath(process.argv[1]);
1857
1879
  const loginPage = process.argv.length === 3 && process.argv[2] === "--workbuddy-login-page";
1858
1880
  const preview = process.argv.length === 3 && process.argv[2] === "--workbuddy-preview";
1859
1881
  const installationFile = entry.replace(/\.launcher\.mjs$/, ".json");
@@ -1861,23 +1883,26 @@ async function start() {
1861
1883
  await assertPlainPath(installationFile);
1862
1884
  const initial = await readInstallation(installationFile);
1863
1885
  await assertPlainPath(path5.join(initial.runtime_root, ".path-check"));
1864
- const unlock = await import_proper_lockfile.default.lock(initial.runtime_root, { stale: 12e4, retries: { retries: 240, minTimeout: 250, maxTimeout: 500 } });
1886
+ const unlock = await import_proper_lockfile.default.lock(resolveFilePath(initial.runtime_root), { stale: 12e4, retries: { retries: 240, minTimeout: 250, maxTimeout: 500 } });
1865
1887
  let identity, state, lease;
1866
1888
  try {
1867
1889
  state = await readInstallation(installationFile);
1868
1890
  if ((loginPage || preview) && (process.platform !== "win32" || state.host !== "workbuddy")) throw new Error("The Windows background task requires a WorkBuddy installation");
1869
- if (state.runtime_root !== initial.runtime_root || state.schema !== 2) throw new Error("Craft installation changed or needs migration");
1891
+ if (!sameFilePath(state.runtime_root, initial.runtime_root) || state.schema !== 2) throw new Error("Craft installation changed or needs migration");
1870
1892
  await verifyLauncher(state, installationFile, { args: [entry] });
1871
- if (process.env.CRAFT_INSTALLATION_FILE && path5.resolve(process.env.CRAFT_INSTALLATION_FILE) !== installationFile) throw new Error("Craft launcher installation scope mismatch");
1893
+ if (process.env.CRAFT_INSTALLATION_FILE && !sameFilePath(process.env.CRAFT_INSTALLATION_FILE, installationFile)) throw new Error("Craft launcher installation scope mismatch");
1872
1894
  if (state.host === "workbuddy" && state.login_data_dir && process.env.CRAFT_STANDALONE_PROBE !== "1") {
1873
1895
  process.env.CLIENT_DATA_DIR ||= state.login_data_dir;
1874
1896
  }
1875
1897
  for (const [key, expected] of Object.entries({ CRAFT_CLIENT_IDE: state.host, CRAFT_SERVER_ID: state.server_id, CLIENT_WORKSPACE_ROOT: state.workspace, CRAFT_WEB_URL: state.platform })) {
1876
- if (process.env[key] && process.env[key] !== expected) throw new Error("Craft launcher scope mismatch: " + key);
1898
+ const value = process.env[key];
1899
+ if (value && value !== expected) {
1900
+ const sameWorkspace = key === "CLIENT_WORKSPACE_ROOT" && path5.isAbsolute(value) && sameFilePath(value, expected);
1901
+ if (!sameWorkspace) throw new Error("Craft launcher scope mismatch: " + key);
1902
+ }
1877
1903
  process.env[key] = expected;
1878
1904
  }
1879
- const relative = path5.relative(path5.resolve(state.runtime_root), state.target.package_root);
1880
- if (!relative || relative === ".." || relative.startsWith(".." + path5.sep) || path5.isAbsolute(relative)) throw new Error("Craft target is outside the managed runtime root");
1905
+ if (!isPathInside(state.runtime_root, state.target.package_root)) throw new Error("Craft target is outside the managed runtime root");
1881
1906
  await assertPlainPath(state.target.entry);
1882
1907
  identity = await readRunningIdentity(state.target.package_root, { managed: true });
1883
1908
  if (!sameRuntimeIdentity(identity, state.target)) throw new Error("Craft target and installed runtime identity differ; run doctor for the selected instance");
@@ -10,7 +10,7 @@ import { defaultProfileDataDir } from '../core/app-paths.mjs';
10
10
  import { readInstallation } from '../integrations/installation-state.mjs';
11
11
  import { verifyLauncher } from '../integrations/fixed-launcher.mjs';
12
12
  import { runWorkBuddyLoginTask } from '../integrations/workbuddy-login-task.mjs';
13
- import { CraftAigc } from '../upstream/craft-aigc.mjs';
13
+ import { CraftPlatform } from '../upstream/craft-platform.mjs';
14
14
  import { openControlPanel } from './control-panel.mjs';
15
15
  import { createLoginPageLifecycle } from './login-page-lifecycle.mjs';
16
16
 
@@ -158,7 +158,7 @@ export async function startLoginPage(sessionFile,base,{successGraceMs=successGra
158
158
  clearTimeout(timer);
159
159
  timer=setTimeout(()=>{void close().catch(()=>{process.exitCode=1;});},delay);
160
160
  }
161
- panel=await openControlPanel(new CraftAigc(sessionFile,base),{
161
+ panel=await openControlPanel(new CraftPlatform(sessionFile,base),{
162
162
  loginOnly:true,
163
163
  proveOwnership:challenge=>!completed && !closing && proof(key,challenge),
164
164
  lifecycle:()=>lifecycle.snapshot(),
@@ -7,7 +7,7 @@ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
7
7
  import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
8
8
  import { installProjectDependencies } from '#craft-sdk';
9
9
  import { getUserDataDir, getWorkspaceRoot, getProjectBindingsDir } from '../core/app-paths.mjs';
10
- import { CraftAigc } from '../upstream/craft-aigc.mjs';
10
+ import { CraftPlatform } from '../upstream/craft-platform.mjs';
11
11
  import { Projects, fingerprint } from '../game-workflow/projects.mjs';
12
12
  import { RequestStore } from '../game-workflow/request-store.mjs';
13
13
  import { Tasks } from '../game-workflow/tasks.mjs';
@@ -39,7 +39,7 @@ const { version } = runtimeIdentity;
39
39
  await mkdir(getWorkspaceRoot(),{ recursive:true });
40
40
  const root = await realpath(getWorkspaceRoot()), state = getUserDataDir(), resources = process.env.CRAFT_MCP_RESOURCES_DIR;
41
41
  const sessionFile = path.join(state,'auth-session.json');
42
- const platform = new CraftAigc(sessionFile,process.env.CRAFT_WEB_URL,
42
+ const platform = new CraftPlatform(sessionFile,process.env.CRAFT_WEB_URL,
43
43
  connectorAuth ? new ConnectorAuthStore() : undefined);
44
44
  if (connectorAuth) {
45
45
  try { await platform.login(connectorToken); }
@@ -68,7 +68,9 @@ const previews = new Previews(state,{windowsWorkBuddy:process.platform==='win32'
68
68
  const reviewed = new Set();
69
69
  const uploadStore = new RequestStore(path.join(state,'uploads'),root); await uploadStore.init();
70
70
  const resourcePaths = { capture:path.join(resources,'game_visual_qa.mjs'), evidence:path.join(path.dirname(uploadStore.directory),'checks') };
71
- const drafts = new DraftUploads(platform,uploadStore,resourcePaths.evidence,new DraftBindings(getProjectBindingsDir(),root));
71
+ const drafts = new DraftUploads(platform,uploadStore,resourcePaths.evidence,new DraftBindings(getProjectBindingsDir(),root),{
72
+ onBound:(scope,projectID)=>productionTelemetry().events.bindPending(scope,projectID),
73
+ });
72
74
  let telemetry;
73
75
  const leases = new ProjectLeases(root,name=>{
74
76
  telemetry?.end(name);
@@ -148,7 +150,7 @@ const tools = [
148
150
  ...taskField,visual_passed:{ type:'boolean' },visual_notes:{ type:'string',minLength:10,maxLength:2000 },
149
151
  },['task_id','visual_passed','visual_notes']),
150
152
  tool('craft_game_upload','Upload the frozen source and dist as a private Craft version. The upload rechecks both snapshots for security. Report any findings and run a new check after fixing them. Local files become current; unsynced Web changes stay in history. Default: append to the bound project, or create on first upload. To update the original project, read the bound target and pass expected_appid. Only explicit requests select new_project. Poll craft_task_status; reuse the check ID, mode and request key for retries. Report vN, appid and project_url from draft_ready. Public review follows in Craft Web.',{...draftFields,expected_appid:{type:'string',pattern:'^[A-Za-z0-9_-]{1,128}$',description:'Require current_project to be bound to this appid; stop if unbound or different.'}},['name','check_task_id']),
151
- tool('craft_game_upload_status','With name only, inspect the upload target for the current account and platform before updating the original appid. With check_task_id, read the private upload receipt and project link.',draftFields,['name']),
153
+ tool('craft_game_upload_status','If an upload returns processing=true, poll with its original check_task_id, mode and request_key until content review finishes. On rejection, report content_audit.location when available. Report the project link at draft_ready. With name only, inspect the upload target for the current account and platform.',draftFields,['name']),
152
154
  tool('craft_preview_stop','Stop this project independent preview and cancel pending starts, including an earlier session preview.',nameField,['name']),
153
155
  tool('craft_auth_open','Check login first. Return a login URL only when unauthenticated; an authenticated account continues without a login URL. Never read credentials or automate login.'),
154
156
  tool('craft_auth_status','Check the Craft account without exposing credentials.'),
@@ -224,7 +226,7 @@ server.setRequestHandler(CallToolRequestSchema,async request=>{
224
226
  next:update.next ?? 'Resolve the update diagnostic, then retry this prepare with the same request_key. No project work was acquired.'};
225
227
  return {content:[{type:'text',text:JSON.stringify(blocked)}]};
226
228
  }
227
- if (['update_failed','offline'].includes(update.status)) updateWarning=update;
229
+ if (['update_failed','offline','channel_not_found'].includes(update.status)) updateWarning=update;
228
230
  }
229
231
  work=await leases.acquire(args.name,{...args,host});
230
232
  if(work.task_id) {
@@ -353,13 +355,9 @@ server.setRequestHandler(CallToolRequestSchema,async request=>{
353
355
  if (!status.authenticated) { result = await loginAction(); break; }
354
356
  // An already authorized upload resumes its frozen check, even after later source edits.
355
357
  const resume = await drafts.hasRequest(args.name,args.check_task_id,status.user_id,args);
356
- const { task } = await completedCheck(args.check_task_id,args.name,resume);
357
- result = viewTask(await tasks.start(args.name,'upload',async signal=>{
358
- const uploaded = await drafts.upload(task,status.user_id,signal,args);
359
- if (uploaded.state === 'draft_ready') await production.events.bindPending(
360
- { name:task.name,engine:task.result.engine,owner:status.user_id },uploaded.conversation_id);
361
- return uploaded;
362
- },{ 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 }));
358
+ const { task,project } = await completedCheck(args.check_task_id,args.name,resume);
359
+ result = viewTask(await tasks.start(args.name,'upload',signal=>drafts.upload(task,status.user_id,signal,{ ...args,project }),
360
+ { 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 }));
363
361
  break;
364
362
  }
365
363
  case 'craft_game_upload_status': {