codexmate 0.1.29 → 0.1.31

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 (72) hide show
  1. package/README.md +95 -4
  2. package/README.vi.md +95 -4
  3. package/README.zh.md +96 -4
  4. package/cli/config-bootstrap.js +25 -11
  5. package/cli/skills.js +33 -8
  6. package/cli.js +364 -42
  7. package/lib/cli-config-engine.js +260 -0
  8. package/lib/cli-utils.js +2 -1
  9. package/lib/cli-webhook.js +1 -1
  10. package/lib/handoff-mcp.js +282 -0
  11. package/lib/http-access-control.js +335 -0
  12. package/lib/thread-handoff.js +130 -0
  13. package/lib/web-startup-auth.js +49 -0
  14. package/lib/workflow-engine.js +92 -21
  15. package/lib/workflow-runner.js +261 -0
  16. package/package.json +6 -1
  17. package/web-ui/app.js +33 -4
  18. package/web-ui/logic.sessions.mjs +24 -0
  19. package/web-ui/modules/access-token.mjs +33 -0
  20. package/web-ui/modules/api.mjs +2 -1
  21. package/web-ui/modules/app.computed.dashboard.mjs +1 -1
  22. package/web-ui/modules/app.methods.codex-config.mjs +1 -1
  23. package/web-ui/modules/app.methods.index.mjs +2 -0
  24. package/web-ui/modules/app.methods.navigation.mjs +17 -3
  25. package/web-ui/modules/app.methods.prompts-editor.mjs +7 -0
  26. package/web-ui/modules/app.methods.providers.mjs +2 -2
  27. package/web-ui/modules/app.methods.runtime.mjs +3 -2
  28. package/web-ui/modules/app.methods.session-actions.mjs +3 -0
  29. package/web-ui/modules/app.methods.session-browser.mjs +11 -3
  30. package/web-ui/modules/app.methods.system-prompt.mjs +1 -8
  31. package/web-ui/modules/app.methods.workflows.mjs +41 -0
  32. package/web-ui/modules/i18n/locales/en.mjs +43 -2
  33. package/web-ui/modules/i18n/locales/ja.mjs +43 -2
  34. package/web-ui/modules/i18n/locales/vi.mjs +43 -2
  35. package/web-ui/modules/i18n/locales/zh-tw.mjs +43 -2
  36. package/web-ui/modules/i18n/locales/zh.mjs +43 -2
  37. package/web-ui/modules/i18n.mjs +16 -0
  38. package/web-ui/modules/sessions-filters-url.mjs +3 -0
  39. package/web-ui/modules/skills.computed.mjs +11 -0
  40. package/web-ui/modules/skills.methods.mjs +63 -12
  41. package/web-ui/modules/thread-handoff.mjs +142 -0
  42. package/web-ui/partials/index/layout-footer.html +1 -1
  43. package/web-ui/partials/index/layout-header.html +32 -12
  44. package/web-ui/partials/index/panel-config-claude.html +2 -0
  45. package/web-ui/partials/index/panel-config-codex.html +2 -0
  46. package/web-ui/partials/index/panel-config-kilocode.html +3 -1
  47. package/web-ui/partials/index/panel-config-openclaw.html +2 -0
  48. package/web-ui/partials/index/panel-config-opencode.html +3 -1
  49. package/web-ui/partials/index/panel-config-pi.html +2 -0
  50. package/web-ui/partials/index/panel-dashboard.html +59 -0
  51. package/web-ui/partials/index/panel-market.html +23 -5
  52. package/web-ui/partials/index/panel-prompts.html +28 -16
  53. package/web-ui/partials/index/panel-sessions.html +51 -70
  54. package/web-ui/partials/index/panel-trash.html +3 -0
  55. package/web-ui/partials/index/thread-handoff.html +59 -0
  56. package/web-ui/res/web-ui-render.precompiled.js +1020 -493
  57. package/web-ui/styles/controls-forms.css +9 -0
  58. package/web-ui/styles/dashboard.css +51 -0
  59. package/web-ui/styles/feedback.css +26 -0
  60. package/web-ui/styles/layout-shell.css +66 -2
  61. package/web-ui/styles/modals-core.css +87 -0
  62. package/web-ui/styles/navigation-panels.css +5 -11
  63. package/web-ui/styles/plugins-panel.css +62 -0
  64. package/web-ui/styles/prompts-editor.css +11 -4
  65. package/web-ui/styles/responsive.css +19 -10
  66. package/web-ui/styles/sessions-list.css +19 -1
  67. package/web-ui/styles/sessions-preview.css +224 -140
  68. package/web-ui/styles/sessions-toolbar-trash.css +2 -2
  69. package/web-ui/styles/settings-panel.css +1 -1
  70. package/web-ui/styles/skills-market.css +47 -0
  71. package/web-ui/styles/titles-cards.css +1 -1
  72. package/web-ui/styles/trash-panel.css +43 -6
package/cli.js CHANGED
@@ -30,6 +30,12 @@ const {
30
30
  normalizeBaseUrl,
31
31
  joinApiUrl
32
32
  } = require('./lib/cli-utils');
33
+ const {
34
+ validateProviderNamesInParsedConfig,
35
+ createConfigError,
36
+ formatConfigError,
37
+ writeConfigAtomicWithBackup
38
+ } = require('./lib/cli-config-engine');
33
39
  const {
34
40
  ensureDir,
35
41
  readJsonFile,
@@ -40,6 +46,8 @@ const {
40
46
  formatTimestampForFileName
41
47
  } = require('./lib/cli-file-utils');
42
48
  const { buildLineDiff } = require('./lib/text-diff');
49
+ const { cmdThread, handleThreadAction } = require('./lib/thread-handoff');
50
+ const { createStartupAuth } = require('./lib/web-startup-auth');
43
51
  const {
44
52
  extractModelNames,
45
53
  hasModelsListPayload,
@@ -65,6 +73,11 @@ const {
65
73
  parseMaxMessagesValue,
66
74
  resolveMaxMessagesValue
67
75
  } = require('./lib/cli-session-utils');
76
+ const {
77
+ createHttpAccessControlMiddleware,
78
+ assertExternalTokenConfigured,
79
+ parseAllowedIps
80
+ } = require('./lib/http-access-control');
68
81
  let DatabaseSync = null;
69
82
  function getNodeSqliteDatabaseSync() {
70
83
  if (DatabaseSync !== null) {
@@ -82,6 +95,7 @@ const {
82
95
  validateWorkflowDefinition,
83
96
  executeWorkflowDefinition
84
97
  } = require('./lib/workflow-engine');
98
+ const { createWorkflowRunner } = require('./lib/workflow-runner');
85
99
  const {
86
100
  ALLOWED_EVENTS: WEBHOOK_ALLOWED_EVENTS,
87
101
  defaultConfigPath: defaultWebhookConfigPath,
@@ -149,6 +163,7 @@ const {
149
163
  importCodexSkillsFromZip,
150
164
  exportSkills,
151
165
  exportCodexSkills,
166
+ backupSkills,
152
167
  deleteSkills,
153
168
  deleteCodexSkills
154
169
  } = require('./cli/skills');
@@ -828,8 +843,18 @@ function ensureConfigDir() {
828
843
  }
829
844
 
830
845
  function createConfigLoadError(type, message, detail) {
831
- const err = new Error(detail || message);
832
- err.configErrorType = type || 'read';
846
+ const errorType = type || 'read';
847
+ const code = errorType === 'parse'
848
+ ? 'CONFIG_TOML_PARSE_ERROR'
849
+ : (errorType === 'missing' ? 'CONFIG_TOML_MISSING' : 'CONFIG_TOML_READ_ERROR');
850
+ const err = createConfigError({
851
+ code,
852
+ type: errorType,
853
+ path: CONFIG_FILE,
854
+ message: message || '读取 config.toml 失败',
855
+ detail: detail || message || ''
856
+ });
857
+ err.configErrorType = errorType;
833
858
  err.configPublicReason = message || '读取 config.toml 失败';
834
859
  err.configDetail = detail || message || '';
835
860
  return err;
@@ -875,11 +900,7 @@ function readConfig() {
875
900
 
876
901
  function writeConfig(content) {
877
902
  assertToolConfigWriteAllowed('codex');
878
- try {
879
- fs.writeFileSync(CONFIG_FILE, content, 'utf-8');
880
- } catch (e) {
881
- throw new Error(`写入配置失败: ${e.message}`);
882
- }
903
+ return writeConfigAtomicWithBackup(CONFIG_FILE, content);
883
904
  }
884
905
 
885
906
  function readModels() {
@@ -2899,7 +2920,15 @@ async function fetchModelsFromBaseUrlCore(baseUrl, apiKey) {
2899
2920
  }
2900
2921
 
2901
2922
  async function fetchProviderModels(providerName, overrides = {}) {
2902
- const { config } = readConfigOrVirtualDefault();
2923
+ const configResult = readConfigOrVirtualDefault();
2924
+ if (hasConfigLoadError(configResult)) {
2925
+ throw createConfigLoadError(
2926
+ configResult.errorType,
2927
+ configResult.reason,
2928
+ configResult.detail
2929
+ );
2930
+ }
2931
+ const { config } = configResult;
2903
2932
  const targetProvider = providerName || config.model_provider || '';
2904
2933
  if (!targetProvider) return { error: '未设置当前提供商' };
2905
2934
 
@@ -3128,6 +3157,17 @@ async function buildAllProvidersHealthReport(params = {}) {
3128
3157
  });
3129
3158
  }
3130
3159
 
3160
+ function buildConfigLoadErrorPayload(result) {
3161
+ const errorType = result && result.errorType === 'read' ? 'read' : 'parse';
3162
+ return {
3163
+ code: errorType === 'parse' ? 'CONFIG_TOML_PARSE_ERROR' : 'CONFIG_TOML_READ_ERROR',
3164
+ type: errorType,
3165
+ path: CONFIG_FILE,
3166
+ message: result && result.reason ? result.reason : (errorType === 'parse' ? 'config.toml 解析失败' : '读取 config.toml 失败'),
3167
+ detail: result && result.detail ? result.detail : ''
3168
+ };
3169
+ }
3170
+
3131
3171
  function hasConfigLoadError(result) {
3132
3172
  return !!(result
3133
3173
  && result.isVirtual
@@ -3325,6 +3365,8 @@ function applyConfigTemplate(params = {}) {
3325
3365
  } catch (e) {
3326
3366
  return { error: `模板 TOML 解析失败: ${e.message}` };
3327
3367
  }
3368
+ const providerNameError = validateProviderNamesInParsedConfig(parsed);
3369
+ if (providerNameError) return providerNameError;
3328
3370
 
3329
3371
  if (
3330
3372
  Object.prototype.hasOwnProperty.call(parsed, 'model_context_window')
@@ -3389,6 +3431,8 @@ function buildConfigTemplateDiff(params = {}) {
3389
3431
  } catch (e) {
3390
3432
  return { error: `模板 TOML 解析失败: ${e.message}` };
3391
3433
  }
3434
+ const providerNameError = validateProviderNamesInParsedConfig(parsed);
3435
+ if (providerNameError) return providerNameError;
3392
3436
 
3393
3437
  if (
3394
3438
  Object.prototype.hasOwnProperty.call(parsed, 'model_context_window')
@@ -3522,7 +3566,7 @@ function addProviderToConfig(params = {}) {
3522
3566
  if (!url) return { error: 'URL 不能为空' };
3523
3567
  if (!model) return { error: '模型名称不能为空' };
3524
3568
  if (!isValidProviderName(name)) {
3525
- return { error: '名称仅支持字母/数字/._-' };
3569
+ return { error: '名称仅支持字母/数字/_-' };
3526
3570
  }
3527
3571
  if (!isValidHttpUrl(normalizedUrl)) {
3528
3572
  return { error: 'URL 仅支持 http/https' };
@@ -3649,6 +3693,7 @@ function updateProviderInConfig(params = {}) {
3649
3693
  cmdUpdate(name, url || undefined, key, true, { allowManaged, useTransform, ...(hasOpenaiBridgeMaxRetries ? { openaiBridgeMaxRetries } : {}) });
3650
3694
  return { success: true };
3651
3695
  } catch (e) {
3696
+ if (e && typeof e.code === 'string' && e.code.startsWith('CONFIG_')) throw e;
3652
3697
  return { error: e.message || '更新失败' };
3653
3698
  }
3654
3699
  }
@@ -4198,6 +4243,7 @@ function deleteProviderFromConfig(params = {}) {
4198
4243
  try {
4199
4244
  config = readConfig();
4200
4245
  } catch (e) {
4246
+ if (e && typeof e.code === 'string' && e.code.startsWith('CONFIG_')) throw e;
4201
4247
  return { error: `读取配置失败: ${e.message}` };
4202
4248
  }
4203
4249
 
@@ -10461,7 +10507,11 @@ async function importDerivedSessionToNative(params = {}) {
10461
10507
  }
10462
10508
 
10463
10509
  function buildExportPayload(includeKeys) {
10464
- const { config } = readConfigOrVirtualDefault();
10510
+ const configResult = readConfigOrVirtualDefault();
10511
+ if (hasConfigLoadError(configResult)) {
10512
+ return { error: buildConfigLoadErrorPayload(configResult) };
10513
+ }
10514
+ const { config } = configResult;
10465
10515
  const providers = config.model_providers || {};
10466
10516
  const providerData = {};
10467
10517
  for (const [name, provider] of Object.entries(providers)) {
@@ -10509,7 +10559,19 @@ function buildProviderSharePayload(params = {}) {
10509
10559
  return { error: '缺少提供商名称' };
10510
10560
  }
10511
10561
 
10512
- const { config } = readConfigOrVirtualDefault();
10562
+ const configResult = readConfigOrVirtualDefault();
10563
+ if (configResult.errorType === 'parse' || configResult.errorType === 'read') {
10564
+ return {
10565
+ error: {
10566
+ code: configResult.errorType === 'parse' ? 'CONFIG_TOML_PARSE_ERROR' : 'CONFIG_TOML_READ_ERROR',
10567
+ type: configResult.errorType,
10568
+ path: configResult.path || '',
10569
+ message: configResult.reason || '读取 config.toml 失败',
10570
+ detail: configResult.detail || ''
10571
+ }
10572
+ };
10573
+ }
10574
+ const { config } = configResult;
10513
10575
  const providers = config.model_providers || {};
10514
10576
  const provider = providers[name];
10515
10577
  if (!provider || typeof provider !== 'object') {
@@ -10569,19 +10631,21 @@ function normalizeImportPayload(payload) {
10569
10631
  if (Array.isArray(rawProviders)) {
10570
10632
  for (const item of rawProviders) {
10571
10633
  if (!item || typeof item !== 'object') continue;
10572
- const name = item.name || item.provider || '';
10634
+ const rawName = item.name || item.provider || '';
10635
+ const name = typeof rawName === 'string' ? rawName.trim() : '';
10573
10636
  const baseUrl = item.baseUrl || item.base_url || item.url || '';
10574
10637
  const apiKey = item.apiKey ?? item.key ?? item.preferred_auth_method ?? null;
10575
- if (name && baseUrl && /^[a-zA-Z0-9_\-.\s]+$/.test(name)) {
10638
+ if (name && baseUrl) {
10576
10639
  providers[name] = { baseUrl, apiKey };
10577
10640
  }
10578
10641
  }
10579
10642
  } else if (typeof rawProviders === 'object') {
10580
- for (const [name, item] of Object.entries(rawProviders)) {
10643
+ for (const [rawName, item] of Object.entries(rawProviders)) {
10581
10644
  if (!item || typeof item !== 'object') continue;
10645
+ const name = typeof rawName === 'string' ? rawName.trim() : '';
10582
10646
  const baseUrl = item.baseUrl || item.base_url || item.url || '';
10583
10647
  const apiKey = item.apiKey ?? item.key ?? item.preferred_auth_method ?? null;
10584
- if (name && baseUrl && /^[a-zA-Z0-9_\-.\s]+$/.test(name)) {
10648
+ if (name && baseUrl) {
10585
10649
  providers[name] = { baseUrl, apiKey };
10586
10650
  }
10587
10651
  }
@@ -10591,12 +10655,17 @@ function normalizeImportPayload(payload) {
10591
10655
  return { error: 'Invalid import payload' };
10592
10656
  }
10593
10657
 
10658
+ const currentProvider = typeof payload.currentProvider === 'string' ? payload.currentProvider.trim() : '';
10659
+ const currentModels = payload.currentModels && typeof payload.currentModels === 'object'
10660
+ ? payload.currentModels
10661
+ : {};
10662
+
10594
10663
  return {
10595
10664
  providers,
10596
10665
  models: Array.isArray(payload.models) ? payload.models : [],
10597
- currentProvider: typeof payload.currentProvider === 'string' ? payload.currentProvider : '',
10666
+ currentProvider,
10598
10667
  currentModel: typeof payload.currentModel === 'string' ? payload.currentModel : '',
10599
- currentModels: payload.currentModels && typeof payload.currentModels === 'object' ? payload.currentModels : {}
10668
+ currentModels
10600
10669
  };
10601
10670
  }
10602
10671
 
@@ -10610,11 +10679,29 @@ function importConfigData(payload, options = {}) {
10610
10679
  const applyCurrent = !!options.applyCurrent;
10611
10680
  const applyCurrentModels = !!options.applyCurrentModels;
10612
10681
 
10613
- const { config: existingConfig } = readConfigOrVirtualDefault();
10682
+ const existingConfigResult = readConfigOrVirtualDefault();
10683
+ if (hasConfigLoadError(existingConfigResult)) {
10684
+ return { error: buildConfigLoadErrorPayload(existingConfigResult) };
10685
+ }
10686
+ const existingConfig = existingConfigResult.config;
10614
10687
  const existingProviders = existingConfig.model_providers || {};
10615
10688
  let addedProviders = 0;
10616
10689
  let updatedProviders = 0;
10617
10690
 
10691
+ for (const name of Object.keys(normalized.providers)) {
10692
+ if (!existingProviders[name] && !isValidProviderName(name)) {
10693
+ return { error: `provider 名称非法: ${name}(名称仅支持字母/数字/_-)` };
10694
+ }
10695
+ }
10696
+ if (normalized.currentProvider && !existingProviders[normalized.currentProvider] && !isValidProviderName(normalized.currentProvider)) {
10697
+ return { error: `当前 provider 名称非法: ${normalized.currentProvider}(名称仅支持字母/数字/_-)` };
10698
+ }
10699
+ for (const name of Object.keys(normalized.currentModels)) {
10700
+ if (!existingProviders[name] && !isValidProviderName(name)) {
10701
+ return { error: `provider 名称非法: ${name}(名称仅支持字母/数字/_-)` };
10702
+ }
10703
+ }
10704
+
10618
10705
  for (const [name, provider] of Object.entries(normalized.providers)) {
10619
10706
  if (isBuiltinManagedProvider(name)) {
10620
10707
  continue;
@@ -10740,7 +10827,11 @@ function resolveSpeedTestTarget(params) {
10740
10827
  }
10741
10828
 
10742
10829
  if (params.name) {
10743
- const { config } = readConfigOrVirtualDefault();
10830
+ const configResult = readConfigOrVirtualDefault();
10831
+ if (hasConfigLoadError(configResult)) {
10832
+ return { error: buildConfigLoadErrorPayload(configResult) };
10833
+ }
10834
+ const { config } = configResult;
10744
10835
  const providers = config.model_providers || {};
10745
10836
  const provider = providers[params.name];
10746
10837
  if (!provider) {
@@ -10872,7 +10963,15 @@ async function cmdSetup() {
10872
10963
  let isCustomProvider = false;
10873
10964
 
10874
10965
  try {
10875
- const { config } = readConfigOrVirtualDefault();
10966
+ const setupConfigResult = readConfigOrVirtualDefault();
10967
+ if (hasConfigLoadError(setupConfigResult)) {
10968
+ throw createConfigLoadError(
10969
+ setupConfigResult.errorType,
10970
+ setupConfigResult.reason,
10971
+ setupConfigResult.detail
10972
+ );
10973
+ }
10974
+ const { config } = setupConfigResult;
10876
10975
  const providers = config.model_providers || {};
10877
10976
  const providerNames = Object.keys(providers);
10878
10977
  const currentProvider = typeof config.model_provider === 'string' ? config.model_provider.trim() : '';
@@ -10932,7 +11031,7 @@ async function cmdSetup() {
10932
11031
  break;
10933
11032
  }
10934
11033
 
10935
- console.log('提示: 名称仅支持字母/数字/._-');
11034
+ console.log('提示: 名称仅支持字母/数字/_-');
10936
11035
  }
10937
11036
 
10938
11037
  if (isCustomProvider && !providerName) {
@@ -10943,7 +11042,7 @@ async function cmdSetup() {
10943
11042
  continue;
10944
11043
  }
10945
11044
  if (!isValidProviderName(nameInput)) {
10946
- console.log('提示: 名称仅支持字母/数字/._-');
11045
+ console.log('提示: 名称仅支持字母/数字/_-');
10947
11046
  continue;
10948
11047
  }
10949
11048
  providerName = nameInput;
@@ -11067,7 +11166,11 @@ async function cmdSetup() {
11067
11166
  console.log(' 模型:', modelName);
11068
11167
  console.log();
11069
11168
  } catch (e) {
11070
- console.error('错误:', e.message || e);
11169
+ if (e && typeof e.code === 'string' && e.code.startsWith('CONFIG_')) {
11170
+ console.error(formatConfigError(e));
11171
+ } else {
11172
+ console.error('错误:', e.message || e);
11173
+ }
11071
11174
  process.exitCode = 1;
11072
11175
  } finally {
11073
11176
  rl.close();
@@ -11382,8 +11485,8 @@ function cmdAdd(name, baseUrl, apiKey, silent = false, options = {}) {
11382
11485
  throw new Error('名称和URL必填');
11383
11486
  }
11384
11487
  if (!isValidProviderName(providerName)) {
11385
- if (!silent) console.error('错误: 名称仅支持字母/数字/._-');
11386
- throw new Error('名称仅支持字母/数字/._-');
11488
+ if (!silent) console.error('错误: 名称仅支持字母/数字/_-');
11489
+ throw new Error('名称仅支持字母/数字/_-');
11387
11490
  }
11388
11491
  if (isReservedProviderNameForCreation(providerName)) {
11389
11492
  if (!silent) console.error('错误: 提供商名称不可用');
@@ -13810,7 +13913,31 @@ function readServerToken() {
13810
13913
  return raw;
13811
13914
  }
13812
13915
 
13916
+ function assertWebAccessControlConfigured(host) {
13917
+ const token = readServerToken();
13918
+ assertExternalTokenConfigured(host, token);
13919
+ try {
13920
+ parseAllowedIps(process.env.CODEXMATE_ALLOWED_IPS || '');
13921
+ } catch (error) {
13922
+ throw new Error(`CODEXMATE_ALLOWED_IPS 配置无效: ${error.message}`);
13923
+ }
13924
+ return token;
13925
+ }
13926
+
13927
+ function createWebAccessControlMiddleware(host) {
13928
+ const token = assertWebAccessControlConfigured(host);
13929
+ return createHttpAccessControlMiddleware({
13930
+ token,
13931
+ bypassLoopback: true,
13932
+ allowedIps: process.env.CODEXMATE_ALLOWED_IPS || '',
13933
+ requiresToken(req) {
13934
+ const requestPath = (req && req.url ? req.url : '/').split('?')[0];
13935
+ return requestPath.startsWith('/bridge/');
13936
+ }
13937
+ });
13938
+ }
13813
13939
  function assertRequestAuthorized(req, res) {
13940
+ if (req.codexmateStartupAuthenticated === true) return { ok: true, mode: 'startup-token' };
13814
13941
  const remoteAddr = req && req.socket ? req.socket.remoteAddress : '';
13815
13942
  if (isLoopbackRemoteAddress(remoteAddr)) {
13816
13943
  return { ok: true, mode: 'loopback' };
@@ -14048,6 +14175,9 @@ const PUBLIC_WEB_UI_STATIC_ASSETS = new Set([
14048
14175
 
14049
14176
  function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser }) {
14050
14177
  const connections = new Set();
14178
+ const startupAuth = createStartupAuth(readServerToken());
14179
+ const httpToken = startupAuth.token;
14180
+ const accessControlMiddleware = createWebAccessControlMiddleware(host);
14051
14181
  const probeWebUiReadiness = (callback) => {
14052
14182
  const payload = JSON.stringify({ action: 'health-check', params: {} });
14053
14183
  const requestOptions = {
@@ -14057,7 +14187,8 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
14057
14187
  method: 'POST',
14058
14188
  headers: {
14059
14189
  'Content-Type': 'application/json; charset=utf-8',
14060
- 'Content-Length': Buffer.byteLength(payload, 'utf-8')
14190
+ 'Content-Length': Buffer.byteLength(payload, 'utf-8'),
14191
+ ...(httpToken ? { Authorization: `Bearer ${httpToken}` } : {})
14061
14192
  }
14062
14193
  };
14063
14194
  let settled = false;
@@ -14086,7 +14217,8 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
14086
14217
  hostname: openHost,
14087
14218
  port,
14088
14219
  path: '/web-ui/app.js',
14089
- method: 'GET'
14220
+ method: 'GET',
14221
+ headers: httpToken ? { Authorization: `Bearer ${httpToken}` } : {}
14090
14222
  };
14091
14223
  let settled = false;
14092
14224
  const finish = (ready) => {
@@ -14207,7 +14339,7 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
14207
14339
  }
14208
14340
  }, RATE_LIMIT_WINDOW_MS).unref();
14209
14341
 
14210
- const server = http.createServer((req, res) => {
14342
+ const handleRequest = (req, res) => {
14211
14343
  const securityHeaders = {
14212
14344
  'X-Content-Type-Options': 'nosniff',
14213
14345
  'X-Frame-Options': 'DENY',
@@ -14363,6 +14495,17 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
14363
14495
  modelContextWindow,
14364
14496
  modelAutoCompactTokenLimit,
14365
14497
  configReady: !statusConfigResult.isVirtual,
14498
+ ...(hasConfigLoadError(statusConfigResult)
14499
+ ? {
14500
+ error: {
14501
+ code: statusConfigResult.errorType === 'parse' ? 'CONFIG_TOML_PARSE_ERROR' : 'CONFIG_TOML_READ_ERROR',
14502
+ type: statusConfigResult.errorType,
14503
+ path: statusConfigResult.path || '',
14504
+ message: statusConfigResult.reason || '读取 config.toml 失败',
14505
+ detail: statusConfigResult.detail || ''
14506
+ }
14507
+ }
14508
+ : {}),
14366
14509
  configErrorType: statusConfigResult.errorType || '',
14367
14510
  configNotice: statusConfigResult.reason || '',
14368
14511
  initNotice: consumeInitNotice(),
@@ -14574,6 +14717,9 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
14574
14717
  case 'export-skills':
14575
14718
  result = await exportSkills(params || {});
14576
14719
  break;
14720
+ case 'backup-skills':
14721
+ result = await backupSkills(params || {});
14722
+ break;
14577
14723
  case 'list-codex-skills':
14578
14724
  result = listCodexSkills();
14579
14725
  break;
@@ -14710,11 +14856,13 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
14710
14856
  case 'export-provider':
14711
14857
  result = buildProviderSharePayload(params || {});
14712
14858
  break;
14713
- case 'export-config':
14714
- result = {
14715
- data: buildExportPayload(!!params.includeKeys)
14716
- };
14859
+ case 'export-config': {
14860
+ const exportPayload = buildExportPayload(!!params.includeKeys);
14861
+ result = exportPayload && exportPayload.error
14862
+ ? exportPayload
14863
+ : { data: exportPayload };
14717
14864
  break;
14865
+ }
14718
14866
  case 'import-config':
14719
14867
  result = importConfigData(params.payload, params.options || {});
14720
14868
  break;
@@ -14867,6 +15015,12 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
14867
15015
  case 'session-message-counts':
14868
15016
  result = await readSessionMessageCounts(params || {});
14869
15017
  break;
15018
+ case 'thread-handoff-list':
15019
+ case 'thread-handoff-create':
15020
+ case 'thread-handoff-fallback':
15021
+ case 'thread-handoff-ack':
15022
+ result = await handleThreadAction(action, params || {});
15023
+ break;
14870
15024
  case 'session-detail':
14871
15025
  result = await readSessionDetail(params);
14872
15026
  break;
@@ -14964,6 +15118,24 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
14964
15118
  case 'claude-local-bridge-sync-providers':
14965
15119
  result = syncClaudeBridgeProviders(params || {});
14966
15120
  break;
15121
+ case 'workflow-submit':
15122
+ result = submitUnattendedWorkflow(params.id, params.input, params);
15123
+ break;
15124
+ case 'workflow-active-runs':
15125
+ result = { runs: getUnattendedWorkflowRunner().list() };
15126
+ break;
15127
+ case 'workflow-run-detail':
15128
+ result = getUnattendedWorkflowRunner().get(params.runId) || { error: 'run not found' };
15129
+ break;
15130
+ case 'workflow-resume':
15131
+ result = getUnattendedWorkflowRunner().resume(params.runId, {
15132
+ ...(params.input ? { input: params.input } : {}),
15133
+ ...(params.allowWrite === true ? { allowWrite: true } : {})
15134
+ });
15135
+ break;
15136
+ case 'workflow-cancel':
15137
+ result = getUnattendedWorkflowRunner().cancel(params.runId);
15138
+ break;
14967
15139
  case 'workflow-list':
14968
15140
  result = listWorkflowDefinitions();
14969
15141
  break;
@@ -15030,7 +15202,21 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
15030
15202
  if (leaveToolConfigWriteGuard) leaveToolConfigWriteGuard();
15031
15203
  } catch (e) {
15032
15204
  if (leaveToolConfigWriteGuard) leaveToolConfigWriteGuard();
15033
- const errorBody = JSON.stringify({ error: e.message }, null, 2);
15205
+ const errorPayload = e && typeof e.code === 'string' && e.code.startsWith('CONFIG_')
15206
+ ? {
15207
+ error: {
15208
+ code: e.code,
15209
+ type: e.type || 'config',
15210
+ path: e.path || '',
15211
+ message: e.publicReason || e.message || '配置操作失败',
15212
+ detail: e.detail || e.message || '配置操作失败',
15213
+ ...(e.backupPath ? { backupPath: e.backupPath } : {}),
15214
+ ...(typeof e.rolledBack === 'boolean' ? { rolledBack: e.rolledBack } : {}),
15215
+ ...(e.rollbackFailed ? { rollbackFailed: true } : {})
15216
+ }
15217
+ }
15218
+ : { error: e.message };
15219
+ const errorBody = JSON.stringify(errorPayload, null, 2);
15034
15220
  res.writeHead(500, {
15035
15221
  'Content-Type': 'application/json; charset=utf-8',
15036
15222
  'Content-Length': Buffer.byteLength(errorBody, 'utf-8')
@@ -15187,6 +15373,12 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
15187
15373
  res.end('Not Found');
15188
15374
  }
15189
15375
  }
15376
+ };
15377
+ const server = http.createServer((req, res) => {
15378
+ accessControlMiddleware(req, res, () => startupAuth.middleware(req, res, () => {
15379
+ req.codexmateStartupAuthenticated = true;
15380
+ handleRequest(req, res);
15381
+ }));
15190
15382
  });
15191
15383
 
15192
15384
  server.on('connection', (socket) => {
@@ -15219,8 +15411,9 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
15219
15411
  const openHost = host === '::'
15220
15412
  ? '::1'
15221
15413
  : (host === '0.0.0.0' ? DEFAULT_WEB_OPEN_HOST : host);
15222
- const openUrl = `http://${formatHostForUrl(openHost)}:${port}`;
15414
+ const openUrl = `http://${formatHostForUrl(openHost)}:${port}/?token=${encodeURIComponent(httpToken)}`;
15223
15415
  server.listen(port, host, () => {
15416
+ getUnattendedWorkflowRunner().recover();
15224
15417
  console.log('\n✓ Web UI 已启动');
15225
15418
  const willOpenBrowser = !!openBrowser && !process.env.CODEXMATE_NO_BROWSER;
15226
15419
  console.log(` ${willOpenBrowser ? '已打开' : '待访问'}: ${openUrl}`);
@@ -15229,11 +15422,11 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
15229
15422
  }
15230
15423
  console.log(' 退出: Ctrl+C\n');
15231
15424
  if (isAnyAddressHost(host)) {
15232
- const tokenEnabled = typeof process.env.CODEXMATE_HTTP_TOKEN === 'string' && process.env.CODEXMATE_HTTP_TOKEN.trim().length > 0;
15233
- console.warn(`! 安全提示: 当前监听所有网卡(${tokenEnabled ? '已启用鉴权' : '无鉴权'})。`);
15234
- if (!tokenEnabled) {
15235
- console.warn(' 建议仅在可信网络使用,或改用 --host 127.0.0.1。');
15236
- console.warn(' 如需远程访问,请设置 CODEXMATE_HTTP_TOKEN。');
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}`);
15237
15430
  }
15238
15431
  }
15239
15432
 
@@ -15344,6 +15537,16 @@ async function cmdStart(options = {}) {
15344
15537
  let port = resolveWebPort();
15345
15538
  const explicitPort = isWebPortExplicit();
15346
15539
  const host = resolveWebHost(options);
15540
+ try {
15541
+ assertWebAccessControlConfigured(host);
15542
+ } catch (error) {
15543
+ const message = error && error.message ? error.message : String(error);
15544
+ console.error(`! 启动失败: ${message}`);
15545
+ if (message.includes('CODEXMATE_HTTP_TOKEN')) {
15546
+ console.error(' 对外监听必须设置 CODEXMATE_HTTP_TOKEN;仅本机访问请改用 --host 127.0.0.1。');
15547
+ }
15548
+ process.exit(1);
15549
+ }
15347
15550
  releaseRunPortIfNeeded(port, host);
15348
15551
  const selectedPort = await resolveAvailableWebPort(port, host, { explicitPort });
15349
15552
  if (selectedPort.error) {
@@ -15581,7 +15784,7 @@ function parseWorkflowInputArg(rawInput) {
15581
15784
  }
15582
15785
 
15583
15786
  function printWorkflowHelp() {
15584
- console.log('\n用法: codexmate workflow <list|get|validate|run|runs> [参数]');
15787
+ console.log('\n用法: codexmate workflow <list|get|validate|run|runs|submit|active-runs|detail|resume|cancel> [参数]');
15585
15788
  console.log(' codexmate workflow list');
15586
15789
  console.log(' codexmate workflow get diagnose-config');
15587
15790
  console.log(' codexmate workflow validate safe-provider-switch --input \'{"provider":"e2e"}\'');
@@ -15650,6 +15853,28 @@ function parseWorkflowCliOptions(args = []) {
15650
15853
  return { options, rest };
15651
15854
  }
15652
15855
 
15856
+ async function callWorkflowService(action, params = {}) {
15857
+ const actions = { submit: 'workflow-submit', 'active-runs': 'workflow-active-runs', detail: 'workflow-run-detail', resume: 'workflow-resume', cancel: 'workflow-cancel' };
15858
+ const port = parseInt(process.env.CODEXMATE_PORT, 10) || DEFAULT_WEB_PORT;
15859
+ const token = readServerToken();
15860
+ const body = JSON.stringify({ action: actions[action], params });
15861
+ return new Promise((resolve, reject) => {
15862
+ const req = http.request({ hostname: '127.0.0.1', port, path: '/api', method: 'POST', headers: {
15863
+ 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body),
15864
+ ...(token ? { Authorization: `Bearer ${token}` } : {})
15865
+ } }, res => {
15866
+ let text = '';
15867
+ res.on('data', chunk => { text += chunk; });
15868
+ res.on('end', () => {
15869
+ try { resolve(JSON.parse(text)); } catch (error) { reject(error); }
15870
+ });
15871
+ });
15872
+ req.on('error', reject);
15873
+ req.setTimeout(10000, () => req.destroy(new Error('workflow service request timed out')));
15874
+ req.end(body);
15875
+ });
15876
+ }
15877
+
15653
15878
  async function cmdWorkflow(args = []) {
15654
15879
  const argv = Array.isArray(args) ? args : [];
15655
15880
  if (argv.length === 0 || argv.includes('--help') || argv.includes('-h')) {
@@ -15660,6 +15885,16 @@ async function cmdWorkflow(args = []) {
15660
15885
  const parsed = parseWorkflowCliOptions(argv.slice(1));
15661
15886
  const options = parsed.options;
15662
15887
  const rest = parsed.rest;
15888
+ if (['submit', 'active-runs', 'detail', 'resume', 'cancel'].includes(subcommand)) {
15889
+ const result = await callWorkflowService(subcommand, {
15890
+ id: rest[0], runId: rest[0],
15891
+ ...(options.inputRaw ? { input: parseWorkflowInputArg(options.inputRaw) } : {}),
15892
+ allowWrite: options.allowWrite === true, dryRun: options.dryRun === true
15893
+ });
15894
+ console.log(JSON.stringify(result, null, 2));
15895
+ if (result.error) throw new Error(result.error);
15896
+ return;
15897
+ }
15663
15898
 
15664
15899
  if (subcommand === 'list') {
15665
15900
  const result = listWorkflowDefinitions();
@@ -16246,6 +16481,17 @@ function buildMcpStatusPayload() {
16246
16481
  modelContextWindow,
16247
16482
  modelAutoCompactTokenLimit,
16248
16483
  configReady: !statusConfigResult.isVirtual,
16484
+ ...(hasConfigLoadError(statusConfigResult)
16485
+ ? {
16486
+ error: {
16487
+ code: statusConfigResult.errorType === 'parse' ? 'CONFIG_TOML_PARSE_ERROR' : 'CONFIG_TOML_READ_ERROR',
16488
+ type: statusConfigResult.errorType,
16489
+ path: statusConfigResult.path || '',
16490
+ message: statusConfigResult.reason || '读取 config.toml 失败',
16491
+ detail: statusConfigResult.detail || ''
16492
+ }
16493
+ }
16494
+ : {}),
16249
16495
  configErrorType: statusConfigResult.errorType || '',
16250
16496
  configNotice: statusConfigResult.reason || '',
16251
16497
  initNotice: consumeInitNotice()
@@ -16259,6 +16505,17 @@ function buildMcpProviderListPayload() {
16259
16505
  const current = listConfig.model_provider;
16260
16506
  return {
16261
16507
  configReady: !listConfigResult.isVirtual,
16508
+ ...(listConfigResult.errorType === 'parse' || listConfigResult.errorType === 'read'
16509
+ ? {
16510
+ error: {
16511
+ code: listConfigResult.errorType === 'parse' ? 'CONFIG_TOML_PARSE_ERROR' : 'CONFIG_TOML_READ_ERROR',
16512
+ type: listConfigResult.errorType,
16513
+ path: listConfigResult.path || '',
16514
+ message: listConfigResult.reason || '读取 config.toml 失败',
16515
+ detail: listConfigResult.detail || ''
16516
+ }
16517
+ }
16518
+ : {}),
16262
16519
  configErrorType: listConfigResult.errorType || '',
16263
16520
  configNotice: listConfigResult.reason || '',
16264
16521
  providers: Object.entries(providers).map(([name, p]) => {
@@ -16519,6 +16776,9 @@ function normalizeWorkflowDefinition(raw, idHint = '', source = 'custom') {
16519
16776
  tool: toolName,
16520
16777
  arguments: args,
16521
16778
  when,
16779
+ ...(item.dependsOn !== undefined ? { dependsOn: cloneJson(item.dependsOn, null) } : {}),
16780
+ ...(item.retry !== undefined ? { retry: item.retry } : {}),
16781
+ ...(item.timeoutMs !== undefined ? { timeoutMs: item.timeoutMs } : {}),
16522
16782
  continueOnError: item.continueOnError === true,
16523
16783
  write: item.write === true
16524
16784
  });
@@ -16803,6 +17063,47 @@ function validateWorkflowById(workflowId, input = {}) {
16803
17063
  };
16804
17064
  }
16805
17065
 
17066
+ let unattendedWorkflowRunner = null;
17067
+ function getUnattendedWorkflowRunner() {
17068
+ if (unattendedWorkflowRunner) return unattendedWorkflowRunner;
17069
+ unattendedWorkflowRunner = createWorkflowRunner({
17070
+ directory: path.join(CONFIG_DIR, 'workflow-runs'),
17071
+ execute: async (definition, input, options) => {
17072
+ const check = validateWorkflowInputBySchema(definition.inputSchema, input);
17073
+ if (!check.ok) return { success: false, waiting: true, error: check.error, steps: options.resumeSteps || [] };
17074
+ const catalog = createWorkflowToolCatalog();
17075
+ return executeWorkflowDefinition(definition, input, {
17076
+ ...options,
17077
+ invokeTool: async (name, args, execution) => {
17078
+ const tool = catalog[name];
17079
+ if (!tool) return { error: `workflow tool not supported: ${name}`, blocked: true };
17080
+ if (!tool.readOnly && !options.allowWrite) return { error: 'write permission required', blocked: true };
17081
+ if (!tool.readOnly && !isToolConfigWriteAllowed('codex')) return { error: 'codex configuration permission required', blocked: true };
17082
+ return tool.handler(args, { signal: execution.signal });
17083
+ }
17084
+ });
17085
+ },
17086
+ notify: async run => {
17087
+ const result = await notifyWebhook(
17088
+ run.status === 'waiting' ? 'workflow-waiting' : (run.status === 'completed' ? 'workflow-completed' : 'workflow-failed'),
17089
+ `工作流 ${run.definition.id}: ${run.status}`, { runId: run.id, summary: run.summary }
17090
+ );
17091
+ return result;
17092
+ }
17093
+ });
17094
+ return unattendedWorkflowRunner;
17095
+ }
17096
+ function submitUnattendedWorkflow(id, input, options = {}) {
17097
+ const result = getWorkflowDefinitionById(id);
17098
+ if (result.error) return result;
17099
+ const definition = resolveWorkflowDefinitionWithToolMeta(result.workflow);
17100
+ const validation = validateWorkflowDefinition(definition, { knownTools: getWorkflowKnownToolsSet() });
17101
+ if (!validation.ok) return validation;
17102
+ return getUnattendedWorkflowRunner().submit(definition, input || {}, {
17103
+ allowWrite: options.allowWrite === true, dryRun: options.dryRun === true
17104
+ });
17105
+ }
17106
+
16806
17107
  async function runWorkflowById(workflowId, input = {}, options = {}) {
16807
17108
  const definitionResult = getWorkflowDefinitionById(workflowId);
16808
17109
  if (definitionResult.error) {
@@ -17090,6 +17391,18 @@ function createMcpTools(options = {}) {
17090
17391
  handler: async () => getBuiltinClaudeProxyStatus()
17091
17392
  });
17092
17393
 
17394
+ for (const action of ['submit', 'active-runs', 'detail', 'resume', 'cancel']) {
17395
+ pushTool({
17396
+ name: `codexmate.workflow.${action}`,
17397
+ description: `Persistent workflow ${action}; requires the Web service.`,
17398
+ readOnly: !['submit', 'resume', 'cancel'].includes(action),
17399
+ inputSchema: { type: 'object', properties: {
17400
+ id: { type: 'string' }, runId: { type: 'string' }, input: { type: 'object' }, dryRun: { type: 'boolean' }
17401
+ } },
17402
+ handler: async (params = {}) => callWorkflowService(action, { ...params, allowWrite })
17403
+ });
17404
+ }
17405
+
17093
17406
  pushTool({
17094
17407
  name: 'codexmate.workflow.list',
17095
17408
  description: 'List available workflows (builtin + custom).',
@@ -17720,7 +18033,8 @@ function printMainHelp() {
17720
18033
  console.log(' codexmate auth <list|import|switch|delete|status> 认证管理');
17721
18034
  console.log(' codexmate add-model <模型> 添加模型');
17722
18035
  console.log(' codexmate delete-model <模型> 删除模型');
17723
- console.log(' codexmate workflow <list|get|validate|run|runs> MCP 工作流中心');
18036
+ console.log(' codexmate workflow <list|get|validate|run|runs|submit|active-runs|detail|resume|cancel> MCP 工作流中心');
18037
+ console.log(' codexmate thread <handoff|list|fallback|ack> 交接卡与共享记忆路由');
17724
18038
  console.log(' codexmate analytics export [--format csv|json] [--from YYYY-MM-DD] [--to YYYY-MM-DD] [--model <MODEL>] [--output <PATH|->] [-o <PATH|->] 导出 Usage 数据');
17725
18039
  console.log(' codexmate run [--host <HOST>] [--no-browser] 启动 Web 界面');
17726
18040
  console.log(' codexmate update [--check] 检查并快速更新工具');
@@ -17742,6 +18056,10 @@ function printMainHelp() {
17742
18056
  async function main() {
17743
18057
  const args = process.argv.slice(2);
17744
18058
  const command = args[0];
18059
+ if (command === 'thread') {
18060
+ await cmdThread(args.slice(1));
18061
+ return;
18062
+ }
17745
18063
  const isMcpCommand = command === 'mcp';
17746
18064
  const shouldGateInitialBootstrap = command === 'run' || isMcpCommand;
17747
18065
  const bootstrap = ensureManagedConfigBootstrap({
@@ -17856,6 +18174,10 @@ async function main() {
17856
18174
  }
17857
18175
 
17858
18176
  main().catch((err) => {
17859
- console.error('错误:', err && err.message ? err.message : err);
18177
+ if (err && typeof err.code === 'string' && err.code.startsWith('CONFIG_')) {
18178
+ console.error(formatConfigError(err));
18179
+ } else {
18180
+ console.error('错误:', err && err.message ? err.message : err);
18181
+ }
17860
18182
  process.exit(1);
17861
18183
  });