codexmate 0.1.30 → 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 (53) 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.js +360 -44
  6. package/lib/cli-config-engine.js +260 -0
  7. package/lib/cli-utils.js +2 -1
  8. package/lib/cli-webhook.js +1 -1
  9. package/lib/handoff-mcp.js +282 -0
  10. package/lib/http-access-control.js +335 -0
  11. package/lib/thread-handoff.js +130 -0
  12. package/lib/web-startup-auth.js +49 -0
  13. package/lib/workflow-engine.js +92 -21
  14. package/lib/workflow-runner.js +261 -0
  15. package/package.json +1 -1
  16. package/web-ui/app.js +23 -2
  17. package/web-ui/modules/access-token.mjs +33 -0
  18. package/web-ui/modules/api.mjs +2 -1
  19. package/web-ui/modules/app.methods.index.mjs +2 -0
  20. package/web-ui/modules/app.methods.navigation.mjs +17 -3
  21. package/web-ui/modules/app.methods.prompts-editor.mjs +7 -0
  22. package/web-ui/modules/app.methods.providers.mjs +2 -2
  23. package/web-ui/modules/app.methods.runtime.mjs +3 -2
  24. package/web-ui/modules/app.methods.session-actions.mjs +3 -0
  25. package/web-ui/modules/app.methods.session-browser.mjs +6 -2
  26. package/web-ui/modules/app.methods.workflows.mjs +41 -0
  27. package/web-ui/modules/i18n/locales/en.mjs +37 -2
  28. package/web-ui/modules/i18n/locales/ja.mjs +37 -2
  29. package/web-ui/modules/i18n/locales/vi.mjs +37 -2
  30. package/web-ui/modules/i18n/locales/zh-tw.mjs +37 -2
  31. package/web-ui/modules/i18n/locales/zh.mjs +37 -2
  32. package/web-ui/modules/sessions-filters-url.mjs +3 -0
  33. package/web-ui/modules/skills.methods.mjs +6 -5
  34. package/web-ui/modules/thread-handoff.mjs +142 -0
  35. package/web-ui/partials/index/panel-config-claude.html +2 -0
  36. package/web-ui/partials/index/panel-config-codex.html +2 -0
  37. package/web-ui/partials/index/panel-config-kilocode.html +3 -1
  38. package/web-ui/partials/index/panel-config-openclaw.html +2 -0
  39. package/web-ui/partials/index/panel-config-opencode.html +3 -1
  40. package/web-ui/partials/index/panel-config-pi.html +2 -0
  41. package/web-ui/partials/index/panel-dashboard.html +59 -0
  42. package/web-ui/partials/index/panel-prompts.html +28 -16
  43. package/web-ui/partials/index/panel-sessions.html +21 -33
  44. package/web-ui/partials/index/thread-handoff.html +59 -0
  45. package/web-ui/res/web-ui-render.precompiled.js +614 -152
  46. package/web-ui/styles/controls-forms.css +9 -0
  47. package/web-ui/styles/dashboard.css +51 -0
  48. package/web-ui/styles/modals-core.css +87 -0
  49. package/web-ui/styles/navigation-panels.css +1 -1
  50. package/web-ui/styles/plugins-panel.css +62 -0
  51. package/web-ui/styles/prompts-editor.css +11 -4
  52. package/web-ui/styles/responsive.css +19 -10
  53. package/web-ui/styles/sessions-preview.css +185 -111
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,
@@ -829,8 +843,18 @@ function ensureConfigDir() {
829
843
  }
830
844
 
831
845
  function createConfigLoadError(type, message, detail) {
832
- const err = new Error(detail || message);
833
- 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;
834
858
  err.configPublicReason = message || '读取 config.toml 失败';
835
859
  err.configDetail = detail || message || '';
836
860
  return err;
@@ -876,11 +900,7 @@ function readConfig() {
876
900
 
877
901
  function writeConfig(content) {
878
902
  assertToolConfigWriteAllowed('codex');
879
- try {
880
- fs.writeFileSync(CONFIG_FILE, content, 'utf-8');
881
- } catch (e) {
882
- throw new Error(`写入配置失败: ${e.message}`);
883
- }
903
+ return writeConfigAtomicWithBackup(CONFIG_FILE, content);
884
904
  }
885
905
 
886
906
  function readModels() {
@@ -2900,7 +2920,15 @@ async function fetchModelsFromBaseUrlCore(baseUrl, apiKey) {
2900
2920
  }
2901
2921
 
2902
2922
  async function fetchProviderModels(providerName, overrides = {}) {
2903
- 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;
2904
2932
  const targetProvider = providerName || config.model_provider || '';
2905
2933
  if (!targetProvider) return { error: '未设置当前提供商' };
2906
2934
 
@@ -3129,6 +3157,17 @@ async function buildAllProvidersHealthReport(params = {}) {
3129
3157
  });
3130
3158
  }
3131
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
+
3132
3171
  function hasConfigLoadError(result) {
3133
3172
  return !!(result
3134
3173
  && result.isVirtual
@@ -3326,6 +3365,8 @@ function applyConfigTemplate(params = {}) {
3326
3365
  } catch (e) {
3327
3366
  return { error: `模板 TOML 解析失败: ${e.message}` };
3328
3367
  }
3368
+ const providerNameError = validateProviderNamesInParsedConfig(parsed);
3369
+ if (providerNameError) return providerNameError;
3329
3370
 
3330
3371
  if (
3331
3372
  Object.prototype.hasOwnProperty.call(parsed, 'model_context_window')
@@ -3390,6 +3431,8 @@ function buildConfigTemplateDiff(params = {}) {
3390
3431
  } catch (e) {
3391
3432
  return { error: `模板 TOML 解析失败: ${e.message}` };
3392
3433
  }
3434
+ const providerNameError = validateProviderNamesInParsedConfig(parsed);
3435
+ if (providerNameError) return providerNameError;
3393
3436
 
3394
3437
  if (
3395
3438
  Object.prototype.hasOwnProperty.call(parsed, 'model_context_window')
@@ -3523,7 +3566,7 @@ function addProviderToConfig(params = {}) {
3523
3566
  if (!url) return { error: 'URL 不能为空' };
3524
3567
  if (!model) return { error: '模型名称不能为空' };
3525
3568
  if (!isValidProviderName(name)) {
3526
- return { error: '名称仅支持字母/数字/._-' };
3569
+ return { error: '名称仅支持字母/数字/_-' };
3527
3570
  }
3528
3571
  if (!isValidHttpUrl(normalizedUrl)) {
3529
3572
  return { error: 'URL 仅支持 http/https' };
@@ -3650,6 +3693,7 @@ function updateProviderInConfig(params = {}) {
3650
3693
  cmdUpdate(name, url || undefined, key, true, { allowManaged, useTransform, ...(hasOpenaiBridgeMaxRetries ? { openaiBridgeMaxRetries } : {}) });
3651
3694
  return { success: true };
3652
3695
  } catch (e) {
3696
+ if (e && typeof e.code === 'string' && e.code.startsWith('CONFIG_')) throw e;
3653
3697
  return { error: e.message || '更新失败' };
3654
3698
  }
3655
3699
  }
@@ -4199,6 +4243,7 @@ function deleteProviderFromConfig(params = {}) {
4199
4243
  try {
4200
4244
  config = readConfig();
4201
4245
  } catch (e) {
4246
+ if (e && typeof e.code === 'string' && e.code.startsWith('CONFIG_')) throw e;
4202
4247
  return { error: `读取配置失败: ${e.message}` };
4203
4248
  }
4204
4249
 
@@ -10462,7 +10507,11 @@ async function importDerivedSessionToNative(params = {}) {
10462
10507
  }
10463
10508
 
10464
10509
  function buildExportPayload(includeKeys) {
10465
- const { config } = readConfigOrVirtualDefault();
10510
+ const configResult = readConfigOrVirtualDefault();
10511
+ if (hasConfigLoadError(configResult)) {
10512
+ return { error: buildConfigLoadErrorPayload(configResult) };
10513
+ }
10514
+ const { config } = configResult;
10466
10515
  const providers = config.model_providers || {};
10467
10516
  const providerData = {};
10468
10517
  for (const [name, provider] of Object.entries(providers)) {
@@ -10510,7 +10559,19 @@ function buildProviderSharePayload(params = {}) {
10510
10559
  return { error: '缺少提供商名称' };
10511
10560
  }
10512
10561
 
10513
- 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;
10514
10575
  const providers = config.model_providers || {};
10515
10576
  const provider = providers[name];
10516
10577
  if (!provider || typeof provider !== 'object') {
@@ -10570,19 +10631,21 @@ function normalizeImportPayload(payload) {
10570
10631
  if (Array.isArray(rawProviders)) {
10571
10632
  for (const item of rawProviders) {
10572
10633
  if (!item || typeof item !== 'object') continue;
10573
- const name = item.name || item.provider || '';
10634
+ const rawName = item.name || item.provider || '';
10635
+ const name = typeof rawName === 'string' ? rawName.trim() : '';
10574
10636
  const baseUrl = item.baseUrl || item.base_url || item.url || '';
10575
10637
  const apiKey = item.apiKey ?? item.key ?? item.preferred_auth_method ?? null;
10576
- if (name && baseUrl && /^[a-zA-Z0-9_\-.\s]+$/.test(name)) {
10638
+ if (name && baseUrl) {
10577
10639
  providers[name] = { baseUrl, apiKey };
10578
10640
  }
10579
10641
  }
10580
10642
  } else if (typeof rawProviders === 'object') {
10581
- for (const [name, item] of Object.entries(rawProviders)) {
10643
+ for (const [rawName, item] of Object.entries(rawProviders)) {
10582
10644
  if (!item || typeof item !== 'object') continue;
10645
+ const name = typeof rawName === 'string' ? rawName.trim() : '';
10583
10646
  const baseUrl = item.baseUrl || item.base_url || item.url || '';
10584
10647
  const apiKey = item.apiKey ?? item.key ?? item.preferred_auth_method ?? null;
10585
- if (name && baseUrl && /^[a-zA-Z0-9_\-.\s]+$/.test(name)) {
10648
+ if (name && baseUrl) {
10586
10649
  providers[name] = { baseUrl, apiKey };
10587
10650
  }
10588
10651
  }
@@ -10592,12 +10655,17 @@ function normalizeImportPayload(payload) {
10592
10655
  return { error: 'Invalid import payload' };
10593
10656
  }
10594
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
+
10595
10663
  return {
10596
10664
  providers,
10597
10665
  models: Array.isArray(payload.models) ? payload.models : [],
10598
- currentProvider: typeof payload.currentProvider === 'string' ? payload.currentProvider : '',
10666
+ currentProvider,
10599
10667
  currentModel: typeof payload.currentModel === 'string' ? payload.currentModel : '',
10600
- currentModels: payload.currentModels && typeof payload.currentModels === 'object' ? payload.currentModels : {}
10668
+ currentModels
10601
10669
  };
10602
10670
  }
10603
10671
 
@@ -10611,11 +10679,29 @@ function importConfigData(payload, options = {}) {
10611
10679
  const applyCurrent = !!options.applyCurrent;
10612
10680
  const applyCurrentModels = !!options.applyCurrentModels;
10613
10681
 
10614
- const { config: existingConfig } = readConfigOrVirtualDefault();
10682
+ const existingConfigResult = readConfigOrVirtualDefault();
10683
+ if (hasConfigLoadError(existingConfigResult)) {
10684
+ return { error: buildConfigLoadErrorPayload(existingConfigResult) };
10685
+ }
10686
+ const existingConfig = existingConfigResult.config;
10615
10687
  const existingProviders = existingConfig.model_providers || {};
10616
10688
  let addedProviders = 0;
10617
10689
  let updatedProviders = 0;
10618
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
+
10619
10705
  for (const [name, provider] of Object.entries(normalized.providers)) {
10620
10706
  if (isBuiltinManagedProvider(name)) {
10621
10707
  continue;
@@ -10741,7 +10827,11 @@ function resolveSpeedTestTarget(params) {
10741
10827
  }
10742
10828
 
10743
10829
  if (params.name) {
10744
- const { config } = readConfigOrVirtualDefault();
10830
+ const configResult = readConfigOrVirtualDefault();
10831
+ if (hasConfigLoadError(configResult)) {
10832
+ return { error: buildConfigLoadErrorPayload(configResult) };
10833
+ }
10834
+ const { config } = configResult;
10745
10835
  const providers = config.model_providers || {};
10746
10836
  const provider = providers[params.name];
10747
10837
  if (!provider) {
@@ -10873,7 +10963,15 @@ async function cmdSetup() {
10873
10963
  let isCustomProvider = false;
10874
10964
 
10875
10965
  try {
10876
- 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;
10877
10975
  const providers = config.model_providers || {};
10878
10976
  const providerNames = Object.keys(providers);
10879
10977
  const currentProvider = typeof config.model_provider === 'string' ? config.model_provider.trim() : '';
@@ -10933,7 +11031,7 @@ async function cmdSetup() {
10933
11031
  break;
10934
11032
  }
10935
11033
 
10936
- console.log('提示: 名称仅支持字母/数字/._-');
11034
+ console.log('提示: 名称仅支持字母/数字/_-');
10937
11035
  }
10938
11036
 
10939
11037
  if (isCustomProvider && !providerName) {
@@ -10944,7 +11042,7 @@ async function cmdSetup() {
10944
11042
  continue;
10945
11043
  }
10946
11044
  if (!isValidProviderName(nameInput)) {
10947
- console.log('提示: 名称仅支持字母/数字/._-');
11045
+ console.log('提示: 名称仅支持字母/数字/_-');
10948
11046
  continue;
10949
11047
  }
10950
11048
  providerName = nameInput;
@@ -11068,7 +11166,11 @@ async function cmdSetup() {
11068
11166
  console.log(' 模型:', modelName);
11069
11167
  console.log();
11070
11168
  } catch (e) {
11071
- 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
+ }
11072
11174
  process.exitCode = 1;
11073
11175
  } finally {
11074
11176
  rl.close();
@@ -11383,8 +11485,8 @@ function cmdAdd(name, baseUrl, apiKey, silent = false, options = {}) {
11383
11485
  throw new Error('名称和URL必填');
11384
11486
  }
11385
11487
  if (!isValidProviderName(providerName)) {
11386
- if (!silent) console.error('错误: 名称仅支持字母/数字/._-');
11387
- throw new Error('名称仅支持字母/数字/._-');
11488
+ if (!silent) console.error('错误: 名称仅支持字母/数字/_-');
11489
+ throw new Error('名称仅支持字母/数字/_-');
11388
11490
  }
11389
11491
  if (isReservedProviderNameForCreation(providerName)) {
11390
11492
  if (!silent) console.error('错误: 提供商名称不可用');
@@ -13811,7 +13913,31 @@ function readServerToken() {
13811
13913
  return raw;
13812
13914
  }
13813
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
+ }
13814
13939
  function assertRequestAuthorized(req, res) {
13940
+ if (req.codexmateStartupAuthenticated === true) return { ok: true, mode: 'startup-token' };
13815
13941
  const remoteAddr = req && req.socket ? req.socket.remoteAddress : '';
13816
13942
  if (isLoopbackRemoteAddress(remoteAddr)) {
13817
13943
  return { ok: true, mode: 'loopback' };
@@ -14049,6 +14175,9 @@ const PUBLIC_WEB_UI_STATIC_ASSETS = new Set([
14049
14175
 
14050
14176
  function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser }) {
14051
14177
  const connections = new Set();
14178
+ const startupAuth = createStartupAuth(readServerToken());
14179
+ const httpToken = startupAuth.token;
14180
+ const accessControlMiddleware = createWebAccessControlMiddleware(host);
14052
14181
  const probeWebUiReadiness = (callback) => {
14053
14182
  const payload = JSON.stringify({ action: 'health-check', params: {} });
14054
14183
  const requestOptions = {
@@ -14058,7 +14187,8 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
14058
14187
  method: 'POST',
14059
14188
  headers: {
14060
14189
  'Content-Type': 'application/json; charset=utf-8',
14061
- 'Content-Length': Buffer.byteLength(payload, 'utf-8')
14190
+ 'Content-Length': Buffer.byteLength(payload, 'utf-8'),
14191
+ ...(httpToken ? { Authorization: `Bearer ${httpToken}` } : {})
14062
14192
  }
14063
14193
  };
14064
14194
  let settled = false;
@@ -14087,7 +14217,8 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
14087
14217
  hostname: openHost,
14088
14218
  port,
14089
14219
  path: '/web-ui/app.js',
14090
- method: 'GET'
14220
+ method: 'GET',
14221
+ headers: httpToken ? { Authorization: `Bearer ${httpToken}` } : {}
14091
14222
  };
14092
14223
  let settled = false;
14093
14224
  const finish = (ready) => {
@@ -14208,7 +14339,7 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
14208
14339
  }
14209
14340
  }, RATE_LIMIT_WINDOW_MS).unref();
14210
14341
 
14211
- const server = http.createServer((req, res) => {
14342
+ const handleRequest = (req, res) => {
14212
14343
  const securityHeaders = {
14213
14344
  'X-Content-Type-Options': 'nosniff',
14214
14345
  'X-Frame-Options': 'DENY',
@@ -14364,6 +14495,17 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
14364
14495
  modelContextWindow,
14365
14496
  modelAutoCompactTokenLimit,
14366
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
+ : {}),
14367
14509
  configErrorType: statusConfigResult.errorType || '',
14368
14510
  configNotice: statusConfigResult.reason || '',
14369
14511
  initNotice: consumeInitNotice(),
@@ -14714,11 +14856,13 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
14714
14856
  case 'export-provider':
14715
14857
  result = buildProviderSharePayload(params || {});
14716
14858
  break;
14717
- case 'export-config':
14718
- result = {
14719
- data: buildExportPayload(!!params.includeKeys)
14720
- };
14859
+ case 'export-config': {
14860
+ const exportPayload = buildExportPayload(!!params.includeKeys);
14861
+ result = exportPayload && exportPayload.error
14862
+ ? exportPayload
14863
+ : { data: exportPayload };
14721
14864
  break;
14865
+ }
14722
14866
  case 'import-config':
14723
14867
  result = importConfigData(params.payload, params.options || {});
14724
14868
  break;
@@ -14871,6 +15015,12 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
14871
15015
  case 'session-message-counts':
14872
15016
  result = await readSessionMessageCounts(params || {});
14873
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;
14874
15024
  case 'session-detail':
14875
15025
  result = await readSessionDetail(params);
14876
15026
  break;
@@ -14968,6 +15118,24 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
14968
15118
  case 'claude-local-bridge-sync-providers':
14969
15119
  result = syncClaudeBridgeProviders(params || {});
14970
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;
14971
15139
  case 'workflow-list':
14972
15140
  result = listWorkflowDefinitions();
14973
15141
  break;
@@ -15034,7 +15202,21 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
15034
15202
  if (leaveToolConfigWriteGuard) leaveToolConfigWriteGuard();
15035
15203
  } catch (e) {
15036
15204
  if (leaveToolConfigWriteGuard) leaveToolConfigWriteGuard();
15037
- 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);
15038
15220
  res.writeHead(500, {
15039
15221
  'Content-Type': 'application/json; charset=utf-8',
15040
15222
  'Content-Length': Buffer.byteLength(errorBody, 'utf-8')
@@ -15191,6 +15373,12 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
15191
15373
  res.end('Not Found');
15192
15374
  }
15193
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
+ }));
15194
15382
  });
15195
15383
 
15196
15384
  server.on('connection', (socket) => {
@@ -15223,8 +15411,9 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
15223
15411
  const openHost = host === '::'
15224
15412
  ? '::1'
15225
15413
  : (host === '0.0.0.0' ? DEFAULT_WEB_OPEN_HOST : host);
15226
- const openUrl = `http://${formatHostForUrl(openHost)}:${port}`;
15414
+ const openUrl = `http://${formatHostForUrl(openHost)}:${port}/?token=${encodeURIComponent(httpToken)}`;
15227
15415
  server.listen(port, host, () => {
15416
+ getUnattendedWorkflowRunner().recover();
15228
15417
  console.log('\n✓ Web UI 已启动');
15229
15418
  const willOpenBrowser = !!openBrowser && !process.env.CODEXMATE_NO_BROWSER;
15230
15419
  console.log(` ${willOpenBrowser ? '已打开' : '待访问'}: ${openUrl}`);
@@ -15233,13 +15422,11 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
15233
15422
  }
15234
15423
  console.log(' 退出: Ctrl+C\n');
15235
15424
  if (isAnyAddressHost(host)) {
15236
- const tokenEnabled = typeof process.env.CODEXMATE_HTTP_TOKEN === 'string' && process.env.CODEXMATE_HTTP_TOKEN.trim().length > 0;
15237
- if (tokenEnabled) {
15238
- console.warn('! 安全提示: 当前监听所有网卡,局域网访问需要访问令牌。');
15239
- } else {
15240
- console.warn('! 安全提示: 当前监听所有网卡,但未配置访问令牌,远程访问已禁用。');
15241
- console.warn(' 如需局域网访问,请先设置 CODEXMATE_HTTP_TOKEN。');
15242
- console.warn(' 如需仅限本机访问,请改用 --host 127.0.0.1。');
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}`);
15243
15430
  }
15244
15431
  }
15245
15432
 
@@ -15350,6 +15537,16 @@ async function cmdStart(options = {}) {
15350
15537
  let port = resolveWebPort();
15351
15538
  const explicitPort = isWebPortExplicit();
15352
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
+ }
15353
15550
  releaseRunPortIfNeeded(port, host);
15354
15551
  const selectedPort = await resolveAvailableWebPort(port, host, { explicitPort });
15355
15552
  if (selectedPort.error) {
@@ -15587,7 +15784,7 @@ function parseWorkflowInputArg(rawInput) {
15587
15784
  }
15588
15785
 
15589
15786
  function printWorkflowHelp() {
15590
- 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> [参数]');
15591
15788
  console.log(' codexmate workflow list');
15592
15789
  console.log(' codexmate workflow get diagnose-config');
15593
15790
  console.log(' codexmate workflow validate safe-provider-switch --input \'{"provider":"e2e"}\'');
@@ -15656,6 +15853,28 @@ function parseWorkflowCliOptions(args = []) {
15656
15853
  return { options, rest };
15657
15854
  }
15658
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
+
15659
15878
  async function cmdWorkflow(args = []) {
15660
15879
  const argv = Array.isArray(args) ? args : [];
15661
15880
  if (argv.length === 0 || argv.includes('--help') || argv.includes('-h')) {
@@ -15666,6 +15885,16 @@ async function cmdWorkflow(args = []) {
15666
15885
  const parsed = parseWorkflowCliOptions(argv.slice(1));
15667
15886
  const options = parsed.options;
15668
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
+ }
15669
15898
 
15670
15899
  if (subcommand === 'list') {
15671
15900
  const result = listWorkflowDefinitions();
@@ -16252,6 +16481,17 @@ function buildMcpStatusPayload() {
16252
16481
  modelContextWindow,
16253
16482
  modelAutoCompactTokenLimit,
16254
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
+ : {}),
16255
16495
  configErrorType: statusConfigResult.errorType || '',
16256
16496
  configNotice: statusConfigResult.reason || '',
16257
16497
  initNotice: consumeInitNotice()
@@ -16265,6 +16505,17 @@ function buildMcpProviderListPayload() {
16265
16505
  const current = listConfig.model_provider;
16266
16506
  return {
16267
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
+ : {}),
16268
16519
  configErrorType: listConfigResult.errorType || '',
16269
16520
  configNotice: listConfigResult.reason || '',
16270
16521
  providers: Object.entries(providers).map(([name, p]) => {
@@ -16525,6 +16776,9 @@ function normalizeWorkflowDefinition(raw, idHint = '', source = 'custom') {
16525
16776
  tool: toolName,
16526
16777
  arguments: args,
16527
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 } : {}),
16528
16782
  continueOnError: item.continueOnError === true,
16529
16783
  write: item.write === true
16530
16784
  });
@@ -16809,6 +17063,47 @@ function validateWorkflowById(workflowId, input = {}) {
16809
17063
  };
16810
17064
  }
16811
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
+
16812
17107
  async function runWorkflowById(workflowId, input = {}, options = {}) {
16813
17108
  const definitionResult = getWorkflowDefinitionById(workflowId);
16814
17109
  if (definitionResult.error) {
@@ -17096,6 +17391,18 @@ function createMcpTools(options = {}) {
17096
17391
  handler: async () => getBuiltinClaudeProxyStatus()
17097
17392
  });
17098
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
+
17099
17406
  pushTool({
17100
17407
  name: 'codexmate.workflow.list',
17101
17408
  description: 'List available workflows (builtin + custom).',
@@ -17726,7 +18033,8 @@ function printMainHelp() {
17726
18033
  console.log(' codexmate auth <list|import|switch|delete|status> 认证管理');
17727
18034
  console.log(' codexmate add-model <模型> 添加模型');
17728
18035
  console.log(' codexmate delete-model <模型> 删除模型');
17729
- 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> 交接卡与共享记忆路由');
17730
18038
  console.log(' codexmate analytics export [--format csv|json] [--from YYYY-MM-DD] [--to YYYY-MM-DD] [--model <MODEL>] [--output <PATH|->] [-o <PATH|->] 导出 Usage 数据');
17731
18039
  console.log(' codexmate run [--host <HOST>] [--no-browser] 启动 Web 界面');
17732
18040
  console.log(' codexmate update [--check] 检查并快速更新工具');
@@ -17748,6 +18056,10 @@ function printMainHelp() {
17748
18056
  async function main() {
17749
18057
  const args = process.argv.slice(2);
17750
18058
  const command = args[0];
18059
+ if (command === 'thread') {
18060
+ await cmdThread(args.slice(1));
18061
+ return;
18062
+ }
17751
18063
  const isMcpCommand = command === 'mcp';
17752
18064
  const shouldGateInitialBootstrap = command === 'run' || isMcpCommand;
17753
18065
  const bootstrap = ensureManagedConfigBootstrap({
@@ -17862,6 +18174,10 @@ async function main() {
17862
18174
  }
17863
18175
 
17864
18176
  main().catch((err) => {
17865
- 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
+ }
17866
18182
  process.exit(1);
17867
18183
  });