@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
@@ -1,145 +1,145 @@
1
- import { parse, stringify } from 'smol-toml';
2
- import { isDeepStrictEqual } from 'node:util';
3
- import { readDshConfig, dshRegistrations, mergeDshConfig } from './dsh-config.mjs';
4
-
5
- function object(value) { return value !== null && typeof value === 'object' && !Array.isArray(value); }
6
- function serverTable(config, ide) { return ide === 'zcode' ? config.mcp?.servers : config[ide === 'codex' ? 'mcp_servers' : 'mcpServers']; }
7
- function withServerTable(config, ide, servers) {
8
- return ide === 'zcode' ? { ...config, mcp: { ...config.mcp, servers } } : { ...config, [ide === 'codex' ? 'mcp_servers' : 'mcpServers']: servers };
9
- }
10
-
11
- export function readConfig(text, ide) {
12
- if (ide === 'dsh') return readDshConfig(text);
13
- const config = text.trim() ? (ide === 'codex' ? parse(text) : JSON.parse(text)) : {};
14
- if (!object(config)) throw new Error('Expected an object config');
15
- if (ide === 'zcode' && config.mcp !== undefined && !object(config.mcp)) throw new Error('Invalid ZCode MCP config');
16
- const servers = serverTable(config, ide);
17
- if (servers !== undefined && !object(servers)) throw new Error('Invalid MCP server table');
18
- return config;
19
- }
20
-
21
- export function craftConfig(text, ide, name = 'craft') {
22
- if (ide === 'dsh') return dshRegistrations(text).find(entry => entry.name === name)?.connection;
23
- return serverTable(readConfig(text, ide), ide)?.[name];
24
- }
25
-
26
- export function craftRegistrations(text, ide) {
27
- if (ide === 'dsh') return dshRegistrations(text);
28
- const servers = serverTable(readConfig(text, ide), ide) ?? {};
29
- return Object.entries(servers).filter(([name, value]) => name === 'craft' || (Array.isArray(value?.args) && value.args.some(arg => typeof arg === 'string' && /^@craft_eco\/craft-mcp(?:@[^\s]+)?$/.test(arg)))).map(([name, connection]) => ({ name, connection }));
30
- }
31
-
32
- // ZCode's native table replaces the entire same-scope .agents fallback. Import
33
- // currently effective declarations before adding the first native server.
34
- export function importZcodeFallback(text, fallbackText) {
35
- const before = readConfig(text, 'zcode');
36
- if (Object.keys(serverTable(before, 'zcode') ?? {}).length || !fallbackText?.trim()) return text;
37
- const fallback = readConfig(fallbackText, 'cursor'), servers = fallback.mcpServers ?? {};
38
- if (!Object.keys(servers).length) return text;
39
- const preserved = Object.fromEntries(Object.entries(servers).map(([name, server]) => [name, validateZcodeServer(server, name)]));
40
- return JSON.stringify(withServerTable(before, 'zcode', preserved), null, 2) + '\n';
41
- }
42
-
43
- function validateZcodeServer(server, name) {
44
- const fail = () => { throw new Error('ZCode MCP entry cannot be preserved safely: ' + name + '; repair its schema before installing; config was preserved'); };
45
- if (!object(server)) fail();
46
- const normalized = { ...server };
47
- if (normalized.env === undefined && normalized.environment !== undefined) normalized.env = normalized.environment;
48
- if (normalized.headers === undefined && normalized.http_headers !== undefined) normalized.headers = normalized.http_headers;
49
- if (normalized.enable !== undefined) {
50
- if (typeof normalized.enable !== 'boolean') fail();
51
- normalized.enabled = normalized.enable === false ? false : normalized.enabled ?? true;
52
- }
53
- for (const key of ['environment', 'http_headers', 'enable', 'timeout', 'startup_timeout_sec']) delete normalized[key];
54
- if (normalized.type === 'remote') normalized.type = 'http';
55
- normalized.type ??= normalized.command ? 'stdio' : normalized.url ? 'http' : undefined;
56
- const common = ['alwaysLoad', 'isolation', 'protocolVersion', 'enabled', 'timeoutMs', 'type'];
57
- const fields = normalized.type === 'stdio' ? ['command', 'args', 'cwd', 'env'] : ['url', 'headers', 'oauth'];
58
- if (!['stdio', 'http', 'sse'].includes(normalized.type) || Object.keys(normalized).some(key => ![...common, ...fields].includes(key))) fail();
59
- if (normalized.type === 'stdio') {
60
- if (typeof normalized.command !== 'string' || !normalized.command.trim()) fail();
61
- if (normalized.args !== undefined && (!Array.isArray(normalized.args) || normalized.args.some(arg => typeof arg !== 'string'))) fail();
62
- if (normalized.cwd !== undefined && (typeof normalized.cwd !== 'string' || !normalized.cwd)) fail();
63
- } else if (typeof normalized.url !== 'string' || !normalized.url) fail();
64
- for (const field of ['env', 'headers']) if (normalized[field] !== undefined && (!object(normalized[field]) || Object.values(normalized[field]).some(value => typeof value !== 'string'))) fail();
65
- for (const field of ['alwaysLoad', 'enabled']) if (normalized[field] !== undefined && typeof normalized[field] !== 'boolean') fail();
66
- if (normalized.timeoutMs !== undefined && !(Number.isFinite(normalized.timeoutMs) && normalized.timeoutMs > 0)) fail();
67
- if (normalized.isolation !== undefined && !['session', 'workspace'].includes(normalized.isolation)) fail();
68
- if (normalized.protocolVersion !== undefined && !['auto', 'legacy', '2026-07-28'].includes(normalized.protocolVersion)) fail();
69
- // Complex OAuth declarations need the host's own importer; do not silently
70
- // replace a working fallback when the installer cannot prove equivalence.
71
- if (normalized.oauth !== undefined) fail();
72
- return normalized;
73
- }
74
-
75
- // Track strings and value arrays so apparent headers inside multiline values stay untouched.
76
- function sections(text) {
77
- const found = []; let offset = 0, quote = null, multiline = false, depth = 0;
78
- for (const line of text.match(/[^\n]*\n|[^\n]+$/g) ?? []) {
79
- if (!quote && depth === 0 && /^\s*\[/.test(line)) {
80
- const header = parse(line), keys = []; let child = header;
81
- while (child && typeof child === 'object' && !Array.isArray(child) && Object.keys(child).length === 1) {
82
- const key = Object.keys(child)[0]; keys.push(key); child = child[key];
83
- }
84
- found.push({ start: offset, keys });
85
- } else {
86
- for (let i = 0; i < line.length; i++) {
87
- const c = line[i];
88
- if (quote) {
89
- if (quote === '"' && c === '\\') { i++; continue; }
90
- if (c === quote) {
91
- if (!multiline) quote = null;
92
- else if (line.slice(i, i + 3) === quote.repeat(3)) {
93
- while (line[i + 3] === quote) i++;
94
- i += 2; quote = null; multiline = false;
95
- }
96
- }
97
- } else if (c === '#') break;
98
- else if (c === '"' || c === "'") { quote = c; multiline = line.slice(i, i + 3) === c.repeat(3); if (multiline) i += 2; }
99
- else if (c === '[' || c === '{') depth++;
100
- else if (c === ']' || c === '}') depth--;
101
- }
102
- }
103
- offset += line.length;
104
- }
105
- return found.map((section, i) => ({ ...section, end: found[i + 1]?.start ?? text.length }));
106
- }
107
-
108
- export function mergeConfig(text, ide, connection, { previousName = 'craft', enable = true } = {}) {
109
- if (ide === 'dsh') return mergeDshConfig(text, connection, { previousName, enable });
110
- const before = readConfig(text, ide), servers = serverTable(before, ide);
111
- if (previousName !== 'craft' && servers?.craft) throw new Error('Craft installation conflicts with an existing craft registration');
112
- const previous = servers?.[previousName] ?? {};
113
- if (!object(previous)) throw new Error('Invalid craft server entry');
114
- // Preserve host-specific options and user environment; replace only connection identity.
115
- let next = { ...previous, ...connection, env: { ...(ide === 'zcode' ? previous.environment : {}), ...previous.env, ...connection.env } };
116
- for (const key of ['url', 'headers', 'http_headers', 'env_http_headers', 'bearer_token_env_var', 'bearerTokenEnvVar', 'oauth', 'auth']) delete next[key];
117
- if (ide === 'codex') { delete next.disabled; next.enabled = true; }
118
- else if (['claude', 'zcode', 'kimi'].includes(ide)) {
119
- for (const key of ['disabled', 'enable', 'timeout', 'startup_timeout_sec']) delete next[key];
120
- if (ide === 'claude') { delete next.enabled; delete next.timeoutMs; delete next.startupTimeoutMs; }
121
- else {
122
- next.enabled = true;
123
- if (ide === 'zcode') { delete next.startupTimeoutMs; next = validateZcodeServer(next, 'craft'); }
124
- else { delete next.type; delete next.timeoutMs; delete next.environment_id; next.transport = 'stdio'; next.executor = 'local'; }
125
- }
126
- } else { delete next.enabled; next.disabled = false; }
127
- if (!enable) for (const key of ['enabled', 'disabled', 'enable']) {
128
- if (Object.hasOwn(previous, key)) next[key] = previous[key]; else delete next[key];
129
- }
130
- const normalizedNext = ide === 'codex' ? parse(stringify({ value: next })).value : next;
131
- if (previousName === 'craft' && isDeepStrictEqual(previous, normalizedNext)) return text;
132
- const nextServers = { ...servers, craft: next };
133
- if (previousName !== 'craft') delete nextServers[previousName];
134
- const expected = withServerTable(before, ide, nextServers);
135
- if (ide !== 'codex') return JSON.stringify(expected, null, 2) + '\n';
136
- const owned = sections(text).filter(({ keys }) => keys[0] === 'mcp_servers' && keys[1] === previousName);
137
- if (before.mcp_servers?.[previousName] && !owned.length) throw new Error('Inline/dotted craft TOML entry: move it to [mcp_servers.craft] before installing; config was preserved');
138
- let kept = '', from = 0;
139
- for (const section of owned) { kept += text.slice(from, section.start); from = section.end; }
140
- kept += text.slice(from);
141
- const output = kept + (kept.endsWith('\n') || !kept ? '' : '\n') + '\n' + stringify({ mcp_servers: { craft: next } });
142
- // This also rejects unsupported inline parent tables without changing the user's file.
143
- if (!isDeepStrictEqual(parse(output), parse(stringify(expected)))) throw new Error('TOML merge changed unrelated settings; config was preserved');
144
- return output;
145
- }
1
+ import { parse, stringify } from 'smol-toml';
2
+ import { isDeepStrictEqual } from 'node:util';
3
+ import { readDshConfig, dshRegistrations, mergeDshConfig } from './dsh-config.mjs';
4
+
5
+ function object(value) { return value !== null && typeof value === 'object' && !Array.isArray(value); }
6
+ function serverTable(config, ide) { return ide === 'zcode' ? config.mcp?.servers : config[ide === 'codex' ? 'mcp_servers' : 'mcpServers']; }
7
+ function withServerTable(config, ide, servers) {
8
+ return ide === 'zcode' ? { ...config, mcp: { ...config.mcp, servers } } : { ...config, [ide === 'codex' ? 'mcp_servers' : 'mcpServers']: servers };
9
+ }
10
+
11
+ export function readConfig(text, ide) {
12
+ if (ide === 'dsh') return readDshConfig(text);
13
+ const config = text.trim() ? (ide === 'codex' ? parse(text) : JSON.parse(text)) : {};
14
+ if (!object(config)) throw new Error('Expected an object config');
15
+ if (ide === 'zcode' && config.mcp !== undefined && !object(config.mcp)) throw new Error('Invalid ZCode MCP config');
16
+ const servers = serverTable(config, ide);
17
+ if (servers !== undefined && !object(servers)) throw new Error('Invalid MCP server table');
18
+ return config;
19
+ }
20
+
21
+ export function craftConfig(text, ide, name = 'craft') {
22
+ if (ide === 'dsh') return dshRegistrations(text).find(entry => entry.name === name)?.connection;
23
+ return serverTable(readConfig(text, ide), ide)?.[name];
24
+ }
25
+
26
+ export function craftRegistrations(text, ide) {
27
+ if (ide === 'dsh') return dshRegistrations(text);
28
+ const servers = serverTable(readConfig(text, ide), ide) ?? {};
29
+ return Object.entries(servers).filter(([name, value]) => name === 'craft' || (Array.isArray(value?.args) && value.args.some(arg => typeof arg === 'string' && /^@craft_eco\/craft-mcp(?:@[^\s]+)?$/.test(arg)))).map(([name, connection]) => ({ name, connection }));
30
+ }
31
+
32
+ // ZCode's native table replaces the entire same-scope .agents fallback. Import
33
+ // currently effective declarations before adding the first native server.
34
+ export function importZcodeFallback(text, fallbackText) {
35
+ const before = readConfig(text, 'zcode');
36
+ if (Object.keys(serverTable(before, 'zcode') ?? {}).length || !fallbackText?.trim()) return text;
37
+ const fallback = readConfig(fallbackText, 'cursor'), servers = fallback.mcpServers ?? {};
38
+ if (!Object.keys(servers).length) return text;
39
+ const preserved = Object.fromEntries(Object.entries(servers).map(([name, server]) => [name, validateZcodeServer(server, name)]));
40
+ return JSON.stringify(withServerTable(before, 'zcode', preserved), null, 2) + '\n';
41
+ }
42
+
43
+ function validateZcodeServer(server, name) {
44
+ const fail = () => { throw new Error('ZCode MCP entry cannot be preserved safely: ' + name + '; repair its schema before installing; config was preserved'); };
45
+ if (!object(server)) fail();
46
+ const normalized = { ...server };
47
+ if (normalized.env === undefined && normalized.environment !== undefined) normalized.env = normalized.environment;
48
+ if (normalized.headers === undefined && normalized.http_headers !== undefined) normalized.headers = normalized.http_headers;
49
+ if (normalized.enable !== undefined) {
50
+ if (typeof normalized.enable !== 'boolean') fail();
51
+ normalized.enabled = normalized.enable === false ? false : normalized.enabled ?? true;
52
+ }
53
+ for (const key of ['environment', 'http_headers', 'enable', 'timeout', 'startup_timeout_sec']) delete normalized[key];
54
+ if (normalized.type === 'remote') normalized.type = 'http';
55
+ normalized.type ??= normalized.command ? 'stdio' : normalized.url ? 'http' : undefined;
56
+ const common = ['alwaysLoad', 'isolation', 'protocolVersion', 'enabled', 'timeoutMs', 'type'];
57
+ const fields = normalized.type === 'stdio' ? ['command', 'args', 'cwd', 'env'] : ['url', 'headers', 'oauth'];
58
+ if (!['stdio', 'http', 'sse'].includes(normalized.type) || Object.keys(normalized).some(key => ![...common, ...fields].includes(key))) fail();
59
+ if (normalized.type === 'stdio') {
60
+ if (typeof normalized.command !== 'string' || !normalized.command.trim()) fail();
61
+ if (normalized.args !== undefined && (!Array.isArray(normalized.args) || normalized.args.some(arg => typeof arg !== 'string'))) fail();
62
+ if (normalized.cwd !== undefined && (typeof normalized.cwd !== 'string' || !normalized.cwd)) fail();
63
+ } else if (typeof normalized.url !== 'string' || !normalized.url) fail();
64
+ for (const field of ['env', 'headers']) if (normalized[field] !== undefined && (!object(normalized[field]) || Object.values(normalized[field]).some(value => typeof value !== 'string'))) fail();
65
+ for (const field of ['alwaysLoad', 'enabled']) if (normalized[field] !== undefined && typeof normalized[field] !== 'boolean') fail();
66
+ if (normalized.timeoutMs !== undefined && !(Number.isFinite(normalized.timeoutMs) && normalized.timeoutMs > 0)) fail();
67
+ if (normalized.isolation !== undefined && !['session', 'workspace'].includes(normalized.isolation)) fail();
68
+ if (normalized.protocolVersion !== undefined && !['auto', 'legacy', '2026-07-28'].includes(normalized.protocolVersion)) fail();
69
+ // Complex OAuth declarations need the host's own importer; do not silently
70
+ // replace a working fallback when the installer cannot prove equivalence.
71
+ if (normalized.oauth !== undefined) fail();
72
+ return normalized;
73
+ }
74
+
75
+ // Track strings and value arrays so apparent headers inside multiline values stay untouched.
76
+ function sections(text) {
77
+ const found = []; let offset = 0, quote = null, multiline = false, depth = 0;
78
+ for (const line of text.match(/[^\n]*\n|[^\n]+$/g) ?? []) {
79
+ if (!quote && depth === 0 && /^\s*\[/.test(line)) {
80
+ const header = parse(line), keys = []; let child = header;
81
+ while (child && typeof child === 'object' && !Array.isArray(child) && Object.keys(child).length === 1) {
82
+ const key = Object.keys(child)[0]; keys.push(key); child = child[key];
83
+ }
84
+ found.push({ start: offset, keys });
85
+ } else {
86
+ for (let i = 0; i < line.length; i++) {
87
+ const c = line[i];
88
+ if (quote) {
89
+ if (quote === '"' && c === '\\') { i++; continue; }
90
+ if (c === quote) {
91
+ if (!multiline) quote = null;
92
+ else if (line.slice(i, i + 3) === quote.repeat(3)) {
93
+ while (line[i + 3] === quote) i++;
94
+ i += 2; quote = null; multiline = false;
95
+ }
96
+ }
97
+ } else if (c === '#') break;
98
+ else if (c === '"' || c === "'") { quote = c; multiline = line.slice(i, i + 3) === c.repeat(3); if (multiline) i += 2; }
99
+ else if (c === '[' || c === '{') depth++;
100
+ else if (c === ']' || c === '}') depth--;
101
+ }
102
+ }
103
+ offset += line.length;
104
+ }
105
+ return found.map((section, i) => ({ ...section, end: found[i + 1]?.start ?? text.length }));
106
+ }
107
+
108
+ export function mergeConfig(text, ide, connection, { previousName = 'craft', enable = true } = {}) {
109
+ if (ide === 'dsh') return mergeDshConfig(text, connection, { previousName, enable });
110
+ const before = readConfig(text, ide), servers = serverTable(before, ide);
111
+ if (previousName !== 'craft' && servers?.craft) throw new Error('Craft installation conflicts with an existing craft registration');
112
+ const previous = servers?.[previousName] ?? {};
113
+ if (!object(previous)) throw new Error('Invalid craft server entry');
114
+ // Preserve host-specific options and user environment; replace only connection identity.
115
+ let next = { ...previous, ...connection, env: { ...(ide === 'zcode' ? previous.environment : {}), ...previous.env, ...connection.env } };
116
+ for (const key of ['url', 'headers', 'http_headers', 'env_http_headers', 'bearer_token_env_var', 'bearerTokenEnvVar', 'oauth', 'auth']) delete next[key];
117
+ if (ide === 'codex') { delete next.disabled; next.enabled = true; }
118
+ else if (['claude', 'zcode', 'kimi'].includes(ide)) {
119
+ for (const key of ['disabled', 'enable', 'timeout', 'startup_timeout_sec']) delete next[key];
120
+ if (ide === 'claude') { delete next.enabled; delete next.timeoutMs; delete next.startupTimeoutMs; }
121
+ else {
122
+ next.enabled = true;
123
+ if (ide === 'zcode') { delete next.startupTimeoutMs; next = validateZcodeServer(next, 'craft'); }
124
+ else { delete next.type; delete next.timeoutMs; delete next.environment_id; next.transport = 'stdio'; next.executor = 'local'; }
125
+ }
126
+ } else { delete next.enabled; next.disabled = false; }
127
+ if (!enable) for (const key of ['enabled', 'disabled', 'enable']) {
128
+ if (Object.hasOwn(previous, key)) next[key] = previous[key]; else delete next[key];
129
+ }
130
+ const normalizedNext = ide === 'codex' ? parse(stringify({ value: next })).value : next;
131
+ if (previousName === 'craft' && isDeepStrictEqual(previous, normalizedNext)) return text;
132
+ const nextServers = { ...servers, craft: next };
133
+ if (previousName !== 'craft') delete nextServers[previousName];
134
+ const expected = withServerTable(before, ide, nextServers);
135
+ if (ide !== 'codex') return JSON.stringify(expected, null, 2) + '\n';
136
+ const owned = sections(text).filter(({ keys }) => keys[0] === 'mcp_servers' && keys[1] === previousName);
137
+ if (before.mcp_servers?.[previousName] && !owned.length) throw new Error('Inline/dotted craft TOML entry: move it to [mcp_servers.craft] before installing; config was preserved');
138
+ let kept = '', from = 0;
139
+ for (const section of owned) { kept += text.slice(from, section.start); from = section.end; }
140
+ kept += text.slice(from);
141
+ const output = kept + (kept.endsWith('\n') || !kept ? '' : '\n') + '\n' + stringify({ mcp_servers: { craft: next } });
142
+ // This also rejects unsupported inline parent tables without changing the user's file.
143
+ if (!isDeepStrictEqual(parse(output), parse(stringify(expected)))) throw new Error('TOML merge changed unrelated settings; config was preserved');
144
+ return output;
145
+ }
@@ -0,0 +1,36 @@
1
+ import os from 'node:os';
2
+ import path from 'node:path';
3
+ import { spawn } from 'node:child_process';
4
+ import { hostPaths, hostEnvironment, installTargets } from './hosts.mjs';
5
+ import { craftRegistrations } from './config.mjs';
6
+ import { optionalFile } from './files.mjs';
7
+ import { readInstallation } from './installation-state.mjs';
8
+ import { verifyLauncher } from './fixed-launcher.mjs';
9
+
10
+ // Optional expert/connector declarations use this resolver, never a second
11
+ // installer or an unmanaged business runtime. No host settings are written.
12
+ export async function installedConnection(ide, { home = os.homedir(), codexHome = process.env.CODEX_HOME, hostOptions = hostEnvironment(), env = process.env } = {}) {
13
+ const targets = installTargets(ide);
14
+ if (targets.length !== 1) throw new Error('connect requires exactly one host');
15
+ const host = targets[0], paths = hostPaths(home, host, codexHome, hostOptions);
16
+ const registrations = craftRegistrations(await optionalFile(paths.config) ?? '', host);
17
+ if (registrations.length !== 1) throw new Error('Run craft-mcp install --ide ' + host + ' first; connect requires one standard Craft installation');
18
+ const connection = registrations[0].connection, file = connection.env?.CRAFT_INSTALLATION_FILE;
19
+ const state = await readInstallation(file);
20
+ if (state.host !== host || path.resolve(state.config) !== path.resolve(paths.config)) throw new Error('Craft installation belongs to another host scope');
21
+ if (connection.disabled === true || connection.enabled === false || connection.enable === false) throw new Error('Craft is disabled in the host; enable the existing installation first');
22
+ await verifyLauncher(state, file, connection);
23
+ for (const [key, expected] of Object.entries({ CRAFT_WEB_URL: state.platform, CLIENT_WORKSPACE_ROOT: state.workspace, CRAFT_CLIENT_IDE: host })) {
24
+ if (env[key] && env[key] !== expected) throw new Error('Craft connector scope differs from the standard installation: ' + key);
25
+ }
26
+ return { command: process.execPath, args: [state.launcher.entry, '--workspace', state.workspace], env: { ...env, ...connection.env }, installation: file };
27
+ }
28
+
29
+ export async function connectInstalledHost(ide) {
30
+ const connection = await installedConnection(ide);
31
+ const child = spawn(connection.command, connection.args, { env: connection.env, stdio: 'inherit', shell: false, windowsHide: true });
32
+ const stop = () => child.kill('SIGTERM');
33
+ process.once('SIGINT', stop); process.once('SIGTERM', stop);
34
+ try { process.exitCode = await new Promise((resolve, reject) => { child.once('error', reject); child.once('close', code => resolve(code ?? 1)); }); }
35
+ finally { process.removeListener('SIGINT', stop); process.removeListener('SIGTERM', stop); }
36
+ }
@@ -1,42 +1,36 @@
1
- // The MCP process cannot discover or invoke its parent's control plane. This
2
- // contract is consumed by the host agent after the update response completes.
3
- export function connectionHandoff({ host, target, current, workspace, platform, serverId = 'craft', busy, intent = 'inspect', name, requestKey }) {
4
- const readOnly = intent === 'inspect';
5
- const idle = busy?.can_reconnect;
6
- const codex = host === 'codex';
7
- const workbuddy = host === 'workbuddy';
8
- const state = readOnly ? 'inspect_only' : idle === false ? 'wait_for_idle' : idle === true ? 'ready' : 'check_current_connection';
9
- const fallback = workbuddy
10
- ? ['在 WorkBuddy 的“专家·技能·连接器 → 连接器 → 自定义连接器”中重连 Craft。',
11
- '实际版本仍旧时,保存进度,从 Windows 托盘完整退出 WorkBuddy 后重新打开,等待 Craft 就绪;仅关闭窗口可能保留后台。',
12
- '只有页面实际提示未信任时才由用户点击“信任”;每次更新不一定需要重新信任。']
13
- : [`使用 ${codex ? 'Codex' : '宿主'} 提供的 Craft 重连入口。`,
14
- `重连后实际版本仍旧或没有重连入口时,保存进度,完整退出并重新打开 ${codex ? 'Codex' : '宿主'}。`,
15
- '仅在宿主实际要求信任或授权时,按其提示由用户完成。'];
16
- const next = readOnly
17
- ? '本次仅检查版本,不自动重载或重启。开始创建、恢复或明确更新时,再处理当前连接切版。'
18
- : idle === false
19
- ? '先等待活动任务结束,保存进度并 release 本会话的工作;其他会话占用等待其正常释放。再查询忙闲状态,现在不要重载或重启。'
20
- : `${idle === true ? '' : '先查询当前宿主聊天的 Craft 连接并确认没有活动工作。'}${codex
21
- ? '若宿主实际提供可控制当前聊天的原生重载能力,先遵循宿主规则确认其影响范围内没有活动工作,再于更新调用返回后自动尝试一次;本连接空闲不代表其他聊天空闲。无法确认作用范围、能力缺失、失败或仍是旧版时按回退步骤提示用户。'
22
- : '完成活动工作后按宿主回退步骤重连 Craft。'}重连后必须通过当前聊天的 craft_game_info 核对实际版本、build_id、instance_id、active_verified 和宿主范围;安装回执、重载成功提示或连接绿灯不能代替核验。`;
23
- return {
24
- schema: 1, executor: 'host_agent', host, server_id: serverId, intent, state,
25
- after_response: true,
26
- automatic_reload: readOnly ? 'disabled_read_only' : codex ? 'if_host_capability_available' : 'not_requested',
27
- automatic_reload_attempts: readOnly || !codex ? 0 : 1,
28
- capability_source: 'actual_host_tools', capability_availability: 'not_observable_from_mcp',
29
- busy: busy ?? null, busy_scope: 'current_connection',
30
- preflight: { tool: 'craft_game_info', require_idle: true, honor_host_control_scope: true, require_control_scope_idle: true,
31
- unknown_control_scope: 'manual_reconnect', if_already_verified: 'continue_without_reload' },
32
- expected: { version: target?.version, build_id: target?.build_id, host, workspace, platform },
33
- ...(current?.instance_id ? { previous_instance_id: current.instance_id } : {}),
34
- verify: { tool: 'craft_game_info', arguments: name ? { name } : {}, scope: 'current_chat_connection',
35
- required: ['version', 'runtime.version', 'runtime.build_id', 'runtime.instance_id', 'runtime.activation.status', 'host', 'workspace', 'platform'],
36
- activation_status: 'active_verified', recheck_busy_before_reload: true,
37
- require_new_instance: Boolean(current?.instance_id && (current.version !== target?.version || current.build_id !== target?.build_id)),
38
- independent_probe_is_not_confirmation: true },
39
- retry: { ...(requestKey ? { request_key: requestKey } : {}), only_explicitly_unstarted_prepare: true, never_replay_paid_operations: true },
40
- fallback, next,
41
- };
42
- }
1
+ // The MCP process cannot discover or invoke its parent's control plane. This
2
+ // contract is consumed by the host agent after the update response completes.
3
+ import { hostReloadProfile } from './host-reload.mjs';
4
+ export function connectionHandoff({ host, target, current, workspace, platform, serverId = 'craft', busy, intent = 'inspect', name, requestKey }) {
5
+ const readOnly = intent === 'inspect';
6
+ const idle = busy?.can_reconnect;
7
+ const profile = hostReloadProfile(host);
8
+ const state = readOnly ? 'inspect_only' : idle === false ? 'wait_for_idle' : idle === true ? 'ready' : 'check_current_connection';
9
+ const fallback = [profile.fallback, '只有页面实际提示未信任或授权时才由用户按提示确认;每次更新不一定需要重新信任。'];
10
+ const next = readOnly
11
+ ? '本次仅检查版本,不安装、不重连。已安装新版将在下一次 MCP 启动或用户重连后生效。'
12
+ : idle === false
13
+ ? '新版已安装,当前进程继续使用原版本。先完成活动任务、保存进度并 release;不要为更新中断工作。新版将在下次 MCP 启动或用户重连后加载。'
14
+ : '新版已安装,当前进程保持原版本。下一次 MCP 启动或用户重连后,通过当前聊天的 craft_game_info 核对实际 version、build_id、active_verified 与宿主范围;无需新建聊天。确认后 prepare(resume) 更新当前项目的上下文和 Skill,再重新读取入口与技能索引。不要主动重载宿主或把安装探测当作当前连接确认。';
15
+ return {
16
+ schema: 2, executor: 'host_agent', host, host_profile: profile, server_id: serverId, intent, state,
17
+ after_response: true,
18
+ automatic_reload: readOnly ? 'disabled_read_only' : 'user_requested_reconnect',
19
+ automatic_reload_attempts: 0,
20
+ strategy: ['wait_for_next_mcp_start_or_user_reconnect', 'verify_current_connection', 'prepare_current_project_context'],
21
+ capability_source: 'actual_host_tools', capability_availability: 'not_observable_from_mcp',
22
+ busy: busy ?? null, busy_scope: 'current_connection',
23
+ preflight: { tool: 'craft_game_info', require_idle: true, honor_host_control_scope: true, require_control_scope_idle: true,
24
+ unknown_control_scope: 'manual_reconnect', if_already_verified: 'continue_without_reload' },
25
+ expected: { version: target?.version, build_id: target?.build_id, host, workspace, platform },
26
+ ...(current?.instance_id ? { previous_instance_id: current.instance_id } : {}),
27
+ verify: { tool: 'craft_game_info', arguments: name ? { name } : {}, scope: 'current_chat_connection',
28
+ required: ['version', 'runtime.version', 'runtime.build_id', 'runtime.instance_id', 'runtime.activation.status', 'host', 'workspace', 'platform'],
29
+ activation_status: 'active_verified', recheck_busy_before_reload: true,
30
+ after_reload: { max_reads: 10, interval_ms: 500, retry_transient_connection_errors: true, never_repeat_reload: true },
31
+ require_new_instance: Boolean(current?.instance_id && (current.version !== target?.version || current.build_id !== target?.build_id)),
32
+ independent_probe_is_not_confirmation: true },
33
+ retry: { ...(requestKey ? { request_key: requestKey } : {}), only_explicitly_unstarted_prepare: true, never_replay_paid_operations: true },
34
+ fallback, next,
35
+ };
36
+ }