-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.mjs
More file actions
1125 lines (1008 loc) · 41.1 KB
/
Copy pathindex.mjs
File metadata and controls
1125 lines (1008 loc) · 41.1 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
import fs from 'node:fs'
import path from 'node:path'
import os from 'node:os'
import http from 'node:http'
import { fileURLToPath } from 'node:url'
import { exec, spawn } from 'node:child_process'
import { maskSecrets } from './lib/secretMask.mjs'
import { createHookCollector } from './lib/hookExtract.mjs'
import { createModelResponseCounter, isAggregatableModel } from './lib/modelAttribution.mjs'
import { scanHooks, matchHookEntries, buildHookTelemetryRows, toPublicHookEntries, toServerHookEntries } from './lib/hookScan.mjs'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'package.json'), 'utf-8'))
if (process.argv.includes('--version') || process.argv.includes('-v')) {
console.log(`memradar v${pkg.version}`)
process.exit(0)
}
async function checkForUpdate() {
try {
const res = await fetch('https://registry.npmjs.org/memradar/latest', {
signal: AbortSignal.timeout(4000),
})
if (!res.ok) return null
const data = await res.json()
return data.version || null
} catch {
return null
}
}
async function handleUpdate(latest) {
if (!latest || latest === pkg.version) return
console.log(` ── 새 버전 감지: v${pkg.version} → v${latest} — 최신 버전으로 재실행합니다 ──`)
console.log()
await new Promise((resolve) => {
const args = [`memradar@${latest}`, ...process.argv.slice(2)]
// Child가 또 자기 자신을 자동 업데이트하려 시도하면 npx 캐시 갱신 전까지
// 무한 재시도가 발생할 수 있어 child에서는 update check를 끈다.
const child = spawn('npx', ['--yes', ...args], {
stdio: 'inherit',
shell: true,
env: { ...process.env, MEMRADAR_SKIP_UPDATE_CHECK: '1' },
})
child.on('close', resolve)
child.on('error', () => {
console.log(` 자동 업데이트 실패. npx memradar@latest 로 직접 실행해주세요.`)
resolve()
})
})
process.exit(0)
}
const noUpdateCheck =
process.argv.includes('--no-update-check') ||
process.env.MEMRADAR_SKIP_UPDATE_CHECK === '1'
const updateCheckPromise = noUpdateCheck
? Promise.resolve(null)
: checkForUpdate()
// ─── npm 공개 다운로드 집계 ──────────────────────────────────────────
// 대시보드 상단의 "지금까지 N번 불려나왔어요" 한 줄을 채우는 값.
//
// 프라이버시 계약: 세션·기기·경로 등 로컬 정보를 쿼리·헤더·바디 어디에도
// 싣지 않는 단방향 GET 이다 (checkForUpdate 와 동일한 성격). 나가는 것은
// "memradar 다운로드 수 얼마?" 질문뿐이고 들어오는 것은 숫자 하나다.
// --no-update-check / MEMRADAR_SKIP_UPDATE_CHECK=1 로 업데이트 체크와 함께
// 꺼진다 — 두 호출 모두 npm 을 향하므로 스위치를 하나로 유지한다.
/** memradar 최초 배포(2026-04-13) 직전. 이보다 이른 구간은 npm 이 항상 0 으로 응답한다. */
const NPM_STATS_SINCE = '2026-04-01'
/** api.npmjs.org point API 는 18개월을 넘는 구간을 거부하므로 12개월씩 끊는다. */
const NPM_STATS_CHUNK_MONTHS = 12
const toIsoDay = (date) => date.toISOString().slice(0, 10)
/** [start, end] ISO 날짜 쌍 목록 — 배포일부터 오늘까지를 API 한도 안쪽으로 분할. */
function npmStatChunks(sinceIso, untilIso) {
const chunks = []
const until = new Date(`${untilIso}T00:00:00Z`)
let cursor = new Date(`${sinceIso}T00:00:00Z`)
while (cursor <= until) {
const stop = new Date(cursor)
stop.setUTCMonth(stop.getUTCMonth() + NPM_STATS_CHUNK_MONTHS)
stop.setUTCDate(stop.getUTCDate() - 1)
const end = stop > until ? until : stop
chunks.push([toIsoDay(cursor), toIsoDay(end)])
cursor = new Date(end)
cursor.setUTCDate(cursor.getUTCDate() + 1)
}
return chunks
}
async function fetchNpmDownloads() {
const until = toIsoDay(new Date())
try {
const totals = await Promise.all(
npmStatChunks(NPM_STATS_SINCE, until).map(async ([start, end]) => {
const res = await fetch(`https://api.npmjs.org/downloads/point/${start}:${end}/memradar`, {
signal: AbortSignal.timeout(4000),
})
if (!res.ok) throw new Error(`npm stats ${res.status}`)
const data = await res.json()
if (typeof data?.downloads !== 'number') throw new Error('npm stats shape')
return data.downloads
})
)
// 한 조각이라도 실패하면 부분합을 내보내지 않는다 — 틀린 수보다 없는 편이 낫다.
return { total: totals.reduce((sum, n) => sum + n, 0), since: NPM_STATS_SINCE, until }
} catch {
return null
}
}
const npmDownloadsPromise = noUpdateCheck
? Promise.resolve(null)
: fetchNpmDownloads()
const distDir = path.join(__dirname, '..', 'dist')
const shouldOpenBrowser = process.env.MEMRADAR_NO_OPEN !== '1'
const isStaticMode = !process.argv.includes('--server')
const DEFAULT_PORT = parseInt(process.env.MEMRADAR_PORT || '3939', 10)
// --host <value> 또는 MEMRADAR_HOST 로 바인딩 인터페이스 변경.
// 기본은 127.0.0.1(localhost) — 의도적으로 loopback 만 노출.
// 0.0.0.0 / LAN IP 지정 시 같은 네트워크의 다른 기기에서 접근 가능.
function parseHostArg(argv) {
const i = argv.indexOf('--host')
if (i >= 0 && i + 1 < argv.length) return argv[i + 1]
return process.env.MEMRADAR_HOST || '127.0.0.1'
}
const SERVER_HOST = parseHostArg(process.argv)
function isLoopbackHost(host) {
return host === '127.0.0.1' || host === 'localhost' || host === '::1'
}
function getLanIps() {
const ifaces = os.networkInterfaces()
const ips = []
for (const name of Object.keys(ifaces)) {
for (const iface of ifaces[name] || []) {
if (iface.family === 'IPv4' && !iface.internal) ips.push(iface.address)
}
}
return ips
}
// ─── Common utilities ────────────────────────────────────────────────
function getLogRoots() {
const claudeDir = process.env.MEMRADAR_PROJECTS_DIR || path.join(os.homedir(), '.claude', 'projects')
const codexDir = process.env.MEMRADAR_CODEX_DIR || (
process.env.MEMRADAR_PROJECTS_DIR
? ''
: path.join(os.homedir(), '.codex', 'sessions')
)
return [
{ source: 'claude', dir: claudeDir },
...(codexDir ? [{ source: 'codex', dir: codexDir }] : []),
].filter((entry) => entry.dir)
}
const SKIP_DIRS = new Set(['subagents', 'node_modules', '.git', '.private', '.cache'])
function parseFrontmatter(text) {
if (!text.startsWith('---')) return { frontmatter: {}, body: text }
const end = text.indexOf('\n---', 3)
if (end === -1) return { frontmatter: {}, body: text }
const fmText = text.slice(3, end).replace(/^\r?\n/, '')
const body = text.slice(end + 4).replace(/^\r?\n/, '')
const fm = {}
const lines = fmText.split(/\r?\n/)
let i = 0
while (i < lines.length) {
const line = lines[i]
const m = line.match(/^([A-Za-z0-9_-]+):\s*(.*)$/)
if (!m) { i++; continue }
const key = m[1]
let value = m[2]
if (value === '|' || value === '|-' || value === '>') {
const collected = []
i++
while (i < lines.length && /^\s+/.test(lines[i])) {
collected.push(lines[i].replace(/^\s+/, ''))
i++
}
fm[key] = collected.join(' ').trim()
continue
}
fm[key] = value.replace(/^["']|["']$/g, '').trim()
i++
}
return { frontmatter: fm, body }
}
function summarizeDescription(raw) {
if (!raw) return ''
const flat = raw.replace(/\s+/g, ' ').trim()
if (flat.length <= 140) return flat
return flat.slice(0, 137).trimEnd() + '…'
}
function readSkillFile(filePath) {
try {
return fs.readFileSync(filePath, 'utf-8')
} catch {
return null
}
}
function extractCommandDescription(text) {
const { frontmatter, body } = parseFrontmatter(text)
if (frontmatter.description) return summarizeDescription(frontmatter.description)
const firstLine = body.split(/\r?\n/).find((line) => line.trim().length > 0) || ''
const headingMatch = firstLine.match(/^#+\s*\/?[\w:-]+\s*[-—]\s*(.+)$/)
if (headingMatch) return summarizeDescription(headingMatch[1])
const plain = firstLine.replace(/^#+\s*/, '').trim()
return summarizeDescription(plain)
}
function scanDir(dir, predicate, collect, depth = 0) {
if (depth > 8) return
let entries
try {
entries = fs.readdirSync(dir, { withFileTypes: true })
} catch {
return
}
for (const entry of entries) {
const full = path.join(dir, entry.name)
if (entry.isDirectory()) {
if (SKIP_DIRS.has(entry.name)) continue
scanDir(full, predicate, collect, depth + 1)
} else if (entry.isFile() && predicate(entry.name, full)) {
collect(full)
}
}
}
function scanSkills() {
const home = os.homedir()
const descriptions = {}
const setIfMissing = (name, desc) => {
if (!name || descriptions[name]) return
if (!desc) return
descriptions[name] = desc
}
const personalCommandsDir = path.join(home, '.claude', 'commands')
scanDir(
personalCommandsDir,
(name) => name.endsWith('.md') && !name.endsWith('.tmpl.md') && !name.startsWith('_'),
(full) => {
const text = readSkillFile(full)
if (!text) return
const rel = path.relative(personalCommandsDir, full).replace(/\\/g, '/')
const name = rel.replace(/\.md$/, '')
setIfMissing(name, extractCommandDescription(text))
}
)
const personalSkillsDir = path.join(home, '.claude', 'skills')
scanDir(
personalSkillsDir,
(name) => name === 'SKILL.md',
(full) => {
const text = readSkillFile(full)
if (!text) return
const { frontmatter } = parseFrontmatter(text)
const name = frontmatter.name || path.basename(path.dirname(full))
setIfMissing(name, summarizeDescription(frontmatter.description))
}
)
const pluginsManifest = path.join(home, '.claude', 'plugins', 'installed_plugins.json')
let plugins = {}
try {
plugins = JSON.parse(fs.readFileSync(pluginsManifest, 'utf-8')).plugins || {}
} catch {
plugins = {}
}
for (const [key, entries] of Object.entries(plugins)) {
const pluginName = key.split('@')[0]
const entry = Array.isArray(entries) ? entries[entries.length - 1] : null
const installPath = entry?.installPath
if (!installPath || !fs.existsSync(installPath)) continue
const skillsDir = path.join(installPath, 'skills')
scanDir(
skillsDir,
(name) => name === 'SKILL.md',
(full) => {
const text = readSkillFile(full)
if (!text) return
const { frontmatter } = parseFrontmatter(text)
const skillName = frontmatter.name || path.basename(path.dirname(full))
const desc = summarizeDescription(frontmatter.description)
setIfMissing(`${pluginName}:${skillName}`, desc)
setIfMissing(skillName, desc)
}
)
const commandsDir = path.join(installPath, 'commands')
scanDir(
commandsDir,
(name) => name.endsWith('.md') && !name.endsWith('.tmpl.md') && !name.startsWith('_'),
(full) => {
const text = readSkillFile(full)
if (!text) return
const rel = path.relative(commandsDir, full).replace(/\\/g, '/')
const cmdName = rel.replace(/\.md$/, '')
const desc = extractCommandDescription(text)
setIfMissing(`${pluginName}:${cmdName}`, desc)
setIfMissing(cmdName, desc)
}
)
}
return descriptions
}
function findJsonlFiles(dir, files = [], depth = 0) {
if (depth > 12) return files
try {
const real = fs.realpathSync(dir)
if (real !== dir && files._visited?.has(real)) return files
files._visited ??= new Set()
files._visited.add(real)
const entries = fs.readdirSync(dir, { withFileTypes: true })
for (const entry of entries) {
const fullPath = path.join(dir, entry.name)
if (entry.isDirectory() && !SKIP_DIRS.has(entry.name)) {
findJsonlFiles(fullPath, files, depth + 1)
} else if (entry.isFile() && entry.name.endsWith('.jsonl')) {
files.push(fullPath)
}
}
} catch { }
return files
}
// exec() 로 띄운 런처는 부모가 곧바로 process.exit() 하면 실행 전에 죽는다 (win32 확인).
// 정적 모드는 열자마자 종료하므로 반드시 이 Promise 를 await 해야 한다.
function openBrowser(url) {
const cmd = process.platform === 'win32'
? `start "" "${url}"`
: process.platform === 'darwin'
? `open "${url}"`
: `xdg-open "${url}"`
return new Promise((resolve) => {
exec(cmd, () => resolve())
})
}
// ─── Dist check ──────────────────────────────────────────────────────
if (!fs.existsSync(distDir)) {
console.error('dist/ folder not found. Run `npm run build` first.')
process.exit(1)
}
const logRoots = getLogRoots()
// ─── Parser functions (shared by server and static modes) ────────────
function extractText(content) {
if (typeof content === 'string') return content
if (!Array.isArray(content)) return ''
return content.filter((block) => block.type === 'text' && block.text).map((block) => block.text).join('\n')
}
function extractToolUses(content) {
if (typeof content === 'string' || !Array.isArray(content)) return []
return content.filter((block) => block.type === 'tool_use' && block.name).map((block) => block.name)
}
function applyTextCap(messages, cap) {
if (!cap) return
for (const m of messages) {
if (typeof m.text === 'string' && m.text.length > cap) {
m.text = m.text.slice(0, cap) + '\n\n…[잘림 — 세션 클릭 시 전체 보기]'
}
}
}
function parseClaudeJsonl(text, fileName, options = {}) {
const lines = text.trim().split('\n')
const rawMessages = []
let sessionId = ''
let cwd = ''
let version = ''
let model = ''
// 훅 텔레메트리 수집 — src/parser.ts 와 동일 위치(role-drop 가드 직전) 배선.
// light 경로는 페이로드-프리 summary 만 계산한다 (includeDetail 없음).
const hookCollector = createHookCollector()
// 모델 귀속은 **응답** 단위 — 병합 이전 raw 라인 루프에서. src/parser.ts 와 동일 수집기.
const modelCounter = createModelResponseCounter()
for (const line of lines) {
try {
const raw = JSON.parse(line)
if (raw.type === 'file-history-snapshot') continue
if (raw.isMeta || raw.isSidechain) continue
// 서브에이전트(sidechain) 훅은 위에서 제외됨 — 훅 집계는 부모 세션 것만
// 다룬다(파서가 sidechain 을 전량 제외하는 것과 일관, 의도적). src/parser.ts 와 동일.
hookCollector.collect(raw)
if (!raw.message?.role) continue
const textContent = extractText(raw.message.content)
const toolUses = extractToolUses(raw.message.content)
if (!textContent.trim() && toolUses.length === 0) continue
if (!sessionId && raw.sessionId) sessionId = raw.sessionId
if (!cwd && raw.cwd) cwd = raw.cwd
if (!version && raw.version) version = raw.version
if (!model && raw.message.model) model = raw.message.model
// requestId 로 같은 응답의 추가 라인을 접는다. `<synthetic>` 은 술어가 배제.
if (raw.message.role === 'assistant') modelCounter.add(raw.message.model, raw.requestId)
const usage = raw.message.usage
rawMessages.push({
role: raw.message.role,
text: textContent,
timestamp: raw.timestamp || '',
model: raw.message.model,
tokens: usage
? {
input: usage.input_tokens || 0,
output: usage.output_tokens || 0,
cachedInput: (usage.cache_creation_input_tokens || 0) + (usage.cache_read_input_tokens || 0),
}
: undefined,
toolUses,
})
} catch { }
}
if (rawMessages.length === 0) return null
const merged = []
// merged 와 같은 인덱스 — 블록별 등장 순 distinct 모델 누산기 (src/parser.ts 와 동일 규칙)
const blockModels = []
for (const message of rawMessages) {
const previous = merged[merged.length - 1]
if (previous && previous.role === message.role) {
previous.text += '\n\n' + message.text
previous.timestamp = previous.timestamp || message.timestamp
if (message.tokens) {
if (previous.tokens) {
previous.tokens.input += message.tokens.input
previous.tokens.output += message.tokens.output
previous.tokens.cachedInput = (previous.tokens.cachedInput || 0) + (message.tokens.cachedInput || 0)
} else {
previous.tokens = { ...message.tokens }
}
}
previous.toolUses = [...previous.toolUses, ...message.toolUses]
if (!previous.model && message.model) previous.model = message.model
// 블록 내부 모델 전환 보존 — src/parser.ts 와 동일 규칙
const bm = blockModels[blockModels.length - 1]
if (isAggregatableModel(message.model) && !bm.includes(message.model)) bm.push(message.model)
} else {
merged.push({
...message,
tokens: message.tokens ? { ...message.tokens } : undefined,
toolUses: [...message.toolUses],
})
blockModels.push(isAggregatableModel(message.model) ? [message.model] : [])
}
}
// 2종 이상인 블록에만 models 방출 — src/parser.ts 와 동일
for (let i = 0; i < merged.length; i++) {
if (blockModels[i].length >= 2) merged[i].models = blockModels[i]
}
applyTextCap(merged, options.messageTextCap)
const totalTokens = merged.reduce((accumulator, message) => ({
input: accumulator.input + (message.tokens?.input || 0),
output: accumulator.output + (message.tokens?.output || 0),
cachedInput: (accumulator.cachedInput || 0) + (message.tokens?.cachedInput || 0),
}), { input: 0, output: 0, cachedInput: 0 })
const { summary: hookSummary } = hookCollector.finalize()
const modelResponses = modelCounter.finalize()
return {
id: sessionId || fileName,
fileName,
source: 'claude',
messages: merged,
startTime: merged[0]?.timestamp || '',
endTime: merged[merged.length - 1]?.timestamp || '',
cwd,
version,
model,
totalTokens,
messageCount: {
user: merged.filter((message) => message.role === 'user').length,
assistant: merged.filter((message) => message.role === 'assistant').length,
},
// 페이로드-프리 tier-1 집계 — 훅 레코드가 없으면 필드 생략 (임베드 크기)
...(hookSummary ? { hookSummary } : {}),
// 모델별 응답 수 — 모델명 + 정수만 (식별자 없음)
...(modelResponses ? { modelResponses } : {}),
}
}
const CODEX_SETUP_PREFIXES = [
'# AGENTS.md instructions',
'<environment_context>',
'<collaboration_mode>',
'<permissions instructions>',
]
function extractCodexText(content) {
if (!Array.isArray(content)) return ''
return content
.map((block) => {
const type = typeof block.type === 'string' ? block.type : ''
if (!['input_text', 'output_text', 'summary_text', 'text'].includes(type)) return ''
return typeof block.text === 'string' ? block.text : ''
})
.filter(Boolean)
.join('\n')
}
function normalizeCodexUserText(text) {
const trimmed = text.trim()
if (!trimmed) return ''
if (CODEX_SETUP_PREFIXES.some((prefix) => trimmed.startsWith(prefix))) return ''
const marker = '## My request for Codex:'
if (trimmed.includes(marker)) {
return trimmed.split(marker).pop()?.trim() || ''
}
return trimmed
}
function parseCodexJsonl(text, fileName, options = {}) {
const lines = text.trim().split('\n')
const rawMessages = []
let sessionId = ''
let cwd = ''
let version = ''
let model = ''
let totalTokens = { input: 0, output: 0, cachedInput: 0 }
let pendingToolUses = []
// Codex 는 assistant response_item 1건 = 응답 1건 (dedupe 키 없음). src/providers/codex.ts 와 동일.
const modelCounter = createModelResponseCounter()
for (const line of lines) {
try {
const record = JSON.parse(line)
if (record.type === 'session_meta') {
sessionId = typeof record.payload?.id === 'string' ? record.payload.id : sessionId
cwd = typeof record.payload?.cwd === 'string' ? record.payload.cwd : cwd
version = typeof record.payload?.cli_version === 'string' ? record.payload.cli_version : version
continue
}
if (record.type === 'turn_context') {
cwd = typeof record.payload?.cwd === 'string' ? record.payload.cwd : cwd
model = typeof record.payload?.model === 'string' ? record.payload.model : model
continue
}
if (record.type === 'event_msg') {
const total = record.payload?.info?.total_token_usage
if (total) {
totalTokens = {
input: Number(total.input_tokens || 0),
output: Number(total.output_tokens || 0),
cachedInput: Number(total.cached_input_tokens || 0),
}
}
continue
}
if (record.type !== 'response_item' || !record.payload) continue
if (record.payload.type === 'function_call' && record.payload.name) {
const previous = rawMessages[rawMessages.length - 1]
if (previous?.role === 'assistant') {
previous.toolUses.push(record.payload.name)
} else {
pendingToolUses.push(record.payload.name)
}
continue
}
if (record.payload.type !== 'message') continue
if (record.payload.role !== 'user' && record.payload.role !== 'assistant') continue
const textContent = extractCodexText(record.payload.content)
const normalizedText = record.payload.role === 'user'
? normalizeCodexUserText(textContent)
: textContent.trim()
if (!normalizedText && pendingToolUses.length === 0) continue
rawMessages.push({
role: record.payload.role,
text: normalizedText,
timestamp: record.timestamp || '',
model: record.payload.role === 'assistant' ? model : undefined,
toolUses: pendingToolUses,
})
if (record.payload.role === 'assistant') modelCounter.add(model, null)
pendingToolUses = []
} catch { }
}
if (rawMessages.length === 0) return null
const merged = []
// merged 와 같은 인덱스 — 블록별 등장 순 distinct 모델 누산기 (src/parser.ts 와 동일 규칙)
const blockModels = []
for (const message of rawMessages) {
const previous = merged[merged.length - 1]
if (previous && previous.role === message.role) {
previous.text = previous.text && message.text ? `${previous.text}\n\n${message.text}` : previous.text || message.text
previous.timestamp = previous.timestamp || message.timestamp
previous.toolUses = [...previous.toolUses, ...message.toolUses]
if (!previous.model && message.model) previous.model = message.model
const bm = blockModels[blockModels.length - 1]
if (isAggregatableModel(message.model) && !bm.includes(message.model)) bm.push(message.model)
} else {
merged.push({
...message,
toolUses: [...message.toolUses],
})
blockModels.push(isAggregatableModel(message.model) ? [message.model] : [])
}
}
// 2종 이상인 블록에만 models 방출 — src/parser.ts 와 동일
for (let i = 0; i < merged.length; i++) {
if (blockModels[i].length >= 2) merged[i].models = blockModels[i]
}
// codex 메시지는 보통 짧아 cap 없이도 부담이 작고, SessionView 의 lazy
// fetch 패턴이 아직 claude 만 지원해서 codex 본문은 풀로 들고 있는다.
const modelResponses = modelCounter.finalize()
return {
id: sessionId || fileName,
fileName,
source: 'codex',
messages: merged,
startTime: merged[0]?.timestamp || '',
endTime: merged[merged.length - 1]?.timestamp || '',
cwd,
version,
model,
totalTokens,
messageCount: {
user: merged.filter((message) => message.role === 'user').length,
assistant: merged.filter((message) => message.role === 'assistant').length,
},
// 모델별 응답 수 — 모델명 + 정수만 (식별자 없음)
...(modelResponses ? { modelResponses } : {}),
}
}
function detectAndParse(content, fileName, options) {
const first = content.slice(0, 1200)
if (first.includes('"type":"session_meta"') || first.includes('"originator":"codex_') || first.includes('"type":"turn_context"')) {
return parseCodexJsonl(content, fileName, options)
}
if (first.includes('"sessionId"') || first.includes('"file-history-snapshot"')) {
return parseClaudeJsonl(content, fileName, options)
}
return null
}
// ─── Server mode (--server) ──────────────────────────────────────────
if (!isStaticMode) {
const MIME_TYPES = {
'.html': 'text/html; charset=utf-8',
'.js': 'application/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.svg': 'image/svg+xml',
'.json': 'application/json; charset=utf-8',
'.png': 'image/png',
'.ico': 'image/x-icon',
}
function isAllowedPath(filePath) {
const normalized = path.resolve(filePath)
return logRoots.some((root) => normalized.startsWith(path.resolve(root.dir)))
}
function serveStatic(req, res) {
let urlPath = new URL(req.url, 'http://localhost').pathname
if (urlPath === '/') urlPath = '/index.html'
const filePath = path.join(distDir, urlPath)
const resolved = path.resolve(filePath)
if (!resolved.startsWith(path.resolve(distDir))) {
res.statusCode = 403
res.end('Forbidden')
return
}
try {
const data = fs.readFileSync(resolved)
const ext = path.extname(resolved)
res.setHeader('Content-Type', MIME_TYPES[ext] || 'application/octet-stream')
res.end(data)
} catch {
res.statusCode = 404
res.end('Not found')
}
}
function handleSessions(_req, res) {
const sessions = logRoots.flatMap((root) =>
findJsonlFiles(root.dir).map((filePath) => ({
path: filePath,
name: path.basename(filePath),
project: root.source === 'claude' ? path.basename(path.dirname(filePath)) : 'codex',
size: fs.statSync(filePath).size,
source: root.source,
}))
)
res.setHeader('Content-Type', 'application/json; charset=utf-8')
res.end(JSON.stringify(sessions))
}
function handleSessionContent(req, res) {
const url = new URL(req.url, 'http://localhost')
const filePath = url.searchParams.get('path')
if (!filePath || !filePath.endsWith('.jsonl') || !isAllowedPath(filePath)) {
res.statusCode = 400
res.end('Invalid path')
return
}
try {
const content = fs.readFileSync(filePath, 'utf-8')
res.setHeader('Content-Type', 'text/plain; charset=utf-8')
res.end(content)
} catch {
res.statusCode = 404
res.end('Not found')
}
}
// Light-parsed session cache. Server reads + parses every jsonl once with a
// message-text cap and keeps both the result array AND the serialized JSON
// in memory. The pre-serialized string skips the per-request stringify cost
// (≈1.7s for 1500 sessions / 24MB) so cache hits respond in tens of ms.
let lightCachePromise = null
async function buildLightCache(textCap) {
const filesByRoot = logRoots.flatMap((root) =>
findJsonlFiles(root.dir).map((filePath) => ({ ...root, filePath }))
)
const sessions = []
const concurrency = 32
for (let i = 0; i < filesByRoot.length; i += concurrency) {
const batch = filesByRoot.slice(i, i + concurrency)
const results = await Promise.all(batch.map(async (f) => {
try {
const content = await fs.promises.readFile(f.filePath, 'utf-8')
const session = detectAndParse(content, path.basename(f.filePath), { messageTextCap: textCap })
if (session) {
session.filePath = f.filePath
return session
}
return null
} catch {
return null
}
}))
for (const s of results) if (s) sessions.push(s)
}
const json = JSON.stringify(sessions)
return { sessions, json }
}
function getLightCache(fresh = false) {
if (fresh || !lightCachePromise) {
lightCachePromise = buildLightCache(4000).catch((err) => {
// 다음 요청에서 재시도 가능하게 promise 초기화
lightCachePromise = null
throw err
})
}
return lightCachePromise
}
async function handleLightSessions(req, res) {
try {
const url = new URL(req.url, 'http://localhost')
const fresh = url.searchParams.get('fresh') === '1'
const cache = await getLightCache(fresh)
res.setHeader('Content-Type', 'application/json; charset=utf-8')
res.end(cache.json)
} catch (err) {
res.statusCode = 500
res.end('Failed: ' + (err?.message || 'unknown'))
}
}
// 훅 설정 인벤토리 + 관측 매칭 — light 캐시(hookSummary)와 대조해
// observed/confidence 를 서버에서 계산한다. command 는 toServerHookEntries
// 가 직렬화 경계에서 maskSecrets 적용 (loopback 응답 전용, 외부 전송 없음).
async function handleHooks(_req, res) {
try {
const cache = await getLightCache()
const { entries, errors } = scanHooks()
const matched = matchHookEntries(entries, buildHookTelemetryRows(cache.sessions), process.cwd())
res.setHeader('Content-Type', 'application/json; charset=utf-8')
res.end(JSON.stringify({ entries: toServerHookEntries(matched), errors }))
} catch (err) {
res.statusCode = 500
res.end('Failed: ' + (err?.message || 'unknown'))
}
}
// npm 공개 다운로드 집계 — CLI 기동 시 한 번 받아둔 값을 그대로 돌려준다.
// 브라우저가 api.npmjs.org 를 직접 부르지 않게 하려는 것 (정적 모드가 값을
// 구워 넣는 것과 같은 이유). 미조회/실패 시 null 이며 프론트는 no-data 처리.
async function handleNpmStats(_req, res) {
const stats = await npmDownloadsPromise
res.setHeader('Content-Type', 'application/json; charset=utf-8')
res.end(JSON.stringify(stats))
}
const server = http.createServer((req, res) => {
const pathname = new URL(req.url, 'http://localhost').pathname
if (pathname === '/api/sessions') return handleSessions(req, res)
if (pathname === '/api/session-content') return handleSessionContent(req, res)
if (pathname === '/api/light-sessions') return handleLightSessions(req, res)
if (pathname === '/api/hooks') return handleHooks(req, res)
if (pathname === '/api/npm-stats') return handleNpmStats(req, res)
if (pathname === '/api/skills') {
res.setHeader('Content-Type', 'application/json; charset=utf-8')
res.end(JSON.stringify(scanSkills()))
return
}
return serveStatic(req, res)
})
function tryListen(port, maxAttempts = 10) {
return new Promise((resolve, reject) => {
let attempts = 0
function attempt() {
server.listen(port + attempts, SERVER_HOST, () => resolve(port + attempts))
server.once('error', (err) => {
if (err.code === 'EADDRINUSE' && ++attempts < maxAttempts) {
server.removeAllListeners('error')
attempt()
} else {
reject(err)
}
})
}
attempt()
})
}
await handleUpdate(await updateCheckPromise)
const actualPort = await tryListen(DEFAULT_PORT)
const localUrl = `http://localhost:${actualPort}`
const url = isLoopbackHost(SERVER_HOST) ? localUrl : `http://${SERVER_HOST}:${actualPort}`
// Pre-warm light parse cache in the background — 첫 클라이언트 요청이 오기 전에
// 미리 파싱을 시작해 응답 지연을 줄인다. 실패해도 첫 요청 시 재시도된다.
getLightCache().catch(() => {})
// Count sessions for display
const fileCount = logRoots.reduce((sum, root) => sum + findJsonlFiles(root.dir).length, 0)
console.log()
console.log(' Memradar')
console.log(' ------------------------------')
console.log(' Log dirs: ')
for (const root of logRoots) {
console.log(` - ${root.source}: ${root.dir}`)
}
console.log(` Sessions: ${fileCount}`)
console.log(` Server: ${url}`)
if (!isLoopbackHost(SERVER_HOST)) {
const lanIps = SERVER_HOST === '0.0.0.0' ? getLanIps() : []
if (lanIps.length > 0) {
console.log(' LAN URLs:')
for (const ip of lanIps) {
console.log(` - http://${ip}:${actualPort}`)
}
}
console.log()
console.log(' ⚠️ 네트워크 노출 모드 (--host ' + SERVER_HOST + ')')
console.log(' 같은 네트워크의 다른 기기에서 세션 로그를 볼 수 있습니다.')
console.log(' 공용 와이파이 등 신뢰하지 않는 네트워크에서는 사용을 피하세요.')
}
console.log(' ------------------------------')
console.log(' Press Ctrl+C to stop')
console.log()
if (shouldOpenBrowser) {
openBrowser(url)
}
process.on('SIGINT', () => {
console.log('\n Shutting down...\n')
server.close(() => process.exit(0))
})
process.on('SIGTERM', () => {
server.close(() => process.exit(0))
})
} else {
// ─── Static HTML mode (default) ─────────────────────────────────────
(async () => {
await handleUpdate(await updateCheckPromise)
const outPath = process.env.MEMRADAR_OUTPUT_HTML || path.join(os.tmpdir(), 'memradar.html')
const files = logRoots.flatMap((root) =>
findJsonlFiles(root.dir).map((filePath) => ({ ...root, filePath }))
)
console.log()
console.log(' Memradar (static)')
console.log(' ------------------------------')
console.log(' Log dirs: ')
for (const root of logRoots) {
console.log(` - ${root.source}: ${root.dir}`)
}
console.log(` Sessions: ${files.length}`)
if (files.length === 0) {
console.log(' No session files found.')
console.log(' ------------------------------')
process.exit(0)
}
// Pre-check: warn if total size exceeds 100MB
const forceStatic = process.argv.includes('--force-static')
if (!forceStatic) {
let totalSize = 0
for (const file of files) {
try {
totalSize += fs.statSync(file.filePath).size
} catch { }
}
const totalMB = (totalSize / 1024 / 1024).toFixed(1)
if (totalSize >= 100 * 1024 * 1024) {
console.log()
console.log(' ⚠️ 대용량 세션 감지 (' + totalMB + ' MB)')
console.log(' 정적 HTML 모드는 시간이 오래 걸릴 수 있습니다.')
console.log(' 서버 모드를 권장합니다: npx memradar@latest --server')
console.log(' 강제 실행: npx memradar --force-static')
console.log(' ------------------------------')
process.exit(1)
}
}
console.log(' Parsing sessions...')
const sessions = []
const concurrency = 32
for (let i = 0; i < files.length; i += concurrency) {
const batch = files.slice(i, i + concurrency)
const results = await Promise.all(batch.map(async (file) => {
try {
const content = await fs.promises.readFile(file.filePath, 'utf-8')
const session = detectAndParse(content, path.basename(file.filePath), { messageTextCap: 4000 })
if (session) {
// 시크릿 마스킹 — 직렬화(임베드) 경계. 원본 .jsonl 은 불변, 메모리 객체만 변형.
// 정적 HTML 에는 원문 시크릿이 아예 없어 공유 안전 (리빌 불가가 의도).
// 서버 모드 API 는 무변경 — loopback 응답은 클라이언트 렌더에서 마스킹된다.
session.messages = session.messages.map((m) => (m.text ? { ...m, text: maskSecrets(m.text).masked } : m))
return session
}
return null
} catch {
return null
}
}))
for (const s of results) if (s) sessions.push(s)
const parsed = sessions.length
process.stdout.write(`\r Parsed: ${parsed}/${files.length}`)
}
console.log()
console.log(` Parsed: ${sessions.length}`)
const assetsDir = path.join(distDir, 'assets')
if (!fs.existsSync(assetsDir)) {
console.error('dist/assets folder not found. Run `npm run build` first.')