@sejuneoh/aitop 0.24.0 → 0.26.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 +6 -3
- package/bin/aitop.mjs +38 -11
- package/package.json +1 -1
- package/src/cache.mjs +3 -1
- package/src/collect.mjs +7 -9
- package/src/i18n.mjs +27 -17
- package/src/line.mjs +18 -6
- package/src/loading.mjs +45 -0
- package/src/order.mjs +9 -3
- package/src/report.mjs +86 -16
- package/src/sources/agy-ledger.mjs +2 -1
- package/src/sources/claude-ledger.mjs +3 -2
- package/src/sources/claude.mjs +8 -3
- package/src/sources/codex-ledger.mjs +2 -1
- package/src/sources/projects.mjs +179 -0
- package/src/summary.mjs +80 -0
- package/src/ui/glyphs.mjs +3 -0
- package/src/ui/table.mjs +32 -9
- package/src/ui.mjs +6 -2
package/README.md
CHANGED
|
@@ -5,6 +5,8 @@
|
|
|
5
5
|
|
|
6
6
|
**`top` for your AI coding agents.** A read-only terminal monitor that shows every Claude Code, Codex CLI and Antigravity CLI session on your machine in one live screen: what each one is doing, which ones are waiting for you, and how many tokens they used.
|
|
7
7
|
|
|
8
|
+

|
|
9
|
+
|
|
8
10
|
- **Live status** of every session and its subagents: thinking, running a tool, waiting for you, idle
|
|
9
11
|
- **Waiting alerts**: blocked sessions jump to the top, with optional bell, desktop notification or hook command
|
|
10
12
|
- **Tokens and cost** per session and for today / last 7 days, at public API list prices
|
|
@@ -29,7 +31,7 @@ aitop live screen
|
|
|
29
31
|
aitop --all include sessions that ended in the last 24 hours
|
|
30
32
|
aitop --json print a snapshot as JSON and exit
|
|
31
33
|
aitop --doctor check which tools and logs aitop can see
|
|
32
|
-
aitop --line print one short status line and exit (for tmux, e.g. $54.13/$50 wait 2 $3.1/h)
|
|
34
|
+
aitop --line print one short status line and exit (for tmux, e.g. $54.13/$50 wait 2 run 3 $3.1/h)
|
|
33
35
|
aitop --report daily daily cost table and exit
|
|
34
36
|
aitop --help all options
|
|
35
37
|
aitop --lang ko Korean screen, help, doctor and error messages (also AITOP_LANG=ko or "lang": "ko" in the config file)
|
|
@@ -41,15 +43,16 @@ In `--json`, `phase` stays the Korean status text in every language (as does `AI
|
|
|
41
43
|
|
|
42
44
|
### Daily report
|
|
43
45
|
|
|
44
|
-
`aitop --report daily` prints tokens and cost (API list price, like the header) per day, newest first, with a total row, then exits. Columns are per tool by default
|
|
46
|
+
`aitop --report daily` prints tokens and cost (API list price, like the header) per day, newest first, with a total row, then exits. Columns are per tool by default, per model with `--by model`, or per project with `--by project` (the last folder name of the working directory: Claude log `cwd`, Codex `turn_context.cwd`, agy workspace; Claude Code worktrees under `<repo>/.claude/worktrees/` count as the repo; `(unknown)` when missing; extra columns beyond the terminal width are merged into `(others)`, `--json` lists all with a `paths` map); `--days N` goes back up to 30 days, and `--json` gives the same numbers for scripts. The first run reads up to 30 days of logs, so it can take a while (progress shows on stderr); later runs use the cache.
|
|
45
47
|
|
|
46
48
|
```
|
|
47
49
|
aitop --report daily --by model --days 14
|
|
50
|
+
aitop --report daily --by project --days 7
|
|
48
51
|
```
|
|
49
52
|
|
|
50
53
|
### tmux status line
|
|
51
54
|
|
|
52
|
-
`aitop --line` prints today's cost (API list price, `/$<budget>` when a daily budget is set), the number of Claude Code sessions
|
|
55
|
+
`aitop --line` prints today's cost (API list price, `/$<budget>` when a daily budget is set), the number of sessions waiting for you (`wait 2`, Claude Code counted live), the number of sessions running (`run 3`), and spend over the last hour. Items that are 0 are left out, and `--line-width N` (default 40) drops items from the end. It reads only aitop's cache, so it is fast once `aitop` has run before; with no cache yet it prints `...` after about 1.5 seconds. The running count (and waiting Antigravity sessions) come from a small summary that the live screen, `--once` and `--json` write to the cache; when no summary is newer than 60 seconds, `run` is left out rather than shown wrong. `--line=tmux` adds tmux colors, `NO_COLOR` turns them off.
|
|
53
56
|
|
|
54
57
|
```tmux
|
|
55
58
|
set -g status-right '#(aitop --line=tmux)'
|
package/bin/aitop.mjs
CHANGED
|
@@ -41,7 +41,7 @@ if (line.error) {
|
|
|
41
41
|
process.stderr.write(`aitop: ${line.error}\n`);
|
|
42
42
|
process.exit(2);
|
|
43
43
|
}
|
|
44
|
-
// --report daily, --by tool|model, --days <N> 은 reportOption 이 꺼낸다.
|
|
44
|
+
// --report daily, --by tool|model|project, --days <N> 은 reportOption 이 꺼낸다.
|
|
45
45
|
const report = reportOption(line.rest);
|
|
46
46
|
if (report.error) {
|
|
47
47
|
process.stderr.write(`aitop: ${report.error}\n`);
|
|
@@ -149,17 +149,21 @@ if (line.mode) {
|
|
|
149
149
|
// --report: 날짜별 사용량 표(또는 --json)를 내고 끝낸다. 실시간 화면·세션 목록은 읽지 않고 장부만 읽는다.
|
|
150
150
|
// 처음 실행은 30일치 기록을 읽으므로 stderr 가 터미널이면 진행률을 보이고, 시간 상한(AITOP_REPORT_MS, 기본 120초)을 넘으면 읽은 만큼 낸다.
|
|
151
151
|
if (report.kind) {
|
|
152
|
-
const { buildReport, collectReport, formatReport, progressWriter, reportJson, MAX_DAYS } = await import('../src/report.mjs');
|
|
152
|
+
const { buildReport, collectReport, fitReport, formatReport, PIPE_COLUMNS, progressWriter, reportJson, MAX_DAYS } = await import('../src/report.mjs');
|
|
153
153
|
const { flushCache } = await import('../src/cache.mjs');
|
|
154
154
|
if (report.capped) process.stderr.write(`aitop: ${t('report.capped', { n: MAX_DAYS })}\n`);
|
|
155
155
|
const progress = progressWriter();
|
|
156
156
|
const maxMs = Number(process.env.AITOP_REPORT_MS) > 0 ? Number(process.env.AITOP_REPORT_MS) : undefined;
|
|
157
157
|
const now = Date.now();
|
|
158
|
-
const got = await collectReport({ days: report.days, maxMs, now, onProgress: progress.update });
|
|
158
|
+
const got = await collectReport({ days: report.days, maxMs, now, by: report.by, onProgress: progress.update });
|
|
159
159
|
progress.done();
|
|
160
160
|
flushCache();
|
|
161
161
|
if (got.partial && args.has('--json')) process.stderr.write(`aitop: ${t('report.partial')}\n`);
|
|
162
|
-
|
|
162
|
+
// --by project 표는 터미널 폭(터미널이 아니면 COLUMNS 를 export 한 경우에만 그 폭, 아니면 열 8개)에 맞춰 열을 줄이고 나머지를 하나로 합친다 (--json 은 다 낸다).
|
|
163
|
+
const fit = report.by === 'project' && !args.has('--json');
|
|
164
|
+
const cols = process.stdout.isTTY ? process.stdout.columns : Number(process.env.COLUMNS) || 0;
|
|
165
|
+
let r = buildReport(got.books, { by: report.by, days: report.days, now, maxColumns: fit && !cols ? PIPE_COLUMNS : Infinity });
|
|
166
|
+
if (fit && cols) r = fitReport(r, cols);
|
|
163
167
|
const text = args.has('--json') ? JSON.stringify(reportJson(r, VERSION, { partial: got.partial }), null, 2) : formatReport(r, { partial: got.partial });
|
|
164
168
|
process.stdout.on('error', (err) => process.exit(err.code === 'EPIPE' ? 0 : 1));
|
|
165
169
|
await new Promise((resolve) => process.stdout.write(text + '\n', resolve));
|
|
@@ -195,9 +199,11 @@ const { arrange } = await import('../src/order.mjs');
|
|
|
195
199
|
const { frameTimer } = await import('../src/frames.mjs');
|
|
196
200
|
const { flushCache } = await import('../src/cache.mjs');
|
|
197
201
|
const { toJson } = await import('../src/json.mjs');
|
|
202
|
+
const { createSummaryWriter, summarize, writeSummary } = await import('../src/summary.mjs');
|
|
198
203
|
const { createAttention, updateAttention, markSeen, nextAttention, windowTitle, createWaitWatch, takeNewlyWaiting, attentionCounts } = await import('../src/attention.mjs');
|
|
199
204
|
const { createNotifier } = await import('../src/notify.mjs');
|
|
200
205
|
const { onKey, fixFocus } = await import('../src/keys.mjs');
|
|
206
|
+
const { admit, createLoading, latchReady } = await import('../src/loading.mjs');
|
|
201
207
|
|
|
202
208
|
// 요청 전체 보기는 기본으로 꺼 둔다. 켜지 않으면 상세 패널에도 --json 에도 나가지 않는다.
|
|
203
209
|
const showRequests = opt.showRequests;
|
|
@@ -205,8 +211,12 @@ const showRequests = opt.showRequests;
|
|
|
205
211
|
const settings = { budgetDay: opt.budgetDay, notify: Boolean(alerts.notify), onWaiting: Boolean(alerts.onWaiting), debug: log.on, configPath: config.path };
|
|
206
212
|
const view = { showRequests, budgetDay: opt.budgetDay, hideIdleTools: opt.hideIdleTools, settings, data: null, selectedId: null, showDetail: 'auto', showEnded: opt.all, frame: 0, filter: '', searching: false, help: false, focus: null, filePath: null, diffScroll: 0, tab: 'now', costMode: 'api', sort: 'default', group: 'none', pins: [] };
|
|
207
213
|
const once = args.has('--once') || args.has('--json') || !process.stdout.isTTY;
|
|
214
|
+
// ready: 시작할 때 세션 기록을 다 읽었는지 (loading.mjs). 그 전에는 비용·컨텍스트 정렬과 ▲ 를 고정한다. 한 번에 다 읽는 --once·--json 은 처음부터 준비 완료다.
|
|
215
|
+
view.ready = once;
|
|
216
|
+
const loading = createLoading();
|
|
208
217
|
// 실시간 화면에서 한 번 갱신할 때 읽는 기록 양과 시간. 큰 기록은 여러 번에 나눠 읽어서 키 입력이 막히지 않게 한다.
|
|
209
|
-
|
|
218
|
+
// AITOP_TICK_BYTES: 테스트에서 캐시 없는 긴 로딩을 흉내 낼 때 쓴다.
|
|
219
|
+
const TICK_BUDGET = Number(process.env.AITOP_TICK_BYTES) > 0 ? Number(process.env.AITOP_TICK_BYTES) : 24 * 1024 * 1024;
|
|
210
220
|
const TICK_MS = 60;
|
|
211
221
|
// 덜 읽은 기록이 있으면 1초를 기다리지 않고 이만큼 쉰 뒤 이어 읽는다 (그 사이 키 입력과 그리기가 돈다).
|
|
212
222
|
const CATCH_UP_MS = 15;
|
|
@@ -220,10 +230,14 @@ const bell = opt.bell;
|
|
|
220
230
|
const waitWatch = createWaitWatch();
|
|
221
231
|
const notifier = !once && (alerts.notify || alerts.onWaiting) ? createNotifier(alerts) : null;
|
|
222
232
|
|
|
223
|
-
|
|
233
|
+
// throttle: 주기 갱신(tick)에서만 참이다. 로딩 중에는 loading.mjs 의 admit 이 허락할 때만 화면 데이터를 바꾼다.
|
|
234
|
+
// 알림(벨·--notify·--on-waiting)은 화면에 올리지 않은 갱신에서도 그대로 돈다. 돌려주는 값은 화면 데이터를 바꿨는지.
|
|
235
|
+
function refresh({ throttle = false } = {}) {
|
|
224
236
|
const data = collect({ showEnded: view.showEnded, selectedId: view.selectedId, budgetBytes: once ? Infinity : TICK_BUDGET, budgetMs: once ? Infinity : TICK_MS });
|
|
237
|
+
// 준비 완료를 먼저 정해, 처음 고르는 세션도 이번 갱신의 정렬을 따르게 한다.
|
|
238
|
+
if (!once) latchReady(loading, data.sessionsMore);
|
|
225
239
|
if (!data.sessions.some((s) => s.id === view.selectedId)) {
|
|
226
|
-
view.selectedId = arrange(data.sessions, view).sessions[0]?.id ?? null;
|
|
240
|
+
view.selectedId = arrange(data.sessions, { ...view, ready: once || loading.ready }).sessions[0]?.id ?? null;
|
|
227
241
|
view.focus = null;
|
|
228
242
|
view.tab = 'now';
|
|
229
243
|
}
|
|
@@ -232,15 +246,23 @@ function refresh() {
|
|
|
232
246
|
// 도구별 점검은 기록 폴더를 훑으므로 30초에 한 번만 한다.
|
|
233
247
|
if (!tools || Date.now() - tools.at > 30_000) tools = { at: Date.now(), result: checkTools() };
|
|
234
248
|
data.tools = tools.result;
|
|
235
|
-
view.data = data;
|
|
236
249
|
if (!once && (bell || notifier)) {
|
|
237
250
|
const fresh = takeNewlyWaiting(waitWatch, data.sessions);
|
|
238
251
|
if (fresh.length && bell) process.stdout.write('\x07');
|
|
239
252
|
notifier?.fire(fresh);
|
|
240
253
|
}
|
|
254
|
+
lastMore = data.more;
|
|
255
|
+
if (!once) {
|
|
256
|
+
const shown = admit(loading, data);
|
|
257
|
+
if (throttle && !shown) return false;
|
|
258
|
+
view.ready = loading.ready;
|
|
259
|
+
}
|
|
260
|
+
view.data = data;
|
|
241
261
|
if (view.filter) keepSelectionVisible();
|
|
242
262
|
fixFocus(view);
|
|
263
|
+
return true;
|
|
243
264
|
}
|
|
265
|
+
let lastMore = false;
|
|
244
266
|
|
|
245
267
|
function select(id) {
|
|
246
268
|
if (id !== view.selectedId) {
|
|
@@ -254,6 +276,8 @@ function select(id) {
|
|
|
254
276
|
if (once) {
|
|
255
277
|
refresh();
|
|
256
278
|
flushCache();
|
|
279
|
+
// --line 이 작업 중 수를 낼 수 있게 요약을 남긴다 (summary.mjs).
|
|
280
|
+
writeSummary(summarize(view.data.sessions));
|
|
257
281
|
const size = (v) => (Number(v) > 0 ? Math.floor(Number(v)) : 0);
|
|
258
282
|
const W = process.stdout.columns || size(process.env.COLUMNS) || 140;
|
|
259
283
|
const H = process.stdout.rows || size(process.env.LINES) || 40;
|
|
@@ -381,14 +405,17 @@ stdin.on('data', (key) => {
|
|
|
381
405
|
});
|
|
382
406
|
|
|
383
407
|
let lastFlush = 0;
|
|
408
|
+
// --line 용 요약. 시작 때 기록을 다 읽기 전(ready 전)에는 수가 덜 잡혔을 수 있어 쓰지 않는다.
|
|
409
|
+
const writeSummaryThrottled = createSummaryWriter();
|
|
384
410
|
function tick() {
|
|
385
|
-
refresh();
|
|
386
|
-
|
|
411
|
+
const shown = refresh({ throttle: true });
|
|
412
|
+
if (loading.ready && view.data) writeSummaryThrottled(view.data.sessions);
|
|
413
|
+
const more = lastMore;
|
|
387
414
|
if (more ? Date.now() - lastFlush > LOADING_FLUSH_MS : Date.now() - lastFlush > 15_000) {
|
|
388
415
|
flushCache();
|
|
389
416
|
lastFlush = Date.now();
|
|
390
417
|
}
|
|
391
|
-
draw();
|
|
418
|
+
if (shown) draw();
|
|
392
419
|
setTimeout(tick, more ? CATCH_UP_MS : 1000);
|
|
393
420
|
}
|
|
394
421
|
|
package/package.json
CHANGED
package/src/cache.mjs
CHANGED
|
@@ -11,6 +11,7 @@ import { debug, debugIo } from './log.mjs';
|
|
|
11
11
|
// 14: 장부의 하루 합계에 모델별 몫(models)을 더하고, 날짜를 10일이 아니라 30일 남긴다 (#128).
|
|
12
12
|
const VERSION = 14;
|
|
13
13
|
const ROOT = join(process.env.XDG_CACHE_HOME ?? join(homedir(), '.cache'), 'aitop');
|
|
14
|
+
export const CACHE_ROOT = ROOT;
|
|
14
15
|
const NAME = `v${VERSION}-${PRICE_TAG}`;
|
|
15
16
|
const DIR = join(ROOT, NAME);
|
|
16
17
|
export const CACHE_DIR = DIR;
|
|
@@ -24,7 +25,8 @@ function removeOldDirs() {
|
|
|
24
25
|
cleaned = true;
|
|
25
26
|
try {
|
|
26
27
|
for (const d of readdirSync(ROOT)) {
|
|
27
|
-
|
|
28
|
+
// summary.json(--line 용 요약, summary.mjs)은 버전 폴더 밖에 두고 여기서 지우지 않는다. 남은 임시 파일은 일주일 뒤 지운다.
|
|
29
|
+
if (d === NAME || d === 'summary.json') continue;
|
|
28
30
|
const p = join(ROOT, d);
|
|
29
31
|
// 이 버전보다 낮은 형식(v2, v6-… 등)은 더 이상 어떤 버전도 쓰지 않으므로 바로 지운다.
|
|
30
32
|
const ver = Number(/^v(\d+)(?:-|$)/.exec(d)?.[1]);
|
package/src/collect.mjs
CHANGED
|
@@ -24,17 +24,14 @@ export function bySession(a, b) {
|
|
|
24
24
|
// 돌려주는 more 가 true 면 한도 때문에 덜 읽은 기록이 있다.
|
|
25
25
|
// 도구마다, 그리고 날짜별 사용량 장부에 한도를 따로 줘서 서로의 읽기를 막지 않게 한다.
|
|
26
26
|
export function collect({ budgetBytes = Infinity, budgetMs = Infinity, ...opts } = {}) {
|
|
27
|
-
|
|
28
|
-
const
|
|
29
|
-
|
|
30
|
-
budgets.push(b);
|
|
31
|
-
return b;
|
|
32
|
-
};
|
|
27
|
+
// 이름별 읽기 한도. 'usage' 는 장부, 나머지는 도구별 세션 기록이다.
|
|
28
|
+
const budgets = {};
|
|
29
|
+
const budgetOf = (name, bytes, ms) => (budgets[name] = createBudget(bytes, ms));
|
|
33
30
|
const sessions = [];
|
|
34
31
|
const errors = [];
|
|
35
32
|
for (const [tool, fn] of [['claude', collectClaude], ['codex', collectCodex], ['gemini', collectGemini], ['agy', collectAgy]]) {
|
|
36
33
|
try {
|
|
37
|
-
sessions.push(...fn({ ...opts, budget: budgetOf(budgetBytes, budgetMs) }));
|
|
34
|
+
sessions.push(...fn({ ...opts, budget: budgetOf(tool, budgetBytes, budgetMs) }));
|
|
38
35
|
} catch (err) {
|
|
39
36
|
errors.push(`${tool}: ${err.message}`);
|
|
40
37
|
}
|
|
@@ -42,10 +39,11 @@ export function collect({ budgetBytes = Infinity, budgetMs = Infinity, ...opts }
|
|
|
42
39
|
// 장부는 세션 화면보다 덜 급하니 한 번 갱신에 세션 한도의 1/3 만 읽는다 (처음 한 번 다 읽은 뒤에는 캐시와 새 줄만 읽는다).
|
|
43
40
|
let usage = null;
|
|
44
41
|
try {
|
|
45
|
-
usage = collectLedger({ budget: budgetOf(budgetBytes / 3, budgetMs / 2) });
|
|
42
|
+
usage = collectLedger({ budget: budgetOf('usage', budgetBytes / 3, budgetMs / 2) });
|
|
46
43
|
} catch (err) {
|
|
47
44
|
errors.push(`usage: ${err.message}`);
|
|
48
45
|
}
|
|
49
46
|
sessions.sort(bySession);
|
|
50
|
-
|
|
47
|
+
// sessionsMore: 세션 기록(장부 빼고)만 덜 읽었는지. 시작할 때의 준비 완료는 이 값으로 정한다 (7일 장부는 헤더 진행 줄로만 보인다).
|
|
48
|
+
return { sessions, usage, errors, at: Date.now(), more: Object.values(budgets).some((b) => b.exhausted), sessionsMore: Object.entries(budgets).some(([name, b]) => name !== 'usage' && b.exhausted) };
|
|
51
49
|
}
|
package/src/i18n.mjs
CHANGED
|
@@ -61,12 +61,14 @@ const HELP_KO = `{logo} aitop - 터미널에서 Claude Code · Codex · Antigrav
|
|
|
61
61
|
aitop 실시간 화면
|
|
62
62
|
aitop --once 현재 상태를 한 번 출력하고 끝낸다
|
|
63
63
|
aitop --all 종료된 세션(24시간 이내)도 함께 본다
|
|
64
|
-
aitop --line 오늘 비용·응답 대기 수·시간당 지출을 한 줄로 내고 끝낸다 (tmux 상태줄용, 예: $54.13/$50 wait 2 $3.1/h)
|
|
64
|
+
aitop --line 오늘 비용·응답 대기 수·작업 중 수·시간당 지출을 한 줄로 내고 끝낸다 (tmux 상태줄용, 예: $54.13/$50 wait 2 run 3 $3.1/h)
|
|
65
65
|
--line=tmux 는 tmux 색 서식(#[fg=...])을 넣는다. --line-width <N> 폭 상한(기본 40, 넘으면 뒤 항목부터 뺀다)
|
|
66
|
-
|
|
66
|
+
캐시만 읽는다. 캐시가 없어 1.5초 안에 못 읽으면 ... 을 낸다. 작업 중 수와 Antigravity 의 대기 수는
|
|
67
|
+
1분 안에 aitop 화면·--once·--json 이 남긴 요약이 있을 때만 보인다
|
|
67
68
|
aitop --json 세션 목록과 사용량 합계를 JSON 으로 한 번 출력한다 (--all 과 함께 쓸 수 있다)
|
|
68
|
-
aitop --report daily [--by tool|model] [--days N] [--json] 최근 N일(기본·최대 30)의 날짜별 토큰·비용(API 정가 환산)을
|
|
69
|
-
|
|
69
|
+
aitop --report daily [--by tool|model|project] [--days N] [--json] 최근 N일(기본·최대 30)의 날짜별 토큰·비용(API 정가 환산)을
|
|
70
|
+
도구별·모델별·프로젝트별 표로 내고 끝낸다. 최근 날짜가 위, 맨 아래는 합계. 처음 실행은 30일치 기록을 읽느라 오래 걸릴 수 있다
|
|
71
|
+
프로젝트는 작업 폴더의 마지막 이름이고, 열이 터미널 폭을 넘으면 비용이 작은 쪽을 (그 외) 로 합친다
|
|
70
72
|
aitop --doctor Claude · Codex · Antigravity · Gemini 기록과 실행 중인 프로세스, 설정 파일을 점검한다 (--json 과 함께 쓸 수 있다)
|
|
71
73
|
aitop --bell 응답 대기 세션이 새로 생기면 터미널 벨을 울린다
|
|
72
74
|
aitop --notify 응답 대기 세션이 새로 생기면 데스크톱 알림을 띄운다 (notify-send · osascript, 없으면 건너뜀)
|
|
@@ -101,12 +103,14 @@ const HELP_EN = `{logo} aitop - watch Claude Code, Codex, Antigravity and Gemini
|
|
|
101
103
|
aitop live screen
|
|
102
104
|
aitop --once print the current state once and exit
|
|
103
105
|
aitop --all also show sessions that ended in the last 24 hours
|
|
104
|
-
aitop --line print today's cost, waiting count and spend per hour on one line and exit (for tmux, e.g. $54.13/$50 wait 2 $3.1/h)
|
|
106
|
+
aitop --line print today's cost, waiting count, running count and spend per hour on one line and exit (for tmux, e.g. $54.13/$50 wait 2 run 3 $3.1/h)
|
|
105
107
|
--line=tmux adds tmux colors (#[fg=...]). --line-width <N> sets the max width (default 40, drops items from the end)
|
|
106
|
-
Reads only the cache. With no cache it prints ... after 1.5 seconds. The
|
|
108
|
+
Reads only the cache. With no cache it prints ... after 1.5 seconds. The running count and waiting Antigravity sessions
|
|
109
|
+
show only when the live screen, --once or --json left a summary in the last minute
|
|
107
110
|
aitop --json print the session list and usage totals as JSON once (works with --all)
|
|
108
|
-
aitop --report daily [--by tool|model] [--days N] [--json] print daily tokens and cost (API list price) for the last N days
|
|
109
|
-
(default and max 30) by tool or
|
|
111
|
+
aitop --report daily [--by tool|model|project] [--days N] [--json] print daily tokens and cost (API list price) for the last N days
|
|
112
|
+
(default and max 30) by tool, model or project, then exit. Newest day first, total at the bottom. The first run reads 30 days of logs and may take a while
|
|
113
|
+
A project is the last folder name of the working directory. Columns beyond the terminal width are merged into (others)
|
|
110
114
|
aitop --doctor check Claude, Codex, Antigravity and Gemini logs, running processes and the config file (works with --json)
|
|
111
115
|
aitop --bell ring the terminal bell when a session starts waiting for you
|
|
112
116
|
aitop --notify show a desktop notification when a session starts waiting (notify-send or osascript, skipped if missing)
|
|
@@ -193,8 +197,8 @@ export const STRINGS = {
|
|
|
193
197
|
'opt.lineWidthBad': '--line-width 값 {value} 이 잘못되었습니다 (0 보다 큰 정수)',
|
|
194
198
|
'opt.reportMissing': '--report 값이 없습니다 (daily)',
|
|
195
199
|
'opt.reportBad': '--report 값 {value} 이 잘못되었습니다 (daily)',
|
|
196
|
-
'opt.byMissing': '--by 값이 없습니다 (tool 또는
|
|
197
|
-
'opt.byBad': '--by 값 {value} 이 잘못되었습니다 (tool 또는
|
|
200
|
+
'opt.byMissing': '--by 값이 없습니다 (tool, model 또는 project)',
|
|
201
|
+
'opt.byBad': '--by 값 {value} 이 잘못되었습니다 (tool, model 또는 project)',
|
|
198
202
|
'opt.daysMissing': '--days 값이 없습니다 (일 수)',
|
|
199
203
|
'opt.daysBad': '--days 값 {value} 이 잘못되었습니다 (0 보다 큰 정수)',
|
|
200
204
|
'opt.reportOnly': '--by, --days 는 --report 와 함께 쓴다',
|
|
@@ -203,6 +207,9 @@ export const STRINGS = {
|
|
|
203
207
|
'report.title': '날짜별 사용량 · 최근 {n}일 ({from} ~ {to}) · {by} · API 정가 환산',
|
|
204
208
|
'report.by.tool': '도구별',
|
|
205
209
|
'report.by.model': '모델별',
|
|
210
|
+
'report.by.project': '프로젝트별',
|
|
211
|
+
'report.unknown': '(모름)',
|
|
212
|
+
'report.others': '(그 외)',
|
|
206
213
|
'report.date': '날짜',
|
|
207
214
|
'report.total': '합계',
|
|
208
215
|
'report.empty': '이 기간에 기록된 사용량이 없습니다',
|
|
@@ -276,7 +283,7 @@ export const STRINGS = {
|
|
|
276
283
|
'phase.think': '생각 중',
|
|
277
284
|
'phase.working': '작업 중',
|
|
278
285
|
'phase.steps': '작업 중 · {n}단계',
|
|
279
|
-
'phase.loading': '
|
|
286
|
+
'phase.loading': '…',
|
|
280
287
|
'phase.write': '답변 작성 중',
|
|
281
288
|
'phase.agents': '에이전트 {n}개 실행 중',
|
|
282
289
|
|
|
@@ -296,7 +303,7 @@ export const STRINGS = {
|
|
|
296
303
|
'hdr.budget': '예산',
|
|
297
304
|
'hdr.today': '오늘',
|
|
298
305
|
'hdr.week': '7일',
|
|
299
|
-
'hdr.
|
|
306
|
+
'hdr.loading': '집계 중',
|
|
300
307
|
'hdr.apiLong': 'API 환산',
|
|
301
308
|
'hdr.apiShort': 'API',
|
|
302
309
|
'hdr.netLong': '캐시 제외',
|
|
@@ -412,7 +419,7 @@ export const STRINGS = {
|
|
|
412
419
|
'hopt.showRequests': '응답 대기 요청 전체를 상세·--json 에',
|
|
413
420
|
'hopt.colorBlind': '적록 색약용 색 (대기·돈·경고를 노랑·파랑 계열로)',
|
|
414
421
|
'hopt.debug': '디버그 로그를 남긴다',
|
|
415
|
-
'hopt.line': '오늘
|
|
422
|
+
'hopt.line': '오늘 비용·대기·작업 중 수·시간당 지출 한 줄 (tmux 상태줄용)',
|
|
416
423
|
'hopt.printConfig': '설정 값과 출처, 설정 파일 위치',
|
|
417
424
|
'hopt.ambiguous': '·→─● 를 2칸으로 그리는 터미널용 (1칸 기호로)',
|
|
418
425
|
'set.budget': '예산 {v}',
|
|
@@ -536,8 +543,8 @@ export const STRINGS = {
|
|
|
536
543
|
'opt.lineWidthBad': 'bad --line-width value {value} (a whole number above 0)',
|
|
537
544
|
'opt.reportMissing': '--report needs a value (daily)',
|
|
538
545
|
'opt.reportBad': 'bad --report value {value} (daily)',
|
|
539
|
-
'opt.byMissing': '--by needs a value (tool or
|
|
540
|
-
'opt.byBad': 'bad --by value {value} (tool or
|
|
546
|
+
'opt.byMissing': '--by needs a value (tool, model or project)',
|
|
547
|
+
'opt.byBad': 'bad --by value {value} (tool, model or project)',
|
|
541
548
|
'opt.daysMissing': '--days needs a value (number of days)',
|
|
542
549
|
'opt.daysBad': 'bad --days value {value} (a whole number above 0)',
|
|
543
550
|
'opt.reportOnly': '--by and --days only work with --report',
|
|
@@ -545,6 +552,9 @@ export const STRINGS = {
|
|
|
545
552
|
'report.title': 'Daily usage, last {n} days ({from} to {to}), {by}, API list price',
|
|
546
553
|
'report.by.tool': 'by tool',
|
|
547
554
|
'report.by.model': 'by model',
|
|
555
|
+
'report.by.project': 'by project',
|
|
556
|
+
'report.unknown': '(unknown)',
|
|
557
|
+
'report.others': '(others)',
|
|
548
558
|
'report.date': 'Date',
|
|
549
559
|
'report.total': 'Total',
|
|
550
560
|
'report.empty': 'No usage recorded in this period',
|
|
@@ -617,7 +627,7 @@ export const STRINGS = {
|
|
|
617
627
|
'phase.think': 'Thinking',
|
|
618
628
|
'phase.working': 'Working',
|
|
619
629
|
'phase.steps': { long: 'Working · step {n}', short: 'Step {n}' },
|
|
620
|
-
'phase.loading':
|
|
630
|
+
'phase.loading': '…',
|
|
621
631
|
'phase.write': { long: 'Writing reply', short: 'Writing' },
|
|
622
632
|
'phase.agents': { long: { one: '{n} agent running', other: '{n} agents running' }, short: { one: '{n} agent', other: '{n} agents' } },
|
|
623
633
|
|
|
@@ -636,7 +646,7 @@ export const STRINGS = {
|
|
|
636
646
|
'hdr.budget': 'budget',
|
|
637
647
|
'hdr.today': 'today',
|
|
638
648
|
'hdr.week': '7d',
|
|
639
|
-
'hdr.
|
|
649
|
+
'hdr.loading': 'Loading',
|
|
640
650
|
'hdr.apiLong': 'API cost',
|
|
641
651
|
'hdr.apiShort': 'API',
|
|
642
652
|
'hdr.netLong': 'no cache',
|
package/src/line.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// aitop --line: tmux 상태줄 같은 곳에 넣을 한 줄 요약. 예) $54.13/$50 wait 2 $3.1/h
|
|
1
|
+
// aitop --line: tmux 상태줄 같은 곳에 넣을 한 줄 요약. 예) $54.13/$50 wait 2 run 3 $3.1/h
|
|
2
2
|
// 글자는 ASCII 만 쓴다 (이모지·폭이 모호한 기호는 tmux 에서 칸이 어긋난다). 표기는 짧은 영어 약어로 고정하고 번역하지 않는다.
|
|
3
3
|
// 색은 --line=tmux 일 때 tmux 서식(#[fg=colourN])으로만 넣고 ANSI 코드는 쓰지 않는다. NO_COLOR 면 서식도 넣지 않는다.
|
|
4
4
|
// 옵션 오류 문구만 i18n 으로 지금 언어를 따른다.
|
|
@@ -12,7 +12,8 @@ export const CAP_MS = 1500;
|
|
|
12
12
|
export const PENDING = '...';
|
|
13
13
|
|
|
14
14
|
// tmux 256색 번호. 응답 대기는 눈에 띄는 주황, 돈은 화면 헤더와 같은 연두. 색약용은 노랑·파랑 계열로 가른다.
|
|
15
|
-
|
|
15
|
+
// 작업 중은 눈에 덜 띄는 회색 계열로 둔다 (주목할 것은 대기다).
|
|
16
|
+
const COLOURS = { normal: { waiting: 'colour214', money: 'colour154', running: 'colour250' }, colorBlind: { waiting: 'colour226', money: 'colour75', running: 'colour250' } };
|
|
16
17
|
|
|
17
18
|
// --line, --line=plain|tmux, --line-width <N>, --line-width=<N> 를 꺼낸다. line 은 켜지 않았으면 null.
|
|
18
19
|
export function lineOption(argv) {
|
|
@@ -50,29 +51,40 @@ const rate = (x) => (x >= 100 ? `$${x.toFixed(0)}` : x >= 1 ? `$${x.toFixed(1)}`
|
|
|
50
51
|
// 표시하면 0 으로 보이는 값은 0 으로 본다.
|
|
51
52
|
const zero = (x) => !(Number(x) >= 0.005);
|
|
52
53
|
|
|
53
|
-
// 값: today(오늘 비용, API 정가 환산), budgetDay(하루 예산, 없으면 null), waiting(응답 대기 수),
|
|
54
|
+
// 값: today(오늘 비용, API 정가 환산), budgetDay(하루 예산, 없으면 null), waiting(응답 대기 수),
|
|
55
|
+
// running(작업 중 수, 요약이 없거나 오래됐으면 null), perHour(최근 1시간 지출).
|
|
54
56
|
// 0 인 항목은 뺀다. 오늘 비용이 0 이어도 예산이 있으면 $0.00/$50 으로 보인다.
|
|
55
57
|
// width 를 넘으면 뒤 항목부터 뺀다. mode 가 tmux 이고 noColor 가 아니면 항목마다 tmux 서식을 씌운다.
|
|
56
|
-
export function formatLine({ today = 0, budgetDay = null, waiting = 0, perHour = 0 } = {}, { mode = 'plain', noColor = false, width = DEFAULT_WIDTH, colorBlind = false } = {}) {
|
|
58
|
+
export function formatLine({ today = 0, budgetDay = null, waiting = 0, running = null, perHour = 0 } = {}, { mode = 'plain', noColor = false, width = DEFAULT_WIDTH, colorBlind = false } = {}) {
|
|
57
59
|
const c = COLOURS[colorBlind ? 'colorBlind' : 'normal'];
|
|
58
60
|
const parts = [];
|
|
59
61
|
const hasBudget = typeof budgetDay === 'number' && budgetDay > 0;
|
|
60
62
|
if (!zero(today) || hasBudget) parts.push({ text: `${money(zero(today) ? 0 : today)}${hasBudget ? `/${budgetText(budgetDay)}` : ''}`, fg: c.money });
|
|
61
63
|
if (waiting > 0) parts.push({ text: `wait ${waiting}`, fg: c.waiting });
|
|
64
|
+
if (running > 0) parts.push({ text: `run ${running}`, fg: c.running });
|
|
62
65
|
if (!zero(perHour)) parts.push({ text: `${rate(perHour)}/h`, fg: c.money });
|
|
63
66
|
while (parts.length && parts.map((p) => p.text).join(' ').length > width) parts.pop();
|
|
64
67
|
const styled = mode === 'tmux' && !noColor;
|
|
65
68
|
return parts.map((p) => (styled ? `#[fg=${p.fg}]${p.text}#[default]` : p.text)).join(' ');
|
|
66
69
|
}
|
|
67
70
|
|
|
68
|
-
//
|
|
71
|
+
// 요약 파일(summary.mjs)에서 작업 중 수와 응답 대기 수를 고른다. claudeWaiting 은 세션 파일에서 지금 센 Claude 대기 수.
|
|
72
|
+
// 대기는 Claude 몫을 늘 지금 값으로 쓰고(요약은 최대 1분 늦다), 다른 도구 몫(지금은 Antigravity)만 요약에서 더한다. 요약이 없으면 Claude 몫만.
|
|
73
|
+
// 작업 중은 요약에만 있으므로 요약이 없거나 오래됐으면 null (줄에서 뺀다).
|
|
74
|
+
export function pickCounts(summary, claudeWaiting) {
|
|
75
|
+
if (!summary) return { waiting: claudeWaiting, running: null };
|
|
76
|
+
return { waiting: claudeWaiting + summary.waitingOther, running: summary.running };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// 장부 캐시와 새로 붙은 줄, 요약 파일만 읽어 값을 모은다 (세션 화면용 기록 전체·프로세스 목록은 읽지 않는다).
|
|
69
80
|
// 시간 상한 안에 다 읽지 못했거나 아직 집계 중이면 null. 읽은 만큼은 aitop 캐시에 남아 다음 실행이 이어 읽는다.
|
|
70
81
|
export async function collectLine({ capMs = CAP_MS, now = Date.now() } = {}) {
|
|
71
82
|
const { createBudget } = await import('./tail.mjs');
|
|
72
83
|
const { collectLedger } = await import('./sources/claude-ledger.mjs');
|
|
73
84
|
const { claudeWaitingCount } = await import('./sources/claude.mjs');
|
|
85
|
+
const { readSummary } = await import('./summary.mjs');
|
|
74
86
|
const budget = createBudget(Infinity, capMs);
|
|
75
87
|
const usage = collectLedger({ budget, now });
|
|
76
88
|
if (budget.exhausted || usage.loading != null) return null;
|
|
77
|
-
return { today: usage.today.cost,
|
|
89
|
+
return { today: usage.today.cost, ...pickCounts(readSummary({ now }), claudeWaitingCount()), perHour: usage.lastHour.cost };
|
|
78
90
|
}
|
package/src/loading.mjs
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// 시작할 때의 로딩을 차분하게: 준비 완료 래치와, 로딩 중 다시 그리기 속도 제한.
|
|
2
|
+
// 캐시가 없으면 세션 기록과 7일 장부를 여러 갱신에 나눠 읽는데, 갱신마다 그리면 숫자·순서·진행률이 쉬지 않고 바뀐다.
|
|
3
|
+
|
|
4
|
+
// 준비 완료를 기다리는 최대 시간. 디스크가 느려 읽기 한도(바이트·시간)에 계속 걸려도 이만큼 지나면 준비 완료로 본다.
|
|
5
|
+
export const READY_CAP_MS = 60_000;
|
|
6
|
+
// 로딩 중에는 중요한 변화가 없으면 이 간격보다 자주 화면에 올리지 않는다.
|
|
7
|
+
export const LOADING_DRAW_MS = 1000;
|
|
8
|
+
|
|
9
|
+
// now: 시계 (테스트에서 바꿔 넣는다).
|
|
10
|
+
export function createLoading({ now = Date.now, capMs = READY_CAP_MS, drawMs = LOADING_DRAW_MS } = {}) {
|
|
11
|
+
return { now, capMs, drawMs, startedAt: now(), ready: false, shownAt: -Infinity, shown: null };
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// 준비 완료 = 처음으로 more(세션 기록만, collect 의 sessionsMore)가 거짓인 갱신, 또는 시작 후 capMs. 한 번 켜지면 되돌리지 않는다 (more 는 한도가 시간이기도 해서 다시 참이 될 수 있다).
|
|
15
|
+
// 7일 장부(usage.loading)는 준비 완료 조건에 넣지 않고 헤더 진행 줄로만 보인다.
|
|
16
|
+
export function latchReady(L, more) {
|
|
17
|
+
if (!L.ready && (more === false || L.now() - L.startedAt >= L.capMs)) L.ready = true;
|
|
18
|
+
return L.ready;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// 바로 그려야 하는 변화를 가리는 데 쓰는 값: 세션 목록과 응답 대기 세션.
|
|
22
|
+
const signature = (data) => {
|
|
23
|
+
const list = data?.sessions ?? [];
|
|
24
|
+
return `${list.map((s) => s.id).join(',')}|${list.filter((s) => s.status === 'waiting').map((s) => s.id).join(',')}`;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
// 이번 갱신 결과를 화면에 올릴지 정한다. 준비 완료 전이나 7일 집계 중에는 drawMs 에 한 번만 올리고,
|
|
28
|
+
// 첫 화면, 준비 완료 순간, 집계가 끝난 순간, 세션 목록·응답 대기가 바뀐 갱신은 바로 올린다. 로딩이 끝난 뒤에는 늘 올린다.
|
|
29
|
+
// 준비 완료 순간은 화면에 마지막으로 올린 값과 견준다 (부르는 쪽이 admit 전에 latchReady 를 먼저 불러도 바로 올린다).
|
|
30
|
+
export function admit(L, data) {
|
|
31
|
+
const ready = latchReady(L, data.sessionsMore ?? data.more);
|
|
32
|
+
const loading = data.usage?.loading != null;
|
|
33
|
+
const prev = L.shown;
|
|
34
|
+
const sig = signature(data);
|
|
35
|
+
const urgent =
|
|
36
|
+
!prev ||
|
|
37
|
+
(ready && !prev.ready) ||
|
|
38
|
+
(!loading && prev.loading) ||
|
|
39
|
+
sig !== prev.sig;
|
|
40
|
+
const now = L.now();
|
|
41
|
+
if (!urgent && (!ready || loading) && now - L.shownAt < L.drawMs) return false;
|
|
42
|
+
L.shown = { sig, loading, ready };
|
|
43
|
+
L.shownAt = now;
|
|
44
|
+
return true;
|
|
45
|
+
}
|
package/src/order.mjs
CHANGED
|
@@ -28,11 +28,16 @@ const KEYS = {
|
|
|
28
28
|
recent: (s) => s.updatedAt ?? -Infinity,
|
|
29
29
|
};
|
|
30
30
|
|
|
31
|
+
// 기록을 읽는 동안 계속 커지는 값. 준비 완료 전에는 이 값으로 줄 세우지 않는다.
|
|
32
|
+
const GROWING = new Set(['cost', 'context']);
|
|
33
|
+
|
|
31
34
|
// 종료 세션은 어떤 정렬에서도 (묶음 안에서도) 아래에 둔다. 그다음 큰 값이 위. 값이 같으면 받은 순서(기본 순서)를 지켜 갱신마다 자리가 흔들리지 않게 한다 (Array.prototype.sort 는 안정 정렬).
|
|
32
|
-
|
|
35
|
+
// ready 가 false 면(시작할 때 기록을 아직 읽는 중) 비용·컨텍스트 정렬은 기본 순서에 고정했다가, 준비 완료 때 한 번만 다시 줄 세운다.
|
|
36
|
+
export function compare(sort, costMode = 'api', ready = true) {
|
|
33
37
|
const key = KEYS[sort];
|
|
34
38
|
if (!key) return () => 0;
|
|
35
39
|
const ended = (s) => (s.status === 'ended' ? 1 : 0);
|
|
40
|
+
if (ready === false && GROWING.has(sort)) return (a, b) => ended(a) - ended(b);
|
|
36
41
|
return (a, b) => ended(a) - ended(b) || key(b, costMode) - key(a, costMode);
|
|
37
42
|
}
|
|
38
43
|
|
|
@@ -42,8 +47,9 @@ const GROUP_KEY = { project: projectOf, tool: (s) => s.tool ?? '?' };
|
|
|
42
47
|
// 돌려주는 sessions 는 화면에 그리는 순서 그대로다 (↑↓·n 도 이 순서를 따른다).
|
|
43
48
|
// groups 는 묶을 때만 있다: { name, count, cost, unknown, waiting, pinned, sessions }. 묶음은 그 안의 첫 세션이 정렬에서 앞선 순으로 놓인다.
|
|
44
49
|
// pins: 고정한 세션 id (고정한 순서). 화면에 없는 id 는 건너뛴다.
|
|
45
|
-
|
|
46
|
-
|
|
50
|
+
// ready: false 면 준비 완료 전이다 (compare 참고). 응답 대기 세션은 그동안에도 맨 위로 올린다.
|
|
51
|
+
export function arrange(sessions, { sort = 'default', group = 'none', costMode = 'api', pins = [], ready = true } = {}) {
|
|
52
|
+
const cmp = compare(sort, costMode, ready);
|
|
47
53
|
const rank = new Map((pins ?? []).map((id, i) => [id, i]));
|
|
48
54
|
const waiting = sessions.filter((s) => s.status === 'waiting').sort(cmp);
|
|
49
55
|
const pinned = sessions.filter((s) => s.status !== 'waiting' && rank.has(s.id)).sort((a, b) => rank.get(a.id) - rank.get(b.id));
|
package/src/report.mjs
CHANGED
|
@@ -3,12 +3,18 @@
|
|
|
3
3
|
// 줄은 최근 날짜가 위(오늘부터 거꾸로)이고, 맨 아래 합계 줄은 위 날짜 줄을 더한 값이다. --json 도 같은 값을 숫자로만 낸다.
|
|
4
4
|
// 처음 읽는 동안 stderr 가 터미널이면 진행률을 보이고, 시간 상한을 넘으면 읽은 만큼으로 표를 내고 덜 읽었다고 알린다.
|
|
5
5
|
import { t } from './i18n.mjs';
|
|
6
|
-
import { fmtTokens, pad, stripControl, width } from './text.mjs';
|
|
6
|
+
import { fmtTokens, pad, stripControl, truncate, width } from './text.mjs';
|
|
7
7
|
import { money } from './line.mjs';
|
|
8
8
|
import { KEEP_DAYS, lastDays } from './sources/common.mjs';
|
|
9
|
+
import { projectLabels } from './sources/projects.mjs';
|
|
9
10
|
|
|
10
11
|
export const KINDS = ['daily'];
|
|
11
|
-
export const BY = ['tool', 'model'];
|
|
12
|
+
export const BY = ['tool', 'model', 'project'];
|
|
13
|
+
// --by project 의 특별한 열: 프로젝트를 못 찾은 기록, 열 수 상한을 넘어 합친 나머지. --json 에도 이 이름 그대로 나간다.
|
|
14
|
+
export const UNKNOWN = '(unknown)';
|
|
15
|
+
export const OTHERS = '(others)';
|
|
16
|
+
// 표 머리글 한 칸의 최대 폭 (긴 프로젝트·모델 이름은 줄인다).
|
|
17
|
+
const HEAD_MAX = 24;
|
|
12
18
|
export const MAX_DAYS = KEEP_DAYS;
|
|
13
19
|
export const DEFAULT_DAYS = KEEP_DAYS;
|
|
14
20
|
// 전체 시간 상한. 넘으면 읽은 만큼으로 표를 낸다 (캐시에 남은 만큼은 다음 실행이 이어 읽는다).
|
|
@@ -20,7 +26,7 @@ const PROGRESS_AFTER_MS = 400;
|
|
|
20
26
|
const FLUSH_MS = 3000;
|
|
21
27
|
const TOOLS = ['claude', 'codex', 'agy'];
|
|
22
28
|
|
|
23
|
-
// --report <kind>, --report=<kind>, --by <tool|model>, --by=..., --days <N>, --days=<N> 를 꺼낸다.
|
|
29
|
+
// --report <kind>, --report=<kind>, --by <tool|model|project>, --by=..., --days <N>, --days=<N> 를 꺼낸다.
|
|
24
30
|
// kind 는 --report 를 주지 않았으면 null. --by·--days 는 --report 와 함께일 때만 받는다. capped: --days 를 30으로 줄였는지.
|
|
25
31
|
export function reportOption(argv) {
|
|
26
32
|
let kind = null;
|
|
@@ -67,21 +73,29 @@ const add = (a, tokens, cost, unpriced) => {
|
|
|
67
73
|
if (unpriced) a.unpriced = true;
|
|
68
74
|
};
|
|
69
75
|
|
|
70
|
-
//
|
|
71
|
-
|
|
76
|
+
// 폭을 모를 때(파이프) --by project 표의 열 수 상한.
|
|
77
|
+
export const PIPE_COLUMNS = 8;
|
|
78
|
+
|
|
79
|
+
// books: collectDaily 의 [{ tool, days }] (--by project 면 project 도). 최근 days 일의 날짜 줄(오늘부터 거꾸로)과
|
|
80
|
+
// 열(도구, 모델 또는 프로젝트), 합계를 만든다. 열은 기간 합계 비용이 큰 순서(같으면 토큰, 이름 순)이고, 기간 안에 토큰이 하나도 없는 열은 뺀다.
|
|
81
|
+
// maxColumns: 열이 이보다 많으면 앞의 maxColumns-1 개만 두고 나머지를 OTHERS 로 합친다 (--by project 표만).
|
|
72
82
|
// unpriced: 가격표에 없는 모델이 끼어 비용이 실제보다 적게 잡혔을 수 있는지.
|
|
73
|
-
export function buildReport(books, { by = 'tool', days = DEFAULT_DAYS, now = Date.now() } = {}) {
|
|
83
|
+
export function buildReport(books, { by = 'tool', days = DEFAULT_DAYS, now = Date.now(), maxColumns = Infinity } = {}) {
|
|
74
84
|
const dates = lastDays(days, now);
|
|
85
|
+
// 프로젝트 경로 → 짧은 이름. paths 는 거꾸로 (--json 에 이름별 경로를 둔다).
|
|
86
|
+
const labels = by === 'project' ? projectLabels(new Set(books.map((b) => b.project).filter(Boolean))) : new Map();
|
|
87
|
+
const paths = {};
|
|
75
88
|
const rows = dates.map((date) => ({ date, tokens: 0, cost: 0, unpriced: false, items: {} }));
|
|
76
89
|
const at = new Map(rows.map((r) => [r.date, r]));
|
|
77
90
|
const total = { tokens: 0, cost: 0, unpriced: false, items: {} };
|
|
78
91
|
let unpriced = false;
|
|
79
|
-
for (const { tool, days: book } of books) {
|
|
92
|
+
for (const { tool, project, days: book } of books) {
|
|
80
93
|
for (const [date, d] of Object.entries(book ?? {})) {
|
|
81
94
|
const row = at.get(date);
|
|
82
95
|
if (!row) continue;
|
|
83
96
|
if (d.unknown) unpriced = true;
|
|
84
|
-
const parts = by === 'model' ? Object.entries(d.models ?? {}) : [[tool, d]];
|
|
97
|
+
const parts = by === 'model' ? Object.entries(d.models ?? {}) : by === 'project' ? [[labels.get(project) ?? UNKNOWN, d]] : [[tool, d]];
|
|
98
|
+
if (by === 'project' && project) paths[labels.get(project)] = project;
|
|
85
99
|
for (const [name, x] of parts) {
|
|
86
100
|
add((row.items[name] ??= zero()), x.tokens, x.cost, x.unknown);
|
|
87
101
|
add((total.items[name] ??= zero()), x.tokens, x.cost, x.unknown);
|
|
@@ -95,7 +109,46 @@ export function buildReport(books, { by = 'tool', days = DEFAULT_DAYS, now = Dat
|
|
|
95
109
|
.filter(([, x]) => x.tokens > 0 || x.cost > 0)
|
|
96
110
|
.sort(([a, x], [b, y]) => y.cost - x.cost || y.tokens - x.tokens || rank(a) - rank(b) || a.localeCompare(b))
|
|
97
111
|
.map(([name]) => name);
|
|
98
|
-
|
|
112
|
+
if (columns.length > maxColumns) foldOthers(columns, Math.max(1, maxColumns - 1), [...rows, total]);
|
|
113
|
+
const out = { report: 'daily', by, days, from: dates.at(-1), to: dates[0], columns, rows, total, unpriced };
|
|
114
|
+
if (by === 'project') out.paths = Object.fromEntries(columns.filter((c) => paths[c]).map((c) => [c, paths[c]]));
|
|
115
|
+
return out;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// 표 r 을 열 keep 개 + OTHERS 로 접은 복사본 (r 은 그대로).
|
|
119
|
+
function folded(r, keep) {
|
|
120
|
+
const copy = (o) => ({ ...o, items: { ...o.items } });
|
|
121
|
+
const out = { ...r, columns: [...r.columns], rows: r.rows.map(copy), total: copy(r.total) };
|
|
122
|
+
foldOthers(out.columns, keep, [...out.rows, out.total]);
|
|
123
|
+
if (r.paths) out.paths = Object.fromEntries(Object.entries(r.paths).filter(([c]) => out.columns.includes(c)));
|
|
124
|
+
return out;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// 표 줄이 터미널 폭 cols 안에 들어가도록, 실제 칸 폭(머리글과 값 중 긴 쪽)을 재어 들어가는 만큼만 열을 남기고 나머지를 OTHERS 로 접는다.
|
|
128
|
+
// 한 열도 안 들어가면 열 1개 + OTHERS 로 낸다.
|
|
129
|
+
export function fitReport(r, cols) {
|
|
130
|
+
// 열이 1개 이하면 접어도 좁아지지 않는다 (빈 OTHERS 만 붙는다).
|
|
131
|
+
if (!(cols > 0) || r.columns.length <= 1 || tableWidth(r) <= cols) return r;
|
|
132
|
+
for (let keep = r.columns.length - 1; keep >= 1; keep--) {
|
|
133
|
+
const f = folded(r, keep);
|
|
134
|
+
if (tableWidth(f) <= cols) return f;
|
|
135
|
+
}
|
|
136
|
+
return folded(r, 1);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// 앞의 keep 개 뒤 열들을 OTHERS 한 열로 합친다 (columns 와 각 줄의 items 를 고친다).
|
|
140
|
+
function foldOthers(columns, keep, lines) {
|
|
141
|
+
const rest = columns.splice(keep);
|
|
142
|
+
columns.push(OTHERS);
|
|
143
|
+
for (const o of lines) {
|
|
144
|
+
let sum = null;
|
|
145
|
+
for (const c of rest) {
|
|
146
|
+
const x = o.items[c];
|
|
147
|
+
delete o.items[c];
|
|
148
|
+
if (x) add((sum ??= zero()), x.tokens, x.cost, x.unpriced);
|
|
149
|
+
}
|
|
150
|
+
if (sum) o.items[OTHERS] = sum;
|
|
151
|
+
}
|
|
99
152
|
}
|
|
100
153
|
|
|
101
154
|
// --json 모양: 키는 영어, 값은 숫자만 (날짜·이름은 문자열). partial: 시간 상한 때문에 덜 읽었는지.
|
|
@@ -113,6 +166,7 @@ export function reportJson(r, version, { partial = false } = {}) {
|
|
|
113
166
|
partial,
|
|
114
167
|
unpriced: r.unpriced,
|
|
115
168
|
columns: r.columns,
|
|
169
|
+
...(r.paths ? { paths: r.paths } : {}),
|
|
116
170
|
rows: r.rows.map((x) => ({ date: x.date, tokens: x.tokens, cost: x.cost, unpriced: x.unpriced, items: items(x) })),
|
|
117
171
|
total: { tokens: r.total.tokens, cost: r.total.cost, unpriced: r.total.unpriced, items: items(r.total) },
|
|
118
172
|
};
|
|
@@ -121,15 +175,28 @@ export function reportJson(r, version, { partial = false } = {}) {
|
|
|
121
175
|
// 칸 하나: '1.2M $3.40'. 토큰이 없으면 '-'. 가격표에 없는 모델이 끼었으면 화면 헤더처럼 비용 뒤에 ? 를 붙인다 ('$12.30?').
|
|
122
176
|
const cell = (x) => (x && (x.tokens > 0 || x.cost > 0) ? `${fmtTokens(Math.round(x.tokens))} ${money(x.cost)}${x.unpriced ? '?' : ''}` : '-');
|
|
123
177
|
|
|
124
|
-
// 사람이 읽는 표. 머리글·합계 줄 문구는 화면 언어(t)를 따른다.
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
178
|
+
// 사람이 읽는 표. 머리글·합계 줄 문구는 화면 언어(t)를 따른다. 도구·모델·프로젝트 이름은 그대로 쓴다.
|
|
179
|
+
const colName = (c) => (c === UNKNOWN ? t('report.unknown') : c === OTHERS ? t('report.others') : truncate(stripControl(c), HEAD_MAX));
|
|
180
|
+
// 표의 머리글·날짜 줄·합계 줄 글과 칸 폭 w.
|
|
181
|
+
function table(r) {
|
|
182
|
+
// 모델·프로젝트 이름은 기록에서 온 글이라 제어문자를 지운다.
|
|
183
|
+
const head = [t('report.date'), ...r.columns.map(colName), t('report.total')];
|
|
128
184
|
const line = (label, o) => [label, ...r.columns.map((c) => cell(o.items[c])), cell(o)];
|
|
129
185
|
const body = r.rows.map((x) => line(x.date, x));
|
|
130
186
|
const foot = line(t('report.total'), r.total);
|
|
131
187
|
const all = [head, ...body, foot];
|
|
132
188
|
const w = head.map((_, i) => Math.max(...all.map((row) => width(row[i]))));
|
|
189
|
+
return { head, body, foot, w };
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// 표 한 줄의 폭 (칸 사이는 두 칸).
|
|
193
|
+
const tableWidth = (r) => {
|
|
194
|
+
const { w } = table(r);
|
|
195
|
+
return w.reduce((a, n) => a + n, 0) + 2 * (w.length - 1);
|
|
196
|
+
};
|
|
197
|
+
|
|
198
|
+
export function formatReport(r, { partial = false } = {}) {
|
|
199
|
+
const { head, body, foot, w } = table(r);
|
|
133
200
|
const fmt = (row) => row.map((s, i) => pad(s, w[i], i === 0 ? 'left' : 'right')).join(' ').trimEnd();
|
|
134
201
|
const rule = w.map((n) => '-'.repeat(n)).join(' ');
|
|
135
202
|
const out = [t('report.title', { n: r.days, by: t(`report.by.${r.by}`), from: r.from, to: r.to }), '', fmt(head), rule, ...body.map(fmt), rule, fmt(foot)];
|
|
@@ -141,23 +208,26 @@ export function formatReport(r, { partial = false } = {}) {
|
|
|
141
208
|
|
|
142
209
|
// 장부를 끝까지(또는 시간 상한까지) 읽는다. 짧게 나눠 읽으며 진행률을 onProgress(0~1, 지난 ms)로 알리고 캐시를 저장한다.
|
|
143
210
|
// 돌려주는 값: { books, partial }. partial 이면 시간 상한 때문에 덜 읽은 기록이 있다.
|
|
144
|
-
|
|
211
|
+
// by 가 'project' 면 장부마다 project(작업 폴더)를 붙인다.
|
|
212
|
+
export async function collectReport({ days = DEFAULT_DAYS, maxMs = MAX_MS, now = Date.now(), by = 'tool', onProgress = () => {} } = {}) {
|
|
145
213
|
const { createBudget } = await import('./tail.mjs');
|
|
146
214
|
const { collectDaily } = await import('./sources/claude-ledger.mjs');
|
|
147
215
|
const { flushCache } = await import('./cache.mjs');
|
|
216
|
+
const { attachProjects } = await import('./sources/projects.mjs');
|
|
217
|
+
const done = (books, partial) => ({ books: by === 'project' ? attachProjects(books) : books, partial });
|
|
148
218
|
const start = Date.now();
|
|
149
219
|
let lastFlush = start;
|
|
150
220
|
for (;;) {
|
|
151
221
|
const budget = createBudget(Infinity, STEP_MS);
|
|
152
222
|
const r = collectDaily({ budget, now, days });
|
|
153
223
|
const spent = Date.now() - start;
|
|
154
|
-
if (!budget.exhausted) return
|
|
224
|
+
if (!budget.exhausted) return done(r.books, false);
|
|
155
225
|
onProgress(r.size ? 1 - r.pending / r.size : 0, spent);
|
|
156
226
|
if (Date.now() - lastFlush > FLUSH_MS) {
|
|
157
227
|
flushCache();
|
|
158
228
|
lastFlush = Date.now();
|
|
159
229
|
}
|
|
160
|
-
if (spent >= maxMs) return
|
|
230
|
+
if (spent >= maxMs) return done(r.books, true);
|
|
161
231
|
// 다른 일(신호 처리 등)이 돌 틈을 준다.
|
|
162
232
|
await new Promise((resolve) => setImmediate(resolve));
|
|
163
233
|
}
|
|
@@ -134,7 +134,7 @@ const books = new Map();
|
|
|
134
134
|
// 대화마다 날짜별 합계(days)와 5분 칸(slots), 처음 읽기가 덜 끝난 기록의 크기(pending)·전체 크기(size).
|
|
135
135
|
// node:sqlite 를 못 쓰는 Node 에서는 비어 있다 (agy 는 프로세스만 보인다).
|
|
136
136
|
export function collectAgyLedger({ budget, days = DAYS } = {}) {
|
|
137
|
-
const out = { days: [], slots: [], pending: 0, size: 0 };
|
|
137
|
+
const out = { days: [], slots: [], paths: [], pending: 0, size: 0 };
|
|
138
138
|
if (!loadSqlite() || !existsSync(join(AGY_ROOT, 'conversations'))) return out;
|
|
139
139
|
const files = recentFiles(days);
|
|
140
140
|
const keep = new Set(files);
|
|
@@ -147,6 +147,7 @@ export function collectAgyLedger({ budget, days = DAYS } = {}) {
|
|
|
147
147
|
out.size += size;
|
|
148
148
|
if (!b.complete) out.pending += size;
|
|
149
149
|
out.days.push(b.days);
|
|
150
|
+
out.paths.push(p);
|
|
150
151
|
out.slots.push(b.slots);
|
|
151
152
|
}
|
|
152
153
|
return out;
|
|
@@ -147,12 +147,13 @@ function gather({ budget, now, days = DAYS }) {
|
|
|
147
147
|
['agy', collectAgyLedger({ budget, now, days })],
|
|
148
148
|
['codex', collectCodexLedger({ budget, days })],
|
|
149
149
|
];
|
|
150
|
-
|
|
150
|
+
// path: 리포트 --by project 가 기록 파일에서 프로젝트를 찾을 때 쓴다 (projects.mjs).
|
|
151
|
+
const books = [...trackers.entries()].map(([path, t]) => ({ tool: 'claude', path, days: t.days }));
|
|
151
152
|
const slots = [...trackers.values()].map((t) => t.slots);
|
|
152
153
|
for (const [tool, o] of others) {
|
|
153
154
|
pending += o.pending;
|
|
154
155
|
size += o.size;
|
|
155
|
-
books.push(...o.days.map((d) => ({ tool, days: d })));
|
|
156
|
+
books.push(...o.days.map((d, i) => ({ tool, path: o.paths[i], days: d })));
|
|
156
157
|
slots.push(...o.slots);
|
|
157
158
|
}
|
|
158
159
|
return { books, slots, pending, size };
|
package/src/sources/claude.mjs
CHANGED
|
@@ -69,13 +69,14 @@ export function _stats() {
|
|
|
69
69
|
return { trackers: trackers.size, subTrackers: subTrackers.size };
|
|
70
70
|
}
|
|
71
71
|
|
|
72
|
+
// 기록을 아직 다 읽지 못한 세션의 상태. 읽다 만 기록의 진행 단계는 틀릴 수 있어 화면에는 … 로만 보인다 (진행률은 헤더 한 줄로 모은다).
|
|
72
73
|
function loadingPhase(t) {
|
|
73
|
-
return t?.loading != null ? { kind: 'think', msg: 'loading'
|
|
74
|
+
return t?.loading != null ? { kind: 'think', msg: 'loading' } : null;
|
|
74
75
|
}
|
|
75
76
|
|
|
76
77
|
// 서브에이전트 전체(끝난 것 포함)의 토큰·비용 합계. 메인 세션 합계에 더해 화면에 보인다.
|
|
77
78
|
function emptySub() {
|
|
78
|
-
return { count: 0, tokens: emptyTokens(), cost: 0, costNoCache: 0, costUnknown: false, files: [], activity: [] };
|
|
79
|
+
return { count: 0, tokens: emptyTokens(), cost: 0, costNoCache: 0, costUnknown: false, loading: false, files: [], activity: [] };
|
|
79
80
|
}
|
|
80
81
|
|
|
81
82
|
// 메인 tracker 와 서브에이전트 합계를 화면에 보일 세션 숫자로 합친다. 기록을 아직 읽지 않았으면(t 없음) 비용은 null.
|
|
@@ -89,6 +90,8 @@ function sessionTotals(t, sub) {
|
|
|
89
90
|
cost: t ? t.cost + sub.cost : null,
|
|
90
91
|
costNoCache: t ? t.costNoCache + sub.costNoCache : null,
|
|
91
92
|
costUnknown: Boolean(t?.costUnknown || sub.costUnknown),
|
|
93
|
+
// 메인이나 서브에이전트 기록을 아직 다 읽지 못해 숫자가 덜 찬 상태. 표는 이 동안 숫자 대신 … 를 보인다.
|
|
94
|
+
loading: Boolean(t?.loading != null || sub.loading),
|
|
92
95
|
context: { used, window: contextWindow(t?.model, used) },
|
|
93
96
|
files: t ? mergeFiles([{ agent: '메인', files: t.files }, ...sub.files]) : [],
|
|
94
97
|
turns: t?.turns ?? [],
|
|
@@ -112,6 +115,7 @@ function readMembers(transcript, parent, budget) {
|
|
|
112
115
|
sub.cost += t.cost;
|
|
113
116
|
sub.costNoCache += t.costNoCache;
|
|
114
117
|
sub.costUnknown ||= t.costUnknown;
|
|
118
|
+
sub.loading ||= t.loading != null;
|
|
115
119
|
sub.activity.push(t.activity);
|
|
116
120
|
if (t.files.length) sub.files.push({ agent: meta.agentType ?? 'agent', files: t.files, startedAt: t.firstAt ?? undefined });
|
|
117
121
|
const age = Date.now() - t.mtimeMs;
|
|
@@ -134,6 +138,7 @@ function readMembers(transcript, parent, budget) {
|
|
|
134
138
|
cost: t.cost,
|
|
135
139
|
costNoCache: t.costNoCache,
|
|
136
140
|
costUnknown: t.costUnknown,
|
|
141
|
+
loading: t.loading != null,
|
|
137
142
|
startedAt: t.events[0]?.at,
|
|
138
143
|
});
|
|
139
144
|
}
|
|
@@ -276,7 +281,7 @@ function endedFromTranscripts(known, selectedId, budget) {
|
|
|
276
281
|
live: false,
|
|
277
282
|
lazy: !t,
|
|
278
283
|
status: 'ended',
|
|
279
|
-
phase:
|
|
284
|
+
phase: { kind: 'ended' },
|
|
280
285
|
waitingFor: null,
|
|
281
286
|
now: '',
|
|
282
287
|
startedAt: head.startedAt,
|
|
@@ -123,7 +123,7 @@ const books = new Map();
|
|
|
123
123
|
// 기록마다 날짜별 합계(days)와 5분 칸(slots), 아직 읽지 않은 크기(pending)·전체 크기(size).
|
|
124
124
|
// days: 최근 며칠 안에 바뀐 기록을 볼지 (평소 7일, 리포트는 더 길게).
|
|
125
125
|
export function collectCodexLedger({ budget, days = DAYS } = {}) {
|
|
126
|
-
const out = { days: [], slots: [], pending: 0, size: 0 };
|
|
126
|
+
const out = { days: [], slots: [], paths: [], pending: 0, size: 0 };
|
|
127
127
|
const files = recentFiles(days);
|
|
128
128
|
const keep = new Set(files);
|
|
129
129
|
for (const p of books.keys()) if (!keep.has(p)) books.delete(p);
|
|
@@ -134,6 +134,7 @@ export function collectCodexLedger({ budget, days = DAYS } = {}) {
|
|
|
134
134
|
out.pending += b.pending;
|
|
135
135
|
out.size += b.tail.size;
|
|
136
136
|
out.days.push(b.days);
|
|
137
|
+
out.paths.push(p);
|
|
137
138
|
out.slots.push(b.slots);
|
|
138
139
|
}
|
|
139
140
|
return out;
|
|
@@ -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
|
+
}
|
package/src/ui/glyphs.mjs
CHANGED
|
@@ -10,6 +10,8 @@ const NORMAL = {
|
|
|
10
10
|
rule: '─',
|
|
11
11
|
bar: { fill: '▃', empty: NO_COLOR ? '▁' : '▃' },
|
|
12
12
|
week: '▁▂▃▄▅▆▇█',
|
|
13
|
+
// 시작할 때 헤더의 집계 진행 막대. 색이 없으면 채운 칸과 빈칸이 모양으로 갈리도록 ASCII 로 그린다.
|
|
14
|
+
progress: NO_COLOR ? { l: '[', r: ']', fill: '#', empty: '.' } : { l: '▕', r: '▏', fill: '█', empty: '░' },
|
|
13
15
|
waiting: '◆',
|
|
14
16
|
waitingBlink: '◇',
|
|
15
17
|
unseen: '●',
|
|
@@ -35,6 +37,7 @@ const SAFE = {
|
|
|
35
37
|
// 색이 없어도 채운 칸과 빈칸이 모양으로 갈리게 한다.
|
|
36
38
|
bar: { fill: '#', empty: NO_COLOR ? '.' : '#' },
|
|
37
39
|
week: '_.:-=+*#',
|
|
40
|
+
progress: { l: '[', r: ']', fill: '#', empty: '.' },
|
|
38
41
|
waiting: '!',
|
|
39
42
|
waitingBlink: '.',
|
|
40
43
|
unseen: '*',
|
package/src/ui/table.mjs
CHANGED
|
@@ -132,7 +132,7 @@ export function header(view, W) {
|
|
|
132
132
|
const rate = rateText ? [{ t: ` (${rateText}/h)`, fg: PALETTE.muted, bg: B }] : null;
|
|
133
133
|
// bar: 7일 금액 뒤의 날짜별 막대. 집계 중이거나 날짜별 값이 없으면 넣지 않는다.
|
|
134
134
|
const bar = u?.loading == null && u?.days7?.length ? [{ t: ' ', bg: B }, ...weekBar(u.days7, view.costMode).map((x) => ({ ...x, bg: B }))] : null;
|
|
135
|
-
const week = (tok, withBar = false) =>
|
|
135
|
+
const week = (tok, withBar = false) => period(t('hdr.week'), u.week, tok, [], withBar && bar ? bar : []);
|
|
136
136
|
// 장부를 못 읽었으면 화면에 있는 세션(모든 도구)의 누적 토큰이라도 보인다.
|
|
137
137
|
const fallback = [{ t: `Σ ${fmtTokens(sessions.reduce((a, s) => a + (s.tokens?.total ?? 0), 0))} tok`, fg: PALETTE.muted, bg: B }];
|
|
138
138
|
const clockSeg = { t: clock(view.data.at), fg: PALETTE.muted, bg: B };
|
|
@@ -164,7 +164,9 @@ export function header(view, W) {
|
|
|
164
164
|
// 캐시 제외 화면에서도 'API 예상' 은 기준이 드러나므로 캐시 제외 표시 없이 남길 수 있다.
|
|
165
165
|
...(projSeg ? [{ api: 'short', budget: 'only' }, { budget: 'only' }] : []),
|
|
166
166
|
];
|
|
167
|
-
|
|
167
|
+
// 7일 장부를 처음 읽는 동안은 오늘·7일·1시간·막대 자리를 진행 줄 하나로 둔다 (집계 중 ▕███░░░░░░░▏ 30%). 좁으면 막대를 뺀다.
|
|
168
|
+
const loading = u?.loading != null ? progressSegs(u.loading, B) : null;
|
|
169
|
+
const rights = loading ? [[...loading.full, dot, clockSeg], [...loading.short, dot, clockSeg], [clockSeg]] : u ? [...shapes.filter((o) => !net || o.api || o.budget === 'only').map(right), [clockSeg]] : [[...fallback, dot, clockSeg], [clockSeg]];
|
|
168
170
|
// 사용량 숫자가 상태 이름보다 중요하므로, 이름을 먼저 줄이고 그래도 모자라면 오른쪽을 줄인다.
|
|
169
171
|
// 시각만 남기 전에는 live 수와 ○ 대기를 먼저 빼서 오늘 비용을 지킨다.
|
|
170
172
|
const fit = (r, narrow, drop) => {
|
|
@@ -174,7 +176,7 @@ export function header(view, W) {
|
|
|
174
176
|
};
|
|
175
177
|
const kept = rights.slice(0, -1);
|
|
176
178
|
// 캐시 제외 기준은 '캐시제외' 표시 때문에 9칸이 더 든다. 시각만 남기기 전에 시각을 빼고 '캐시제외 오늘 $5.20' 을 남긴다.
|
|
177
|
-
const bare = u && net ? [right({ api: 'short', clock: false })] : [];
|
|
179
|
+
const bare = u && net && !loading ? [right({ api: 'short', clock: false })] : [];
|
|
178
180
|
const tries = [
|
|
179
181
|
...kept.flatMap((r) => [[r, false, 0], [r, true, 0]]),
|
|
180
182
|
...[1, 2].flatMap((drop) => kept.map((r) => [r, true, drop])),
|
|
@@ -188,6 +190,22 @@ export function header(view, W) {
|
|
|
188
190
|
return line(leftOf(true, 2), W, B);
|
|
189
191
|
}
|
|
190
192
|
|
|
193
|
+
// 집계 진행률은 10% 단위로만 올린다 (다시 그리는 횟수를 줄인다). 막대는 10칸이라 한 칸이 10% 다.
|
|
194
|
+
export const progressStep = (r) => Math.min(100, Math.max(0, Math.floor((Number(r) || 0) * 10) * 10));
|
|
195
|
+
|
|
196
|
+
// 헤더 진행 줄의 조각. full: 글·막대·%, short: 글·% 만.
|
|
197
|
+
export function progressSegs(r, bg) {
|
|
198
|
+
const pct = progressStep(r);
|
|
199
|
+
const P = glyphs().progress;
|
|
200
|
+
const filled = pct / 10;
|
|
201
|
+
const label = { t: `${t('hdr.loading')} `, fg: PALETTE.info, bg };
|
|
202
|
+
const num = { t: `${pct}%`, fg: PALETTE.muted, bg };
|
|
203
|
+
return {
|
|
204
|
+
full: [label, { t: P.l, fg: PALETTE.faint, bg }, { t: P.fill.repeat(filled), fg: PALETTE.brand, bg }, { t: P.empty.repeat(10 - filled), fg: PALETTE.faint, bg }, { t: P.r + ' ', fg: PALETTE.faint, bg }, num],
|
|
205
|
+
short: [label, num],
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
|
|
191
209
|
// 폭이 모자랄 때 도구 이름 대신 쓰는 짧은 이름.
|
|
192
210
|
export const TOOL_SHORT = { claude: 'cla', codex: 'cdx', gemini: 'gem' };
|
|
193
211
|
|
|
@@ -317,7 +335,9 @@ export function sessionRow(s, c, W, selected, frame, hot, costMode = 'api', pinn
|
|
|
317
335
|
const pc = s.phase?.kind === 'idle' ? PALETTE.info : PHASE_COLOR[s.phase?.kind] ?? PALETTE.muted;
|
|
318
336
|
// 아직 토큰을 하나도 쓰지 않은 세션은 숫자 칸을 비운다. 기다리는 중이면 '아직 지시 없음'.
|
|
319
337
|
const blank = s.lazy || !(s.tokens?.total > 0);
|
|
320
|
-
|
|
338
|
+
// 기록을 아직 다 읽지 못한 세션은 덜 찬 숫자 대신 … 를 둔다 (다 읽은 뒤의 0 은 그대로 0).
|
|
339
|
+
const partial = Boolean(s.loading);
|
|
340
|
+
const status = blank && !partial && s.tool !== 'gemini' && (s.status === 'idle' || s.status === 'live') ? t('phase.noPrompt') : statusText(s.phase);
|
|
321
341
|
const segs = [
|
|
322
342
|
{ t: selected ? glyphs().select : ' ', fg: PALETTE.brand, bold: true },
|
|
323
343
|
{ ...g, t: g.t + ' ' },
|
|
@@ -331,14 +351,17 @@ export function sessionRow(s, c, W, selected, frame, hot, costMode = 'api', pinn
|
|
|
331
351
|
if (c.showProject) segs.push({ t: pad(s.project ?? '', c.project) + ' ', fg: ended ? PALETTE.ended : PALETTE.muted });
|
|
332
352
|
segs.push(
|
|
333
353
|
{ t: pad(status, c.status) + ' ', fg: pc, bold: s.status === 'waiting' },
|
|
334
|
-
{ t: pad(blank ? '' : fmtTokens(s.tokens.total), c.tokens, 'right') + ' ', fg: ended ? PALETTE.ended : PALETTE.muted },
|
|
354
|
+
{ t: pad(partial ? '…' : blank ? '' : fmtTokens(s.tokens.total), c.tokens, 'right') + ' ', fg: ended ? PALETTE.ended : partial ? PALETTE.info : PALETTE.muted },
|
|
335
355
|
);
|
|
336
|
-
if (c.showCost) segs.push({ t: pad(blank ? '' : (hot?.has(s.id) ? glyphs().hot : '') + money(costOf(s, costMode), s.costUnknown), c.cost, 'right') + ' ', fg: s.cost == null || ended ? PALETTE.info : hot?.has(s.id) ? PALETTE.money : PALETTE.muted, bold: Boolean(hot?.has(s.id)) });
|
|
337
|
-
segs.push(...gauge(s.context?.used ?? 0, s.context?.window ?? 0, c.cells), { t: ' ' }, { t: pad(idle, c.age, 'right'), fg: waiting ? PALETTE.waiting : PALETTE.info });
|
|
356
|
+
if (c.showCost) segs.push(partial ? { t: pad('…', c.cost, 'right') + ' ', fg: PALETTE.info } : { t: pad(blank ? '' : (hot?.has(s.id) ? glyphs().hot : '') + money(costOf(s, costMode), s.costUnknown), c.cost, 'right') + ' ', fg: s.cost == null || ended ? PALETTE.info : hot?.has(s.id) ? PALETTE.money : PALETTE.muted, bold: Boolean(hot?.has(s.id)) });
|
|
357
|
+
segs.push(...(partial ? pendingGauge(c.cells) : gauge(s.context?.used ?? 0, s.context?.window ?? 0, c.cells)), { t: ' ' }, { t: pad(idle, c.age, 'right'), fg: waiting ? PALETTE.waiting : PALETTE.info });
|
|
338
358
|
// 종료 행은 밝기 말고도 기울임꼴로 구분한다 (색이 없으면 · 글리프와 '종료' 글자로 구분된다).
|
|
339
359
|
return line(ended ? segs.map((x) => ({ ...x, italic: true })) : segs, W, bg);
|
|
340
360
|
}
|
|
341
361
|
|
|
362
|
+
// 기록을 읽는 중인 세션의 CONTEXT 칸: 빈 막대와 … (gauge 와 같은 폭).
|
|
363
|
+
const pendingGauge = (cells) => [{ t: glyphs().bar.empty.repeat(cells), fg: PALETTE.faint }, { t: pad('…', 5, 'right'), fg: PALETTE.info }];
|
|
364
|
+
|
|
342
365
|
// 표의 STATUS 칸 글. 응답 대기는 ◆ 와 행 색으로 이미 보이므로 무엇을 허락해 달라는지만 적고, 요청 내용이 없으면 '응답 대기' 를 남긴다.
|
|
343
366
|
// 상세 창은 phaseText 의 긴 문구 전체를 보인다.
|
|
344
367
|
export const statusText = (phase) => phaseText(phase, { short: true });
|
|
@@ -369,9 +392,9 @@ export function memberRow(m, last, c, W, frame, parentModel, costMode = 'api') {
|
|
|
369
392
|
);
|
|
370
393
|
segs.push(
|
|
371
394
|
{ t: pad(statusText(m.phase), c.status) + ' ', fg: done ? PALETTE.info : PHASE_COLOR[m.phase?.kind] ?? PALETTE.muted },
|
|
372
|
-
{ t: pad(started ? fmtTokens(m.tokens ?? 0) : '', c.tokens, 'right') + ' ', fg: done ? PALETTE.info : PALETTE.muted },
|
|
395
|
+
{ t: pad(m.loading ? '…' : started ? fmtTokens(m.tokens ?? 0) : '', c.tokens, 'right') + ' ', fg: done || m.loading ? PALETTE.info : PALETTE.muted },
|
|
373
396
|
);
|
|
374
|
-
if (c.showCost) segs.push({ t: pad(started ? money(costOf(m, costMode), m.costUnknown) : '', c.cost, 'right') + ' ', fg: done ? PALETTE.info : PALETTE.muted });
|
|
397
|
+
if (c.showCost) segs.push({ t: pad(m.loading ? '…' : started ? money(costOf(m, costMode), m.costUnknown) : '', c.cost, 'right') + ' ', fg: done || m.loading ? PALETTE.info : PALETTE.muted });
|
|
375
398
|
// 끝난 팀원은 종료 행처럼 기울임꼴로 둔다.
|
|
376
399
|
return line(done ? segs.map((x) => ({ ...x, italic: true })) : segs, W);
|
|
377
400
|
}
|
package/src/ui.mjs
CHANGED
|
@@ -21,8 +21,11 @@ export function animating(view) {
|
|
|
21
21
|
return filterSessions(view.data.sessions, view.filter).some((s) => glyphMoves(s) || (s.members ?? []).some((m) => m.status !== 'done'));
|
|
22
22
|
}
|
|
23
23
|
|
|
24
|
+
// 로딩 중(준비 완료 전이거나 7일 집계 중)에는 경과 시간(IDLE 등)을 데이터를 받은 시각에 맞춰, 스피너 프레임마다 숫자가 따로 바뀌지 않게 한다.
|
|
25
|
+
const settling = (view) => view.data && (view.ready === false || view.data.usage?.loading != null);
|
|
26
|
+
|
|
24
27
|
export function render(view, W, H) {
|
|
25
|
-
setNow(Date.now());
|
|
28
|
+
setNow(settling(view) && view.data.at ? view.data.at : Date.now());
|
|
26
29
|
const lines = [];
|
|
27
30
|
if (!view.data) {
|
|
28
31
|
// 첫 수집은 동기로 돌아 이 화면이 다시 그려지지 않으므로 움직이지 않는 로고를 둔다.
|
|
@@ -78,7 +81,8 @@ export function render(view, W, H) {
|
|
|
78
81
|
if (start === selRow && rows[start - 1]?.g && lastOfSel - start + 2 <= shown) start--;
|
|
79
82
|
const isSession = (r) => r.s && !r.m;
|
|
80
83
|
const visible = rows.slice(start, start + shown);
|
|
81
|
-
|
|
84
|
+
// 준비 완료 전에는 값이 커지는 대로 ▲ 가 옮겨 다니므로 붙이지 않는다.
|
|
85
|
+
const hot = view.ready === false ? null : topCost(visible.filter(isSession).map((r) => r.s), view.costMode);
|
|
82
86
|
if (!sessions.length) table.push(...(view.filter ? [line([{ t: ` ${t('ui.noMatch', { q: view.filter })}`, fg: PALETTE.muted, italic: true }], TW)] : emptyLines(view, TW)));
|
|
83
87
|
for (const r of visible) table.push(r.g ? groupRow(r.g, TW) : r.m ? memberRow(r.m, r.last, c, TW, view.frame, r.s.model, view.costMode) : sessionRow(r.s, c, TW, r.s === sel, view.frame, hot, view.costMode, Boolean(view.pins?.includes(r.s.id))));
|
|
84
88
|
if (clipped) {
|