codexmate 0.1.31 → 0.1.33

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 (92) hide show
  1. package/README.md +8 -3
  2. package/README.vi.md +8 -3
  3. package/README.zh.md +8 -3
  4. package/cli/agents-files.js +18 -4
  5. package/cli/claude-proxy.js +2 -2
  6. package/cli/plugin-config.js +64 -0
  7. package/cli/prompt-history.js +19 -4
  8. package/cli/system-prompt-files.js +7 -2
  9. package/cli.js +200 -214
  10. package/lib/cli-config-engine.js +15 -4
  11. package/lib/cli-file-utils.js +6 -1
  12. package/lib/config-change-fs.js +132 -0
  13. package/lib/config-changes.js +293 -0
  14. package/lib/handoff-mcp.js +18 -2
  15. package/lib/local-feature-store.js +39 -0
  16. package/lib/session-bookmarks.js +72 -0
  17. package/lib/session-context-health.js +102 -0
  18. package/lib/session-context-records.js +153 -0
  19. package/lib/session-diagnostics.js +75 -0
  20. package/lib/session-feature-settings.js +21 -0
  21. package/lib/session-features.js +63 -0
  22. package/lib/session-handoff-draft.js +43 -0
  23. package/lib/session-projects.js +76 -0
  24. package/lib/session-search-index.js +188 -0
  25. package/lib/thread-handoff.js +8 -0
  26. package/lib/web-server.js +216 -0
  27. package/lib/web-startup-auth.js +5 -1
  28. package/package.json +1 -1
  29. package/plugins/prompt-templates/computed.mjs +3 -3
  30. package/plugins/prompt-templates/invocation.mjs +73 -0
  31. package/plugins/prompt-templates/methods.mjs +48 -3
  32. package/plugins/prompt-templates/overview.mjs +2 -0
  33. package/web-ui/app.js +32 -1
  34. package/web-ui/index.html +2 -0
  35. package/web-ui/logic.context-health.mjs +144 -0
  36. package/web-ui/logic.context-window.mjs +15 -0
  37. package/web-ui/modules/api.mjs +72 -39
  38. package/web-ui/modules/app.computed.prompts.mjs +11 -0
  39. package/web-ui/modules/app.methods.agents.mjs +25 -3
  40. package/web-ui/modules/app.methods.claude-config.mjs +2 -0
  41. package/web-ui/modules/app.methods.codex-config.mjs +9 -0
  42. package/web-ui/modules/app.methods.config-changes.mjs +124 -0
  43. package/web-ui/modules/app.methods.index.mjs +4 -0
  44. package/web-ui/modules/app.methods.kilocode-config.mjs +2 -0
  45. package/web-ui/modules/app.methods.openclaw-persist.mjs +2 -0
  46. package/web-ui/modules/app.methods.opencode-config.mjs +2 -0
  47. package/web-ui/modules/app.methods.pi-config.mjs +12 -3
  48. package/web-ui/modules/app.methods.provider-cache.mjs +9 -3
  49. package/web-ui/modules/app.methods.providers.mjs +6 -0
  50. package/web-ui/modules/app.methods.startup-claude.mjs +8 -47
  51. package/web-ui/modules/app.methods.system-prompt.mjs +17 -2
  52. package/web-ui/modules/config-change-actions.mjs +9 -0
  53. package/web-ui/modules/context-health.methods.mjs +70 -0
  54. package/web-ui/modules/i18n/locales/en.mjs +164 -4
  55. package/web-ui/modules/i18n/locales/ja.mjs +164 -4
  56. package/web-ui/modules/i18n/locales/vi.mjs +164 -4
  57. package/web-ui/modules/i18n/locales/zh-tw.mjs +164 -4
  58. package/web-ui/modules/i18n/locales/zh.mjs +164 -4
  59. package/web-ui/modules/plugins.methods.mjs +2 -0
  60. package/web-ui/modules/prompt-ecosystem.methods.mjs +136 -0
  61. package/web-ui/modules/request-deadline.mjs +33 -0
  62. package/web-ui/modules/session-features.mjs +279 -0
  63. package/web-ui/modules/thread-handoff.mjs +1 -1
  64. package/web-ui/partials/index/config-changes.html +25 -0
  65. package/web-ui/partials/index/context-health.html +45 -0
  66. package/web-ui/partials/index/context-window-reference.html +17 -0
  67. package/web-ui/partials/index/layout-header.html +7 -30
  68. package/web-ui/partials/index/modal-openclaw-config.html +0 -2
  69. package/web-ui/partials/index/modal-prompt-invocation.html +17 -0
  70. package/web-ui/partials/index/modal-skills.html +0 -1
  71. package/web-ui/partials/index/modals-basic.html +0 -8
  72. package/web-ui/partials/index/modals-pi-provider.html +0 -1
  73. package/web-ui/partials/index/panel-config-codex.html +0 -3
  74. package/web-ui/partials/index/panel-config-openclaw.html +16 -13
  75. package/web-ui/partials/index/panel-dashboard.html +0 -2
  76. package/web-ui/partials/index/panel-plugins.html +37 -10
  77. package/web-ui/partials/index/panel-prompts.html +18 -3
  78. package/web-ui/partials/index/panel-sessions.html +23 -11
  79. package/web-ui/partials/index/panel-settings.html +1 -12
  80. package/web-ui/partials/index/panel-trash.html +0 -1
  81. package/web-ui/partials/index/session-diagnostics.html +29 -0
  82. package/web-ui/partials/index/session-features.html +107 -0
  83. package/web-ui/partials/index/thread-handoff.html +6 -3
  84. package/web-ui/res/web-ui-render.precompiled.js +1863 -271
  85. package/web-ui/styles/config-changes.css +30 -0
  86. package/web-ui/styles/context-health.css +107 -0
  87. package/web-ui/styles/openclaw-structured.css +205 -189
  88. package/web-ui/styles/prompts-editor.css +23 -0
  89. package/web-ui/styles/session-features.css +148 -0
  90. package/web-ui/styles/sessions-preview.css +21 -0
  91. package/web-ui/styles/sub-tabs.css +181 -0
  92. package/web-ui/styles.css +5 -1
package/cli.js CHANGED
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env node
2
- const fs = require('fs');
2
+ const { fs, isConfigStaging, stageConfigWrites } = require('./lib/config-change-fs');
3
+ const { createConfigChanges } = require('./lib/config-changes');
3
4
  const path = require('path');
4
5
  const os = require('os');
5
6
  const crypto = require('crypto');
@@ -96,6 +97,7 @@ const {
96
97
  executeWorkflowDefinition
97
98
  } = require('./lib/workflow-engine');
98
99
  const { createWorkflowRunner } = require('./lib/workflow-runner');
100
+ const { createWebServerLifecycle } = require('./lib/web-server');
99
101
  const {
100
102
  ALLOWED_EVENTS: WEBHOOK_ALLOWED_EVENTS,
101
103
  defaultConfigPath: defaultWebhookConfigPath,
@@ -138,6 +140,11 @@ const {
138
140
  const {
139
141
  createPromptHistoryController
140
142
  } = require('./cli/prompt-history');
143
+ const { createPluginConfigController } = require('./cli/plugin-config');
144
+ const { createSessionContextHealthController } = require('./lib/session-context-health');
145
+ const { createSessionFeatures } = require('./lib/session-features');
146
+ const { listHandoffs } = require('./lib/thread-handoff');
147
+ const { discoverServers, probeServer } = require('./lib/handoff-mcp');
141
148
  const {
142
149
  createArchiveHelperController
143
150
  } = require('./cli/archive-helpers');
@@ -1291,6 +1298,74 @@ function getApiToolConfigWriteTarget(action) {
1291
1298
  return '';
1292
1299
  }
1293
1300
 
1301
+ const CONFIG_CHANGE_ACTIONS = Object.freeze({
1302
+ 'apply-config-template': 'codex', 'add-provider': 'codex', 'update-provider': 'codex',
1303
+ 'delete-provider': 'codex', 'reset-config': 'codex', 'add-model': 'codex', 'delete-model': 'codex',
1304
+ 'apply-claude-settings-raw': 'claude', 'apply-claude-config': 'claude',
1305
+ 'apply-opencode-config': 'opencode', 'update-opencode-selection': 'opencode',
1306
+ 'apply-kilocode-config': 'kilocode', 'apply-openclaw-config': 'openclaw',
1307
+ 'write-pi-models': 'pi', 'write-pi-settings': 'pi', 'apply-pi-config-history': 'pi'
1308
+ });
1309
+ const CONFIG_CHANGE_READERS = Object.freeze({
1310
+ 'get-config-template': { target: 'codex', read: getConfigTemplate },
1311
+ 'get-claude-settings-raw': { target: 'claude', read: readClaudeSettingsRaw },
1312
+ 'get-openclaw-config': { target: 'openclaw', read: params => readOpenclawConfigFile(params) },
1313
+ 'get-opencode-config': { target: 'opencode', read: readOpencodeConfigInfo },
1314
+ 'get-kilocode-config': { target: 'kilocode', read: readKilocodeConfigInfo },
1315
+ 'read-pi-models': { target: 'pi', read: readPiModels },
1316
+ 'read-pi-settings': { target: 'pi', read: readPiSettings }
1317
+ });
1318
+ const configChanges = createConfigChanges({
1319
+ journalPath: path.join(CODEXMATE_DIR, 'config-change-last.json'),
1320
+ getTarget: action => Object.prototype.hasOwnProperty.call(CONFIG_CHANGE_ACTIONS, action) ? CONFIG_CHANGE_ACTIONS[action] : '',
1321
+ isTarget: target => TOOL_CONFIG_PERMISSION_TARGETS.has(target),
1322
+ isAllowed: isToolConfigWriteAllowed,
1323
+ isPathAllowed(filePath) {
1324
+ if (OPENCODE_CONFIG_ENV_FILE && filePath === OPENCODE_CONFIG_ENV_FILE) return true;
1325
+ const roots = [CONFIG_DIR, CODEXMATE_DIR, CLAUDE_DIR, OPENCLAW_DIR, OPENCODE_CONFIG_DIR, KILOCODE_CONFIG_DIR, getPiAgentDir()];
1326
+ return roots.some(root => {
1327
+ const relative = path.relative(root, filePath);
1328
+ return relative && !relative.startsWith('..' + path.sep) && relative !== '..' && !path.isAbsolute(relative);
1329
+ });
1330
+ },
1331
+ execute(action, params) {
1332
+ const handlers = {
1333
+ 'apply-config-template': applyConfigTemplate,
1334
+ 'add-provider': values => addProviderToConfig({ ...values, requireModel: true }),
1335
+ 'update-provider': updateProviderInConfig, 'delete-provider': deleteProviderFromConfig,
1336
+ 'reset-config': resetConfigToDefault,
1337
+ 'add-model': values => { cmdAddModel(values.model, true); return { success: true }; },
1338
+ 'delete-model': values => { cmdDeleteModel(values.model, true); return { success: true }; },
1339
+ 'apply-claude-settings-raw': applyClaudeSettingsRaw,
1340
+ 'apply-claude-config': values => applyToClaudeSettings(values.config),
1341
+ 'apply-opencode-config': applyOpencodeConfigRaw, 'update-opencode-selection': updateOpencodeSelection,
1342
+ 'apply-kilocode-config': applyKilocodeConfig, 'apply-openclaw-config': applyOpenclawConfig,
1343
+ 'write-pi-models': writePiModels, 'write-pi-settings': writePiSettings,
1344
+ 'apply-pi-config-history': applyPiConfigHistory
1345
+ };
1346
+ return handlers[action](params);
1347
+ },
1348
+ beforeWrite(plan, entry) {
1349
+ if (plan.target !== 'pi') return;
1350
+ const bucket = path.basename(entry.path) === 'models.json' ? 'pi-models' : 'pi-settings';
1351
+ const backup = historyBackup(bucket, entry.path);
1352
+ if (backup && backup.error) throw new Error('保存 Pi 历史备份失败');
1353
+ },
1354
+ runtimeState(plan) {
1355
+ return plan.action === 'apply-claude-config' ? { running: getBuiltinClaudeProxyStatus().running === true } : null;
1356
+ },
1357
+ async reconcileRuntime(plan, rollback, state) {
1358
+ if (plan.action !== 'apply-claude-config') return;
1359
+ await stopBuiltinClaudeProxyRuntime();
1360
+ const saved = readJsonObjectFromFile(BUILTIN_CLAUDE_PROXY_SETTINGS_FILE, DEFAULT_BUILTIN_CLAUDE_PROXY_SETTINGS);
1361
+ if (!saved.ok) throw new Error('读取 Claude 兼容代理配置失败');
1362
+ if (rollback ? state && state.running : saved.data.enabled) {
1363
+ const result = await startBuiltinClaudeProxyRuntime(saved.data, { skipWrite: true });
1364
+ if (result.error) throw new Error('恢复 Claude 兼容代理失败');
1365
+ }
1366
+ }
1367
+ });
1368
+
1294
1369
  function getPiAgentDir() {
1295
1370
  const homeDir = (typeof os.homedir === 'function' ? os.homedir() : null) || process.env.HOME || process.env.USERPROFILE || '';
1296
1371
  return path.join(homeDir, '.pi', 'agent');
@@ -2332,7 +2407,8 @@ function queryOpencodeSessionMessages(sessionId, options = {}) {
2332
2407
  const id = typeof sessionId === 'string' ? sessionId.trim() : '';
2333
2408
  if (!id) return null;
2334
2409
  const maxMessages = resolveMaxMessagesValue(options.maxMessages, DEFAULT_SESSION_DETAIL_MESSAGES);
2335
- const limit = maxMessages === Infinity ? OPENCODE_DB_READ_LIMIT : Math.min(OPENCODE_DB_READ_LIMIT, Math.max(1, Math.floor(maxMessages)));
2410
+ const limit = options.contextHealth === true ? -1
2411
+ : (maxMessages === Infinity ? OPENCODE_DB_READ_LIMIT : Math.min(OPENCODE_DB_READ_LIMIT, Math.max(1, Math.floor(maxMessages))));
2336
2412
  return withOpencodeDb((db) => {
2337
2413
  const totalRow = db.prepare('select count(*) as count from message where session_id = ?').get(id) || {};
2338
2414
  const totalMessages = Math.max(0, Math.floor(Number(totalRow.count) || 0));
@@ -2346,8 +2422,12 @@ function queryOpencodeSessionMessages(sessionId, options = {}) {
2346
2422
  group by m.id
2347
2423
  order by m.time_created asc
2348
2424
  `).all(id, limit);
2349
- const messages = rows.map(normalizeOpencodeMessageRow).filter(Boolean);
2425
+ const messages = options.contextHealth === true ? rows.map((row) => ({
2426
+ role: parseJsonObjectSafe(row.message_data || '')?.role || 'assistant',
2427
+ content: String(row.parts || '').split('\n').map(parseJsonObjectSafe).filter(Boolean)
2428
+ })) : rows.map(normalizeOpencodeMessageRow).filter(Boolean);
2350
2429
  const sessionRow = db.prepare('select id, directory, path, time_updated from session where id = ?').get(id) || null;
2430
+ if (options.contextHealth === true && !sessionRow) return null;
2351
2431
  return {
2352
2432
  sessionId: id,
2353
2433
  cwd: sessionRow && (sessionRow.path || sessionRow.directory) ? (sessionRow.path || sessionRow.directory) : '',
@@ -2601,7 +2681,14 @@ function queryZedSessionMessages(sessionId, options = {}) {
2601
2681
  return withZedThreadsDb((db) => {
2602
2682
  const row = db.prepare('select data, data_type, folder_paths, updated_at from threads where id = ?').get(id) || null;
2603
2683
  const doc = parseZedThreadDocument(row);
2684
+ if (options.contextHealth === true && !doc) return null;
2604
2685
  const modelInfo = readZedThreadModelInfo(doc);
2686
+ if (options.contextHealth === true) return {
2687
+ sessionId: id, messages: Array.isArray(doc?.messages) ? doc.messages : [],
2688
+ cwd: doc ? readZedThreadCwd(row, doc) : '',
2689
+ instructions: doc?.system_prompt || doc?.instructions || '',
2690
+ totalMessages: Array.isArray(doc?.messages) ? doc.messages.length : 0, clipped: false
2691
+ };
2605
2692
  const all = (doc && Array.isArray(doc.messages) ? doc.messages : [])
2606
2693
  .map(entry => normalizeZedThreadMessage(entry, modelInfo))
2607
2694
  .filter(Boolean);
@@ -2956,6 +3043,10 @@ const {
2956
3043
  CONFIG_DIR
2957
3044
  });
2958
3045
 
3046
+ const { getPluginConfig, applyPluginConfig } = createPluginConfigController({
3047
+ fs, path, CONFIG_DIR, backupPromptBeforeWrite: historyBackup
3048
+ });
3049
+
2959
3050
  const {
2960
3051
  resolveAgentsFilePath,
2961
3052
  validateAgentsBaseDir,
@@ -8081,6 +8172,9 @@ const {
8081
8172
  });
8082
8173
 
8083
8174
  const {
8175
+ saveBuiltinClaudeProxySettings,
8176
+ buildBuiltinClaudeProxyListenUrl,
8177
+ resolveBuiltinClaudeProxyUpstream,
8084
8178
  startBuiltinClaudeProxyRuntime,
8085
8179
  stopBuiltinClaudeProxyRuntime,
8086
8180
  getBuiltinClaudeProxyStatus
@@ -9808,6 +9902,33 @@ async function extractMessagesFromFile(filePath, source, options = {}) {
9808
9902
  return state;
9809
9903
  }
9810
9904
 
9905
+ const { readSessionContextHealth, readSessionContextNode, iterateSessionContextNodes } = createSessionContextHealthController({
9906
+ fs, normalizeSessionSourceName, resolveSessionFilePath, queryOpencodeSessionMessages, queryZedSessionMessages
9907
+ });
9908
+
9909
+ const sessionFeatures = createSessionFeatures({ root: path.join(CODEXMATE_DIR, 'session-features'),
9910
+ readNode: readSessionContextNode, nodes: iterateSessionContextNodes,
9911
+ diagnostics: {
9912
+ home: os.homedir(),
9913
+ secrets: () => [readServerToken()],
9914
+ local: async () => {
9915
+ const report = await buildDoctorReport({ remote: false, includeInstall: false, includeUsage: false }, {
9916
+ getStatusPayload: buildMcpStatusPayload, buildConfigHealthReport, listSkills });
9917
+ return { ok: report.ok, issues: report.issues.map((item) => ({ id: item.id, severity: item.severity,
9918
+ problem: item.problem, impact: item.impact, actions: item.actions })),
9919
+ command: 'codexmate doctor --format md' };
9920
+ },
9921
+ provider: async () => {
9922
+ const report = await buildConfigHealthReport({ remote: true });
9923
+ return { ok: report.ok, issues: (report.issues || []).map((item) => ({ code: item.code, statusCode: item.statusCode })),
9924
+ command: 'codexmate doctor --format md' };
9925
+ },
9926
+ mcp: (name, options) => probeServer(name, options),
9927
+ mcpTargets: (cwd) => discoverServers({ cwd, allServers: true }).map((server) => server.name)
9928
+ },
9929
+ handoffs: (threadId) => listHandoffs(threadId),
9930
+ inventory: (source, limit) => listSessionInventoryBySource(source, limit, { scanCount: limit, maxFilesScanned: limit * 4 }, { forceRefresh: true }) });
9931
+
9811
9932
  async function readSessionDetail(params = {}) {
9812
9933
  const source = normalizeSessionSourceName(params.source, '');
9813
9934
  if (!source) {
@@ -12351,9 +12472,9 @@ async function applyToClaudeSettings(config = {}) {
12351
12472
  error: 'chat_completions 模式需要显式的上游 Base URL 或可解析的 provider 名称'
12352
12473
  };
12353
12474
  }
12354
- await stopBuiltinClaudeProxyRuntime();
12475
+ if (!isConfigStaging()) await stopBuiltinClaudeProxyRuntime();
12355
12476
  const proxyToken = crypto.randomBytes(24).toString('hex');
12356
- proxyResult = await startBuiltinClaudeProxyRuntime({
12477
+ const proxyPayload = {
12357
12478
  enabled: true,
12358
12479
  host: DEFAULT_BUILTIN_CLAUDE_PROXY_SETTINGS.host,
12359
12480
  provider: upstreamProviderName,
@@ -12363,9 +12484,18 @@ async function applyToClaudeSettings(config = {}) {
12363
12484
  upstreamProviderName,
12364
12485
  ...(configuredBaseUrl ? { upstreamBaseUrl: configuredBaseUrl } : {}),
12365
12486
  upstreamApiKey: apiKey
12366
- });
12487
+ };
12488
+ if (isConfigStaging()) {
12489
+ const saved = saveBuiltinClaudeProxySettings(proxyPayload);
12490
+ if (saved.error) return { error: saved.error };
12491
+ const upstream = configuredBaseUrl ? null : resolveBuiltinClaudeProxyUpstream(saved.settings);
12492
+ if (upstream && upstream.error) return { error: upstream.error };
12493
+ proxyResult = { success: true, listenUrl: buildBuiltinClaudeProxyListenUrl(saved.settings), upstreamProvider: upstreamProviderName };
12494
+ } else {
12495
+ proxyResult = await startBuiltinClaudeProxyRuntime(proxyPayload);
12496
+ }
12367
12497
  if (!proxyResult || proxyResult.error || proxyResult.success === false || !proxyResult.listenUrl) {
12368
- await stopBuiltinClaudeProxyRuntime();
12498
+ if (!isConfigStaging()) await stopBuiltinClaudeProxyRuntime();
12369
12499
  resetBuiltinClaudeProxySavedSettingsToResponses();
12370
12500
  return {
12371
12501
  success: false,
@@ -12377,14 +12507,14 @@ async function applyToClaudeSettings(config = {}) {
12377
12507
  settingsBaseUrl = proxyResult.listenUrl;
12378
12508
  settingsApiKey = proxyToken;
12379
12509
  } else {
12380
- await stopBuiltinClaudeProxyRuntime();
12510
+ if (!isConfigStaging()) await stopBuiltinClaudeProxyRuntime();
12381
12511
  resetBuiltinClaudeProxySavedSettingsToResponses();
12382
12512
  }
12383
12513
 
12384
12514
  const readResult = readJsonObjectFromFile(CLAUDE_SETTINGS_FILE, {});
12385
12515
  if (!readResult.ok) {
12386
12516
  if (proxyStarted) {
12387
- await stopBuiltinClaudeProxyRuntime();
12517
+ if (!isConfigStaging()) await stopBuiltinClaudeProxyRuntime();
12388
12518
  resetBuiltinClaudeProxySavedSettingsToResponses();
12389
12519
  }
12390
12520
  return { success: false, mode: 'settings-file', error: readResult.error };
@@ -12447,7 +12577,7 @@ async function applyToClaudeSettings(config = {}) {
12447
12577
  return result;
12448
12578
  } catch (e) {
12449
12579
  if (proxyStarted) {
12450
- try { await stopBuiltinClaudeProxyRuntime(); } catch (_) {}
12580
+ try { if (!isConfigStaging()) await stopBuiltinClaudeProxyRuntime(); } catch (_) {}
12451
12581
  try { resetBuiltinClaudeProxySavedSettingsToResponses(); } catch (_) {}
12452
12582
  }
12453
12583
  return {
@@ -14174,137 +14304,11 @@ const PUBLIC_WEB_UI_STATIC_ASSETS = new Set([
14174
14304
  ]);
14175
14305
 
14176
14306
  function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser }) {
14177
- const connections = new Set();
14307
+
14178
14308
  const startupAuth = createStartupAuth(readServerToken());
14179
14309
  const httpToken = startupAuth.token;
14180
14310
  const accessControlMiddleware = createWebAccessControlMiddleware(host);
14181
- const probeWebUiReadiness = (callback) => {
14182
- const payload = JSON.stringify({ action: 'health-check', params: {} });
14183
- const requestOptions = {
14184
- hostname: openHost,
14185
- port,
14186
- path: '/api',
14187
- method: 'POST',
14188
- headers: {
14189
- 'Content-Type': 'application/json; charset=utf-8',
14190
- 'Content-Length': Buffer.byteLength(payload, 'utf-8'),
14191
- ...(httpToken ? { Authorization: `Bearer ${httpToken}` } : {})
14192
- }
14193
- };
14194
- let settled = false;
14195
- const finish = (ready) => {
14196
- if (settled) return;
14197
- settled = true;
14198
- callback(ready);
14199
- };
14200
- const req = http.request(requestOptions, (probeRes) => {
14201
- if (typeof probeRes.resume === 'function') {
14202
- probeRes.resume();
14203
- }
14204
- probeRes.on('end', () => {
14205
- finish(probeRes.statusCode === 200);
14206
- });
14207
- });
14208
- req.on('error', () => finish(false));
14209
- req.setTimeout(1000, () => {
14210
- try { req.destroy(); } catch (_) { }
14211
- finish(false);
14212
- });
14213
- req.end(payload, 'utf-8');
14214
- };
14215
- const probeWebUiAssetReadiness = (callback) => {
14216
- const requestOptions = {
14217
- hostname: openHost,
14218
- port,
14219
- path: '/web-ui/app.js',
14220
- method: 'GET',
14221
- headers: httpToken ? { Authorization: `Bearer ${httpToken}` } : {}
14222
- };
14223
- let settled = false;
14224
- const finish = (ready) => {
14225
- if (settled) return;
14226
- settled = true;
14227
- callback(ready);
14228
- };
14229
- const req = http.request(requestOptions, (probeRes) => {
14230
- if (typeof probeRes.resume === 'function') {
14231
- probeRes.resume();
14232
- }
14233
- probeRes.on('end', () => {
14234
- finish(probeRes.statusCode === 200);
14235
- });
14236
- });
14237
- req.on('error', () => finish(false));
14238
- req.setTimeout(1000, () => {
14239
- try { req.destroy(); } catch (_) { }
14240
- finish(false);
14241
- });
14242
- req.end();
14243
- };
14244
- const openBrowserAfterReady = (url) => {
14245
- // Some environments may start the listener before the bundled web-ui assets
14246
- // are ready for the first browser hit; wait until both API and assets respond.
14247
- const maxAttempts = 120;
14248
- const retryDelayMs = 200;
14249
- let finished = false;
14250
-
14251
- const finish = (ready) => {
14252
- if (finished) return;
14253
- finished = true;
14254
- if (!ready) {
14255
- console.warn('! Web UI 就绪探测超时,未自动打开浏览器,请手动访问:', url);
14256
- return;
14257
- }
14258
-
14259
- const platform = process.platform;
14260
- const commandSpec = platform === 'win32'
14261
- ? { command: 'cmd', args: ['/c', 'start', '', url] }
14262
- : (platform === 'darwin'
14263
- ? { command: 'open', args: [url] }
14264
- : { command: 'xdg-open', args: [url] });
14265
14311
 
14266
- try {
14267
- const child = spawn(commandSpec.command, commandSpec.args, {
14268
- stdio: 'ignore',
14269
- detached: true,
14270
- windowsHide: true
14271
- });
14272
- child.on('error', () => {
14273
- console.warn('无法自动打开浏览器,请手动访问:', url);
14274
- });
14275
- if (typeof child.unref === 'function') {
14276
- child.unref();
14277
- }
14278
- } catch (_) {
14279
- console.warn('无法自动打开浏览器,请手动访问:', url);
14280
- }
14281
- };
14282
- const scheduleProbe = (attempt) => {
14283
- probeWebUiReadiness((apiReady) => {
14284
- if (!apiReady) {
14285
- if (attempt >= maxAttempts) {
14286
- finish(false);
14287
- return;
14288
- }
14289
- setTimeout(() => scheduleProbe(attempt + 1), retryDelayMs);
14290
- return;
14291
- }
14292
- probeWebUiAssetReadiness((assetReady) => {
14293
- if (assetReady) {
14294
- finish(true);
14295
- return;
14296
- }
14297
- if (attempt >= maxAttempts) {
14298
- finish(false);
14299
- return;
14300
- }
14301
- setTimeout(() => scheduleProbe(attempt + 1), retryDelayMs);
14302
- });
14303
- });
14304
- };
14305
-
14306
- scheduleProbe(1);
14307
- };
14308
14312
  const writeWebUiAssetError = (res, requestPath, error) => {
14309
14313
  const message = error && error.message ? error.message : String(error);
14310
14314
  console.error(`! Web UI 资源读取失败 [${requestPath}]:`, message);
@@ -14440,10 +14444,31 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
14440
14444
  let result;
14441
14445
 
14442
14446
  const guardedToolConfigTarget = getApiToolConfigWriteTarget(action);
14443
- if (guardedToolConfigTarget && !isToolConfigWriteAllowed(guardedToolConfigTarget)) {
14447
+ if (guardedToolConfigTarget && configChanges.isBusy()) {
14448
+ result = { error: '已有配置变更正在执行', errorCode: 'config-change-busy' };
14449
+ } else if (guardedToolConfigTarget && !isToolConfigWriteAllowed(guardedToolConfigTarget)) {
14444
14450
  result = buildToolConfigWriteDeniedPayload(guardedToolConfigTarget);
14451
+ } else if (Object.prototype.hasOwnProperty.call(CONFIG_CHANGE_READERS, action)) {
14452
+ const reader = CONFIG_CHANGE_READERS[action];
14453
+ const observed = await stageConfigWrites(() => reader.read(params || {}), { maxFileBytes: Infinity, allowSymlinks: true });
14454
+ result = { ...observed.result, configChangeTarget: reader.target, configChangeBaseline: observed.files.map(entry => ({ path: entry.path, exists: entry.before.exists, hash: entry.before.hash, mode: entry.before.mode })) };
14445
14455
  } else {
14446
14456
  switch (action) {
14457
+ case 'preview-config-change':
14458
+ result = await configChanges.preview(params || {});
14459
+ break;
14460
+ case 'apply-config-change':
14461
+ result = await configChanges.apply(params || {});
14462
+ if (result.change && result.change.action === 'apply-claude-config') {
14463
+ notifyWebhook('provider-switch', 'Claude provider configuration applied', { changeId: result.change.id }).catch(function () { });
14464
+ }
14465
+ break;
14466
+ case 'get-last-config-change':
14467
+ result = configChanges.last(params || {});
14468
+ break;
14469
+ case 'undo-config-change':
14470
+ result = await configChanges.undo(params || {});
14471
+ break;
14447
14472
  case 'health-check':
14448
14473
  result = { ok: true };
14449
14474
  break;
@@ -14771,6 +14796,12 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
14771
14796
  case 'preview-system-prompt-diff':
14772
14797
  result = buildSystemPromptDiff(params || {});
14773
14798
  break;
14799
+ case 'get-plugin-config':
14800
+ result = getPluginConfig();
14801
+ break;
14802
+ case 'apply-plugin-config':
14803
+ result = applyPluginConfig(params || {});
14804
+ break;
14774
14805
  case 'list-prompt-history':
14775
14806
  result = listPromptHistory((params && params.bucket) || '');
14776
14807
  break;
@@ -15021,6 +15052,33 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
15021
15052
  case 'thread-handoff-ack':
15022
15053
  result = await handleThreadAction(action, params || {});
15023
15054
  break;
15055
+ case 'session-diagnostics-targets':
15056
+ case 'session-diagnostics-start':
15057
+ case 'session-diagnostics-status':
15058
+ case 'session-diagnostics-cancel':
15059
+ case 'session-feature-settings-get':
15060
+ case 'session-feature-settings-save':
15061
+ case 'session-projects':
15062
+ case 'session-project-map':
15063
+ case 'session-project-prompt':
15064
+ case 'session-handoff-draft':
15065
+ case 'session-index-status':
15066
+ case 'session-index-refresh':
15067
+ case 'session-index-cancel':
15068
+ case 'session-index-search':
15069
+ case 'session-index-node':
15070
+ case 'session-bookmarks-list':
15071
+ case 'session-bookmark-save':
15072
+ case 'session-bookmark-remove':
15073
+ case 'session-bookmark-locate':
15074
+ result = await sessionFeatures.handle(action, params || {});
15075
+ break;
15076
+ case 'session-context-health':
15077
+ result = await readSessionContextHealth(params || {});
15078
+ break;
15079
+ case 'session-context-node':
15080
+ result = await readSessionContextNode(params || {});
15081
+ break;
15024
15082
  case 'session-detail':
15025
15083
  result = await readSessionDetail(params);
15026
15084
  break;
@@ -15380,83 +15438,11 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
15380
15438
  handleRequest(req, res);
15381
15439
  }));
15382
15440
  });
15383
-
15384
- server.on('connection', (socket) => {
15385
- connections.add(socket);
15386
- socket.on('close', () => connections.delete(socket));
15387
- });
15388
-
15389
- const printPortOverrideHint = () => {
15390
- const examplePort = port === 8080 ? 8081 : 8080;
15391
- console.error(` 临时换端口(macOS/Linux): CODEXMATE_PORT=${examplePort} codexmate run`);
15392
- console.error(` 临时换端口(Windows PowerShell): $env:CODEXMATE_PORT=${examplePort}; codexmate run`);
15393
- console.error(` 临时换端口(Windows CMD): set CODEXMATE_PORT=${examplePort} && codexmate run`);
15394
- };
15395
-
15396
- server.once('error', (err) => {
15397
- if (err && err.code === 'EADDRINUSE') {
15398
- console.error(`! 启动失败: 端口 ${port} 已被占用,可能有残留的 codexmate run 实例。`);
15399
- console.error(' 请先停止旧实例或更换端口后重试。');
15400
- printPortOverrideHint();
15401
- } else if (err && err.code === 'EACCES') {
15402
- console.error(`! 启动失败: 没有权限监听 ${host}:${port}。`);
15403
- console.error(' 请检查系统/安全软件限制,或更换端口后重试。');
15404
- printPortOverrideHint();
15405
- } else {
15406
- console.error('! 启动 Web UI 失败:', err && err.message ? err.message : err);
15407
- }
15408
- process.exit(1);
15409
- });
15410
-
15411
- const openHost = host === '::'
15412
- ? '::1'
15413
- : (host === '0.0.0.0' ? DEFAULT_WEB_OPEN_HOST : host);
15414
- const openUrl = `http://${formatHostForUrl(openHost)}:${port}/?token=${encodeURIComponent(httpToken)}`;
15415
- server.listen(port, host, () => {
15416
- getUnattendedWorkflowRunner().recover();
15417
- console.log('\n✓ Web UI 已启动');
15418
- const willOpenBrowser = !!openBrowser && !process.env.CODEXMATE_NO_BROWSER;
15419
- console.log(` ${willOpenBrowser ? '已打开' : '待访问'}: ${openUrl}`);
15420
- if (host && host !== openHost) {
15421
- console.log(' 监听地址:', host);
15422
- }
15423
- console.log(' 退出: Ctrl+C\n');
15424
- if (isAnyAddressHost(host)) {
15425
- console.warn('! 安全提示: 当前监听所有网卡,局域网访问需要访问令牌。');
15426
- console.warn(' 远程 /bridge/ 请求需携带 Authorization: Bearer <访问令牌>。');
15427
- const allowedIps = (process.env.CODEXMATE_ALLOWED_IPS || '').trim();
15428
- if (allowedIps) {
15429
- console.warn(` 已启用的来源 IP 白名单: ${allowedIps}`);
15430
- }
15431
- }
15432
-
15433
- if (willOpenBrowser) {
15434
- openBrowserAfterReady(openUrl);
15435
- }
15436
- });
15437
-
15438
- const stop = () => new Promise((resolve) => {
15439
- let done = false;
15440
- const finish = () => {
15441
- if (done) return;
15442
- done = true;
15443
- for (const socket of connections) {
15444
- try { socket.destroy(); } catch (_) { }
15445
- }
15446
- connections.clear();
15447
- resolve();
15448
- };
15449
-
15450
- if (!server.listening) {
15451
- finish();
15452
- return;
15453
- }
15454
-
15455
- server.close(() => finish());
15456
- setTimeout(() => finish(), 800);
15441
+ return createWebServerLifecycle({ server, host, port, httpToken, openBrowser }, {
15442
+ http, process, console, setTimeout, formatHostForUrl, DEFAULT_WEB_OPEN_HOST, isAnyAddressHost,
15443
+ spawn: (...args) => spawn(...args),
15444
+ getUnattendedWorkflowRunner: () => getUnattendedWorkflowRunner()
15457
15445
  });
15458
-
15459
- return { server, stop };
15460
15446
  }
15461
15447
 
15462
15448
  // Region markers are used by unit tests that extract these helpers directly.
@@ -1,5 +1,5 @@
1
1
  const crypto = require('crypto');
2
- const fs = require('fs');
2
+ const { fs, isConfigStaging } = require('./config-change-fs');
3
3
  const path = require('path');
4
4
  const toml = require('@iarna/toml');
5
5
 
@@ -144,6 +144,7 @@ function writeBufferAtomically(filePath, buffer, mode, fsImpl) {
144
144
  const tmpPath = `${filePath}.tmp-${process.pid}-${Date.now()}-${crypto.randomBytes(4).toString('hex')}`;
145
145
  try {
146
146
  fsImpl.writeFileSync(tmpPath, buffer, { encoding: 'utf-8', mode });
147
+ fsImpl.chmodSync(tmpPath, mode);
147
148
  syncFile(tmpPath, fsImpl);
148
149
  fsImpl.renameSync(tmpPath, filePath);
149
150
  } catch (error) {
@@ -155,9 +156,7 @@ function writeBufferAtomically(filePath, buffer, mode, fsImpl) {
155
156
  }
156
157
 
157
158
  function writeConfigAtomicWithBackup(filePath, content, options = {}) {
158
- const fsImpl = options.fs || fs;
159
159
  const tomlImpl = options.toml || toml;
160
- const now = options.now instanceof Date ? options.now : new Date();
161
160
  const text = typeof content === 'string' ? content : String(content || '');
162
161
 
163
162
  try {
@@ -172,6 +171,17 @@ function writeConfigAtomicWithBackup(filePath, content, options = {}) {
172
171
  });
173
172
  }
174
173
 
174
+ return writeTextAtomicWithBackup(filePath, text, options);
175
+ }
176
+
177
+ function writeTextAtomicWithBackup(filePath, content, options = {}) {
178
+ const fsImpl = options.fs || fs;
179
+ const now = options.now instanceof Date ? options.now : new Date();
180
+ const text = typeof content === 'string' ? content : String(content || '');
181
+ if (isConfigStaging() && fsImpl === fs) {
182
+ fsImpl.writeFileSync(filePath, text, 'utf8');
183
+ return { path: filePath, backupPath: '', backupCreated: false };
184
+ }
175
185
  fsImpl.mkdirSync(path.dirname(filePath), { recursive: true });
176
186
  const targetExists = fsImpl.existsSync(filePath);
177
187
  const originalBuffer = targetExists ? fsImpl.readFileSync(filePath) : null;
@@ -256,5 +266,6 @@ module.exports = {
256
266
  isValidProviderName,
257
267
  createConfigError,
258
268
  formatConfigError,
259
- writeConfigAtomicWithBackup
269
+ writeConfigAtomicWithBackup,
270
+ writeTextAtomicWithBackup
260
271
  };
@@ -1,4 +1,4 @@
1
- const fs = require('fs');
1
+ const { fs, isConfigStaging } = require('./config-change-fs');
2
2
  const path = require('path');
3
3
 
4
4
  function ensureDir(dirPath) {
@@ -85,6 +85,7 @@ function formatTimestampForFileName(value) {
85
85
  }
86
86
 
87
87
  function backupFileIfNeededOnce(filePath, backupPrefix = 'codexmate-backup') {
88
+ if (isConfigStaging()) return '';
88
89
  if (!fs.existsSync(filePath)) {
89
90
  return '';
90
91
  }
@@ -106,6 +107,10 @@ function backupFileIfNeededOnce(filePath, backupPrefix = 'codexmate-backup') {
106
107
  }
107
108
 
108
109
  function writeJsonAtomic(filePath, data) {
110
+ if (isConfigStaging()) {
111
+ fs.writeFileSync(filePath, JSON.stringify(data, null, 2) + '\n', 'utf8');
112
+ return;
113
+ }
109
114
  const dirPath = path.dirname(filePath);
110
115
  ensureDir(dirPath);
111
116