codexmate 0.1.30 → 0.1.32

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 (77) hide show
  1. package/README.md +98 -7
  2. package/README.vi.md +98 -7
  3. package/README.zh.md +99 -7
  4. package/cli/agents-files.js +18 -4
  5. package/cli/config-bootstrap.js +25 -11
  6. package/cli/plugin-config.js +64 -0
  7. package/cli/prompt-history.js +17 -4
  8. package/cli/system-prompt-files.js +7 -2
  9. package/cli.js +396 -46
  10. package/lib/cli-config-engine.js +266 -0
  11. package/lib/cli-utils.js +2 -1
  12. package/lib/cli-webhook.js +1 -1
  13. package/lib/handoff-mcp.js +282 -0
  14. package/lib/http-access-control.js +335 -0
  15. package/lib/session-context-health.js +82 -0
  16. package/lib/session-context-records.js +153 -0
  17. package/lib/thread-handoff.js +130 -0
  18. package/lib/web-startup-auth.js +53 -0
  19. package/lib/workflow-engine.js +92 -21
  20. package/lib/workflow-runner.js +261 -0
  21. package/package.json +1 -1
  22. package/plugins/prompt-templates/computed.mjs +3 -3
  23. package/plugins/prompt-templates/invocation.mjs +73 -0
  24. package/plugins/prompt-templates/methods.mjs +48 -3
  25. package/plugins/prompt-templates/overview.mjs +2 -0
  26. package/web-ui/app.js +48 -2
  27. package/web-ui/index.html +1 -0
  28. package/web-ui/logic.context-health.mjs +144 -0
  29. package/web-ui/modules/access-token.mjs +33 -0
  30. package/web-ui/modules/api.mjs +2 -1
  31. package/web-ui/modules/app.computed.prompts.mjs +11 -0
  32. package/web-ui/modules/app.methods.agents.mjs +20 -3
  33. package/web-ui/modules/app.methods.index.mjs +6 -0
  34. package/web-ui/modules/app.methods.navigation.mjs +17 -3
  35. package/web-ui/modules/app.methods.prompts-editor.mjs +7 -0
  36. package/web-ui/modules/app.methods.providers.mjs +2 -2
  37. package/web-ui/modules/app.methods.runtime.mjs +3 -2
  38. package/web-ui/modules/app.methods.session-actions.mjs +3 -0
  39. package/web-ui/modules/app.methods.session-browser.mjs +6 -2
  40. package/web-ui/modules/app.methods.system-prompt.mjs +17 -2
  41. package/web-ui/modules/app.methods.workflows.mjs +41 -0
  42. package/web-ui/modules/context-health.methods.mjs +70 -0
  43. package/web-ui/modules/i18n/locales/en.mjs +70 -2
  44. package/web-ui/modules/i18n/locales/ja.mjs +70 -2
  45. package/web-ui/modules/i18n/locales/vi.mjs +70 -2
  46. package/web-ui/modules/i18n/locales/zh-tw.mjs +70 -2
  47. package/web-ui/modules/i18n/locales/zh.mjs +70 -2
  48. package/web-ui/modules/plugins.methods.mjs +2 -0
  49. package/web-ui/modules/prompt-ecosystem.methods.mjs +136 -0
  50. package/web-ui/modules/sessions-filters-url.mjs +3 -0
  51. package/web-ui/modules/skills.methods.mjs +6 -5
  52. package/web-ui/modules/thread-handoff.mjs +142 -0
  53. package/web-ui/partials/index/context-health.html +45 -0
  54. package/web-ui/partials/index/modal-prompt-invocation.html +17 -0
  55. package/web-ui/partials/index/panel-config-claude.html +2 -0
  56. package/web-ui/partials/index/panel-config-codex.html +2 -0
  57. package/web-ui/partials/index/panel-config-kilocode.html +3 -1
  58. package/web-ui/partials/index/panel-config-openclaw.html +2 -0
  59. package/web-ui/partials/index/panel-config-opencode.html +3 -1
  60. package/web-ui/partials/index/panel-config-pi.html +2 -0
  61. package/web-ui/partials/index/panel-dashboard.html +59 -0
  62. package/web-ui/partials/index/panel-plugins.html +37 -9
  63. package/web-ui/partials/index/panel-prompts.html +46 -18
  64. package/web-ui/partials/index/panel-sessions.html +35 -44
  65. package/web-ui/partials/index/thread-handoff.html +59 -0
  66. package/web-ui/res/web-ui-render.precompiled.js +1289 -177
  67. package/web-ui/styles/context-health.css +107 -0
  68. package/web-ui/styles/controls-forms.css +9 -0
  69. package/web-ui/styles/dashboard.css +51 -0
  70. package/web-ui/styles/modals-core.css +87 -0
  71. package/web-ui/styles/navigation-panels.css +1 -1
  72. package/web-ui/styles/plugins-panel.css +62 -0
  73. package/web-ui/styles/prompts-editor.css +34 -4
  74. package/web-ui/styles/responsive.css +19 -10
  75. package/web-ui/styles/sessions-preview.css +206 -111
  76. package/web-ui/styles/sub-tabs.css +181 -0
  77. package/web-ui/styles.css +2 -0
@@ -0,0 +1,266 @@
1
+ const crypto = require('crypto');
2
+ const fs = require('fs');
3
+ const path = require('path');
4
+ const toml = require('@iarna/toml');
5
+
6
+ const PROVIDER_NAME_PATTERN = /^[a-zA-Z0-9_-]+$/;
7
+ const PROVIDER_NAME_MESSAGE = '名称仅支持字母/数字/_-';
8
+
9
+ function normalizeProviderName(name) {
10
+ return typeof name === 'string' ? name.trim() : '';
11
+ }
12
+
13
+ function validateProviderName(name) {
14
+ const normalized = normalizeProviderName(name);
15
+ if (!normalized) {
16
+ return {
17
+ valid: false,
18
+ code: 'INVALID_PROVIDER_NAME',
19
+ field: 'name',
20
+ message: '名称不能为空',
21
+ name: normalized
22
+ };
23
+ }
24
+ if (!PROVIDER_NAME_PATTERN.test(normalized)) {
25
+ return {
26
+ valid: false,
27
+ code: 'INVALID_PROVIDER_NAME',
28
+ field: 'name',
29
+ message: PROVIDER_NAME_MESSAGE,
30
+ name: normalized
31
+ };
32
+ }
33
+ return {
34
+ valid: true,
35
+ code: '',
36
+ field: '',
37
+ message: '',
38
+ name: normalized
39
+ };
40
+ }
41
+
42
+ function isValidProviderName(name) {
43
+ return validateProviderName(name).valid;
44
+ }
45
+
46
+ function validateProviderNamesInParsedConfig(parsed) {
47
+ const activeProvider = parsed && typeof parsed.model_provider === 'string' ? parsed.model_provider.trim() : '';
48
+ if (activeProvider && !isValidProviderName(activeProvider)) {
49
+ return { error: `当前 provider 名称非法: ${activeProvider}(名称仅支持字母/数字/_-)` };
50
+ }
51
+ const providers = parsed && typeof parsed.model_providers === 'object' && parsed.model_providers !== null
52
+ ? parsed.model_providers
53
+ : {};
54
+ for (const name of Object.keys(providers)) {
55
+ if (!isValidProviderName(name)) {
56
+ return { error: `provider 名称非法: ${name}(名称仅支持字母/数字/_-)` };
57
+ }
58
+ }
59
+ return null;
60
+ }
61
+
62
+ function createConfigError(options = {}) {
63
+ const error = new Error(options.detail || options.message || '配置操作失败');
64
+ error.code = options.code || 'CONFIG_ERROR';
65
+ error.type = options.type || 'config';
66
+ error.path = options.path || '';
67
+ error.publicReason = options.message || error.message;
68
+ error.detail = options.detail || error.message;
69
+ error.backupPath = options.backupPath || '';
70
+ error.rolledBack = options.rolledBack === true;
71
+ error.rollbackFailed = options.rollbackFailed === true;
72
+ return error;
73
+ }
74
+
75
+ function formatConfigError(error) {
76
+ const payload = {
77
+ error: {
78
+ code: error && error.code ? error.code : 'CONFIG_ERROR',
79
+ type: error && error.type ? error.type : 'config',
80
+ path: error && error.path ? error.path : '',
81
+ message: error && error.publicReason ? error.publicReason : (error && error.message ? error.message : '配置操作失败'),
82
+ detail: error && error.detail ? error.detail : (error && error.message ? error.message : '配置操作失败')
83
+ }
84
+ };
85
+ if (error && error.backupPath) payload.error.backupPath = error.backupPath;
86
+ if (error && typeof error.rolledBack === 'boolean') payload.error.rolledBack = error.rolledBack;
87
+ if (error && error.rollbackFailed === true) payload.error.rollbackFailed = true;
88
+ return JSON.stringify(payload);
89
+ }
90
+
91
+ function hashBuffer(buffer) {
92
+ return crypto.createHash('sha256').update(buffer).digest('hex');
93
+ }
94
+
95
+ function formatBackupTimestamp(value) {
96
+ const date = value instanceof Date && !Number.isNaN(value.getTime()) ? value : new Date();
97
+ const pad = (num) => String(num).padStart(2, '0');
98
+ return [
99
+ date.getFullYear(),
100
+ pad(date.getMonth() + 1),
101
+ pad(date.getDate()),
102
+ '-',
103
+ pad(date.getHours()),
104
+ pad(date.getMinutes()),
105
+ pad(date.getSeconds()),
106
+ '-',
107
+ String(date.getMilliseconds()).padStart(3, '0')
108
+ ].join('');
109
+ }
110
+
111
+ function createBackupPath(filePath, fsImpl, now) {
112
+ const dirPath = path.dirname(filePath);
113
+ const baseName = path.basename(filePath);
114
+ const timestamp = formatBackupTimestamp(now);
115
+ const prefix = `${baseName}.codexmate-backup-${timestamp}`;
116
+ let backupPath = path.join(dirPath, `${prefix}.bak`);
117
+ let suffix = 1;
118
+ while (fsImpl.existsSync(backupPath)) {
119
+ backupPath = path.join(dirPath, `${prefix}-${suffix}.bak`);
120
+ suffix += 1;
121
+ }
122
+ return backupPath;
123
+ }
124
+
125
+ function ensureAtomicTargetWritable(filePath, fsImpl) {
126
+ if (!fsImpl.existsSync(filePath)) return 0o600;
127
+ return fsImpl.statSync(filePath).mode & 0o777;
128
+ }
129
+
130
+ function syncFile(filePath, fsImpl) {
131
+ let fd = null;
132
+ try {
133
+ fd = fsImpl.openSync(filePath, 'r');
134
+ fsImpl.fsyncSync(fd);
135
+ } catch (_) {
136
+ } finally {
137
+ if (fd !== null) {
138
+ try { fsImpl.closeSync(fd); } catch (_) {}
139
+ }
140
+ }
141
+ }
142
+
143
+ function writeBufferAtomically(filePath, buffer, mode, fsImpl) {
144
+ const tmpPath = `${filePath}.tmp-${process.pid}-${Date.now()}-${crypto.randomBytes(4).toString('hex')}`;
145
+ try {
146
+ fsImpl.writeFileSync(tmpPath, buffer, { encoding: 'utf-8', mode });
147
+ syncFile(tmpPath, fsImpl);
148
+ fsImpl.renameSync(tmpPath, filePath);
149
+ } catch (error) {
150
+ if (fsImpl.existsSync(tmpPath)) {
151
+ try { fsImpl.unlinkSync(tmpPath); } catch (_) {}
152
+ }
153
+ throw error;
154
+ }
155
+ }
156
+
157
+ function writeConfigAtomicWithBackup(filePath, content, options = {}) {
158
+ const tomlImpl = options.toml || toml;
159
+ const text = typeof content === 'string' ? content : String(content || '');
160
+
161
+ try {
162
+ tomlImpl.parse(text);
163
+ } catch (error) {
164
+ throw createConfigError({
165
+ code: 'CONFIG_TOML_WRITE_INVALID',
166
+ type: 'parse',
167
+ path: filePath,
168
+ message: '待写入的 config.toml 无效',
169
+ detail: error && error.message ? error.message : String(error)
170
+ });
171
+ }
172
+
173
+ return writeTextAtomicWithBackup(filePath, text, options);
174
+ }
175
+
176
+ function writeTextAtomicWithBackup(filePath, content, options = {}) {
177
+ const fsImpl = options.fs || fs;
178
+ const now = options.now instanceof Date ? options.now : new Date();
179
+ const text = typeof content === 'string' ? content : String(content || '');
180
+ fsImpl.mkdirSync(path.dirname(filePath), { recursive: true });
181
+ const targetExists = fsImpl.existsSync(filePath);
182
+ const originalBuffer = targetExists ? fsImpl.readFileSync(filePath) : null;
183
+ const originalHash = originalBuffer ? hashBuffer(originalBuffer) : '';
184
+ let backupPath = '';
185
+
186
+ if (targetExists) {
187
+ backupPath = createBackupPath(filePath, fsImpl, now);
188
+ try {
189
+ fsImpl.copyFileSync(filePath, backupPath);
190
+ const backupBuffer = fsImpl.readFileSync(backupPath);
191
+ if (hashBuffer(backupBuffer) !== originalHash) {
192
+ throw new Error('备份文件校验失败');
193
+ }
194
+ } catch (error) {
195
+ throw createConfigError({
196
+ code: 'CONFIG_BACKUP_FAILED',
197
+ type: 'backup',
198
+ path: filePath,
199
+ message: '创建配置备份失败',
200
+ detail: error && error.message ? error.message : String(error),
201
+ backupPath
202
+ });
203
+ }
204
+ }
205
+
206
+ const nextBuffer = Buffer.from(text, 'utf-8');
207
+ const nextHash = hashBuffer(nextBuffer);
208
+ const mode = ensureAtomicTargetWritable(filePath, fsImpl);
209
+
210
+ try {
211
+ writeBufferAtomically(filePath, nextBuffer, mode, fsImpl);
212
+ const writtenBuffer = fsImpl.readFileSync(filePath);
213
+ if (hashBuffer(writtenBuffer) !== nextHash) {
214
+ throw new Error('写入结果校验失败');
215
+ }
216
+ } catch (error) {
217
+ let rolledBack = false;
218
+ let rollbackFailed = false;
219
+ if (targetExists && backupPath) {
220
+ try {
221
+ const backupBuffer = fsImpl.readFileSync(backupPath);
222
+ writeBufferAtomically(filePath, backupBuffer, mode, fsImpl);
223
+ const restoredBuffer = fsImpl.readFileSync(filePath);
224
+ rolledBack = hashBuffer(restoredBuffer) === originalHash;
225
+ rollbackFailed = !rolledBack;
226
+ } catch (_) {
227
+ rollbackFailed = true;
228
+ }
229
+ } else if (!targetExists && fsImpl.existsSync(filePath)) {
230
+ try {
231
+ fsImpl.unlinkSync(filePath);
232
+ rolledBack = true;
233
+ } catch (_) {
234
+ rollbackFailed = true;
235
+ }
236
+ }
237
+ throw createConfigError({
238
+ code: 'CONFIG_WRITE_FAILED',
239
+ type: 'write',
240
+ path: filePath,
241
+ message: '写入配置失败',
242
+ detail: error && error.message ? error.message : String(error),
243
+ backupPath,
244
+ rolledBack,
245
+ rollbackFailed
246
+ });
247
+ }
248
+
249
+ return {
250
+ backupPath,
251
+ backupCreated: !!backupPath,
252
+ path: filePath
253
+ };
254
+ }
255
+
256
+ module.exports = {
257
+ PROVIDER_NAME_PATTERN,
258
+ PROVIDER_NAME_MESSAGE,
259
+ validateProviderName,
260
+ validateProviderNamesInParsedConfig,
261
+ isValidProviderName,
262
+ createConfigError,
263
+ formatConfigError,
264
+ writeConfigAtomicWithBackup,
265
+ writeTextAtomicWithBackup
266
+ };
package/lib/cli-utils.js CHANGED
@@ -1,4 +1,5 @@
1
1
  const fs = require('fs');
2
+ const { isValidProviderName: isValidProviderNameByRule } = require('./cli-config-engine');
2
3
  const path = require('path');
3
4
  const os = require('os');
4
5
 
@@ -68,7 +69,7 @@ function normalizeLineEnding(text, lineEnding) {
68
69
  }
69
70
 
70
71
  function isValidProviderName(name) {
71
- return typeof name === 'string' && /^[a-zA-Z0-9._-]+$/.test(name.trim());
72
+ return isValidProviderNameByRule(name);
72
73
  }
73
74
 
74
75
  function escapeTomlBasicString(value) {
@@ -5,7 +5,7 @@ const https = require('https');
5
5
  const os = require('os');
6
6
  const net = require('net');
7
7
 
8
- const ALLOWED_EVENTS = ['provider-switch', 'claude-md-edit'];
8
+ const ALLOWED_EVENTS = ['provider-switch', 'claude-md-edit', 'workflow-completed', 'workflow-failed', 'workflow-waiting'];
9
9
  const DEFAULT_TIMEOUT_MS = 5000;
10
10
 
11
11
  function isPrivateNetworkHost(hostname) {
@@ -0,0 +1,282 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const os = require('os');
4
+ const { spawn } = require('child_process');
5
+ const http = require('http');
6
+ const https = require('https');
7
+ const toml = require('@iarna/toml');
8
+
9
+ const TIMEOUT_MS = 5000;
10
+ const SHARED_SERVER = /unified.agent.context|shared.context|memory|\buac\b/i;
11
+
12
+ function discoverServers(options = {}, warnings = []) {
13
+ const cwd = options.cwd || process.cwd();
14
+ const home = options.home || os.homedir();
15
+ const sources = [
16
+ path.join(cwd, '.mcp.json'),
17
+ path.join(cwd, '.codex', 'config.toml'),
18
+ path.join(home, '.claude.json'),
19
+ path.join(home, '.claude', 'settings.json'),
20
+ path.join(home, '.codex', 'config.toml')
21
+ ];
22
+ const servers = [];
23
+ for (const file of sources) {
24
+ if (!fs.existsSync(file)) continue;
25
+ let config;
26
+ try {
27
+ const text = fs.readFileSync(file, 'utf8');
28
+ config = file.endsWith('.toml') ? toml.parse(text) : JSON.parse(text);
29
+ } catch (_) {
30
+ warnings.push({ source: path.relative(file.startsWith(cwd + path.sep) ? cwd : home, file), reason: 'MCP 配置读取或解析失败' });
31
+ continue;
32
+ }
33
+ const project = (config.projects || {})[cwd] || (config.projects || {})[cwd.split(path.sep).join('/')] || {};
34
+ const entries = { ...(config.mcpServers || config.mcp_servers || {}), ...project.mcpServers };
35
+ const disabled = new Set([...(config.disabledMcpServers || []), ...(project.disabledMcpServers || [])]);
36
+ for (const [name, entry] of Object.entries(entries)) {
37
+ if (!entry || entry.disabled || entry.enabled === false || disabled.has(name)) continue;
38
+ if (!SHARED_SERVER.test([name, entry.command, ...(entry.args || []), entry.url].join(' '))) continue;
39
+ if (!servers.some(server => server.name === name)) servers.push({ ...entry, name, cwd: entry.cwd || cwd });
40
+ }
41
+ }
42
+ return servers;
43
+ }
44
+
45
+ function openStdio(server, timeoutMs) {
46
+ const child = spawn(server.command, server.args || [], {
47
+ cwd: server.cwd || process.cwd(),
48
+ env: { ...process.env, ...(server.env || {}) },
49
+ windowsHide: true,
50
+ stdio: ['pipe', 'pipe', 'pipe']
51
+ });
52
+ let serial = 0;
53
+ let buffer = '';
54
+ let failure = null;
55
+ const pending = new Map();
56
+ function fail(error) {
57
+ failure = error;
58
+ for (const { reject } of pending.values()) reject(error);
59
+ pending.clear();
60
+ }
61
+ child.on('error', fail);
62
+ child.stdin.on('error', fail);
63
+ child.on('exit', () => fail(new Error('MCP 进程已退出')));
64
+ child.stderr.resume();
65
+ child.stdout.setEncoding('utf8');
66
+ child.stdout.on('data', chunk => {
67
+ buffer += chunk;
68
+ if (Buffer.byteLength(buffer) > 1024 * 1024) return fail(new Error('MCP 响应超过限制'));
69
+ let newline;
70
+ while ((newline = buffer.indexOf('\n')) >= 0) {
71
+ const line = buffer.slice(0, newline);
72
+ buffer = buffer.slice(newline + 1);
73
+ let message;
74
+ try { message = JSON.parse(line); } catch (_) { continue; }
75
+ const waiter = pending.get(message.id);
76
+ if (!waiter) continue;
77
+ pending.delete(message.id);
78
+ if (message.error) waiter.reject(new Error('MCP 返回协议错误'));
79
+ else waiter.resolve(message.result);
80
+ }
81
+ });
82
+ return {
83
+ request(method, params, notification = false) {
84
+ if (failure) return Promise.reject(failure);
85
+ const id = ++serial;
86
+ const message = { jsonrpc: '2.0', method, params, ...(!notification ? { id } : {}) };
87
+ if (notification) {
88
+ child.stdin.write(JSON.stringify(message) + '\n');
89
+ return Promise.resolve();
90
+ }
91
+ return new Promise((resolve, reject) => {
92
+ const timer = setTimeout(() => {
93
+ pending.delete(id);
94
+ reject(new Error('MCP 请求超时'));
95
+ }, timeoutMs);
96
+ pending.set(id, {
97
+ resolve: value => { clearTimeout(timer); resolve(value); },
98
+ reject: error => { clearTimeout(timer); reject(error); }
99
+ });
100
+ child.stdin.write(JSON.stringify(message) + '\n');
101
+ });
102
+ },
103
+ async close() {
104
+ fail(new Error('MCP 连接已关闭'));
105
+ child.stdin.end();
106
+ if (child.exitCode !== null) return;
107
+ await new Promise(resolve => {
108
+ const timer = setTimeout(() => { child.kill('SIGKILL'); resolve(); }, 250);
109
+ child.once('exit', () => { clearTimeout(timer); resolve(); });
110
+ child.kill();
111
+ });
112
+ }
113
+ };
114
+ }
115
+
116
+ function openHttp(server, timeoutMs) {
117
+ const url = new URL(server.url);
118
+ if (!['http:', 'https:'].includes(url.protocol)) throw new Error('MCP URL 协议不受支持');
119
+ let serial = 0;
120
+ let session = '';
121
+ let protocol = '';
122
+ const transport = url.protocol === 'https:' ? https : http;
123
+ function send(method, params, notification = false, closing = false) {
124
+ const id = ++serial;
125
+ const body = closing ? '' : JSON.stringify({ jsonrpc: '2.0', method, params, ...(!notification ? { id } : {}) });
126
+ return new Promise((resolve, reject) => {
127
+ const request = transport.request(url, {
128
+ method: closing ? 'DELETE' : 'POST',
129
+ headers: { ...(server.headers || {}),
130
+ ...(server.bearer_token_env_var && process.env[server.bearer_token_env_var]
131
+ ? { Authorization: `Bearer ${process.env[server.bearer_token_env_var]}` } : {}),
132
+ 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream',
133
+ ...(session ? { 'Mcp-Session-Id': session } : {}),
134
+ ...(protocol ? { 'MCP-Protocol-Version': protocol } : {}) }
135
+ }, response => {
136
+ if (response.statusCode < 200 || response.statusCode >= 300) {
137
+ response.resume();
138
+ reject(new Error(`MCP HTTP ${response.statusCode}`));
139
+ return;
140
+ }
141
+ session = response.headers['mcp-session-id'] || session;
142
+ let text = '';
143
+ response.setEncoding('utf8');
144
+ response.on('error', reject);
145
+ response.on('data', chunk => {
146
+ text += chunk;
147
+ if (Buffer.byteLength(text) > 1024 * 1024) request.destroy(new Error('MCP 响应超过限制'));
148
+ if ((response.headers['content-type'] || '').includes('text/event-stream')) {
149
+ const events = text.split(/\r?\n\r?\n/);
150
+ text = events.pop();
151
+ for (const event of events) {
152
+ const data = event.split(/\r?\n/).filter(line => line.startsWith('data:')).map(line => line.slice(5).trim()).join('\n');
153
+ if (!data) continue;
154
+ try {
155
+ const message = JSON.parse(data);
156
+ if (message.id !== id) continue;
157
+ if (message.error) reject(new Error('MCP 返回协议错误'));
158
+ else resolve(message.result);
159
+ response.destroy();
160
+ } catch (_) { reject(new Error('MCP 返回无效事件')); }
161
+ }
162
+ }
163
+ });
164
+ response.on('end', () => {
165
+ if (response.statusCode < 200 || response.statusCode >= 300) return reject(new Error(`MCP HTTP ${response.statusCode}`));
166
+ if (notification || closing) return resolve();
167
+ try {
168
+ const message = JSON.parse(text);
169
+ if (message.id !== id || message.error) throw new Error();
170
+ resolve(message.result);
171
+ } catch (_) { reject(new Error('MCP 返回无效响应')); }
172
+ });
173
+ });
174
+ const timer = setTimeout(() => request.destroy(new Error('MCP 请求超时')), timeoutMs);
175
+ request.on('close', () => clearTimeout(timer));
176
+ request.on('error', reject);
177
+ request.end(body);
178
+ });
179
+ }
180
+ return {
181
+ async request(method, params, notification) {
182
+ const result = await send(method, params, notification);
183
+ if (method === 'initialize') protocol = result.protocolVersion;
184
+ return result;
185
+ },
186
+ async close() { if (session) await send('', {}, false, true).catch(() => {}); }
187
+ };
188
+ }
189
+
190
+ // Only map semantic fields exposed by a native tool. Unknown required fields
191
+ // make a tool incompatible rather than inventing server-specific arguments.
192
+ function nativeWrite(tool, handoff) {
193
+ const name = tool.name || '';
194
+ if (!/^(memory_write|set_memory|save_context|store_context|add_context|write_context|store_memory|save_memory|add_memory|create_memory|create_entities)$/.test(name)) return null;
195
+ const schema = tool.inputSchema || {};
196
+ const properties = schema.properties || {};
197
+ const content = JSON.stringify(handoff);
198
+ const values = {
199
+ content, text: content, memory: content, context: content, value: content,
200
+ title: `Handoff ${handoff.id}`, name: `Handoff ${handoff.id}`,
201
+ key: `handoff:${handoff.id}`, agent_id: handoff.target, agent: handoff.target,
202
+ project_id: handoff.threadId, project: handoff.threadId,
203
+ tags: ['handoff', handoff.threadId, handoff.target],
204
+ metadata: { handoffId: handoff.id, threadId: handoff.threadId, target: handoff.target },
205
+ entities: [{ name: `handoff:${handoff.id}`, entityType: 'handoff', observations: [content] }]
206
+ };
207
+ const args = {};
208
+ for (const [key, property] of Object.entries(properties)) {
209
+ const value = values[key];
210
+ if (value === undefined) continue;
211
+ const type = Array.isArray(value) ? 'array' : typeof value;
212
+ if (property.type && property.type !== type) continue;
213
+ if (property.enum && !property.enum.includes(value)) continue;
214
+ args[key] = value;
215
+ }
216
+ if ((schema.required || []).some(key => !(key in args))) return null;
217
+ if (!['content', 'text', 'memory', 'context', 'value', 'entities'].some(key => key in args)) return null;
218
+ if (name === 'set_memory' && !('key' in args && 'value' in args)) return null;
219
+ return { name, arguments: args };
220
+ }
221
+
222
+ async function deliver(handoff, options = {}) {
223
+ const start = Date.now();
224
+ let server;
225
+ let connection;
226
+ let stage = 'discovery';
227
+ let tool = null;
228
+ const discoveryWarnings = [];
229
+ let writeStarted = null;
230
+ try {
231
+ const servers = discoverServers(options, discoveryWarnings);
232
+ if (!servers.length) return { ok: false, reason: discoveryWarnings.length ? 'MCP 配置读取或解析失败;未探测到可用共享记忆 MCP' : '未探测到共享记忆 MCP', stage,
233
+ durationMs: Date.now() - start, writeDurationMs: 0, mcp: null, discoveryWarnings };
234
+ // Probe candidates read-only; after the first compatible tool is selected,
235
+ // perform exactly one write. A failed write never selects another server.
236
+ for (const candidate of servers) {
237
+ server = candidate;
238
+ stage = 'initialize';
239
+ tool = null;
240
+ try {
241
+ const timeout = options.timeoutMs || TIMEOUT_MS;
242
+ connection = server.url ? openHttp(server, timeout) : openStdio(server, timeout);
243
+ await connection.request('initialize', {
244
+ protocolVersion: '2025-03-26', capabilities: {}, clientInfo: { name: 'codexmate-handoff', version: '1.0.0' }
245
+ });
246
+ await connection.request('notifications/initialized', {}, true);
247
+ stage = 'tools/list';
248
+ let cursor;
249
+ do {
250
+ const listing = await connection.request('tools/list', cursor ? { cursor } : {});
251
+ for (const entry of listing.tools || []) {
252
+ tool = nativeWrite(entry, handoff);
253
+ if (tool) break;
254
+ }
255
+ cursor = listing.nextCursor;
256
+ } while (!tool && cursor);
257
+ if (!tool) throw new Error('共享记忆工具接口不兼容');
258
+ break;
259
+ } catch (error) {
260
+ if (connection) await connection.close();
261
+ connection = null;
262
+ if (candidate === servers[servers.length - 1]) throw error;
263
+ }
264
+ }
265
+ stage = 'tools/call';
266
+ writeStarted = Date.now();
267
+ const result = await connection.request('tools/call', tool);
268
+ if (!result || result.isError) throw new Error('共享记忆写入失败');
269
+ return { ok: true, reason: '', stage, mcp: { server: server.name, tool: tool.name },
270
+ durationMs: Date.now() - start, writeDurationMs: Date.now() - writeStarted, discoveryWarnings };
271
+ } catch (error) {
272
+ // Never persist server response bodies, environment values or credentials.
273
+ const safeReasons = ['共享记忆工具接口不兼容', '共享记忆写入失败', 'MCP 请求超时', 'MCP 进程已退出', 'MCP 返回协议错误'];
274
+ return { ok: false, reason: safeReasons.includes(error.message) ? error.message : `MCP ${stage} 失败`,
275
+ stage, mcp: server ? { server: server.name, tool: tool && tool.name } : null,
276
+ durationMs: Date.now() - start, writeDurationMs: writeStarted === null ? 0 : Date.now() - writeStarted, discoveryWarnings };
277
+ } finally {
278
+ if (connection) await connection.close();
279
+ }
280
+ }
281
+
282
+ module.exports = { deliver, discoverServers, nativeWrite };