@sejuneoh/aitop 0.39.0 → 0.40.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -72,7 +72,7 @@
72
72
  **Keys on the live screen**
73
73
 
74
74
  - `↑↓` select · `n` next session to check · `/` search · `s` sort · `g` group
75
- - `p` pin · `f` changed files · `a` waiting alerts on/off · `?` help · `q` quit
75
+ - `p` pin · `f` changed files · `v` artifacts (Enter views the source) · `a` waiting alerts on/off · `?` help · `q` quit
76
76
 
77
77
  **Config file**
78
78
 
@@ -124,6 +124,7 @@
124
124
  - The detail panel shows `── Artifacts N ──` when a session published any: `title · v1→v3 · 14:02 · claude.ai/…`, plus `edited in place` for an `edits` publish `org` for an org-shared link and `public` for a public one (nothing for `owner`). The version range comes from the publish sequence number; without one it is left out. When space is short, the latest few and `+N`.
125
125
  - Only `https://claude.ai/` addresses become OSC 8 links. Under `NO_COLOR`, in piped output and in terminals not known to support links they are plain text; `FORCE_HYPERLINK=1` or `0` overrides. Only the title, address, publish sequence number, time, audience and whether `edits` was used are read (no file paths or edit contents).
126
126
  - `--json` has `artifacts` per session (`title`, `url`, `versionFrom`, `versionTo`, `updatedAt`, `audience`, `viaEdits`); `url` is `null` unless it is a `https://claude.ai/` address.
127
+ - `v` moves into the list, `↑↓` picks and `Enter` shows the source full screen (`↑↓` · `space` · `PgUp/PgDn` · `Home/End` scroll, `[ ]` previous/next, `Esc` back one step). The source is looked up only then: the local file at the published path (a regular file, not a symlink, first 2MB), else the last `Write` of that path in the same session's transcripts (subagents included, marked `may differ from the published version` when an `Edit` or an `edits` publish came after it), else `no source`. HTML is never run: scripts, styles, templates and comments are dropped and headings, paragraphs, lists, tables, code and quotes are shown as text, with `data:` images as `[image 120KB]`. Markdown gets simple headings, lists and code blocks.
127
128
 
128
129
  **Tool line and empty screen**
129
130
 
package/bin/aitop.mjs CHANGED
@@ -532,6 +532,8 @@ const act = {
532
532
  move,
533
533
  next: () => goTo(nextAttention(attention, visible(), view.selectedId)),
534
534
  keepVisible: keepSelectionVisible,
535
+ // 아티팩트 원본을 뒤에서 찾은 뒤 다시 그린다 (#307).
536
+ redraw: () => draw(),
535
537
  };
536
538
 
537
539
  stdin.on('data', (key) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sejuneoh/aitop",
3
- "version": "0.39.0",
3
+ "version": "0.40.0",
4
4
  "description": "터미널에서 Claude Code · Codex · Antigravity · Gemini 세션과 토큰을 실시간으로 보는 읽기 전용 모니터",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/help.mjs CHANGED
@@ -34,6 +34,7 @@ export const VIEWS = {
34
34
  keys: [
35
35
  k('detail.switch', '↑↓ j k', 'switchSession', '↑↓/jk'),
36
36
  k('detail.files', 'f Tab', 'files'),
37
+ k('detail.artifacts', 'v', 'artifacts'),
37
38
  k('detail.copy', 'y', 'copy'),
38
39
  k('detail.close', 'd', 'close'),
39
40
  ],
@@ -58,6 +59,26 @@ export const VIEWS = {
58
59
  k('diff.back', 'Esc h ← f Tab', 'back'),
59
60
  ],
60
61
  },
62
+ artifacts: {
63
+ name: 'artifacts',
64
+ title: ko('view.artifacts'),
65
+ keys: [
66
+ k('artifacts.pick', '↑↓ j k', 'pick', '↑↓/jk'),
67
+ k('artifacts.open', 'Enter l', 'source'),
68
+ k('artifacts.back', 'Esc h v', 'back'),
69
+ ],
70
+ },
71
+ artifact: {
72
+ name: 'artifact',
73
+ title: ko('view.artifact'),
74
+ keys: [
75
+ k('artifact.scroll', '↑↓ j k', 'scroll', '↑↓/jk'),
76
+ k('artifact.page', 'space PgDn PgUp', 'page', 'space'),
77
+ k('artifact.ends', 'Home End', 'ends', 'Home/End'),
78
+ k('artifact.prevNext', '[ ]', 'prevNextArt', '[ ]'),
79
+ k('artifact.back', 'Esc h ←', 'back'),
80
+ ],
81
+ },
61
82
  filtered: {
62
83
  name: 'filtered',
63
84
  title: ko('view.filtered'),
@@ -107,9 +128,9 @@ const OPTION_IDS = [
107
128
  export const options = (lang = getLang()) => OPTION_IDS.map(([o, d]) => [o.startsWith('hopt.') ? t(o, null, { lang }) : o, t(d, null, { lang })]);
108
129
  export const OPTIONS = options('ko');
109
130
 
110
- // 지금 보는 화면: 파일 목록·diff 에 들어가 있으면 그 화면, 아니면 세션 표. 검색어는 표에 붙는 것이라 helpSections 가 따로 본다.
131
+ // 지금 보는 화면: 파일 목록·diff·아티팩트 목록·원본에 들어가 있으면 그 화면, 아니면 세션 표. 검색어는 표에 붙는 것이라 helpSections 가 따로 본다.
111
132
  export function helpContext(view) {
112
- if (view.focus === 'diff' || view.focus === 'files') return view.focus;
133
+ if (['diff', 'files', 'artifacts', 'artifact'].includes(view.focus)) return view.focus;
113
134
  return 'table';
114
135
  }
115
136
 
@@ -130,7 +151,7 @@ export function viewText(v, lang = getLang()) {
130
151
  // aitop --help 끝의 키 안내. 지금 언어(bin 이 정한다)로 쓴다.
131
152
  export function keysText(lang = getLang()) {
132
153
  const title = (n) => t(`view.${n}`, null, { lang });
133
- return [`${t('help.keys', null, { lang })}: ${keysLine('table', lang)} · ${keysLine('common', lang)}`, ...['detail', 'files', 'diff', 'filtered', 'search'].map((n) => ` ${title(n)}: ${keysLine(n, lang)}`)].join('\n');
154
+ return [`${t('help.keys', null, { lang })}: ${keysLine('table', lang)} · ${keysLine('common', lang)}`, ...['detail', 'files', 'diff', 'artifacts', 'artifact', 'filtered', 'search'].map((n) => ` ${title(n)}: ${keysLine(n, lang)}`)].join('\n');
134
155
  }
135
156
 
136
157
  // 지금 설정 값 한 줄 (예: 예산 $50 · 알림 켜짐 · 디버그 꺼짐). settings 가 없으면 null.
package/src/i18n.mjs CHANGED
@@ -187,6 +187,8 @@ export const STRINGS = {
187
187
  'view.detail': '상세 패널',
188
188
  'view.files': '변경 파일 목록',
189
189
  'view.diff': 'diff',
190
+ 'view.artifacts': '아티팩트 목록',
191
+ 'view.artifact': '아티팩트 원본',
190
192
  'view.filtered': '검색어가 걸린 표',
191
193
  'view.search': '검색 입력 중',
192
194
  'view.common': '어디서나',
@@ -211,6 +213,10 @@ export const STRINGS = {
211
213
  'key.scroll': '스크롤',
212
214
  'key.page': '페이지',
213
215
  'key.prevNext': '이전·다음 파일',
216
+ 'key.artifacts': '아티팩트',
217
+ 'key.source': '원본 보기',
218
+ 'key.ends': '처음·끝',
219
+ 'key.prevNextArt': '이전·다음 아티팩트',
214
220
  'key.clearSearch': '검색어 지우기',
215
221
  'key.newSearch': '새 검색',
216
222
  'key.type': '입력',
@@ -492,6 +498,10 @@ export const STRINGS = {
492
498
  'foot.pickFile': '파일 선택',
493
499
  'foot.viewDiff': 'diff 보기',
494
500
  'foot.toSessions': '세션으로',
501
+ 'foot.artifacts': '아티팩트',
502
+ 'foot.pickArtifact': '아티팩트 선택',
503
+ 'foot.viewSource': '원본 보기',
504
+ 'foot.toArtifacts': '목록으로',
495
505
  'foot.hideEnded': '종료 숨김',
496
506
  'foot.showEnded': '종료 포함',
497
507
  'foot.next': '다음',
@@ -580,6 +590,15 @@ export const STRINGS = {
580
590
  'hk.diff.page': '한 페이지씩',
581
591
  'hk.diff.prevNext': '이전·다음 파일',
582
592
  'hk.diff.back': '파일 목록으로',
593
+ 'hk.detail.artifacts': '아티팩트 목록으로 (게시한 것이 있을 때)',
594
+ 'hk.artifacts.pick': '아티팩트 고르기',
595
+ 'hk.artifacts.open': '고른 아티팩트의 원본을 전체 화면으로 (로컬 파일 → 기록의 Write 본문 순으로 찾는다)',
596
+ 'hk.artifacts.back': '세션 표로',
597
+ 'hk.artifact.scroll': '한 줄씩 스크롤',
598
+ 'hk.artifact.page': '한 페이지씩',
599
+ 'hk.artifact.ends': '처음·끝으로',
600
+ 'hk.artifact.prevNext': '이전·다음 아티팩트',
601
+ 'hk.artifact.back': '아티팩트 목록으로',
583
602
  'hk.filtered.select': '검색 결과 안에서 세션 선택',
584
603
  'hk.filtered.clear': '검색어 지우기 (표 전체로)',
585
604
  'hk.filtered.new': '지금 검색어를 지우고 새로 입력',
@@ -633,6 +652,17 @@ export const STRINGS = {
633
652
  'detail.artEdits': '바로 수정',
634
653
  'detail.artPublic': '공개',
635
654
  'detail.artOrg': '조직 공유',
655
+ 'art.srcLocal': '로컬 파일',
656
+ 'art.srcRecord': '기록 본문',
657
+ 'art.srcNone': '원본 없음',
658
+ 'art.srcLoading': '찾는 중…',
659
+ 'art.loading': '기록에서 원본을 찾는 중…',
660
+ 'art.noneNote': '원본 없음 (임시 파일이 지워졌고 기록에도 본문이 없다)',
661
+ 'art.mayDiffer': '게시본과 다를 수 있음',
662
+ 'art.cut': '앞 {n}만',
663
+ 'art.empty': '(보일 글이 없음)',
664
+ 'art.image': '[이미지 {size}]',
665
+ 'art.imageAlt': '[이미지: {alt}]',
636
666
  'detail.activity': '최근 활동',
637
667
  'detail.files': '변경 파일',
638
668
  'detail.tabNone': ' · {tab} 0개',
@@ -688,6 +718,8 @@ export const STRINGS = {
688
718
  'view.detail': 'Detail panel',
689
719
  'view.files': 'Changed files',
690
720
  'view.diff': 'diff',
721
+ 'view.artifacts': 'Artifact list',
722
+ 'view.artifact': 'Artifact source',
691
723
  'view.filtered': 'Filtered table',
692
724
  'view.search': 'Typing a search',
693
725
  'view.common': 'Anywhere',
@@ -712,6 +744,10 @@ export const STRINGS = {
712
744
  'key.scroll': 'scroll',
713
745
  'key.page': 'page',
714
746
  'key.prevNext': 'prev/next file',
747
+ 'key.artifacts': 'artifacts',
748
+ 'key.source': 'view source',
749
+ 'key.ends': 'top/bottom',
750
+ 'key.prevNextArt': 'prev/next artifact',
715
751
  'key.clearSearch': 'clear search',
716
752
  'key.newSearch': 'new search',
717
753
  'key.type': 'to search',
@@ -984,6 +1020,10 @@ export const STRINGS = {
984
1020
  'foot.pickFile': 'pick file',
985
1021
  'foot.viewDiff': 'view diff',
986
1022
  'foot.toSessions': 'to sessions',
1023
+ 'foot.artifacts': 'artifacts',
1024
+ 'foot.pickArtifact': 'pick artifact',
1025
+ 'foot.viewSource': 'view source',
1026
+ 'foot.toArtifacts': 'to list',
987
1027
  'foot.hideEnded': 'hide ended',
988
1028
  'foot.showEnded': 'show ended',
989
1029
  'foot.next': 'next',
@@ -1071,6 +1111,15 @@ export const STRINGS = {
1071
1111
  'hk.diff.page': 'Scroll one page',
1072
1112
  'hk.diff.prevNext': 'Previous or next file',
1073
1113
  'hk.diff.back': 'Back to the file list',
1114
+ 'hk.detail.artifacts': 'Open the artifact list (when something was published)',
1115
+ 'hk.artifacts.pick': 'Pick an artifact',
1116
+ 'hk.artifacts.open': 'View the source full screen (local file first, then the Write body in the transcript)',
1117
+ 'hk.artifacts.back': 'Back to the session table',
1118
+ 'hk.artifact.scroll': 'Scroll one line',
1119
+ 'hk.artifact.page': 'Scroll one page',
1120
+ 'hk.artifact.ends': 'Jump to top or bottom',
1121
+ 'hk.artifact.prevNext': 'Previous or next artifact',
1122
+ 'hk.artifact.back': 'Back to the artifact list',
1074
1123
  'hk.filtered.select': 'Select a session in the results',
1075
1124
  'hk.filtered.clear': 'Clear the search (full table)',
1076
1125
  'hk.filtered.new': 'Clear the search and type a new one',
@@ -1122,6 +1171,17 @@ export const STRINGS = {
1122
1171
  'detail.artEdits': 'edited in place',
1123
1172
  'detail.artPublic': 'public',
1124
1173
  'detail.artOrg': 'org',
1174
+ 'art.srcLocal': 'local file',
1175
+ 'art.srcRecord': 'transcript body',
1176
+ 'art.srcNone': 'no source',
1177
+ 'art.srcLoading': 'searching…',
1178
+ 'art.loading': 'Searching the transcript for the source…',
1179
+ 'art.noneNote': 'No source (the temp file is gone and the transcript has no body)',
1180
+ 'art.mayDiffer': 'may differ from the published version',
1181
+ 'art.cut': 'first {n} only',
1182
+ 'art.empty': '(nothing to show)',
1183
+ 'art.image': '[image {size}]',
1184
+ 'art.imageAlt': '[image: {alt}]',
1125
1185
  'detail.activity': 'Recent activity',
1126
1186
  'detail.files': 'Changed files',
1127
1187
  'detail.tabNone': ' · {tab}: none',
package/src/keys.mjs CHANGED
@@ -1,15 +1,21 @@
1
1
  // 키 입력 처리. 화면 상태(view)를 바꾸고, 종료·갱신·세션 이동처럼 밖에서 해야 할 일은 act 로 부른다.
2
2
  // view.focus: null(세션 선택) → 'files'(변경 파일 목록) → 'diff'(고른 파일의 변경 내용). Esc 는 한 단계씩 뒤로 가고 종료하지 않는다.
3
+ // 아티팩트(#307): v 로 상세 패널의 아티팩트 목록에 들어가 'artifacts'(목록) → Enter 'artifact'(원본 전체 화면). Esc 로 한 단계씩 돌아온다.
4
+ // view.artifactId: 고른 아티팩트, view.artDoc: 연 원본 (Enter 때만 artifact-source.mjs 가 찾는다), view.artScroll: 원본 스크롤 위치.
3
5
  // view.tab: 변경 파일을 보는 지시 탭 ('now' 이번 지시, 지시 번호, 'all' 전체). turns.mjs 참고.
4
6
  import { turnTabs, visibleFiles } from './turns.mjs';
5
7
  import { detailOpen } from './ui/chrome.mjs';
6
8
  import { nextGroup, nextSort, togglePin } from './order.mjs';
9
+ import { openArtifactSource } from './sources/artifact-source.mjs';
7
10
 
8
- export const KEY = { up: '\x1b[A', down: '\x1b[B', right: '\x1b[C', left: '\x1b[D', pageUp: '\x1b[5~', pageDown: '\x1b[6~', esc: '\x1b', enter: '\r', tab: '\t', ctrlC: '\x03', backspace: '\x7f' };
11
+ export const KEY = { up: '\x1b[A', down: '\x1b[B', right: '\x1b[C', left: '\x1b[D', pageUp: '\x1b[5~', pageDown: '\x1b[6~', home: '\x1b[H', end: '\x1b[F', esc: '\x1b', enter: '\r', tab: '\t', ctrlC: '\x03', backspace: '\x7f' };
9
12
 
10
13
  const isUp = (k) => k === KEY.up || k === 'k';
11
14
  const isDown = (k) => k === KEY.down || k === 'j';
12
15
  const isBack = (k) => k === KEY.esc || k === 'h';
16
+ // 터미널마다 Home·End 를 보내는 모양이 다르다.
17
+ const isHome = (k) => k === KEY.home || k === '\x1b[1~' || k === '\x1b[7~' || k === '\x1bOH';
18
+ const isEnd = (k) => k === KEY.end || k === '\x1b[4~' || k === '\x1b[8~' || k === '\x1bOF';
13
19
 
14
20
  export function selectedSession(view) {
15
21
  return view.data?.sessions.find((s) => s.id === view.selectedId) ?? null;
@@ -19,9 +25,23 @@ const hasFiles = (view) => Boolean(selectedSession(view)?.files?.length);
19
25
  // 지금 탭에 보이는 파일
20
26
  const filesOf = (view) => visibleFiles(selectedSession(view), view.tab);
21
27
 
28
+ const artsOf = (view) => selectedSession(view)?.artifacts ?? [];
29
+ const pickedArtifact = (view) => artsOf(view).find((a) => a.id === view.artifactId) ?? null;
30
+
22
31
  // 갱신 뒤에 고른 파일이 탭에서 빠졌거나 세션에 고친 파일이 없어졌으면 포커스를 맞춘다.
23
32
  export function fixFocus(view) {
24
33
  if (!view.focus) return;
34
+ // 원본 화면은 연 원본(artDoc)이 있는 동안 그대로 둔다. 목록은 아티팩트가 없어지면 닫는다.
35
+ if (view.focus === 'artifact') {
36
+ if (!view.artDoc) view.focus = artsOf(view).length ? 'artifacts' : null;
37
+ return;
38
+ }
39
+ if (view.focus === 'artifacts') {
40
+ const arts = artsOf(view);
41
+ if (!arts.length || !view.showDetail) view.focus = null;
42
+ else if (!pickedArtifact(view)) view.artifactId = arts[0].id;
43
+ return;
44
+ }
25
45
  if (!hasFiles(view) || !view.showDetail) {
26
46
  view.focus = null;
27
47
  return;
@@ -87,6 +107,76 @@ function diffKey(view, key) {
87
107
  return true;
88
108
  }
89
109
 
110
+ function enterArtifacts(view) {
111
+ const arts = artsOf(view);
112
+ if (!arts.length) return;
113
+ view.showDetail = true;
114
+ view.focus = 'artifacts';
115
+ if (!pickedArtifact(view)) view.artifactId = arts[0].id;
116
+ }
117
+
118
+ function stepArtifact(view, delta) {
119
+ const arts = artsOf(view);
120
+ const i = Math.max(0, arts.findIndex((a) => a.id === view.artifactId));
121
+ view.artifactId = arts[Math.min(arts.length - 1, Math.max(0, i + delta))]?.id ?? null;
122
+ }
123
+
124
+ // 원본은 화면을 열 때만 찾는다 (act.loadArtifact 는 테스트가 바꿔 끼운다).
125
+ // 기억한 위치로 바로 찾지 못하면 '찾는 중…' 을 먼저 보이고, 기록 훑기가 끝나면 바꾼 뒤 act.redraw 로 다시 그린다.
126
+ // 그 사이 다른 원본을 열거나 목록으로 돌아가면(view.artDoc 가 바뀜) 훑기를 그만둔다.
127
+ function openArtifact(view, act) {
128
+ const a = pickedArtifact(view);
129
+ if (!a) return;
130
+ view.focus = 'artifact';
131
+ view.artScroll = 0;
132
+ if (act?.loadArtifact) {
133
+ view.artDoc = act.loadArtifact(selectedSession(view), a);
134
+ return;
135
+ }
136
+ const wait = { kind: 'loading', path: null, text: '', cut: false, changed: false };
137
+ view.artDoc = wait;
138
+ const doc = openArtifactSource(selectedSession(view), a, {
139
+ cancelled: () => view.artDoc !== wait,
140
+ done: (d) => {
141
+ if (view.artDoc !== wait) return;
142
+ view.artDoc = d;
143
+ act?.redraw?.();
144
+ },
145
+ });
146
+ if (doc) view.artDoc = doc;
147
+ }
148
+
149
+ function artifactsKey(view, key, act) {
150
+ if (isUp(key)) stepArtifact(view, -1);
151
+ else if (isDown(key)) stepArtifact(view, 1);
152
+ else if (key === KEY.enter || key === 'l') openArtifact(view, act);
153
+ else if (isBack(key) || key === 'v') view.focus = null;
154
+ else return false;
155
+ return true;
156
+ }
157
+
158
+ // 원본 화면은 모달이다: 스크롤·이전/다음·뒤로 말고는 받지 않는다 (? 와 q 는 onKey 가 먼저 본다).
159
+ function artifactKey(view, key, act) {
160
+ const page = view.artPage ?? 10;
161
+ const at = view.artScroll ?? 0;
162
+ if (isUp(key)) view.artScroll = Math.max(0, at - 1);
163
+ else if (isDown(key)) view.artScroll = at + 1;
164
+ else if (key === ' ' || key === KEY.pageDown) view.artScroll = at + page;
165
+ else if (key === KEY.pageUp) view.artScroll = Math.max(0, at - page);
166
+ else if (isHome(key)) view.artScroll = 0;
167
+ // 끝은 그릴 때 본문 길이에 맞춘다 (artifact-view.mjs artifactScreen).
168
+ else if (isEnd(key)) view.artScroll = Infinity;
169
+ else if (key === '[' || key === ']') {
170
+ const before = view.artifactId;
171
+ stepArtifact(view, key === '[' ? -1 : 1);
172
+ if (view.artifactId !== before) openArtifact(view, act);
173
+ } else if (isBack(key) || key === KEY.left) {
174
+ view.focus = 'artifacts';
175
+ view.artDoc = null;
176
+ }
177
+ return true;
178
+ }
179
+
90
180
  // 검색 중에는 글자를 검색어로 받는다. Enter 는 검색어를 남기고 목록으로, Esc 는 검색을 지운다.
91
181
  function searchKey(view, key, act) {
92
182
  if (key === KEY.enter) view.searching = false;
@@ -120,6 +210,8 @@ export function onKey(view, key, act) {
120
210
  return;
121
211
  }
122
212
  if (key === 'q') return act.quit();
213
+ if (view.focus === 'artifact' && artifactKey(view, key, act)) return;
214
+ if (view.focus === 'artifacts' && artifactsKey(view, key, act)) return;
123
215
  if (view.focus === 'diff' && diffKey(view, key)) return;
124
216
  if (view.focus === 'files' && filesKey(view, key)) return;
125
217
  if (key === KEY.esc) {
@@ -127,6 +219,7 @@ export function onKey(view, key, act) {
127
219
  return;
128
220
  }
129
221
  if (key === 'f' || key === KEY.tab) return enterFiles(view);
222
+ if (key === 'v') return enterArtifacts(view);
130
223
  if (key === '/') {
131
224
  view.searching = true;
132
225
  view.filter = '';
@@ -0,0 +1,278 @@
1
+ // 아티팩트 원본 찾기 (#307). 상세 패널 아티팩트 목록에서 Enter 로 볼 때만 부른다 (미리 읽거나 캐시에 쌓지 않는다).
2
+ // 순서: 1) 게시 결과의 path 에 있는 로컬 파일 2) 같은 세션(서브에이전트 포함) 기록에서 그 경로로 마지막에 Write 한 본문 3) 원본 없음.
3
+ // 기록 본문을 쓸 때 그 Write 뒤에 같은 경로의 Edit 이나 Artifact edits 가 있었으면 게시본과 다를 수 있다고 알린다.
4
+ // 경로는 기록의 게시 결과(toolUseResult.path, 없으면 게시 호출의 file_path)에서만 얻는다. 목록·캐시·--json 에는 경로를 두지 않는다.
5
+ // 보통은 기록을 읽던 tracker 가 메모리에 기억한 위치(경로, Write 결과 줄의 오프셋)만 읽고, 위치를 모를 때만 기록을 뒤에서 나눠 훑는다.
6
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readSync } from 'node:fs';
7
+ import { StringDecoder } from 'node:string_decoder';
8
+ import { isAbsolute } from 'node:path';
9
+ import { isPublish, pathKey, pickArtifact } from './artifacts.mjs';
10
+ import { parseTs } from './common.mjs';
11
+ import { liveTracker } from './claude-tracker.mjs';
12
+
13
+ // 원본으로 읽는 최대 바이트 (artifacts.mjs). 넘으면 앞부분만 보이고 cut 을 켠다.
14
+ export { SOURCE_MAX } from './artifacts.mjs';
15
+ import { SOURCE_MAX } from './artifacts.mjs';
16
+
17
+ const PATH_MAX = 4096;
18
+ const okPath = (p) => typeof p === 'string' && p.length <= PATH_MAX && isAbsolute(p) && !/[\x00-\x1f\x7f]/.test(p);
19
+
20
+ // 바이트 앞부분을 글로. 잘린 자리의 반쪽 글자는 버린다.
21
+ function decode(buf) {
22
+ const d = new StringDecoder('utf8');
23
+ return d.write(buf);
24
+ }
25
+
26
+ // 로컬 파일 읽기: 일반 파일이고 심볼릭 링크가 아닐 때만. 실패하면 null (조용히 다음 출처로).
27
+ // lstat 와 open 사이에 링크로 바뀌는 것도 막는다 (O_NOFOLLOW 가 있는 OS 는 열 때 거절, 없으면 같은 파일인지 dev·ino 로 다시 본다).
28
+ export function readLocal(path, max = SOURCE_MAX) {
29
+ if (!okPath(path)) return null;
30
+ let fd;
31
+ try {
32
+ const st = lstatSync(path);
33
+ if (st.isSymbolicLink() || !st.isFile()) return null;
34
+ fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
35
+ const f = fstatSync(fd);
36
+ if (!f.isFile() || f.dev !== st.dev || f.ino !== st.ino) return null;
37
+ const n = Math.min(f.size, max);
38
+ const buf = Buffer.alloc(n);
39
+ let got = 0;
40
+ while (got < n) {
41
+ const r = readSync(fd, buf, got, n - got, got);
42
+ if (!r) break;
43
+ got += r;
44
+ }
45
+ return { text: decode(buf.subarray(0, got)), cut: f.size > max, size: f.size };
46
+ } catch {
47
+ return null;
48
+ } finally {
49
+ if (fd != null)
50
+ try {
51
+ closeSync(fd);
52
+ } catch {}
53
+ }
54
+ }
55
+
56
+ // 기록을 한 줄씩 읽는다 (큰 기록도 통째로 올리지 않는다). want 에 걸리는 줄만 JSON 으로 푼다.
57
+ // 생성기라서 1MB 를 읽을 때마다 한 번 멈춘다(yield). 화면 쪽은 시간을 잘라 이어 돌려 키 입력과 그리기를 막지 않는다.
58
+ function* eachRecord(path, want, fn) {
59
+ let fd;
60
+ try {
61
+ fd = openSync(path, 'r');
62
+ const d = new StringDecoder('utf8');
63
+ const buf = Buffer.alloc(1 << 20);
64
+ let rest = '';
65
+ let pos = 0;
66
+ const take = (l) => {
67
+ if (!want(l)) return;
68
+ try {
69
+ fn(JSON.parse(l));
70
+ } catch {}
71
+ };
72
+ for (;;) {
73
+ const n = readSync(fd, buf, 0, buf.length, pos);
74
+ if (!n) break;
75
+ pos += n;
76
+ rest += d.write(buf.subarray(0, n));
77
+ let start = 0;
78
+ let i;
79
+ while ((i = rest.indexOf('\n', start)) >= 0) {
80
+ take(rest.slice(start, i));
81
+ start = i + 1;
82
+ }
83
+ rest = rest.slice(start);
84
+ yield n;
85
+ }
86
+ if (rest) take(rest);
87
+ } catch {
88
+ } finally {
89
+ if (fd != null)
90
+ try {
91
+ closeSync(fd);
92
+ } catch {}
93
+ }
94
+ }
95
+
96
+ // JSON 안에 적힌 모양 (따옴표 없이).
97
+ const inJson = (s) => JSON.stringify(s).slice(1, -1);
98
+
99
+ const toolUses = (x) => (x?.type === 'assistant' && Array.isArray(x.message?.content) ? x.message.content.filter((c) => c?.type === 'tool_use') : []);
100
+ const toolResults = (x) => (x?.type === 'user' && Array.isArray(x.message?.content) ? x.message.content.filter((c) => c?.type === 'tool_result') : []);
101
+
102
+ // 기록들에서 이 아티팩트(a.id)를 마지막으로 게시한 결과의 경로와 시각 { path, at }. 결과에 path 가 없으면 게시 호출의 file_path.
103
+ function* findPathSteps(logs, a) {
104
+ const calls = new Map();
105
+ let best = null;
106
+ const raw = a?.id && !a.id.startsWith('h:') ? inJson(a.id) : null;
107
+ for (const log of logs ?? []) {
108
+ yield* eachRecord(
109
+ log,
110
+ (l) => l.includes('"Artifact"') || (l.includes('"toolUseResult"') && (!raw || l.includes(raw))),
111
+ (x) => {
112
+ for (const c of toolUses(x)) if (c.name === 'Artifact' && isPublish(c.input)) calls.set(c.id, c.input?.file_path);
113
+ if (!x.toolUseResult) return;
114
+ for (const p of toolResults(x)) {
115
+ if (!calls.has(p.tool_use_id) || p.is_error) continue;
116
+ const got = pickArtifact(x.toolUseResult, parseTs(x.timestamp));
117
+ if (got?.id !== a.id) continue;
118
+ const path = okPath(x.toolUseResult.path) ? x.toolUseResult.path : okPath(calls.get(p.tool_use_id)) ? calls.get(p.tool_use_id) : null;
119
+ const at = parseTs(x.timestamp);
120
+ if (path && (!best || at >= best.at)) best = { path, at };
121
+ }
122
+ },
123
+ );
124
+ }
125
+ return best;
126
+ }
127
+
128
+ // 기록들에서 path 를 쓰고 고친 일. 게시 시각(pubAt) 이전(같거나 이전)의 마지막 Write 본문(pre),
129
+ // 게시 뒤 첫 Write 본문(post), 그리고 Write·Edit·Artifact edits 가 있었던 시각들(mods)을 모은다. 본문은 둘까지만 든다.
130
+ function* findWritesSteps(logs, path, pubAt, max = SOURCE_MAX) {
131
+ let pre = null;
132
+ let post = null;
133
+ const mods = [];
134
+ const key = pathKey(path);
135
+ const esc = inJson(path);
136
+ // Windows 는 구분자·대소문자가 다르게 적힌 줄도 봐야 하므로 넓게 거른다.
137
+ const want = process.platform === 'win32' ? (l) => l.includes('"filePath"') || l.includes('"file_path"') : (l) => l.includes(esc) || l.includes(path);
138
+ for (const log of logs ?? []) {
139
+ yield* eachRecord(log, want, (x) => {
140
+ const at = parseTs(x.timestamp);
141
+ for (const c of toolUses(x)) if (c.name === 'Artifact' && isPublish(c.input) && pathKey(c.input?.file_path) === key && Array.isArray(c.input.edits) && c.input.edits.length) mods.push(at);
142
+ const r = x.toolUseResult;
143
+ if (x.type !== 'user' || !r || typeof r !== 'object' || pathKey(r.filePath) !== key) return;
144
+ if (toolResults(x).some((p) => p.is_error)) return;
145
+ if (typeof r.content === 'string' && (r.type === 'create' || r.type === 'update')) {
146
+ mods.push(at);
147
+ if (at <= pubAt) {
148
+ if (!pre || at >= pre.at) pre = { at, ...cap(r.content, max) };
149
+ } else if (!post || at < post.at) post = { at, ...cap(r.content, max) };
150
+ } else if (Array.isArray(r.structuredPatch)) mods.push(at);
151
+ });
152
+ }
153
+ return { pre, post, mods };
154
+ }
155
+
156
+ const cap = (text, max) => (text.length > max ? { text: text.slice(0, max), cut: true } : { text, cut: false });
157
+ const none = (path) => ({ kind: 'none', path, text: '', cut: false, changed: false });
158
+
159
+ // 생성기를 끝까지 돌린 값.
160
+ function run(gen) {
161
+ for (;;) {
162
+ const r = gen.next();
163
+ if (r.done) return r.value;
164
+ }
165
+ }
166
+
167
+ export const findPath = (logs, a) => run(findPathSteps(logs, a))?.path ?? null;
168
+
169
+ // 게시본과 다를 수 있는지 (#307 리뷰):
170
+ // - 로컬 파일: 마지막 게시 뒤에 같은 경로의 Write·Edit·Artifact edits 가 있었으면.
171
+ // - 기록 본문: 게시 이전 마지막 Write 를 쓰고, 그 뒤에 고친 일이 있었으면. 게시 이전 Write 가 없어 게시 뒤 첫 Write 를 쓰면 늘.
172
+ function* scanSteps(s, a) {
173
+ const logs = s?.logs ?? [];
174
+ const hit = yield* findPathSteps(logs, a);
175
+ if (!hit) return none(null);
176
+ const local = readLocal(hit.path);
177
+ const { pre, post, mods } = yield* findWritesSteps(logs, hit.path, hit.at);
178
+ if (local) return { kind: 'local', path: hit.path, text: local.text, cut: local.cut, changed: mods.some((at) => at > hit.at) };
179
+ const w = pre ?? post;
180
+ if (!w) return none(hit.path);
181
+ return { kind: 'record', path: hit.path, text: w.text, cut: w.cut, changed: w === post || mods.some((at) => at > w.at) };
182
+ }
183
+
184
+ // 기억한 위치의 Write 결과 줄 하나만 읽는다. 그 자리에 같은 경로의 Write 결과가 없으면(기록이 다시 쓰임) null.
185
+ export const LINE_MAX = 64 * 1024 * 1024;
186
+ export function readWriteAt(log, offset, length, path, max = SOURCE_MAX) {
187
+ if (!Number.isFinite(offset) || !(length > 0) || length > LINE_MAX) return null;
188
+ let fd;
189
+ try {
190
+ fd = openSync(log, 'r');
191
+ const buf = Buffer.alloc(length);
192
+ let got = 0;
193
+ while (got < length) {
194
+ const r = readSync(fd, buf, got, length - got, offset + got);
195
+ if (!r) break;
196
+ got += r;
197
+ }
198
+ if (got < length) return null;
199
+ const x = JSON.parse(buf.toString('utf8'));
200
+ const r = x?.toolUseResult;
201
+ if (x?.type !== 'user' || pathKey(r?.filePath) !== pathKey(path) || typeof r.content !== 'string' || (r.type !== 'create' && r.type !== 'update')) return null;
202
+ return cap(r.content, max);
203
+ } catch {
204
+ return null;
205
+ } finally {
206
+ if (fd != null)
207
+ try {
208
+ closeSync(fd);
209
+ } catch {}
210
+ }
211
+ }
212
+
213
+ // 기록을 읽는 tracker 가 기억한 위치로 찾는다 (claude-tracker.mjs noteSource). 훑지 않는다. 결과는 훑기(scanSteps)와 같은 규칙이다.
214
+ // 모르면 null: tracker 가 없거나, 캐시에서 이어 읽어 앞부분을 모르거나 상한 때문에 기억을 버린(srcLost) 상태에서 찾지 못했거나,
215
+ // 기억한 줄이 바뀌었거나, 게시 이전 마지막 Write 를 확실히 모를 때. srcLost 면 '고친 적 없음(changed false)' 도 믿을 수 없어 훑기로 넘긴다.
216
+ export function quickSource(s, a, find = liveTracker) {
217
+ const ts = (s?.logs ?? []).map((p) => find(p));
218
+ if (!ts.length || ts.some((t) => !t)) return null;
219
+ // 모든 기록을 처음부터 읽었고 버린 기억도 없으면 못 찾은 것도 답이다.
220
+ const lost = ts.some((t) => t.srcLost);
221
+ const complete = !lost && ts.every((t) => t.srcFrom === 0);
222
+ let hit = null;
223
+ let owner = null;
224
+ for (const t of ts) {
225
+ const p = t.artPaths?.get(a?.id);
226
+ if (p && okPath(p.path) && (!hit || p.at >= hit.at)) [hit, owner] = [p, t];
227
+ }
228
+ if (!hit) return complete ? none(null) : null;
229
+ const key = pathKey(hit.path);
230
+ // 경로를 마지막으로 쓰거나 고친 시각 (기록마다 마지막 Write 와 마지막 Edit·edits).
231
+ const lastMod = Math.max(-Infinity, ...ts.flatMap((t) => [t.edited?.get(key) ?? -Infinity, t.writes?.get(key)?.at ?? -Infinity]));
232
+ const done = (doc) => (doc.changed || !lost ? doc : null);
233
+ const local = readLocal(hit.path);
234
+ if (local) return done({ kind: 'local', path: hit.path, text: local.text, cut: local.cut, changed: lastMod > hit.at });
235
+ // 게시 이전 마지막 Write: 기록마다 마지막 Write 가 게시 이전이면 그것, 게시한 기록은 게시 때 붙여 둔 것(pre).
236
+ // 게시 뒤 Write 만 아는 기록이 있으면 그 앞 Write 를 모르므로 훑는다.
237
+ let w = null;
238
+ for (const t of ts) {
239
+ const last = t.writes?.get(key);
240
+ let x = last && last.at <= hit.at ? last : null;
241
+ if (!x && t === owner && hit.pre && hit.pre.at <= hit.at) x = hit.pre;
242
+ else if (!x && last) return null;
243
+ if (x && (!w || x.at >= w.at)) w = { ...x, log: t.path };
244
+ }
245
+ if (!w) return complete ? none(hit.path) : null;
246
+ const body = readWriteAt(w.log, w.offset, w.length, hit.path);
247
+ if (!body) return null;
248
+ return done({ kind: 'record', path: hit.path, text: body.text, cut: body.cut, changed: lastMod > w.at });
249
+ }
250
+
251
+ // 원본 찾기 (기다리는 판). s.logs: 세션 기록 경로 (메인과 서브에이전트, claude.mjs sessionTotals).
252
+ // 돌려주는 값: { kind: 'local'|'record'|'none', path, text, cut, changed }
253
+ export function loadArtifactSource(s, a) {
254
+ return quickSource(s, a) ?? run(scanSteps(s, a));
255
+ }
256
+
257
+ // 화면용: 기억한 위치로 바로 찾으면 그 값을, 아니면 null 을 돌려주고 기록 훑기를 뒤에서 시간을 잘라 돌린다.
258
+ // 한 번에 slice ms 만 돌고 다음 이벤트 루프로 넘긴다. cancelled() 가 참이면 그만둔다. 끝나면 done(doc).
259
+ export function openArtifactSource(s, a, { done, cancelled = () => false, slice = 30 } = {}) {
260
+ const quick = quickSource(s, a);
261
+ if (quick) return quick;
262
+ const gen = scanSteps(s, a);
263
+ const step = () => {
264
+ if (cancelled()) {
265
+ gen.return();
266
+ return;
267
+ }
268
+ const until = Date.now() + slice;
269
+ for (;;) {
270
+ const r = gen.next();
271
+ if (r.done) return done?.(r.value);
272
+ if (Date.now() >= until) break;
273
+ }
274
+ setImmediate(step);
275
+ };
276
+ setImmediate(step);
277
+ return null;
278
+ }
@@ -2,8 +2,18 @@
2
2
  // 게시(publish, action 이 없으면 publish) 호출과 짝이 되는 결과 줄의 toolUseResult 에서 몇 값만 꺼낸다.
3
3
  // 입력의 file_path·edits 내용·prompt 와 결과의 나머지 값(path 등)은 담지 않는다.
4
4
  import { createHash } from 'node:crypto';
5
+ import { win32 } from 'node:path';
5
6
  import { mask, stripControl } from '../text.mjs';
6
7
 
8
+ // 경로를 비교하는 키. Windows 는 구분자(/ 와 역슬래시)와 대소문자를 맞추고, 다른 OS 는 그대로 (#307).
9
+ // 아티팩트 원본으로 읽는 최대 바이트 (artifact-source.mjs, 화면의 잘림 표시).
10
+ export const SOURCE_MAX = 2 * 1024 * 1024;
11
+
12
+ export function pathKey(p, platform = process.platform) {
13
+ if (typeof p !== 'string') return null;
14
+ return platform === 'win32' ? win32.normalize(p).toLowerCase() : p;
15
+ }
16
+
7
17
  // 세션마다 남기는 아티팩트 수 (마지막 게시가 최근인 것부터).
8
18
  export const ARTIFACT_MAX = 20;
9
19
  // 짝을 기다리는 게시 호출 수 상한. 결과가 오지 않은 호출이 쌓이지 않게 한다.