@sejuneoh/aitop 0.28.0 → 0.30.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 +29 -3
- package/bin/aitop.mjs +32 -4
- package/package.json +1 -1
- package/src/attention.mjs +66 -0
- package/src/config.mjs +20 -6
- package/src/doctor.mjs +64 -21
- package/src/help.mjs +6 -3
- package/src/i18n.mjs +72 -16
- package/src/json.mjs +3 -0
- package/src/keys.mjs +2 -0
- package/src/line.mjs +62 -17
- package/src/notify.mjs +47 -9
- package/src/procs.mjs +47 -3
- package/src/resume.mjs +57 -0
- package/src/sources/antigravity.mjs +2 -0
- package/src/sources/claude-ledger.mjs +55 -45
- package/src/sources/claude-tracker.mjs +45 -2
- package/src/sources/claude.mjs +180 -52
- package/src/sources/codex-ledger.mjs +6 -2
- package/src/sources/codex.mjs +82 -20
- package/src/sources/common.mjs +10 -0
- package/src/sources/dirs.mjs +140 -0
- package/src/sources/projects.mjs +12 -10
- package/src/summary.mjs +29 -2
- package/src/text.mjs +2 -2
- package/src/ui/chrome.mjs +14 -2
- package/src/ui/detail.mjs +36 -1
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
|
|
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
|
|
@@ -42,7 +42,9 @@ aitop --lang ko Korean screen, help, doctor and error messages (also AITOP_LANG
|
|
|
42
42
|
|
|
43
43
|
The language is picked from `--lang`, then `AITOP_LANG`, then `lang` in the config file, then `LC_ALL`, `LC_MESSAGES` and `LANG`: Korean when the locale starts with `ko`, English otherwise (including `C.UTF-8` and unset). If you used aitop on a `C.UTF-8` or `en_US` locale before, the screen, help and doctor output are now in English; set `AITOP_LANG=ko` to keep Korean.
|
|
44
44
|
|
|
45
|
-
|
|
45
|
+
To continue a session elsewhere (for example when you cannot jump to its tab, as in Windows Terminal with WSL), the detail panel shows a `Resume` command and `y` copies it to the clipboard with OSC 52: Claude `cd <dir> && claude --resume <id>`, Codex `cd <dir> && codex resume <id>`, Antigravity `cd <dir> && agy --conversation <id>` (none for Gemini CLI). A session from a data folder other than `~/.claude` / `~/.codex` (or any session while `CLAUDE_CONFIG_DIR` / `CODEX_HOME` is set) gets `CLAUDE_CONFIG_DIR=<dir>` / `CODEX_HOME=<dir>` before the tool so it finds the right history. Claude finds sessions per folder, so without a known folder no command is made; ids that are not UUIDs make none either. A short detail panel leaves the command out; use `y` or `--json` then. Paths and ids are shell quoted and control characters are stripped. Windows Terminal, WezTerm, iTerm2 and kitty accept OSC 52; tmux needs `set -g set-clipboard on`; other terminals ignore it silently, so copy the command from the panel. Nothing is sent to the session. `--json` has the same command as `resumeCmd` per session (`null` if none).
|
|
46
|
+
|
|
47
|
+
In `--json`, `phase` stays the Korean status text in every language (as does `AITOP_WAITING_FOR` for `--on-waiting`). Session `name` uses the same user-given names as the table: a Codex session's `name` changes from the folder name to its `thread_name` once it has one. For scripts, use `phaseKind`, a stable state name: `think`, `write`, `tool`, `team`, `waiting`, `idle`, `done`, `ended` (or `null`). Other text fields follow their own rules: with English selected, `--doctor --json` has Korean `tools.*.hint` but English `config.problems`.
|
|
46
48
|
|
|
47
49
|
### Daily report
|
|
48
50
|
|
|
@@ -59,9 +61,29 @@ aitop --report daily --by project --days 7
|
|
|
59
61
|
aitop --report monthly --by model --months 6
|
|
60
62
|
```
|
|
61
63
|
|
|
64
|
+
### Notifications
|
|
65
|
+
|
|
66
|
+
Off by default and only on the live screen. Sessions already waiting (or already over 90% context) when aitop starts are not reported.
|
|
67
|
+
|
|
68
|
+
```
|
|
69
|
+
aitop --notify desktop notification when a session starts waiting (notify-send on Linux/WSL, osascript on macOS)
|
|
70
|
+
aitop --notify=waiting,done,context pick the kinds; plain --notify uses the config file kinds, or waiting only when none are set
|
|
71
|
+
aitop --on-waiting 'my-hook.sh' run a command with /bin/sh -c for the same events (10 second limit, runs as you)
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
- `waiting`: a session starts waiting for your approval or answer.
|
|
75
|
+
- `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.
|
|
76
|
+
- `context`: context use passes 90%, once; it re-arms after it drops below 85% (for example after compaction).
|
|
77
|
+
|
|
78
|
+
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.
|
|
79
|
+
|
|
80
|
+
The notification body shows the session's own name when it has one (Claude Code `/rename`, or a name given by a peer session; Codex `thread_name`), otherwise the project. Desktop notifications can appear on the lock screen, so the name is visible there too.
|
|
81
|
+
|
|
62
82
|
### tmux status line
|
|
63
83
|
|
|
64
|
-
`aitop --line` prints today's cost (API list price, `/$<budget>` when a daily budget is set), the
|
|
84
|
+
`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.
|
|
85
|
+
|
|
86
|
+
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
87
|
|
|
66
88
|
```tmux
|
|
67
89
|
set -g status-right '#(aitop --line=tmux)'
|
|
@@ -72,6 +94,10 @@ Keys: `↑↓` select · `n` next session to check · `/` search · `s` sort ·
|
|
|
72
94
|
|
|
73
95
|
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).
|
|
74
96
|
|
|
97
|
+
### Several Claude or Codex profiles
|
|
98
|
+
|
|
99
|
+
aitop reads `~/.claude` and `~/.codex` by default. To read more profiles, list them in the config file, `"claudeDirs": ["~/.claude", "~/.claude-work"]` and `"codexHomes": ["~/.codex", "~/.codex-alt"]`, or set `AITOP_CLAUDE_DIRS` / `AITOP_CODEX_HOMES` with paths joined by `:` (`;` on Windows), for example `AITOP_CLAUDE_DIRS=~/.claude:~/.claude-work aitop`. Order: `AITOP_*` > config file > an inherited `CLAUDE_CONFIG_DIR` / `CODEX_HOME` > default, so a `CLAUDE_CONFIG_DIR` exported for Claude Code does not hide your config list; `aitop --print-config` shows which source is used. A value that is itself an existing folder is never split, so an old single path containing `:` keeps working. The same folder listed twice (also through a link) is read once, and a session log copied into two folders is counted once. For monthly reports, a month counts as complete only from the day after the oldest remaining log of the folder that was cleaned most recently, so a folder with old logs cannot make a month look complete when another folder already lost logs for it. aitop does not read look-alike folders on its own; `aitop --doctor` lists every folder it reads plus folders that hold logs but are not read (`~/.claude-*`, `~/.config/claude`, `~/.codex-*` and similar owned by you, and a `CLAUDE_CONFIG_DIR` / `CODEX_HOME` the config list left out), with how to add them.
|
|
100
|
+
|
|
75
101
|
## License
|
|
76
102
|
|
|
77
103
|
[MIT](https://github.com/SejuneOh/aitop/blob/main/LICENSE)
|
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
|
-
|
|
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 });
|
|
@@ -82,6 +83,9 @@ process.env.AITOP_COLOR_BLIND = opt.colorBlind ? '1' : '0';
|
|
|
82
83
|
if (config.values.icons.source === 'file') process.env.AITOP_ICONS = opt.icons;
|
|
83
84
|
// 폭이 모호한 기호를 2칸으로 셀지는 글자 폭 계산(text.mjs)이 쓴다. 화면 모듈은 그릴 때마다 이 값을 본다.
|
|
84
85
|
setAmbiguous(opt.ambiguous);
|
|
86
|
+
// 읽을 Claude·Codex 기록 폴더 목록. 기록을 읽는 모듈을 불러오기 전에 정한다 (#212).
|
|
87
|
+
const { setDataDirs } = await import('../src/sources/dirs.mjs');
|
|
88
|
+
setDataDirs({ claude: opt.claudeDirs, codex: opt.codexHomes });
|
|
85
89
|
const { BRAND, userVarsSeq } = await import('../src/brand.mjs');
|
|
86
90
|
const { keysText } = await import('../src/help.mjs');
|
|
87
91
|
const { debug, initLog, logPath } = await import('../src/log.mjs');
|
|
@@ -204,15 +208,16 @@ const { frameTimer } = await import('../src/frames.mjs');
|
|
|
204
208
|
const { flushCache } = await import('../src/cache.mjs');
|
|
205
209
|
const { toJson } = await import('../src/json.mjs');
|
|
206
210
|
const { createSummaryWriter, summarize, writeSummary } = await import('../src/summary.mjs');
|
|
207
|
-
const { createAttention, updateAttention, markSeen, nextAttention, windowTitle, createWaitWatch, takeNewlyWaiting, attentionCounts } = await import('../src/attention.mjs');
|
|
211
|
+
const { createAttention, updateAttention, markSeen, nextAttention, windowTitle, createWaitWatch, takeNewlyWaiting, attentionCounts, createEventWatch, takeEvents } = await import('../src/attention.mjs');
|
|
208
212
|
const { createNotifier } = await import('../src/notify.mjs');
|
|
209
213
|
const { onKey, fixFocus } = await import('../src/keys.mjs');
|
|
210
214
|
const { admit, createLoading, latchReady } = await import('../src/loading.mjs');
|
|
215
|
+
const { osc52, resumeCmd } = await import('../src/resume.mjs');
|
|
211
216
|
|
|
212
217
|
// 요청 전체 보기는 기본으로 꺼 둔다. 켜지 않으면 상세 패널에도 --json 에도 나가지 않는다.
|
|
213
218
|
const showRequests = opt.showRequests;
|
|
214
219
|
// settings: 도움말(?)에 보이는 지금 설정 값.
|
|
215
|
-
const settings = { budgetDay: opt.budgetDay, notify: Boolean(alerts.notify), onWaiting: Boolean(alerts.onWaiting), debug: log.on, configPath: config.path };
|
|
220
|
+
const settings = { budgetDay: opt.budgetDay, notify: Boolean(alerts.notify), events: alerts.events, onWaiting: Boolean(alerts.onWaiting), debug: log.on, configPath: config.path };
|
|
216
221
|
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
222
|
const once = args.has('--once') || args.has('--json') || !process.stdout.isTTY;
|
|
218
223
|
// ready: 시작할 때 세션 기록을 다 읽었는지 (loading.mjs). 그 전에는 비용·컨텍스트 정렬과 ▲ 를 고정한다. 한 번에 다 읽는 --once·--json 은 처음부터 준비 완료다.
|
|
@@ -233,6 +238,9 @@ let tools = null;
|
|
|
233
238
|
const bell = opt.bell;
|
|
234
239
|
const waitWatch = createWaitWatch();
|
|
235
240
|
const notifier = !once && (alerts.notify || alerts.onWaiting) ? createNotifier(alerts) : null;
|
|
241
|
+
// 끝남(done)·context 경고는 켠 경우에만 센다 (#204). 벨은 늘 응답 대기만 울린다.
|
|
242
|
+
const eventKinds = alerts.events.filter((k) => k !== 'waiting');
|
|
243
|
+
const eventWatch = notifier && eventKinds.length ? createEventWatch({ doneMs: opt.doneMinutes * 60_000 }) : null;
|
|
236
244
|
|
|
237
245
|
// throttle: 주기 갱신(tick)에서만 참이다. 로딩 중에는 loading.mjs 의 admit 이 허락할 때만 화면 데이터를 바꾼다.
|
|
238
246
|
// 알림(벨·--notify·--on-waiting)은 화면에 올리지 않은 갱신에서도 그대로 돈다. 돌려주는 값은 화면 데이터를 바꿨는지.
|
|
@@ -253,7 +261,11 @@ function refresh({ throttle = false } = {}) {
|
|
|
253
261
|
if (!once && (bell || notifier)) {
|
|
254
262
|
const fresh = takeNewlyWaiting(waitWatch, data.sessions);
|
|
255
263
|
if (fresh.length && bell) process.stdout.write('\x07');
|
|
256
|
-
notifier?.fire(fresh);
|
|
264
|
+
if (alerts.events.includes('waiting')) notifier?.fire(fresh);
|
|
265
|
+
}
|
|
266
|
+
if (eventWatch) {
|
|
267
|
+
const evs = takeEvents(eventWatch, data.sessions, { ready: loading.ready });
|
|
268
|
+
for (const kind of eventKinds) notifier.fire(evs.filter((e) => e.kind === kind).map((e) => e.session), kind);
|
|
257
269
|
}
|
|
258
270
|
lastMore = data.more;
|
|
259
271
|
if (!once) {
|
|
@@ -394,8 +406,24 @@ function keepSelectionVisible() {
|
|
|
394
406
|
if (list.length && !list.some((s) => s.id === view.selectedId)) select(list[0].id);
|
|
395
407
|
}
|
|
396
408
|
|
|
409
|
+
// y: 이어 여는 명령을 OSC 52 로 클립보드에 쓴다. 터미널이 아니면 아무것도 하지 않는다. 알림은 2초 보인다.
|
|
410
|
+
const TOAST_MS = 2000;
|
|
411
|
+
let toastTimer = null;
|
|
412
|
+
function copy(s) {
|
|
413
|
+
if (!out.isTTY) return;
|
|
414
|
+
const cmd = resumeCmd(s);
|
|
415
|
+
if (cmd) out.write(osc52(cmd));
|
|
416
|
+
view.toast = { key: cmd ? 'foot.copied' : 'foot.copyNone', until: Date.now() + TOAST_MS };
|
|
417
|
+
clearTimeout(toastTimer);
|
|
418
|
+
toastTimer = setTimeout(() => {
|
|
419
|
+
view.toast = null;
|
|
420
|
+
draw();
|
|
421
|
+
}, TOAST_MS);
|
|
422
|
+
}
|
|
423
|
+
|
|
397
424
|
stdin.setEncoding('utf8');
|
|
398
425
|
const act = {
|
|
426
|
+
copy,
|
|
399
427
|
quit,
|
|
400
428
|
refresh,
|
|
401
429
|
move,
|
package/package.json
CHANGED
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,15 @@
|
|
|
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
|
-
// 화면 모듈은 불러올 때 테마·아이콘을 고르므로, 이 모듈은
|
|
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 { posix, win32 } from 'node:path';
|
|
7
|
+
import { join, 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';
|
|
12
|
+
import { DIR_ENV, pathLike, splitPaths } from './sources/dirs.mjs';
|
|
11
13
|
|
|
12
14
|
const bool = (v) => typeof v === 'boolean';
|
|
13
15
|
const oneOf = (...xs) => (v) => xs.includes(v);
|
|
@@ -46,6 +48,8 @@ export function budgetDayOption(argv) {
|
|
|
46
48
|
}
|
|
47
49
|
|
|
48
50
|
const BOOL = ['true', 'false'];
|
|
51
|
+
// 기록 폴더 목록: 절대 경로(또는 ~ 로 시작) 문자열 배열, 1~16개.
|
|
52
|
+
const pathList = (v) => Array.isArray(v) && v.length > 0 && v.length <= 16 && v.every(pathLike);
|
|
49
53
|
// expect, envExpect: 둘 중 하나면 [a, b], 아니면 i18n 키. 문구는 쓸 때 지금 언어로 만든다.
|
|
50
54
|
const expectText = (x) => (Array.isArray(x) ? t('cfg.either', { a: x[0], b: x[1] }) : t(x));
|
|
51
55
|
|
|
@@ -58,7 +62,10 @@ export const KEYS = {
|
|
|
58
62
|
bell: { ok: bool, expect: BOOL, def: false },
|
|
59
63
|
showRequests: { ok: bool, expect: BOOL, def: false, env: ['AITOP_SHOW_REQUESTS', (v) => (v === '1' ? true : v === '0' ? false : undefined)] },
|
|
60
64
|
all: { ok: bool, expect: BOOL, def: false },
|
|
61
|
-
notify
|
|
65
|
+
// notify 는 true/false 또는 알릴 종류 배열 (예: ["waiting", "done", "context"]).
|
|
66
|
+
notify: { ok: (v) => bool(v) || (Array.isArray(v) && v.length > 0 && v.every((x) => EVENT_KINDS.includes(x))), expect: 'cfg.notify', def: false },
|
|
67
|
+
// done 알림을 띄우려면 작업 중이 이어져야 하는 시간(분).
|
|
68
|
+
doneMinutes: { ok: (v) => typeof v === 'number' && Number.isFinite(v) && v > 0, expect: 'cfg.positive', def: 3 },
|
|
62
69
|
onWaiting: { ok: (v) => typeof v === 'string' && v.trim() !== '', expect: 'cfg.command', def: null },
|
|
63
70
|
debug: { ok: bool, expect: BOOL, def: false, env: ['AITOP_DEBUG', (v) => (v === '1' ? true : v === '0' ? false : undefined)], envProblem: true, envExpect: ['1', '0'] },
|
|
64
71
|
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 },
|
|
@@ -70,6 +77,10 @@ export const KEYS = {
|
|
|
70
77
|
ambiguous: { ok: oneOf('narrow', 'wide'), expect: ['narrow', 'wide'], def: 'narrow', env: ['AITOP_AMBIGUOUS', (v) => (v === 'narrow' || v === 'wide' ? v : undefined)], envProblem: true },
|
|
71
78
|
// --help·--doctor·오류 문구의 언어(i18n.mjs). 기본값은 로캘(LC_ALL > LC_MESSAGES > LANG)이 ko 로 시작하면 ko, 아니면 en.
|
|
72
79
|
lang: { ok: oneOf('ko', 'en'), expect: ['ko', 'en'], def: localeLang, env: ['AITOP_LANG', langValue], envProblem: true },
|
|
80
|
+
// 읽을 Claude 설정 폴더·Codex 홈 폴더 목록 (#212, sources/dirs.mjs). 환경 변수는 path.delimiter(: 또는 ;)로 여러 개를 잇는다.
|
|
81
|
+
// AITOP_CLAUDE_DIRS > 설정 파일 > 물려받은 CLAUDE_CONFIG_DIR (inherit, Claude Code 용 변수라 설정 파일보다 낮다) > ~/.claude.
|
|
82
|
+
claudeDirs: { ok: pathList, expect: 'cfg.paths', def: () => [join(homedir(), DIR_ENV.claude.home)], env: [DIR_ENV.claude.own, (v) => splitPaths(v)], inherit: [DIR_ENV.claude.inherited, (v) => splitPaths(v)] },
|
|
83
|
+
codexHomes: { ok: pathList, expect: 'cfg.paths', def: () => [join(homedir(), DIR_ENV.codex.home)], env: [DIR_ENV.codex.own, (v) => splitPaths(v)], inherit: [DIR_ENV.codex.inherited, (v) => splitPaths(v)] },
|
|
73
84
|
};
|
|
74
85
|
|
|
75
86
|
// Windows 는 XDG_CONFIG_HOME 이 없으면 %APPDATA%\aitop\config.json.
|
|
@@ -155,8 +166,10 @@ export function resolveConfig({ flags = {}, env = process.env, file } = {}) {
|
|
|
155
166
|
const fromEnv = spec.env && env[spec.env[0]] != null ? spec.env[1](env[spec.env[0]]) : undefined;
|
|
156
167
|
if (spec.envProblem && env[spec.env[0]] != null && fromEnv === undefined) problems.push(t('cfg.badEnv', { name: spec.env[0], value: show(env[spec.env[0]]), expect: expectText(spec.envExpect ?? spec.expect) }));
|
|
157
168
|
if (flags[key] !== undefined) values[key] = { value: flags[key], source: 'flag' };
|
|
158
|
-
else if (fromEnv !== undefined) values[key] = { value: fromEnv, source: 'env' };
|
|
169
|
+
else if (fromEnv !== undefined) values[key] = spec.inherit ? { value: fromEnv, source: 'env', env: spec.env[0] } : { value: fromEnv, source: 'env' };
|
|
159
170
|
else if (key in file.values) values[key] = { value: file.values[key], source: 'file' };
|
|
171
|
+
// 물려받은 변수(CLAUDE_CONFIG_DIR 등)는 설정 파일 다음. 어느 변수에서 왔는지 env 에 남긴다.
|
|
172
|
+
else if (spec.inherit && spec.inherit[1](env[spec.inherit[0]]) !== undefined) values[key] = { value: spec.inherit[1](env[spec.inherit[0]]), source: 'env', env: spec.inherit[0] };
|
|
160
173
|
// 기본값이 함수면 환경에서 고른다 (lang 은 로캘).
|
|
161
174
|
else values[key] = { value: typeof spec.def === 'function' ? spec.def(env) : spec.def, source: 'default' };
|
|
162
175
|
}
|
|
@@ -167,8 +180,9 @@ export function resolveConfig({ flags = {}, env = process.env, file } = {}) {
|
|
|
167
180
|
export function configText(cfg) {
|
|
168
181
|
const out = [t('cfg.file', { path: stripControl(cfg.path), state: t(cfg.exists ? 'cfg.exists' : 'cfg.missing') }), ''];
|
|
169
182
|
for (const [key, { value, source }] of Object.entries(cfg.values)) {
|
|
170
|
-
|
|
171
|
-
|
|
183
|
+
// 배열(notify 의 종류, 기록 폴더)은 waiting,done 처럼 쉼표로 잇는다.
|
|
184
|
+
const v = value == null ? (key === 'theme' ? 'auto' : '-') : typeof value === 'string' ? JSON.stringify(value) : Array.isArray(value) ? stripControl(value.join(',')) : String(value);
|
|
185
|
+
out.push(`${key.padEnd(14)}${v.padEnd(12)} ${source}${cfg.values[key].env ? ` (${cfg.values[key].env})` : ''}`);
|
|
172
186
|
}
|
|
173
187
|
if (cfg.problems.length) out.push('', ...cfg.problems.map((p) => `! ${stripControl(p)}`));
|
|
174
188
|
return out.join('\n');
|
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';
|
|
5
|
-
import { join } from 'node:path';
|
|
4
|
+
import { readdirSync, readFileSync, statSync, existsSync, openSync, readSync, closeSync } from 'node:fs';
|
|
5
|
+
import { basename, 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';
|
|
@@ -12,13 +12,12 @@ import { BRAND } from './brand.mjs';
|
|
|
12
12
|
import { tildeIn } from './paths.mjs';
|
|
13
13
|
import { findNotifier, isWsl } from './notify.mjs';
|
|
14
14
|
import { getLang, t as tr } from './i18n.mjs';
|
|
15
|
+
import { candidateDirs, claudeDirs, codexHomes } from './sources/dirs.mjs';
|
|
15
16
|
|
|
16
17
|
const UNIT = { s: '초', m: '분', h: '시간', d: '일' };
|
|
17
18
|
const ago = (ms) => fmtAgo(ms).replace(/[smhd]$/, (u) => UNIT[u]);
|
|
18
19
|
|
|
19
20
|
const HOME = homedir();
|
|
20
|
-
const CLAUDE = process.env.CLAUDE_CONFIG_DIR ?? join(HOME, '.claude');
|
|
21
|
-
const CODEX = join(process.env.CODEX_HOME ?? join(HOME, '.codex'), 'sessions');
|
|
22
21
|
const GEMINI = join(process.env.GEMINI_HOME ?? join(HOME, '.gemini'), 'tmp');
|
|
23
22
|
|
|
24
23
|
// Windows 는 \ 와 대소문자를 무시하고 줄인다 (paths.mjs).
|
|
@@ -102,23 +101,59 @@ function topKeys(path) {
|
|
|
102
101
|
}
|
|
103
102
|
}
|
|
104
103
|
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
return { tool: 'claude', state: 'ok', path: tilde(dir), records: files.length, lastAt: last?.mtime ?? null, running, readable: last ? firstLineIsJson(last.path) : null, hint: null };
|
|
104
|
+
// 살아 있는 pid 의 세션 파일만 연다. 대기 프로세스(spare)와 pid 재사용은 세지 않는다.
|
|
105
|
+
function liveSessionFile(path) {
|
|
106
|
+
try {
|
|
107
|
+
const e = JSON.parse(readFileSync(path, 'utf8'));
|
|
108
|
+
return !e.spare && isSessionAlive(e.pid, e.procStart);
|
|
109
|
+
} catch {
|
|
110
|
+
return false;
|
|
111
|
+
}
|
|
114
112
|
}
|
|
115
113
|
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
114
|
+
// 기록 폴더 여러 개(#212)를 한 도구 결과로 모은다. 같은 기록(key 가 같은 파일)은 한 번만 센다.
|
|
115
|
+
// path 는 첫 폴더(예전 모양), dirs 는 읽는 폴더마다 { path, found, records }.
|
|
116
|
+
function gatherDirs(roots, list) {
|
|
117
|
+
const dirs = [];
|
|
118
|
+
const byKey = new Map();
|
|
119
|
+
for (const root of roots) {
|
|
120
|
+
const files = existsSync(root) ? list(root) : null;
|
|
121
|
+
dirs.push({ path: tilde(root), found: Boolean(files), records: files?.length ?? 0 });
|
|
122
|
+
for (const f of files ?? []) if (!byKey.has(f.key)) byKey.set(f.key, f.path);
|
|
123
|
+
}
|
|
124
|
+
const found = dirs.some((d) => d.found);
|
|
125
|
+
const files = [...byKey.values()];
|
|
126
|
+
const last = found ? newest(files) : null;
|
|
127
|
+
return { found, path: dirs[0]?.path ?? '', dirs, records: files.length, lastAt: last?.mtime ?? null, readable: last ? firstLineIsJson(last.path) : null };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const claudeFiles = (dir) => walk(dir, 1, (n) => n.endsWith('.jsonl')).map((p) => ({ key: p.slice(dir.length), path: p }));
|
|
131
|
+
const codexFiles = (dir) => walk(dir, 3, (n) => n.startsWith('rollout-') && n.endsWith('.jsonl')).map((p) => ({ key: basename(p), path: p }));
|
|
132
|
+
|
|
133
|
+
// 읽지 않는 폴더 중 기록이 있는 것 (dirs.mjs candidateDirs). 기록 수만 센다.
|
|
134
|
+
function candidatesOf(paths, sub, list) {
|
|
135
|
+
return paths.map((p) => ({ path: tilde(p), records: list(join(p, sub)).length })).filter((c) => c.records > 0);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function claude(cand) {
|
|
139
|
+
const homes = claudeDirs();
|
|
140
|
+
const g = gatherDirs(homes.map((h) => join(h, 'projects')), claudeFiles);
|
|
141
|
+
let running = null;
|
|
142
|
+
if (canListProcesses()) {
|
|
143
|
+
running = 0;
|
|
144
|
+
for (const h of homes) running += ls(join(h, 'sessions')).filter((e) => /^\d+\.json$/.test(e.name) && isAlive(Number(e.name.split('.')[0])) && liveSessionFile(join(h, 'sessions', e.name))).length;
|
|
145
|
+
}
|
|
146
|
+
const candidates = candidatesOf(cand, 'projects', claudeFiles);
|
|
147
|
+
if (!g.found) return { tool: 'claude', state: 'missing', path: g.path, dirs: g.dirs, candidates, records: 0, lastAt: null, running, readable: null, hint: null };
|
|
148
|
+
return { tool: 'claude', state: 'ok', path: g.path, dirs: g.dirs, candidates, records: g.records, lastAt: g.lastAt, running, readable: g.readable, hint: null };
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function codex(cand) {
|
|
152
|
+
const g = gatherDirs(codexHomes().map((h) => join(h, 'sessions')), codexFiles);
|
|
119
153
|
const running = canListProcesses() ? findProcesses(isCodex).length : null;
|
|
120
|
-
|
|
121
|
-
return { tool: 'codex', state: '
|
|
154
|
+
const candidates = candidatesOf(cand, 'sessions', codexFiles);
|
|
155
|
+
if (!g.found) return { tool: 'codex', state: 'missing', path: g.path, dirs: g.dirs, candidates, records: 0, lastAt: null, running, readable: null, hint: null };
|
|
156
|
+
return { tool: 'codex', state: 'ok', path: g.path, dirs: g.dirs, candidates, records: g.records, lastAt: g.lastAt, running, readable: g.readable, hint: null };
|
|
122
157
|
}
|
|
123
158
|
|
|
124
159
|
// Gemini 는 세션 기록 형식을 아직 모른다. 프로세스만 세고, 기록 폴더가 있으면 형식 확인용 키 이름을 남긴다.
|
|
@@ -169,10 +204,12 @@ export function hintOf(r, lang = 'ko') {
|
|
|
169
204
|
return null;
|
|
170
205
|
}
|
|
171
206
|
|
|
172
|
-
|
|
207
|
+
// home: 후보 폴더를 찾을 홈 폴더 (테스트에서 바꿔 끼운다).
|
|
208
|
+
export function checkTools({ home = HOME } = {}) {
|
|
209
|
+
const cand = candidateDirs({ home });
|
|
173
210
|
const tools = {};
|
|
174
211
|
for (const fn of [claude, codex, gemini, agy]) {
|
|
175
|
-
const r = fn();
|
|
212
|
+
const r = fn === claude ? claude(cand.claude) : fn === codex ? codex(cand.codex) : fn();
|
|
176
213
|
r.hint = hintOf(r, 'ko');
|
|
177
214
|
tools[r.tool] = r;
|
|
178
215
|
}
|
|
@@ -222,8 +259,14 @@ export function doctorText(result, version, now = Date.now(), lang = getLang())
|
|
|
222
259
|
for (const t of Object.values(result.tools)) {
|
|
223
260
|
const d = describe(t, now, lang);
|
|
224
261
|
out.push(`${d.mark} ${pad(t.tool, 7)}${pad(d.state, 10)}${d.path}`);
|
|
262
|
+
// 기록 폴더가 여럿이면 둘째부터 한 줄씩, 읽지 않는 후보 폴더는 넣는 방법과 함께 (#212).
|
|
263
|
+
for (const x of t.dirs?.slice(1) ?? []) out.push(` + ${pad('', 15)}${x.path} ${x.found ? tr('doctor.records', { n: x.records.toLocaleString('en-US') }, o) : tr('doctor.dirMissing', null, o)}`);
|
|
225
264
|
out.push(` ${d.detail}`);
|
|
226
265
|
if (d.hint) out.push(` → ${d.hint}`);
|
|
266
|
+
if (t.candidates?.length) {
|
|
267
|
+
for (const c of t.candidates) out.push(` ? ${tr('doctor.candidate', { path: c.path, n: c.records.toLocaleString('en-US') }, o)}`);
|
|
268
|
+
out.push(` → ${tr(t.tool === 'claude' ? 'doctor.candidateHintClaude' : 'doctor.candidateHintCodex', null, o)}`);
|
|
269
|
+
}
|
|
227
270
|
}
|
|
228
271
|
if ('notifier' in result) out.push('', notifierText(result.notifier, result.platform, lang));
|
|
229
272
|
// 설정 파일: 무시한 키와 값, 받지 않은 onWaiting 을 알린다.
|
package/src/help.mjs
CHANGED
|
@@ -33,6 +33,7 @@ export const VIEWS = {
|
|
|
33
33
|
keys: [
|
|
34
34
|
k('detail.switch', '↑↓ j k', 'switchSession', '↑↓/jk'),
|
|
35
35
|
k('detail.files', 'f Tab', 'files'),
|
|
36
|
+
k('detail.copy', 'y', 'copy'),
|
|
36
37
|
k('detail.close', 'd', 'close'),
|
|
37
38
|
],
|
|
38
39
|
},
|
|
@@ -90,7 +91,7 @@ export const COMMON = {
|
|
|
90
91
|
|
|
91
92
|
// 화면 안 도움말의 옵션 묶음. 자세한 설명은 aitop --help. [옵션(값을 받는 옵션은 i18n 키), 설명 i18n 키]
|
|
92
93
|
const OPTION_IDS = [
|
|
93
|
-
['
|
|
94
|
+
['hopt.notifyOpt', 'hopt.notify'],
|
|
94
95
|
['hopt.onWaiting', 'hopt.onWaitingText'],
|
|
95
96
|
['hopt.budgetDay', 'hopt.budgetDayText'],
|
|
96
97
|
['--show-requests', 'hopt.showRequests'],
|
|
@@ -128,7 +129,7 @@ export function viewText(v, lang = getLang()) {
|
|
|
128
129
|
// aitop --help 끝의 키 안내. 지금 언어(bin 이 정한다)로 쓴다.
|
|
129
130
|
export function keysText(lang = getLang()) {
|
|
130
131
|
const title = (n) => t(`view.${n}`, null, { lang });
|
|
131
|
-
return [`${t('help.keys', null, { lang })}: ${keysLine('table', lang)} · ${keysLine('common', lang)}`, ...['files', 'diff', 'filtered', 'search'].map((n) => ` ${title(n)}: ${keysLine(n, lang)}`)].join('\n');
|
|
132
|
+
return [`${t('help.keys', null, { lang })}: ${keysLine('table', lang)} · ${keysLine('common', lang)}`, ...['detail', 'files', 'diff', 'filtered', 'search'].map((n) => ` ${title(n)}: ${keysLine(n, lang)}`)].join('\n');
|
|
132
133
|
}
|
|
133
134
|
|
|
134
135
|
// 지금 설정 값 한 줄 (예: 예산 $50 · 알림 켜짐 · 디버그 꺼짐). settings 가 없으면 null.
|
|
@@ -137,5 +138,7 @@ export function settingsLine(s, lang = getLang()) {
|
|
|
137
138
|
const o = { lang };
|
|
138
139
|
const onOff = (v) => t(v ? 'set.on' : 'set.off', null, o);
|
|
139
140
|
const usd = (x) => (Number.isInteger(x) ? `$${x}` : `$${x.toFixed(2)}`);
|
|
140
|
-
|
|
141
|
+
// 알림이 켜져 있고 종류를 기본(waiting)과 다르게 정했으면 함께 보인다. 예: 알림 켜짐 (waiting,done)
|
|
142
|
+
const kinds = s.notify && s.events && s.events.join(',') !== 'waiting' ? ` (${s.events.join(',')})` : '';
|
|
143
|
+
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
144
|
}
|