-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathcli.js
More file actions
13202 lines (12078 loc) · 462 KB
/
cli.js
File metadata and controls
13202 lines (12078 loc) · 462 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const os = require('os');
const crypto = require('crypto');
const toml = require('@iarna/toml');
const JSON5 = require('json5');
const zipLib = require('zip-lib');
const yauzl = require('yauzl');
const { exec, execSync, spawn, spawnSync } = require('child_process');
const http = require('http');
const https = require('https');
const net = require('net');
const readline = require('readline');
const {
expandHomePath,
resolveExistingDir,
resolveHomePath,
hasUtf8Bom,
stripUtf8Bom,
ensureUtf8Bom,
detectLineEnding,
normalizeLineEnding,
isValidProviderName,
escapeTomlBasicString,
buildModelProviderTableHeader,
buildModelsCandidates,
isValidHttpUrl,
normalizeBaseUrl,
joinApiUrl
} = require('./lib/cli-utils');
const {
ensureDir,
readJsonFile,
readJsonArrayFile,
readJsonObjectFromFile,
backupFileIfNeededOnce,
writeJsonAtomic,
formatTimestampForFileName
} = require('./lib/cli-file-utils');
const { buildLineDiff } = require('./lib/text-diff');
const {
extractModelNames,
hasModelsListPayload,
extractModelIds,
buildModelsProbeUrl,
buildModelProbeSpec,
buildModelsCacheKey
} = require('./lib/cli-models-utils');
const { probeUrl, probeJsonPost } = require('./lib/cli-network-utils');
const {
toIsoTime,
updateLatestIso,
truncateText,
extractMessageText,
normalizeRole,
parseMaxMessagesValue,
resolveMaxMessagesValue
} = require('./lib/cli-session-utils');
const { createMcpStdioServer } = require('./lib/mcp-stdio');
const {
validateWorkflowDefinition,
executeWorkflowDefinition
} = require('./lib/workflow-engine');
const DEFAULT_WEB_PORT = 3737;
const DEFAULT_WEB_HOST = '0.0.0.0';
const DEFAULT_WEB_OPEN_HOST = '127.0.0.1';
// ============================================================================
// 配置
// ============================================================================
const CONFIG_DIR = path.join(os.homedir(), '.codex');
const CONFIG_FILE = path.join(CONFIG_DIR, 'config.toml');
const AUTH_FILE = path.join(CONFIG_DIR, 'auth.json');
const AUTH_PROFILES_DIR = path.join(CONFIG_DIR, 'auth-profiles');
const AUTH_REGISTRY_FILE = path.join(AUTH_PROFILES_DIR, 'registry.json');
const MODELS_FILE = path.join(CONFIG_DIR, 'models.json');
const CURRENT_MODELS_FILE = path.join(CONFIG_DIR, 'provider-current-models.json');
const INIT_MARK_FILE = path.join(CONFIG_DIR, 'codexmate-init.json');
const BUILTIN_PROXY_SETTINGS_FILE = path.join(CONFIG_DIR, 'codexmate-proxy.json');
const CODEX_SESSIONS_DIR = path.join(CONFIG_DIR, 'sessions');
const SESSION_TRASH_DIR = path.join(CONFIG_DIR, 'codexmate-session-trash');
const SESSION_TRASH_FILES_DIR = path.join(SESSION_TRASH_DIR, 'files');
const SESSION_TRASH_INDEX_FILE = path.join(SESSION_TRASH_DIR, 'index.json');
const OPENCLAW_DIR = path.join(os.homedir(), '.openclaw');
const OPENCLAW_CONFIG_FILE = path.join(OPENCLAW_DIR, 'openclaw.json');
const OPENCLAW_WORKSPACE_DIR = path.join(OPENCLAW_DIR, 'workspace');
const CLAUDE_DIR = path.join(os.homedir(), '.claude');
const CLAUDE_SETTINGS_FILE = path.join(CLAUDE_DIR, 'settings.json');
const CLAUDE_PROJECTS_DIR = path.join(os.homedir(), '.claude', 'projects');
const RECENT_CONFIGS_FILE = path.join(CONFIG_DIR, 'recent-configs.json');
const WORKFLOW_DEFINITIONS_FILE = path.join(CONFIG_DIR, 'codexmate-workflows.json');
const WORKFLOW_RUNS_FILE = path.join(CONFIG_DIR, 'codexmate-workflow-runs.jsonl');
const DEFAULT_CLAUDE_MODEL = 'glm-4.7';
const DEFAULT_MODEL_CONTEXT_WINDOW = 190000;
const DEFAULT_MODEL_AUTO_COMPACT_TOKEN_LIMIT = 185000;
const CODEX_BACKUP_NAME = 'codex-config';
const DEFAULT_MODELS = ['gpt-5.3-codex', 'gpt-5.1-codex-max', 'gpt-4-turbo', 'gpt-4'];
const SPEED_TEST_TIMEOUT_MS = 8000;
const HEALTH_CHECK_TIMEOUT_MS = 6000;
const MAX_SESSION_LIST_SIZE = 300;
const MAX_SESSION_TRASH_LIST_SIZE = 500;
const MAX_EXPORT_MESSAGES = 1000;
const DEFAULT_SESSION_DETAIL_MESSAGES = 300;
const MAX_SESSION_DETAIL_MESSAGES = 1000;
const SESSION_TITLE_READ_BYTES = 64 * 1024;
const CODEXMATE_MANAGED_MARKER = '# codexmate-managed: true';
const SESSION_LIST_CACHE_TTL_MS = 4000;
const SESSION_SUMMARY_READ_BYTES = 256 * 1024;
const SESSION_CONTENT_READ_BYTES = SESSION_SUMMARY_READ_BYTES;
const EXACT_MESSAGE_COUNT_CACHE_MAX_ENTRIES = 800;
const DEFAULT_CONTENT_SCAN_LIMIT = 50;
const SESSION_SCAN_FACTOR = 4;
const SESSION_SCAN_MIN_FILES = 800;
const MAX_SESSION_PATH_LIST_SIZE = 2000;
const AGENTS_FILE_NAME = 'AGENTS.md';
const CODEX_SKILLS_DIR = path.join(CONFIG_DIR, 'skills');
const CLAUDE_SKILLS_DIR = path.join(CLAUDE_DIR, 'skills');
const AGENTS_SKILLS_DIR = path.join(os.homedir(), '.agents', 'skills');
const SKILL_TARGETS = Object.freeze([
Object.freeze({ app: 'codex', label: 'Codex', dir: getCodexSkillsDir() }),
Object.freeze({ app: 'claude', label: 'Claude Code', dir: getClaudeSkillsDir() })
]);
const SKILL_IMPORT_SOURCES = Object.freeze([
...SKILL_TARGETS,
Object.freeze({ app: 'agents', label: 'Agents', dir: AGENTS_SKILLS_DIR })
]);
const MODELS_CACHE_TTL_MS = 60 * 1000;
const MODELS_NEGATIVE_CACHE_TTL_MS = 5 * 1000;
const MODELS_CACHE_MAX_ENTRIES = 50;
const MODELS_RESPONSE_MAX_BYTES = 1024 * 1024;
const MAX_RECENT_CONFIGS = 3;
const MAX_UPLOAD_SIZE = 200 * 1024 * 1024;
const MAX_SKILLS_ZIP_UPLOAD_SIZE = 20 * 1024 * 1024;
const MAX_API_BODY_SIZE = 4 * 1024 * 1024;
const MAX_SKILLS_ZIP_ENTRY_COUNT = 2000;
const MAX_SKILLS_ZIP_UNCOMPRESSED_BYTES = 512 * 1024 * 1024;
const DEFAULT_EXTRACT_SUFFIXES = Object.freeze(['.json']);
const DOWNLOAD_ARTIFACT_TTL_MS = 10 * 60 * 1000;
const g_downloadArtifacts = new Map();
const BUILTIN_PROXY_PROVIDER_NAME = 'codexmate-proxy';
const DEFAULT_BUILTIN_PROXY_SETTINGS = Object.freeze({
enabled: false,
host: '127.0.0.1',
port: 8318,
provider: '',
authSource: 'provider',
timeoutMs: 30000
});
const BOOTSTRAP_TEXT_MARKERS = [
'agents.md instructions',
'<instructions>',
'<environment_context>',
'you are a coding agent',
'codex cli'
];
const CLI_INSTALL_TARGETS = Object.freeze([
{
id: 'claude',
name: 'Claude Code CLI',
packageName: '@anthropic-ai/claude-code',
bins: ['claude']
},
{
id: 'codex',
name: 'Codex CLI',
packageName: '@openai/codex',
bins: ['codex']
}
]);
const HTTP_KEEP_ALIVE_AGENT = new http.Agent({ keepAlive: true });
const HTTPS_KEEP_ALIVE_AGENT = new https.Agent({ keepAlive: true });
function getCodexSkillsDir() {
const envCodexHome = typeof process.env.CODEX_HOME === 'string' ? process.env.CODEX_HOME.trim() : '';
if (envCodexHome) {
const target = path.join(envCodexHome, 'skills');
return resolveExistingDir([target], target);
}
const xdgConfig = typeof process.env.XDG_CONFIG_HOME === 'string' ? process.env.XDG_CONFIG_HOME.trim() : '';
if (xdgConfig) {
const target = path.join(xdgConfig, 'codex', 'skills');
return resolveExistingDir([target], target);
}
const homeConfigDir = path.join(os.homedir(), '.config', 'codex', 'skills');
return resolveExistingDir([homeConfigDir], CODEX_SKILLS_DIR);
}
function getClaudeSkillsDir() {
const envClaudeHome = typeof process.env.CLAUDE_HOME === 'string' && process.env.CLAUDE_HOME.trim()
? process.env.CLAUDE_HOME.trim()
: (typeof process.env.CLAUDE_CONFIG_DIR === 'string' ? process.env.CLAUDE_CONFIG_DIR.trim() : '');
if (envClaudeHome) {
const target = path.join(envClaudeHome, 'skills');
return resolveExistingDir([target], target);
}
const xdgConfig = typeof process.env.XDG_CONFIG_HOME === 'string' ? process.env.XDG_CONFIG_HOME.trim() : '';
if (xdgConfig) {
const target = path.join(xdgConfig, 'claude', 'skills');
return resolveExistingDir([target], target);
}
const homeConfigDir = path.join(os.homedir(), '.config', 'claude', 'skills');
return resolveExistingDir([homeConfigDir], CLAUDE_SKILLS_DIR);
}
function resolveWebPort() {
const raw = process.env.CODEXMATE_PORT;
if (!raw) return DEFAULT_WEB_PORT;
const parsed = parseInt(raw, 10);
if (!Number.isFinite(parsed) || parsed <= 0) return DEFAULT_WEB_PORT;
return parsed;
}
function resolveWebHost(options = {}) {
const optionHost = typeof options.host === 'string' ? options.host.trim() : '';
if (optionHost) {
return optionHost;
}
const envHost = typeof process.env.CODEXMATE_HOST === 'string' ? process.env.CODEXMATE_HOST.trim() : '';
if (envHost) {
return envHost;
}
return DEFAULT_WEB_HOST;
}
const EMPTY_CONFIG_FALLBACK_TEMPLATE = `model = "gpt-5.3-codex"
model_reasoning_effort = "high"
model_context_window = ${DEFAULT_MODEL_CONTEXT_WINDOW}
model_auto_compact_token_limit = ${DEFAULT_MODEL_AUTO_COMPACT_TOKEN_LIMIT}
disable_response_storage = true
approval_policy = "never"
sandbox_mode = "danger-full-access"
model_provider = "maxx"
personality = "pragmatic"
web_search = "live"
[model_providers.maxx]
name = "maxx"
base_url = "https://maxx-direct.cloverstd.com"
wire_api = "responses"
requires_openai_auth = false
preferred_auth_method = "sk-"
request_max_retries = 4
stream_max_retries = 10
stream_idle_timeout_ms = 300000
`;
let g_initNotice = '';
let g_sessionListCache = new Map();
let g_exactMessageCountCache = new Map();
let g_modelsCache = new Map();
let g_modelsInFlight = new Map();
let g_builtinProxyRuntime = null;
const DEFAULT_LOCAL_PROVIDER_NAME = 'local';
function isBuiltinProxyProvider(providerName) {
return typeof providerName === 'string' && providerName.trim().toLowerCase() === BUILTIN_PROXY_PROVIDER_NAME.toLowerCase();
}
function isReservedProviderNameForCreation(providerName) {
return typeof providerName === 'string'
&& providerName.trim().toLowerCase() === DEFAULT_LOCAL_PROVIDER_NAME;
}
function isDefaultLocalProvider(providerName) {
return typeof providerName === 'string' && providerName.trim() === DEFAULT_LOCAL_PROVIDER_NAME;
}
function isNonDeletableProvider(providerName) {
return isBuiltinProxyProvider(providerName) || isDefaultLocalProvider(providerName);
}
function isNonEditableProvider(providerName) {
return isBuiltinProxyProvider(providerName) || isDefaultLocalProvider(providerName);
}
// ============================================================================
// 工具函数
// ============================================================================
function ensureConfigDir() {
if (!fs.existsSync(CONFIG_DIR)) {
fs.mkdirSync(CONFIG_DIR, { recursive: true });
}
}
function createConfigLoadError(type, message, detail) {
const err = new Error(detail || message);
err.configErrorType = type || 'read';
err.configPublicReason = message || '读取 config.toml 失败';
err.configDetail = detail || message || '';
return err;
}
function readConfig() {
if (!fs.existsSync(CONFIG_FILE)) {
throw createConfigLoadError(
'missing',
'未检测到 config.toml',
`配置文件不存在: ${CONFIG_FILE}`
);
}
let content = '';
try {
content = fs.readFileSync(CONFIG_FILE, 'utf-8');
} catch (e) {
throw createConfigLoadError(
'read',
'读取 config.toml 失败',
`读取配置文件失败: ${e && e.message ? e.message : e}`
);
}
let parsed;
try {
parsed = toml.parse(content);
} catch (e) {
throw createConfigLoadError(
'parse',
'config.toml 解析失败',
`配置文件解析失败: ${e && e.message ? e.message : e}`
);
}
if (isPlainObject(parsed) && isPlainObject(parsed.model_providers)) {
const providerHeaderSegmentKeySet = collectModelProviderHeaderSegmentKeySet(content);
parsed.model_providers = normalizeLegacyModelProviders(parsed.model_providers, providerHeaderSegmentKeySet);
}
return parsed;
}
function writeConfig(content) {
try {
fs.writeFileSync(CONFIG_FILE, content, 'utf-8');
} catch (e) {
throw new Error(`写入配置失败: ${e.message}`);
}
}
function readModels() {
if (fs.existsSync(MODELS_FILE)) {
try {
return JSON.parse(fs.readFileSync(MODELS_FILE, 'utf-8'));
} catch (e) {}
}
return [...DEFAULT_MODELS];
}
function writeModels(models) {
fs.writeFileSync(MODELS_FILE, JSON.stringify(models, null, 2), 'utf-8');
}
function readCurrentModels() {
if (fs.existsSync(CURRENT_MODELS_FILE)) {
try {
return JSON.parse(fs.readFileSync(CURRENT_MODELS_FILE, 'utf-8'));
} catch (e) {}
}
return {};
}
function writeCurrentModels(data) {
fs.writeFileSync(CURRENT_MODELS_FILE, JSON.stringify(data, null, 2), 'utf-8');
}
function updateAuthJson(apiKey) {
let authData = {};
if (fs.existsSync(AUTH_FILE)) {
try {
const content = fs.readFileSync(AUTH_FILE, 'utf-8');
if (content.trim()) authData = JSON.parse(content);
} catch (e) {}
}
authData['OPENAI_API_KEY'] = apiKey;
fs.writeFileSync(AUTH_FILE, JSON.stringify(authData, null, 2), 'utf-8');
}
function isPlainObject(value) {
return !!value && typeof value === 'object' && !Array.isArray(value);
}
const PROVIDER_CONFIG_KEYS = new Set([
'name',
'base_url',
'wire_api',
'requires_openai_auth',
'preferred_auth_method',
'request_max_retries',
'stream_max_retries',
'stream_idle_timeout_ms'
]);
const RECOVERABLE_PROVIDER_SIGNAL_KEYS = [...PROVIDER_CONFIG_KEYS].filter((key) => key !== 'name' && key !== 'base_url');
function looksLikeProviderConfig(value) {
if (!isPlainObject(value)) return false;
return Object.keys(value).some((key) => PROVIDER_CONFIG_KEYS.has(key));
}
function isRecoverableNestedProviderConfig(value) {
if (!isPlainObject(value)) return false;
const hasBaseUrl = typeof value.base_url === 'string' && value.base_url.trim() !== '';
if (!hasBaseUrl) return false;
const hasName = typeof value.name === 'string' && value.name.trim() !== '';
const hasProviderSignals = RECOVERABLE_PROVIDER_SIGNAL_KEYS.some((key) => Object.prototype.hasOwnProperty.call(value, key));
return hasName || hasProviderSignals;
}
function collectNestedProviderConfigs(node, pathSegments, collector) {
if (!isPlainObject(node)) return;
const segments = Array.isArray(pathSegments) ? pathSegments : [String(pathSegments || '')];
const lastSegment = segments.length > 0 ? segments[segments.length - 1] : '';
if (segments.length > 1 && lastSegment === 'metadata') {
return;
}
if (isRecoverableNestedProviderConfig(node)) {
collector.push({
name: segments.join('.'),
segments: segments.slice(),
provider: node
});
}
for (const [childKey, childValue] of Object.entries(node)) {
if (!isPlainObject(childValue)) continue;
collectNestedProviderConfigs(childValue, [...segments, childKey], collector);
}
}
function normalizeLegacySegments(segments) {
if (!Array.isArray(segments) || segments.length === 0) return null;
return segments.map((item) => String(item));
}
function buildLegacySegmentsKey(segments) {
const normalized = normalizeLegacySegments(segments);
return normalized ? JSON.stringify(normalized) : '';
}
function appendLegacySegmentsVariant(provider, segments) {
if (!isPlainObject(provider)) return;
const normalized = normalizeLegacySegments(segments);
if (!normalized) return;
const variants = [];
const seen = new Set();
const pushVariant = (candidate) => {
const key = buildLegacySegmentsKey(candidate);
if (!key || seen.has(key)) return;
seen.add(key);
variants.push(normalizeLegacySegments(candidate));
};
if (Array.isArray(provider.__codexmate_legacy_segments)) {
pushVariant(provider.__codexmate_legacy_segments);
}
if (Array.isArray(provider.__codexmate_legacy_segment_variants)) {
for (const candidate of provider.__codexmate_legacy_segment_variants) {
pushVariant(candidate);
}
}
pushVariant(normalized);
try {
if (!Array.isArray(provider.__codexmate_legacy_segments)) {
Object.defineProperty(provider, '__codexmate_legacy_segments', {
value: normalized,
enumerable: false,
configurable: true,
writable: true
});
}
Object.defineProperty(provider, '__codexmate_legacy_segment_variants', {
value: variants,
enumerable: false,
configurable: true,
writable: true
});
} catch (e) {}
}
function setLegacySegmentsMetadata(provider, segments) {
appendLegacySegmentsVariant(provider, segments);
}
function normalizeLegacyModelProviders(modelProviders, providerHeaderSegmentKeySet = null) {
if (!isPlainObject(modelProviders)) {
return modelProviders;
}
let changed = false;
const normalized = {};
const addRecovered = (entry) => {
const name = entry && typeof entry.name === 'string' ? entry.name : '';
const segments = entry && Array.isArray(entry.segments) ? entry.segments.slice() : null;
const provider = entry ? entry.provider : null;
if (!name || !isPlainObject(provider)) return;
const segmentKey = buildLegacySegmentsKey(segments);
if (providerHeaderSegmentKeySet instanceof Set && segmentKey && !providerHeaderSegmentKeySet.has(segmentKey)) {
return;
}
const existing = Object.prototype.hasOwnProperty.call(normalized, name)
? normalized[name]
: (Object.prototype.hasOwnProperty.call(modelProviders, name) ? modelProviders[name] : null);
if (isPlainObject(existing)) {
if (!Array.isArray(existing.__codexmate_legacy_segments)) {
setLegacySegmentsMetadata(existing, [name]);
}
appendLegacySegmentsVariant(existing, segments);
return;
}
if (Object.prototype.hasOwnProperty.call(modelProviders, name)) return;
if (Object.prototype.hasOwnProperty.call(normalized, name)) return;
setLegacySegmentsMetadata(provider, segments);
normalized[name] = provider;
changed = true;
};
for (const [name, provider] of Object.entries(modelProviders)) {
normalized[name] = provider;
if (!isPlainObject(provider)) continue;
if (looksLikeProviderConfig(provider)) {
setLegacySegmentsMetadata(provider, [name]);
for (const [childKey, childValue] of Object.entries(provider)) {
if (!isPlainObject(childValue)) continue;
const recovered = [];
collectNestedProviderConfigs(childValue, [name, childKey], recovered);
for (const recoveredEntry of recovered) {
addRecovered(recoveredEntry);
}
}
continue;
}
const recovered = [];
collectNestedProviderConfigs(provider, [name], recovered);
delete normalized[name];
changed = true;
for (const recoveredEntry of recovered) {
addRecovered(recoveredEntry);
}
}
return changed ? normalized : modelProviders;
}
function escapeRegex(value) {
return String(value || '').replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
function areStringArraysEqual(a, b) {
if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
for (let i = 0; i < a.length; i++) {
if (String(a[i]) !== String(b[i])) return false;
}
return true;
}
function parseTomlDottedKeyExpression(expression) {
const text = String(expression || '');
let index = 0;
const segments = [];
const skipWhitespace = () => {
while (index < text.length && /\s/.test(text[index])) index++;
};
while (index < text.length) {
skipWhitespace();
if (index >= text.length) break;
const ch = text[index];
if (ch === "'") {
const end = text.indexOf("'", index + 1);
if (end === -1) return null;
segments.push(text.slice(index + 1, end));
index = end + 1;
} else if (ch === '"') {
index += 1;
let value = '';
let closed = false;
while (index < text.length) {
const cur = text[index];
if (cur === '"') {
index += 1;
closed = true;
break;
}
if (cur !== '\\') {
value += cur;
index += 1;
continue;
}
if (index + 1 >= text.length) return null;
const esc = text[index + 1];
if (esc === 'u' || esc === 'U') {
const hexLen = esc === 'u' ? 4 : 8;
const hex = text.slice(index + 2, index + 2 + hexLen);
if (!/^[0-9a-fA-F]+$/.test(hex)) return null;
try {
value += String.fromCodePoint(parseInt(hex, 16));
} catch (e) {
return null;
}
index += 2 + hexLen;
continue;
}
const unescaped = {
b: '\b',
t: '\t',
n: '\n',
f: '\f',
r: '\r',
'"': '"',
'\\': '\\'
}[esc];
if (unescaped === undefined) return null;
value += unescaped;
index += 2;
}
if (!closed) return null;
segments.push(value);
} else {
const start = index;
while (index < text.length && !/\s|\./.test(text[index])) index++;
const bare = text.slice(start, index);
if (!bare) return null;
segments.push(bare);
}
skipWhitespace();
if (index >= text.length) break;
if (text[index] !== '.') return null;
index += 1;
}
return segments.length > 0 ? segments : null;
}
function collectTomlMultilineStringRanges(text) {
const source = typeof text === 'string' ? text : '';
const ranges = [];
let i = 0;
let inMultilineBasic = false;
let inMultilineLiteral = false;
let rangeStart = -1;
while (i < source.length) {
if (inMultilineBasic) {
if (source.slice(i, i + 3) === '"""') {
let slashCount = 0;
for (let j = i - 1; j >= 0 && source[j] === '\\'; j--) {
slashCount++;
}
if (slashCount % 2 === 0) {
let runEnd = i + 3;
while (runEnd < source.length && source[runEnd] === '"') runEnd++;
ranges.push({ start: rangeStart, end: runEnd });
inMultilineBasic = false;
rangeStart = -1;
i = runEnd;
continue;
}
}
i++;
continue;
}
if (inMultilineLiteral) {
if (source.slice(i, i + 3) === "'''") {
let runEnd = i + 3;
while (runEnd < source.length && source[runEnd] === '\'') runEnd++;
ranges.push({ start: rangeStart, end: runEnd });
inMultilineLiteral = false;
rangeStart = -1;
i = runEnd;
continue;
}
i++;
continue;
}
const ch = source[i];
if (ch === '#') {
while (i < source.length && source[i] !== '\n') i++;
continue;
}
if (source.slice(i, i + 3) === '"""') {
inMultilineBasic = true;
rangeStart = i;
i += 3;
continue;
}
if (source.slice(i, i + 3) === "'''") {
inMultilineLiteral = true;
rangeStart = i;
i += 3;
continue;
}
if (ch === '"') {
i++;
while (i < source.length) {
if (source[i] === '\\') {
i += 2;
continue;
}
if (source[i] === '"' || source[i] === '\n') {
i++;
break;
}
i++;
}
continue;
}
if (ch === '\'') {
i++;
while (i < source.length) {
if (source[i] === '\'' || source[i] === '\n') {
i++;
break;
}
i++;
}
continue;
}
i++;
}
if (rangeStart >= 0) {
ranges.push({ start: rangeStart, end: source.length });
}
return ranges;
}
function isIndexInRanges(index, ranges) {
for (const range of ranges) {
if (index < range.start) return false;
if (index >= range.start && index < range.end) return true;
}
return false;
}
function findProviderSectionRanges(content, providerName, exactSegments = null) {
const text = typeof content === 'string' ? content : '';
const name = typeof providerName === 'string' ? providerName.trim() : '';
const targetSegments = Array.isArray(exactSegments) ? exactSegments.map((item) => String(item)) : null;
if (!text || !name) return [];
const safeName = escapeRegex(name);
const headerPatterns = [
{ priority: 0, regex: new RegExp(`^\\s*model_providers\\s*\\.\\s*"${safeName}"\\s*$`) },
{ priority: 1, regex: new RegExp(`^\\s*model_providers\\s*\\.\\s*'${safeName}'\\s*$`) },
{ priority: 2, regex: new RegExp(`^\\s*model_providers\\s*\\.\\s*${safeName}\\s*$`) }
];
const allHeaders = [];
const targetPriorityByStart = new Map();
const multilineStringRanges = collectTomlMultilineStringRanges(text);
const sectionLineRegex = /^[ \t]*\[(?!\[)([^\]\n]+)\][ \t]*(?:#.*)?$/gm;
let match;
while ((match = sectionLineRegex.exec(text)) !== null) {
const start = match.index;
if (isIndexInRanges(start, multilineStringRanges)) {
continue;
}
allHeaders.push(start);
const headerExpr = String(match[1] || '').trim();
const parsedSegments = parseTomlDottedKeyExpression(headerExpr);
if (Array.isArray(parsedSegments) && parsedSegments.length >= 2 && parsedSegments[0] === 'model_providers') {
const providerSegments = parsedSegments.slice(1);
if (targetSegments && targetSegments.length > 0 && areStringArraysEqual(providerSegments, targetSegments)) {
const prev = targetPriorityByStart.get(start);
if (prev === undefined || -3 < prev) {
targetPriorityByStart.set(start, -3);
}
continue;
}
if (!targetSegments || targetSegments.length === 0) {
const parsedName = providerSegments.join('.');
if (parsedName === name) {
const prev = targetPriorityByStart.get(start);
if (prev === undefined || -2 < prev) {
targetPriorityByStart.set(start, -2);
}
continue;
}
}
}
for (const pattern of headerPatterns) {
if (pattern.regex.test(headerExpr)) {
const prev = targetPriorityByStart.get(start);
if (prev === undefined || pattern.priority < prev) {
targetPriorityByStart.set(start, pattern.priority);
}
break;
}
}
}
if (targetPriorityByStart.size === 0) {
return [];
}
const ranges = [];
for (let i = 0; i < allHeaders.length; i++) {
const start = allHeaders[i];
if (!targetPriorityByStart.has(start)) continue;
const end = i + 1 < allHeaders.length ? allHeaders[i + 1] : text.length;
ranges.push({
start,
end,
priority: targetPriorityByStart.get(start)
});
}
const exactMatches = ranges.filter((range) => range.priority === -3);
return exactMatches.length > 0 ? exactMatches : ranges;
}
function doesSegmentsStartWith(segments, prefix) {
if (!Array.isArray(segments) || !Array.isArray(prefix) || prefix.length === 0 || segments.length < prefix.length) {
return false;
}
for (let i = 0; i < prefix.length; i++) {
if (String(segments[i]) !== String(prefix[i])) return false;
}
return true;
}
function findProviderDescendantSectionRanges(content, prefixSegments) {
const text = typeof content === 'string' ? content : '';
const prefix = Array.isArray(prefixSegments) ? prefixSegments.map((item) => String(item)) : [];
if (!text || prefix.length === 0) return [];
const allHeaders = [];
const parsedProviderSegmentsByStart = new Map();
const multilineStringRanges = collectTomlMultilineStringRanges(text);
const sectionLineRegex = /^[ \t]*\[(?!\[)([^\]\n]+)\][ \t]*(?:#.*)?$/gm;
let match;
while ((match = sectionLineRegex.exec(text)) !== null) {
const start = match.index;
if (isIndexInRanges(start, multilineStringRanges)) {
continue;
}
allHeaders.push(start);
const headerExpr = String(match[1] || '').trim();
const parsedSegments = parseTomlDottedKeyExpression(headerExpr);
if (!Array.isArray(parsedSegments) || parsedSegments.length < 2 || parsedSegments[0] !== 'model_providers') {
continue;
}
parsedProviderSegmentsByStart.set(start, parsedSegments.slice(1));
}
const ranges = [];
for (let i = 0; i < allHeaders.length; i++) {
const start = allHeaders[i];
const providerSegments = parsedProviderSegmentsByStart.get(start);
if (!providerSegments) continue;
if (!doesSegmentsStartWith(providerSegments, prefix)) continue;
if (providerSegments.length <= prefix.length) continue;
const end = i + 1 < allHeaders.length ? allHeaders[i + 1] : text.length;
ranges.push({ start, end, priority: 0 });
}
return ranges;
}
function collectModelProviderHeaderSegmentKeySet(content) {
const text = typeof content === 'string' ? content : '';
const keys = new Set();
if (!text) return keys;
const multilineStringRanges = collectTomlMultilineStringRanges(text);
const sectionLineRegex = /^[ \t]*\[(?!\[)([^\]\n]+)\][ \t]*(?:#.*)?$/gm;
let match;
while ((match = sectionLineRegex.exec(text)) !== null) {
const start = match.index;
if (isIndexInRanges(start, multilineStringRanges)) {
continue;
}
const headerExpr = String(match[1] || '').trim();
const parsedSegments = parseTomlDottedKeyExpression(headerExpr);
if (!Array.isArray(parsedSegments) || parsedSegments.length < 2 || parsedSegments[0] !== 'model_providers') {
continue;
}
const key = buildLegacySegmentsKey(parsedSegments.slice(1));
if (key) keys.add(key);
}
return keys;
}
function normalizeAuthProfileName(value) {
const raw = typeof value === 'string' ? value.trim() : '';
if (!raw) return '';
const sanitized = raw
.replace(/[\\\/:*?"<>|]/g, '-')
.replace(/\s+/g, '-')
.replace(/^-+|-+$/g, '')
.slice(0, 120);
return sanitized;
}
function normalizeAuthRegistry(raw) {
const fallback = { version: 1, current: '', items: [] };
if (!isPlainObject(raw)) return fallback;
const items = Array.isArray(raw.items)
? raw.items.filter(item => isPlainObject(item) && typeof item.name === 'string' && item.name.trim())
: [];
return {
version: 1,
current: typeof raw.current === 'string' ? raw.current.trim() : '',
items: items.map((item) => ({
name: normalizeAuthProfileName(item.name) || item.name.trim(),
fileName: typeof item.fileName === 'string' ? path.basename(item.fileName) : '',
type: typeof item.type === 'string' ? item.type : '',
email: typeof item.email === 'string' ? item.email : '',
accountId: typeof item.accountId === 'string' ? item.accountId : '',
expired: typeof item.expired === 'string' ? item.expired : '',
lastRefresh: typeof item.lastRefresh === 'string' ? item.lastRefresh : '',
updatedAt: typeof item.updatedAt === 'string' ? item.updatedAt : '',
importedAt: typeof item.importedAt === 'string' ? item.importedAt : '',
sourceFile: typeof item.sourceFile === 'string' ? item.sourceFile : ''
}))
};
}
function ensureAuthProfileStoragePrepared() {
ensureDir(AUTH_PROFILES_DIR);
}
function readAuthRegistry() {
ensureAuthProfileStoragePrepared();
const parsed = readJsonFile(AUTH_REGISTRY_FILE, null);
return normalizeAuthRegistry(parsed);
}
function writeAuthRegistry(registry) {
ensureAuthProfileStoragePrepared();
writeJsonAtomic(AUTH_REGISTRY_FILE, normalizeAuthRegistry(registry));
}
function parseAuthProfileJson(rawContent, label = '') {
let parsed;
try {
parsed = JSON.parse(stripUtf8Bom(String(rawContent || '')));
} catch (e) {
throw new Error(`认证文件不是有效 JSON${label ? `: ${label}` : ''}`);
}
if (!isPlainObject(parsed)) {
throw new Error('认证文件根节点必须是对象');
}
const hasCredential = ['access_token', 'refresh_token', 'id_token', 'OPENAI_API_KEY']
.some((key) => typeof parsed[key] === 'string' && parsed[key].trim());
if (!hasCredential) {
throw new Error('认证文件缺少可用凭据(access_token / refresh_token / id_token / OPENAI_API_KEY)');
}
return parsed;
}
function buildAuthProfileSummary(name, payload, fileName = '') {
const safePayload = isPlainObject(payload) ? payload : {};
return {
name,
fileName: fileName || `${name}.json`,
type: typeof safePayload.type === 'string' ? safePayload.type : '',
email: typeof safePayload.email === 'string' ? safePayload.email : '',
accountId: typeof safePayload.account_id === 'string'
? safePayload.account_id
: (typeof safePayload.accountId === 'string' ? safePayload.accountId : ''),
expired: typeof safePayload.expired === 'string' ? safePayload.expired : '',
lastRefresh: typeof safePayload.last_refresh === 'string'
? safePayload.last_refresh
: (typeof safePayload.lastRefresh === 'string' ? safePayload.lastRefresh : ''),
updatedAt: toIsoTime(Date.now())
};
}
function getAuthProfileNameFallback(payload, fallbackName = '') {
const fromPayload = isPlainObject(payload)
? (payload.email || payload.account_id || payload.accountId || '')
: '';
const fromFallback = typeof fallbackName === 'string' ? fallbackName : '';
const resolved = normalizeAuthProfileName(fromPayload) || normalizeAuthProfileName(fromFallback);
if (resolved) return resolved;
return `auth-${Date.now()}`;
}
function listAuthProfilesInfo() {
const registry = readAuthRegistry();
return registry.items.map((item) => ({
...item,
current: item.name === registry.current
}));
}