@sejuneoh/aitop 0.25.0 → 0.27.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 +13 -3
- package/bin/aitop.mjs +20 -6
- package/package.json +1 -1
- package/src/cache.mjs +5 -1
- package/src/i18n.mjs +56 -19
- package/src/line.mjs +18 -6
- package/src/monthly.mjs +273 -0
- package/src/pricing.mjs +36 -7
- package/src/report.mjs +236 -31
- package/src/sources/agy-ledger.mjs +53 -13
- package/src/sources/claude-ledger.mjs +63 -12
- package/src/sources/codex-ledger.mjs +11 -12
- package/src/sources/codex.mjs +14 -0
- package/src/sources/common.mjs +19 -4
- package/src/sources/projects.mjs +179 -0
- package/src/summary.mjs +80 -0
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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);
|
|
@@ -147,12 +150,13 @@ function gather({ budget, now, days = DAYS }) {
|
|
|
147
150
|
['agy', collectAgyLedger({ budget, now, days })],
|
|
148
151
|
['codex', collectCodexLedger({ budget, days })],
|
|
149
152
|
];
|
|
150
|
-
|
|
153
|
+
// path: 리포트 --by project 가 기록 파일에서 프로젝트를 찾을 때 쓴다 (projects.mjs).
|
|
154
|
+
const books = [...trackers.entries()].map(([path, t]) => ({ tool: 'claude', path, days: t.days }));
|
|
151
155
|
const slots = [...trackers.values()].map((t) => t.slots);
|
|
152
156
|
for (const [tool, o] of others) {
|
|
153
157
|
pending += o.pending;
|
|
154
158
|
size += o.size;
|
|
155
|
-
books.push(...o.days.map((d) => ({ tool, days: d })));
|
|
159
|
+
books.push(...o.days.map((d, i) => ({ tool, path: o.paths[i], days: d, ...(o.stale?.[i] ? { staleFrom: o.stale[i] } : {}) })));
|
|
156
160
|
slots.push(...o.slots);
|
|
157
161
|
}
|
|
158
162
|
return { books, slots, pending, size };
|
|
@@ -161,14 +165,61 @@ function gather({ budget, now, days = DAYS }) {
|
|
|
161
165
|
// 기간 리포트용: 최근 days 일(최대 KEEP_DAYS) 안에 바뀐 기록의 날짜별·모델별 장부.
|
|
162
166
|
// 평소 화면(collectLedger)은 7일 안에 바뀐 기록만 보므로, 이 함수를 부를 때만 더 오래된 기록을 읽는다.
|
|
163
167
|
export function collectDaily({ budget, now = Date.now(), days = KEEP_DAYS } = {}) {
|
|
164
|
-
|
|
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) });
|
|
165
174
|
return { books, pending, size };
|
|
166
175
|
}
|
|
167
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
|
+
|
|
168
217
|
// 오늘·최근 7일·최근 1시간 합계 (Claude + agy + Codex). 아직 다 읽지 못했으면 loading 에 진행률(0~1).
|
|
169
|
-
|
|
218
|
+
// fold: 지난 날을 월별 보관함에 접을지 (평소 켠다).
|
|
219
|
+
export function collectLedger({ budget, now = Date.now(), fold = true } = {}) {
|
|
170
220
|
const g = gather({ budget, now });
|
|
171
221
|
const { pending, size } = g;
|
|
222
|
+
if (fold && !budget?.exhausted && !pending) foldLedger(g.books, now);
|
|
172
223
|
const books = g.books.map((b) => b.days);
|
|
173
224
|
const slots = g.slots;
|
|
174
225
|
const sum = (keys) => {
|
|
@@ -199,4 +250,4 @@ export function collectLedger({ budget, now = Date.now() } = {}) {
|
|
|
199
250
|
};
|
|
200
251
|
}
|
|
201
252
|
|
|
202
|
-
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 {
|
|
11
|
-
import { dayKey,
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
// 며칠 전에 시작했거나 다시 이어 쓴 세션도 시작한 날짜 폴더에 쓰므로,
|
|
97
|
-
//
|
|
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
|
|
100
|
+
for (const dir of allDayDirs()) {
|
|
103
101
|
let names = [];
|
|
104
102
|
try {
|
|
105
103
|
names = readdirSync(dir);
|
|
@@ -123,7 +121,7 @@ const books = new Map();
|
|
|
123
121
|
// 기록마다 날짜별 합계(days)와 5분 칸(slots), 아직 읽지 않은 크기(pending)·전체 크기(size).
|
|
124
122
|
// days: 최근 며칠 안에 바뀐 기록을 볼지 (평소 7일, 리포트는 더 길게).
|
|
125
123
|
export function collectCodexLedger({ budget, days = DAYS } = {}) {
|
|
126
|
-
const out = { days: [], slots: [], pending: 0, size: 0 };
|
|
124
|
+
const out = { days: [], slots: [], paths: [], pending: 0, size: 0 };
|
|
127
125
|
const files = recentFiles(days);
|
|
128
126
|
const keep = new Set(files);
|
|
129
127
|
for (const p of books.keys()) if (!keep.has(p)) books.delete(p);
|
|
@@ -134,6 +132,7 @@ export function collectCodexLedger({ budget, days = DAYS } = {}) {
|
|
|
134
132
|
out.pending += b.pending;
|
|
135
133
|
out.size += b.tail.size;
|
|
136
134
|
out.days.push(b.days);
|
|
135
|
+
out.paths.push(p);
|
|
137
136
|
out.slots.push(b.slots);
|
|
138
137
|
}
|
|
139
138
|
return out;
|
package/src/sources/codex.mjs
CHANGED
|
@@ -30,6 +30,20 @@ export function dayDirs(days = 7) {
|
|
|
30
30
|
return dirs;
|
|
31
31
|
}
|
|
32
32
|
|
|
33
|
+
// 남아 있는 날짜 폴더 전부 (sessions/YYYY/MM/DD). 장부는 시작한 날과 상관없이 최근에 바뀐 기록을 모두 봐야 해서 이것을 쓴다.
|
|
34
|
+
export function allDayDirs() {
|
|
35
|
+
const dirs = [];
|
|
36
|
+
const sub = (p) => {
|
|
37
|
+
try {
|
|
38
|
+
return readdirSync(p).filter((n) => /^\d+$/.test(n)).map((n) => join(p, n));
|
|
39
|
+
} catch {
|
|
40
|
+
return [];
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
for (const y of sub(ROOT)) for (const m of sub(y)) dirs.push(...sub(m));
|
|
44
|
+
return dirs;
|
|
45
|
+
}
|
|
46
|
+
|
|
33
47
|
// 날짜 폴더를 매초 다시 훑지 않도록 파일 이름 목록만 잠깐 재사용한다. 수정 시각은 매번 확인한다.
|
|
34
48
|
const LIST_TTL_MS = 5000;
|
|
35
49
|
let listed = { at: 0, paths: [] };
|
package/src/sources/common.mjs
CHANGED
|
@@ -27,17 +27,32 @@ export function lastDays(n, now = Date.now()) {
|
|
|
27
27
|
return keys;
|
|
28
28
|
}
|
|
29
29
|
|
|
30
|
-
//
|
|
31
|
-
// 평소 실행은 최근 7일 안에 바뀐 기록만 읽지만, 그 기록 안의
|
|
30
|
+
// 날짜별 리포트(--report daily)가 볼 수 있는 가장 긴 기간. 리포트는 30일 안에 바뀐 기록을 읽는다.
|
|
31
|
+
// 평소 실행은 최근 7일 안에 바뀐 기록만 읽지만, 그 기록 안의 날짜 합계는 캐시에 남겨(STORE_DAYS) 리포트가 다시 읽지 않게 한다.
|
|
32
32
|
export const KEEP_DAYS = 30;
|
|
33
33
|
|
|
34
|
-
//
|
|
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
|
-
|
|
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)에 모으고, 그 장부에서 가장 새 칸부터
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
// 기간 리포트 --by project 용: 기록 파일 하나가 어느 프로젝트(작업 폴더)의 것인지 찾는다.
|
|
2
|
+
// Claude 는 기록 앞부분 줄의 cwd (없으면 projects/ 아래 폴더 이름), Codex 는 turn_context.cwd (없으면 session_meta.cwd),
|
|
3
|
+
// agy 는 conversation_summaries.db 의 workspace_uris (서브에이전트는 부모 대화의 것) 를 쓴다. 못 찾으면 null.
|
|
4
|
+
// agy 기록은 immutable 로 열어 -wal 에만 있는 막 생긴 대화는 아직 안 보이므로, 그 대화는 (unknown) 으로 나올 수 있다.
|
|
5
|
+
// 장부 캐시 모양은 그대로 두고, 리포트를 낼 때만 파일 앞부분을 조금 읽는다.
|
|
6
|
+
import { openSync, readSync, closeSync, statSync } from 'node:fs';
|
|
7
|
+
import { basename, join, relative, sep } from 'node:path';
|
|
8
|
+
import { homedir } from 'node:os';
|
|
9
|
+
import { AGY_ROOT, cwdOf } from './antigravity.mjs';
|
|
10
|
+
import { openReadOnly } from '../sqlite.mjs';
|
|
11
|
+
import { debugIo } from '../log.mjs';
|
|
12
|
+
|
|
13
|
+
const HOME = process.env.CLAUDE_CONFIG_DIR ?? join(homedir(), '.claude');
|
|
14
|
+
const PROJECTS = join(HOME, 'projects');
|
|
15
|
+
// 앞부분에서 cwd 를 찾을 때 읽는 최대 크기. Codex 의 첫 줄(session_meta)은 지침 글이 들어 있어 길 수 있다.
|
|
16
|
+
const HEAD_BYTES = 256 * 1024;
|
|
17
|
+
const heads = new Map();
|
|
18
|
+
// 앞부분을 읽는 버퍼. scanHead 는 동기 함수라 하나를 돌려 쓴다.
|
|
19
|
+
const BUF = Buffer.allocUnsafe(HEAD_BYTES);
|
|
20
|
+
|
|
21
|
+
// 파일 앞부분의 완성된 줄을 차례로 pick 에 넘긴다. pick 이 true 를 돌려주면 멈춘다.
|
|
22
|
+
// 대개 첫 몇 줄에 있으므로 CHUNK 씩 읽고, 찾으면 더 읽지 않는다.
|
|
23
|
+
const CHUNK = 16 * 1024;
|
|
24
|
+
function scanHead(path, pick) {
|
|
25
|
+
let fd;
|
|
26
|
+
try {
|
|
27
|
+
fd = openSync(path, 'r');
|
|
28
|
+
const buf = BUF;
|
|
29
|
+
let len = 0;
|
|
30
|
+
let done = 0;
|
|
31
|
+
while (len < HEAD_BYTES) {
|
|
32
|
+
const n = readSync(fd, buf, len, Math.min(CHUNK, HEAD_BYTES - len), len);
|
|
33
|
+
if (n <= 0) break;
|
|
34
|
+
len += n;
|
|
35
|
+
const end = buf.lastIndexOf(10, len - 1);
|
|
36
|
+
if (end < done) continue;
|
|
37
|
+
for (const line of buf.toString('utf8', done, end).split('\n')) {
|
|
38
|
+
let x;
|
|
39
|
+
try {
|
|
40
|
+
x = JSON.parse(line);
|
|
41
|
+
} catch {
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
if (pick(x)) return;
|
|
45
|
+
}
|
|
46
|
+
done = end + 1;
|
|
47
|
+
}
|
|
48
|
+
} catch (e) {
|
|
49
|
+
debugIo('report', 'log head read failed', e, path);
|
|
50
|
+
} finally {
|
|
51
|
+
if (fd != null) closeSync(fd);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// 같은 파일(inode)이면 다시 읽지 않는다.
|
|
56
|
+
function memo(path, find) {
|
|
57
|
+
let ino = null;
|
|
58
|
+
try {
|
|
59
|
+
ino = statSync(path).ino;
|
|
60
|
+
} catch {}
|
|
61
|
+
const c = heads.get(path);
|
|
62
|
+
if (c && c.ino === ino) return c.cwd;
|
|
63
|
+
const cwd = find();
|
|
64
|
+
heads.set(path, { ino, cwd });
|
|
65
|
+
return cwd;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// Claude 기록 앞부분 줄의 cwd. 없으면 null.
|
|
69
|
+
export function claudeProject(path) {
|
|
70
|
+
return memo(path, () => {
|
|
71
|
+
let cwd = null;
|
|
72
|
+
scanHead(path, (x) => typeof x?.cwd === 'string' && x.cwd && (cwd = x.cwd));
|
|
73
|
+
return cwd;
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Claude 가 projects/ 아래 폴더 이름을 만드는 방식: 영문·숫자 밖의 글자를 - 로 바꾼다.
|
|
78
|
+
export const encodeFolder = (cwd) => cwd.replace(/[^A-Za-z0-9]/g, '-');
|
|
79
|
+
|
|
80
|
+
// cwd 를 못 찾았을 때 쓰는 projects/ 바로 아래 폴더 이름. 작업 트리 꼴(--claude-worktrees-<이름>)이면 그 부분을 뗀다.
|
|
81
|
+
export function claudeFolder(path, root = PROJECTS) {
|
|
82
|
+
const rel = relative(root, path);
|
|
83
|
+
const dir = rel.split(sep)[0];
|
|
84
|
+
if (!dir || rel.startsWith('..') || dir === rel) return null;
|
|
85
|
+
return dir.replace(/--claude-worktrees-.*$/, '') || dir;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function codexProject(path) {
|
|
89
|
+
return memo(path, () => {
|
|
90
|
+
let meta = null;
|
|
91
|
+
let turn = null;
|
|
92
|
+
scanHead(path, (x) => {
|
|
93
|
+
const p = x?.payload;
|
|
94
|
+
if (x?.type === 'session_meta' && typeof p?.cwd === 'string') meta ??= p.cwd;
|
|
95
|
+
if (x?.type === 'turn_context' && typeof p?.cwd === 'string') turn = p.cwd;
|
|
96
|
+
return turn != null;
|
|
97
|
+
});
|
|
98
|
+
return turn || meta || null;
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// 대화 id → 작업 폴더. 서브에이전트는 작업 폴더가 비어 있으면 부모를 따라 올라간다. 리포트 한 번에 한 번만 읽는다.
|
|
103
|
+
export function agyWorkspaces(root = AGY_ROOT) {
|
|
104
|
+
const out = new Map();
|
|
105
|
+
let db;
|
|
106
|
+
try {
|
|
107
|
+
db = openReadOnly(join(root, 'conversation_summaries.db'));
|
|
108
|
+
if (!db) return out;
|
|
109
|
+
const rows = db.prepare('select conversation_id id, parent_conversation_id parent, workspace_uris ws from conversation_summaries').all();
|
|
110
|
+
const byId = new Map(rows.map((r) => [r.id, r]));
|
|
111
|
+
for (const r of rows) {
|
|
112
|
+
let cur = r;
|
|
113
|
+
let cwd = cwdOf(cur.ws);
|
|
114
|
+
for (let i = 0; !cwd && cur?.parent && i < 10; i++) {
|
|
115
|
+
cur = byId.get(cur.parent);
|
|
116
|
+
cwd = cur ? cwdOf(cur.ws) : null;
|
|
117
|
+
}
|
|
118
|
+
out.set(r.id, cwd);
|
|
119
|
+
}
|
|
120
|
+
} catch (e) {
|
|
121
|
+
debugIo('report', 'agy workspaces read failed', e);
|
|
122
|
+
} finally {
|
|
123
|
+
db?.close();
|
|
124
|
+
}
|
|
125
|
+
return out;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// Claude Code 가 만든 작업 트리(<저장소>/.claude/worktrees/<이름>) 는 저장소 하나로 본다.
|
|
129
|
+
// 에이전트마다 작업 트리가 생겨 그대로 두면 열이 수십 개로 갈라진다.
|
|
130
|
+
export function projectRoot(cwd) {
|
|
131
|
+
if (!cwd) return null;
|
|
132
|
+
const m = /^(.+?)[\\/]\.claude[\\/]worktrees[\\/][^\\/]+(?:[\\/].*)?$/.exec(cwd);
|
|
133
|
+
return m ? m[1] : cwd;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// books: collectDaily 의 [{ tool, path, days }]. 각 장부에 project(작업 폴더 경로 또는 null)를 붙여 돌려준다.
|
|
137
|
+
// Claude 기록에서 cwd 를 못 찾으면 폴더 이름을 쓰되, 같은 폴더 이름이 되는 경로를 다른 기록에서 찾았으면 그 경로로 묶는다.
|
|
138
|
+
export function attachProjects(books, root = PROJECTS) {
|
|
139
|
+
let agy = null;
|
|
140
|
+
const folder = new Map();
|
|
141
|
+
const out = books.map((b) => {
|
|
142
|
+
let project = null;
|
|
143
|
+
let fallback = null;
|
|
144
|
+
if (b.path) {
|
|
145
|
+
if (b.tool === 'claude') {
|
|
146
|
+
project = claudeProject(b.path);
|
|
147
|
+
if (!project) fallback = claudeFolder(b.path, root);
|
|
148
|
+
} else if (b.tool === 'codex') project = codexProject(b.path);
|
|
149
|
+
else if (b.tool === 'agy') project = (agy ??= agyWorkspaces()).get(basename(b.path, '.db')) ?? null;
|
|
150
|
+
}
|
|
151
|
+
project = projectRoot(project);
|
|
152
|
+
// 한 폴더 이름에 서로 다른 경로가 둘 이상 모이면(/a/b-c 와 /a/b/c, 한글 이름 등) 어느 쪽인지 모르니 묶지 않는다 (false).
|
|
153
|
+
if (project) {
|
|
154
|
+
const k = encodeFolder(project);
|
|
155
|
+
const had = folder.get(k);
|
|
156
|
+
folder.set(k, had === undefined || had === project ? project : false);
|
|
157
|
+
}
|
|
158
|
+
return { ...b, project: project ?? fallback, fallback: Boolean(fallback) };
|
|
159
|
+
});
|
|
160
|
+
return out.map(({ fallback, ...b }) => (fallback ? { ...b, project: folder.get(b.project) || b.project } : b));
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// 작업 폴더 경로들 → 짧은 이름. 마지막 폴더 이름을 쓰고, 이름이 겹치면 겹치지 않을 때까지 앞 폴더를 붙인다 (dev/aitop).
|
|
164
|
+
export function projectLabels(paths) {
|
|
165
|
+
const segs = new Map();
|
|
166
|
+
for (const p of paths) segs.set(p, String(p).split(/[\\/]+/).filter(Boolean));
|
|
167
|
+
const out = new Map();
|
|
168
|
+
let todo = [...segs.keys()];
|
|
169
|
+
for (let n = 1; todo.length; n++) {
|
|
170
|
+
const name = (p) => segs.get(p).slice(-n).join('/') || p;
|
|
171
|
+
const count = new Map();
|
|
172
|
+
for (const p of segs.keys()) if (!out.has(p)) count.set(name(p), (count.get(name(p)) ?? 0) + 1);
|
|
173
|
+
// 모든 경로가 다 쓰였는데도 겹치면(같은 경로를 다르게 쓴 것) 전체 경로를 쓴다.
|
|
174
|
+
const last = todo.every((p) => segs.get(p).length <= n);
|
|
175
|
+
for (const p of todo) if (count.get(name(p)) === 1 || last) out.set(p, last && count.get(name(p)) > 1 ? p : name(p));
|
|
176
|
+
todo = todo.filter((p) => !out.has(p));
|
|
177
|
+
}
|
|
178
|
+
return out;
|
|
179
|
+
}
|
package/src/summary.mjs
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// --line 용 작은 요약 파일. 실시간 화면·--once·--json 이 세션을 다 모은 뒤 작업 중·응답 대기 수를 적고,
|
|
2
|
+
// --line 은 이 파일만 읽어 작업 중 수를 낸다 (세션 기록·프로세스 목록을 다시 읽지 않게).
|
|
3
|
+
// 가격·캐시 형식과 무관하므로 버전 폴더가 아니라 캐시 루트에 두고, 파일 안의 v 로 형식을 가른다.
|
|
4
|
+
// 그래야 다른 버전의 aitop 화면이 쓴 요약도 --line 이 읽는다.
|
|
5
|
+
import { readFileSync, writeFileSync, mkdirSync, renameSync, rmSync } from 'node:fs';
|
|
6
|
+
import { dirname, join } from 'node:path';
|
|
7
|
+
import { CACHE_ROOT } from './cache.mjs';
|
|
8
|
+
import { debugIo } from './log.mjs';
|
|
9
|
+
|
|
10
|
+
const V = 1;
|
|
11
|
+
export const SUMMARY_FILE = join(CACHE_ROOT, 'summary.json');
|
|
12
|
+
// 이보다 오래된 요약은 버린다. 화면은 수가 그대로여도 HEARTBEAT_MS 마다 다시 쓰므로 두 번 넘게 놓쳐야 버려진다.
|
|
13
|
+
// 화면을 끄면 마지막 수가 1분 안에 사라진다 (tmux 기본 갱신 15초로 네 번 안).
|
|
14
|
+
export const STALE_MS = 60_000;
|
|
15
|
+
// 수가 바뀌었을 때도 이 간격보다 자주 쓰지 않는다.
|
|
16
|
+
export const MIN_WRITE_MS = 5_000;
|
|
17
|
+
// 수가 그대로여도 이 간격마다 시각을 새로 적는다.
|
|
18
|
+
export const HEARTBEAT_MS = 20_000;
|
|
19
|
+
// 시계가 조금 어긋난 것은 봐준다. 이보다 미래 시각이면 잘못된 파일로 본다.
|
|
20
|
+
const SKEW_MS = 5_000;
|
|
21
|
+
|
|
22
|
+
const nat = (x) => Number.isInteger(x) && x >= 0;
|
|
23
|
+
|
|
24
|
+
// 세션 목록에서 요약 값을 뽑는다. 화면 헤더(ui/table.mjs)와 같은 기준이다.
|
|
25
|
+
export function summarize(sessions, now = Date.now()) {
|
|
26
|
+
const live = sessions.filter((s) => s.live);
|
|
27
|
+
const waiting = live.filter((s) => s.status === 'waiting');
|
|
28
|
+
return {
|
|
29
|
+
v: V,
|
|
30
|
+
at: now,
|
|
31
|
+
running: live.filter((s) => s.status === 'busy' || s.status === 'shell').length,
|
|
32
|
+
waiting: waiting.length,
|
|
33
|
+
// Claude 대기 수는 --line 이 세션 파일에서 바로 세므로, 그 밖의 도구 몫(지금은 Antigravity 만 대기 상태가 있다)을 따로 적는다.
|
|
34
|
+
waitingOther: waiting.filter((s) => s.tool !== 'claude').length,
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// 여러 aitop 이 함께 써도 섞이지 않게 pid 별 임시 파일에 쓰고 rename 한다 (마지막에 쓴 쪽이 남는다).
|
|
39
|
+
export function writeSummary(summary, file = SUMMARY_FILE) {
|
|
40
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
41
|
+
try {
|
|
42
|
+
mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
|
|
43
|
+
writeFileSync(tmp, JSON.stringify(summary), { mode: 0o600 });
|
|
44
|
+
renameSync(tmp, file);
|
|
45
|
+
return true;
|
|
46
|
+
} catch (e) {
|
|
47
|
+
debugIo('summary', 'summary write failed', e);
|
|
48
|
+
try {
|
|
49
|
+
rmSync(tmp, { force: true });
|
|
50
|
+
} catch {}
|
|
51
|
+
return false;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// 새 요약이면 값, 없거나 깨졌거나 오래됐으면 null.
|
|
56
|
+
export function readSummary({ file = SUMMARY_FILE, now = Date.now(), staleMs = STALE_MS } = {}) {
|
|
57
|
+
let s;
|
|
58
|
+
try {
|
|
59
|
+
s = JSON.parse(readFileSync(file, 'utf8'));
|
|
60
|
+
} catch {
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
if (s?.v !== V || !Number.isFinite(s.at) || ![s.running, s.waiting, s.waitingOther].every(nat)) return null;
|
|
64
|
+
if (now - s.at > staleMs || s.at - now > SKEW_MS) return null;
|
|
65
|
+
return s;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// 실시간 화면용: 수가 바뀌면 지난번 쓴 뒤 minMs 가 지났을 때, 그대로면 heartbeatMs 마다 쓴다.
|
|
69
|
+
export function createSummaryWriter({ file = SUMMARY_FILE, minMs = MIN_WRITE_MS, heartbeatMs = HEARTBEAT_MS, write = writeSummary } = {}) {
|
|
70
|
+
let last = null;
|
|
71
|
+
return (sessions, now = Date.now()) => {
|
|
72
|
+
const s = summarize(sessions, now);
|
|
73
|
+
const since = last ? now - last.at : Infinity;
|
|
74
|
+
const changed = !last || s.running !== last.running || s.waiting !== last.waiting || s.waitingOther !== last.waitingOther;
|
|
75
|
+
if (since < (changed ? minMs : heartbeatMs)) return false;
|
|
76
|
+
if (!write(s, file)) return false;
|
|
77
|
+
last = s;
|
|
78
|
+
return true;
|
|
79
|
+
};
|
|
80
|
+
}
|