@sejuneoh/aitop 0.26.0 → 0.28.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.
@@ -7,17 +7,20 @@ import { join } from 'node:path';
7
7
  import { homedir } from 'node:os';
8
8
  import { JsonlTail } from '../tail.mjs';
9
9
  import { loadCache, markDirty } from '../cache.mjs';
10
- import { claudeCost } from '../pricing.mjs';
11
- import { dayKey, lastDays, addSlot, addModel, lastHourOf, recentTodayOf, KEEP_DAYS } from './common.mjs';
10
+ import { claudeCost, claudeVec } from '../pricing.mjs';
11
+ import { dayKey, lastDays, addSlot, addModel, lastHourOf, recentTodayOf, recentDays, KEEP_DAYS } from './common.mjs';
12
12
  import { collectAgyLedger } from './agy-ledger.mjs';
13
13
  import { collectCodexLedger } from './codex-ledger.mjs';
14
14
  import { debugIo } from '../log.mjs';
15
+ import { foldArchive, foldHi } from '../monthly.mjs';
16
+ import { attachProjects } from './projects.mjs';
15
17
 
16
18
  export { dayKey };
17
19
 
18
20
  const HOME = process.env.CLAUDE_CONFIG_DIR ?? join(homedir(), '.claude');
19
21
  const PROJECTS = join(HOME, 'projects');
20
- const KIND = 'ledger';
22
+ // 2: 모델 몫에 사용량 벡터(u, f), 날짜 400일 보관 (#164). 이름을 바꾸면 장부만 다시 센다.
23
+ const KIND = 'ledger2';
21
24
  const DAYS = 7;
22
25
  const LIST_TTL_MS = 30_000;
23
26
  const RECENT_IDS = 64;
@@ -55,9 +58,7 @@ export class UsageTracker {
55
58
  }
56
59
 
57
60
  snapshot() {
58
- const keep = new Set(lastDays(KEEP_DAYS));
59
- const days = Object.fromEntries(Object.entries(this.days).filter(([k]) => keep.has(k)));
60
- return { offset: this.tail.lineOffset, days, slots: this.slots, recent: [...this.recent] };
61
+ return { offset: this.tail.lineOffset, days: recentDays(this.days), slots: this.slots, recent: [...this.recent] };
61
62
  }
62
63
 
63
64
  // 같은 message.id 가 여러 줄로 반복되므로 직전 값과의 차이만, 그 줄의 날짜와 5분 칸에 더한다.
@@ -77,7 +78,9 @@ export class UsageTracker {
77
78
  const dTokens = tokensOf(u) - tokensOf(prev?.u);
78
79
  day.tokens += dTokens;
79
80
  day.cost += dCost;
80
- addModel(day, m.model, dTokens, dCost, !cost && tokensOf(u) > 0);
81
+ const vec = claudeVec(u);
82
+ const was = claudeVec(prev?.u);
83
+ addModel(day, m.model, dTokens, dCost, !cost && tokensOf(u) > 0, vec.map((x, i) => x - was[i]), u.speed === 'fast');
81
84
  day.costNoCache = (day.costNoCache ?? 0) + (cost?.noCache ?? 0) - (prev?.costNoCache ?? 0);
82
85
  if (unknown) day.unknown = true;
83
86
  addSlot(this.slots, at, dCost, dNoCache, unknown);
@@ -153,7 +156,7 @@ function gather({ budget, now, days = DAYS }) {
153
156
  for (const [tool, o] of others) {
154
157
  pending += o.pending;
155
158
  size += o.size;
156
- books.push(...o.days.map((d, i) => ({ tool, path: o.paths[i], days: d })));
159
+ books.push(...o.days.map((d, i) => ({ tool, path: o.paths[i], days: d, ...(o.stale?.[i] ? { staleFrom: o.stale[i] } : {}) })));
157
160
  slots.push(...o.slots);
158
161
  }
159
162
  return { books, slots, pending, size };
@@ -162,14 +165,61 @@ function gather({ budget, now, days = DAYS }) {
162
165
  // 기간 리포트용: 최근 days 일(최대 KEEP_DAYS) 안에 바뀐 기록의 날짜별·모델별 장부.
163
166
  // 평소 화면(collectLedger)은 7일 안에 바뀐 기록만 보므로, 이 함수를 부를 때만 더 오래된 기록을 읽는다.
164
167
  export function collectDaily({ budget, now = Date.now(), days = KEEP_DAYS } = {}) {
165
- const { books, pending, size } = gather({ budget, now, days: Math.max(DAYS, Math.min(KEEP_DAYS, days)) });
168
+ return collectSpan({ budget, now, days: Math.min(KEEP_DAYS, days) });
169
+ }
170
+
171
+ // 최근 days 일(상한 없음) 안에 바뀐 기록의 장부. 월별 리포트가 보관함을 처음 채울 때 1년치까지 넓혀 읽는다.
172
+ export function collectSpan({ budget, now = Date.now(), days = KEEP_DAYS } = {}) {
173
+ const { books, pending, size } = gather({ budget, now, days: Math.max(DAYS, days) });
166
174
  return { books, pending, size };
167
175
  }
168
176
 
177
+ // 남은 Claude 기록 중 가장 오래된 수정 시각(ms, 없으면 null). Claude Code 는 수정 시각이 오래된 기록부터 지우므로,
178
+ // 이 시각이 든 날까지는 지워진 기록이 있었을 수 있다 (월별 리포트가 '일부' 를 가를 때 쓴다).
179
+ export function oldestClaudeMtime() {
180
+ let oldest = null;
181
+ const see = (p) => {
182
+ try {
183
+ const m = statSync(p).mtimeMs;
184
+ if (oldest == null || m < oldest) oldest = m;
185
+ } catch {}
186
+ };
187
+ let dirs = [];
188
+ try {
189
+ dirs = readdirSync(PROJECTS);
190
+ } catch {}
191
+ for (const dir of dirs) {
192
+ let names = [];
193
+ try {
194
+ names = readdirSync(join(PROJECTS, dir));
195
+ } catch {
196
+ continue;
197
+ }
198
+ for (const n of names) if (n.endsWith('.jsonl')) see(join(PROJECTS, dir, n));
199
+ }
200
+ return oldest;
201
+ }
202
+
203
+ // 평소 화면이 하루 한 번 지난 날을 월별 보관함(monthly.mjs)에 접는다. 7일 안에 바뀐 기록을 다 읽었을 때만
204
+ // (한도 소진 없음, 남은 바이트 없음. 갱신이 실패한 agy 기록이 있으면 monthly.mjs foldArchive 가 그 날들을 미룬다):
205
+ // 어떤 날 D 에 쓴 기록은 D 이후에 바뀌었으니, 7일 창 안의 날(lo~그제)은 이 장부에 빠짐없이 들어 있다.
206
+ // 이미 접었으면 보관함 파일만 읽고 끝난다. 실패(다른 aitop 이 먼저 씀 등)면 10분 뒤 다시 해 본다.
207
+ let folded = { hi: null, retry: 0 };
208
+ const FOLD_RETRY_MS = 10 * 60_000;
209
+ function foldLedger(books, now) {
210
+ const hi = foldHi(now);
211
+ if (folded.hi === hi || now < folded.retry) return;
212
+ const r = foldArchive(books, { lo: lastDays(DAYS, now).at(-1), hi, now, attach: attachProjects });
213
+ if (r === 'busy' || r === 'error') folded = { hi: null, retry: now + FOLD_RETRY_MS };
214
+ else folded = { hi, retry: 0 };
215
+ }
216
+
169
217
  // 오늘·최근 7일·최근 1시간 합계 (Claude + agy + Codex). 아직 다 읽지 못했으면 loading 에 진행률(0~1).
170
- export function collectLedger({ budget, now = Date.now() } = {}) {
218
+ // fold: 지난 날을 월별 보관함에 접을지 (평소 켠다).
219
+ export function collectLedger({ budget, now = Date.now(), fold = true } = {}) {
171
220
  const g = gather({ budget, now });
172
221
  const { pending, size } = g;
222
+ if (fold && !budget?.exhausted && !pending) foldLedger(g.books, now);
173
223
  const books = g.books.map((b) => b.days);
174
224
  const slots = g.slots;
175
225
  const sum = (keys) => {
@@ -200,4 +250,4 @@ export function collectLedger({ budget, now = Date.now() } = {}) {
200
250
  };
201
251
  }
202
252
 
203
- export const _test = { lastDays };
253
+ export const _test = { lastDays, resetFold: () => (folded = { hi: null, retry: 0 }) };
@@ -7,14 +7,14 @@ import { join } from 'node:path';
7
7
  import { JsonlTail } from '../tail.mjs';
8
8
  import { loadCache, markDirty } from '../cache.mjs';
9
9
  import { codexCost } from '../pricing.mjs';
10
- import { dayDirs } from './codex.mjs';
11
- import { dayKey, lastDays, addSlot, addModel, KEEP_DAYS } from './common.mjs';
10
+ import { allDayDirs } from './codex.mjs';
11
+ import { dayKey, addSlot, addModel, recentDays } from './common.mjs';
12
12
  import { debugIo } from '../log.mjs';
13
13
 
14
- const KIND = 'codex-ledger';
14
+ // 2: 사용량 벡터, 날짜 400일 보관 (#164).
15
+ const KIND = 'codex-ledger2';
15
16
  const DAYS = 7;
16
17
  const LIST_TTL_MS = 30_000;
17
- const SCAN_DAYS = 30;
18
18
 
19
19
  // total_token_usage 를 codexCost 가 받는 모양으로 바꾼다 (input 은 캐시 제외).
20
20
  export function tokensOf(t) {
@@ -62,9 +62,7 @@ export class CodexBook {
62
62
  }
63
63
 
64
64
  snapshot() {
65
- const keep = new Set(lastDays(KEEP_DAYS));
66
- const days = Object.fromEntries(Object.entries(this.days).filter(([k]) => keep.has(k)));
67
- return { offset: this.tail.lineOffset, model: this.model, last: this.last, days, slots: this.slots };
65
+ return { offset: this.tail.lineOffset, model: this.model, last: this.last, days: recentDays(this.days), slots: this.slots };
68
66
  }
69
67
 
70
68
  apply(x) {
@@ -85,7 +83,7 @@ export class CodexBook {
85
83
  day.tokens += tokens;
86
84
  day.cost += cost?.total ?? 0;
87
85
  day.costNoCache += cost?.noCache ?? 0;
88
- addModel(day, this.model, tokens, cost?.total ?? 0, !cost);
86
+ addModel(day, this.model, tokens, cost?.total ?? 0, !cost, [d.input, d.output, d.cacheRead, 0, 0]);
89
87
  if (!cost) day.unknown = true;
90
88
  addSlot(this.slots, at, cost?.total ?? 0, cost?.noCache ?? 0, !cost);
91
89
  }
@@ -93,13 +91,13 @@ export class CodexBook {
93
91
 
94
92
  let listed = { at: 0, files: [], days: 0 };
95
93
 
96
- // 며칠 전에 시작했거나 다시 이어 쓴 세션도 시작한 날짜 폴더에 쓰므로, 30일치 폴더에서 7일 안에 바뀐 기록을 고른다.
97
- // 7일보다 오래된 줄은 날짜 키로 걸러진다. 리포트처럼 days 를 늘리면 폴더도 그만큼 더 거슬러 본다 (30일 리포트면 53일치).
94
+ // 며칠 전에 시작했거나 다시 이어 쓴 세션도 시작한 날짜 폴더에 쓰므로, 모든 날짜 폴더에서 days 일 안에 바뀐 기록을 고른다.
95
+ // 오래전에 시작해 최근까지 이어 쓴 세션도 빠지지 않아야 월별 보관함에 빠짐없이 접힌다 (목록은 30초 동안 다시 쓴다).
98
96
  function recentFiles(days = DAYS) {
99
97
  if (listed.days === days && Date.now() - listed.at < LIST_TTL_MS) return listed.files;
100
98
  const cutoff = Date.now() - days * 86400_000;
101
99
  const files = [];
102
- for (const dir of dayDirs(SCAN_DAYS + days - DAYS)) {
100
+ for (const dir of allDayDirs()) {
103
101
  let names = [];
104
102
  try {
105
103
  names = readdirSync(dir);
@@ -4,18 +4,23 @@ import { join, basename } from 'node:path';
4
4
  import { homedir } from 'node:os';
5
5
  import { JsonlTail } from '../tail.mjs';
6
6
  import { loadCache, markDirty } from '../cache.mjs';
7
- import { findProcesses, isCodex, openFiles, processStart } from '../procs.mjs';
7
+ import { canListProcesses, findProcesses, isCodex, openFiles, processStart } from '../procs.mjs';
8
8
  import { addActivity, emptyTokens, parseTs, pushEvent, describeTool, isNoisePrompt } from './common.mjs';
9
9
  import { addChange, mergeFiles } from './files.mjs';
10
10
  import { codexCost } from '../pricing.mjs';
11
11
  import { parsePatch, extractPatch, patchSucceeded } from './patch.mjs';
12
12
  import { debug, debugIo } from '../log.mjs';
13
+ import { lastName } from '../paths.mjs';
13
14
 
14
15
  // 지시 탭에 쓰는 지시 목록은 최근 것만 남긴다.
15
16
  const MAX_TURNS = 50;
16
17
 
17
18
  const ROOT = join(process.env.CODEX_HOME ?? join(homedir(), '.codex'), 'sessions');
18
19
  const RECENT_MS = 24 * 3600 * 1000;
20
+ // 프로세스 목록을 못 얻는 OS(지금은 Windows)에서는 이 시간 안에 바뀐 기록을 실행 중으로 본다.
21
+ // codex 는 답할 때마다 기록에 쓰므로, 답을 읽고 다음 지시를 쓰는 동안(대개 몇 분)은 남고 닫은 세션은 곧 빠진다.
22
+ // Claude 팀원의 MEMBER_STALE_MS(15분)보다 짧게 둔다. 실제 프로세스가 없으니 끝난 세션이 오래 남는 쪽이 더 헷갈린다.
23
+ export const NO_PROC_LIVE_MS = 10 * 60_000;
19
24
 
20
25
  const states = new Map();
21
26
 
@@ -30,6 +35,20 @@ export function dayDirs(days = 7) {
30
35
  return dirs;
31
36
  }
32
37
 
38
+ // 남아 있는 날짜 폴더 전부 (sessions/YYYY/MM/DD). 장부는 시작한 날과 상관없이 최근에 바뀐 기록을 모두 봐야 해서 이것을 쓴다.
39
+ export function allDayDirs() {
40
+ const dirs = [];
41
+ const sub = (p) => {
42
+ try {
43
+ return readdirSync(p).filter((n) => /^\d+$/.test(n)).map((n) => join(p, n));
44
+ } catch {
45
+ return [];
46
+ }
47
+ };
48
+ for (const y of sub(ROOT)) for (const m of sub(y)) dirs.push(...sub(m));
49
+ return dirs;
50
+ }
51
+
33
52
  // 날짜 폴더를 매초 다시 훑지 않도록 파일 이름 목록만 잠깐 재사용한다. 수정 시각은 매번 확인한다.
34
53
  const LIST_TTL_MS = 5000;
35
54
  let listed = { at: 0, paths: [] };
@@ -266,11 +285,14 @@ function applyLine(st, x) {
266
285
 
267
286
  export const _test = { newState, applyLine, phaseOf, snapshot };
268
287
 
269
- export function collectCodex({ showEnded, budget, filesOf = openFiles, startOf = processStart }) {
270
- const procs = findProcesses(isCodex);
271
- if (!procs.length && !showEnded) return [];
288
+ export function collectCodex({ showEnded, budget, filesOf = openFiles, startOf = processStart, canList = canListProcesses }) {
289
+ // 프로세스를 못 세면 숨기지 않고 최근에 바뀐 기록으로 판정한다 (pid 는 null).
290
+ const blind = !canList();
291
+ const procs = blind ? [] : findProcesses(isCodex);
292
+ if (!procs.length && !showEnded && !blind) return [];
272
293
 
273
- const files = recentFiles();
294
+ const fresh = (f) => Date.now() - f.mtime <= NO_PROC_LIVE_MS;
295
+ const files = blind && !showEnded ? recentFiles().filter(fresh) : recentFiles();
274
296
  const read = (path) => {
275
297
  let st = states.get(path);
276
298
  if (!st) states.set(path, (st = newState(path)));
@@ -322,6 +344,8 @@ export function collectCodex({ showEnded, budget, filesOf = openFiles, startOf =
322
344
  }
323
345
  }
324
346
 
347
+ if (blind) for (const f of files) if (fresh(f)) liveByPath.set(f.path, null);
348
+
325
349
  const seen = new Set(files.map((f) => f.path));
326
350
  for (const path of states.keys()) if (!seen.has(path)) states.delete(path);
327
351
 
@@ -339,9 +363,9 @@ export function collectCodex({ showEnded, budget, filesOf = openFiles, startOf =
339
363
  id: st.id,
340
364
  pid: pid ?? null,
341
365
  kind: 'interactive',
342
- name: basename(st.cwd ?? '') || 'codex',
366
+ name: lastName(st.cwd) || 'codex',
343
367
  cwd: st.cwd,
344
- project: basename(st.cwd ?? ''),
368
+ project: lastName(st.cwd),
345
369
  branch: st.branch,
346
370
  model: st.model,
347
371
  live,
@@ -367,7 +391,7 @@ export function collectCodex({ showEnded, budget, filesOf = openFiles, startOf =
367
391
  // 아직 세션 파일을 만들지 않은(첫 입력 전) codex 프로세스도 보여 준다.
368
392
  for (const [cwd, pids] of slots) {
369
393
  for (const pid of pids) {
370
- out.push({ tool: 'codex', id: `pid-${pid}`, pid, kind: 'interactive', name: basename(cwd ?? '') || 'codex', cwd, project: basename(cwd ?? ''), live: true, status: 'idle', phase: { kind: 'idle', msg: 'firstInput' }, cost: null, now: '', updatedAt: Date.now(), tokens: emptyTokens(), context: { used: 0, window: 0 }, events: [], members: [] });
394
+ out.push({ tool: 'codex', id: `pid-${pid}`, pid, kind: 'interactive', name: lastName(cwd) || 'codex', cwd, project: lastName(cwd), live: true, status: 'idle', phase: { kind: 'idle', msg: 'firstInput' }, cost: null, now: '', updatedAt: Date.now(), tokens: emptyTokens(), context: { used: 0, window: 0 }, events: [], members: [] });
371
395
  }
372
396
  }
373
397
  return out;
@@ -27,17 +27,32 @@ export function lastDays(n, now = Date.now()) {
27
27
  return keys;
28
28
  }
29
29
 
30
- // 장부가 날짜별로 남기는 일수. 기간 리포트(--report)가 볼 수 있는 가장 긴 기간이기도 하다.
31
- // 평소 실행은 최근 7일 안에 바뀐 기록만 읽지만, 그 기록 안의 30일치 날짜 합계는 캐시에 남겨 리포트가 다시 읽지 않게 한다.
30
+ // 날짜별 리포트(--report daily)가 볼 수 있는 가장 긴 기간. 리포트는 30일 안에 바뀐 기록을 읽는다.
31
+ // 평소 실행은 최근 7일 안에 바뀐 기록만 읽지만, 그 기록 안의 날짜 합계는 캐시에 남겨(STORE_DAYS) 리포트가 다시 읽지 않게 한다.
32
32
  export const KEEP_DAYS = 30;
33
33
 
34
- // 하루 합계(day)에 모델별 몫 { tokens, cost } 를 더한다. 모델 이름을 모르면 'unknown' 으로 센다.
34
+ // 캐시에 날짜별 합계를 남기는 일수. 월별 보관함(monthly.mjs)이 12개월치를 처음 채울 때 다시 읽지 않게 1년 넘게 남긴다.
35
+ // 기록 하나에는 그 기록이 쓰인 날만 있어 길게 남겨도 캐시가 거의 커지지 않는다.
36
+ export const STORE_DAYS = 400;
37
+
38
+ // 날짜별 합계 중 최근 n 일(키 비교) 것만 남긴 복사본.
39
+ export function recentDays(days, n = STORE_DAYS, now = Date.now()) {
40
+ const from = dayKey(now - (n - 1) * 86400_000);
41
+ return Object.fromEntries(Object.entries(days).filter(([k]) => k >= from));
42
+ }
43
+
44
+ // 하루 합계(day)에 모델별 몫 { tokens, cost, u } 를 더한다. 모델 이름을 모르면 'unknown' 으로 센다.
35
45
  // unknown: 가격표에 없는 모델이라 비용을 0 으로 셌을 때. 그 모델 몫에 unknown 을 남겨 리포트가 ? 를 붙인다.
36
- export function addModel(day, model, tokens, cost, unknown = false) {
46
+ // vec: 사용량 벡터(pricing.mjs VEC). fast 면 f 에 따로 더한다 (Claude fast 모드는 단가가 다르다).
47
+ export function addModel(day, model, tokens, cost, unknown = false, vec = null, fast = false) {
37
48
  const m = ((day.models ??= {})[String(model || 'unknown')] ??= { tokens: 0, cost: 0 });
38
49
  m.tokens += tokens;
39
50
  m.cost += cost;
40
51
  if (unknown) m.unknown = true;
52
+ if (vec) {
53
+ const to = fast ? (m.f ??= [0, 0, 0, 0, 0]) : (m.u ??= [0, 0, 0, 0, 0]);
54
+ for (let i = 0; i < to.length; i++) to[i] += vec[i] ?? 0;
55
+ }
41
56
  }
42
57
 
43
58
  // 지출 속도용 짧은 구간 장부. 비용을 5분 칸(키 = 칸 시작 시각 ms)에 모으고, 그 장부에서 가장 새 칸부터
@@ -6,7 +6,10 @@
6
6
  // *** Add File: src/new.mjs (+ 줄이 본문)
7
7
  // *** Delete File: src/old.mjs
8
8
  // *** End Patch
9
- import { isAbsolute, join } from 'node:path';
9
+ import { isAbsolute, join, normalize } from 'node:path';
10
+
11
+ // Windows 는 패치의 절대 경로(C:/x/y)도 \ 로 맞춰 화면에서 섞이지 않게 한다. 그 밖의 OS 는 그대로 둔다.
12
+ const WIN = process.platform === 'win32';
10
13
 
11
14
  // 글 안에서 패치 부분만 꺼낸다 (예전 shell 호출은 명령 인자 안에 들어 있다).
12
15
  // 시작·끝 표시는 줄 전체가 그 표시일 때만 본다. 본문 글에 '*** End Patch' 가 들어 있어도 끊기지 않게 한다.
@@ -22,7 +25,7 @@ export function extractPatch(text) {
22
25
  export function parsePatch(text, cwd) {
23
26
  const patch = extractPatch(text);
24
27
  if (!patch) return [];
25
- const abs = (p) => (isAbsolute(p) || !cwd ? p : join(cwd, p));
28
+ const abs = (p) => (isAbsolute(p) || !cwd ? (WIN ? normalize(p) : p) : join(cwd, p));
26
29
  const out = [];
27
30
  let cur = null;
28
31
  let hunk = null;
package/src/ui/draw.mjs CHANGED
@@ -1,6 +1,7 @@
1
1
  // 그리기 기본: 조각(segment) 줄 만들기·자르기·채우기, 상자, 가로줄, 게이지, 시각·금액 표기.
2
2
  import { pad, stripControl, truncate, width } from '../text.mjs';
3
3
  import { homedir } from 'node:os';
4
+ import { tildeIn } from '../paths.mjs';
4
5
  import { NO_COLOR, PALETTE, PHASE_COLOR, RESET, style } from './theme.mjs';
5
6
  import { glyphs } from './glyphs.mjs';
6
7
 
@@ -85,7 +86,8 @@ export function money(usd, unknown = false) {
85
86
  return dollars(usd);
86
87
  }
87
88
 
88
- export const tilde = (p) => (p ?? '').replace(homedir(), '~');
89
+ // 홈 폴더로 시작하는 경로만 줄인다. Windows 는 \ 와 대소문자를 무시한다 (paths.mjs).
90
+ export const tilde = (p) => tildeIn(p, homedir());
89
91
 
90
92
  export const two = (n) => String(n).padStart(2, '0');
91
93