-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
2225 lines (1968 loc) · 71.9 KB
/
server.js
File metadata and controls
2225 lines (1968 loc) · 71.9 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
'use strict';
const express = require('express');
const path = require('path');
const fs = require('fs');
const os = require('os');
const { randomUUID } = require('crypto');
const { execFileSync } = require('child_process');
const matter = require('gray-matter');
const chokidar = require('chokidar');
const TOML = require('@iarna/toml');
const app = express();
app.use(express.json({ limit: '2mb' }));
const PORT = process.env.PORT || 3131;
const BIND_HOST = process.env.HOST || '127.0.0.1';
const CODEX_DIR = path.resolve(os.homedir(), '.codex');
const PINNED_FILE = path.join(CODEX_DIR, 'codex-map-projects.json');
const SESSION_ROOT = path.join(CODEX_DIR, 'sessions');
const STATE_DB = path.join(CODEX_DIR, 'state_5.sqlite');
const PLUGINS_CACHE_DIR = path.join(CODEX_DIR, '.tmp', 'plugins');
const PLUGINS_ROOT = path.join(PLUGINS_CACHE_DIR, 'plugins');
const MARKETPLACE_PATH = path.join(PLUGINS_CACHE_DIR, '.agents', 'plugins', 'marketplace.json');
const MAX_FILE_BYTES = 512 * 1024;
const TREE_SKIP_DIRS = new Set(['.git', 'cache', 'log', 'logs', '.tmp', 'tmp', 'sqlite', 'vendor_imports']);
const MODEL_PRICING = {
'gpt-5': { input: 2.5e-6, output: 10e-6, cacheRead: 1.25e-6 },
'gpt-5.3-codex': { input: 2.5e-6, output: 10e-6, cacheRead: 1.25e-6 },
'gpt-5.4': { input: 2.5e-6, output: 10e-6, cacheRead: 1.25e-6 },
'gpt-5.4-mini': { input: 0.4e-6, output: 1.6e-6, cacheRead: 0.2e-6 },
'gpt-4o': { input: 2.5e-6, output: 10e-6, cacheRead: 1.25e-6 },
'gpt-4o-mini': { input: 0.15e-6, output: 0.6e-6, cacheRead: 0.075e-6 }
};
const TOOL_DISPLAY_NAMES = {
exec_command: 'Bash',
read_file: 'Read',
write_file: 'Edit',
apply_patch: 'Edit',
apply_diff: 'Edit',
read_dir: 'Glob',
spawn_agent: 'Agent',
wait_agent: 'Agent',
close_agent: 'Agent'
};
const EDIT_TOOLS = new Set(['Edit', 'Write', 'apply_patch', 'write_file']);
const READ_TOOLS = new Set(['Read', 'Grep', 'Glob', 'read_file', 'read_dir']);
const BASH_TOOLS = new Set(['Bash', 'exec_command']);
const TASK_TOOLS = new Set(['TaskCreate', 'TaskUpdate', 'TaskGet', 'TaskList', 'TaskOutput', 'TaskStop', 'TodoWrite']);
const SEARCH_TOOLS = new Set(['WebSearch', 'WebFetch', 'ToolSearch']);
const TEST_PATTERNS = /\b(test|pytest|vitest|jest|mocha|spec|coverage|npm\s+test|npx\s+vitest|npx\s+jest)\b/i;
const GIT_PATTERNS = /\bgit\s+(push|pull|commit|merge|rebase|checkout|branch|stash|log|diff|status|add|reset|cherry-pick|tag)\b/i;
const BUILD_PATTERNS = /\b(npm\s+run\s+build|npm\s+publish|pip\s+install|docker|deploy|make\s+build|npm\s+run\s+dev|npm\s+start|pm2|systemctl|brew|cargo\s+build)\b/i;
const INSTALL_PATTERNS = /\b(npm\s+install|pip\s+install|brew\s+install|apt\s+install|cargo\s+add)\b/i;
const DEBUG_KEYWORDS = /\b(fix|bug|error|broken|failing|crash|issue|debug|traceback|exception|stack\s*trace|not\s+working|wrong|unexpected|status\s+code|404|500|401|403)\b/i;
const FEATURE_KEYWORDS = /\b(add|create|implement|new|build|feature|introduce|set\s*up|scaffold|generate|make\s+(?:a|me|the)|write\s+(?:a|me|the))\b/i;
const REFACTOR_KEYWORDS = /\b(refactor|clean\s*up|rename|reorganize|simplify|extract|restructure|move|migrate|split)\b/i;
const BRAINSTORM_KEYWORDS = /\b(brainstorm|idea|what\s+if|explore|think\s+about|approach|strategy|design|consider|how\s+should|what\s+would|opinion|suggest|recommend)\b/i;
const RESEARCH_KEYWORDS = /\b(research|investigate|look\s+into|find\s+out|check|search|analyze|review|understand|explain|how\s+does|what\s+is|show\s+me|list|compare)\b/i;
const FILE_PATTERNS = /\.(py|js|ts|tsx|jsx|json|yaml|yml|toml|sql|sh|go|rs|java|rb|php|css|html|md|csv|xml)\b/i;
const SCRIPT_PATTERNS = /\b(run\s+\S+\.\w+|execute|scrip?t|curl|api\s+\S+|endpoint|request\s+url|fetch\s+\S+|query|database|db\s+\S+)\b/i;
const URL_PATTERN = /https?:\/\/\S+/i;
const cache = new Map();
const sseClients = new Set();
function invalidateCache() {
cache.clear();
}
function getCacheKey(projectPath) {
return projectPath ? `project:${path.resolve(projectPath)}` : 'global';
}
async function getCachedScan(projectPath) {
const key = getCacheKey(projectPath);
const now = Date.now();
const hit = cache.get(key);
if (hit && (now - hit.ts) < 5000) return hit.data;
const data = await buildScanResult(projectPath);
cache.set(key, { ts: now, data });
return data;
}
function fileExists(filePath) {
try {
fs.accessSync(filePath);
return true;
} catch {
return false;
}
}
function safeReadText(filePath) {
try {
return fs.readFileSync(filePath, 'utf8');
} catch {
return null;
}
}
function safeReadJson(filePath) {
try {
return JSON.parse(fs.readFileSync(filePath, 'utf8'));
} catch {
return null;
}
}
function safeReadToml(filePath) {
try {
return TOML.parse(fs.readFileSync(filePath, 'utf8'));
} catch {
return null;
}
}
function writeText(filePath, content) {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.writeFileSync(filePath, content, 'utf8');
}
function sqlString(value) {
return `'${String(value).replace(/'/g, "''")}'`;
}
function querySqliteJson(dbPath, sql) {
try {
const output = execFileSync('sqlite3', ['-json', dbPath, sql], { encoding: 'utf8' }).trim();
return output ? JSON.parse(output) : [];
} catch {
return [];
}
}
function execSqlite(dbPath, sql) {
execFileSync('sqlite3', [dbPath, sql], { encoding: 'utf8' });
}
function excerpt(text, len = 220) {
if (!text) return '';
const clean = text.replace(/^---[\s\S]*?---\n?/, '').trim();
return clean.length > len ? `${clean.slice(0, len)}…` : clean;
}
function wordCount(text) {
return text ? text.trim().split(/\s+/).length : 0;
}
function ensureArray(value) {
return Array.isArray(value) ? value : value == null ? [] : [value];
}
function emptyTokenUsage() {
return {
inputTokens: 0,
cachedInputTokens: 0,
outputTokens: 0,
reasoningTokens: 0,
totalTokens: 0,
estimatedCostUsd: 0
};
}
function mergeTokenUsage(target, delta) {
target.inputTokens += delta.inputTokens || 0;
target.cachedInputTokens += delta.cachedInputTokens || 0;
target.outputTokens += delta.outputTokens || 0;
target.reasoningTokens += delta.reasoningTokens || 0;
target.totalTokens += delta.totalTokens || 0;
target.estimatedCostUsd += delta.estimatedCostUsd || 0;
return target;
}
function canonicalModelName(model) {
return String(model || '')
.trim()
.replace(/@.*$/, '')
.replace(/-\d{8}$/, '');
}
function getModelPricing(model) {
const canonical = canonicalModelName(model);
if (MODEL_PRICING[canonical]) return MODEL_PRICING[canonical];
for (const [name, pricing] of Object.entries(MODEL_PRICING)) {
if (canonical === name || canonical.startsWith(`${name}-`)) return pricing;
}
return null;
}
function estimateUsageCostUsd(model, usage) {
const pricing = getModelPricing(model);
if (!pricing) return 0;
return (
((usage.inputTokens || 0) * pricing.input) +
(((usage.outputTokens || 0) + (usage.reasoningTokens || 0)) * pricing.output) +
((usage.cachedInputTokens || 0) * pricing.cacheRead)
);
}
function resolveTokenModel(row, state) {
const current = row?.payload?.info?.model || row?.payload?.info?.model_name || row?.payload?.model || state.turnModel || state.sessionModel || 'gpt-5';
return canonicalModelName(current) || 'gpt-5';
}
function createBreakdownEntry(name) {
return {
name,
calls: 0,
turns: 0,
sessions: 0,
...emptyTokenUsage()
};
}
function normalizeToolName(name) {
if (!name) return null;
if (name.startsWith('mcp__')) return name;
return TOOL_DISPLAY_NAMES[name] || name;
}
function mcpServerName(toolName) {
if (!toolName || !toolName.startsWith('mcp__')) return null;
return toolName.split('__')[1] || toolName;
}
function categorizeConversation(userMessage) {
if (BRAINSTORM_KEYWORDS.test(userMessage)) return 'brainstorming';
if (RESEARCH_KEYWORDS.test(userMessage)) return 'exploration';
if (DEBUG_KEYWORDS.test(userMessage)) return 'debugging';
if (FEATURE_KEYWORDS.test(userMessage)) return 'feature';
if (FILE_PATTERNS.test(userMessage)) return 'coding';
if (SCRIPT_PATTERNS.test(userMessage)) return 'coding';
if (URL_PATTERN.test(userMessage)) return 'exploration';
return 'conversation';
}
function refineCategory(category, userMessage) {
if (category === 'coding') {
if (DEBUG_KEYWORDS.test(userMessage)) return 'debugging';
if (REFACTOR_KEYWORDS.test(userMessage)) return 'refactoring';
if (FEATURE_KEYWORDS.test(userMessage)) return 'feature';
return 'coding';
}
if (category === 'exploration') {
if (DEBUG_KEYWORDS.test(userMessage)) return 'debugging';
return 'exploration';
}
return category;
}
function classifyUsageTurn(turn) {
const tools = Object.keys(turn.toolCounts || {});
if (!tools.length) return categorizeConversation(turn.userMessage || '');
if (tools.includes('Agent')) return 'delegation';
if (tools.includes('EnterPlanMode') || tools.some(tool => TASK_TOOLS.has(tool))) return 'planning';
const hasEdits = tools.some(tool => EDIT_TOOLS.has(tool));
const hasReads = tools.some(tool => READ_TOOLS.has(tool));
const hasBash = tools.some(tool => BASH_TOOLS.has(tool));
const hasSearch = tools.some(tool => SEARCH_TOOLS.has(tool));
const hasMcp = tools.some(tool => tool.startsWith('mcp__'));
if (hasBash && !hasEdits) {
const text = turn.userMessage || '';
if (TEST_PATTERNS.test(text)) return 'testing';
if (GIT_PATTERNS.test(text)) return 'git';
if (BUILD_PATTERNS.test(text) || INSTALL_PATTERNS.test(text)) return 'build/deploy';
}
if (hasEdits) return refineCategory('coding', turn.userMessage || '');
if (hasBash && hasReads) return refineCategory('exploration', turn.userMessage || '');
if (hasBash) return refineCategory('coding', turn.userMessage || '');
if (hasSearch || hasMcp) return refineCategory('exploration', turn.userMessage || '');
if (hasReads) return refineCategory('exploration', turn.userMessage || '');
return categorizeConversation(turn.userMessage || '');
}
function createUsageTurn() {
return {
userMessage: '',
timestamp: null,
tokenUpdates: 0,
toolCounts: {},
mcpCounts: {},
...emptyTokenUsage()
};
}
function addTurnTool(turn, rawName) {
const name = normalizeToolName(rawName);
if (!name) return;
turn.toolCounts[name] = (turn.toolCounts[name] || 0) + 1;
const server = mcpServerName(name);
if (server) turn.mcpCounts[server] = (turn.mcpCounts[server] || 0) + 1;
}
function finalizeUsageTurn(turn, session, totals) {
const toolNames = Object.keys(turn.toolCounts);
const hasActivity = turn.totalTokens || turn.estimatedCostUsd || toolNames.length || turn.userMessage;
if (!hasActivity) return;
const category = classifyUsageTurn(turn);
if (!totals.byTaskType[category]) totals.byTaskType[category] = createBreakdownEntry(category);
totals.byTaskType[category].turns += 1;
totals.byTaskType[category].calls += turn.tokenUpdates || 0;
mergeTokenUsage(totals.byTaskType[category], turn);
const projectName = session.cwd || '(unknown)';
if (!totals.byProject[projectName]) {
totals.byProject[projectName] = createBreakdownEntry(projectName);
totals.byProject[projectName].sessions = 1;
}
totals.byProject[projectName].turns += 1;
totals.byProject[projectName].calls += turn.tokenUpdates || 0;
mergeTokenUsage(totals.byProject[projectName], turn);
const toolTotal = Object.values(turn.toolCounts).reduce((sum, count) => sum + count, 0);
if (toolTotal) {
for (const [toolName, count] of Object.entries(turn.toolCounts)) {
if (!totals.byTool[toolName]) totals.byTool[toolName] = createBreakdownEntry(toolName);
totals.byTool[toolName].calls += count;
totals.byTool[toolName].turns += 1;
mergeTokenUsage(totals.byTool[toolName], {
inputTokens: (turn.inputTokens * count) / toolTotal,
cachedInputTokens: (turn.cachedInputTokens * count) / toolTotal,
outputTokens: (turn.outputTokens * count) / toolTotal,
reasoningTokens: (turn.reasoningTokens * count) / toolTotal,
totalTokens: (turn.totalTokens * count) / toolTotal,
estimatedCostUsd: (turn.estimatedCostUsd * count) / toolTotal
});
}
}
const mcpTotal = Object.values(turn.mcpCounts).reduce((sum, count) => sum + count, 0);
if (mcpTotal) {
for (const [serverName, count] of Object.entries(turn.mcpCounts)) {
if (!totals.byMcpServer[serverName]) totals.byMcpServer[serverName] = createBreakdownEntry(serverName);
totals.byMcpServer[serverName].calls += count;
totals.byMcpServer[serverName].turns += 1;
mergeTokenUsage(totals.byMcpServer[serverName], {
inputTokens: (turn.inputTokens * count) / mcpTotal,
cachedInputTokens: (turn.cachedInputTokens * count) / mcpTotal,
outputTokens: (turn.outputTokens * count) / mcpTotal,
reasoningTokens: (turn.reasoningTokens * count) / mcpTotal,
totalTokens: (turn.totalTokens * count) / mcpTotal,
estimatedCostUsd: (turn.estimatedCostUsd * count) / mcpTotal
});
}
}
}
function extractTokenUsage(row, state, scopeKey) {
if (row?.type === 'turn_context' && row.payload?.model) {
state.turnModel = row.payload.model;
if (!state.sessionModel) state.sessionModel = row.payload.model;
return null;
}
if (row?.type === 'session_meta' && row.payload?.model) {
state.sessionModel = row.payload.model;
return null;
}
if (row?.type !== 'event_msg' || row.payload?.type !== 'token_count') return null;
const info = row.payload?.info;
if (!info) return null;
const cumulativeTotal = info.total_token_usage?.total_tokens ?? 0;
const dedupeKey = `${scopeKey}:${row.timestamp || ''}:${cumulativeTotal}`;
if (cumulativeTotal > 0 && state.seen.has(dedupeKey)) return null;
if (cumulativeTotal > 0) state.seen.add(dedupeKey);
const last = info.last_token_usage;
let inputTokens = 0;
let cachedInputTokens = 0;
let outputTokens = 0;
let reasoningTokens = 0;
if (last) {
inputTokens = last.input_tokens ?? 0;
cachedInputTokens = last.cached_input_tokens ?? 0;
outputTokens = last.output_tokens ?? 0;
reasoningTokens = last.reasoning_output_tokens ?? 0;
} else if (cumulativeTotal > 0 && info.total_token_usage) {
inputTokens = (info.total_token_usage.input_tokens ?? 0) - state.prevInput;
cachedInputTokens = (info.total_token_usage.cached_input_tokens ?? 0) - state.prevCached;
outputTokens = (info.total_token_usage.output_tokens ?? 0) - state.prevOutput;
reasoningTokens = (info.total_token_usage.reasoning_output_tokens ?? 0) - state.prevReasoning;
}
if (info.total_token_usage) {
state.prevInput = info.total_token_usage.input_tokens ?? state.prevInput;
state.prevCached = info.total_token_usage.cached_input_tokens ?? state.prevCached;
state.prevOutput = info.total_token_usage.output_tokens ?? state.prevOutput;
state.prevReasoning = info.total_token_usage.reasoning_output_tokens ?? state.prevReasoning;
}
const normalizedUsage = {
inputTokens: Math.max(0, inputTokens - cachedInputTokens),
cachedInputTokens: Math.max(0, cachedInputTokens),
outputTokens: Math.max(0, outputTokens),
reasoningTokens: Math.max(0, reasoningTokens)
};
normalizedUsage.totalTokens = normalizedUsage.inputTokens + normalizedUsage.cachedInputTokens + normalizedUsage.outputTokens + normalizedUsage.reasoningTokens;
if (!normalizedUsage.totalTokens) return null;
const model = resolveTokenModel(row, state);
normalizedUsage.estimatedCostUsd = estimateUsageCostUsd(model, normalizedUsage);
return {
timestamp: row.timestamp || null,
model,
usage: normalizedUsage
};
}
function resolveIfExists(basePath, ...parts) {
const target = path.join(basePath, ...parts);
return fileExists(target) ? target : null;
}
function readAgentsMd(basePath) {
if (!basePath) return null;
const filePath = resolveIfExists(basePath, 'AGENTS.md');
if (!filePath) return null;
const raw = safeReadText(filePath);
if (!raw) return null;
return { path: filePath, raw, excerpt: excerpt(raw, 320) };
}
function buildSkillMeta(frontmatter, fallbackName) {
const data = frontmatter || {};
const allowedToolsRaw = data['allowed-tools'] || data.allowedTools || '';
return {
displayName: data.name || fallbackName,
description: data.description || null,
allowedTools: allowedToolsRaw
? String(allowedToolsRaw).split(',').map(item => item.trim()).filter(Boolean)
: [],
argumentHint: data['argument-hint'] || data.argumentHint || null,
userInvocable: data['user-invocable'] !== false,
agent: data.agent || null
};
}
function readSkillsDir(basePath) {
const skillsDir = path.join(basePath, 'skills');
if (!fileExists(skillsDir)) return [];
const entries = [];
try {
const items = fs.readdirSync(skillsDir).sort();
for (const item of items) {
const itemPath = path.join(skillsDir, item);
const stat = fs.statSync(itemPath);
if (stat.isDirectory()) {
const skillFile = resolveIfExists(itemPath, 'SKILL.md') || resolveIfExists(itemPath, `${item}.md`);
if (!skillFile) continue;
const raw = safeReadText(skillFile);
if (!raw) continue;
const parsed = matter(raw);
entries.push({
name: item,
filename: path.basename(skillFile),
path: skillFile,
raw,
body: parsed.content || raw,
frontmatter: parsed.data || {},
meta: buildSkillMeta(parsed.data, item),
excerpt: excerpt(parsed.content || raw, 180),
hasArgs: raw.includes('$ARGUMENTS'),
isFolder: true,
wordCount: wordCount(raw)
});
continue;
}
if (!item.endsWith('.md')) continue;
const raw = safeReadText(itemPath);
if (!raw) continue;
const parsed = matter(raw);
entries.push({
name: item.replace(/\.md$/, ''),
filename: item,
path: itemPath,
raw,
body: parsed.content || raw,
frontmatter: parsed.data || {},
meta: buildSkillMeta(parsed.data, item.replace(/\.md$/, '')),
excerpt: excerpt(parsed.content || raw, 180),
hasArgs: raw.includes('$ARGUMENTS'),
isFolder: false,
wordCount: wordCount(raw)
});
}
} catch {
return [];
}
return entries;
}
function getSkillsBaseDir(scope, projectPath) {
if (scope === 'project') {
if (!projectPath) throw new Error('Missing projectPath for project-scoped skill operation');
return path.join(path.resolve(projectPath), '.codex', 'skills');
}
return path.join(CODEX_DIR, 'skills');
}
function sanitizeSkillName(name) {
return String(name || '').trim().replace(/[^a-zA-Z0-9._-]/g, '_');
}
function resolveSkillFile(baseDir, name) {
const safeName = sanitizeSkillName(name);
const directFile = path.join(baseDir, `${safeName}.md`);
const folderSkill = path.join(baseDir, safeName, 'SKILL.md');
const folderAlt = path.join(baseDir, safeName, `${safeName}.md`);
if (fileExists(directFile)) return directFile;
if (fileExists(folderSkill)) return folderSkill;
if (fileExists(folderAlt)) return folderAlt;
return directFile;
}
function readConfigToml() {
const filePath = path.join(CODEX_DIR, 'config.toml');
const raw = safeReadText(filePath);
const data = raw ? safeReadToml(filePath) : null;
if (!raw || !data) return null;
return {
path: filePath,
raw,
excerpt: excerpt(raw, 420),
approvalsReviewer: data.approvals_reviewer || null,
personality: data.personality || null,
projects: Object.entries(data.projects || {}).map(([projectPath, cfg]) => ({
path: projectPath,
trustLevel: cfg.trust_level || null
})),
mcpServers: Object.entries(data.mcp_servers || {}).map(([name, cfg]) => ({
name,
command: cfg.command || null,
args: ensureArray(cfg.args),
envKeys: Object.keys(cfg.env || {}),
cwd: cfg.cwd || null
})),
profiles: Object.entries(data.profiles || {}).map(([name, cfg]) => ({
name,
keys: Object.keys(cfg || {})
})),
featureFlags: Object.keys(data.features || {}).filter(key => data.features[key])
};
}
function readConfigTomlDoc() {
const filePath = path.join(CODEX_DIR, 'config.toml');
const raw = safeReadText(filePath) || '';
const data = safeReadToml(filePath) || {};
return { filePath, raw, data };
}
function writeConfigTomlData(data) {
const filePath = path.join(CODEX_DIR, 'config.toml');
const raw = TOML.stringify(data);
writeText(filePath, raw);
invalidateCache();
return summarizeConfigToml(raw, data, filePath);
}
function sessionFilePathFor(id, date = new Date()) {
const year = String(date.getFullYear());
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const stamp = date.toISOString().replace(/\.\d{3}Z$/, '').replace(/:/g, '-');
return path.join(SESSION_ROOT, year, month, day, `rollout-${stamp}-${id}.jsonl`);
}
function createSessionFile({ id, cwd, title, modelProvider = 'openai', cliVersion = '0.120.0' }) {
const now = new Date();
const iso = now.toISOString();
const filePath = sessionFilePathFor(id, now);
const rows = [
{
timestamp: iso,
type: 'session_meta',
payload: {
id,
timestamp: iso,
cwd,
originator: 'codex-map',
cli_version: cliVersion,
source: 'cli',
model_provider: modelProvider
}
},
{
timestamp: iso,
type: 'event_msg',
payload: {
type: 'user_message',
message: title
}
}
];
writeText(filePath, `${rows.map(row => JSON.stringify(row)).join('\n')}\n`);
return { filePath, timestamp: Math.floor(now.getTime() / 1000) };
}
function summarizeConfigToml(raw, data, filePath) {
return {
path: filePath,
raw,
excerpt: excerpt(raw, 420),
approvalsReviewer: data.approvals_reviewer || null,
personality: data.personality || null,
projects: Object.entries(data.projects || {}).map(([projectPath, cfg]) => ({
path: projectPath,
trustLevel: cfg.trust_level || null
})),
mcpServers: Object.entries(data.mcp_servers || {}).map(([name, cfg]) => ({
name,
command: cfg.command || null,
args: ensureArray(cfg.args),
envKeys: Object.keys(cfg.env || {}),
env: cfg.env || {},
cwd: cfg.cwd || null
})),
profiles: Object.entries(data.profiles || {}).map(([name, cfg]) => ({
name,
keys: Object.keys(cfg || {})
})),
featureFlags: Object.keys(data.features || {}).filter(key => data.features[key])
};
}
function readMcpJson(projectPath) {
if (!projectPath) return null;
const candidates = [
path.join(projectPath, '.mcp.json'),
path.join(projectPath, '.codex', '.mcp.json')
];
for (const candidate of candidates) {
const data = safeReadJson(candidate);
if (!data) continue;
return {
path: candidate,
raw: JSON.stringify(data, null, 2),
servers: Object.keys(data.mcpServers || {}),
data
};
}
return null;
}
function readPluginManifests() {
if (!fileExists(PLUGINS_ROOT)) return [];
const marketplace = safeReadJson(MARKETPLACE_PATH) || { plugins: [] };
const marketplaceMap = new Map((marketplace.plugins || []).map(item => [item.name, item]));
const plugins = [];
try {
for (const item of fs.readdirSync(PLUGINS_ROOT).sort()) {
const manifestPath = path.join(PLUGINS_ROOT, item, '.codex-plugin', 'plugin.json');
const manifest = safeReadJson(manifestPath);
if (!manifest) continue;
const market = marketplaceMap.get(item) || {};
plugins.push({
id: manifest.id || item,
name: manifest.name || manifest.id || item,
description: manifest.description || null,
version: manifest.version || null,
category: market.category || manifest.interface?.category || null,
displayName: manifest.interface?.displayName || manifest.name || item,
path: manifestPath,
tools: (manifest.tools || []).length,
prompts: (manifest.prompts || []).length
});
}
} catch {
return [];
}
return plugins;
}
function buildFileTree(basePath, depth = 0, maxDepth = 3) {
let stat;
try {
stat = fs.statSync(basePath);
} catch {
return null;
}
const node = {
name: path.basename(basePath) || basePath,
path: basePath,
isDir: stat.isDirectory(),
size: stat.isDirectory() ? null : stat.size,
children: []
};
if (!node.isDir || depth >= maxDepth) return node;
if (TREE_SKIP_DIRS.has(path.basename(basePath))) return node;
try {
const items = fs.readdirSync(basePath).sort();
for (const item of items) {
if (item.startsWith('.') && !['.codex', '.mcp.json'].includes(item)) continue;
const child = buildFileTree(path.join(basePath, item), depth + 1, maxDepth);
if (child) node.children.push(child);
}
} catch {
return node;
}
return node;
}
function readPinned() {
const data = safeReadJson(PINNED_FILE);
return Array.isArray(data?.projects) ? data.projects : [];
}
function writePinned(projects) {
fs.writeFileSync(PINNED_FILE, JSON.stringify({ projects }, null, 2), 'utf8');
}
function readHistoryEntries(limit = 200) {
const filePath = path.join(CODEX_DIR, 'history.jsonl');
if (!fileExists(filePath)) return [];
const entries = [];
const lines = safeReadText(filePath)?.split('\n').filter(Boolean) || [];
for (const line of lines) {
try {
const row = JSON.parse(line);
entries.push({
sessionId: row.session_id || null,
timestamp: row.ts ? new Date(row.ts * 1000).toISOString() : null,
text: row.text || ''
});
} catch {
continue;
}
}
entries.sort((a, b) => (b.timestamp || '').localeCompare(a.timestamp || ''));
return entries.slice(0, limit);
}
function findSessionFile(sessionId) {
return walkSessionFiles().find(file => file.includes(sessionId)) || null;
}
function readThreadRows(projectPath = null, includeArchived = false) {
if (!fileExists(STATE_DB)) return [];
const filters = [];
if (projectPath) filters.push(`cwd = ${sqlString(path.resolve(projectPath))}`);
if (!includeArchived) filters.push('archived = 0');
const where = filters.length ? `WHERE ${filters.join(' AND ')}` : '';
return querySqliteJson(STATE_DB, `
SELECT id, title, cwd, updated_at, created_at, archived, cli_version, model_provider
FROM threads
${where}
ORDER BY updated_at DESC;
`);
}
function readSessionIndex() {
const filePath = path.join(CODEX_DIR, 'session_index.jsonl');
if (!fileExists(filePath)) return new Map();
const index = new Map();
const lines = safeReadText(filePath)?.split('\n').filter(Boolean) || [];
for (const line of lines) {
try {
const row = JSON.parse(line);
if (!row.id) continue;
index.set(row.id, {
threadName: row.thread_name || null,
updatedAt: row.updated_at || null
});
} catch {
continue;
}
}
return index;
}
function walkSessionFiles() {
const files = [];
if (!fileExists(SESSION_ROOT)) return files;
function walk(dirPath) {
let entries = [];
try {
entries = fs.readdirSync(dirPath, { withFileTypes: true });
} catch {
return;
}
for (const entry of entries) {
const fullPath = path.join(dirPath, entry.name);
if (entry.isDirectory()) walk(fullPath);
if (entry.isFile() && entry.name.endsWith('.jsonl')) files.push(fullPath);
}
}
walk(SESSION_ROOT);
return files;
}
function toolNameFromEventType(type) {
const map = {
exec_command_end: 'exec_command',
patch_apply_end: 'apply_patch',
browser_snapshot_end: 'browser_snapshot',
browser_navigate_end: 'browser_navigate',
browser_click_end: 'browser_click'
};
return map[type] || null;
}
function parseSessionFile(filePath, sessionIndex) {
const raw = safeReadText(filePath);
if (!raw) return null;
let meta = null;
let title = null;
let startedAt = null;
let endedAt = null;
let messageCount = 0;
let toolCallCount = 0;
const toolBreakdown = {};
const tokenUsage = emptyTokenUsage();
const modelBreakdown = {};
const tokenState = {
sessionModel: null,
turnModel: null,
prevInput: 0,
prevCached: 0,
prevOutput: 0,
prevReasoning: 0,
seen: new Set()
};
for (const line of raw.split('\n').filter(Boolean)) {
let row;
try {
row = JSON.parse(line);
} catch {
continue;
}
if (row.timestamp) {
if (!startedAt) startedAt = row.timestamp;
endedAt = row.timestamp;
}
if (row.type === 'session_meta') {
meta = row.payload || {};
if (row.payload?.model) tokenState.sessionModel = row.payload.model;
if (!startedAt && row.payload?.timestamp) startedAt = row.payload.timestamp;
continue;
}
if (row.type === 'event_msg' && row.payload?.type === 'user_message') {
messageCount += 1;
if (!title && row.payload.message) title = String(row.payload.message).slice(0, 120);
continue;
}
if (row.type === 'event_msg' && row.payload?.type === 'agent_message') {
messageCount += 1;
continue;
}
const tokenEntry = extractTokenUsage(row, tokenState, filePath);
if (tokenEntry) {
mergeTokenUsage(tokenUsage, tokenEntry.usage);
if (!modelBreakdown[tokenEntry.model]) {
modelBreakdown[tokenEntry.model] = {
model: tokenEntry.model,
calls: 0,
...emptyTokenUsage()
};
}
modelBreakdown[tokenEntry.model].calls += 1;
mergeTokenUsage(modelBreakdown[tokenEntry.model], tokenEntry.usage);
continue;
}
if (row.type === 'event_msg') {
const tool = toolNameFromEventType(row.payload?.type);
if (!tool) continue;
toolCallCount += 1;
toolBreakdown[tool] = (toolBreakdown[tool] || 0) + 1;
}
}
if (!meta?.id) return null;
const indexed = sessionIndex.get(meta.id) || {};
const stat = fs.statSync(filePath);
return {
id: meta.id,
title: indexed.threadName || title || '(untitled session)',
cwd: meta.cwd || null,
cliVersion: meta.cli_version || null,
modelProvider: meta.model_provider || null,
model: canonicalModelName(tokenState.turnModel || tokenState.sessionModel || meta?.model || '') || null,
source: meta.source || null,
startedAt: startedAt || meta.timestamp || null,
endedAt: endedAt || indexed.updatedAt || null,
updatedAt: indexed.updatedAt || endedAt || stat.mtime.toISOString(),
messageCount,
toolCallCount,
toolBreakdown,
tokenUsage,
modelBreakdown: Object.values(modelBreakdown).sort((a, b) => b.totalTokens - a.totalTokens),
filePath,
fileSize: stat.size
};
}
function listSessions(projectPath = null) {
const sessionIndex = readSessionIndex();
const threadRows = new Map(readThreadRows(projectPath).map(row => [row.id, row]));
const files = walkSessionFiles();
const target = projectPath ? path.resolve(projectPath) : null;
const sessions = [];
for (const filePath of files) {
const session = parseSessionFile(filePath, sessionIndex);
if (!session) continue;
if (target && path.resolve(session.cwd || '') !== target) continue;
const row = threadRows.get(session.id);
if (row?.archived) continue;
if (row?.title) session.title = row.title;
if (row?.updated_at) session.updatedAt = new Date(row.updated_at * 1000).toISOString();
sessions.push(session);
}
sessions.sort((a, b) => (b.updatedAt || '').localeCompare(a.updatedAt || ''));
return sessions;
}
function readSessionDetail(sessionId) {
const sessionIndex = readSessionIndex();
const row = readThreadRows(null, true).find(item => item.id === sessionId) || null;
const filePath = walkSessionFiles().find(file => file.includes(sessionId));
if (!filePath) return null;
const raw = safeReadText(filePath);
if (!raw) return null;
const timeline = [];
const toolBreakdown = {};
let meta = null;
for (const line of raw.split('\n').filter(Boolean)) {
let row;
try {
row = JSON.parse(line);
} catch {
continue;
}
if (row.type === 'session_meta') {
meta = row.payload || {};
timeline.push({
kind: 'meta',
timestamp: row.timestamp || row.payload?.timestamp || null,
title: 'Session started',