@sejuneoh/aitop 0.27.0 → 0.29.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
@@ -17,7 +17,9 @@
17
17
 
18
18
  ## Install
19
19
 
20
- Requires Node.js 22+ on Linux, macOS or WSL.
20
+ Requires Node.js 22+ on Linux, macOS, WSL or Windows.
21
+
22
+ Native Windows support is early (Windows Terminal recommended): Claude Code and Codex sessions, `--once`, `--json`, `--report` and `--doctor` work, but process detection, desktop notifications and `--on-waiting` are not there yet ([#195](https://github.com/SejuneOh/aitop/issues/195)-[#197](https://github.com/SejuneOh/aitop/issues/197)). Until then a Codex session counts as running while its log was written in the last 10 minutes, so it drops out during a long step that writes nothing for over 10 minutes, and a crashed session can stay up to 10 minutes. Cache, log and config live in `%LOCALAPPDATA%\aitop\cache`, `%LOCALAPPDATA%\aitop\state` and `%APPDATA%\aitop` unless `XDG_*` is set.
21
23
 
22
24
  ```bash
23
25
  npm install -g @sejuneoh/aitop
@@ -31,7 +33,7 @@ aitop live screen
31
33
  aitop --all include sessions that ended in the last 24 hours
32
34
  aitop --json print a snapshot as JSON and exit
33
35
  aitop --doctor check which tools and logs aitop can see
34
- aitop --line print one short status line and exit (for tmux, e.g. $54.13/$50 wait 2 run 3 $3.1/h)
36
+ aitop --line print one short status line and exit (for tmux, e.g. $54.13 wait 2 fix-login 3m run 3 $3.1/h)
35
37
  aitop --report daily daily cost table and exit
36
38
  aitop --report monthly monthly cost table (last 12 months) and exit
37
39
  aitop --help all options
@@ -57,9 +59,27 @@ aitop --report daily --by project --days 7
57
59
  aitop --report monthly --by model --months 6
58
60
  ```
59
61
 
62
+ ### Notifications
63
+
64
+ Off by default and only on the live screen. Sessions already waiting (or already over 90% context) when aitop starts are not reported.
65
+
66
+ ```
67
+ aitop --notify desktop notification when a session starts waiting (notify-send on Linux/WSL, osascript on macOS)
68
+ aitop --notify=waiting,done,context pick the kinds; plain --notify uses the config file kinds, or waiting only when none are set
69
+ aitop --on-waiting 'my-hook.sh' run a command with /bin/sh -c for the same events (10 second limit, runs as you)
70
+ ```
71
+
72
+ - `waiting`: a session starts waiting for your approval or answer.
73
+ - `done`: a session that was busy for over 3 minutes in one turn (config `doneMinutes`; time spent waiting for approval does not count) goes idle and stays idle for 5 seconds. Brief idle gaps between tool calls, approval waits, ended sessions, subagents and sessions whose status is guessed from file times are not reported. Once per turn.
74
+ - `context`: context use passes 90%, once; it re-arms after it drops below 85% (for example after compaction).
75
+
76
+ The hook keeps its name: it gets `AITOP_EVENT` (`waiting`, `done` or `context`) plus `AITOP_TOOL`, `AITOP_PROJECT`, `AITOP_SESSION_ID`, `AITOP_CWD` and `AITOP_WAITING_FOR` in its environment. Config file: `"notify": true` or `"notify": ["waiting", "done", "context"]`, `"onWaiting": "..."` (file must be `chmod 600`), `"doneMinutes": 5`. Plain `--notify` keeps the kinds from the config `notify` list (waiting only when there is none). `--no-notify` turns off only the desktop notification: the hook still follows those kinds. `--bell` stays waiting only.
77
+
60
78
  ### tmux status line
61
79
 
62
- `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.
80
+ `aitop --line` prints today's cost (API list price, `/$<budget>` when a daily budget is set), the sessions waiting for you with the longest waiting one's name and wait time (`wait fix-login 3m` for one, `wait 2 fix-login 3m` for more; Claude Code read live, names cut to 12 columns with `~`), 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 (the waiting name goes before the waiting count; with a daily budget and a waiting name, `$/h` often does not fit in 40, so raise `--line-width` to keep it). 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 with their names) 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.
81
+
82
+ Session names come from your sessions, so in tmux always use `--line=tmux`: it escapes `#` in names, while plain output could let tmux expand a `#{...}` or `#(...)` inside a name. In a zsh prompt with `PROMPT_SUBST`, a `%` in a name can be expanded by zsh, so escape `%` (for example `${$(aitop --line)//\%/%%}`) or use the line only in tmux.
63
83
 
64
84
  ```tmux
65
85
  set -g status-right '#(aitop --line=tmux)'
@@ -68,7 +88,7 @@ set -g status-interval 15
68
88
 
69
89
  Keys: `↑↓` select · `n` next session to check · `/` search · `s` sort · `g` group · `p` pin · `f` changed files · `?` help · `q` quit
70
90
 
71
- 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).
91
+ Settings can also go in `~/.config/aitop/config.json` (`%APPDATA%\aitop\config.json` on Windows). See `aitop --help` or the [detailed manual (Korean)](https://github.com/SejuneOh/aitop/blob/main/docs/README.ko.md).
72
92
 
73
93
  ## License
74
94
 
package/bin/aitop.mjs CHANGED
@@ -68,7 +68,8 @@ const flag = (name) => {
68
68
  return on < 0 && off < 0 ? undefined : on > off;
69
69
  };
70
70
  // notify 는 --notify 가 뒤에 오면 true, --no-notify 가 뒤에 오면 false, 둘 다 없으면 정하지 않은 것이다.
71
- const notifyFlag = cli.notify ? true : notifyOptions(cliArgs, { notify: true }).notify ? undefined : false;
71
+ // --notify=<종류> 로 종류를 정했으면 그 배열을 값으로 둔다 (--print-config 에 보이게).
72
+ const notifyFlag = cli.notify ? (cli.eventsSet ? cli.events : true) : notifyOptions(cliArgs, { notify: true }).notify ? undefined : false;
72
73
  // onWaiting 은 --on-waiting 이 뒤에 오면 그 명령, --no-on-waiting 이 뒤에 오면 null(끔), 둘 다 없으면 정하지 않은 것이다.
73
74
  const onWaitingFlag = cli.onWaiting ?? (notifyOptions(cliArgs, { onWaiting: 'x' }).onWaiting === null ? null : undefined);
74
75
  const config = resolveConfig({ flags: { theme: THEMES.includes(theme) ? theme : undefined, colorBlind: flag('color-blind'), bell: flag('bell'), showRequests: flag('show-requests'), all: flag('all'), debug: flag('debug'), notify: notifyFlag, onWaiting: onWaitingFlag, budgetDay: budget.value, lang: langOpt.value }, file: cfgFile });
@@ -204,7 +205,7 @@ const { frameTimer } = await import('../src/frames.mjs');
204
205
  const { flushCache } = await import('../src/cache.mjs');
205
206
  const { toJson } = await import('../src/json.mjs');
206
207
  const { createSummaryWriter, summarize, writeSummary } = await import('../src/summary.mjs');
207
- const { createAttention, updateAttention, markSeen, nextAttention, windowTitle, createWaitWatch, takeNewlyWaiting, attentionCounts } = await import('../src/attention.mjs');
208
+ const { createAttention, updateAttention, markSeen, nextAttention, windowTitle, createWaitWatch, takeNewlyWaiting, attentionCounts, createEventWatch, takeEvents } = await import('../src/attention.mjs');
208
209
  const { createNotifier } = await import('../src/notify.mjs');
209
210
  const { onKey, fixFocus } = await import('../src/keys.mjs');
210
211
  const { admit, createLoading, latchReady } = await import('../src/loading.mjs');
@@ -212,7 +213,7 @@ const { admit, createLoading, latchReady } = await import('../src/loading.mjs');
212
213
  // 요청 전체 보기는 기본으로 꺼 둔다. 켜지 않으면 상세 패널에도 --json 에도 나가지 않는다.
213
214
  const showRequests = opt.showRequests;
214
215
  // settings: 도움말(?)에 보이는 지금 설정 값.
215
- const settings = { budgetDay: opt.budgetDay, notify: Boolean(alerts.notify), onWaiting: Boolean(alerts.onWaiting), debug: log.on, configPath: config.path };
216
+ const settings = { budgetDay: opt.budgetDay, notify: Boolean(alerts.notify), events: alerts.events, onWaiting: Boolean(alerts.onWaiting), debug: log.on, configPath: config.path };
216
217
  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: [] };
217
218
  const once = args.has('--once') || args.has('--json') || !process.stdout.isTTY;
218
219
  // ready: 시작할 때 세션 기록을 다 읽었는지 (loading.mjs). 그 전에는 비용·컨텍스트 정렬과 ▲ 를 고정한다. 한 번에 다 읽는 --once·--json 은 처음부터 준비 완료다.
@@ -233,6 +234,9 @@ let tools = null;
233
234
  const bell = opt.bell;
234
235
  const waitWatch = createWaitWatch();
235
236
  const notifier = !once && (alerts.notify || alerts.onWaiting) ? createNotifier(alerts) : null;
237
+ // 끝남(done)·context 경고는 켠 경우에만 센다 (#204). 벨은 늘 응답 대기만 울린다.
238
+ const eventKinds = alerts.events.filter((k) => k !== 'waiting');
239
+ const eventWatch = notifier && eventKinds.length ? createEventWatch({ doneMs: opt.doneMinutes * 60_000 }) : null;
236
240
 
237
241
  // throttle: 주기 갱신(tick)에서만 참이다. 로딩 중에는 loading.mjs 의 admit 이 허락할 때만 화면 데이터를 바꾼다.
238
242
  // 알림(벨·--notify·--on-waiting)은 화면에 올리지 않은 갱신에서도 그대로 돈다. 돌려주는 값은 화면 데이터를 바꿨는지.
@@ -253,7 +257,11 @@ function refresh({ throttle = false } = {}) {
253
257
  if (!once && (bell || notifier)) {
254
258
  const fresh = takeNewlyWaiting(waitWatch, data.sessions);
255
259
  if (fresh.length && bell) process.stdout.write('\x07');
256
- notifier?.fire(fresh);
260
+ if (alerts.events.includes('waiting')) notifier?.fire(fresh);
261
+ }
262
+ if (eventWatch) {
263
+ const evs = takeEvents(eventWatch, data.sessions, { ready: loading.ready });
264
+ for (const kind of eventKinds) notifier.fire(evs.filter((e) => e.kind === kind).map((e) => e.session), kind);
257
265
  }
258
266
  lastMore = data.more;
259
267
  if (!once) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sejuneoh/aitop",
3
- "version": "0.27.0",
3
+ "version": "0.29.0",
4
4
  "description": "터미널에서 Claude Code · Codex · Antigravity · Gemini 세션과 토큰을 실시간으로 보는 읽기 전용 모니터",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -18,7 +18,8 @@
18
18
  },
19
19
  "os": [
20
20
  "linux",
21
- "darwin"
21
+ "darwin",
22
+ "win32"
22
23
  ],
23
24
  "homepage": "https://github.com/SejuneOh/aitop#readme",
24
25
  "bugs": "https://github.com/SejuneOh/aitop/issues",
@@ -32,7 +33,7 @@
32
33
  },
33
34
  "scripts": {
34
35
  "start": "node bin/aitop.mjs",
35
- "test": "AITOP_LANG=ko node --test test/*.test.mjs",
36
- "test:e2e": "AITOP_LANG=ko node --test test/e2e/*.e2e.mjs"
36
+ "test": "node --import ./test/lang-ko.mjs --test test/*.test.mjs",
37
+ "test:e2e": "node --import ./test/lang-ko.mjs --test test/e2e/*.e2e.mjs"
37
38
  }
38
39
  }
package/src/attention.mjs CHANGED
@@ -68,3 +68,69 @@ export function takeNewlyWaiting(watch, sessions) {
68
68
  watch.ready = true;
69
69
  return ready ? fresh : [];
70
70
  }
71
+
72
+ // 끝남(done)·context 경고 감시 (#204). 켠 종류만 bin 이 골라 알린다.
73
+ // done: 한 작업(턴)의 작업 중(busy·shell) 시간 합이 doneMs 이상이고, 대기(idle)가 settleMs 동안 이어지면 한 번 알린다.
74
+ // 도구 호출 사이의 잠깐 대기는 settleMs 안에 다시 작업 중이 되므로 같은 작업으로 이어 센다 (그 틈도 작업 시간에 넣는다).
75
+ // 응답 대기(waiting)는 따로 알리므로 끝남으로 치지 않는다. 같은 작업은 이어지지만 기다린 시간은 작업 시간에 넣지 않는다.
76
+ // 상태를 추측한 세션(statusGuessed), 끝난 세션, 하위 에이전트 줄은 알리지 않는다.
77
+ // context: 사용률이 ctxHigh 이상이 되면 한 번 알리고, ctxRearm 아래로 내려가면(압축 등) 다시 알릴 수 있게 한다.
78
+ // 기록을 다 읽기 전(s.loading)의 세션은 기준선만 잡고, 다 읽은 첫 갱신에 이미 높으면 알리지 않는다.
79
+ export const DONE_MS = 3 * 60_000;
80
+ export const SETTLE_MS = 5_000;
81
+ export const CTX_HIGH = 0.9;
82
+ export const CTX_REARM = 0.85;
83
+
84
+ export function createEventWatch({ doneMs = DONE_MS, settleMs = SETTLE_MS, ctxHigh = CTX_HIGH, ctxRearm = CTX_REARM } = {}) {
85
+ return { doneMs, settleMs, ctxHigh, ctxRearm, per: new Map() };
86
+ }
87
+
88
+ const isBusy = (s) => s.status === 'busy' || s.status === 'shell';
89
+ const isSub = (s) => Boolean(s.parentId || s.parent || s.kind === 'subagent');
90
+ const ctxRatio = (s) => (s.context?.window > 0 ? (s.context.used ?? 0) / s.context.window : null);
91
+
92
+ // ready 가 false 면(처음 읽는 중) 상태만 기록하고 알리지 않는다. 돌려주는 값: [{ kind: 'done'|'context', session }]
93
+ export function takeEvents(watch, sessions, { now = Date.now(), ready = true } = {}) {
94
+ const out = [];
95
+ const ids = new Set();
96
+ for (const s of sessions) {
97
+ if (!s.live || s.status === 'ended' || isSub(s)) continue;
98
+ ids.add(s.id);
99
+ let st = watch.per.get(s.id);
100
+ if (!st) watch.per.set(s.id, (st = { run: false, busyMs: 0, busyAt: null, idleSince: null, ctxArmed: true, first: true }));
101
+ const reset = () => Object.assign(st, { run: false, busyMs: 0, busyAt: null, idleSince: null });
102
+
103
+ // done
104
+ if (s.statusGuessed) reset();
105
+ else if (isBusy(s)) {
106
+ st.run = true;
107
+ st.busyAt ??= now;
108
+ st.idleSince = null;
109
+ } else if (s.status === 'idle' && st.run) {
110
+ st.idleSince ??= now;
111
+ if (now - st.idleSince >= watch.settleMs) {
112
+ const worked = st.busyMs + (st.busyAt != null ? st.idleSince - st.busyAt : 0);
113
+ if (ready && worked >= watch.doneMs) out.push({ kind: 'done', session: s });
114
+ reset();
115
+ }
116
+ } else if (s.status === 'waiting' && st.run) {
117
+ // 응답 대기 동안은 작업 시간을 멈춘다.
118
+ if (st.busyAt != null) st.busyMs += (st.idleSince ?? now) - st.busyAt;
119
+ st.busyAt = st.idleSince = null;
120
+ } else reset();
121
+
122
+ // context: 처음 다 읽은 세션이나 준비 전에는 이미 높은 값을 알리지 않는다.
123
+ const r = ctxRatio(s);
124
+ if (r != null) {
125
+ if (r < watch.ctxRearm) st.ctxArmed = true;
126
+ else if (r >= watch.ctxHigh && st.ctxArmed) {
127
+ st.ctxArmed = false;
128
+ if (ready && !st.first && !s.loading) out.push({ kind: 'context', session: s });
129
+ }
130
+ }
131
+ if (!s.loading) st.first = false;
132
+ }
133
+ // 끝났거나 목록에서 빠진 세션은 잊는다 (다시 나타나면 처음부터 센다).
134
+ for (const id of watch.per.keys()) if (!ids.has(id)) watch.per.delete(id);
135
+ return out;
136
+ }
package/src/cache.mjs CHANGED
@@ -3,6 +3,7 @@
3
3
  import { readFileSync, writeFileSync, mkdirSync, renameSync, statSync, readdirSync, rmSync } from 'node:fs';
4
4
  import { join } from 'node:path';
5
5
  import { homedir } from 'node:os';
6
+ import { appDir } from './paths.mjs';
6
7
  import { createHash } from 'node:crypto';
7
8
  import { PRICE_TAG } from './pricing.mjs';
8
9
  import { debug, debugIo } from './log.mjs';
@@ -11,7 +12,8 @@ import { debug, debugIo } from './log.mjs';
11
12
  // 14: 장부의 하루 합계에 모델별 몫(models)을 더하고, 날짜를 10일이 아니라 30일 남긴다 (#128).
12
13
  // 장부(ledger)만 형식이 바뀔 때는 VERSION 대신 장부의 kind 이름을 바꿔 장부만 다시 센다 (세션 화면 캐시는 그대로).
13
14
  const VERSION = 14;
14
- const ROOT = join(process.env.XDG_CACHE_HOME ?? join(homedir(), '.cache'), 'aitop');
15
+ // Windows 는 XDG_CACHE_HOME 이 없으면 %LOCALAPPDATA%\aitop\cache (paths.mjs).
16
+ const ROOT = appDir('cache', { home: homedir() });
15
17
  export const CACHE_ROOT = ROOT;
16
18
  const NAME = `v${VERSION}-${PRICE_TAG}`;
17
19
  const DIR = join(ROOT, NAME);
package/src/config.mjs CHANGED
@@ -1,12 +1,14 @@
1
1
  // 설정: 옵션마다 명령줄 옵션(flag) > 환경 변수(env) > 설정 파일(file) > 기본값(default) 순서로 고른다.
2
2
  // 설정 파일은 $XDG_CONFIG_HOME/aitop/config.json (없으면 ~/.config/aitop/config.json). aitop 은 이 파일을 읽기만 한다.
3
3
  // 잘못된 JSON, 모르는 키, 잘못된 값은 그 키만 무시하고 problems 에 남긴다 (--doctor 와 --print-config 가 보인다).
4
- // 화면 모듈은 불러올 때 테마·아이콘을 고르므로, 이 모듈은 다른 aitop 모듈을 불러오지 않는다.
4
+ // 화면 모듈은 불러올 때 테마·아이콘을 고르므로, 이 모듈은 화면 모듈을 불러오지 않는다 (notify.mjs 는 text·i18n 만 쓴다).
5
5
  import { closeSync, constants, fstatSync, openSync, readSync, statSync } from 'node:fs';
6
6
  import { homedir } from 'node:os';
7
- import { isAbsolute, join } from 'node:path';
7
+ import { posix, win32 } from 'node:path';
8
+ import { appDir } from './paths.mjs';
8
9
  import { stripControl } from './text.mjs';
9
10
  import { langValue, localeLang, t } from './i18n.mjs';
11
+ import { EVENT_KINDS } from './notify.mjs';
10
12
 
11
13
  const bool = (v) => typeof v === 'boolean';
12
14
  const oneOf = (...xs) => (v) => xs.includes(v);
@@ -57,7 +59,10 @@ export const KEYS = {
57
59
  bell: { ok: bool, expect: BOOL, def: false },
58
60
  showRequests: { ok: bool, expect: BOOL, def: false, env: ['AITOP_SHOW_REQUESTS', (v) => (v === '1' ? true : v === '0' ? false : undefined)] },
59
61
  all: { ok: bool, expect: BOOL, def: false },
60
- notify: { ok: bool, expect: BOOL, def: false },
62
+ // notify 는 true/false 또는 알릴 종류 배열 (예: ["waiting", "done", "context"]).
63
+ notify: { ok: (v) => bool(v) || (Array.isArray(v) && v.length > 0 && v.every((x) => EVENT_KINDS.includes(x))), expect: 'cfg.notify', def: false },
64
+ // done 알림을 띄우려면 작업 중이 이어져야 하는 시간(분).
65
+ doneMinutes: { ok: (v) => typeof v === 'number' && Number.isFinite(v) && v > 0, expect: 'cfg.positive', def: 3 },
61
66
  onWaiting: { ok: (v) => typeof v === 'string' && v.trim() !== '', expect: 'cfg.command', def: null },
62
67
  debug: { ok: bool, expect: BOOL, def: false, env: ['AITOP_DEBUG', (v) => (v === '1' ? true : v === '0' ? false : undefined)], envProblem: true, envExpect: ['1', '0'] },
63
68
  budgetDay: { ok: (v) => typeof v === 'number' && Number.isFinite(v) && v > 0, expect: 'cfg.positive', def: null, env: ['AITOP_BUDGET_DAY', (v) => usd(v) ?? undefined], envProblem: true },
@@ -71,9 +76,9 @@ export const KEYS = {
71
76
  lang: { ok: oneOf('ko', 'en'), expect: ['ko', 'en'], def: localeLang, env: ['AITOP_LANG', langValue], envProblem: true },
72
77
  };
73
78
 
74
- export function configPath(env = process.env, home = homedir()) {
75
- const xdg = env.XDG_CONFIG_HOME;
76
- return join(xdg && isAbsolute(xdg) ? xdg : join(home, '.config'), 'aitop', 'config.json');
79
+ // Windows 는 XDG_CONFIG_HOME 이 없으면 %APPDATA%\aitop\config.json.
80
+ export function configPath(env = process.env, home = homedir(), platform = process.platform) {
81
+ return (platform === 'win32' ? win32 : posix).join(appDir('config', { env, home, platform }), 'config.json');
77
82
  }
78
83
 
79
84
  // 설정 파일은 작다. 이보다 크면 읽지 않는다.
@@ -166,7 +171,8 @@ export function resolveConfig({ flags = {}, env = process.env, file } = {}) {
166
171
  export function configText(cfg) {
167
172
  const out = [t('cfg.file', { path: stripControl(cfg.path), state: t(cfg.exists ? 'cfg.exists' : 'cfg.missing') }), ''];
168
173
  for (const [key, { value, source }] of Object.entries(cfg.values)) {
169
- const v = value == null ? (key === 'theme' ? 'auto' : '-') : typeof value === 'string' ? JSON.stringify(value) : String(value);
174
+ // 배열(notify 의 종류)은 waiting,done 처럼 쉼표로 잇는다.
175
+ const v = value == null ? (key === 'theme' ? 'auto' : '-') : typeof value === 'string' ? JSON.stringify(value) : Array.isArray(value) ? value.join(',') : String(value);
170
176
  out.push(`${key.padEnd(14)}${v.padEnd(12)} ${source}`);
171
177
  }
172
178
  if (cfg.problems.length) out.push('', ...cfg.problems.map((p) => `! ${stripControl(p)}`));
package/src/doctor.mjs CHANGED
@@ -1,14 +1,15 @@
1
1
  // 도구별 연결 점검: 기록 폴더를 찾았는지, 기록이 몇 개이고 언제 마지막으로 쓰였는지, 지금 몇 개가 실행 중인지,
2
2
  // 가장 최근 기록을 읽을 수 있는지. aitop --doctor, 빈 화면, --json 의 tools 가 같은 결과를 쓴다.
3
3
  // 기록 내용은 읽어 내보내지 않는다 (Gemini 는 형식 확인용으로 JSON 키 이름만 보인다).
4
- import { readdirSync, statSync, existsSync, openSync, readSync, closeSync } from 'node:fs';
4
+ import { readdirSync, readFileSync, statSync, existsSync, openSync, readSync, closeSync } from 'node:fs';
5
5
  import { join } from 'node:path';
6
6
  import { homedir, platform } from 'node:os';
7
- import { findProcesses, isCodex, isGemini, isAgy, canListProcesses, isAlive } from './procs.mjs';
7
+ import { findProcesses, isCodex, isGemini, isAgy, canListProcesses, isAlive, isSessionAlive } from './procs.mjs';
8
8
  import { AGY_ROOT } from './sources/antigravity.mjs';
9
9
  import { loadSqlite, openReadOnly } from './sqlite.mjs';
10
10
  import { fmtAgo, pad, stripControl } from './text.mjs';
11
11
  import { BRAND } from './brand.mjs';
12
+ import { tildeIn } from './paths.mjs';
12
13
  import { findNotifier, isWsl } from './notify.mjs';
13
14
  import { getLang, t as tr } from './i18n.mjs';
14
15
 
@@ -20,7 +21,8 @@ const CLAUDE = process.env.CLAUDE_CONFIG_DIR ?? join(HOME, '.claude');
20
21
  const CODEX = join(process.env.CODEX_HOME ?? join(HOME, '.codex'), 'sessions');
21
22
  const GEMINI = join(process.env.GEMINI_HOME ?? join(HOME, '.gemini'), 'tmp');
22
23
 
23
- const tilde = (p) => (p.startsWith(HOME + '/') ? '~' + p.slice(HOME.length) : p);
24
+ // Windows 는 \ 와 대소문자를 무시하고 줄인다 (paths.mjs).
25
+ const tilde = (p) => tildeIn(p, HOME);
24
26
  const ls = (dir) => {
25
27
  try {
26
28
  return readdirSync(dir, { withFileTypes: true });
@@ -100,12 +102,22 @@ function topKeys(path) {
100
102
  }
101
103
  }
102
104
 
105
+ // 살아 있는 pid 의 세션 파일만 연다. 대기 프로세스(spare)와 pid 재사용은 세지 않는다.
106
+ function liveSessionFile(path) {
107
+ try {
108
+ const e = JSON.parse(readFileSync(path, 'utf8'));
109
+ return !e.spare && isSessionAlive(e.pid, e.procStart);
110
+ } catch {
111
+ return false;
112
+ }
113
+ }
114
+
103
115
  function claude() {
104
116
  const dir = join(CLAUDE, 'projects');
105
117
  const files = existsSync(dir) ? walk(dir, 1, (n) => n.endsWith('.jsonl')) : null;
106
118
  const last = files && newest(files);
107
119
  const running = canListProcesses()
108
- ? ls(join(CLAUDE, 'sessions')).filter((e) => /^\d+\.json$/.test(e.name) && isAlive(Number(e.name.split('.')[0]))).length
120
+ ? ls(join(CLAUDE, 'sessions')).filter((e) => /^\d+\.json$/.test(e.name) && isAlive(Number(e.name.split('.')[0])) && liveSessionFile(join(CLAUDE, 'sessions', e.name))).length
109
121
  : null;
110
122
  if (!files) return { tool: 'claude', state: 'missing', path: tilde(dir), records: 0, lastAt: null, running, readable: null, hint: null };
111
123
  return { tool: 'claude', state: 'ok', path: tilde(dir), records: files.length, lastAt: last?.mtime ?? null, running, readable: last ? firstLineIsJson(last.path) : null, hint: null };
package/src/help.mjs CHANGED
@@ -90,7 +90,7 @@ export const COMMON = {
90
90
 
91
91
  // 화면 안 도움말의 옵션 묶음. 자세한 설명은 aitop --help. [옵션(값을 받는 옵션은 i18n 키), 설명 i18n 키]
92
92
  const OPTION_IDS = [
93
- ['--notify', 'hopt.notify'],
93
+ ['hopt.notifyOpt', 'hopt.notify'],
94
94
  ['hopt.onWaiting', 'hopt.onWaitingText'],
95
95
  ['hopt.budgetDay', 'hopt.budgetDayText'],
96
96
  ['--show-requests', 'hopt.showRequests'],
@@ -137,5 +137,7 @@ export function settingsLine(s, lang = getLang()) {
137
137
  const o = { lang };
138
138
  const onOff = (v) => t(v ? 'set.on' : 'set.off', null, o);
139
139
  const usd = (x) => (Number.isInteger(x) ? `$${x}` : `$${x.toFixed(2)}`);
140
- return [t('set.budget', { v: s.budgetDay > 0 ? usd(s.budgetDay) : t('set.none', null, o) }, o), t('set.notify', { v: onOff(s.notify) }, o), ...(s.onWaiting ? [t('set.onWaiting', null, o)] : []), t('set.debug', { v: onOff(s.debug) }, o)].join(' · ');
140
+ // 알림이 켜져 있고 종류를 기본(waiting)과 다르게 정했으면 함께 보인다. 예: 알림 켜짐 (waiting,done)
141
+ const kinds = s.notify && s.events && s.events.join(',') !== 'waiting' ? ` (${s.events.join(',')})` : '';
142
+ return [t('set.budget', { v: s.budgetDay > 0 ? usd(s.budgetDay) : t('set.none', null, o) }, o), t('set.notify', { v: onOff(s.notify) + kinds }, o), ...(s.onWaiting ? [t('set.onWaiting', null, o)] : []), t('set.debug', { v: onOff(s.debug) }, o)].join(' · ');
141
143
  }
package/src/i18n.mjs CHANGED
@@ -61,8 +61,9 @@ 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 run 3 $3.1/h)
65
- --line=tmux 는 tmux 색 서식(#[fg=...])을 넣는다. --line-width <N> 폭 상한(기본 40, 넘으면 뒤 항목부터 뺀다)
64
+ aitop --line 오늘 비용·응답 대기(가장 오래 기다린 세션 이름과 대기 시간)·작업 중 수·시간당 지출을 한 줄로 내고 끝낸다
65
+ (tmux 상태줄용, 예: $54.13 wait 2 fix-login 3m run 3 $3.1/h. 하나만 기다리면 wait fix-login 3m)
66
+ --line=tmux 는 tmux 색 서식(#[fg=...])을 넣는다. --line-width <N> 폭 상한(기본 40, 넘으면 뒤 항목부터 빼고 대기 세션 이름은 대기 수보다 먼저 뺀다)
66
67
  캐시만 읽는다. 캐시가 없어 1.5초 안에 못 읽으면 ... 을 낸다. 작업 중 수와 Antigravity 의 대기 수는
67
68
  1분 안에 aitop 화면·--once·--json 이 남긴 요약이 있을 때만 보인다
68
69
  aitop --json 세션 목록과 사용량 합계를 JSON 으로 한 번 출력한다 (--all 과 함께 쓸 수 있다)
@@ -74,8 +75,10 @@ const HELP_KO = `{logo} aitop - 터미널에서 Claude Code · Codex · Antigrav
74
75
  aitop --doctor Claude · Codex · Antigravity · Gemini 기록과 실행 중인 프로세스, 설정 파일을 점검한다 (--json 과 함께 쓸 수 있다)
75
76
  aitop --bell 응답 대기 세션이 새로 생기면 터미널 벨을 울린다
76
77
  aitop --notify 응답 대기 세션이 새로 생기면 데스크톱 알림을 띄운다 (notify-send · osascript, 없으면 건너뜀)
77
- aitop --on-waiting <명령> 응답 대기 세션이 새로 생기면 /bin/sh -c 로 명령을 실행한다 (내 권한으로 실행, 10초 제한)
78
- 세션 정보는 환경변수로만: AITOP_TOOL AITOP_PROJECT AITOP_SESSION_ID AITOP_CWD AITOP_WAITING_FOR
78
+ aitop --notify=waiting,done,context 알릴 종류를 고른다 (--notify 만 주면 설정 파일 notify 배열, 없으면 waiting). done: 3분(설정 파일 doneMinutes, 응답 대기 시간 빼고) 넘게 작업하던 세션이 다음 지시를
79
+ 기다리면 한 번. context: 컨텍스트가 90% 를 넘으면 한 번 (85% 아래로 내려가면 다시)
80
+ aitop --on-waiting <명령> 알릴 일이 생기면 /bin/sh -c 로 명령을 실행한다 (내 권한으로 실행, 10초 제한). 종류는 --notify 를 따른다 (--no-notify 여도)
81
+ 세션 정보는 환경변수로만: AITOP_EVENT(waiting|done|context) AITOP_TOOL AITOP_PROJECT AITOP_SESSION_ID AITOP_CWD AITOP_WAITING_FOR
79
82
  aitop --show-requests 응답 대기 요청 전체를 상세 패널·--json 에 보인다 (AITOP_SHOW_REQUESTS=1). 비밀값 가림은 최선일 뿐이라 명령 속 비밀값이 보일 수 있다
80
83
  aitop --budget-day <달러> 하루 예산. 헤더에 오늘 $12.30/$50 처럼 보이고, 오늘 끝 예상 비용(오늘 + 최근 속도 × 자정까지, 늘 API 환산)이
81
84
  80% 를 넘으면 '예상 $45', 100% 를 넘으면 '예상 $60!' 로 알린다 (AITOP_BUDGET_DAY, 설정 파일 budgetDay)
@@ -93,6 +96,7 @@ const HELP_KO = `{logo} aitop - 터미널에서 Claude Code · Codex · Antigrav
93
96
 
94
97
  설정 파일: {configPath}
95
98
  예) { "theme": "light", "icons": "plain", "bell": true, "notify": true, "onWaiting": "say 대기", "budgetDay": 50, "ambiguous": "wide", "hideIdleTools": false }
99
+ notify 에 ["waiting", "done", "context"] 처럼 종류를 주면 그 종류만 알린다. doneMinutes: done 알림 기준 작업 시간(분, 기본 3)
96
100
  hideIdleTools: 실행 중 세션이 없고 7일 동안 쓰지 않은 도구를 헤더 아래 도구 줄에서 숨긴다 (기본 true, false 면 늘 셋 다)
97
101
  onWaiting 은 파일 소유자가 나이고 그룹·다른 사용자가 쓸 수 없을 때(chmod 600)만 받는다.
98
102
  옵션 > 환경 변수 > 설정 파일 순서로 정한다. 잘못된 값은 무시하고 --doctor 에 알린다.
@@ -105,8 +109,9 @@ const HELP_EN = `{logo} aitop - watch Claude Code, Codex, Antigravity and Gemini
105
109
  aitop live screen
106
110
  aitop --once print the current state once and exit
107
111
  aitop --all also show sessions that ended in the last 24 hours
108
- 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)
109
- --line=tmux adds tmux colors (#[fg=...]). --line-width <N> sets the max width (default 40, drops items from the end)
112
+ aitop --line print today's cost, waiting sessions (the longest waiting one's name and wait time), running count and spend per hour on one line
113
+ and exit (for tmux, e.g. $54.13 wait 2 fix-login 3m run 3 $3.1/h; with one waiting: wait fix-login 3m)
114
+ --line=tmux adds tmux colors (#[fg=...]). --line-width <N> sets the max width (default 40, drops items from the end, the waiting name before its count)
110
115
  Reads only the cache. With no cache it prints ... after 1.5 seconds. The running count and waiting Antigravity sessions
111
116
  show only when the live screen, --once or --json left a summary in the last minute
112
117
  aitop --json print the session list and usage totals as JSON once (works with --all)
@@ -119,8 +124,10 @@ const HELP_EN = `{logo} aitop - watch Claude Code, Codex, Antigravity and Gemini
119
124
  aitop --doctor check Claude, Codex, Antigravity and Gemini logs, running processes and the config file (works with --json)
120
125
  aitop --bell ring the terminal bell when a session starts waiting for you
121
126
  aitop --notify show a desktop notification when a session starts waiting (notify-send or osascript, skipped if missing)
122
- aitop --on-waiting <cmd> run a command with /bin/sh -c when a session starts waiting (runs as you, 10 second limit)
123
- Session info is passed only in env vars: AITOP_TOOL AITOP_PROJECT AITOP_SESSION_ID AITOP_CWD AITOP_WAITING_FOR
127
+ aitop --notify=waiting,done,context pick what to notify about (plain --notify: the config notify list, else waiting). done: once when a session that worked for
128
+ over 3 minutes (config doneMinutes, approval waits not counted) waits for its next instruction. context: once when context passes 90% (again after it drops below 85%)
129
+ aitop --on-waiting <cmd> run a command with /bin/sh -c when there is something to notify (runs as you, 10 second limit). Follows the --notify kinds (even with --no-notify)
130
+ Session info is passed only in env vars: AITOP_EVENT(waiting|done|context) AITOP_TOOL AITOP_PROJECT AITOP_SESSION_ID AITOP_CWD AITOP_WAITING_FOR
124
131
  aitop --show-requests show full waiting requests in the detail panel and --json (AITOP_SHOW_REQUESTS=1). Secret masking is best effort, so secrets in commands may show
125
132
  aitop --budget-day <usd> daily budget. The header shows today $12.30/$50, and it warns when the projected end-of-day cost (today + recent rate until midnight, always API cost)
126
133
  passes 80%, and in the warning color with ! past 100% (AITOP_BUDGET_DAY, config budgetDay)
@@ -138,6 +145,7 @@ const HELP_EN = `{logo} aitop - watch Claude Code, Codex, Antigravity and Gemini
138
145
 
139
146
  Config file: {configPath}
140
147
  e.g. { "theme": "light", "icons": "plain", "bell": true, "notify": true, "onWaiting": "say waiting", "budgetDay": 50, "ambiguous": "wide", "hideIdleTools": false, "lang": "en" }
148
+ notify can also be a list like ["waiting", "done", "context"] to pick the kinds. doneMinutes: busy time (minutes, default 3) before a done notice
141
149
  hideIdleTools: hide tools with no running session and no use in 7 days from the tool line under the header (default true, false always shows all)
142
150
  onWaiting is accepted only when you own the file and no group or other user can write it (chmod 600).
143
151
  Order: option > env var > config file. Bad values are ignored and reported by --doctor.
@@ -196,6 +204,7 @@ export const STRINGS = {
196
204
  'opt.budgetMissing': '--budget-day 값이 없습니다 (하루 예산, 달러)',
197
205
  'opt.budgetBad': '--budget-day 값 {value} 이 잘못되었습니다 (0 보다 큰 수)',
198
206
  'opt.onWaitingMissing': '--on-waiting 값이 없습니다 (실행할 명령)',
207
+ 'opt.notifyBad': '--notify={value} 를 알 수 없습니다. 쉼표로 이은 {kinds} 중에서 고른다',
199
208
  'opt.onWaitingDash': "--on-waiting 값이 - 로 시작합니다 ({value}). 명령이 맞으면 --on-waiting='{value}' 처럼 = 로 붙여 쓴다",
200
209
  'opt.lineBad': '--line 값 {value} 이 잘못되었습니다 (plain 또는 tmux)',
201
210
  'opt.lineWidthMissing': '--line-width 값이 없습니다 (글자 수)',
@@ -247,6 +256,7 @@ export const STRINGS = {
247
256
  'cfg.shared': '그룹·다른 사용자가 쓸 수 있음 (mode {mode})',
248
257
  'cfg.either': '{a} 또는 {b}',
249
258
  'cfg.command': '실행할 명령 문자열',
259
+ 'cfg.notify': 'true, false 또는 waiting·done·context 배열',
250
260
  'cfg.positive': '0 보다 큰 수',
251
261
  'cfg.file': '설정 파일: {path} ({state})',
252
262
  'cfg.exists': '있음',
@@ -270,7 +280,7 @@ export const STRINGS = {
270
280
  'doctor.hint.agyMissing': 'agy 를 한 번 실행하면 생깁니다 (Gemini 탭에 보입니다)',
271
281
  'doctor.hint.gemini': '프로세스만 감지합니다 (세션·토큰은 아직 지원하지 않음)',
272
282
  'doctor.hint.agyNode': 'Node {node} 에서는 기록을 읽기 전용으로 열 수 없어 프로세스만 감지합니다 (Node 22.15 이상 필요)',
273
- 'doctor.notifier': '✓ 알림 {kind} ({path}) · --notify 로 켬',
283
+ 'doctor.notifier': '✓ 알림 {kind} ({path}) · --notify 로 켬 (끝남·context 경고는 --notify=waiting,done,context)',
274
284
  'doctor.noNotifier': '○ 알림 {want} 없음 · --notify 를 켜도 알림을 건너뜀{wsl}',
275
285
  'doctor.wsl': ' (WSL 은 notify-send 만 쓴다)',
276
286
  'doctor.config': '{mark} 설정 {state}{path}',
@@ -428,9 +438,10 @@ export const STRINGS = {
428
438
 
429
439
  // 화면 안 도움말의 옵션 묶음 (help.mjs 의 OPTIONS). 값이 있는 옵션은 이름도 언어마다 다르다.
430
440
  'hopt.onWaiting': '--on-waiting <명령>',
441
+ 'hopt.notifyOpt': '--notify[=종류]',
431
442
  'hopt.budgetDay': '--budget-day <달러>',
432
- 'hopt.notify': '응답 대기가 생기면 데스크톱 알림',
433
- 'hopt.onWaitingText': '응답 대기가 생기면 명령 실행',
443
+ 'hopt.notify': '응답 대기(·작업 끝남·context 90%)에 데스크톱 알림',
444
+ 'hopt.onWaitingText': '알릴 일이 생기면 명령 실행 (AITOP_EVENT)',
434
445
  'hopt.budgetDayText': '하루 예산. 헤더에 예상 비용 경고',
435
446
  'hopt.showRequests': '응답 대기 요청 전체를 상세·--json 에',
436
447
  'hopt.colorBlind': '적록 색약용 색 (대기·돈·경고를 노랑·파랑 계열로)',
@@ -501,6 +512,12 @@ export const STRINGS = {
501
512
  'notify.one': 'aitop: 응답 대기 ({tool})',
502
513
  'notify.title': 'aitop: 응답 대기',
503
514
  'notify.many': '{n}개 세션이 응답을 기다립니다',
515
+ 'notify.done.one': 'aitop: 작업 끝남 ({tool})',
516
+ 'notify.done.title': 'aitop: 작업 끝남',
517
+ 'notify.done.many': '{n}개 세션이 다음 지시를 기다립니다',
518
+ 'notify.context.one': 'aitop: context 90% 넘음 ({tool})',
519
+ 'notify.context.title': 'aitop: context 90% 넘음',
520
+ 'notify.context.many': '{n}개 세션의 context 가 90% 를 넘었습니다',
504
521
  // Antigravity 소스가 요청 이름을 모를 때 넣는 대기 사유. --json 에는 이 한국어 그대로 나가고 화면에서만 바꾼다.
505
522
  'phase.approve': '도구 허락',
506
523
  },
@@ -553,6 +570,7 @@ export const STRINGS = {
553
570
  'opt.budgetMissing': '--budget-day needs a value (daily budget in USD)',
554
571
  'opt.budgetBad': 'bad --budget-day value {value} (a number above 0)',
555
572
  'opt.onWaitingMissing': '--on-waiting needs a value (a command to run)',
573
+ 'opt.notifyBad': 'unknown --notify={value}. Use a comma separated list of {kinds}',
556
574
  'opt.onWaitingDash': "--on-waiting value starts with - ({value}). If it is the command, attach it with =, like --on-waiting='{value}'",
557
575
  'opt.lineBad': 'bad --line value {value} (plain or tmux)',
558
576
  'opt.lineWidthMissing': '--line-width needs a value (characters)',
@@ -603,6 +621,7 @@ export const STRINGS = {
603
621
  'cfg.shared': 'group or other users can write it (mode {mode})',
604
622
  'cfg.either': '{a} or {b}',
605
623
  'cfg.command': 'a command string',
624
+ 'cfg.notify': 'true, false or a list of waiting, done, context',
606
625
  'cfg.positive': 'a number above 0',
607
626
  'cfg.file': 'Config file: {path} ({state})',
608
627
  'cfg.exists': 'found',
@@ -626,7 +645,7 @@ export const STRINGS = {
626
645
  'doctor.hint.agyMissing': 'created after you run agy once (shown in the Gemini tab)',
627
646
  'doctor.hint.gemini': 'detects processes only (sessions and tokens not supported yet)',
628
647
  'doctor.hint.agyNode': 'Node {node} cannot open the logs read-only, so only processes are detected (needs Node 22.15 or later)',
629
- 'doctor.notifier': '✓ notify {kind} ({path}) · turn on with --notify',
648
+ 'doctor.notifier': '✓ notify {kind} ({path}) · turn on with --notify (done and context alerts: --notify=waiting,done,context)',
630
649
  'doctor.noNotifier': '○ notify {want} not found · --notify will skip notifications{wsl}',
631
650
  'doctor.wsl': ' (WSL uses notify-send only)',
632
651
  'doctor.config': '{mark} config {state}{path}',
@@ -780,9 +799,10 @@ export const STRINGS = {
780
799
  'hk.common.quit': 'Quit',
781
800
 
782
801
  'hopt.onWaiting': '--on-waiting <cmd>',
802
+ 'hopt.notifyOpt': '--notify[=kinds]',
783
803
  'hopt.budgetDay': '--budget-day <usd>',
784
- 'hopt.notify': 'Desktop alert when a session waits',
785
- 'hopt.onWaitingText': 'Run a command when a session waits',
804
+ 'hopt.notify': 'Desktop alert on waiting (or done, context 90%)',
805
+ 'hopt.onWaitingText': 'Run a command on alerts (AITOP_EVENT)',
786
806
  'hopt.budgetDayText': 'Daily budget, warns in the header',
787
807
  'hopt.showRequests': 'Show full waiting requests',
788
808
  'hopt.colorBlind': 'Red-green color blind palette',
@@ -851,6 +871,12 @@ export const STRINGS = {
851
871
  'notify.one': 'aitop: waiting ({tool})',
852
872
  'notify.title': 'aitop: waiting',
853
873
  'notify.many': { one: '{n} session is waiting for you', other: '{n} sessions are waiting for you' },
874
+ 'notify.done.one': 'aitop: done ({tool})',
875
+ 'notify.done.title': 'aitop: done',
876
+ 'notify.done.many': { one: '{n} session finished its work', other: '{n} sessions finished their work' },
877
+ 'notify.context.one': 'aitop: context over 90% ({tool})',
878
+ 'notify.context.title': 'aitop: context over 90%',
879
+ 'notify.context.many': { one: '{n} session passed 90% context', other: '{n} sessions passed 90% context' },
854
880
  'phase.approve': 'Approve tool',
855
881
  },
856
882
  };