@sejuneoh/aitop 0.21.2 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -29,9 +29,19 @@ aitop live screen
29
29
  aitop --all include sessions that ended in the last 24 hours
30
30
  aitop --json print a snapshot as JSON and exit
31
31
  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)
32
33
  aitop --help all options
33
34
  ```
34
35
 
36
+ ### tmux status line
37
+
38
+ `aitop --line` prints today's cost (API list price, `/$<budget>` when a daily budget is set), the number of Claude Code sessions waiting for you, 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. `--line=tmux` adds tmux colours, `NO_COLOR` turns them off.
39
+
40
+ ```tmux
41
+ set -g status-right '#(aitop --line=tmux)'
42
+ set -g status-interval 15
43
+ ```
44
+
35
45
  Keys: `↑↓` select · `n` next session to check · `/` search · `s` sort · `g` group · `p` pin · `f` changed files · `?` help · `q` quit
36
46
 
37
47
  Settings can also go in `~/.config/aitop/config.json`. See `aitop --help` or the [detailed manual (Korean)](https://github.com/SejuneOh/aitop/blob/main/docs/README.ko.md).
package/bin/aitop.mjs CHANGED
@@ -2,6 +2,7 @@
2
2
  import { readFileSync } from 'node:fs';
3
3
  import { budgetDayOption, configJson, configText, resolveConfig } from '../src/config.mjs';
4
4
  import { notifyOptions } from '../src/notify.mjs';
5
+ import { lineOption } from '../src/line.mjs';
5
6
  import { mask, setAmbiguous, stripControl } from '../src/text.mjs';
6
7
 
7
8
  const KNOWN = new Set(['-h', '--help', '-v', '--version', '--once', '--all', '--json', '--doctor', '--bell', '--show-requests', '--print-config', '--no-bell', '--no-all', '--no-show-requests', '--debug', '--no-debug', '--color-blind', '--no-color-blind']);
@@ -21,8 +22,16 @@ if (budget.error) {
21
22
  process.stderr.write(`aitop: ${budget.error}\n`);
22
23
  process.exit(2);
23
24
  }
25
+ // --line, --line=tmux, --line-width <N> 은 lineOption 이 꺼낸다.
26
+ const line = lineOption(budget.rest);
27
+ if (line.error) {
28
+ process.stderr.write(`aitop: ${line.error}\n`);
29
+ process.exit(2);
30
+ }
31
+ // 사용자가 준 NO_COLOR. 아래에서 파이프 출력이면 NO_COLOR 를 켜므로 그 전에 읽어 둔다 (tmux 의 #() 는 TTY 가 아니다).
32
+ const userNoColor = Boolean(process.env.NO_COLOR);
24
33
  // --theme light, --theme=light 처럼 값을 받는 옵션은 따로 꺼낸다.
25
- const argv = budget.rest;
34
+ const argv = line.rest;
26
35
  let theme = null;
27
36
  const rest = [];
28
37
  for (let i = 0; i < argv.length; i++) {
@@ -75,6 +84,9 @@ const HELP = `${BRAND.logo} aitop - 터미널에서 Claude Code · Codex · Anti
75
84
  aitop 실시간 화면
76
85
  aitop --once 현재 상태를 한 번 출력하고 끝낸다
77
86
  aitop --all 종료된 세션(24시간 이내)도 함께 본다
87
+ aitop --line 오늘 비용·응답 대기 수·시간당 지출을 한 줄로 내고 끝낸다 (tmux 상태줄용, 예: $54.13/$50 wait 2 $3.1/h)
88
+ --line=tmux 는 tmux 색 서식(#[fg=...])을 넣는다. --line-width <N> 폭 상한(기본 40, 넘으면 뒤 항목부터 뺀다)
89
+ 장부 캐시만 읽는다. 캐시가 없어 1.5초 안에 못 읽으면 ... 을 낸다. 응답 대기 수는 Claude Code 세션만 센다
78
90
  aitop --json 세션 목록과 사용량 합계를 JSON 으로 한 번 출력한다 (--all 과 함께 쓸 수 있다)
79
91
  aitop --doctor Claude · Codex · Antigravity · Gemini 기록과 실행 중인 프로세스, 설정 파일을 점검한다 (--json 과 함께 쓸 수 있다)
80
92
  aitop --bell 응답 대기 세션이 새로 생기면 터미널 벨을 울린다
@@ -131,6 +143,24 @@ if (args.has('--print-config')) {
131
143
  const log = initLog({ enabled: opt.debug, version: VERSION });
132
144
  if (opt.debug && !log.on) process.stderr.write(`aitop: 디버그 로그를 열 수 없어 끕니다 (${log.path})\n`);
133
145
 
146
+ // --line: 세션 화면·프로세스 목록 없이 장부 캐시만 읽어 한 줄을 내고 끝낸다. 실패해도 tmux 에 오류를 남기지 않게 0 으로 끝낸다.
147
+ if (line.mode) {
148
+ const { collectLine, formatLine, PENDING } = await import('../src/line.mjs');
149
+ const { flushCache } = await import('../src/cache.mjs');
150
+ let text = PENDING;
151
+ try {
152
+ // AITOP_LINE_MS: 시간 상한(ms). 테스트에서 캐시 없는 첫 실행을 흉내 낼 때 쓴다.
153
+ const capMs = Number(process.env.AITOP_LINE_MS) > 0 ? Number(process.env.AITOP_LINE_MS) : undefined;
154
+ const v = await collectLine({ capMs });
155
+ if (v) text = formatLine({ ...v, budgetDay: opt.budgetDay }, { mode: line.mode, noColor: userNoColor, width: line.width, colorBlind: opt.colorBlind });
156
+ flushCache();
157
+ } catch (e) {
158
+ debug('aitop', 'line failed', e);
159
+ }
160
+ await new Promise((resolve) => process.stdout.write(text + '\n', resolve));
161
+ process.exit(0);
162
+ }
163
+
134
164
  // 파이프나 파일로 받을 때는 색 코드를 넣지 않는다. 화면 모듈이 불러올 때 NO_COLOR 를 읽으므로 그 전에 정한다.
135
165
  const forced = process.env.FORCE_COLOR != null && !['', '0', 'false'].includes(process.env.FORCE_COLOR);
136
166
  if (!process.stdout.isTTY && !forced && !process.env.NO_COLOR) process.env.NO_COLOR = '1';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sejuneoh/aitop",
3
- "version": "0.21.2",
3
+ "version": "0.22.0",
4
4
  "description": "터미널에서 Claude Code · Codex · Antigravity · Gemini 세션과 토큰을 실시간으로 보는 읽기 전용 모니터",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/help.mjs CHANGED
@@ -82,6 +82,7 @@ export const OPTIONS = [
82
82
  ['--show-requests', '응답 대기 요청 전체를 상세·--json 에'],
83
83
  ['--color-blind', '적록 색약용 색 (대기·돈·경고를 노랑·파랑 계열로)'],
84
84
  ['--debug', '디버그 로그를 남긴다'],
85
+ ['--line[=tmux]', '오늘 비용·대기 수·시간당 지출 한 줄 (tmux 상태줄용)'],
85
86
  ['--print-config', '설정 값과 출처, 설정 파일 위치'],
86
87
  ['AITOP_AMBIGUOUS=wide', '·→─● 를 2칸으로 그리는 터미널용 (1칸 기호로)'],
87
88
  ];
package/src/line.mjs ADDED
@@ -0,0 +1,76 @@
1
+ // aitop --line: tmux 상태줄 같은 곳에 넣을 한 줄 요약. 예) $54.13/$50 wait 2 $3.1/h
2
+ // 글자는 ASCII 만 쓴다 (이모지·폭이 모호한 기호는 tmux 에서 칸이 어긋난다). 표기는 짧은 영어 약어로 고정하고 번역하지 않는다.
3
+ // 색은 --line=tmux 일 때 tmux 서식(#[fg=colourN])으로만 넣고 ANSI 코드는 쓰지 않는다. NO_COLOR 면 서식도 넣지 않는다.
4
+
5
+ export const MODES = ['plain', 'tmux'];
6
+ export const DEFAULT_WIDTH = 40;
7
+ // 캐시가 없을 때(처음 실행) 장부를 읽는 시간 상한. 넘으면 '...' 만 내고 끝낸다 (tmux 를 오래 막지 않게).
8
+ export const CAP_MS = 1500;
9
+ // 캐시가 없거나 시간 상한을 넘었을 때 내는 글.
10
+ export const PENDING = '...';
11
+
12
+ // tmux 256색 번호. 응답 대기는 눈에 띄는 주황, 돈은 화면 헤더와 같은 연두. 색약용은 노랑·파랑 계열로 가른다.
13
+ const COLOURS = { normal: { waiting: 'colour214', money: 'colour154' }, colorBlind: { waiting: 'colour226', money: 'colour75' } };
14
+
15
+ // --line, --line=plain|tmux, --line-width <N>, --line-width=<N> 를 꺼낸다. line 은 켜지 않았으면 null.
16
+ export function lineOption(argv) {
17
+ let mode = null;
18
+ let width = DEFAULT_WIDTH;
19
+ let error = null;
20
+ const rest = [];
21
+ for (let i = 0; i < argv.length; i++) {
22
+ const a = argv[i];
23
+ const m = /^--line(?:=(.*))?$/.exec(a);
24
+ if (m) {
25
+ const v = m[1] ?? 'plain';
26
+ if (MODES.includes(v)) mode = v;
27
+ else error ??= `--line 값 ${JSON.stringify(v)} 이 잘못되었습니다 (plain 또는 tmux)`;
28
+ continue;
29
+ }
30
+ const w = /^--line-width(?:=(.*))?$/.exec(a);
31
+ if (!w) {
32
+ rest.push(a);
33
+ continue;
34
+ }
35
+ const raw = w[1] ?? (argv[i + 1]?.startsWith('-') ? '' : (argv[++i] ?? ''));
36
+ const n = /^\d+$/.test(raw) ? Number(raw) : NaN;
37
+ if (n > 0) width = n;
38
+ else error ??= raw === '' ? '--line-width 값이 없습니다 (글자 수)' : `--line-width 값 ${JSON.stringify(raw)} 이 잘못되었습니다 (0 보다 큰 정수)`;
39
+ }
40
+ return { mode, width, rest, error };
41
+ }
42
+
43
+ // 오늘 비용: 화면 헤더와 같은 자릿수 (100 달러 아래는 센트까지).
44
+ export const money = (x) => (x >= 1000 ? `$${Math.round(x).toLocaleString('en-US')}` : x >= 100 ? `$${x.toFixed(0)}` : `$${x.toFixed(2)}`);
45
+ const budgetText = (d) => (Number.isInteger(d) ? `$${d}` : `$${d.toFixed(2)}`);
46
+ // 시간당 지출: 짧게 (1 달러 아래만 센트까지).
47
+ const rate = (x) => (x >= 100 ? `$${x.toFixed(0)}` : x >= 1 ? `$${x.toFixed(1)}` : `$${x.toFixed(2)}`);
48
+ // 표시하면 0 으로 보이는 값은 0 으로 본다.
49
+ const zero = (x) => !(Number(x) >= 0.005);
50
+
51
+ // 값: today(오늘 비용, API 정가 환산), budgetDay(하루 예산, 없으면 null), waiting(응답 대기 수), perHour(최근 1시간 지출).
52
+ // 0 인 항목은 뺀다. 오늘 비용이 0 이어도 예산이 있으면 $0.00/$50 으로 보인다.
53
+ // width 를 넘으면 뒤 항목부터 뺀다. mode 가 tmux 이고 noColor 가 아니면 항목마다 tmux 서식을 씌운다.
54
+ export function formatLine({ today = 0, budgetDay = null, waiting = 0, perHour = 0 } = {}, { mode = 'plain', noColor = false, width = DEFAULT_WIDTH, colorBlind = false } = {}) {
55
+ const c = COLOURS[colorBlind ? 'colorBlind' : 'normal'];
56
+ const parts = [];
57
+ const hasBudget = typeof budgetDay === 'number' && budgetDay > 0;
58
+ if (!zero(today) || hasBudget) parts.push({ text: `${money(zero(today) ? 0 : today)}${hasBudget ? `/${budgetText(budgetDay)}` : ''}`, fg: c.money });
59
+ if (waiting > 0) parts.push({ text: `wait ${waiting}`, fg: c.waiting });
60
+ if (!zero(perHour)) parts.push({ text: `${rate(perHour)}/h`, fg: c.money });
61
+ while (parts.length && parts.map((p) => p.text).join(' ').length > width) parts.pop();
62
+ const styled = mode === 'tmux' && !noColor;
63
+ return parts.map((p) => (styled ? `#[fg=${p.fg}]${p.text}#[default]` : p.text)).join(' ');
64
+ }
65
+
66
+ // 장부 캐시와 새로 붙은 줄만 읽어 값을 모은다 (세션 화면용 기록 전체·프로세스 목록은 읽지 않는다).
67
+ // 시간 상한 안에 다 읽지 못했거나 아직 집계 중이면 null. 읽은 만큼은 aitop 캐시에 남아 다음 실행이 이어 읽는다.
68
+ export async function collectLine({ capMs = CAP_MS, now = Date.now() } = {}) {
69
+ const { createBudget } = await import('./tail.mjs');
70
+ const { collectLedger } = await import('./sources/claude-ledger.mjs');
71
+ const { claudeWaitingCount } = await import('./sources/claude.mjs');
72
+ const budget = createBudget(Infinity, capMs);
73
+ const usage = collectLedger({ budget, now });
74
+ if (budget.exhausted || usage.loading != null) return null;
75
+ return { today: usage.today.cost, waiting: claudeWaitingCount(), perHour: usage.lastHour.cost };
76
+ }
package/src/notify.mjs CHANGED
@@ -67,10 +67,11 @@ export function which(name, envPath = process.env.PATH ?? '') {
67
67
  return null;
68
68
  }
69
69
 
70
- export function isWsl(env = process.env) {
70
+ // WSL 인지. --doctor 의 알림 안내에 쓴다. readVersion 은 테스트에서 /proc/version 대신 넣는다.
71
+ export function isWsl(env = process.env, readVersion = () => readFileSync('/proc/version', 'utf8')) {
71
72
  if (env.WSL_DISTRO_NAME || env.WSL_INTEROP) return true;
72
73
  try {
73
- return /microsoft/i.test(readFileSync('/proc/version', 'utf8'));
74
+ return /microsoft/i.test(readVersion());
74
75
  } catch {
75
76
  return false;
76
77
  }
package/src/pricing.mjs CHANGED
@@ -39,8 +39,8 @@ const GEMINI_PRICES = {
39
39
  'gemini-3.1-flash-lite': [{ input: 0.25, output: 1.5, cacheRead: 0.025 }],
40
40
  };
41
41
 
42
- // 가격표가 바뀌면 이 값이 바뀌고, 캐시 폴더도 바뀌어 예전 비용이 다시 계산된다.
43
- export const PRICE_TAG = createHash('sha1').update(JSON.stringify([PRICES, GEMINI_PRICES])).digest('hex').slice(0, 8);
42
+ // 가격표의 지문(8자리). 표의 값이 하나라도 바뀌면 지문도 바뀐다.
43
+ export const priceTag = (tables) => createHash('sha1').update(JSON.stringify(tables)).digest('hex').slice(0, 8);
44
44
 
45
45
  // 모델별 컨텍스트 창 크기(토큰). 출처: Anthropic 모델 표(2026-10). 표에 없는 모델은 contextWindow 가 추측한다.
46
46
  const WINDOWS = {
@@ -93,7 +93,9 @@ export function claudeCost(model, u) {
93
93
  }
94
94
 
95
95
  // Codex(OpenAI) API 정가 기준 환산 비용 (USD / 100만 토큰). Claude 와 같이 "API 로 썼다면" 기준이다.
96
- // 출처: 2026-11 가격 비교 사이트(pricepertoken.com, computeprices.com)의 OpenAI 정가. 추정값이라 README 에 적어 둔다.
96
+ // 출처: OpenAI 공식 가격표 https://developers.openai.com/api/docs/pricing 와 모델별 문서
97
+ // (https://developers.openai.com/api/docs/models/gpt-5.3-codex, gpt-5.1-codex, gpt-5.1-codex-mini, codex-mini-latest, gpt-4o-mini).
98
+ // 2026-11-11 확인, 다섯 모델 모두 공식 값과 같다. cacheRead 는 cached input 가격이다.
97
99
  const OPENAI_PRICES = {
98
100
  'gpt-5.3-codex': { input: 1.75, cacheRead: 0.175, output: 14 },
99
101
  'gpt-5.1-codex-mini': { input: 0.25, cacheRead: 0.025, output: 2 },
@@ -102,6 +104,10 @@ const OPENAI_PRICES = {
102
104
  'gpt-4o-mini': { input: 0.15, cacheRead: 0.075, output: 0.6 },
103
105
  };
104
106
 
107
+ // 가격표가 바뀌면 이 값이 바뀌고, 캐시 폴더도 바뀌어 예전 비용이 다시 계산된다. 세 표(Claude, Gemini, Codex)를 모두 넣는다.
108
+ export const PRICE_TABLES = [PRICES, GEMINI_PRICES, OPENAI_PRICES];
109
+ export const PRICE_TAG = priceTag(PRICE_TABLES);
110
+
105
111
  // Codex 세션 누적 토큰(tokens: input 은 캐시 제외, cacheRead, output)의 환산 비용. 가격표에 없는 모델이면 null.
106
112
  export function codexCost(model, t) {
107
113
  const p = lookup(OPENAI_PRICES, model);
@@ -289,15 +289,15 @@ function endedFromTranscripts(known, selectedId, budget) {
289
289
  return out;
290
290
  }
291
291
 
292
- export function collectClaude({ showEnded, budget, selectedId }) {
292
+ // ~/.claude/sessions/*.json 을 세션 id 마다 하나로 (살아 있는 쪽, 그다음 최근에 바뀐 쪽). 폴더를 읽지 못하면 null.
293
+ function sessionEntries() {
293
294
  let files;
294
295
  try {
295
296
  files = readdirSync(SESSIONS).filter((n) => n.endsWith('.json'));
296
297
  } catch (e) {
297
298
  debugIo('claude', 'sessions read failed', e);
298
- return [];
299
+ return null;
299
300
  }
300
- seen = new Set();
301
301
  const latest = new Map();
302
302
  for (const f of files) {
303
303
  const e = readJson(join(SESSIONS, f));
@@ -306,6 +306,20 @@ export function collectClaude({ showEnded, budget, selectedId }) {
306
306
  const prev = latest.get(e.sessionId);
307
307
  if (!prev || (e.alive && !prev.alive) || (e.updatedAt ?? e.startedAt) > (prev.updatedAt ?? prev.startedAt)) latest.set(e.sessionId, e);
308
308
  }
309
+ return latest;
310
+ }
311
+
312
+ // 응답 대기 중인 Claude 세션 수. 세션 파일과 pid 만 보므로 대화 기록·프로세스 목록을 읽지 않는다 (aitop --line 용).
313
+ export function claudeWaitingCount() {
314
+ let n = 0;
315
+ for (const e of sessionEntries()?.values() ?? []) if (e.alive && e.waitingFor) n++;
316
+ return n;
317
+ }
318
+
319
+ export function collectClaude({ showEnded, budget, selectedId }) {
320
+ const latest = sessionEntries();
321
+ if (!latest) return [];
322
+ seen = new Set();
309
323
 
310
324
  // 읽기 한도가 큰 기록 하나에 다 쓰이지 않도록, 살아 있는 세션의 새 줄부터 읽는다.
311
325
  const entries = [...latest.values()].sort((a, b) => Number(b.alive) - Number(a.alive));