codexmate 0.1.30 → 0.1.32
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +98 -7
- package/README.vi.md +98 -7
- package/README.zh.md +99 -7
- package/cli/agents-files.js +18 -4
- package/cli/config-bootstrap.js +25 -11
- package/cli/plugin-config.js +64 -0
- package/cli/prompt-history.js +17 -4
- package/cli/system-prompt-files.js +7 -2
- package/cli.js +396 -46
- package/lib/cli-config-engine.js +266 -0
- package/lib/cli-utils.js +2 -1
- package/lib/cli-webhook.js +1 -1
- package/lib/handoff-mcp.js +282 -0
- package/lib/http-access-control.js +335 -0
- package/lib/session-context-health.js +82 -0
- package/lib/session-context-records.js +153 -0
- package/lib/thread-handoff.js +130 -0
- package/lib/web-startup-auth.js +53 -0
- package/lib/workflow-engine.js +92 -21
- package/lib/workflow-runner.js +261 -0
- package/package.json +1 -1
- package/plugins/prompt-templates/computed.mjs +3 -3
- package/plugins/prompt-templates/invocation.mjs +73 -0
- package/plugins/prompt-templates/methods.mjs +48 -3
- package/plugins/prompt-templates/overview.mjs +2 -0
- package/web-ui/app.js +48 -2
- package/web-ui/index.html +1 -0
- package/web-ui/logic.context-health.mjs +144 -0
- package/web-ui/modules/access-token.mjs +33 -0
- package/web-ui/modules/api.mjs +2 -1
- package/web-ui/modules/app.computed.prompts.mjs +11 -0
- package/web-ui/modules/app.methods.agents.mjs +20 -3
- package/web-ui/modules/app.methods.index.mjs +6 -0
- package/web-ui/modules/app.methods.navigation.mjs +17 -3
- package/web-ui/modules/app.methods.prompts-editor.mjs +7 -0
- package/web-ui/modules/app.methods.providers.mjs +2 -2
- package/web-ui/modules/app.methods.runtime.mjs +3 -2
- package/web-ui/modules/app.methods.session-actions.mjs +3 -0
- package/web-ui/modules/app.methods.session-browser.mjs +6 -2
- package/web-ui/modules/app.methods.system-prompt.mjs +17 -2
- package/web-ui/modules/app.methods.workflows.mjs +41 -0
- package/web-ui/modules/context-health.methods.mjs +70 -0
- package/web-ui/modules/i18n/locales/en.mjs +70 -2
- package/web-ui/modules/i18n/locales/ja.mjs +70 -2
- package/web-ui/modules/i18n/locales/vi.mjs +70 -2
- package/web-ui/modules/i18n/locales/zh-tw.mjs +70 -2
- package/web-ui/modules/i18n/locales/zh.mjs +70 -2
- package/web-ui/modules/plugins.methods.mjs +2 -0
- package/web-ui/modules/prompt-ecosystem.methods.mjs +136 -0
- package/web-ui/modules/sessions-filters-url.mjs +3 -0
- package/web-ui/modules/skills.methods.mjs +6 -5
- package/web-ui/modules/thread-handoff.mjs +142 -0
- package/web-ui/partials/index/context-health.html +45 -0
- package/web-ui/partials/index/modal-prompt-invocation.html +17 -0
- package/web-ui/partials/index/panel-config-claude.html +2 -0
- package/web-ui/partials/index/panel-config-codex.html +2 -0
- package/web-ui/partials/index/panel-config-kilocode.html +3 -1
- package/web-ui/partials/index/panel-config-openclaw.html +2 -0
- package/web-ui/partials/index/panel-config-opencode.html +3 -1
- package/web-ui/partials/index/panel-config-pi.html +2 -0
- package/web-ui/partials/index/panel-dashboard.html +59 -0
- package/web-ui/partials/index/panel-plugins.html +37 -9
- package/web-ui/partials/index/panel-prompts.html +46 -18
- package/web-ui/partials/index/panel-sessions.html +35 -44
- package/web-ui/partials/index/thread-handoff.html +59 -0
- package/web-ui/res/web-ui-render.precompiled.js +1289 -177
- package/web-ui/styles/context-health.css +107 -0
- package/web-ui/styles/controls-forms.css +9 -0
- package/web-ui/styles/dashboard.css +51 -0
- package/web-ui/styles/modals-core.css +87 -0
- package/web-ui/styles/navigation-panels.css +1 -1
- package/web-ui/styles/plugins-panel.css +62 -0
- package/web-ui/styles/prompts-editor.css +34 -4
- package/web-ui/styles/responsive.css +19 -10
- package/web-ui/styles/sessions-preview.css +206 -111
- package/web-ui/styles/sub-tabs.css +181 -0
- package/web-ui/styles.css +2 -0
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,
|
|
@@ -124,6 +138,8 @@ const {
|
|
|
124
138
|
const {
|
|
125
139
|
createPromptHistoryController
|
|
126
140
|
} = require('./cli/prompt-history');
|
|
141
|
+
const { createPluginConfigController } = require('./cli/plugin-config');
|
|
142
|
+
const { createSessionContextHealthController } = require('./lib/session-context-health');
|
|
127
143
|
const {
|
|
128
144
|
createArchiveHelperController
|
|
129
145
|
} = require('./cli/archive-helpers');
|
|
@@ -829,8 +845,18 @@ function ensureConfigDir() {
|
|
|
829
845
|
}
|
|
830
846
|
|
|
831
847
|
function createConfigLoadError(type, message, detail) {
|
|
832
|
-
const
|
|
833
|
-
|
|
848
|
+
const errorType = type || 'read';
|
|
849
|
+
const code = errorType === 'parse'
|
|
850
|
+
? 'CONFIG_TOML_PARSE_ERROR'
|
|
851
|
+
: (errorType === 'missing' ? 'CONFIG_TOML_MISSING' : 'CONFIG_TOML_READ_ERROR');
|
|
852
|
+
const err = createConfigError({
|
|
853
|
+
code,
|
|
854
|
+
type: errorType,
|
|
855
|
+
path: CONFIG_FILE,
|
|
856
|
+
message: message || '读取 config.toml 失败',
|
|
857
|
+
detail: detail || message || ''
|
|
858
|
+
});
|
|
859
|
+
err.configErrorType = errorType;
|
|
834
860
|
err.configPublicReason = message || '读取 config.toml 失败';
|
|
835
861
|
err.configDetail = detail || message || '';
|
|
836
862
|
return err;
|
|
@@ -876,11 +902,7 @@ function readConfig() {
|
|
|
876
902
|
|
|
877
903
|
function writeConfig(content) {
|
|
878
904
|
assertToolConfigWriteAllowed('codex');
|
|
879
|
-
|
|
880
|
-
fs.writeFileSync(CONFIG_FILE, content, 'utf-8');
|
|
881
|
-
} catch (e) {
|
|
882
|
-
throw new Error(`写入配置失败: ${e.message}`);
|
|
883
|
-
}
|
|
905
|
+
return writeConfigAtomicWithBackup(CONFIG_FILE, content);
|
|
884
906
|
}
|
|
885
907
|
|
|
886
908
|
function readModels() {
|
|
@@ -2312,7 +2334,8 @@ function queryOpencodeSessionMessages(sessionId, options = {}) {
|
|
|
2312
2334
|
const id = typeof sessionId === 'string' ? sessionId.trim() : '';
|
|
2313
2335
|
if (!id) return null;
|
|
2314
2336
|
const maxMessages = resolveMaxMessagesValue(options.maxMessages, DEFAULT_SESSION_DETAIL_MESSAGES);
|
|
2315
|
-
const limit =
|
|
2337
|
+
const limit = options.contextHealth === true ? -1
|
|
2338
|
+
: (maxMessages === Infinity ? OPENCODE_DB_READ_LIMIT : Math.min(OPENCODE_DB_READ_LIMIT, Math.max(1, Math.floor(maxMessages))));
|
|
2316
2339
|
return withOpencodeDb((db) => {
|
|
2317
2340
|
const totalRow = db.prepare('select count(*) as count from message where session_id = ?').get(id) || {};
|
|
2318
2341
|
const totalMessages = Math.max(0, Math.floor(Number(totalRow.count) || 0));
|
|
@@ -2326,8 +2349,12 @@ function queryOpencodeSessionMessages(sessionId, options = {}) {
|
|
|
2326
2349
|
group by m.id
|
|
2327
2350
|
order by m.time_created asc
|
|
2328
2351
|
`).all(id, limit);
|
|
2329
|
-
const messages = rows.map(
|
|
2352
|
+
const messages = options.contextHealth === true ? rows.map((row) => ({
|
|
2353
|
+
role: parseJsonObjectSafe(row.message_data || '')?.role || 'assistant',
|
|
2354
|
+
content: String(row.parts || '').split('\n').map(parseJsonObjectSafe).filter(Boolean)
|
|
2355
|
+
})) : rows.map(normalizeOpencodeMessageRow).filter(Boolean);
|
|
2330
2356
|
const sessionRow = db.prepare('select id, directory, path, time_updated from session where id = ?').get(id) || null;
|
|
2357
|
+
if (options.contextHealth === true && !sessionRow) return null;
|
|
2331
2358
|
return {
|
|
2332
2359
|
sessionId: id,
|
|
2333
2360
|
cwd: sessionRow && (sessionRow.path || sessionRow.directory) ? (sessionRow.path || sessionRow.directory) : '',
|
|
@@ -2581,7 +2608,14 @@ function queryZedSessionMessages(sessionId, options = {}) {
|
|
|
2581
2608
|
return withZedThreadsDb((db) => {
|
|
2582
2609
|
const row = db.prepare('select data, data_type, folder_paths, updated_at from threads where id = ?').get(id) || null;
|
|
2583
2610
|
const doc = parseZedThreadDocument(row);
|
|
2611
|
+
if (options.contextHealth === true && !doc) return null;
|
|
2584
2612
|
const modelInfo = readZedThreadModelInfo(doc);
|
|
2613
|
+
if (options.contextHealth === true) return {
|
|
2614
|
+
sessionId: id, messages: Array.isArray(doc?.messages) ? doc.messages : [],
|
|
2615
|
+
cwd: doc ? readZedThreadCwd(row, doc) : '',
|
|
2616
|
+
instructions: doc?.system_prompt || doc?.instructions || '',
|
|
2617
|
+
totalMessages: Array.isArray(doc?.messages) ? doc.messages.length : 0, clipped: false
|
|
2618
|
+
};
|
|
2585
2619
|
const all = (doc && Array.isArray(doc.messages) ? doc.messages : [])
|
|
2586
2620
|
.map(entry => normalizeZedThreadMessage(entry, modelInfo))
|
|
2587
2621
|
.filter(Boolean);
|
|
@@ -2900,7 +2934,15 @@ async function fetchModelsFromBaseUrlCore(baseUrl, apiKey) {
|
|
|
2900
2934
|
}
|
|
2901
2935
|
|
|
2902
2936
|
async function fetchProviderModels(providerName, overrides = {}) {
|
|
2903
|
-
const
|
|
2937
|
+
const configResult = readConfigOrVirtualDefault();
|
|
2938
|
+
if (hasConfigLoadError(configResult)) {
|
|
2939
|
+
throw createConfigLoadError(
|
|
2940
|
+
configResult.errorType,
|
|
2941
|
+
configResult.reason,
|
|
2942
|
+
configResult.detail
|
|
2943
|
+
);
|
|
2944
|
+
}
|
|
2945
|
+
const { config } = configResult;
|
|
2904
2946
|
const targetProvider = providerName || config.model_provider || '';
|
|
2905
2947
|
if (!targetProvider) return { error: '未设置当前提供商' };
|
|
2906
2948
|
|
|
@@ -2928,6 +2970,10 @@ const {
|
|
|
2928
2970
|
CONFIG_DIR
|
|
2929
2971
|
});
|
|
2930
2972
|
|
|
2973
|
+
const { getPluginConfig, applyPluginConfig } = createPluginConfigController({
|
|
2974
|
+
fs, path, CONFIG_DIR, backupPromptBeforeWrite: historyBackup
|
|
2975
|
+
});
|
|
2976
|
+
|
|
2931
2977
|
const {
|
|
2932
2978
|
resolveAgentsFilePath,
|
|
2933
2979
|
validateAgentsBaseDir,
|
|
@@ -3129,6 +3175,17 @@ async function buildAllProvidersHealthReport(params = {}) {
|
|
|
3129
3175
|
});
|
|
3130
3176
|
}
|
|
3131
3177
|
|
|
3178
|
+
function buildConfigLoadErrorPayload(result) {
|
|
3179
|
+
const errorType = result && result.errorType === 'read' ? 'read' : 'parse';
|
|
3180
|
+
return {
|
|
3181
|
+
code: errorType === 'parse' ? 'CONFIG_TOML_PARSE_ERROR' : 'CONFIG_TOML_READ_ERROR',
|
|
3182
|
+
type: errorType,
|
|
3183
|
+
path: CONFIG_FILE,
|
|
3184
|
+
message: result && result.reason ? result.reason : (errorType === 'parse' ? 'config.toml 解析失败' : '读取 config.toml 失败'),
|
|
3185
|
+
detail: result && result.detail ? result.detail : ''
|
|
3186
|
+
};
|
|
3187
|
+
}
|
|
3188
|
+
|
|
3132
3189
|
function hasConfigLoadError(result) {
|
|
3133
3190
|
return !!(result
|
|
3134
3191
|
&& result.isVirtual
|
|
@@ -3326,6 +3383,8 @@ function applyConfigTemplate(params = {}) {
|
|
|
3326
3383
|
} catch (e) {
|
|
3327
3384
|
return { error: `模板 TOML 解析失败: ${e.message}` };
|
|
3328
3385
|
}
|
|
3386
|
+
const providerNameError = validateProviderNamesInParsedConfig(parsed);
|
|
3387
|
+
if (providerNameError) return providerNameError;
|
|
3329
3388
|
|
|
3330
3389
|
if (
|
|
3331
3390
|
Object.prototype.hasOwnProperty.call(parsed, 'model_context_window')
|
|
@@ -3390,6 +3449,8 @@ function buildConfigTemplateDiff(params = {}) {
|
|
|
3390
3449
|
} catch (e) {
|
|
3391
3450
|
return { error: `模板 TOML 解析失败: ${e.message}` };
|
|
3392
3451
|
}
|
|
3452
|
+
const providerNameError = validateProviderNamesInParsedConfig(parsed);
|
|
3453
|
+
if (providerNameError) return providerNameError;
|
|
3393
3454
|
|
|
3394
3455
|
if (
|
|
3395
3456
|
Object.prototype.hasOwnProperty.call(parsed, 'model_context_window')
|
|
@@ -3523,7 +3584,7 @@ function addProviderToConfig(params = {}) {
|
|
|
3523
3584
|
if (!url) return { error: 'URL 不能为空' };
|
|
3524
3585
|
if (!model) return { error: '模型名称不能为空' };
|
|
3525
3586
|
if (!isValidProviderName(name)) {
|
|
3526
|
-
return { error: '
|
|
3587
|
+
return { error: '名称仅支持字母/数字/_-' };
|
|
3527
3588
|
}
|
|
3528
3589
|
if (!isValidHttpUrl(normalizedUrl)) {
|
|
3529
3590
|
return { error: 'URL 仅支持 http/https' };
|
|
@@ -3650,6 +3711,7 @@ function updateProviderInConfig(params = {}) {
|
|
|
3650
3711
|
cmdUpdate(name, url || undefined, key, true, { allowManaged, useTransform, ...(hasOpenaiBridgeMaxRetries ? { openaiBridgeMaxRetries } : {}) });
|
|
3651
3712
|
return { success: true };
|
|
3652
3713
|
} catch (e) {
|
|
3714
|
+
if (e && typeof e.code === 'string' && e.code.startsWith('CONFIG_')) throw e;
|
|
3653
3715
|
return { error: e.message || '更新失败' };
|
|
3654
3716
|
}
|
|
3655
3717
|
}
|
|
@@ -4199,6 +4261,7 @@ function deleteProviderFromConfig(params = {}) {
|
|
|
4199
4261
|
try {
|
|
4200
4262
|
config = readConfig();
|
|
4201
4263
|
} catch (e) {
|
|
4264
|
+
if (e && typeof e.code === 'string' && e.code.startsWith('CONFIG_')) throw e;
|
|
4202
4265
|
return { error: `读取配置失败: ${e.message}` };
|
|
4203
4266
|
}
|
|
4204
4267
|
|
|
@@ -9763,6 +9826,10 @@ async function extractMessagesFromFile(filePath, source, options = {}) {
|
|
|
9763
9826
|
return state;
|
|
9764
9827
|
}
|
|
9765
9828
|
|
|
9829
|
+
const { readSessionContextHealth, readSessionContextNode } = createSessionContextHealthController({
|
|
9830
|
+
fs, normalizeSessionSourceName, resolveSessionFilePath, queryOpencodeSessionMessages, queryZedSessionMessages
|
|
9831
|
+
});
|
|
9832
|
+
|
|
9766
9833
|
async function readSessionDetail(params = {}) {
|
|
9767
9834
|
const source = normalizeSessionSourceName(params.source, '');
|
|
9768
9835
|
if (!source) {
|
|
@@ -10462,7 +10529,11 @@ async function importDerivedSessionToNative(params = {}) {
|
|
|
10462
10529
|
}
|
|
10463
10530
|
|
|
10464
10531
|
function buildExportPayload(includeKeys) {
|
|
10465
|
-
const
|
|
10532
|
+
const configResult = readConfigOrVirtualDefault();
|
|
10533
|
+
if (hasConfigLoadError(configResult)) {
|
|
10534
|
+
return { error: buildConfigLoadErrorPayload(configResult) };
|
|
10535
|
+
}
|
|
10536
|
+
const { config } = configResult;
|
|
10466
10537
|
const providers = config.model_providers || {};
|
|
10467
10538
|
const providerData = {};
|
|
10468
10539
|
for (const [name, provider] of Object.entries(providers)) {
|
|
@@ -10510,7 +10581,19 @@ function buildProviderSharePayload(params = {}) {
|
|
|
10510
10581
|
return { error: '缺少提供商名称' };
|
|
10511
10582
|
}
|
|
10512
10583
|
|
|
10513
|
-
const
|
|
10584
|
+
const configResult = readConfigOrVirtualDefault();
|
|
10585
|
+
if (configResult.errorType === 'parse' || configResult.errorType === 'read') {
|
|
10586
|
+
return {
|
|
10587
|
+
error: {
|
|
10588
|
+
code: configResult.errorType === 'parse' ? 'CONFIG_TOML_PARSE_ERROR' : 'CONFIG_TOML_READ_ERROR',
|
|
10589
|
+
type: configResult.errorType,
|
|
10590
|
+
path: configResult.path || '',
|
|
10591
|
+
message: configResult.reason || '读取 config.toml 失败',
|
|
10592
|
+
detail: configResult.detail || ''
|
|
10593
|
+
}
|
|
10594
|
+
};
|
|
10595
|
+
}
|
|
10596
|
+
const { config } = configResult;
|
|
10514
10597
|
const providers = config.model_providers || {};
|
|
10515
10598
|
const provider = providers[name];
|
|
10516
10599
|
if (!provider || typeof provider !== 'object') {
|
|
@@ -10570,19 +10653,21 @@ function normalizeImportPayload(payload) {
|
|
|
10570
10653
|
if (Array.isArray(rawProviders)) {
|
|
10571
10654
|
for (const item of rawProviders) {
|
|
10572
10655
|
if (!item || typeof item !== 'object') continue;
|
|
10573
|
-
const
|
|
10656
|
+
const rawName = item.name || item.provider || '';
|
|
10657
|
+
const name = typeof rawName === 'string' ? rawName.trim() : '';
|
|
10574
10658
|
const baseUrl = item.baseUrl || item.base_url || item.url || '';
|
|
10575
10659
|
const apiKey = item.apiKey ?? item.key ?? item.preferred_auth_method ?? null;
|
|
10576
|
-
if (name && baseUrl
|
|
10660
|
+
if (name && baseUrl) {
|
|
10577
10661
|
providers[name] = { baseUrl, apiKey };
|
|
10578
10662
|
}
|
|
10579
10663
|
}
|
|
10580
10664
|
} else if (typeof rawProviders === 'object') {
|
|
10581
|
-
for (const [
|
|
10665
|
+
for (const [rawName, item] of Object.entries(rawProviders)) {
|
|
10582
10666
|
if (!item || typeof item !== 'object') continue;
|
|
10667
|
+
const name = typeof rawName === 'string' ? rawName.trim() : '';
|
|
10583
10668
|
const baseUrl = item.baseUrl || item.base_url || item.url || '';
|
|
10584
10669
|
const apiKey = item.apiKey ?? item.key ?? item.preferred_auth_method ?? null;
|
|
10585
|
-
if (name && baseUrl
|
|
10670
|
+
if (name && baseUrl) {
|
|
10586
10671
|
providers[name] = { baseUrl, apiKey };
|
|
10587
10672
|
}
|
|
10588
10673
|
}
|
|
@@ -10592,12 +10677,17 @@ function normalizeImportPayload(payload) {
|
|
|
10592
10677
|
return { error: 'Invalid import payload' };
|
|
10593
10678
|
}
|
|
10594
10679
|
|
|
10680
|
+
const currentProvider = typeof payload.currentProvider === 'string' ? payload.currentProvider.trim() : '';
|
|
10681
|
+
const currentModels = payload.currentModels && typeof payload.currentModels === 'object'
|
|
10682
|
+
? payload.currentModels
|
|
10683
|
+
: {};
|
|
10684
|
+
|
|
10595
10685
|
return {
|
|
10596
10686
|
providers,
|
|
10597
10687
|
models: Array.isArray(payload.models) ? payload.models : [],
|
|
10598
|
-
currentProvider
|
|
10688
|
+
currentProvider,
|
|
10599
10689
|
currentModel: typeof payload.currentModel === 'string' ? payload.currentModel : '',
|
|
10600
|
-
currentModels
|
|
10690
|
+
currentModels
|
|
10601
10691
|
};
|
|
10602
10692
|
}
|
|
10603
10693
|
|
|
@@ -10611,11 +10701,29 @@ function importConfigData(payload, options = {}) {
|
|
|
10611
10701
|
const applyCurrent = !!options.applyCurrent;
|
|
10612
10702
|
const applyCurrentModels = !!options.applyCurrentModels;
|
|
10613
10703
|
|
|
10614
|
-
const
|
|
10704
|
+
const existingConfigResult = readConfigOrVirtualDefault();
|
|
10705
|
+
if (hasConfigLoadError(existingConfigResult)) {
|
|
10706
|
+
return { error: buildConfigLoadErrorPayload(existingConfigResult) };
|
|
10707
|
+
}
|
|
10708
|
+
const existingConfig = existingConfigResult.config;
|
|
10615
10709
|
const existingProviders = existingConfig.model_providers || {};
|
|
10616
10710
|
let addedProviders = 0;
|
|
10617
10711
|
let updatedProviders = 0;
|
|
10618
10712
|
|
|
10713
|
+
for (const name of Object.keys(normalized.providers)) {
|
|
10714
|
+
if (!existingProviders[name] && !isValidProviderName(name)) {
|
|
10715
|
+
return { error: `provider 名称非法: ${name}(名称仅支持字母/数字/_-)` };
|
|
10716
|
+
}
|
|
10717
|
+
}
|
|
10718
|
+
if (normalized.currentProvider && !existingProviders[normalized.currentProvider] && !isValidProviderName(normalized.currentProvider)) {
|
|
10719
|
+
return { error: `当前 provider 名称非法: ${normalized.currentProvider}(名称仅支持字母/数字/_-)` };
|
|
10720
|
+
}
|
|
10721
|
+
for (const name of Object.keys(normalized.currentModels)) {
|
|
10722
|
+
if (!existingProviders[name] && !isValidProviderName(name)) {
|
|
10723
|
+
return { error: `provider 名称非法: ${name}(名称仅支持字母/数字/_-)` };
|
|
10724
|
+
}
|
|
10725
|
+
}
|
|
10726
|
+
|
|
10619
10727
|
for (const [name, provider] of Object.entries(normalized.providers)) {
|
|
10620
10728
|
if (isBuiltinManagedProvider(name)) {
|
|
10621
10729
|
continue;
|
|
@@ -10741,7 +10849,11 @@ function resolveSpeedTestTarget(params) {
|
|
|
10741
10849
|
}
|
|
10742
10850
|
|
|
10743
10851
|
if (params.name) {
|
|
10744
|
-
const
|
|
10852
|
+
const configResult = readConfigOrVirtualDefault();
|
|
10853
|
+
if (hasConfigLoadError(configResult)) {
|
|
10854
|
+
return { error: buildConfigLoadErrorPayload(configResult) };
|
|
10855
|
+
}
|
|
10856
|
+
const { config } = configResult;
|
|
10745
10857
|
const providers = config.model_providers || {};
|
|
10746
10858
|
const provider = providers[params.name];
|
|
10747
10859
|
if (!provider) {
|
|
@@ -10873,7 +10985,15 @@ async function cmdSetup() {
|
|
|
10873
10985
|
let isCustomProvider = false;
|
|
10874
10986
|
|
|
10875
10987
|
try {
|
|
10876
|
-
const
|
|
10988
|
+
const setupConfigResult = readConfigOrVirtualDefault();
|
|
10989
|
+
if (hasConfigLoadError(setupConfigResult)) {
|
|
10990
|
+
throw createConfigLoadError(
|
|
10991
|
+
setupConfigResult.errorType,
|
|
10992
|
+
setupConfigResult.reason,
|
|
10993
|
+
setupConfigResult.detail
|
|
10994
|
+
);
|
|
10995
|
+
}
|
|
10996
|
+
const { config } = setupConfigResult;
|
|
10877
10997
|
const providers = config.model_providers || {};
|
|
10878
10998
|
const providerNames = Object.keys(providers);
|
|
10879
10999
|
const currentProvider = typeof config.model_provider === 'string' ? config.model_provider.trim() : '';
|
|
@@ -10933,7 +11053,7 @@ async function cmdSetup() {
|
|
|
10933
11053
|
break;
|
|
10934
11054
|
}
|
|
10935
11055
|
|
|
10936
|
-
console.log('提示:
|
|
11056
|
+
console.log('提示: 名称仅支持字母/数字/_-');
|
|
10937
11057
|
}
|
|
10938
11058
|
|
|
10939
11059
|
if (isCustomProvider && !providerName) {
|
|
@@ -10944,7 +11064,7 @@ async function cmdSetup() {
|
|
|
10944
11064
|
continue;
|
|
10945
11065
|
}
|
|
10946
11066
|
if (!isValidProviderName(nameInput)) {
|
|
10947
|
-
console.log('提示:
|
|
11067
|
+
console.log('提示: 名称仅支持字母/数字/_-');
|
|
10948
11068
|
continue;
|
|
10949
11069
|
}
|
|
10950
11070
|
providerName = nameInput;
|
|
@@ -11068,7 +11188,11 @@ async function cmdSetup() {
|
|
|
11068
11188
|
console.log(' 模型:', modelName);
|
|
11069
11189
|
console.log();
|
|
11070
11190
|
} catch (e) {
|
|
11071
|
-
|
|
11191
|
+
if (e && typeof e.code === 'string' && e.code.startsWith('CONFIG_')) {
|
|
11192
|
+
console.error(formatConfigError(e));
|
|
11193
|
+
} else {
|
|
11194
|
+
console.error('错误:', e.message || e);
|
|
11195
|
+
}
|
|
11072
11196
|
process.exitCode = 1;
|
|
11073
11197
|
} finally {
|
|
11074
11198
|
rl.close();
|
|
@@ -11383,8 +11507,8 @@ function cmdAdd(name, baseUrl, apiKey, silent = false, options = {}) {
|
|
|
11383
11507
|
throw new Error('名称和URL必填');
|
|
11384
11508
|
}
|
|
11385
11509
|
if (!isValidProviderName(providerName)) {
|
|
11386
|
-
if (!silent) console.error('错误:
|
|
11387
|
-
throw new Error('
|
|
11510
|
+
if (!silent) console.error('错误: 名称仅支持字母/数字/_-');
|
|
11511
|
+
throw new Error('名称仅支持字母/数字/_-');
|
|
11388
11512
|
}
|
|
11389
11513
|
if (isReservedProviderNameForCreation(providerName)) {
|
|
11390
11514
|
if (!silent) console.error('错误: 提供商名称不可用');
|
|
@@ -13811,7 +13935,31 @@ function readServerToken() {
|
|
|
13811
13935
|
return raw;
|
|
13812
13936
|
}
|
|
13813
13937
|
|
|
13938
|
+
function assertWebAccessControlConfigured(host) {
|
|
13939
|
+
const token = readServerToken();
|
|
13940
|
+
assertExternalTokenConfigured(host, token);
|
|
13941
|
+
try {
|
|
13942
|
+
parseAllowedIps(process.env.CODEXMATE_ALLOWED_IPS || '');
|
|
13943
|
+
} catch (error) {
|
|
13944
|
+
throw new Error(`CODEXMATE_ALLOWED_IPS 配置无效: ${error.message}`);
|
|
13945
|
+
}
|
|
13946
|
+
return token;
|
|
13947
|
+
}
|
|
13948
|
+
|
|
13949
|
+
function createWebAccessControlMiddleware(host) {
|
|
13950
|
+
const token = assertWebAccessControlConfigured(host);
|
|
13951
|
+
return createHttpAccessControlMiddleware({
|
|
13952
|
+
token,
|
|
13953
|
+
bypassLoopback: true,
|
|
13954
|
+
allowedIps: process.env.CODEXMATE_ALLOWED_IPS || '',
|
|
13955
|
+
requiresToken(req) {
|
|
13956
|
+
const requestPath = (req && req.url ? req.url : '/').split('?')[0];
|
|
13957
|
+
return requestPath.startsWith('/bridge/');
|
|
13958
|
+
}
|
|
13959
|
+
});
|
|
13960
|
+
}
|
|
13814
13961
|
function assertRequestAuthorized(req, res) {
|
|
13962
|
+
if (req.codexmateStartupAuthenticated === true) return { ok: true, mode: 'startup-token' };
|
|
13815
13963
|
const remoteAddr = req && req.socket ? req.socket.remoteAddress : '';
|
|
13816
13964
|
if (isLoopbackRemoteAddress(remoteAddr)) {
|
|
13817
13965
|
return { ok: true, mode: 'loopback' };
|
|
@@ -14049,6 +14197,9 @@ const PUBLIC_WEB_UI_STATIC_ASSETS = new Set([
|
|
|
14049
14197
|
|
|
14050
14198
|
function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser }) {
|
|
14051
14199
|
const connections = new Set();
|
|
14200
|
+
const startupAuth = createStartupAuth(readServerToken());
|
|
14201
|
+
const httpToken = startupAuth.token;
|
|
14202
|
+
const accessControlMiddleware = createWebAccessControlMiddleware(host);
|
|
14052
14203
|
const probeWebUiReadiness = (callback) => {
|
|
14053
14204
|
const payload = JSON.stringify({ action: 'health-check', params: {} });
|
|
14054
14205
|
const requestOptions = {
|
|
@@ -14058,7 +14209,8 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
|
|
|
14058
14209
|
method: 'POST',
|
|
14059
14210
|
headers: {
|
|
14060
14211
|
'Content-Type': 'application/json; charset=utf-8',
|
|
14061
|
-
'Content-Length': Buffer.byteLength(payload, 'utf-8')
|
|
14212
|
+
'Content-Length': Buffer.byteLength(payload, 'utf-8'),
|
|
14213
|
+
...(httpToken ? { Authorization: `Bearer ${httpToken}` } : {})
|
|
14062
14214
|
}
|
|
14063
14215
|
};
|
|
14064
14216
|
let settled = false;
|
|
@@ -14087,7 +14239,8 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
|
|
|
14087
14239
|
hostname: openHost,
|
|
14088
14240
|
port,
|
|
14089
14241
|
path: '/web-ui/app.js',
|
|
14090
|
-
method: 'GET'
|
|
14242
|
+
method: 'GET',
|
|
14243
|
+
headers: httpToken ? { Authorization: `Bearer ${httpToken}` } : {}
|
|
14091
14244
|
};
|
|
14092
14245
|
let settled = false;
|
|
14093
14246
|
const finish = (ready) => {
|
|
@@ -14208,7 +14361,7 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
|
|
|
14208
14361
|
}
|
|
14209
14362
|
}, RATE_LIMIT_WINDOW_MS).unref();
|
|
14210
14363
|
|
|
14211
|
-
const
|
|
14364
|
+
const handleRequest = (req, res) => {
|
|
14212
14365
|
const securityHeaders = {
|
|
14213
14366
|
'X-Content-Type-Options': 'nosniff',
|
|
14214
14367
|
'X-Frame-Options': 'DENY',
|
|
@@ -14364,6 +14517,17 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
|
|
|
14364
14517
|
modelContextWindow,
|
|
14365
14518
|
modelAutoCompactTokenLimit,
|
|
14366
14519
|
configReady: !statusConfigResult.isVirtual,
|
|
14520
|
+
...(hasConfigLoadError(statusConfigResult)
|
|
14521
|
+
? {
|
|
14522
|
+
error: {
|
|
14523
|
+
code: statusConfigResult.errorType === 'parse' ? 'CONFIG_TOML_PARSE_ERROR' : 'CONFIG_TOML_READ_ERROR',
|
|
14524
|
+
type: statusConfigResult.errorType,
|
|
14525
|
+
path: statusConfigResult.path || '',
|
|
14526
|
+
message: statusConfigResult.reason || '读取 config.toml 失败',
|
|
14527
|
+
detail: statusConfigResult.detail || ''
|
|
14528
|
+
}
|
|
14529
|
+
}
|
|
14530
|
+
: {}),
|
|
14367
14531
|
configErrorType: statusConfigResult.errorType || '',
|
|
14368
14532
|
configNotice: statusConfigResult.reason || '',
|
|
14369
14533
|
initNotice: consumeInitNotice(),
|
|
@@ -14629,6 +14793,12 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
|
|
|
14629
14793
|
case 'preview-system-prompt-diff':
|
|
14630
14794
|
result = buildSystemPromptDiff(params || {});
|
|
14631
14795
|
break;
|
|
14796
|
+
case 'get-plugin-config':
|
|
14797
|
+
result = getPluginConfig();
|
|
14798
|
+
break;
|
|
14799
|
+
case 'apply-plugin-config':
|
|
14800
|
+
result = applyPluginConfig(params || {});
|
|
14801
|
+
break;
|
|
14632
14802
|
case 'list-prompt-history':
|
|
14633
14803
|
result = listPromptHistory((params && params.bucket) || '');
|
|
14634
14804
|
break;
|
|
@@ -14714,11 +14884,13 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
|
|
|
14714
14884
|
case 'export-provider':
|
|
14715
14885
|
result = buildProviderSharePayload(params || {});
|
|
14716
14886
|
break;
|
|
14717
|
-
case 'export-config':
|
|
14718
|
-
|
|
14719
|
-
|
|
14720
|
-
|
|
14887
|
+
case 'export-config': {
|
|
14888
|
+
const exportPayload = buildExportPayload(!!params.includeKeys);
|
|
14889
|
+
result = exportPayload && exportPayload.error
|
|
14890
|
+
? exportPayload
|
|
14891
|
+
: { data: exportPayload };
|
|
14721
14892
|
break;
|
|
14893
|
+
}
|
|
14722
14894
|
case 'import-config':
|
|
14723
14895
|
result = importConfigData(params.payload, params.options || {});
|
|
14724
14896
|
break;
|
|
@@ -14871,6 +15043,18 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
|
|
|
14871
15043
|
case 'session-message-counts':
|
|
14872
15044
|
result = await readSessionMessageCounts(params || {});
|
|
14873
15045
|
break;
|
|
15046
|
+
case 'thread-handoff-list':
|
|
15047
|
+
case 'thread-handoff-create':
|
|
15048
|
+
case 'thread-handoff-fallback':
|
|
15049
|
+
case 'thread-handoff-ack':
|
|
15050
|
+
result = await handleThreadAction(action, params || {});
|
|
15051
|
+
break;
|
|
15052
|
+
case 'session-context-health':
|
|
15053
|
+
result = await readSessionContextHealth(params || {});
|
|
15054
|
+
break;
|
|
15055
|
+
case 'session-context-node':
|
|
15056
|
+
result = await readSessionContextNode(params || {});
|
|
15057
|
+
break;
|
|
14874
15058
|
case 'session-detail':
|
|
14875
15059
|
result = await readSessionDetail(params);
|
|
14876
15060
|
break;
|
|
@@ -14968,6 +15152,24 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
|
|
|
14968
15152
|
case 'claude-local-bridge-sync-providers':
|
|
14969
15153
|
result = syncClaudeBridgeProviders(params || {});
|
|
14970
15154
|
break;
|
|
15155
|
+
case 'workflow-submit':
|
|
15156
|
+
result = submitUnattendedWorkflow(params.id, params.input, params);
|
|
15157
|
+
break;
|
|
15158
|
+
case 'workflow-active-runs':
|
|
15159
|
+
result = { runs: getUnattendedWorkflowRunner().list() };
|
|
15160
|
+
break;
|
|
15161
|
+
case 'workflow-run-detail':
|
|
15162
|
+
result = getUnattendedWorkflowRunner().get(params.runId) || { error: 'run not found' };
|
|
15163
|
+
break;
|
|
15164
|
+
case 'workflow-resume':
|
|
15165
|
+
result = getUnattendedWorkflowRunner().resume(params.runId, {
|
|
15166
|
+
...(params.input ? { input: params.input } : {}),
|
|
15167
|
+
...(params.allowWrite === true ? { allowWrite: true } : {})
|
|
15168
|
+
});
|
|
15169
|
+
break;
|
|
15170
|
+
case 'workflow-cancel':
|
|
15171
|
+
result = getUnattendedWorkflowRunner().cancel(params.runId);
|
|
15172
|
+
break;
|
|
14971
15173
|
case 'workflow-list':
|
|
14972
15174
|
result = listWorkflowDefinitions();
|
|
14973
15175
|
break;
|
|
@@ -15034,7 +15236,21 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
|
|
|
15034
15236
|
if (leaveToolConfigWriteGuard) leaveToolConfigWriteGuard();
|
|
15035
15237
|
} catch (e) {
|
|
15036
15238
|
if (leaveToolConfigWriteGuard) leaveToolConfigWriteGuard();
|
|
15037
|
-
const
|
|
15239
|
+
const errorPayload = e && typeof e.code === 'string' && e.code.startsWith('CONFIG_')
|
|
15240
|
+
? {
|
|
15241
|
+
error: {
|
|
15242
|
+
code: e.code,
|
|
15243
|
+
type: e.type || 'config',
|
|
15244
|
+
path: e.path || '',
|
|
15245
|
+
message: e.publicReason || e.message || '配置操作失败',
|
|
15246
|
+
detail: e.detail || e.message || '配置操作失败',
|
|
15247
|
+
...(e.backupPath ? { backupPath: e.backupPath } : {}),
|
|
15248
|
+
...(typeof e.rolledBack === 'boolean' ? { rolledBack: e.rolledBack } : {}),
|
|
15249
|
+
...(e.rollbackFailed ? { rollbackFailed: true } : {})
|
|
15250
|
+
}
|
|
15251
|
+
}
|
|
15252
|
+
: { error: e.message };
|
|
15253
|
+
const errorBody = JSON.stringify(errorPayload, null, 2);
|
|
15038
15254
|
res.writeHead(500, {
|
|
15039
15255
|
'Content-Type': 'application/json; charset=utf-8',
|
|
15040
15256
|
'Content-Length': Buffer.byteLength(errorBody, 'utf-8')
|
|
@@ -15191,6 +15407,12 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
|
|
|
15191
15407
|
res.end('Not Found');
|
|
15192
15408
|
}
|
|
15193
15409
|
}
|
|
15410
|
+
};
|
|
15411
|
+
const server = http.createServer((req, res) => {
|
|
15412
|
+
accessControlMiddleware(req, res, () => startupAuth.middleware(req, res, () => {
|
|
15413
|
+
req.codexmateStartupAuthenticated = true;
|
|
15414
|
+
handleRequest(req, res);
|
|
15415
|
+
}));
|
|
15194
15416
|
});
|
|
15195
15417
|
|
|
15196
15418
|
server.on('connection', (socket) => {
|
|
@@ -15223,8 +15445,9 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
|
|
|
15223
15445
|
const openHost = host === '::'
|
|
15224
15446
|
? '::1'
|
|
15225
15447
|
: (host === '0.0.0.0' ? DEFAULT_WEB_OPEN_HOST : host);
|
|
15226
|
-
const openUrl = `http://${formatHostForUrl(openHost)}:${port}`;
|
|
15448
|
+
const openUrl = `http://${formatHostForUrl(openHost)}:${port}/?token=${encodeURIComponent(httpToken)}`;
|
|
15227
15449
|
server.listen(port, host, () => {
|
|
15450
|
+
getUnattendedWorkflowRunner().recover();
|
|
15228
15451
|
console.log('\n✓ Web UI 已启动');
|
|
15229
15452
|
const willOpenBrowser = !!openBrowser && !process.env.CODEXMATE_NO_BROWSER;
|
|
15230
15453
|
console.log(` ${willOpenBrowser ? '已打开' : '待访问'}: ${openUrl}`);
|
|
@@ -15233,13 +15456,11 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
|
|
|
15233
15456
|
}
|
|
15234
15457
|
console.log(' 退出: Ctrl+C\n');
|
|
15235
15458
|
if (isAnyAddressHost(host)) {
|
|
15236
|
-
|
|
15237
|
-
|
|
15238
|
-
|
|
15239
|
-
|
|
15240
|
-
console.warn(
|
|
15241
|
-
console.warn(' 如需局域网访问,请先设置 CODEXMATE_HTTP_TOKEN。');
|
|
15242
|
-
console.warn(' 如需仅限本机访问,请改用 --host 127.0.0.1。');
|
|
15459
|
+
console.warn('! 安全提示: 当前监听所有网卡,局域网访问需要访问令牌。');
|
|
15460
|
+
console.warn(' 远程 /bridge/ 请求需携带 Authorization: Bearer <访问令牌>。');
|
|
15461
|
+
const allowedIps = (process.env.CODEXMATE_ALLOWED_IPS || '').trim();
|
|
15462
|
+
if (allowedIps) {
|
|
15463
|
+
console.warn(` 已启用的来源 IP 白名单: ${allowedIps}`);
|
|
15243
15464
|
}
|
|
15244
15465
|
}
|
|
15245
15466
|
|
|
@@ -15350,6 +15571,16 @@ async function cmdStart(options = {}) {
|
|
|
15350
15571
|
let port = resolveWebPort();
|
|
15351
15572
|
const explicitPort = isWebPortExplicit();
|
|
15352
15573
|
const host = resolveWebHost(options);
|
|
15574
|
+
try {
|
|
15575
|
+
assertWebAccessControlConfigured(host);
|
|
15576
|
+
} catch (error) {
|
|
15577
|
+
const message = error && error.message ? error.message : String(error);
|
|
15578
|
+
console.error(`! 启动失败: ${message}`);
|
|
15579
|
+
if (message.includes('CODEXMATE_HTTP_TOKEN')) {
|
|
15580
|
+
console.error(' 对外监听必须设置 CODEXMATE_HTTP_TOKEN;仅本机访问请改用 --host 127.0.0.1。');
|
|
15581
|
+
}
|
|
15582
|
+
process.exit(1);
|
|
15583
|
+
}
|
|
15353
15584
|
releaseRunPortIfNeeded(port, host);
|
|
15354
15585
|
const selectedPort = await resolveAvailableWebPort(port, host, { explicitPort });
|
|
15355
15586
|
if (selectedPort.error) {
|
|
@@ -15587,7 +15818,7 @@ function parseWorkflowInputArg(rawInput) {
|
|
|
15587
15818
|
}
|
|
15588
15819
|
|
|
15589
15820
|
function printWorkflowHelp() {
|
|
15590
|
-
console.log('\n用法: codexmate workflow <list|get|validate|run|runs> [参数]');
|
|
15821
|
+
console.log('\n用法: codexmate workflow <list|get|validate|run|runs|submit|active-runs|detail|resume|cancel> [参数]');
|
|
15591
15822
|
console.log(' codexmate workflow list');
|
|
15592
15823
|
console.log(' codexmate workflow get diagnose-config');
|
|
15593
15824
|
console.log(' codexmate workflow validate safe-provider-switch --input \'{"provider":"e2e"}\'');
|
|
@@ -15656,6 +15887,28 @@ function parseWorkflowCliOptions(args = []) {
|
|
|
15656
15887
|
return { options, rest };
|
|
15657
15888
|
}
|
|
15658
15889
|
|
|
15890
|
+
async function callWorkflowService(action, params = {}) {
|
|
15891
|
+
const actions = { submit: 'workflow-submit', 'active-runs': 'workflow-active-runs', detail: 'workflow-run-detail', resume: 'workflow-resume', cancel: 'workflow-cancel' };
|
|
15892
|
+
const port = parseInt(process.env.CODEXMATE_PORT, 10) || DEFAULT_WEB_PORT;
|
|
15893
|
+
const token = readServerToken();
|
|
15894
|
+
const body = JSON.stringify({ action: actions[action], params });
|
|
15895
|
+
return new Promise((resolve, reject) => {
|
|
15896
|
+
const req = http.request({ hostname: '127.0.0.1', port, path: '/api', method: 'POST', headers: {
|
|
15897
|
+
'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body),
|
|
15898
|
+
...(token ? { Authorization: `Bearer ${token}` } : {})
|
|
15899
|
+
} }, res => {
|
|
15900
|
+
let text = '';
|
|
15901
|
+
res.on('data', chunk => { text += chunk; });
|
|
15902
|
+
res.on('end', () => {
|
|
15903
|
+
try { resolve(JSON.parse(text)); } catch (error) { reject(error); }
|
|
15904
|
+
});
|
|
15905
|
+
});
|
|
15906
|
+
req.on('error', reject);
|
|
15907
|
+
req.setTimeout(10000, () => req.destroy(new Error('workflow service request timed out')));
|
|
15908
|
+
req.end(body);
|
|
15909
|
+
});
|
|
15910
|
+
}
|
|
15911
|
+
|
|
15659
15912
|
async function cmdWorkflow(args = []) {
|
|
15660
15913
|
const argv = Array.isArray(args) ? args : [];
|
|
15661
15914
|
if (argv.length === 0 || argv.includes('--help') || argv.includes('-h')) {
|
|
@@ -15666,6 +15919,16 @@ async function cmdWorkflow(args = []) {
|
|
|
15666
15919
|
const parsed = parseWorkflowCliOptions(argv.slice(1));
|
|
15667
15920
|
const options = parsed.options;
|
|
15668
15921
|
const rest = parsed.rest;
|
|
15922
|
+
if (['submit', 'active-runs', 'detail', 'resume', 'cancel'].includes(subcommand)) {
|
|
15923
|
+
const result = await callWorkflowService(subcommand, {
|
|
15924
|
+
id: rest[0], runId: rest[0],
|
|
15925
|
+
...(options.inputRaw ? { input: parseWorkflowInputArg(options.inputRaw) } : {}),
|
|
15926
|
+
allowWrite: options.allowWrite === true, dryRun: options.dryRun === true
|
|
15927
|
+
});
|
|
15928
|
+
console.log(JSON.stringify(result, null, 2));
|
|
15929
|
+
if (result.error) throw new Error(result.error);
|
|
15930
|
+
return;
|
|
15931
|
+
}
|
|
15669
15932
|
|
|
15670
15933
|
if (subcommand === 'list') {
|
|
15671
15934
|
const result = listWorkflowDefinitions();
|
|
@@ -16252,6 +16515,17 @@ function buildMcpStatusPayload() {
|
|
|
16252
16515
|
modelContextWindow,
|
|
16253
16516
|
modelAutoCompactTokenLimit,
|
|
16254
16517
|
configReady: !statusConfigResult.isVirtual,
|
|
16518
|
+
...(hasConfigLoadError(statusConfigResult)
|
|
16519
|
+
? {
|
|
16520
|
+
error: {
|
|
16521
|
+
code: statusConfigResult.errorType === 'parse' ? 'CONFIG_TOML_PARSE_ERROR' : 'CONFIG_TOML_READ_ERROR',
|
|
16522
|
+
type: statusConfigResult.errorType,
|
|
16523
|
+
path: statusConfigResult.path || '',
|
|
16524
|
+
message: statusConfigResult.reason || '读取 config.toml 失败',
|
|
16525
|
+
detail: statusConfigResult.detail || ''
|
|
16526
|
+
}
|
|
16527
|
+
}
|
|
16528
|
+
: {}),
|
|
16255
16529
|
configErrorType: statusConfigResult.errorType || '',
|
|
16256
16530
|
configNotice: statusConfigResult.reason || '',
|
|
16257
16531
|
initNotice: consumeInitNotice()
|
|
@@ -16265,6 +16539,17 @@ function buildMcpProviderListPayload() {
|
|
|
16265
16539
|
const current = listConfig.model_provider;
|
|
16266
16540
|
return {
|
|
16267
16541
|
configReady: !listConfigResult.isVirtual,
|
|
16542
|
+
...(listConfigResult.errorType === 'parse' || listConfigResult.errorType === 'read'
|
|
16543
|
+
? {
|
|
16544
|
+
error: {
|
|
16545
|
+
code: listConfigResult.errorType === 'parse' ? 'CONFIG_TOML_PARSE_ERROR' : 'CONFIG_TOML_READ_ERROR',
|
|
16546
|
+
type: listConfigResult.errorType,
|
|
16547
|
+
path: listConfigResult.path || '',
|
|
16548
|
+
message: listConfigResult.reason || '读取 config.toml 失败',
|
|
16549
|
+
detail: listConfigResult.detail || ''
|
|
16550
|
+
}
|
|
16551
|
+
}
|
|
16552
|
+
: {}),
|
|
16268
16553
|
configErrorType: listConfigResult.errorType || '',
|
|
16269
16554
|
configNotice: listConfigResult.reason || '',
|
|
16270
16555
|
providers: Object.entries(providers).map(([name, p]) => {
|
|
@@ -16525,6 +16810,9 @@ function normalizeWorkflowDefinition(raw, idHint = '', source = 'custom') {
|
|
|
16525
16810
|
tool: toolName,
|
|
16526
16811
|
arguments: args,
|
|
16527
16812
|
when,
|
|
16813
|
+
...(item.dependsOn !== undefined ? { dependsOn: cloneJson(item.dependsOn, null) } : {}),
|
|
16814
|
+
...(item.retry !== undefined ? { retry: item.retry } : {}),
|
|
16815
|
+
...(item.timeoutMs !== undefined ? { timeoutMs: item.timeoutMs } : {}),
|
|
16528
16816
|
continueOnError: item.continueOnError === true,
|
|
16529
16817
|
write: item.write === true
|
|
16530
16818
|
});
|
|
@@ -16809,6 +17097,47 @@ function validateWorkflowById(workflowId, input = {}) {
|
|
|
16809
17097
|
};
|
|
16810
17098
|
}
|
|
16811
17099
|
|
|
17100
|
+
let unattendedWorkflowRunner = null;
|
|
17101
|
+
function getUnattendedWorkflowRunner() {
|
|
17102
|
+
if (unattendedWorkflowRunner) return unattendedWorkflowRunner;
|
|
17103
|
+
unattendedWorkflowRunner = createWorkflowRunner({
|
|
17104
|
+
directory: path.join(CONFIG_DIR, 'workflow-runs'),
|
|
17105
|
+
execute: async (definition, input, options) => {
|
|
17106
|
+
const check = validateWorkflowInputBySchema(definition.inputSchema, input);
|
|
17107
|
+
if (!check.ok) return { success: false, waiting: true, error: check.error, steps: options.resumeSteps || [] };
|
|
17108
|
+
const catalog = createWorkflowToolCatalog();
|
|
17109
|
+
return executeWorkflowDefinition(definition, input, {
|
|
17110
|
+
...options,
|
|
17111
|
+
invokeTool: async (name, args, execution) => {
|
|
17112
|
+
const tool = catalog[name];
|
|
17113
|
+
if (!tool) return { error: `workflow tool not supported: ${name}`, blocked: true };
|
|
17114
|
+
if (!tool.readOnly && !options.allowWrite) return { error: 'write permission required', blocked: true };
|
|
17115
|
+
if (!tool.readOnly && !isToolConfigWriteAllowed('codex')) return { error: 'codex configuration permission required', blocked: true };
|
|
17116
|
+
return tool.handler(args, { signal: execution.signal });
|
|
17117
|
+
}
|
|
17118
|
+
});
|
|
17119
|
+
},
|
|
17120
|
+
notify: async run => {
|
|
17121
|
+
const result = await notifyWebhook(
|
|
17122
|
+
run.status === 'waiting' ? 'workflow-waiting' : (run.status === 'completed' ? 'workflow-completed' : 'workflow-failed'),
|
|
17123
|
+
`工作流 ${run.definition.id}: ${run.status}`, { runId: run.id, summary: run.summary }
|
|
17124
|
+
);
|
|
17125
|
+
return result;
|
|
17126
|
+
}
|
|
17127
|
+
});
|
|
17128
|
+
return unattendedWorkflowRunner;
|
|
17129
|
+
}
|
|
17130
|
+
function submitUnattendedWorkflow(id, input, options = {}) {
|
|
17131
|
+
const result = getWorkflowDefinitionById(id);
|
|
17132
|
+
if (result.error) return result;
|
|
17133
|
+
const definition = resolveWorkflowDefinitionWithToolMeta(result.workflow);
|
|
17134
|
+
const validation = validateWorkflowDefinition(definition, { knownTools: getWorkflowKnownToolsSet() });
|
|
17135
|
+
if (!validation.ok) return validation;
|
|
17136
|
+
return getUnattendedWorkflowRunner().submit(definition, input || {}, {
|
|
17137
|
+
allowWrite: options.allowWrite === true, dryRun: options.dryRun === true
|
|
17138
|
+
});
|
|
17139
|
+
}
|
|
17140
|
+
|
|
16812
17141
|
async function runWorkflowById(workflowId, input = {}, options = {}) {
|
|
16813
17142
|
const definitionResult = getWorkflowDefinitionById(workflowId);
|
|
16814
17143
|
if (definitionResult.error) {
|
|
@@ -17096,6 +17425,18 @@ function createMcpTools(options = {}) {
|
|
|
17096
17425
|
handler: async () => getBuiltinClaudeProxyStatus()
|
|
17097
17426
|
});
|
|
17098
17427
|
|
|
17428
|
+
for (const action of ['submit', 'active-runs', 'detail', 'resume', 'cancel']) {
|
|
17429
|
+
pushTool({
|
|
17430
|
+
name: `codexmate.workflow.${action}`,
|
|
17431
|
+
description: `Persistent workflow ${action}; requires the Web service.`,
|
|
17432
|
+
readOnly: !['submit', 'resume', 'cancel'].includes(action),
|
|
17433
|
+
inputSchema: { type: 'object', properties: {
|
|
17434
|
+
id: { type: 'string' }, runId: { type: 'string' }, input: { type: 'object' }, dryRun: { type: 'boolean' }
|
|
17435
|
+
} },
|
|
17436
|
+
handler: async (params = {}) => callWorkflowService(action, { ...params, allowWrite })
|
|
17437
|
+
});
|
|
17438
|
+
}
|
|
17439
|
+
|
|
17099
17440
|
pushTool({
|
|
17100
17441
|
name: 'codexmate.workflow.list',
|
|
17101
17442
|
description: 'List available workflows (builtin + custom).',
|
|
@@ -17726,7 +18067,8 @@ function printMainHelp() {
|
|
|
17726
18067
|
console.log(' codexmate auth <list|import|switch|delete|status> 认证管理');
|
|
17727
18068
|
console.log(' codexmate add-model <模型> 添加模型');
|
|
17728
18069
|
console.log(' codexmate delete-model <模型> 删除模型');
|
|
17729
|
-
console.log(' codexmate workflow <list|get|validate|run|runs> MCP 工作流中心');
|
|
18070
|
+
console.log(' codexmate workflow <list|get|validate|run|runs|submit|active-runs|detail|resume|cancel> MCP 工作流中心');
|
|
18071
|
+
console.log(' codexmate thread <handoff|list|fallback|ack> 交接卡与共享记忆路由');
|
|
17730
18072
|
console.log(' codexmate analytics export [--format csv|json] [--from YYYY-MM-DD] [--to YYYY-MM-DD] [--model <MODEL>] [--output <PATH|->] [-o <PATH|->] 导出 Usage 数据');
|
|
17731
18073
|
console.log(' codexmate run [--host <HOST>] [--no-browser] 启动 Web 界面');
|
|
17732
18074
|
console.log(' codexmate update [--check] 检查并快速更新工具');
|
|
@@ -17748,6 +18090,10 @@ function printMainHelp() {
|
|
|
17748
18090
|
async function main() {
|
|
17749
18091
|
const args = process.argv.slice(2);
|
|
17750
18092
|
const command = args[0];
|
|
18093
|
+
if (command === 'thread') {
|
|
18094
|
+
await cmdThread(args.slice(1));
|
|
18095
|
+
return;
|
|
18096
|
+
}
|
|
17751
18097
|
const isMcpCommand = command === 'mcp';
|
|
17752
18098
|
const shouldGateInitialBootstrap = command === 'run' || isMcpCommand;
|
|
17753
18099
|
const bootstrap = ensureManagedConfigBootstrap({
|
|
@@ -17862,6 +18208,10 @@ async function main() {
|
|
|
17862
18208
|
}
|
|
17863
18209
|
|
|
17864
18210
|
main().catch((err) => {
|
|
17865
|
-
|
|
18211
|
+
if (err && typeof err.code === 'string' && err.code.startsWith('CONFIG_')) {
|
|
18212
|
+
console.error(formatConfigError(err));
|
|
18213
|
+
} else {
|
|
18214
|
+
console.error('错误:', err && err.message ? err.message : err);
|
|
18215
|
+
}
|
|
17866
18216
|
process.exit(1);
|
|
17867
18217
|
});
|