-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
6361 lines (5963 loc) · 236 KB
/
Copy pathserver.js
File metadata and controls
6361 lines (5963 loc) · 236 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
import http from 'node:http';
import { spawn } from 'node:child_process';
import { createHash, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
import { appendFile, copyFile, mkdir, readFile, writeFile, stat, rename, readdir, unlink, statfs, readlink, realpath } from 'node:fs/promises';
import { chmodSync, copyFileSync, createReadStream, statSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { createSerialExecutor, createSingleFlight } from './server-concurrency.js';
import { createSqliteMessageStore, stateMetadataSnapshot } from './state-store.js';
import { versionSessionStatus } from './session-status.js';
import { compactBriefMessages } from './public/brief-view.js';
import {
SECRETARY_QUICK_TASKS,
createSecretaryAuditEntry,
normalizeSecretaryControl,
normalizeSecretarySettings,
parseSecretaryAudit,
secretaryAutonomyPrompt,
selectSecretaryTrigger,
secretaryQuickPrompt
} from './secretary-agent.js';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const HOST = process.env.HOST || '127.0.0.1';
const PORT = Number(process.env.PORT || 7072);
const DATA_DIR = process.env.DATA_DIR || path.join(__dirname, 'data');
const PUBLIC_DIR = path.join(__dirname, 'public');
const STATE_FILE = path.join(DATA_DIR, 'state.json');
const MESSAGE_DB_FILE = path.join(DATA_DIR, 'messages.sqlite3');
const RESTART_MARKER_FILE = path.join(DATA_DIR, 'restart-marker.json');
const PASSWORD_FILE = path.join(DATA_DIR, 'admin-password.txt');
const SKILL_REGISTRY_FILE = path.join(DATA_DIR, 'skill-registry.json');
const SECRETARY_AUDIT_FILE = path.join(DATA_DIR, 'secretary-audit.jsonl');
const SECRETARY_PROJECT_DIR = path.resolve(process.env.SECRETARY_PROJECT_DIR || '/root/Projects/secretary-agent');
const SECRETARY_TASK_FILE = path.join(SECRETARY_PROJECT_DIR, 'data', 'tasks.json');
const UPLOAD_DIR = path.join(DATA_DIR, 'uploads');
const CODEX_HOME = process.env.CODEX_HOME || '/root/.codex';
const SKILL_ROOTS = (process.env.SKILL_ROOTS || `${path.join(CODEX_HOME, 'skills')},/root/.agents/skills`)
.split(',')
.map((item) => item.trim())
.filter(Boolean);
const CODEX_BIN = process.env.CODEX_BIN || '/usr/bin/codex';
const CODEX_NODE = process.env.CODEX_NODE || process.execPath;
const CODEX_BIN_DIR = path.dirname(CODEX_BIN);
const COOKIE_NAME = 'cmc_session';
const THIRTY_DAYS = 30 * 24 * 60 * 60 * 1000;
const RUNTIME_DIR = path.join(__dirname, 'runtime');
const SERVICE_STARTED_AT = new Date().toISOString();
const DEFAULT_STORAGE_SETTINGS = {
autoCleanup: false,
uploadRetentionDays: 30,
runtimeRetentionDays: 7,
maxUploadMb: 1024
};
const DEFAULT_APP_UPDATE_SETTINGS = {
autoUpdate: false,
checkIntervalHours: 6
};
const MAX_SESSION_RUNS = 200;
const MAX_RUN_EVENTS = 80;
const MAX_AUDIT_EVENTS = 200;
const SMART_TAG_RULE_VERSION = 4;
const COMMAND_KILL_GRACE_MS = 3000;
const APP_UPDATE_CHECK_TIMEOUT_MS = 18000;
const APP_UPDATE_MANIFEST_URL = process.env.APP_UPDATE_MANIFEST_URL || process.env.UPDATE_MANIFEST_URL || '';
const CODEX_UPGRADE_TIMEOUT_MS = 10 * 60 * 1000;
const PROJECTS_ROOT = path.resolve(process.env.PROJECTS_ROOT || '/root/Projects');
const SITE_MOUNT_ROOT = path.resolve(process.env.SITE_MOUNT_ROOT || '/root/Projects');
const SITE_MOUNT_CANDIDATES = ['dist', 'build', 'out', 'site', 'preview', 'web', '.'];
const SITE_MOUNT_BLOCKED_PARTS = new Set(['.git', '.hg', '.svn', 'node_modules', 'data', 'runtime']);
const SITE_MOUNT_BLOCKED_FILES = new Set(['.env', '.env.local', '.env.production', '.env.development']);
const SITE_MOUNT_SAFE_EXTENSIONS = new Set([
'.html', '.css', '.js', '.mjs', '.json', '.svg', '.png', '.jpg', '.jpeg', '.webp', '.gif',
'.ico', '.txt', '.map', '.wasm', '.woff', '.woff2', '.ttf', '.otf', '.mp3', '.mp4', '.webm'
]);
const contentTypes = {
'.html': 'text/html; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.mjs': 'text/javascript; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.svg': 'image/svg+xml; charset=utf-8',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.webp': 'image/webp',
'.gif': 'image/gif',
'.ico': 'image/x-icon',
'.txt': 'text/plain; charset=utf-8',
'.map': 'application/json; charset=utf-8',
'.wasm': 'application/wasm',
'.woff': 'font/woff',
'.woff2': 'font/woff2',
'.ttf': 'font/ttf',
'.otf': 'font/otf',
'.mp3': 'audio/mpeg',
'.mp4': 'video/mp4',
'.webm': 'video/webm'
};
let adminPassword = '';
let state = {
version: 1,
nextSeq: 1,
authSessions: {},
sessions: {}
};
const clients = new Map();
const running = new Map();
const codexUsageCache = new Map();
const codexMessagesCache = new Map();
const runCodexImportSingleFlight = createSingleFlight();
const runStateWriteSerial = createSerialExecutor();
const secretaryAuditWriteSerial = createSerialExecutor();
const messageStore = createSqliteMessageStore({ databaseFile: MESSAGE_DB_FILE });
const clockTick = Number(process.env.CLK_TCK || 100);
let totalRequests = 0;
let activeRequests = 0;
let packageMetaCache = null;
let skillRegistry = {
version: 1,
roots: SKILL_ROOTS,
skills: [],
lastScanAt: '',
scanStatus: 'idle',
scanError: ''
};
let skillScanPromise = null;
let skillMaintenanceTimer = null;
let skillRegistryFileMtimeMs = 0;
let codexUpgradeTask = null;
let appUpdateTask = null;
let appUpdateMaintenanceTimer = null;
let appAutoUpdateInFlight = false;
let secretaryAutonomyTimer = null;
let secretaryAutonomyInFlight = false;
function commandPath() {
const fallback = `/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:${CODEX_BIN_DIR}`;
const value = process.env.PATH || fallback;
return value.split(path.delimiter).includes(CODEX_BIN_DIR) ? value : `${value}${path.delimiter}${CODEX_BIN_DIR}`;
}
function commandEnv() {
return {
...process.env,
PATH: commandPath(),
GIT_TERMINAL_PROMPT: process.env.GIT_TERMINAL_PROMPT || '0',
GIT_ASKPASS: process.env.GIT_ASKPASS || '/bin/false',
GIT_SSH_COMMAND: process.env.GIT_SSH_COMMAND || 'ssh -o BatchMode=yes -o ConnectTimeout=8 -o StrictHostKeyChecking=accept-new'
};
}
function terminateChildProcess(child, signal = 'SIGTERM') {
if (!child) return;
try {
if (child.pid && process.platform !== 'win32') process.kill(-child.pid, signal);
else child.kill(signal);
} catch {
try {
child.kill(signal);
} catch {
// Best effort. The close/error handler reconciles final state.
}
}
}
async function exists(file) {
try {
await stat(file);
return true;
} catch {
return false;
}
}
async function init() {
await mkdir(DATA_DIR, { recursive: true });
await mkdir(UPLOAD_DIR, { recursive: true });
await loadSkillRegistry();
if (!(await exists(PASSWORD_FILE))) {
const password = randomBytes(18).toString('base64url');
await writeFile(PASSWORD_FILE, `${password}\n`, { mode: 0o600 });
}
adminPassword = (await readFile(PASSWORD_FILE, 'utf8')).trim();
await messageStore.initialize();
if (await exists(STATE_FILE)) {
state = JSON.parse(await readFile(STATE_FILE, 'utf8'));
state.authSessions ||= {};
state.sessions ||= {};
state.hiddenCodexSessions ||= {};
state.codexSessionTitles ||= {};
state.codexSessionTags ||= {};
state.codexSessionProjects ||= {};
state.starredMessages ||= {};
state.siteMounts ||= {};
state.storageSettings = normalizeStorageSettings(state.storageSettings);
state.appUpdateSettings = normalizeAppUpdateSettings(state.appUpdateSettings);
state.secretary = normalizeSecretaryControl(state.secretary);
state.nextSeq ||= 1;
} else {
state.hiddenCodexSessions ||= {};
state.codexSessionTitles ||= {};
state.codexSessionTags ||= {};
state.codexSessionProjects ||= {};
state.starredMessages ||= {};
state.siteMounts ||= {};
state.storageSettings = normalizeStorageSettings(state.storageSettings);
state.appUpdateSettings = normalizeAppUpdateSettings(state.appUpdateSettings);
state.secretary = normalizeSecretaryControl(state.secretary);
await saveState();
}
await recoverSecretaryAuditHead();
const hydratedFromSqlite = await messageStore.hydrateState(state);
if (!hydratedFromSqlite && Object.values(state.sessions || {}).some((session) => Array.isArray(session.messages) && session.messages.length)) {
await saveState();
}
for (const session of Object.values(state.sessions || {})) ensureSessionHarness(session);
retagSessionsIfNeeded();
const restartMarker = await consumeRestartMarker();
reconcileRunningSessions(restartMarker);
pruneAuthSessions();
startStorageMaintenance();
startRunMonitor();
startSkillMaintenance();
startAppUpdateMaintenance();
startSecretaryAutonomy();
}
function normalizeStorageSettings(value = {}) {
return {
autoCleanup: value.autoCleanup === true,
uploadRetentionDays: clampInteger(value.uploadRetentionDays, 0, 3650, DEFAULT_STORAGE_SETTINGS.uploadRetentionDays),
runtimeRetentionDays: clampInteger(value.runtimeRetentionDays, 0, 3650, DEFAULT_STORAGE_SETTINGS.runtimeRetentionDays),
maxUploadMb: clampInteger(value.maxUploadMb, 0, 102400, DEFAULT_STORAGE_SETTINGS.maxUploadMb)
};
}
function normalizeAppUpdateSettings(value = {}) {
return {
autoUpdate: value.autoUpdate === true || (!Object.hasOwn(value, 'autoUpdate') && Boolean(APP_UPDATE_MANIFEST_URL)),
checkIntervalHours: clampInteger(value.checkIntervalHours, 1, 168, DEFAULT_APP_UPDATE_SETTINGS.checkIntervalHours),
lastAutoCheckAt: String(value.lastAutoCheckAt || ''),
lastAutoUpdateAt: String(value.lastAutoUpdateAt || ''),
lastAutoError: String(value.lastAutoError || '').slice(0, 500)
};
}
function cleanShortString(value, limit = 120) {
return String(value || '').trim().replace(/\s+/g, ' ').slice(0, limit);
}
function cleanLineList(value, limit = 12) {
const source = Array.isArray(value) ? value : String(value || '').split(/\r?\n/);
return source
.map((item) => String(item || '').trim())
.filter(Boolean)
.slice(0, limit);
}
function cleanConfigOverrides(value) {
return cleanLineList(value, 20)
.filter((item) => /^[A-Za-z0-9_.-]+\s*=/.test(item))
.map((item) => item.replace(/\s*=\s*/, '='));
}
function normalizeSessionConfig(value = {}, current = {}) {
const sandbox = ['read-only', 'workspace-write', 'danger-full-access'].includes(value.sandbox)
? value.sandbox
: current.sandbox || 'workspace-write';
const approval = ['untrusted', 'on-request', 'on-failure', 'never'].includes(value.approval)
? value.approval
: current.approval || 'on-request';
const reasoningEffort = ['', 'minimal', 'low', 'medium', 'high'].includes(value.reasoningEffort)
? value.reasoningEffort
: current.reasoningEffort || '';
return {
model: cleanShortString(value.model ?? current.model ?? '', 100),
profile: cleanShortString(value.profile ?? current.profile ?? '', 80),
reasoningEffort,
sandbox,
approval,
addDirs: cleanLineList(value.addDirs ?? current.addDirs ?? [], 10),
configOverrides: cleanConfigOverrides(value.configOverrides ?? current.configOverrides ?? []),
strictConfig: value.strictConfig === undefined ? current.strictConfig === true : value.strictConfig === true,
ignoreUserConfig: value.ignoreUserConfig === undefined ? current.ignoreUserConfig === true : value.ignoreUserConfig === true,
ignoreRules: value.ignoreRules === undefined ? current.ignoreRules === true : value.ignoreRules === true
};
}
function parseTopLevelTomlConfig(text = '') {
const result = {};
for (const rawLine of String(text || '').split(/\r?\n/)) {
const line = rawLine.trim();
if (!line || line.startsWith('#')) continue;
if (line.startsWith('[')) break;
const match = line.match(/^([A-Za-z0-9_.-]+)\s*=\s*(.+)$/);
if (!match) continue;
const key = match[1];
let value = match[2].trim();
const commentIndex = value.search(/\s+#/);
if (commentIndex >= 0) value = value.slice(0, commentIndex).trim();
const quoted = value.match(/^"([\s\S]*)"$/) || value.match(/^'([\s\S]*)'$/);
result[key] = quoted ? quoted[1] : value;
}
return result;
}
async function codexConfigSummary() {
const configPath = path.join(CODEX_HOME, 'config.toml');
let topLevel = {};
let exists = false;
try {
topLevel = parseTopLevelTomlConfig(await readFile(configPath, 'utf8'));
exists = true;
} catch {
topLevel = {};
}
let profiles = [];
try {
const entries = await readdir(CODEX_HOME, { withFileTypes: true });
profiles = entries
.filter((entry) => entry.isFile() && entry.name.endsWith('.config.toml'))
.map((entry) => entry.name.replace(/\.config\.toml$/, ''))
.sort((a, b) => a.localeCompare(b))
.slice(0, 30);
} catch {
profiles = [];
}
return {
codexHome: CODEX_HOME,
configPath,
exists,
profiles,
values: {
model: topLevel.model || '',
modelProvider: topLevel.model_provider || '',
reasoningEffort: topLevel.model_reasoning_effort || '',
approvalPolicy: topLevel.approval_policy || '',
sandboxMode: topLevel.sandbox_mode || '',
disableResponseStorage: topLevel.disable_response_storage || '',
preferredAuthMethod: topLevel.preferred_auth_method || ''
}
};
}
function clampInteger(value, min, max, fallback) {
const next = Number(value);
if (!Number.isFinite(next)) return fallback;
return Math.max(min, Math.min(max, Math.floor(next)));
}
async function writeRestartMarker(reason = 'manual') {
const marker = {
version: 1,
reason,
requestedAt: nowIso(),
pid: process.pid,
running: [...running.keys()]
};
const tmp = `${RESTART_MARKER_FILE}.tmp`;
await writeFile(tmp, JSON.stringify(marker, null, 2), { mode: 0o600 });
await rename(tmp, RESTART_MARKER_FILE);
return marker;
}
async function consumeRestartMarker() {
try {
const marker = JSON.parse(await readFile(RESTART_MARKER_FILE, 'utf8'));
await unlink(RESTART_MARKER_FILE).catch(() => {});
return marker;
} catch {
return null;
}
}
function summarizeRunPrompt(activeRun) {
const prompt = String(activeRun?.prompt || '').replace(/\s+/g, ' ').trim();
if (!prompt) return '';
return prompt.length > 180 ? `${prompt.slice(0, 180)}...` : prompt;
}
function compactEventText(value, limit = 800) {
return String(value || '').replace(/\s+/g, ' ').trim().slice(0, limit);
}
function ensureSessionHarness(session) {
if (!session) return session;
session.messages ||= [];
session.queue ||= [];
session.runs = Array.isArray(session.runs) ? session.runs : [];
session.audit = Array.isArray(session.audit) ? session.audit : [];
session.tags = normalizeSessionTags(session.tags || []);
if (session.runs.length > MAX_SESSION_RUNS) session.runs = session.runs.slice(-MAX_SESSION_RUNS);
if (session.audit.length > MAX_AUDIT_EVENTS) session.audit = session.audit.slice(-MAX_AUDIT_EVENTS);
return session;
}
function normalizeSessionTags(tags = []) {
const source = Array.isArray(tags) ? tags : String(tags || '').split(/[,\s,、]+/);
const seen = new Set();
const normalized = [];
for (const raw of source) {
const tag = String(raw || '').trim().replace(/^#/, '').slice(0, 18);
if (!tag || seen.has(tag)) continue;
seen.add(tag);
normalized.push(tag);
if (normalized.length >= 8) break;
}
return normalized;
}
function snapshotSessionTags() {
const web = {};
const codex = {};
for (const [id, session] of Object.entries(state.sessions || {})) {
web[id] = normalizeSessionTags(session.tags || []);
}
for (const [id, tags] of Object.entries(state.codexSessionTags || {})) {
codex[id] = normalizeSessionTags(tags || []);
}
state.lastTagSnapshot = {
version: 1,
createdAt: nowIso(),
web,
codex
};
}
function tagSummaryFromSessions(sessions = []) {
const tags = new Map();
for (const session of sessions) {
for (const tag of normalizeSessionTags(session.tags || [])) {
const item = tags.get(tag) || {
tag,
count: 0,
webCount: 0,
codexCount: 0,
latestActivityAt: ''
};
item.count += 1;
if (session.source === 'codex') item.codexCount += 1;
else item.webCount += 1;
const activityAt = session.activityAt || session.updatedAt || session.createdAt || '';
if (String(activityAt) > String(item.latestActivityAt)) item.latestActivityAt = activityAt;
tags.set(tag, item);
}
}
return [...tags.values()].sort((a, b) => b.count - a.count || a.tag.localeCompare(b.tag, 'zh-Hans-CN'));
}
async function allPublicSessionsForTags() {
const webSessions = Object.values(state.sessions || {}).map(publicSession);
const codexSessions = await listCodexSessions();
return sortPublicSessions([...webSessions, ...codexSessions]);
}
async function tagManagementSummary() {
const sessions = await allPublicSessionsForTags();
return {
tags: tagSummaryFromSessions(sessions),
sessions,
lastSnapshotAt: state.lastTagSnapshot?.createdAt || '',
smartTagRuleVersion: SMART_TAG_RULE_VERSION
};
}
function applyTagTransform(transform) {
let changed = 0;
for (const session of Object.values(state.sessions || {})) {
ensureSessionHarness(session);
const next = normalizeSessionTags(transform(session.tags || []));
if (JSON.stringify(next) === JSON.stringify(normalizeSessionTags(session.tags || []))) continue;
session.tags = next;
auditSession(session, 'tags.updated', { summary: session.tags.join(', ') || 'none' });
changed += 1;
}
state.codexSessionTags ||= {};
for (const [codexSessionId, tags] of Object.entries(state.codexSessionTags)) {
const next = normalizeSessionTags(transform(tags || []));
if (JSON.stringify(next) === JSON.stringify(normalizeSessionTags(tags || []))) continue;
state.codexSessionTags[codexSessionId] = next;
changed += 1;
}
return changed;
}
function inferSessionTags(session) {
const tags = new Set();
const title = String(session.title || '').toLowerCase();
const cwd = String(session.cwd || '');
const base = path.basename(cwd).trim();
const text = [
title,
cwd.toLowerCase()
].join(' ');
const keywordMap = [
['购物', ['购物', '买', '价格', '京东', '淘宝', '苏宁', '商品', '品牌', '好物', '调研', '冰箱', '手机', '笔记本', '电脑', '数码', '烘干机', '洗衣', '家电']],
['学习网站', ['学习', '课程', '教程', '知识库', '文档站', '教育', '笔记', 'academy', 'wiki']],
['开发平台', ['codex', 'console', '平台', '控制台', '开发平台', '开发工具', 'github', 'api', '插件', 'skill', 'skills']],
['服务器维护', ['服务器', '部署', '域名', 'https', 'caddy', 'nginx', 'systemd', '端口', '服务', '重启', '运维', 'ssh']],
['娱乐网站', ['娱乐', '视频', 'youtube', '游戏', '旅行', '旅游', '活动', '世界杯', '音乐', '影视', '上饶', '北海']],
['工作项目', ['客户', '业务', '项目', 'crm', '后台', '管理', '报表']],
['个人工具', ['工具', '效率', '自动化', '脚本', '快捷', '本机']],
['内容创作', ['图片', '截图', '分享', 'markdown', '表格', '文案', '生成', '编辑']],
['问题排查', ['bug', '修复', '报错', '失败', '卡死', '卡顿', '性能', '重试', '恢复']],
['系统设置', ['设置', '配置', 'config', 'profile', 'model', 'sandbox', 'approval']]
];
for (const [tag, words] of keywordMap) {
if (words.some((word) => text.includes(word))) tags.add(tag);
}
if (!tags.size && /\/root\/Projects/i.test(cwd)) tags.add('开发平台');
if (!tags.size && session.source === 'codex') tags.add('开发平台');
if (!tags.size) tags.add('其他');
return normalizeSessionTags([...tags]);
}
function applySmartTagsToState() {
snapshotSessionTags();
const webSessions = Object.values(state.sessions || {});
for (const session of webSessions) {
ensureSessionHarness(session);
session.tags = inferSessionTags(session);
auditSession(session, 'tags.inferred', { summary: session.tags.join(', ') || 'none' });
}
state.codexSessionTags = {};
state.smartTagRuleVersion = SMART_TAG_RULE_VERSION;
return webSessions.length;
}
function retagSessionsIfNeeded() {
if (Number(state.smartTagRuleVersion || 0) >= SMART_TAG_RULE_VERSION) return;
applySmartTagsToState();
scheduleSave();
}
function runAttachments(images = [], files = []) {
return {
imageCount: images.length,
fileCount: files.length,
images: images.slice(0, 12).map((image) => ({
name: image.name || image.fileName || '',
type: image.type || '',
url: image.url || ''
})),
files: files.slice(0, 12).map((file) => ({
name: file.name || file.fileName || '',
type: file.type || '',
size: Number(file.size || 0),
url: file.url || ''
}))
};
}
function auditSession(session, type, detail = {}) {
ensureSessionHarness(session);
const entry = {
id: randomUUID(),
at: nowIso(),
type,
runId: detail.runId || '',
messageId: detail.messageId || '',
summary: compactEventText(detail.summary || detail.error || detail.prompt || detail.status || type, 500)
};
session.audit.push(entry);
if (session.audit.length > MAX_AUDIT_EVENTS) session.audit = session.audit.slice(-MAX_AUDIT_EVENTS);
if (isSecretarySession(session)) {
appendSecretaryAudit(type, {
sessionId: session.id,
runId: entry.runId,
messageId: entry.messageId,
summary: entry.summary
});
}
return entry;
}
function secretaryControl() {
state.secretary = normalizeSecretaryControl(state.secretary);
return state.secretary;
}
function isSecretarySession(session) {
return Boolean(session && (session.kind === 'secretary' || session.id === state.secretary?.sessionId));
}
function appendSecretaryAudit(type, detail = {}) {
const result = createSecretaryAuditEntry(secretaryControl(), { type, ...detail });
state.secretary = result.control;
secretaryAuditWriteSerial(() => appendFile(SECRETARY_AUDIT_FILE, `${JSON.stringify(result.entry)}\n`, { mode: 0o600 }))
.catch((error) => console.error('secretary audit append failed', error));
return result.entry;
}
async function recentSecretaryAudit(limit = 80) {
try {
return parseSecretaryAudit(await readFile(SECRETARY_AUDIT_FILE, 'utf8'), limit);
} catch {
return [];
}
}
async function recoverSecretaryAuditHead() {
const entries = await recentSecretaryAudit(1);
const latest = entries.at(-1);
if (!latest?.hash) return;
const control = secretaryControl();
state.secretary = {
...control,
auditSeq: Math.max(control.auditSeq, Number(latest.seq || 0)),
auditHead: String(latest.hash),
lastEventAt: String(latest.at || control.lastEventAt || '')
};
}
function findRun(session, runId) {
ensureSessionHarness(session);
if (!runId) return null;
return session.runs.find((run) => run.id === runId) || null;
}
function findRunByMessage(session, messageId) {
ensureSessionHarness(session);
if (!messageId) return null;
return session.runs.find((run) => run.userMessageId === messageId || run.clientMessageId === messageId) || null;
}
function latestRun(session) {
ensureSessionHarness(session);
return session.runs.at(-1) || null;
}
function activeRunRecord(session) {
ensureSessionHarness(session);
return findRun(session, session.activeRun?.runId) || findRunByMessage(session, session.activeRun?.messageId) || null;
}
function publicRun(run) {
if (!run) return null;
return {
id: run.id,
userMessageId: run.userMessageId || '',
clientMessageId: run.clientMessageId || '',
status: run.status || 'unknown',
promptSummary: run.promptSummary || summarizeRunPrompt(run),
elevated: run.elevated === true,
origin: run.origin || '',
triggerType: run.triggerType || '',
codexSessionId: run.codexSessionId || '',
pid: run.pid || 0,
queuedAt: run.queuedAt || '',
startedAt: run.startedAt || '',
endedAt: run.endedAt || '',
exitCode: run.exitCode ?? null,
signalCode: run.signalCode || null,
errorCode: run.errorCode || '',
errorSummary: run.errorSummary || '',
tokenSnapshot: run.tokenSnapshot || null,
outputCount: run.outputCount || 0,
toolCount: run.toolCount || 0,
eventCount: Array.isArray(run.events) ? run.events.length : 0,
attachments: run.attachments || { imageCount: 0, fileCount: 0, images: [], files: [] }
};
}
function createHarnessRun(session, props = {}) {
ensureSessionHarness(session);
const existing = props.runId ? findRun(session, props.runId) : null;
if (existing) return existing;
const prompt = String(props.prompt || '');
const run = {
id: props.runId || randomUUID(),
userMessageId: props.messageId || '',
clientMessageId: props.clientMessageId || '',
status: props.status || 'submitted',
prompt: compactText(prompt, 12000),
promptSummary: summarizeRunPrompt({ prompt }),
elevated: props.elevated === true,
origin: String(props.origin || '').slice(0, 40),
triggerType: String(props.triggerType || '').slice(0, 80),
signalId: String(props.signalId || '').slice(0, 120),
codexSessionId: session.codexSessionId || '',
pid: 0,
queuedAt: props.status === 'queued' ? nowIso() : '',
createdAt: nowIso(),
startedAt: '',
endedAt: '',
exitCode: null,
signalCode: null,
errorCode: '',
errorSummary: '',
tokenSnapshot: null,
outputCount: 0,
toolCount: 0,
attachments: runAttachments(props.images || [], props.files || []),
outputMessageIds: [],
events: []
};
session.runs.push(run);
if (session.runs.length > MAX_SESSION_RUNS) session.runs = session.runs.slice(-MAX_SESSION_RUNS);
auditSession(session, 'run.created', { runId: run.id, messageId: run.userMessageId, prompt: run.promptSummary });
return run;
}
function appendRunEvent(session, type, detail = {}, options = {}) {
ensureSessionHarness(session);
const run = findRun(session, options.runId)
|| findRunByMessage(session, options.messageId)
|| activeRunRecord(session)
|| latestRun(session);
if (!run) return null;
const event = {
at: nowIso(),
type,
summary: compactEventText(detail.summary || detail.error || detail.message || detail.text || type, 800)
};
if (detail.exitCode !== undefined) event.exitCode = detail.exitCode;
if (detail.status) event.status = detail.status;
if (detail.errorCode) event.errorCode = detail.errorCode;
if (detail.contextTokens !== undefined) event.contextTokens = detail.contextTokens;
if (detail.contextRemaining !== undefined) event.contextRemaining = detail.contextRemaining;
run.events ||= [];
run.events.push(event);
if (run.events.length > MAX_RUN_EVENTS) run.events = run.events.slice(-MAX_RUN_EVENTS);
if (isSecretarySession(session)) {
appendSecretaryAudit(`run.${type}`, {
sessionId: session.id,
runId: run.id,
messageId: run.userMessageId,
summary: event.summary
});
}
return event;
}
function updateRunStatus(session, runId, status, patch = {}) {
ensureSessionHarness(session);
const run = findRun(session, runId) || findRunByMessage(session, runId);
if (!run) return null;
run.status = status;
Object.assign(run, patch);
if (status === 'queued' && !run.queuedAt) run.queuedAt = nowIso();
if (['running', 'stopping'].includes(status) && !run.startedAt) run.startedAt = nowIso();
if (['completed', 'failed', 'stopped', 'recovered', 'merged'].includes(status)) run.endedAt ||= nowIso();
auditSession(session, `run.${status}`, {
runId: run.id,
messageId: run.userMessageId,
summary: patch.errorSummary || run.promptSummary || status
});
return run;
}
function contextHealthFromUsage(usage) {
if (!usage?.modelContextWindow) {
return { state: 'unknown', label: '上下文未知', severity: 'neutral', action: '' };
}
if (codexContextIsFull(usage)) {
return {
state: 'full',
label: '上下文已满',
severity: 'danger',
action: 'new_session',
detail: `${usage.contextTokens}/${usage.modelContextWindow}`
};
}
if (usage.contextPercent >= 90 || usage.contextRemaining <= 16000) {
return {
state: 'warning',
label: '上下文接近上限',
severity: 'warn',
action: 'compact_or_new_session',
detail: `${usage.contextTokens}/${usage.modelContextWindow}`
};
}
return {
state: 'ok',
label: '上下文正常',
severity: 'ok',
action: '',
detail: `${usage.contextTokens}/${usage.modelContextWindow}`
};
}
function queueStatusFingerprint(queue = []) {
const compact = queue.map((item) => ({
id: item.id || '',
runId: item.runId || '',
messageId: item.messageId || '',
clientMessageId: item.clientMessageId || '',
prompt: item.displayPrompt || item.prompt || '',
elevated: item.elevated === true,
createdAt: item.createdAt || '',
images: (item.images || []).map((image) => [image.id || '', image.name || image.fileName || '', image.path || '', image.url || '']),
files: (item.files || []).map((file) => [file.id || '', file.name || file.fileName || '', file.path || '', file.url || '', Number(file.size || 0)])
}));
return createHash('sha256').update(JSON.stringify(compact)).digest('hex');
}
function classifyCodexFailure({ code, lastError = '', session, spawnError = null, wasStopping = false } = {}) {
const errorText = String(lastError || spawnError?.message || '').trim();
if (wasStopping) return { code: 'process_killed', retryable: true, summary: '任务已停止。' };
if (codexContextIsFull(session?.lastCodexUsage)) {
return {
code: 'context_full',
retryable: false,
summary: `Codex 上下文已满(${session.lastCodexUsage.contextTokens}/${session.lastCodexUsage.modelContextWindow} tokens),请新建干净会话或先压缩原生会话。`
};
}
if (spawnError?.code === 'ENOENT') {
return { code: 'codex_not_found', retryable: false, summary: 'Codex 命令不可用,检查 CODEX_BIN 或 PATH。' };
}
if (/no such file or directory|cwd|ENOENT/i.test(errorText)) {
return { code: 'cwd_missing', retryable: false, summary: `工作目录或文件不存在:${compactEventText(errorText, 260)}` };
}
if (/permission denied|EACCES/i.test(errorText)) {
return { code: 'permission_denied', retryable: true, summary: `权限不足:${compactEventText(errorText, 260)}` };
}
if (/stream disconnected|upstream request failed|reconnecting/i.test(errorText)) {
return { code: 'upstream_disconnected', retryable: true, summary: `Codex 上游连接中断:${compactEventText(errorText, 260)}` };
}
if (code !== undefined && code !== 0) {
return {
code: 'unknown_exit',
retryable: true,
summary: errorText ? `Codex 退出码 ${code}:${compactEventText(errorText, 260)}` : `Codex 退出码 ${code}。`
};
}
return { code: 'unknown', retryable: true, summary: errorText || '未知 Codex 失败。' };
}
function deriveSessionStatusSummary(session) {
ensureSessionHarness(session);
const runtimeRunning = running.has(session.id);
const active = activeRunRecord(session);
const isStopping = runtimeRunning && session.status === 'stopping';
const queueCount = session.queue.length;
const contextHealth = contextHealthFromUsage(session.lastCodexUsage);
let status = 'idle';
if (runtimeRunning) status = isStopping ? 'stopping' : 'running';
else if (session.status === 'error') status = 'error';
else if (queueCount > 0) status = 'queued';
else if (['running', 'stopping'].includes(session.status)) status = 'idle';
else status = session.status || 'idle';
const labels = {
running: '运行中',
stopping: '停止中',
queued: '有排队',
error: '失败',
idle: '空闲'
};
const previousRevision = Number(session.statusRevision || 0);
const summary = versionSessionStatus(session, {
status,
label: labels[status] || status,
running: runtimeRunning,
canStop: runtimeRunning && !isStopping,
queueCount,
activeRunId: active?.id || session.activeRun?.runId || '',
lastRunStatus: latestRun(session)?.status || '',
contextHealth
}, nowIso, queueStatusFingerprint(session.queue));
if (summary.revision !== previousRevision) scheduleSave();
return summary;
}
function reconcileRunningSessions(restartMarker = null) {
const planned = Boolean(restartMarker);
for (const session of Object.values(state.sessions || {})) {
ensureSessionHarness(session);
if (session.status === 'running' || session.status === 'stopping') {
const activeRun = session.activeRun;
const promptSummary = summarizeRunPrompt(activeRun);
session.status = planned ? 'idle' : 'error';
if (activeRun?.messageId) {
updateMessageRunState(session, activeRun.messageId, planned ? 'recovered' : 'failed', {
delivery: planned ? 'recovered' : 'failed'
});
}
updateRunStatus(session, activeRun?.runId || activeRun?.messageId, planned ? 'recovered' : 'failed', {
errorCode: planned ? 'service_restarted' : 'service_crashed',
errorSummary: planned
? 'Service restarted with a recovery marker.'
: 'Service restarted unexpectedly while Codex was running.'
});
delete session.activeRun;
auditSession(session, planned ? 'service.restart.recovered' : 'service.restart.unexpected', {
runId: activeRun?.runId || '',
messageId: activeRun?.messageId || '',
summary: promptSummary
});
addMessage(session, {
role: 'system',
text: [
planned
? 'Service restarted with a recovery marker. The session was restored to an operable state.'
: 'Service restarted unexpectedly while Codex was running. The session status was reconciled.',
promptSummary ? `Interrupted prompt: ${promptSummary}` : '',
'The interrupted prompt was not replayed automatically to avoid repeating file changes or commands.'
].filter(Boolean).join('\n'),
status: session.status,
queuedCount: session.queue.length
});
}
}
}
function updateMessageRunState(session, messageId, runState, extra = {}) {
if (!messageId) return null;
const message = (session.messages || []).find((item) => item.id === messageId || item.clientMessageId === messageId);
if (!message) return null;
message.runState = runState;
message.completedAt = ['completed', 'failed', 'stopped', 'recovered', 'merged'].includes(runState) ? nowIso() : message.completedAt;
Object.assign(message, extra);
messageStore.markSessionDirty(session.id);
scheduleSave();
broadcastEvent(session.id, 'message_update', message);
return message;
}
function queueItemMatchesId(item, id) {
return item?.id === id || item?.clientMessageId === id || item?.messageId === id;
}
function mergeQueuedItems(session, selectedIds = []) {
session.queue ||= [];
const ids = Array.isArray(selectedIds) ? selectedIds.map((id) => String(id || '').trim()).filter(Boolean) : [];
const selected = ids.length
? session.queue.filter((item) => ids.some((id) => queueItemMatchesId(item, id)))
: session.queue;
if (selected.length < 2) return null;
const selectedSet = new Set(selected.map((item) => item.id || item.clientMessageId || item.messageId));
const isSelected = (item) => selectedSet.has(item.id || item.clientMessageId || item.messageId);
const items = selected;
let imageCursor = 1;
const mergedPrompt = [
'以下是合并后的多条排队输入,请按顺序一起处理:',
'每条输入的“对应图片”和“对应文件”指合并后附件顺序,请不要混用不同输入的附件。',
...items.map((item, index) => {
const prompt = String(item.displayPrompt || item.prompt || '').trim() || '(空输入)';
const images = item.images || [];
const files = item.files || [];
let imageText = '对应图片:无';
if (images.length) {
const start = imageCursor;
const end = imageCursor + images.length - 1;
imageCursor = end + 1;
const range = start === end ? `第 ${start} 张` : `第 ${start}-${end} 张`;
const names = images
.map((image, imageIndex) => `${start + imageIndex}. ${image.name || '未命名图片'}`)
.join('\n');
imageText = `对应图片:${range}\n图片清单:\n${names}`;
}
const fileText = files.length
? `对应文件:\n${files.map((file, fileIndex) => `${fileIndex + 1}. ${file.name || file.fileName || '未命名文件'}\n 路径: ${file.path}\n 类型: ${file.type || '未知'}\n 大小: ${uploadSizeText(file.size)}`).join('\n')}`
: '对应文件:无';
return `\n## ${index + 1}\n${imageText}\n${fileText}\n内容:\n${prompt}`;
})
].join('\n');
const mergedImages = items.flatMap((item) => item.images || []);
const mergedFiles = items.flatMap((item) => item.files || []);
const primary = items[0];
primary.prompt = mergedPrompt;
primary.displayPrompt = mergedPrompt;
primary.elevated = items.some((item) => item.elevated === true);
primary.images = mergedImages;
primary.files = mergedFiles;
const primaryRun = findRun(session, primary.runId);
if (primaryRun) {
primaryRun.prompt = compactText(mergedPrompt, 12000);
primaryRun.promptSummary = summarizeRunPrompt({ prompt: mergedPrompt });
primaryRun.elevated = primary.elevated;
primaryRun.attachments = runAttachments(mergedImages, mergedFiles);
appendRunEvent(session, 'queue.merged_primary', { summary: `merged ${items.length} queued inputs` }, { runId: primaryRun.id });
}
let inserted = false;
session.queue = session.queue.flatMap((item) => {
if (!isSelected(item)) return [item];
if (inserted) return [];
inserted = true;
return [primary];
});
const primaryMessage = (session.messages || []).find((entry) => entry.id === primary.messageId || entry.clientMessageId === primary.clientMessageId);
if (primaryMessage) {
primaryMessage.text = mergedPrompt;
primaryMessage.images = mergedImages;
primaryMessage.files = mergedFiles;
primaryMessage.elevated = primary.elevated;
primaryMessage.updatedAt = nowIso();
messageStore.markSessionDirty(session.id);
broadcastEvent(session.id, 'message_update', primaryMessage);
}
for (const item of items.slice(1)) {
updateMessageRunState(session, item.messageId || item.clientMessageId, 'merged', { delivery: 'merged' });
updateRunStatus(session, item.runId || item.messageId || item.clientMessageId, 'merged', {