@sejuneoh/aitop 0.28.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
@@ -33,7 +33,7 @@ aitop live screen
33
33
  aitop --all include sessions that ended in the last 24 hours
34
34
  aitop --json print a snapshot as JSON and exit
35
35
  aitop --doctor check which tools and logs aitop can see
36
- 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)
37
37
  aitop --report daily daily cost table and exit
38
38
  aitop --report monthly monthly cost table (last 12 months) and exit
39
39
  aitop --help all options
@@ -59,9 +59,27 @@ aitop --report daily --by project --days 7
59
59
  aitop --report monthly --by model --months 6
60
60
  ```
61
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
+
62
78
  ### tmux status line
63
79
 
64
- `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.
65
83
 
66
84
  ```tmux
67
85
  set -g status-right '#(aitop --line=tmux)'
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.28.0",
3
+ "version": "0.29.0",
4
4
  "description": "터미널에서 Claude Code · Codex · Antigravity · Gemini 세션과 토큰을 실시간으로 보는 읽기 전용 모니터",
5
5
  "license": "MIT",
6
6
  "type": "module",
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/config.mjs CHANGED
@@ -1,13 +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
7
  import { posix, win32 } from 'node:path';
8
8
  import { appDir } from './paths.mjs';
9
9
  import { stripControl } from './text.mjs';
10
10
  import { langValue, localeLang, t } from './i18n.mjs';
11
+ import { EVENT_KINDS } from './notify.mjs';
11
12
 
12
13
  const bool = (v) => typeof v === 'boolean';
13
14
  const oneOf = (...xs) => (v) => xs.includes(v);
@@ -58,7 +59,10 @@ export const KEYS = {
58
59
  bell: { ok: bool, expect: BOOL, def: false },
59
60
  showRequests: { ok: bool, expect: BOOL, def: false, env: ['AITOP_SHOW_REQUESTS', (v) => (v === '1' ? true : v === '0' ? false : undefined)] },
60
61
  all: { ok: bool, expect: BOOL, def: false },
61
- 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 },
62
66
  onWaiting: { ok: (v) => typeof v === 'string' && v.trim() !== '', expect: 'cfg.command', def: null },
63
67
  debug: { ok: bool, expect: BOOL, def: false, env: ['AITOP_DEBUG', (v) => (v === '1' ? true : v === '0' ? false : undefined)], envProblem: true, envExpect: ['1', '0'] },
64
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 },
@@ -167,7 +171,8 @@ export function resolveConfig({ flags = {}, env = process.env, file } = {}) {
167
171
  export function configText(cfg) {
168
172
  const out = [t('cfg.file', { path: stripControl(cfg.path), state: t(cfg.exists ? 'cfg.exists' : 'cfg.missing') }), ''];
169
173
  for (const [key, { value, source }] of Object.entries(cfg.values)) {
170
- 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);
171
176
  out.push(`${key.padEnd(14)}${v.padEnd(12)} ${source}`);
172
177
  }
173
178
  if (cfg.problems.length) out.push('', ...cfg.problems.map((p) => `! ${stripControl(p)}`));
package/src/doctor.mjs CHANGED
@@ -1,10 +1,10 @@
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';
@@ -102,12 +102,22 @@ function topKeys(path) {
102
102
  }
103
103
  }
104
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
+
105
115
  function claude() {
106
116
  const dir = join(CLAUDE, 'projects');
107
117
  const files = existsSync(dir) ? walk(dir, 1, (n) => n.endsWith('.jsonl')) : null;
108
118
  const last = files && newest(files);
109
119
  const running = canListProcesses()
110
- ? 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
111
121
  : null;
112
122
  if (!files) return { tool: 'claude', state: 'missing', path: tilde(dir), records: 0, lastAt: null, running, readable: null, hint: null };
113
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
  };
package/src/line.mjs CHANGED
@@ -1,8 +1,10 @@
1
- // aitop --line: tmux 상태줄 같은 곳에 넣을 한 줄 요약. 예) $54.13/$50 wait 2 run 3 $3.1/h
1
+ // aitop --line: tmux 상태줄 같은 곳에 넣을 한 줄 요약. 예) $54.13/$50 wait 2 gemini-gen 2m run 3 $3.1/h
2
2
  // 글자는 ASCII 만 쓴다 (이모지·폭이 모호한 기호는 tmux 에서 칸이 어긋난다). 표기는 짧은 영어 약어로 고정하고 번역하지 않는다.
3
+ // 예외는 세션 이름 속 한글·한자·가나뿐이다 (늘 2칸이라 어긋나지 않는다). 그 밖의 글자는 이름에서 지운다.
3
4
  // 색은 --line=tmux 일 때 tmux 서식(#[fg=colourN])으로만 넣고 ANSI 코드는 쓰지 않는다. NO_COLOR 면 서식도 넣지 않는다.
4
5
  // 옵션 오류 문구만 i18n 으로 지금 언어를 따른다.
5
6
  import { t } from './i18n.mjs';
7
+ import { fmtAgo, stripControl, truncate, width } from './text.mjs';
6
8
 
7
9
  export const MODES = ['plain', 'tmux'];
8
10
  export const DEFAULT_WIDTH = 40;
@@ -10,6 +12,10 @@ export const DEFAULT_WIDTH = 40;
10
12
  export const CAP_MS = 1500;
11
13
  // 캐시가 없거나 시간 상한을 넘었을 때 내는 글.
12
14
  export const PENDING = '...';
15
+ // 기다리는 세션 이름의 최대 폭 (칸). 기본 폭 40 에 오늘 비용·예산·대기(이름과 시간)·작업 중이 함께 들어가는 길이.
16
+ export const NAME_WIDTH = 12;
17
+ // 이름을 자른 자리 표시. … 는 ASCII 가 아니다.
18
+ const CUT = '~';
13
19
 
14
20
  // tmux 256색 번호. 응답 대기는 눈에 띄는 주황, 돈은 화면 헤더와 같은 연두. 색약용은 노랑·파랑 계열로 가른다.
15
21
  // 작업 중은 눈에 덜 띄는 회색 계열로 둔다 (주목할 것은 대기다).
@@ -51,29 +57,68 @@ const rate = (x) => (x >= 100 ? `$${x.toFixed(0)}` : x >= 1 ? `$${x.toFixed(1)}`
51
57
  // 표시하면 0 으로 보이는 값은 0 으로 본다.
52
58
  const zero = (x) => !(Number(x) >= 0.005);
53
59
 
60
+ // 이름에 남겨 둘 글자: 보이는 ASCII, 한글, 한자, 가나. 나머지(제어 문자·이모지·폭이 모호한 기호)는 공백으로 바꾼다.
61
+ const KEEP = /[\x20-\x7e\u1100-\u115f\u3041-\u30ff\u3131-\u318e\u3400-\u4dbf\u4e00-\u9fff\uac00-\ud7a3]/u;
62
+
63
+ // 상태줄에 넣을 세션 이름: 제어 문자와 색 순서를 지우고, 쓸 수 없는 글자를 빼고, 공백을 하나로 줄여 NAME_WIDTH 칸으로 자른다.
64
+ export function lineName(s, max = NAME_WIDTH) {
65
+ // 터미널 순서는 ESC 만 지우면 [31m 같은 꼬리가 남으므로 통째로 지운다: CSI(ESC [ ... 끝 글자), OSC(ESC ] ... BEL 또는 ESC \).
66
+ const bare = String(s ?? '')
67
+ .replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\|$)/g, '')
68
+ .replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '');
69
+ const kept = [...stripControl(bare)].map((ch) => (KEEP.test(ch) ? ch : ' ')).join('').replace(/\s+/g, ' ').trim();
70
+ return truncate(kept, max, CUT);
71
+ }
72
+
73
+ // 응답 대기 항목의 글: [이름과 대기 시간까지 넣은 글, 수만 넣은 글]. 폭이 모자라면 이름부터 뺀다.
74
+ // 하나만 기다리면 수 대신 이름을 쓴다 (wait gemini-gen 2m). 둘 이상이면 수 뒤에 가장 오래 기다린 세션 (wait 3 gemini-gen 2m).
75
+ function waitTexts(waiting, longest, now) {
76
+ const count = `wait ${waiting}`;
77
+ const name = longest ? lineName(longest.name) : '';
78
+ if (!name) return [count];
79
+ const age = Number.isFinite(longest.since) ? ` ${fmtAgo(now - longest.since)}` : '';
80
+ return [`${waiting === 1 ? 'wait' : count} ${name}${age}`, count];
81
+ }
82
+
54
83
  // 값: today(오늘 비용, API 정가 환산), budgetDay(하루 예산, 없으면 null), waiting(응답 대기 수),
55
- // running(작업 중 수, 요약이 없거나 오래됐으면 null), perHour(최근 1시간 지출).
84
+ // longest(가장 오래 기다린 세션 { name, since }, 모르면 null), running(작업 중 수, 요약이 없거나 오래됐으면 null), perHour(최근 1시간 지출).
56
85
  // 0 인 항목은 뺀다. 오늘 비용이 0 이어도 예산이 있으면 $0.00/$50 으로 보인다.
57
- // width 를 넘으면 뒤 항목부터 뺀다. mode 가 tmux 이고 noColor 가 아니면 항목마다 tmux 서식을 씌운다.
58
- export function formatLine({ today = 0, budgetDay = null, waiting = 0, running = null, perHour = 0 } = {}, { mode = 'plain', noColor = false, width = DEFAULT_WIDTH, colorBlind = false } = {}) {
86
+ // width 를 넘으면 뒤 항목부터 줄인다: 시간당 지출, 작업 중, 대기 세션 이름, 대기 수, 오늘 비용 차례.
87
+ // mode 가 tmux 이고 noColor 가 아니면 항목마다 tmux 서식을 씌운다. tmux 모드에서는 이름 속 # 을 ## 로 바꿔 서식으로 읽히지 않게 한다.
88
+ export function formatLine({ today = 0, budgetDay = null, waiting = 0, longest = null, running = null, perHour = 0 } = {}, { mode = 'plain', noColor = false, width: max = DEFAULT_WIDTH, colorBlind = false, now = Date.now() } = {}) {
59
89
  const c = COLOURS[colorBlind ? 'colorBlind' : 'normal'];
90
+ // texts: 긴 글부터. 폭이 모자라면 다음 글로 줄이고, 마지막 글도 넘으면 항목을 뺀다.
60
91
  const parts = [];
61
92
  const hasBudget = typeof budgetDay === 'number' && budgetDay > 0;
62
- if (!zero(today) || hasBudget) parts.push({ text: `${money(zero(today) ? 0 : today)}${hasBudget ? `/${budgetText(budgetDay)}` : ''}`, fg: c.money });
63
- if (waiting > 0) parts.push({ text: `wait ${waiting}`, fg: c.waiting });
64
- if (running > 0) parts.push({ text: `run ${running}`, fg: c.running });
65
- if (!zero(perHour)) parts.push({ text: `${rate(perHour)}/h`, fg: c.money });
66
- while (parts.length && parts.map((p) => p.text).join(' ').length > width) parts.pop();
67
- const styled = mode === 'tmux' && !noColor;
68
- return parts.map((p) => (styled ? `#[fg=${p.fg}]${p.text}#[default]` : p.text)).join(' ');
93
+ if (!zero(today) || hasBudget) parts.push({ texts: [`${money(zero(today) ? 0 : today)}${hasBudget ? `/${budgetText(budgetDay)}` : ''}`], fg: c.money });
94
+ if (waiting > 0) parts.push({ texts: waitTexts(waiting, longest, now), fg: c.waiting });
95
+ if (running > 0) parts.push({ texts: [`run ${running}`], fg: c.running });
96
+ if (!zero(perHour)) parts.push({ texts: [`${rate(perHour)}/h`], fg: c.money });
97
+ while (parts.length && width(parts.map((p) => p.texts[0]).join(' ')) > max) {
98
+ if (parts.at(-1).texts.length > 1) parts.at(-1).texts.shift();
99
+ else parts.pop();
100
+ }
101
+ const tmux = mode === 'tmux';
102
+ const styled = tmux && !noColor;
103
+ return parts
104
+ .map((p) => {
105
+ const text = tmux ? p.texts[0].replaceAll('#', '##') : p.texts[0];
106
+ return styled ? `#[fg=${p.fg}]${text}#[default]` : text;
107
+ })
108
+ .join(' ');
69
109
  }
70
110
 
71
- // 요약 파일(summary.mjs)에서 작업 중 수와 응답 대기 수를 고른다. claudeWaiting 은 세션 파일에서 지금 센 Claude 대기 수.
111
+ // 요약 파일(summary.mjs)에서 작업 중 수와 응답 대기 수를 고른다. claudeWaiting 은 세션 파일에서 지금 찾은 Claude 대기 세션 [{ name, since }].
72
112
  // 대기는 Claude 몫을 늘 지금 값으로 쓰고(요약은 최대 1분 늦다), 다른 도구 몫(지금은 Antigravity)만 요약에서 더한다. 요약이 없으면 Claude 몫만.
113
+ // longest 는 둘을 합쳐 대기 시작이 가장 이른 세션. 요약이 오래돼 버려지면 다른 도구 몫은 수도 이름도 뺀다.
73
114
  // 작업 중은 요약에만 있으므로 요약이 없거나 오래됐으면 null (줄에서 뺀다).
74
- export function pickCounts(summary, claudeWaiting) {
75
- if (!summary) return { waiting: claudeWaiting, running: null };
76
- return { waiting: claudeWaiting + summary.waitingOther, running: summary.running };
115
+ export function pickCounts(summary, claudeWaiting = []) {
116
+ const list = [...claudeWaiting, ...(summary?.waitTop ?? [])];
117
+ const at = (w) => (Number.isFinite(w.since) ? w.since : Number.MAX_SAFE_INTEGER);
118
+ const top = list.toSorted((x, y) => at(x) - at(y))[0];
119
+ const pick = top ? { name: top.name, since: top.since } : null;
120
+ if (!summary) return { waiting: claudeWaiting.length, longest: pick, running: null };
121
+ return { waiting: claudeWaiting.length + summary.waitingOther, longest: pick, running: summary.running };
77
122
  }
78
123
 
79
124
  // 장부 캐시와 새로 붙은 줄, 요약 파일만 읽어 값을 모은다 (세션 화면용 기록 전체·프로세스 목록은 읽지 않는다).
@@ -81,10 +126,10 @@ export function pickCounts(summary, claudeWaiting) {
81
126
  export async function collectLine({ capMs = CAP_MS, now = Date.now() } = {}) {
82
127
  const { createBudget } = await import('./tail.mjs');
83
128
  const { collectLedger } = await import('./sources/claude-ledger.mjs');
84
- const { claudeWaitingCount } = await import('./sources/claude.mjs');
129
+ const { claudeWaiting } = await import('./sources/claude.mjs');
85
130
  const { readSummary } = await import('./summary.mjs');
86
131
  const budget = createBudget(Infinity, capMs);
87
132
  const usage = collectLedger({ budget, now });
88
133
  if (budget.exhausted || usage.loading != null) return null;
89
- return { today: usage.today.cost, ...pickCounts(readSummary({ now }), claudeWaitingCount()), perHour: usage.lastHour.cost };
134
+ return { today: usage.today.cost, ...pickCounts(readSummary({ now }), claudeWaiting()), perHour: usage.lastHour.cost };
90
135
  }
package/src/notify.mjs CHANGED
@@ -1,4 +1,4 @@
1
- // 응답 대기 알림: --notify (데스크톱 알림), --on-waiting <명령> (사용자 명령 실행).
1
+ // 알림: --notify[=종류] (데스크톱 알림), --on-waiting <명령> (사용자 명령 실행). 종류는 waiting(기본)·done·context.
2
2
  // 세션 정보는 명령 문자열에 넣지 않는다. 알림 도구에는 인자로, 사용자 명령에는 AITOP_* 환경변수로만 넘긴다.
3
3
  import { spawn } from 'node:child_process';
4
4
  import { accessSync, constants, readFileSync } from 'node:fs';
@@ -13,8 +13,25 @@ const LABEL_MAX = 120;
13
13
  // argv 에서 --notify, --no-notify, --on-waiting <cmd>, --on-waiting=<cmd>, --no-on-waiting 을 꺼내고 나머지는 rest 로 돌려준다.
14
14
  // 값을 따로 받는 다른 옵션(valueOpts)의 값은 건드리지 않고 그대로 넘긴다 (그 옵션의 해석과 같게 - 로 시작하지 않는 다음 인자).
15
15
  export const VALUE_OPTS = ['--theme'];
16
+ // 알림 종류. --notify 만 주면 예전처럼 waiting 만 알린다 (#204).
17
+ export const EVENT_KINDS = ['waiting', 'done', 'context'];
18
+ export const DEFAULT_EVENTS = ['waiting'];
19
+
20
+ // 'waiting,done' 같은 글이나 배열을 종류 목록으로. 모르는 종류나 빈 목록이면 null.
21
+ export function parseEvents(v) {
22
+ const list = Array.isArray(v) ? v : typeof v === 'string' ? v.split(',') : null;
23
+ if (!list) return null;
24
+ const out = [...new Set(list.map((x) => (typeof x === 'string' ? x.trim() : x)).filter((x) => x !== ''))];
25
+ return out.length && out.every((x) => EVENT_KINDS.includes(x)) ? out : null;
26
+ }
27
+
28
+ // events: 알릴 종류 (데스크톱 알림과 --on-waiting 명령에 함께 쓴다). eventsSet: 명령줄 --notify=<종류> 로 정했는지.
29
+ // config.notify 는 true/false 또는 종류 배열(켜고 종류를 정함)이다.
16
30
  export function notifyOptions(argv, config = {}, valueOpts = VALUE_OPTS) {
17
- let notify = config.notify === true;
31
+ const cfgEvents = Array.isArray(config.notify) ? parseEvents(config.notify) : null;
32
+ let notify = config.notify === true || cfgEvents != null;
33
+ let events = cfgEvents ?? DEFAULT_EVENTS;
34
+ let eventsSet = false;
18
35
  let onWaiting = typeof config.onWaiting === 'string' && config.onWaiting.trim() ? config.onWaiting : null;
19
36
  let error = null;
20
37
  const rest = [];
@@ -29,6 +46,16 @@ export function notifyOptions(argv, config = {}, valueOpts = VALUE_OPTS) {
29
46
  notify = true;
30
47
  continue;
31
48
  }
49
+ if (a.startsWith('--notify=')) {
50
+ const v = parseEvents(a.slice('--notify='.length));
51
+ if (!v) error = t('opt.notifyBad', { value: a.slice('--notify='.length), kinds: EVENT_KINDS.join(',') });
52
+ else {
53
+ notify = true;
54
+ events = v;
55
+ eventsSet = true;
56
+ }
57
+ continue;
58
+ }
32
59
  if (a === '--no-notify') {
33
60
  notify = false;
34
61
  continue;
@@ -47,7 +74,7 @@ export function notifyOptions(argv, config = {}, valueOpts = VALUE_OPTS) {
47
74
  else if (m[1] == null && v.startsWith('-')) error = t('opt.onWaitingDash', { value: v });
48
75
  else onWaiting = v;
49
76
  }
50
- return { notify, onWaiting, rest, error };
77
+ return { notify, events, eventsSet, onWaiting, rest, error };
51
78
  }
52
79
 
53
80
  function executable(path) {
@@ -125,8 +152,15 @@ export function waitingEnv(s) {
125
152
  }
126
153
 
127
154
  // 알림 제목·본문은 화면 언어를 따른다 (AITOP_WAITING_FOR 와 달리 사람이 읽는 글이라).
128
- export function notifyText(sessions, lang = getLang()) {
155
+ // kind 가 done·context 면 그 종류의 문구를 쓴다. context 본문에는 사용률(%)을 붙인다.
156
+ export function notifyText(sessions, lang = getLang(), kind = 'waiting') {
129
157
  const o = { lang };
158
+ if (kind !== 'waiting') {
159
+ if (sessions.length !== 1) return { title: t(`notify.${kind}.title`, null, o), body: t(`notify.${kind}.many`, { n: sessions.length }, o) };
160
+ const s = sessions[0];
161
+ const pct = s.context?.window > 0 ? ` · ${Math.round(((s.context.used ?? 0) / s.context.window) * 100)}%` : '';
162
+ return { title: t(`notify.${kind}.one`, { tool: s.tool ?? '?' }, o), body: stripControl(`${s.project ?? s.id ?? ''}${kind === 'context' ? pct : ''}`) };
163
+ }
130
164
  if (sessions.length === 1) {
131
165
  const s = sessions[0];
132
166
  const label = waitingLabel(s, lang);
@@ -234,7 +268,8 @@ export function createRunner({ timeoutMs = HOOK_TIMEOUT_MS, spawnFn = spawn } =
234
268
  };
235
269
  }
236
270
 
237
- // --notify, --on-waiting 을 묶은 알리미. 새로 응답 대기가 된 세션 목록을 받는다.
271
+ // --notify, --on-waiting 을 묶은 알리미. 알릴 세션 목록과 종류(waiting·done·context)를 받는다.
272
+ // --on-waiting 명령에는 AITOP_EVENT 로 종류를 넘긴다 (예전 명령은 waiting 만 받으므로 그대로 동작한다).
238
273
  export function createNotifier({ notify = false, onWaiting = null, notifier = notify ? findNotifier() : null, env = process.env, timeoutMs = HOOK_TIMEOUT_MS, spawnFn = spawn } = {}) {
239
274
  const hook = onWaiting ? createRunner({ timeoutMs, spawnFn }) : null;
240
275
  const desk = notify && notifier ? createRunner({ timeoutMs, spawnFn }) : null;
@@ -245,14 +280,14 @@ export function createNotifier({ notify = false, onWaiting = null, notifier = no
245
280
  hook?.killAll();
246
281
  desk?.killAll();
247
282
  },
248
- fire(fresh) {
283
+ fire(fresh, kind = 'waiting') {
249
284
  if (!fresh.length) return;
250
285
  if (desk) {
251
- const { title, body } = notifyText(fresh);
286
+ const { title, body } = notifyText(fresh, getLang(), kind);
252
287
  const [file, args] = notifierCommand(notifier, title, body);
253
288
  desk.run({ file, args, env });
254
289
  }
255
- if (hook) for (const s of fresh) hook.run({ file: '/bin/sh', args: ['-c', onWaiting], env: { ...env, ...waitingEnv(s) } });
290
+ if (hook) for (const s of fresh) hook.run({ file: '/bin/sh', args: ['-c', onWaiting], env: { ...env, ...waitingEnv(s), AITOP_EVENT: kind } });
256
291
  },
257
292
  };
258
293
  }
package/src/procs.mjs CHANGED
@@ -176,6 +176,33 @@ let ticksPerSec = null;
176
176
  let bootMs = null;
177
177
 
178
178
  // /proc/<pid>/stat 의 22번째 칸은 부팅 뒤 지난 시간(클럭 틱)이다. 명령 이름에 공백·괄호가 들 수 있어 마지막 ')' 뒤부터 센다.
179
+ export function parseStartTicks(stat) {
180
+ const s = String(stat);
181
+ const end = s.lastIndexOf(')');
182
+ if (end < 0) return null;
183
+ const ticks = Number(s.slice(end + 2).split(' ')[19]);
184
+ return Number.isFinite(ticks) ? ticks : null;
185
+ }
186
+
187
+ // /proc/<pid>/stat 원문을 읽는다. /proc 가 없는 OS 는 null. 테스트는 _setStatReader 로 바꾼다.
188
+ let readStat = HAS_PROC ? (pid) => readFileSync(`/proc/${pid}/stat`, 'utf8') : null;
189
+
190
+ export function _setStatReader(fn) {
191
+ const prev = readStat;
192
+ readStat = fn;
193
+ return prev;
194
+ }
195
+
196
+ // 프로세스 시작 시각(부팅 뒤 클럭 틱). 알 수 없으면 null.
197
+ export function startTicks(pid) {
198
+ if (!readStat) return null;
199
+ try {
200
+ return parseStartTicks(readStat(pid));
201
+ } catch {
202
+ return null;
203
+ }
204
+ }
205
+
179
206
  function procStartLinux(pid) {
180
207
  if (bootMs === null) {
181
208
  const m = /^btime (\d+)$/m.exec(readFileSync('/proc/stat', 'utf8'));
@@ -189,9 +216,26 @@ function procStartLinux(pid) {
189
216
  ticksPerSec = 100;
190
217
  }
191
218
  }
192
- const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
193
- const ticks = Number(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[19]);
194
- return Number.isFinite(ticks) ? bootMs + (ticks / ticksPerSec) * 1000 : null;
219
+ const ticks = parseStartTicks(readFileSync(`/proc/${pid}/stat`, 'utf8'));
220
+ return ticks !== null ? bootMs + (ticks / ticksPerSec) * 1000 : null;
221
+ }
222
+
223
+ // 세션 파일의 procStart(부팅 뒤 클럭 틱, 문자열)와 지금 그 pid 의 시작 시각을 비교한다.
224
+ // pid 를 다른 프로세스가 다시 쓰면 시작 시각이 다르다. 틱 단위로 비교해 btime 흔들림(WSL)의 영향을 받지 않는다.
225
+ // procStart 가 없거나 /proc 를 못 읽으면 알 수 없으므로 같은 프로세스로 본다 (예전 동작).
226
+ const START_TOLERANCE_TICKS = 100;
227
+
228
+ export function sameProcess(pid, procStart) {
229
+ const want = Number(procStart);
230
+ if (procStart == null || procStart === '' || !Number.isFinite(want)) return true;
231
+ const got = startTicks(pid);
232
+ if (got === null) return true;
233
+ return Math.abs(got - want) <= START_TOLERANCE_TICKS;
234
+ }
235
+
236
+ // 세션 파일의 주인 프로세스가 아직 살아 있는지 (pid 재사용 제외).
237
+ export function isSessionAlive(pid, procStart) {
238
+ return isAlive(pid) && sameProcess(pid, procStart);
195
239
  }
196
240
 
197
241
  // 프로세스가 시작한 시각(ms). 알 수 없으면 null. 시작 시각은 바뀌지 않으므로 pid 별로 기억한다.
@@ -749,6 +749,8 @@ export function collectAgy({ showEnded, budget }) {
749
749
  now: g.lastTool ?? g.events.at(-1)?.text ?? '',
750
750
  startedAt: null,
751
751
  updatedAt: r.updatedAt ?? Date.now(),
752
+ // 대기 시작 시각 (--line 요약용). 기록에 시각이 없으면 지금 시각으로 메우지 않고 null.
753
+ waitSince: wait ? (r.updatedAt ?? null) : null,
752
754
  tokens,
753
755
  context: { used: g.prompt, window: contextWindow(g.model, g.prompt) },
754
756
  events: g.events,
@@ -5,7 +5,7 @@ import { loadCache } from '../cache.mjs';
5
5
  import { contextWindow } from '../pricing.mjs';
6
6
  import { join, basename } from 'node:path';
7
7
  import { homedir } from 'node:os';
8
- import { isAlive } from '../procs.mjs';
8
+ import { isSessionAlive } from '../procs.mjs';
9
9
  import { ClaudeTracker } from './claude-tracker.mjs';
10
10
  import { emptyTokens, mergeActivity, MEMBER_FADE_MS } from './common.mjs';
11
11
  import { mergeFiles } from './files.mjs';
@@ -294,31 +294,85 @@ function endedFromTranscripts(known, selectedId, budget) {
294
294
  return out;
295
295
  }
296
296
 
297
+ // sessions 폴더 목록은 폴더 수정 시각이 그대로면 재사용한다 (#135).
298
+ // 수정 시각은 틱(수 ms)이나 초 단위로 거칠어, 읽기 직전·직후의 변경이 같은 시각으로 남을 수 있다.
299
+ // 그래서 수정된 지 RACY_MS 안에 읽은 결과는 믿지 않고 다음 갱신에 다시 읽는다 (git 의 racy 검사와 같다).
300
+ const RACY_MS = 2000;
301
+ const LIST_MAX_AGE_MS = 10_000;
302
+ let listing = { mtime: -1, at: 0, files: [] };
303
+ // 파일별로 읽은 내용. 수정 시각·크기가 그대로면 다시 읽지 않는다.
304
+ // 한 번 죽은 것으로 본 pid 는 살아나지 않으므로(같은 pid 는 다른 프로세스), 파일이 바뀌기 전까지 다시 확인하지 않는다.
305
+ const fileCache = new Map();
306
+ let sessionReads = 0;
307
+
308
+ export function _sessionReads() {
309
+ return sessionReads;
310
+ }
311
+
312
+ function listSessionFiles() {
313
+ const mtime = statSync(SESSIONS).mtimeMs;
314
+ if (mtime === listing.mtime && listing.at - mtime > RACY_MS && Date.now() - listing.at < LIST_MAX_AGE_MS) return listing.files;
315
+ const files = readdirSync(SESSIONS).filter((n) => n.endsWith('.json'));
316
+ listing = { mtime, at: Date.now(), files };
317
+ return files;
318
+ }
319
+
320
+ function sessionFile(name) {
321
+ const path = join(SESSIONS, name);
322
+ let st;
323
+ try {
324
+ st = statSync(path);
325
+ } catch (e) {
326
+ debugIo('claude', 'session file stat failed', e, path);
327
+ fileCache.delete(name);
328
+ return null;
329
+ }
330
+ let c = fileCache.get(name);
331
+ if (!c || c.mtime !== st.mtimeMs || c.size !== st.size || c.at - c.mtime <= RACY_MS) {
332
+ sessionReads++;
333
+ const at = Date.now();
334
+ c = { mtime: st.mtimeMs, size: st.size, at, entry: readJson(path), dead: false };
335
+ fileCache.set(name, c);
336
+ }
337
+ // 미리 띄워 둔 대기 프로세스(claude bg-spare)는 아직 세션이 아니다. 작업을 맡으면 spare 가 빠진 파일로 다시 쓰인다.
338
+ if (!c.entry?.sessionId || c.entry.spare) return null;
339
+ if (!c.dead && !isSessionAlive(c.entry.pid, c.entry.procStart)) c.dead = true;
340
+ return { ...c.entry, alive: !c.dead };
341
+ }
342
+
297
343
  // ~/.claude/sessions/*.json 을 세션 id 마다 하나로 (살아 있는 쪽, 그다음 최근에 바뀐 쪽). 폴더를 읽지 못하면 null.
298
344
  function sessionEntries() {
299
345
  let files;
300
346
  try {
301
- files = readdirSync(SESSIONS).filter((n) => n.endsWith('.json'));
347
+ files = listSessionFiles();
302
348
  } catch (e) {
303
349
  debugIo('claude', 'sessions read failed', e);
304
350
  return null;
305
351
  }
352
+ const names = new Set(files);
353
+ for (const n of fileCache.keys()) if (!names.has(n)) fileCache.delete(n);
306
354
  const latest = new Map();
307
355
  for (const f of files) {
308
- const e = readJson(join(SESSIONS, f));
309
- if (!e?.sessionId) continue;
310
- e.alive = isAlive(e.pid);
356
+ const e = sessionFile(f);
357
+ if (!e) continue;
311
358
  const prev = latest.get(e.sessionId);
312
359
  if (!prev || (e.alive && !prev.alive) || (e.updatedAt ?? e.startedAt) > (prev.updatedAt ?? prev.startedAt)) latest.set(e.sessionId, e);
313
360
  }
314
361
  return latest;
315
362
  }
316
363
 
317
- // 응답 대기 중인 Claude 세션 수. 세션 파일과 pid 만 보므로 대화 기록·프로세스 목록을 읽지 않는다 (aitop --line 용).
318
- export function claudeWaitingCount() {
319
- let n = 0;
320
- for (const e of sessionEntries()?.values() ?? []) if (e.alive && e.waitingFor) n++;
321
- return n;
364
+ // 응답 대기 중인 Claude 세션들 [{ tool, name, since }]. 세션 파일과 pid 만 보므로 대화 기록·프로세스 목록을 읽지 않는다 (aitop --line 용).
365
+ // 이름은 세션 파일의 이름, 자동 이름(id 앞 8자)이면 대화 제목 대신 작업 폴더 이름을 쓴다 (제목은 기록을 읽어야 안다).
366
+ // 대기 시작은 상태가 바뀐 시각(statusUpdatedAt), 없으면 세션 파일이 바뀐 시각.
367
+ export function claudeWaiting() {
368
+ const out = [];
369
+ for (const e of sessionEntries()?.values() ?? []) {
370
+ if (!e.alive || !e.waitingFor) continue;
371
+ const autoName = !e.name || e.name === e.sessionId.slice(0, 8);
372
+ const since = [e.statusUpdatedAt, e.updatedAt, e.startedAt].find(Number.isFinite) ?? null;
373
+ out.push({ tool: 'claude', name: autoName ? basename(e.cwd ?? '') : String(e.name), since });
374
+ }
375
+ return out;
322
376
  }
323
377
 
324
378
  export function collectClaude({ showEnded, budget, selectedId }) {
package/src/summary.mjs CHANGED
@@ -20,6 +20,25 @@ export const HEARTBEAT_MS = 20_000;
20
20
  const SKEW_MS = 5_000;
21
21
 
22
22
  const nat = (x) => Number.isInteger(x) && x >= 0;
23
+ // 요약에 적는 다른 도구 대기 세션 수 상한. --line 은 가장 오래 기다린 하나만 보이지만, 둘을 적어 둔다.
24
+ export const WAIT_TOP = 2;
25
+ // 이름은 화면에 보이는 것보다 넉넉히, 그래도 파일이 커지지 않게 자른다.
26
+ const NAME_MAX = 80;
27
+
28
+ // 요약의 waitTop: [{ tool, name, since }]. since 는 모르면 null. 형식이 맞는 항목만 남긴다 (예전 요약에는 없으므로 없으면 빈 목록).
29
+ function waitTopOf(x) {
30
+ if (!Array.isArray(x)) return [];
31
+ return x.filter((w) => typeof w?.name === 'string' && (w.since === null || Number.isFinite(w.since))).slice(0, WAIT_TOP);
32
+ }
33
+
34
+ // 세션의 대기 시작 시각. 출처가 따로 적은 waitSince 가 있으면 그것(null 이면 모름), 없으면 updatedAt.
35
+ // 모르는 시각을 지금 시각으로 메우면 요약이 매번 바뀌고 대기 시간이 늘 0s 로 보인다.
36
+ function sinceOf(s) {
37
+ const t = s.waitSince !== undefined ? s.waitSince : s.updatedAt;
38
+ return Number.isFinite(t) ? t : null;
39
+ }
40
+ // 시각을 모르는 세션은 정렬에서 맨 뒤.
41
+ const sinceKey = (t) => t ?? Number.MAX_SAFE_INTEGER;
23
42
 
24
43
  // 세션 목록에서 요약 값을 뽑는다. 화면 헤더(ui/table.mjs)와 같은 기준이다.
25
44
  export function summarize(sessions, now = Date.now()) {
@@ -32,6 +51,13 @@ export function summarize(sessions, now = Date.now()) {
32
51
  waiting: waiting.length,
33
52
  // Claude 대기 수는 --line 이 세션 파일에서 바로 세므로, 그 밖의 도구 몫(지금은 Antigravity 만 대기 상태가 있다)을 따로 적는다.
34
53
  waitingOther: waiting.filter((s) => s.tool !== 'claude').length,
54
+ // 그중 가장 오래 기다린 세션 이름과 대기 시작 시각 (화면 IDLE 칸과 같은 기준). 대기 시간은 읽는 쪽이 지금 시각으로 센다.
55
+ // v 는 그대로 둔다: 예전 aitop 은 이 칸을 모르고 넘기고, 새 aitop 은 이 칸이 없는 예전 요약도 읽는다.
56
+ waitTop: waiting
57
+ .filter((s) => s.tool !== 'claude')
58
+ .map((s) => ({ tool: s.tool, name: String(s.name ?? '').slice(0, NAME_MAX), since: sinceOf(s) }))
59
+ .sort((a, b) => sinceKey(a.since) - sinceKey(b.since))
60
+ .slice(0, WAIT_TOP),
35
61
  };
36
62
  }
37
63
 
@@ -62,7 +88,7 @@ export function readSummary({ file = SUMMARY_FILE, now = Date.now(), staleMs = S
62
88
  }
63
89
  if (s?.v !== V || !Number.isFinite(s.at) || ![s.running, s.waiting, s.waitingOther].every(nat)) return null;
64
90
  if (now - s.at > staleMs || s.at - now > SKEW_MS) return null;
65
- return s;
91
+ return { ...s, waitTop: waitTopOf(s.waitTop) };
66
92
  }
67
93
 
68
94
  // 실시간 화면용: 수가 바뀌면 지난번 쓴 뒤 minMs 가 지났을 때, 그대로면 heartbeatMs 마다 쓴다.
@@ -71,7 +97,8 @@ export function createSummaryWriter({ file = SUMMARY_FILE, minMs = MIN_WRITE_MS,
71
97
  return (sessions, now = Date.now()) => {
72
98
  const s = summarize(sessions, now);
73
99
  const since = last ? now - last.at : Infinity;
74
- const changed = !last || s.running !== last.running || s.waiting !== last.waiting || s.waitingOther !== last.waitingOther;
100
+ const top = (x) => x.waitTop.map((w) => `${w.name}@${w.since}`).join('|');
101
+ const changed = !last || s.running !== last.running || s.waiting !== last.waiting || s.waitingOther !== last.waitingOther || top(s) !== top(last);
75
102
  if (since < (changed ? minMs : heartbeatMs)) return false;
76
103
  if (!write(s, file)) return false;
77
104
  last = s;
package/src/text.mjs CHANGED
@@ -75,10 +75,10 @@ export function width(s) {
75
75
  return w;
76
76
  }
77
77
 
78
- export function truncate(s, max) {
78
+ // mark: 자른 자리 표시. 기본은 … (ASCII 만 써야 하는 aitop --line 은 다른 글자를 넘긴다).
79
+ export function truncate(s, max, mark = ellipsis(max)) {
79
80
  if (max <= 0) return '';
80
81
  if (width(s) <= max) return s;
81
- const mark = ellipsis(max);
82
82
  const room = max - width(mark);
83
83
  let out = '';
84
84
  let w = 0;