-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
executable file
·3078 lines (2817 loc) · 116 KB
/
Copy pathserver.js
File metadata and controls
executable file
·3078 lines (2817 loc) · 116 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
'use strict';
const http = require('http');
const os = require('os');
const path = require('path');
const fs = require('fs');
const crypto = require('crypto');
const { spawn } = require('child_process');
const { URL } = require('url');
const APP_NAME = process.env.CODEX_MAX_APP_NAME || process.env.CODEX_MINI_APP_NAME || 'Codex Max';
const PORT = Number(process.env.PORT || 8787);
const HOST = process.env.HOST || '0.0.0.0';
const TOKEN = process.env.MOBILE_TYPER_TOKEN || crypto.randomBytes(12).toString('base64url');
const PUBLIC_DIR = path.join(__dirname, 'public');
const MAX_BODY_BYTES = Number(process.env.CODEX_MAX_MAX_BODY_BYTES || process.env.CODEX_MINI_MAX_BODY_BYTES || 28 * 1024 * 1024);
const MAX_TEXT_LENGTH = 8000;
const MAX_ATTACHMENTS = 6;
const MAX_ATTACHMENT_BYTES = Number(process.env.CODEX_MAX_MAX_ATTACHMENT_BYTES || process.env.CODEX_MINI_MAX_ATTACHMENT_BYTES || 8 * 1024 * 1024);
const UPLOAD_DIR = path.join(os.tmpdir(), 'codex-max-uploads');
const STATE_DIR = process.env.CODEX_MAX_STATE_DIR || process.env.CODEX_MINI_STATE_DIR || path.join(os.homedir(), '.codex-max');
const STATE_FILE = path.join(STATE_DIR, 'state.json');
const CODEX_SESSIONS_DIR = path.join(os.homedir(), '.codex', 'sessions');
const CODEX_SESSION_INDEX = path.join(os.homedir(), '.codex', 'session_index.jsonl');
const CODEX_DESKTOP_LOGS_DIR = process.platform === 'darwin'
? path.join(os.homedir(), 'Library', 'Logs', 'com.openai.codex')
: process.platform === 'win32'
? path.join(os.homedir(), 'AppData', 'Roaming', 'com.openai.codex', 'logs')
: path.join(os.homedir(), '.codex', 'logs');
const CODEX_SESSION_TAIL_BYTES = 5 * 1024 * 1024;
const CODEX_ACTIVITY_TAIL_BYTES = 512 * 1024;
const CODEX_ACTIVITY_LOOKBACK_BYTES = CODEX_SESSION_TAIL_BYTES;
const CODEX_RUNTIME_STALE_MS = 2 * 60 * 60 * 1000;
const CODEX_HISTORY_TAIL_BYTES = 128 * 1024 * 1024;
const CODEX_TITLE_SCAN_BYTES = 12 * 1024 * 1024;
const MAX_HISTORY_MESSAGES = 120;
const GUI_FAILURE_REPORT_LIMIT = 80;
const GUI_FAILURE_LOG_SCAN_BYTES = 2 * 1024 * 1024;
const GUI_FAILURE_LOG_RECENT_MS = 15 * 60 * 1000;
const RECENT_SEND_TTL_MS = 5 * 60 * 1000;
const CODEX_THREAD_SYNC_FRESH_MS = process.platform === 'win32' ? 10 * 60 * 1000 : 5000;
const CODEX_DEEPLINK_SETTLE_MS = process.platform === 'win32' ? 1400 : 560;
const CODEX_APP_FOCUS_SETTLE_MS = 100;
const CODEX_CLICK_SETTLE_MS = 60;
const TEXT_PASTE_SETTLE_MS = process.platform === 'win32' ? 180 : 140;
const ATTACHMENT_PASTE_SETTLE_MS = process.platform === 'win32' ? 520 : 220;
const CODEX_COMMAND_SETTLE_MS = process.platform === 'win32' ? 220 : 180;
const CODEX_MODEL_COMMAND_SETTLE_MS = process.platform === 'win32' ? 520 : 450;
const CODEX_REASONING_COMMAND_SETTLE_MS = process.platform === 'win32' ? 520 : 450;
const CODEX_SEND_CONFIRM_TIMEOUT_MS = process.platform === 'win32' ? 1800 : 0;
const CODEX_SESSION_FILE_CACHE_MS = 1200;
const CODEX_THREAD_LIST_CACHE_MS = 1200;
const CODEX_HISTORY_INITIAL_TAIL_BYTES = 8 * 1024 * 1024;
const REASONING_MODE_TARGETS = {
low: { key: 'low', value: 'low', label: '低', displayName: '低' },
medium: { key: 'medium', value: 'medium', label: '中', displayName: '中' },
high: { key: 'high', value: 'high', label: '高', displayName: '高' },
xhigh: { key: 'xhigh', value: 'xhigh', label: '超高', displayName: '超高' },
};
const recentSendRequests = new Map();
let lastCodexThreadActivation = { threadId: '', at: 0 };
let codexSessionFilesCache = { at: 0, files: [] };
let threadIndexCache = { mtimeMs: 0, size: 0, byId: null };
const sessionMetaCache = new Map();
const firstUserMessageCache = new Map();
const runtimeSummaryCache = new Map();
const codexThreadListCache = new Map();
let modelCatalogCache = { mtimeMs: -1, path: '', models: null };
let keepAwakeProcess = null;
let keepAwakeStartedAt = '';
function fileCacheSignature(stat) {
return stat ? `${stat.size}:${stat.mtimeMs}` : '';
}
function boundedSet(map, key, value, limit = 300) {
if (map.size >= limit && !map.has(key)) {
const firstKey = map.keys().next().value;
if (firstKey !== undefined) map.delete(firstKey);
}
map.set(key, value);
return value;
}
function invalidateCodexThreadListCache() {
codexThreadListCache.clear();
}
function isKeepAwakeActive() {
return Boolean(platform.keepAwakeStatus().enabled);
}
function keepAwakeStatus() {
return platform.keepAwakeStatus();
}
function startKeepAwake() {
return platform.startKeepAwake();
}
function stopKeepAwake() {
return platform.stopKeepAwake();
}
function cleanupKeepAwake() {
platform.cleanup();
}
function readCodexConfigText() {
try {
return fs.readFileSync(path.join(os.homedir(), '.codex', 'config.toml'), 'utf8');
} catch {
return '';
}
}
function tomlStringValue(text, key) {
const escaped = key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const match = text.match(new RegExp(`^\\s*${escaped}\\s*=\\s*"([^"]*)"\\s*$`, 'm'));
return match ? match[1] : '';
}
function labelFromModelName(name = '') {
const text = String(name || '').trim();
if (!text) return '';
return text
.replace(/[((].*?[))]/g, '')
.replace(/^GPT-/i, '')
.replace(/^gpt-/i, '')
.replace(/^codex-/i, '')
.trim() || text;
}
function normalizeModelOption(row = {}) {
const id = String(row.slug || row.id || row.model || '').trim();
if (!id) return null;
const displayName = String(row.display_name || row.name || row.label || id).trim();
return {
key: id,
id,
label: labelFromModelName(displayName || id),
displayName: displayName || id,
source: 'local',
};
}
function readModelCatalogOptions() {
const configText = readCodexConfigText();
const catalogPath = tomlStringValue(configText, 'model_catalog_json');
const resolvedPath = catalogPath.startsWith('~') ? path.join(os.homedir(), catalogPath.slice(1)) : catalogPath;
const fallback = () => {
const current = tomlStringValue(configText, 'model');
return current ? [{ key: current, id: current, label: labelFromModelName(current), displayName: current, source: 'local' }] : [];
};
if (!resolvedPath) return fallback();
let stat;
try {
stat = fs.statSync(resolvedPath);
} catch {
return fallback();
}
if (modelCatalogCache.models && modelCatalogCache.path === resolvedPath && modelCatalogCache.mtimeMs === stat.mtimeMs) {
return modelCatalogCache.models;
}
try {
const parsed = JSON.parse(fs.readFileSync(resolvedPath, 'utf8'));
const models = (Array.isArray(parsed.models) ? parsed.models : [])
.filter(row => row && row.visibility !== 'hide')
.map(normalizeModelOption)
.filter(Boolean);
modelCatalogCache = { path: resolvedPath, mtimeMs: stat.mtimeMs, models };
return models.length ? models : fallback();
} catch {
return fallback();
}
}
function findModelOption(id = '') {
const targetId = String(id || '').trim();
if (!targetId) return null;
return readModelCatalogOptions().find(item => item.id === targetId || item.key === targetId) || null;
}
function emptyCodexMiniState() {
return {
pinnedThreadIds: [],
archivedThreadIds: [],
titleOverrides: {},
guiFailureReports: {},
};
}
function readCodexMiniState() {
try {
const parsed = JSON.parse(fs.readFileSync(STATE_FILE, 'utf8'));
return {
pinnedThreadIds: Array.isArray(parsed.pinnedThreadIds) ? parsed.pinnedThreadIds.filter(isCodexThreadId) : [],
archivedThreadIds: Array.isArray(parsed.archivedThreadIds) ? parsed.archivedThreadIds.filter(isCodexThreadId) : [],
titleOverrides: parsed.titleOverrides && typeof parsed.titleOverrides === 'object' ? parsed.titleOverrides : {},
guiFailureReports: normalizeGuiFailureReports(parsed.guiFailureReports),
};
} catch {
return emptyCodexMiniState();
}
}
function writeCodexMiniState(state) {
fs.mkdirSync(STATE_DIR, { recursive: true });
const normalized = {
pinnedThreadIds: [...new Set((state.pinnedThreadIds || []).filter(isCodexThreadId))],
archivedThreadIds: [...new Set((state.archivedThreadIds || []).filter(isCodexThreadId))],
titleOverrides: state.titleOverrides && typeof state.titleOverrides === 'object' ? state.titleOverrides : {},
guiFailureReports: normalizeGuiFailureReports(state.guiFailureReports),
};
fs.writeFileSync(STATE_FILE, `${JSON.stringify(normalized, null, 2)}\n`, 'utf8');
invalidateCodexThreadListCache();
return normalized;
}
function normalizeGuiFailureReports(value) {
const out = {};
if (!value || typeof value !== 'object') return out;
for (const [threadId, rows] of Object.entries(value)) {
if (!isCodexThreadId(threadId) || !Array.isArray(rows)) continue;
const normalizedRows = rows
.map(row => ({
turnId: typeof row.turnId === 'string' ? row.turnId : '',
text: truncateText(normalizeHistoryText(row.text || ''), 2000),
capturedAt: typeof row.capturedAt === 'string' ? row.capturedAt : '',
completedAt: typeof row.completedAt === 'string' ? row.completedAt : '',
source: typeof row.source === 'string' ? row.source : 'unknown',
}))
.filter(row => row.text)
.slice(-GUI_FAILURE_REPORT_LIMIT);
if (normalizedRows.length) out[threadId] = normalizedRows;
}
return out;
}
function setThreadSetMembership(list, threadId, enabled) {
const set = new Set((Array.isArray(list) ? list : []).filter(isCodexThreadId));
if (enabled) set.add(threadId);
else set.delete(threadId);
return [...set];
}
function truncateText(value, max = 700) {
const text = String(value || '').replace(/\s+/g, ' ').trim();
return text.length > max ? `${text.slice(0, max)}…` : text;
}
function extractMessageText(content) {
if (typeof content === 'string') return content;
if (!Array.isArray(content)) return '';
return content.map(item => item && (item.text || item.message || '')).filter(Boolean).join('\n');
}
function normalizeHistoryText(value) {
return String(value || '').replace(/\r\n/g, '\n').trim();
}
function extractPlainTextDeep(value, seen = new Set()) {
if (value == null) return [];
if (typeof value === 'string') return [value];
if (typeof value === 'number' || typeof value === 'boolean') return [String(value)];
if (typeof value !== 'object') return [];
if (seen.has(value)) return [];
seen.add(value);
const out = [];
if (Array.isArray(value)) {
for (const item of value) out.push(...extractPlainTextDeep(item, seen));
return out;
}
for (const key of ['message', 'detail', 'details', 'error', 'reason', 'description', 'status', 'code', 'title', 'text']) {
if (Object.prototype.hasOwnProperty.call(value, key)) out.push(...extractPlainTextDeep(value[key], seen));
}
return out;
}
function isFailureLikePayload(payload = {}) {
const type = String(payload.type || '').toLowerCase();
const status = String(payload.status || '').toLowerCase();
const code = String(payload.code || '').toLowerCase();
return (
/(?:error|fail|failed|failure|timeout|rate_limit|unavailable|overload|abort|cancel|interrupt)/.test(type) ||
/(?:error|fail|failed|failure|timeout|rate_limit|unavailable|overload|abort|cancel|interrupt)/.test(status) ||
/(?:error|fail|failed|failure|timeout|rate_limit|unavailable|overload|abort|cancel|interrupt)/.test(code) ||
payload.error != null ||
payload.detail != null ||
payload.details != null ||
payload.reason != null
);
}
function isTerminalFailurePayload(payload = {}) {
if (!payload || typeof payload !== 'object') return false;
const type = String(payload.type || '').toLowerCase();
return (
type === 'turn_aborted' ||
/(?:^|_)(?:failed|failure|error|timeout|cancelled|canceled|aborted|interrupted)$/.test(type) ||
(
isFailureLikePayload(payload) &&
/(?:abort|cancel|interrupt|fail|error|timeout|unavailable|overload)/.test(type)
)
);
}
function extractFailureTextFromPayload(payload = {}) {
if (!payload || typeof payload !== 'object' || !isFailureLikePayload(payload)) return '';
const text = extractPlainTextDeep(payload)
.map(value => normalizeHistoryText(value))
.filter(Boolean)
.filter(value => !/^(true|false|null|undefined)$/i.test(value))
.join('\n');
return truncateText(text, 1600);
}
function emptyCodexFailureText() {
return 'Codex GUI 这次没有返回可显示回复。会话日志也没有写入可读取的失败提示原文;请在电脑 Codex GUI 查看原始失败提示。';
}
function decodeLogQuotedValue(value) {
const raw = String(value || '');
if (!raw) return '';
try {
return JSON.parse(`"${raw.replace(/"/g, '\\"')}"`);
} catch {
return raw.replace(/\\n/g, '\n').replace(/\\"/g, '"').replace(/\\\\/g, '\\');
}
}
function safeParseJsonText(value) {
try {
return JSON.parse(value);
} catch {
return null;
}
}
function extractJsonAssignment(line, key) {
const marker = `${key}=`;
const start = line.indexOf(marker);
if (start < 0) return null;
const open = line.indexOf('{', start + marker.length);
if (open < 0) return null;
let depth = 0;
let inString = false;
let escaped = false;
for (let i = open; i < line.length; i += 1) {
const ch = line[i];
if (escaped) {
escaped = false;
continue;
}
if (ch === '\\') {
escaped = true;
continue;
}
if (ch === '"') {
inString = !inString;
continue;
}
if (inString) continue;
if (ch === '{') depth += 1;
if (ch === '}') {
depth -= 1;
if (depth === 0) return line.slice(open, i + 1);
}
}
return null;
}
function extractDesktopLogFailureText(line) {
const raw = String(line || '');
if (!/(?:\berror\b|failed|failure|Forbidden|unexpected status|channel affinity|AiMaMi|revoked|Unauthorized)/i.test(raw)) return '';
if (/(?:git\.command\.complete|worker_rpc_response_error|Conversation state not found|Received turn\/(?:started|completed) for unknown conversation|Item not found in turn state)/i.test(raw)) return '';
const candidates = [];
for (const key of ['error', 'result']) {
const jsonText = extractJsonAssignment(raw, key);
const parsed = jsonText ? safeParseJsonText(jsonText) : null;
const directText = parsed && typeof parsed === 'object'
? normalizeHistoryText(parsed.message || parsed.detail || parsed.error || parsed.reason || '')
: '';
const text = parsed ? (directText || extractFailureTextFromPayload(parsed) || truncateText(extractPlainTextDeep(parsed).map(value => normalizeHistoryText(value)).filter(Boolean).join('\n'), 2000)) : '';
if (text) candidates.push(text);
}
for (const key of ['errorMessage', 'message', 'detail']) {
const match = raw.match(new RegExp(`(?:^|\\s)${key}="((?:\\\\.|[^"])*)"`, 'i'));
if (match) candidates.push(decodeLogQuotedValue(match[1]));
}
if (!candidates.length && /(?:unexpected status|Forbidden|channel affinity|AiMaMi)/i.test(raw)) {
candidates.push(raw.replace(/^\S+\s+\w+\s+\[[^\]]+\]\s*/, '').trim());
}
const text = uniqueList(candidates
.map(value => normalizeHistoryText(value))
.filter(Boolean)
.filter(value => !/^Request failed$/i.test(value)))
.join('\n');
return truncateText(text, 2000);
}
function scoreDesktopFailureLine(line, text, options = {}) {
const raw = String(line || '');
const failure = String(text || '');
if (!failure) return 0;
let score = 1;
const threadId = isCodexThreadId(options.threadId) ? options.threadId : '';
const turnId = typeof options.turnId === 'string' ? options.turnId : '';
if (threadId && raw.includes(threadId)) score += 80;
if (turnId && raw.includes(turnId)) score += 80;
if (/Structured turn failed/i.test(failure)) score += 55;
if (/unexpected status|Forbidden|channel affinity|AiMaMi/i.test(failure)) score += 45;
if (/refresh token was revoked|log out and sign in again|access token could not be refreshed/i.test(failure)) score += 45;
if (/Failed to generate thread title/i.test(raw) && /Structured turn failed/i.test(failure)) score += 25;
if (/Conversation state not found|unknown conversation|Failed to write temporary index tree snapshot|remote\.upstream\.url/i.test(failure)) score -= 80;
return score;
}
function recentCodexDesktopLogFiles(referenceMs = Date.now()) {
return walkFiles(CODEX_DESKTOP_LOGS_DIR, file => file.endsWith('.log'))
.map(file => {
try {
const stat = fs.statSync(file);
return { file, mtimeMs: stat.mtimeMs };
} catch {
return null;
}
})
.filter(Boolean)
.filter(item => item.mtimeMs >= referenceMs - GUI_FAILURE_LOG_RECENT_MS)
.sort((a, b) => b.mtimeMs - a.mtimeMs)
.slice(0, 40)
.map(item => item.file);
}
function findCodexDesktopFailureText(options = {}) {
const threadId = isCodexThreadId(options.threadId) ? options.threadId : '';
const turnId = typeof options.turnId === 'string' ? options.turnId : '';
const startedMs = Date.parse(options.startedAt || '') || 0;
const completedMs = Date.parse(options.completedAt || '') || Date.now();
const minMs = startedMs ? startedMs - 60 * 1000 : completedMs - GUI_FAILURE_LOG_RECENT_MS;
const maxMs = completedMs + 2 * 60 * 1000;
const matches = [];
for (const file of recentCodexDesktopLogFiles(completedMs)) {
let lines;
try {
lines = readTailLinesWithLimit(file, GUI_FAILURE_LOG_SCAN_BYTES);
} catch {
continue;
}
for (const line of lines) {
const lineMs = Date.parse(line.slice(0, 24));
if (Number.isFinite(lineMs) && (lineMs < minMs || lineMs > maxMs)) continue;
const text = extractDesktopLogFailureText(line);
const score = scoreDesktopFailureLine(line, text, options);
if (score >= 50) matches.push({ text, lineMs: Number.isFinite(lineMs) ? lineMs : 0, score });
}
}
matches.sort((a, b) => b.score - a.score || b.lineMs - a.lineMs);
return matches[0] ? matches[0].text : '';
}
function findStoredGuiFailureText(threadId, options = {}) {
if (!isCodexThreadId(threadId)) return '';
const rows = readCodexMiniState().guiFailureReports[threadId] || [];
const turnId = typeof options.turnId === 'string' ? options.turnId : '';
if (turnId) {
const exact = [...rows].reverse().find(row => row.turnId === turnId && row.text);
if (exact) return exact.text;
}
const completedMs = Date.parse(options.completedAt || '') || 0;
if (completedMs) {
const close = [...rows].reverse().find(row => {
const rowMs = Date.parse(row.completedAt || row.capturedAt || '') || 0;
return row.text && rowMs && Math.abs(rowMs - completedMs) <= GUI_FAILURE_LOG_RECENT_MS;
});
if (close) return close.text;
}
const latest = rows[rows.length - 1];
return latest && latest.text ? latest.text : '';
}
function storeGuiFailureText(threadId, report = {}) {
if (!isCodexThreadId(threadId)) return '';
const text = truncateText(normalizeHistoryText(report.text || ''), 2000);
if (!text || text === emptyCodexFailureText()) return '';
const state = readCodexMiniState();
const rows = state.guiFailureReports[threadId] || [];
const turnId = typeof report.turnId === 'string' ? report.turnId : '';
const completedAt = typeof report.completedAt === 'string' ? report.completedAt : '';
const existingIndex = rows.findIndex(row => (turnId && row.turnId === turnId) || (completedAt && row.completedAt === completedAt && row.text === text));
const row = {
turnId,
text,
capturedAt: new Date().toISOString(),
completedAt,
source: typeof report.source === 'string' ? report.source : 'codex_desktop',
};
if (existingIndex >= 0) rows[existingIndex] = { ...rows[existingIndex], ...row };
else rows.push(row);
state.guiFailureReports[threadId] = rows.slice(-GUI_FAILURE_REPORT_LIMIT);
writeCodexMiniState(state);
return text;
}
function resolveFailureTextForTurn(threadId, options = {}) {
const sessionText = normalizeHistoryText(options.failureText || '');
if (sessionText) {
storeGuiFailureText(threadId, { ...options, text: sessionText, source: 'codex_session' });
return sessionText;
}
const storedText = findStoredGuiFailureText(threadId, options);
if (storedText) return storedText;
const desktopText = findCodexDesktopFailureText({ ...options, threadId });
if (desktopText) return storeGuiFailureText(threadId, { ...options, text: desktopText, source: 'codex_desktop_log' }) || desktopText;
return '';
}
function cleanUserHistoryText(value) {
const text = normalizeHistoryText(value);
const marker = '## My request for Codex:';
const index = text.indexOf(marker);
if (index >= 0) return normalizeHistoryText(text.slice(index + marker.length));
return text;
}
function isPlaceholderThreadName(value) {
const text = String(value || '').trim().toLowerCase();
if (!text) return true;
return [
'未命名线程',
'未命名',
'untitled',
'untitled thread',
'new thread',
].includes(text);
}
function summarizeThreadTitle(value, maxLength = 34) {
let text = cleanUserHistoryText(value)
.replace(/```[\s\S]*?```/g, ' ')
.replace(/`([^`]+)`/g, '$1')
.replace(/\bsk-[a-zA-Z0-9_-]{12,}\b/g, '[key]')
.replace(/\b[A-Za-z0-9_-]{24,}\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\b/g, '[token]')
.replace(/https?:\/\/\S+/g, '[link]')
.replace(/[#>*_[\]()~]/g, ' ')
.replace(/\s+/g, ' ')
.trim();
if (!text) return '';
if (text.length <= maxLength) return text;
return `${text.slice(0, maxLength).trim()}…`;
}
function walkFiles(dir, predicate, out = []) {
let entries;
try {
entries = fs.readdirSync(dir, { withFileTypes: true });
} catch {
return out;
}
for (const entry of entries) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) walkFiles(full, predicate, out);
else if (predicate(full)) out.push(full);
}
return out;
}
function listCodexSessionFiles(options = {}) {
const now = Date.now();
if (!options.force && codexSessionFilesCache.files.length && now - codexSessionFilesCache.at <= CODEX_SESSION_FILE_CACHE_MS) {
return codexSessionFilesCache.files;
}
const files = walkFiles(CODEX_SESSIONS_DIR, file => file.endsWith('.jsonl'));
codexSessionFilesCache = { at: now, files };
return files;
}
function threadIdFromSessionFile(file) {
return (path.basename(file || '').match(/([a-f0-9]{8}-[a-f0-9-]{27,})\.jsonl$/i) || [])[1] || '';
}
function normalizeComparableMessage(value) {
return cleanUserHistoryText(value).replace(/\s+/g, ' ').trim();
}
function findLatestCodexSessionFile(options = {}) {
const excludeThreadId = isCodexThreadId(options.excludeThreadId) ? options.excludeThreadId : '';
const afterMs = Number(options.afterMs) || 0;
const expectedCwd = validLocalDirectory(options.cwd || '');
const files = listCodexSessionFiles(afterMs ? { force: true } : {});
let best = null;
for (const file of files) {
try {
const stat = fs.statSync(file);
const threadId = threadIdFromSessionFile(file);
if (excludeThreadId && threadId === excludeThreadId) continue;
if (afterMs && stat.mtimeMs < afterMs - 2500) continue;
if (expectedCwd) {
const metaCwd = validLocalDirectory(readSessionMeta(file).cwd || '');
if (metaCwd !== expectedCwd) continue;
}
if (!best || stat.mtimeMs > best.mtimeMs) best = { file, mtimeMs: stat.mtimeMs };
} catch {
// ignore disappearing files
}
}
return best && best.file;
}
function findCodexSessionFileByName(name) {
if (!name || name.includes('/') || name.includes('..')) return null;
const files = listCodexSessionFiles();
return files.find(file => path.basename(file) === name) || null;
}
function findCodexSessionFileByThreadId(threadId) {
if (!isCodexThreadId(threadId)) return null;
const files = listCodexSessionFiles();
let best = null;
for (const file of files) {
if (!path.basename(file).includes(threadId)) continue;
try {
const stat = fs.statSync(file);
if (!best || stat.mtimeMs > best.mtimeMs) best = { file, mtimeMs: stat.mtimeMs };
} catch {}
}
return best && best.file;
}
function isCodexThreadId(value) {
return typeof value === 'string' && /^[a-f0-9]{8}-[a-f0-9-]{27,}$/i.test(value);
}
function codexThreadDeepLink(threadId) {
if (!isCodexThreadId(threadId)) return null;
// Codex desktop's own “Copy app link” action uses codex://threads/<id>.
// The previous codex://local/<id> only brought the app forward on this build,
// but did not navigate the visible UI, so paste could still hit the wrong thread.
return `codex://threads/${threadId}`;
}
function codexNewThreadDeepLink(cwd = '') {
const url = new URL('codex://threads/new');
if (cwd) url.searchParams.set('path', cwd);
return url.toString();
}
const platform = require('./src/platform')({
rootDir: __dirname,
delay,
isCodexThreadId,
codexThreadDeepLink,
codexNewThreadDeepLink,
CODEX_DEEPLINK_SETTLE_MS,
CODEX_APP_FOCUS_SETTLE_MS,
CODEX_CLICK_SETTLE_MS,
CODEX_THREAD_SYNC_FRESH_MS,
});
function readThreadIndex() {
let stat = null;
try { stat = fs.statSync(CODEX_SESSION_INDEX); } catch {}
if (
stat &&
threadIndexCache.byId &&
threadIndexCache.mtimeMs === stat.mtimeMs &&
threadIndexCache.size === stat.size
) {
return new Map(threadIndexCache.byId);
}
const byId = new Map();
try {
const lines = fs.readFileSync(CODEX_SESSION_INDEX, 'utf8').split('\n').filter(Boolean);
for (const line of lines) {
try {
const item = JSON.parse(line);
if (!item.id) continue;
byId.set(item.id, {
id: item.id,
name: item.thread_name || '',
updatedAt: item.updated_at || '',
});
} catch {}
}
} catch {}
if (stat) threadIndexCache = { mtimeMs: stat.mtimeMs, size: stat.size, byId: new Map(byId) };
return byId;
}
function findFirstCodexUserMessage(file, maxBytes = CODEX_TITLE_SCAN_BYTES) {
let stat;
try { stat = fs.statSync(file); } catch { return ''; }
const cacheKey = `${file}:${fileCacheSignature(stat)}:${maxBytes}`;
if (firstUserMessageCache.has(cacheKey)) return firstUserMessageCache.get(cacheKey);
const limit = Math.min(stat.size, maxBytes);
const chunkSize = 64 * 1024;
const maxLineBytes = 2 * 1024 * 1024;
let fd;
let carry = '';
let skippingLongLine = false;
try {
fd = fs.openSync(file, 'r');
const buffer = Buffer.alloc(chunkSize);
let offset = 0;
while (offset < limit) {
const bytes = fs.readSync(fd, buffer, 0, Math.min(chunkSize, limit - offset), offset);
if (!bytes) break;
offset += bytes;
let text = buffer.toString('utf8', 0, bytes);
if (skippingLongLine) {
const newline = text.indexOf('\n');
if (newline < 0) continue;
text = text.slice(newline + 1);
skippingLongLine = false;
}
carry += text;
if (carry.length > maxLineBytes) {
const newline = carry.indexOf('\n');
if (newline < 0) {
carry = '';
skippingLongLine = true;
continue;
}
}
let newlineIndex;
while ((newlineIndex = carry.indexOf('\n')) >= 0) {
const line = carry.slice(0, newlineIndex);
carry = carry.slice(newlineIndex + 1);
if (!line.trim()) continue;
let item;
try { item = JSON.parse(line); } catch { continue; }
const payload = item.payload || {};
if (item.type === 'event_msg' && payload.type === 'user_message') {
const title = summarizeThreadTitle(payload.message || '');
if (title) return boundedSet(firstUserMessageCache, cacheKey, title);
}
}
}
if (carry.trim() && carry.length <= maxLineBytes) {
try {
const item = JSON.parse(carry);
const payload = item.payload || {};
if (item.type === 'event_msg' && payload.type === 'user_message') {
return boundedSet(firstUserMessageCache, cacheKey, summarizeThreadTitle(payload.message || ''));
}
} catch {}
}
} catch {
return '';
} finally {
if (typeof fd === 'number') {
try { fs.closeSync(fd); } catch {}
}
}
return boundedSet(firstUserMessageCache, cacheKey, '');
}
function readSessionMeta(file) {
let stat = null;
try { stat = fs.statSync(file); } catch {}
const cacheKey = stat ? `${file}:${fileCacheSignature(stat)}` : '';
if (cacheKey && sessionMetaCache.has(cacheKey)) return sessionMetaCache.get(cacheKey);
try {
const fd = fs.openSync(file, 'r');
try {
const buffer = Buffer.alloc(64 * 1024);
const bytes = fs.readSync(fd, buffer, 0, buffer.length, 0);
const lines = buffer.toString('utf8', 0, bytes).split('\n').filter(Boolean).slice(0, 80);
for (const line of lines) {
let item;
try { item = JSON.parse(line); } catch { continue; }
if (item.type === 'session_meta' && item.payload) return cacheKey ? boundedSet(sessionMetaCache, cacheKey, item.payload) : item.payload;
}
} finally {
fs.closeSync(fd);
}
} catch {}
return cacheKey ? boundedSet(sessionMetaCache, cacheKey, {}) : {};
}
function userMessageMatchScore(file, sinceMs = 0, text = '') {
const expected = normalizeComparableMessage(text);
const items = readJsonlTailObjects(file, CODEX_TITLE_SCAN_BYTES);
let score = 0;
for (const item of items) {
const payload = item.payload || {};
if (item.type !== 'event_msg' || payload.type !== 'user_message') continue;
const t = Date.parse(item.timestamp || '');
if (sinceMs && Number.isFinite(t) && t < sinceMs - 2500) continue;
const actual = normalizeComparableMessage(payload.message || '');
if (!actual && expected) continue;
score = Math.max(score, 10);
if (Number.isFinite(t)) score += Math.max(0, Math.min(25, Math.round((t - sinceMs) / 1000) + 20));
if (expected && actual) {
if (actual === expected) score += 100;
else if (actual.includes(expected) || expected.includes(actual)) score += 70;
}
}
return score;
}
function findCodexSessionFileForNewSend(options = {}) {
const sinceMs = Number(options.sinceMs) || 0;
const text = typeof options.text === 'string' ? options.text : '';
const expectedCwd = validLocalDirectory(options.cwd || '');
const excludeThreadId = isCodexThreadId(options.excludeThreadId) ? options.excludeThreadId : '';
const files = listCodexSessionFiles({ force: true });
let best = null;
for (const file of files) {
try {
const stat = fs.statSync(file);
const threadId = threadIdFromSessionFile(file);
if (excludeThreadId && threadId === excludeThreadId) continue;
if (sinceMs && stat.mtimeMs < sinceMs - 2500) continue;
let score = userMessageMatchScore(file, sinceMs, text);
if (score <= 0 && text.trim()) continue;
const metaCwd = validLocalDirectory(readSessionMeta(file).cwd || '');
if (expectedCwd) {
if (metaCwd !== expectedCwd) continue;
score += 35;
}
score += Math.max(0, Math.min(20, Math.round((stat.mtimeMs - sinceMs) / 1000) + 10));
if (!best || score > best.score || (score === best.score && stat.mtimeMs > best.mtimeMs)) {
best = { file, score, mtimeMs: stat.mtimeMs };
}
} catch {
// ignore disappearing files
}
}
return best && best.file;
}
async function waitForCodexSessionFileForNewSend(options = {}, timeoutMs = 7000) {
const deadline = Date.now() + timeoutMs;
let file = null;
while (Date.now() <= deadline) {
file = findCodexSessionFileForNewSend(options);
if (file) return file;
await delay(220);
}
return findCodexSessionFileForNewSend(options);
}
function sessionHasUserMessage(file, text, sinceMs = 0) {
if (!file || !fs.existsSync(file)) return false;
const target = normalizeComparableMessage(text);
if (!target) return false;
const items = readJsonlTailObjects(file, CODEX_SESSION_TAIL_BYTES);
for (const item of items) {
const payload = item.payload || {};
if (item.type !== 'event_msg' || payload.type !== 'user_message') continue;
const itemTime = Date.parse(item.timestamp || '') || 0;
if (sinceMs && itemTime && itemTime < sinceMs - 1200) continue;
const message = normalizeComparableMessage(payload.message || '');
if (!message) continue;
if (message === target || message.includes(target) || target.includes(message)) return true;
}
return false;
}
async function waitForUserMessageInSession(file, text, sinceMs = 0, timeoutMs = CODEX_SEND_CONFIRM_TIMEOUT_MS) {
if (!timeoutMs || !file || !String(text || '').trim()) return true;
const deadline = Date.now() + timeoutMs;
while (Date.now() <= deadline) {
if (sessionHasUserMessage(file, text, sinceMs)) return true;
await delay(180);
}
return false;
}
function readJsonlTailObjects(file, maxBytes) {
let stat;
try { stat = fs.statSync(file); } catch { return []; }
const start = Math.max(0, stat.size - maxBytes);
let fd;
try {
fd = fs.openSync(file, 'r');
const buffer = Buffer.alloc(stat.size - start);
fs.readSync(fd, buffer, 0, buffer.length, start);
let text = buffer.toString('utf8');
if (start > 0) {
const firstNewline = text.indexOf('\n');
text = firstNewline >= 0 ? text.slice(firstNewline + 1) : '';
}
return text.split('\n').filter(Boolean).map(line => {
try { return JSON.parse(line); } catch { return null; }
}).filter(Boolean);
} catch {
return [];
} finally {
if (typeof fd === 'number') {
try { fs.closeSync(fd); } catch {}
}
}
}
function summarizeCodexRuntimeItems(items, stat = null) {
let status = 'idle';
let active = false;
let startedAt = '';
let completedAt = '';
let updatedAt = stat ? new Date(stat.mtimeMs).toISOString() : '';
let turnId = '';
let sawRuntimeActivity = false;
let sawTaskMarker = false;
for (const item of items) {
const payload = item.payload || {};
if (item.timestamp) updatedAt = item.timestamp;
if (item.type === 'response_item' || (item.type === 'event_msg' && payload.type && !String(payload.type).startsWith('task_'))) {
sawRuntimeActivity = true;
}
if (item.type === 'turn_context' && payload.turn_id) turnId = payload.turn_id;
if (item.type === 'event_msg' && payload.type === 'task_started') {
sawTaskMarker = true;
status = 'running';
active = true;
startedAt = item.timestamp || startedAt;
completedAt = '';
turnId = payload.turn_id || turnId;
updatedAt = item.timestamp || updatedAt;
}
if (item.type === 'event_msg' && payload.type === 'task_complete') {
sawTaskMarker = true;
status = 'complete';
active = false;
completedAt = item.timestamp || completedAt;
updatedAt = item.timestamp || updatedAt;
}
if (item.type === 'event_msg' && isTerminalFailurePayload(payload)) {
sawTaskMarker = true;
status = 'error';
active = false;
completedAt = item.timestamp || completedAt;
turnId = payload.turn_id || turnId;
updatedAt = item.timestamp || updatedAt;
}
}
return { status, active, startedAt, completedAt, updatedAt, turnId, sawRuntimeActivity, sawTaskMarker };
}
function quickCodexRuntimeFromFile(file, stat = null) {
let fileStat = stat;
if (!fileStat) {
try { fileStat = fs.statSync(file); } catch { fileStat = null; }
}
const cacheKey = fileStat ? `${file}:${fileCacheSignature(fileStat)}` : '';
if (cacheKey && runtimeSummaryCache.has(cacheKey)) return runtimeSummaryCache.get(cacheKey);
const isFresh = fileStat ? Date.now() - fileStat.mtimeMs <= CODEX_RUNTIME_STALE_MS : false;
let runtime = summarizeCodexRuntimeItems(readJsonlTailObjects(file, CODEX_ACTIVITY_TAIL_BYTES), fileStat);
if (
runtime.status === 'idle' &&
runtime.sawRuntimeActivity &&
!runtime.sawTaskMarker &&
isFresh &&
fileStat &&
fileStat.size > CODEX_ACTIVITY_TAIL_BYTES
) {
runtime = summarizeCodexRuntimeItems(readJsonlTailObjects(file, CODEX_ACTIVITY_LOOKBACK_BYTES), fileStat);
}
if (runtime.status === 'idle' && runtime.sawRuntimeActivity && !runtime.sawTaskMarker && isFresh) {
runtime.status = 'running';
runtime.active = true;
}
if (runtime.status === 'running' && fileStat && !isFresh) {
runtime.status = 'idle';
runtime.active = false;
}
const { status, active, startedAt, completedAt, updatedAt, turnId } = runtime;
return cacheKey
? boundedSet(runtimeSummaryCache, cacheKey, { status, active, startedAt, completedAt, updatedAt, turnId }, 600)
: { status, active, startedAt, completedAt, updatedAt, turnId };
}
function displayPathName(cwd) {
if (!cwd) return '对话';
const normalized = path.normalize(cwd);
if (normalized === os.homedir()) return '~';
if (normalized === path.parse(normalized).root) return normalized;
return path.basename(normalized) || normalized;
}
function classifyThreadProject(cwd) {
const normalized = cwd ? path.normalize(cwd) : '';