@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/src/i18n.mjs
CHANGED
|
@@ -61,11 +61,13 @@ const HELP_KO = `{logo} aitop - 터미널에서 Claude Code · Codex · Antigrav
|
|
|
61
61
|
aitop 실시간 화면
|
|
62
62
|
aitop --once 현재 상태를 한 번 출력하고 끝낸다
|
|
63
63
|
aitop --all 종료된 세션(24시간 이내)도 함께 본다
|
|
64
|
-
aitop --line 오늘 비용·응답 대기
|
|
65
|
-
|
|
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 과 함께 쓸 수 있다)
|
|
70
|
+
세션마다 resumeCmd 에 그 세션을 이어 여는 명령을 넣는다 (예: cd /repo && claude --resume <id>, 없으면 null)
|
|
69
71
|
aitop --report daily [--by tool|model|project] [--days N] [--json] 최근 N일(기본·최대 30)의 날짜별 토큰·비용(API 정가 환산)을
|
|
70
72
|
도구별·모델별·프로젝트별 표로 내고 끝낸다. 최근 날짜가 위, 맨 아래는 합계. 처음 실행은 30일치 기록을 읽느라 오래 걸릴 수 있다
|
|
71
73
|
프로젝트는 작업 폴더의 마지막 이름이고, 열이 터미널 폭을 넘으면 비용이 작은 쪽을 (그 외) 로 합친다
|
|
@@ -74,8 +76,10 @@ const HELP_KO = `{logo} aitop - 터미널에서 Claude Code · Codex · Antigrav
|
|
|
74
76
|
aitop --doctor Claude · Codex · Antigravity · Gemini 기록과 실행 중인 프로세스, 설정 파일을 점검한다 (--json 과 함께 쓸 수 있다)
|
|
75
77
|
aitop --bell 응답 대기 세션이 새로 생기면 터미널 벨을 울린다
|
|
76
78
|
aitop --notify 응답 대기 세션이 새로 생기면 데스크톱 알림을 띄운다 (notify-send · osascript, 없으면 건너뜀)
|
|
77
|
-
aitop --
|
|
78
|
-
|
|
79
|
+
aitop --notify=waiting,done,context 알릴 종류를 고른다 (--notify 만 주면 설정 파일 notify 배열, 없으면 waiting). done: 3분(설정 파일 doneMinutes, 응답 대기 시간 빼고) 넘게 작업하던 세션이 다음 지시를
|
|
80
|
+
기다리면 한 번. context: 컨텍스트가 90% 를 넘으면 한 번 (85% 아래로 내려가면 다시)
|
|
81
|
+
aitop --on-waiting <명령> 알릴 일이 생기면 /bin/sh -c 로 명령을 실행한다 (내 권한으로 실행, 10초 제한). 종류는 --notify 를 따른다 (--no-notify 여도)
|
|
82
|
+
세션 정보는 환경변수로만: AITOP_EVENT(waiting|done|context) AITOP_TOOL AITOP_PROJECT AITOP_SESSION_ID AITOP_CWD AITOP_WAITING_FOR
|
|
79
83
|
aitop --show-requests 응답 대기 요청 전체를 상세 패널·--json 에 보인다 (AITOP_SHOW_REQUESTS=1). 비밀값 가림은 최선일 뿐이라 명령 속 비밀값이 보일 수 있다
|
|
80
84
|
aitop --budget-day <달러> 하루 예산. 헤더에 오늘 $12.30/$50 처럼 보이고, 오늘 끝 예상 비용(오늘 + 최근 속도 × 자정까지, 늘 API 환산)이
|
|
81
85
|
80% 를 넘으면 '예상 $45', 100% 를 넘으면 '예상 $60!' 로 알린다 (AITOP_BUDGET_DAY, 설정 파일 budgetDay)
|
|
@@ -93,23 +97,30 @@ const HELP_KO = `{logo} aitop - 터미널에서 Claude Code · Codex · Antigrav
|
|
|
93
97
|
|
|
94
98
|
설정 파일: {configPath}
|
|
95
99
|
예) { "theme": "light", "icons": "plain", "bell": true, "notify": true, "onWaiting": "say 대기", "budgetDay": 50, "ambiguous": "wide", "hideIdleTools": false }
|
|
100
|
+
notify 에 ["waiting", "done", "context"] 처럼 종류를 주면 그 종류만 알린다. doneMinutes: done 알림 기준 작업 시간(분, 기본 3)
|
|
96
101
|
hideIdleTools: 실행 중 세션이 없고 7일 동안 쓰지 않은 도구를 헤더 아래 도구 줄에서 숨긴다 (기본 true, false 면 늘 셋 다)
|
|
102
|
+
claudeDirs, codexHomes: 읽을 Claude 설정 폴더·Codex 홈 목록 (예: ["~/.claude", "~/.claude-work"], 기본 ~/.claude, ~/.codex).
|
|
103
|
+
AITOP_CLAUDE_DIRS, AITOP_CODEX_HOMES 에 경로를 : (Windows 는 ;) 로 이어 주면 설정 파일보다 먼저 쓴다.
|
|
104
|
+
설정 파일 목록이 있으면 물려받은 CLAUDE_CONFIG_DIR, CODEX_HOME 은 쓰지 않는다 (없으면 그 경로를 읽는다)
|
|
97
105
|
onWaiting 은 파일 소유자가 나이고 그룹·다른 사용자가 쓸 수 없을 때(chmod 600)만 받는다.
|
|
98
106
|
옵션 > 환경 변수 > 설정 파일 순서로 정한다. 잘못된 값은 무시하고 --doctor 에 알린다.
|
|
99
107
|
|
|
100
108
|
{keys}
|
|
101
|
-
실시간 화면에서 ? 를 누르면 지금 화면의 키부터
|
|
109
|
+
실시간 화면에서 ? 를 누르면 지금 화면의 키부터 보인다
|
|
110
|
+
y 는 고른 세션을 이어 여는 명령을 OSC 52 로 클립보드에 복사한다. 지원하지 않는 터미널(tmux 는 set-clipboard on 필요)은 조용히 무시하니 상세 패널의 명령을 직접 복사한다`;
|
|
102
111
|
|
|
103
112
|
const HELP_EN = `{logo} aitop - watch Claude Code, Codex, Antigravity and Gemini sessions live in your terminal
|
|
104
113
|
|
|
105
114
|
aitop live screen
|
|
106
115
|
aitop --once print the current state once and exit
|
|
107
116
|
aitop --all also show sessions that ended in the last 24 hours
|
|
108
|
-
aitop --line print today's cost, waiting
|
|
109
|
-
|
|
117
|
+
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
|
|
118
|
+
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)
|
|
119
|
+
--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
120
|
Reads only the cache. With no cache it prints ... after 1.5 seconds. The running count and waiting Antigravity sessions
|
|
111
121
|
show only when the live screen, --once or --json left a summary in the last minute
|
|
112
122
|
aitop --json print the session list and usage totals as JSON once (works with --all)
|
|
123
|
+
Each session has resumeCmd, the command that reopens it (e.g. cd /repo && claude --resume <id>, null if none)
|
|
113
124
|
aitop --report daily [--by tool|model|project] [--days N] [--json] print daily tokens and cost (API list price) for the last N days
|
|
114
125
|
(default and max 30) by tool, model or project, then exit. Newest day first, total at the bottom. The first run reads 30 days of logs and may take a while
|
|
115
126
|
A project is the last folder name of the working directory. Columns beyond the terminal width are merged into (others)
|
|
@@ -119,8 +130,10 @@ const HELP_EN = `{logo} aitop - watch Claude Code, Codex, Antigravity and Gemini
|
|
|
119
130
|
aitop --doctor check Claude, Codex, Antigravity and Gemini logs, running processes and the config file (works with --json)
|
|
120
131
|
aitop --bell ring the terminal bell when a session starts waiting for you
|
|
121
132
|
aitop --notify show a desktop notification when a session starts waiting (notify-send or osascript, skipped if missing)
|
|
122
|
-
aitop --
|
|
123
|
-
|
|
133
|
+
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
|
|
134
|
+
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%)
|
|
135
|
+
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)
|
|
136
|
+
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
137
|
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
138
|
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
139
|
passes 80%, and in the warning color with ! past 100% (AITOP_BUDGET_DAY, config budgetDay)
|
|
@@ -138,12 +151,17 @@ const HELP_EN = `{logo} aitop - watch Claude Code, Codex, Antigravity and Gemini
|
|
|
138
151
|
|
|
139
152
|
Config file: {configPath}
|
|
140
153
|
e.g. { "theme": "light", "icons": "plain", "bell": true, "notify": true, "onWaiting": "say waiting", "budgetDay": 50, "ambiguous": "wide", "hideIdleTools": false, "lang": "en" }
|
|
154
|
+
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
155
|
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)
|
|
156
|
+
claudeDirs, codexHomes: Claude config folders and Codex homes to read (e.g. ["~/.claude", "~/.claude-work"], default ~/.claude, ~/.codex).
|
|
157
|
+
AITOP_CLAUDE_DIRS and AITOP_CODEX_HOMES take paths joined with : (; on Windows) and win over the config file.
|
|
158
|
+
With a config list, an inherited CLAUDE_CONFIG_DIR or CODEX_HOME is not used (without one, that path is read)
|
|
142
159
|
onWaiting is accepted only when you own the file and no group or other user can write it (chmod 600).
|
|
143
160
|
Order: option > env var > config file. Bad values are ignored and reported by --doctor.
|
|
144
161
|
|
|
145
162
|
{keys}
|
|
146
|
-
Press ? on the live screen to see the keys for the current view first
|
|
163
|
+
Press ? on the live screen to see the keys for the current view first
|
|
164
|
+
y copies the selected session's resume command to the clipboard with OSC 52. Terminals without it (tmux needs set-clipboard on) ignore it silently, so copy it from the detail panel`;
|
|
147
165
|
|
|
148
166
|
export const STRINGS = {
|
|
149
167
|
ko: {
|
|
@@ -170,6 +188,7 @@ export const STRINGS = {
|
|
|
170
188
|
'key.back': '뒤로',
|
|
171
189
|
'key.switchSession': '세션 바꾸기',
|
|
172
190
|
'key.close': '닫기',
|
|
191
|
+
'key.copy': '명령 복사',
|
|
173
192
|
'key.pick': '고르기',
|
|
174
193
|
'key.promptTab': '지시 탭',
|
|
175
194
|
'key.diff': 'diff',
|
|
@@ -196,6 +215,7 @@ export const STRINGS = {
|
|
|
196
215
|
'opt.budgetMissing': '--budget-day 값이 없습니다 (하루 예산, 달러)',
|
|
197
216
|
'opt.budgetBad': '--budget-day 값 {value} 이 잘못되었습니다 (0 보다 큰 수)',
|
|
198
217
|
'opt.onWaitingMissing': '--on-waiting 값이 없습니다 (실행할 명령)',
|
|
218
|
+
'opt.notifyBad': '--notify={value} 를 알 수 없습니다. 쉼표로 이은 {kinds} 중에서 고른다',
|
|
199
219
|
'opt.onWaitingDash': "--on-waiting 값이 - 로 시작합니다 ({value}). 명령이 맞으면 --on-waiting='{value}' 처럼 = 로 붙여 쓴다",
|
|
200
220
|
'opt.lineBad': '--line 값 {value} 이 잘못되었습니다 (plain 또는 tmux)',
|
|
201
221
|
'opt.lineWidthMissing': '--line-width 값이 없습니다 (글자 수)',
|
|
@@ -247,7 +267,9 @@ export const STRINGS = {
|
|
|
247
267
|
'cfg.shared': '그룹·다른 사용자가 쓸 수 있음 (mode {mode})',
|
|
248
268
|
'cfg.either': '{a} 또는 {b}',
|
|
249
269
|
'cfg.command': '실행할 명령 문자열',
|
|
270
|
+
'cfg.notify': 'true, false 또는 waiting·done·context 배열',
|
|
250
271
|
'cfg.positive': '0 보다 큰 수',
|
|
272
|
+
'cfg.paths': '절대 경로(또는 ~/...) 문자열 배열, 1~16개',
|
|
251
273
|
'cfg.file': '설정 파일: {path} ({state})',
|
|
252
274
|
'cfg.exists': '있음',
|
|
253
275
|
'cfg.missing': '없음',
|
|
@@ -261,6 +283,10 @@ export const STRINGS = {
|
|
|
261
283
|
'doctor.state.limited': '일부 지원',
|
|
262
284
|
'doctor.noFolder': '기록 폴더 없음',
|
|
263
285
|
'doctor.records': '기록 {n}개',
|
|
286
|
+
'doctor.dirMissing': '폴더 없음',
|
|
287
|
+
'doctor.candidate': '읽지 않는 기록 폴더 {path} (기록 {n}개)',
|
|
288
|
+
'doctor.candidateHintClaude': '읽으려면 설정 파일 claudeDirs 배열에 넣거나 AITOP_CLAUDE_DIRS 로 주세요 (예: ["~/.claude", "~/.claude-work"])',
|
|
289
|
+
'doctor.candidateHintCodex': '읽으려면 설정 파일 codexHomes 배열에 넣거나 AITOP_CODEX_HOMES 로 주세요 (예: ["~/.codex", "~/.codex-alt"])',
|
|
264
290
|
'doctor.last': '마지막 {ago} 전',
|
|
265
291
|
'doctor.runningUnknown': '실행 수 확인 불가 (Linux·WSL·macOS 만 지원)',
|
|
266
292
|
'doctor.running': '실행 {n}',
|
|
@@ -270,7 +296,7 @@ export const STRINGS = {
|
|
|
270
296
|
'doctor.hint.agyMissing': 'agy 를 한 번 실행하면 생깁니다 (Gemini 탭에 보입니다)',
|
|
271
297
|
'doctor.hint.gemini': '프로세스만 감지합니다 (세션·토큰은 아직 지원하지 않음)',
|
|
272
298
|
'doctor.hint.agyNode': 'Node {node} 에서는 기록을 읽기 전용으로 열 수 없어 프로세스만 감지합니다 (Node 22.15 이상 필요)',
|
|
273
|
-
'doctor.notifier': '✓ 알림 {kind} ({path}) · --notify 로 켬',
|
|
299
|
+
'doctor.notifier': '✓ 알림 {kind} ({path}) · --notify 로 켬 (끝남·context 경고는 --notify=waiting,done,context)',
|
|
274
300
|
'doctor.noNotifier': '○ 알림 {want} 없음 · --notify 를 켜도 알림을 건너뜀{wsl}',
|
|
275
301
|
'doctor.wsl': ' (WSL 은 notify-send 만 쓴다)',
|
|
276
302
|
'doctor.config': '{mark} 설정 {state}{path}',
|
|
@@ -363,6 +389,8 @@ export const STRINGS = {
|
|
|
363
389
|
'foot.showDetail': '상세 열기',
|
|
364
390
|
'foot.unpin': '고정 해제',
|
|
365
391
|
'foot.costMode': '비용 기준',
|
|
392
|
+
'foot.copied': '이어 여는 명령을 클립보드로 보냄 (OSC 52)',
|
|
393
|
+
'foot.copyNone': '이 세션은 이어 여는 명령이 없다',
|
|
366
394
|
'foot.clearSearch': '검색 지우기',
|
|
367
395
|
|
|
368
396
|
'help.title': '도움말 · ? 또는 Esc 로 닫기',
|
|
@@ -408,6 +436,7 @@ export const STRINGS = {
|
|
|
408
436
|
'hk.detail.switch': '다른 세션을 고르면 상세도 따라 바뀐다',
|
|
409
437
|
'hk.detail.files': '변경 파일 목록으로',
|
|
410
438
|
'hk.detail.close': '상세 패널 닫기',
|
|
439
|
+
'hk.detail.copy': '이어 여는 명령을 클립보드로 복사 (OSC 52, 지원하지 않는 터미널은 조용히 무시)',
|
|
411
440
|
'hk.files.pick': '파일 고르기',
|
|
412
441
|
'hk.files.tabs': '지시 탭: 이번 지시 · 편집이 있던 이전 지시 T번호 · 전체',
|
|
413
442
|
'hk.files.diff': '고른 파일의 diff 보기',
|
|
@@ -428,9 +457,10 @@ export const STRINGS = {
|
|
|
428
457
|
|
|
429
458
|
// 화면 안 도움말의 옵션 묶음 (help.mjs 의 OPTIONS). 값이 있는 옵션은 이름도 언어마다 다르다.
|
|
430
459
|
'hopt.onWaiting': '--on-waiting <명령>',
|
|
460
|
+
'hopt.notifyOpt': '--notify[=종류]',
|
|
431
461
|
'hopt.budgetDay': '--budget-day <달러>',
|
|
432
|
-
'hopt.notify': '응답
|
|
433
|
-
'hopt.onWaitingText': '
|
|
462
|
+
'hopt.notify': '응답 대기(·작업 끝남·context 90%)에 데스크톱 알림',
|
|
463
|
+
'hopt.onWaitingText': '알릴 일이 생기면 명령 실행 (AITOP_EVENT)',
|
|
434
464
|
'hopt.budgetDayText': '하루 예산. 헤더에 예상 비용 경고',
|
|
435
465
|
'hopt.showRequests': '응답 대기 요청 전체를 상세·--json 에',
|
|
436
466
|
'hopt.colorBlind': '적록 색약용 색 (대기·돈·경고를 노랑·파랑 계열로)',
|
|
@@ -478,6 +508,7 @@ export const STRINGS = {
|
|
|
478
508
|
'detail.sub': ' +서브{n}',
|
|
479
509
|
'detail.netTag': '캐시제외 ',
|
|
480
510
|
'detail.session': '세션',
|
|
511
|
+
'detail.resume': '이어 열기',
|
|
481
512
|
'detail.folder': '폴더',
|
|
482
513
|
'detail.branch': '브랜치',
|
|
483
514
|
'detail.model': '모델',
|
|
@@ -501,6 +532,12 @@ export const STRINGS = {
|
|
|
501
532
|
'notify.one': 'aitop: 응답 대기 ({tool})',
|
|
502
533
|
'notify.title': 'aitop: 응답 대기',
|
|
503
534
|
'notify.many': '{n}개 세션이 응답을 기다립니다',
|
|
535
|
+
'notify.done.one': 'aitop: 작업 끝남 ({tool})',
|
|
536
|
+
'notify.done.title': 'aitop: 작업 끝남',
|
|
537
|
+
'notify.done.many': '{n}개 세션이 다음 지시를 기다립니다',
|
|
538
|
+
'notify.context.one': 'aitop: context 90% 넘음 ({tool})',
|
|
539
|
+
'notify.context.title': 'aitop: context 90% 넘음',
|
|
540
|
+
'notify.context.many': '{n}개 세션의 context 가 90% 를 넘었습니다',
|
|
504
541
|
// Antigravity 소스가 요청 이름을 모를 때 넣는 대기 사유. --json 에는 이 한국어 그대로 나가고 화면에서만 바꾼다.
|
|
505
542
|
'phase.approve': '도구 허락',
|
|
506
543
|
},
|
|
@@ -527,6 +564,7 @@ export const STRINGS = {
|
|
|
527
564
|
'key.back': 'back',
|
|
528
565
|
'key.switchSession': 'switch session',
|
|
529
566
|
'key.close': 'close',
|
|
567
|
+
'key.copy': 'copy cmd',
|
|
530
568
|
'key.pick': 'pick',
|
|
531
569
|
'key.promptTab': 'prompt tabs',
|
|
532
570
|
'key.diff': 'diff',
|
|
@@ -553,6 +591,7 @@ export const STRINGS = {
|
|
|
553
591
|
'opt.budgetMissing': '--budget-day needs a value (daily budget in USD)',
|
|
554
592
|
'opt.budgetBad': 'bad --budget-day value {value} (a number above 0)',
|
|
555
593
|
'opt.onWaitingMissing': '--on-waiting needs a value (a command to run)',
|
|
594
|
+
'opt.notifyBad': 'unknown --notify={value}. Use a comma separated list of {kinds}',
|
|
556
595
|
'opt.onWaitingDash': "--on-waiting value starts with - ({value}). If it is the command, attach it with =, like --on-waiting='{value}'",
|
|
557
596
|
'opt.lineBad': 'bad --line value {value} (plain or tmux)',
|
|
558
597
|
'opt.lineWidthMissing': '--line-width needs a value (characters)',
|
|
@@ -603,7 +642,9 @@ export const STRINGS = {
|
|
|
603
642
|
'cfg.shared': 'group or other users can write it (mode {mode})',
|
|
604
643
|
'cfg.either': '{a} or {b}',
|
|
605
644
|
'cfg.command': 'a command string',
|
|
645
|
+
'cfg.notify': 'true, false or a list of waiting, done, context',
|
|
606
646
|
'cfg.positive': 'a number above 0',
|
|
647
|
+
'cfg.paths': 'a list of 1 to 16 absolute paths (or ~/...)',
|
|
607
648
|
'cfg.file': 'Config file: {path} ({state})',
|
|
608
649
|
'cfg.exists': 'found',
|
|
609
650
|
'cfg.missing': 'not found',
|
|
@@ -617,6 +658,10 @@ export const STRINGS = {
|
|
|
617
658
|
'doctor.state.limited': { long: 'partial support', short: 'partial' },
|
|
618
659
|
'doctor.noFolder': 'no log folder',
|
|
619
660
|
'doctor.records': { one: '{n} log', other: '{n} logs' },
|
|
661
|
+
'doctor.dirMissing': 'folder not found',
|
|
662
|
+
'doctor.candidate': { one: 'not read: {path} ({n} log)', other: 'not read: {path} ({n} logs)' },
|
|
663
|
+
'doctor.candidateHintClaude': 'to read it, add it to claudeDirs in the config file or AITOP_CLAUDE_DIRS (e.g. ["~/.claude", "~/.claude-work"])',
|
|
664
|
+
'doctor.candidateHintCodex': 'to read it, add it to codexHomes in the config file or AITOP_CODEX_HOMES (e.g. ["~/.codex", "~/.codex-alt"])',
|
|
620
665
|
'doctor.last': 'last {ago} ago',
|
|
621
666
|
'doctor.runningUnknown': 'cannot count running (Linux, WSL and macOS only)',
|
|
622
667
|
'doctor.running': 'running {n}',
|
|
@@ -626,7 +671,7 @@ export const STRINGS = {
|
|
|
626
671
|
'doctor.hint.agyMissing': 'created after you run agy once (shown in the Gemini tab)',
|
|
627
672
|
'doctor.hint.gemini': 'detects processes only (sessions and tokens not supported yet)',
|
|
628
673
|
'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',
|
|
674
|
+
'doctor.notifier': '✓ notify {kind} ({path}) · turn on with --notify (done and context alerts: --notify=waiting,done,context)',
|
|
630
675
|
'doctor.noNotifier': '○ notify {want} not found · --notify will skip notifications{wsl}',
|
|
631
676
|
'doctor.wsl': ' (WSL uses notify-send only)',
|
|
632
677
|
'doctor.config': '{mark} config {state}{path}',
|
|
@@ -717,6 +762,8 @@ export const STRINGS = {
|
|
|
717
762
|
'foot.showDetail': 'show detail',
|
|
718
763
|
'foot.unpin': 'unpin',
|
|
719
764
|
'foot.costMode': 'cost',
|
|
765
|
+
'foot.copied': 'resume command sent to clipboard (OSC 52)',
|
|
766
|
+
'foot.copyNone': 'no resume command for this session',
|
|
720
767
|
'foot.clearSearch': 'clear search',
|
|
721
768
|
|
|
722
769
|
'help.title': 'Help · ? or Esc to close',
|
|
@@ -761,6 +808,7 @@ export const STRINGS = {
|
|
|
761
808
|
'hk.detail.switch': 'Pick another session, the detail follows',
|
|
762
809
|
'hk.detail.files': 'Open the changed files',
|
|
763
810
|
'hk.detail.close': 'Close the detail panel',
|
|
811
|
+
'hk.detail.copy': 'Copy the resume command to the clipboard (OSC 52, terminals without it ignore it silently)',
|
|
764
812
|
'hk.files.pick': 'Pick a file',
|
|
765
813
|
'hk.files.tabs': 'Prompt tabs: latest, earlier (T number), all',
|
|
766
814
|
'hk.files.diff': 'View the diff of the file',
|
|
@@ -780,9 +828,10 @@ export const STRINGS = {
|
|
|
780
828
|
'hk.common.quit': 'Quit',
|
|
781
829
|
|
|
782
830
|
'hopt.onWaiting': '--on-waiting <cmd>',
|
|
831
|
+
'hopt.notifyOpt': '--notify[=kinds]',
|
|
783
832
|
'hopt.budgetDay': '--budget-day <usd>',
|
|
784
|
-
'hopt.notify': 'Desktop alert
|
|
785
|
-
'hopt.onWaitingText': 'Run a command
|
|
833
|
+
'hopt.notify': 'Desktop alert on waiting (or done, context 90%)',
|
|
834
|
+
'hopt.onWaitingText': 'Run a command on alerts (AITOP_EVENT)',
|
|
786
835
|
'hopt.budgetDayText': 'Daily budget, warns in the header',
|
|
787
836
|
'hopt.showRequests': 'Show full waiting requests',
|
|
788
837
|
'hopt.colorBlind': 'Red-green color blind palette',
|
|
@@ -829,6 +878,7 @@ export const STRINGS = {
|
|
|
829
878
|
'detail.sub': ' +sub{n}',
|
|
830
879
|
'detail.netTag': 'no cache ',
|
|
831
880
|
'detail.session': 'Session',
|
|
881
|
+
'detail.resume': 'Resume',
|
|
832
882
|
'detail.folder': 'Folder',
|
|
833
883
|
'detail.branch': 'Branch',
|
|
834
884
|
'detail.model': 'Model',
|
|
@@ -851,6 +901,12 @@ export const STRINGS = {
|
|
|
851
901
|
'notify.one': 'aitop: waiting ({tool})',
|
|
852
902
|
'notify.title': 'aitop: waiting',
|
|
853
903
|
'notify.many': { one: '{n} session is waiting for you', other: '{n} sessions are waiting for you' },
|
|
904
|
+
'notify.done.one': 'aitop: done ({tool})',
|
|
905
|
+
'notify.done.title': 'aitop: done',
|
|
906
|
+
'notify.done.many': { one: '{n} session finished its work', other: '{n} sessions finished their work' },
|
|
907
|
+
'notify.context.one': 'aitop: context over 90% ({tool})',
|
|
908
|
+
'notify.context.title': 'aitop: context over 90%',
|
|
909
|
+
'notify.context.many': { one: '{n} session passed 90% context', other: '{n} sessions passed 90% context' },
|
|
854
910
|
'phase.approve': 'Approve tool',
|
|
855
911
|
},
|
|
856
912
|
};
|
package/src/json.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { projectBudget } from './budget.mjs';
|
|
2
2
|
import { toolsJson } from './doctor.mjs';
|
|
3
3
|
import { phaseText } from './i18n.mjs';
|
|
4
|
+
import { resumeCmd } from './resume.mjs';
|
|
4
5
|
|
|
5
6
|
// aitop --json 출력. 다른 스크립트나 AI 가 읽기 쉬운 모양으로 세션 목록과 사용량 합계를 담는다.
|
|
6
7
|
// 텍스트는 수집 단계에서 이미 비밀값 가림이 적용돼 있다.
|
|
@@ -45,6 +46,8 @@ export function toJson(data, version = null, opts = {}) {
|
|
|
45
46
|
phase: koPhase(s.phase),
|
|
46
47
|
phaseKind: s.phase?.kind ?? null,
|
|
47
48
|
waitingFor: s.waitingFor ?? null,
|
|
49
|
+
// 이 세션을 이어 여는 셸 명령 (resume.mjs). 만들 수 없으면 null.
|
|
50
|
+
resumeCmd: resumeCmd(s),
|
|
48
51
|
// 허락을 기다리는 요청의 전체 내용 (Bash 명령, 파일 경로 등). --show-requests 를 켰을 때만 넣는다. 비밀값 가림은 최선을 다할 뿐이다.
|
|
49
52
|
...(opts.showRequests ? { waitDetail: s.waitDetail ?? null } : {}),
|
|
50
53
|
now: s.now || null,
|
package/src/keys.mjs
CHANGED
|
@@ -142,6 +142,8 @@ export function onKey(view, key, act) {
|
|
|
142
142
|
else if (key === 'p') {
|
|
143
143
|
if (view.selectedId != null && !view.focus) view.pins = togglePin(view.pins, view.selectedId);
|
|
144
144
|
}
|
|
145
|
+
// y: 고른 세션을 이어 여는 명령을 복사한다 (bin 이 OSC 52 로 쓴다). 세션에는 아무것도 보내지 않는다.
|
|
146
|
+
else if (key === 'y') act.copy?.(selectedSession(view));
|
|
145
147
|
else if (key === 'c') view.costMode = view.costMode === 'net' ? 'api' : 'net';
|
|
146
148
|
else if (key === 'd') {
|
|
147
149
|
// view.rows: 마지막으로 그린 화면 높이. 'auto' 일 때 지금 보이는 상태를 뒤집는 데 쓴다.
|
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 를 넘으면 뒤 항목부터
|
|
58
|
-
|
|
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({
|
|
63
|
-
if (waiting > 0) parts.push({
|
|
64
|
-
if (running > 0) parts.push({
|
|
65
|
-
if (!zero(perHour)) parts.push({
|
|
66
|
-
while (parts.length && parts.map((p) => p.
|
|
67
|
-
|
|
68
|
-
|
|
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 은 세션 파일에서 지금
|
|
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
|
-
|
|
76
|
-
|
|
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 {
|
|
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 }),
|
|
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
|
-
//
|
|
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
|
-
|
|
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) {
|
|
@@ -124,13 +151,23 @@ export function waitingEnv(s) {
|
|
|
124
151
|
};
|
|
125
152
|
}
|
|
126
153
|
|
|
154
|
+
// 알림 본문의 세션 이름: 사용자가 붙인 이름(/rename, thread_name)이 있으면 그것, 없으면 예전처럼 프로젝트.
|
|
155
|
+
const whoOf = (s) => s.customName || s.project || s.id || '';
|
|
156
|
+
|
|
127
157
|
// 알림 제목·본문은 화면 언어를 따른다 (AITOP_WAITING_FOR 와 달리 사람이 읽는 글이라).
|
|
128
|
-
|
|
158
|
+
// kind 가 done·context 면 그 종류의 문구를 쓴다. context 본문에는 사용률(%)을 붙인다.
|
|
159
|
+
export function notifyText(sessions, lang = getLang(), kind = 'waiting') {
|
|
129
160
|
const o = { lang };
|
|
161
|
+
if (kind !== 'waiting') {
|
|
162
|
+
if (sessions.length !== 1) return { title: t(`notify.${kind}.title`, null, o), body: t(`notify.${kind}.many`, { n: sessions.length }, o) };
|
|
163
|
+
const s = sessions[0];
|
|
164
|
+
const pct = s.context?.window > 0 ? ` · ${Math.round(((s.context.used ?? 0) / s.context.window) * 100)}%` : '';
|
|
165
|
+
return { title: t(`notify.${kind}.one`, { tool: s.tool ?? '?' }, o), body: stripControl(`${whoOf(s)}${kind === 'context' ? pct : ''}`) };
|
|
166
|
+
}
|
|
130
167
|
if (sessions.length === 1) {
|
|
131
168
|
const s = sessions[0];
|
|
132
169
|
const label = waitingLabel(s, lang);
|
|
133
|
-
return { title: t('notify.one', { tool: s.tool ?? '?' }, o), body: stripControl(`${s
|
|
170
|
+
return { title: t('notify.one', { tool: s.tool ?? '?' }, o), body: stripControl(`${whoOf(s)}${label ? ' · ' + label : ''}`) };
|
|
134
171
|
}
|
|
135
172
|
return { title: t('notify.title', null, o), body: t('notify.many', { n: sessions.length }, o) };
|
|
136
173
|
}
|
|
@@ -234,7 +271,8 @@ export function createRunner({ timeoutMs = HOOK_TIMEOUT_MS, spawnFn = spawn } =
|
|
|
234
271
|
};
|
|
235
272
|
}
|
|
236
273
|
|
|
237
|
-
// --notify, --on-waiting 을 묶은 알리미.
|
|
274
|
+
// --notify, --on-waiting 을 묶은 알리미. 알릴 세션 목록과 종류(waiting·done·context)를 받는다.
|
|
275
|
+
// --on-waiting 명령에는 AITOP_EVENT 로 종류를 넘긴다 (예전 명령은 waiting 만 받으므로 그대로 동작한다).
|
|
238
276
|
export function createNotifier({ notify = false, onWaiting = null, notifier = notify ? findNotifier() : null, env = process.env, timeoutMs = HOOK_TIMEOUT_MS, spawnFn = spawn } = {}) {
|
|
239
277
|
const hook = onWaiting ? createRunner({ timeoutMs, spawnFn }) : null;
|
|
240
278
|
const desk = notify && notifier ? createRunner({ timeoutMs, spawnFn }) : null;
|
|
@@ -245,14 +283,14 @@ export function createNotifier({ notify = false, onWaiting = null, notifier = no
|
|
|
245
283
|
hook?.killAll();
|
|
246
284
|
desk?.killAll();
|
|
247
285
|
},
|
|
248
|
-
fire(fresh) {
|
|
286
|
+
fire(fresh, kind = 'waiting') {
|
|
249
287
|
if (!fresh.length) return;
|
|
250
288
|
if (desk) {
|
|
251
|
-
const { title, body } = notifyText(fresh);
|
|
289
|
+
const { title, body } = notifyText(fresh, getLang(), kind);
|
|
252
290
|
const [file, args] = notifierCommand(notifier, title, body);
|
|
253
291
|
desk.run({ file, args, env });
|
|
254
292
|
}
|
|
255
|
-
if (hook) for (const s of fresh) hook.run({ file: '/bin/sh', args: ['-c', onWaiting], env: { ...env, ...waitingEnv(s) } });
|
|
293
|
+
if (hook) for (const s of fresh) hook.run({ file: '/bin/sh', args: ['-c', onWaiting], env: { ...env, ...waitingEnv(s), AITOP_EVENT: kind } });
|
|
256
294
|
},
|
|
257
295
|
};
|
|
258
296
|
}
|
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
|
|
193
|
-
|
|
194
|
-
|
|
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 별로 기억한다.
|