@sejuneoh/aitop 0.27.0 → 0.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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/log.mjs CHANGED
@@ -4,7 +4,8 @@
4
4
  // 꺼져 있으면 파일을 만들지 않고 debug() 는 바로 돌아간다.
5
5
  import { closeSync, constants, fchmodSync, fstatSync, mkdirSync, openSync, renameSync, statSync, writeSync } from 'node:fs';
6
6
  import { homedir } from 'node:os';
7
- import { basename, dirname, isAbsolute, join } from 'node:path';
7
+ import { basename, dirname, posix, win32 } from 'node:path';
8
+ import { appDir } from './paths.mjs';
8
9
  import { mask, stripControl } from './text.mjs';
9
10
 
10
11
  // 이 크기를 넘으면 aitop.log.1 로 옮기고 새로 쓴다 (이전 것 하나만 남긴다).
@@ -14,9 +15,9 @@ export const MAX_BYTES = 1024 * 1024;
14
15
  export const REPEAT_MS = 60_000;
15
16
  const MAX_KEYS = 1000;
16
17
 
17
- export function logPath(env = process.env, home = homedir()) {
18
- const xdg = env.XDG_STATE_HOME;
19
- return join(xdg && isAbsolute(xdg) ? xdg : join(home, '.local', 'state'), 'aitop', 'aitop.log');
18
+ // Windows 는 XDG_STATE_HOME 이 없으면 %LOCALAPPDATA%\aitop\state\aitop.log.
19
+ export function logPath(env = process.env, home = homedir(), platform = process.platform) {
20
+ return (platform === 'win32' ? win32 : posix).join(appDir('state', { env, home, platform }), 'aitop.log');
20
21
  }
21
22
 
22
23
  let state = { on: false, path: null };
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/order.mjs CHANGED
@@ -5,6 +5,7 @@
5
5
  // 고정(p)한 세션은 응답 대기 바로 아래에 고정한 순서대로 둔다. 정렬을 바꿔도 그 순서는 바뀌지 않고, 묶을 때는 '고정' 묶음 하나로 모은다.
6
6
  // 응답 대기를 고정보다 위에 두는 것은 사람이 할 일이 고정 목록에 가려지지 않게 하려는 것이다. 고정한 세션이 응답 대기가 되면 대기 쪽으로 올라간다.
7
7
  import { costOf } from './ui/draw.mjs';
8
+ import { lastName } from './paths.mjs';
8
9
 
9
10
  export const SORTS = ['default', 'cost', 'context', 'recent'];
10
11
  export const GROUPS = ['none', 'project', 'tool'];
@@ -41,7 +42,7 @@ export function compare(sort, costMode = 'api', ready = true) {
41
42
  return (a, b) => ended(a) - ended(b) || key(b, costMode) - key(a, costMode);
42
43
  }
43
44
 
44
- const projectOf = (s) => s.project || String(s.cwd ?? '').split('/').filter(Boolean).at(-1) || NO_FOLDER;
45
+ const projectOf = (s) => s.project || lastName(s.cwd) || NO_FOLDER;
45
46
  const GROUP_KEY = { project: projectOf, tool: (s) => s.tool ?? '?' };
46
47
 
47
48
  // 돌려주는 sessions 는 화면에 그리는 순서 그대로다 (↑↓·n 도 이 순서를 따른다).
package/src/paths.mjs ADDED
@@ -0,0 +1,61 @@
1
+ // OS 마다 다른 경로 규칙을 한곳에 모은다. platform 과 env 를 받아서 테스트가 win32 를 흉내 낼 수 있다.
2
+ import path from 'node:path';
3
+ import { homedir } from 'node:os';
4
+
5
+ const pathFor = (plat) => (plat === 'win32' ? path.win32 : path.posix);
6
+
7
+ // 경로의 마지막 이름. win32 는 / 와 \ 를 모두 나누고, 그 밖의 OS 는 예전처럼 / 만 나눈다.
8
+ export const lastName = (p, plat = process.platform) =>
9
+ String(p ?? '')
10
+ .split(plat === 'win32' ? /[\\/]+/ : '/')
11
+ .filter(Boolean)
12
+ .at(-1) ?? '';
13
+
14
+ // 실행 파일 이름. win32 는 마지막 이름에서 .exe·.cmd·.bat·.ps1 을 떼고, 그 밖의 OS 는 예전처럼 마지막 / 뒤 그대로.
15
+ export const exeName = (p, plat = process.platform) =>
16
+ plat === 'win32' ? lastName(p, plat).replace(/\.(exe|cmd|bat|ps1)$/i, '') : String(p).split('/').pop();
17
+
18
+ // home 아래 경로를 ~ 로 줄인다. win32 는 드라이브 문자·대소문자를 무시하고 \ 와 / 를 같게 본다.
19
+ export function tildeIn(p, home = homedir(), plat = process.platform) {
20
+ const s = String(p ?? '');
21
+ const win = plat === 'win32';
22
+ const norm = (x) => (win ? x.replace(/\//g, '\\').toLowerCase() : x);
23
+ const h = String(home ?? '').replace(win ? /[\\/]+$/ : /\/+$/, '');
24
+ if (!h || s.length < h.length) return s;
25
+ if (norm(s.slice(0, h.length)) !== norm(h)) return s;
26
+ const rest = s.slice(h.length);
27
+ if (rest === '') return '~';
28
+ const sepOk = win ? /^[\\/]/.test(rest) : rest.startsWith('/');
29
+ return sepOk ? '~' + rest : s;
30
+ }
31
+
32
+ // 절대 경로인 환경 변수 값만 쓴다.
33
+ const absEnv = (env, key, plat) => {
34
+ const v = env[key];
35
+ return v && pathFor(plat).isAbsolute(v) ? v : null;
36
+ };
37
+
38
+ // aitop 이 쓰는 폴더(끝이 aitop 또는 aitop\<종류>). XDG_* 가 있으면 어느 OS 든 그것을 쓴다.
39
+ // Linux·macOS: ~/.cache/aitop, ~/.local/state/aitop, ~/.config/aitop
40
+ // Windows: %LOCALAPPDATA%\aitop\cache, %LOCALAPPDATA%\aitop\state, %APPDATA%\aitop
41
+ export function appDir(kind, { env = process.env, home = homedir(), platform = process.platform } = {}) {
42
+ const { join } = pathFor(platform);
43
+ const win = platform === 'win32';
44
+ const local = () => absEnv(env, 'LOCALAPPDATA', platform) ?? join(home, 'AppData', 'Local');
45
+ if (kind === 'cache') {
46
+ // 캐시는 예전부터 XDG_CACHE_HOME 을 절대 경로인지 보지 않고 썼다. 그대로 둔다.
47
+ if (env.XDG_CACHE_HOME != null) return join(env.XDG_CACHE_HOME, 'aitop');
48
+ return win ? join(local(), 'aitop', 'cache') : join(home, '.cache', 'aitop');
49
+ }
50
+ if (kind === 'state') {
51
+ const xdg = absEnv(env, 'XDG_STATE_HOME', platform);
52
+ if (xdg) return join(xdg, 'aitop');
53
+ return win ? join(local(), 'aitop', 'state') : join(home, '.local', 'state', 'aitop');
54
+ }
55
+ if (kind === 'config') {
56
+ const xdg = absEnv(env, 'XDG_CONFIG_HOME', platform);
57
+ if (xdg) return join(xdg, 'aitop');
58
+ return win ? join(absEnv(env, 'APPDATA', platform) ?? join(home, 'AppData', 'Roaming'), 'aitop') : join(home, '.config', 'aitop');
59
+ }
60
+ throw new Error(`unknown dir kind: ${kind}`);
61
+ }
package/src/procs.mjs CHANGED
@@ -3,6 +3,7 @@
3
3
  import { readdirSync, readFileSync, readlinkSync, existsSync } from 'node:fs';
4
4
  import { execFileSync } from 'node:child_process';
5
5
  import { platform } from 'node:os';
6
+ import { exeName } from './paths.mjs';
6
7
 
7
8
  const OS = platform();
8
9
  const HAS_PROC = existsSync('/proc/self');
@@ -24,12 +25,15 @@ export function isAlive(pid) {
24
25
 
25
26
  // ps 는 인자를 공백으로만 이어 보여 준다. 앞 두 칸(실행 파일, node 스크립트)이 없는 절대 경로면
26
27
  // 실제로 있는 경로가 될 때까지 뒤 토큰을 이어 붙인다 (예: ~/Library/Application Support/…/codex.js).
28
+ // 절대 경로: /… 또는 드라이브 문자(C:\…, C:/…).
29
+ const isAbs = (p) => p.startsWith('/') || /^[A-Za-z]:[\\/]/.test(p);
30
+
27
31
  export function joinPaths(tokens, exists = existsSync) {
28
32
  const out = [];
29
33
  let i = 0;
30
34
  while (i < tokens.length) {
31
35
  let cur = tokens[i++];
32
- if (out.length < 2 && cur.startsWith('/') && !exists(cur)) {
36
+ if (out.length < 2 && isAbs(cur) && !exists(cur)) {
33
37
  let j = i;
34
38
  let joined = cur;
35
39
  while (j < tokens.length && j - i < 8) {
@@ -133,7 +137,8 @@ export function findProcesses(match) {
133
137
  return found.map((p) => ({ ...p, cwd: cwdOf(p.pid) }));
134
138
  }
135
139
 
136
- const base = (p) => p.split('/').pop();
140
+ // 실행 파일 이름 (paths.mjs exeName). Windows 에서만 \ 도 나누고 .exe·.cmd 등을 뗀다 (codex.cmd, agy.exe).
141
+ const base = (p) => exeName(p);
137
142
 
138
143
  // `codex` 는 node 스크립트(…/bin/codex.js)이거나 네이티브 바이너리(codex-*)로 뜬다.
139
144
  export function isCodex(argv) {
@@ -171,6 +176,33 @@ let ticksPerSec = null;
171
176
  let bootMs = null;
172
177
 
173
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
+
174
206
  function procStartLinux(pid) {
175
207
  if (bootMs === null) {
176
208
  const m = /^btime (\d+)$/m.exec(readFileSync('/proc/stat', 'utf8'));
@@ -184,9 +216,26 @@ function procStartLinux(pid) {
184
216
  ticksPerSec = 100;
185
217
  }
186
218
  }
187
- const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
188
- const ticks = Number(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[19]);
189
- 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);
190
239
  }
191
240
 
192
241
  // 프로세스가 시작한 시각(ms). 알 수 없으면 null. 시작 시각은 바뀌지 않으므로 pid 별로 기억한다.
@@ -522,7 +522,9 @@ export function cwdOf(workspaceUris) {
522
522
  try {
523
523
  const first = JSON.parse(workspaceUris || '[]')[0];
524
524
  if (!first) return null;
525
- return first.startsWith('file:') ? fileURLToPath(first) : first;
525
+ const p = first.startsWith('file:') ? fileURLToPath(first) : first;
526
+ // Windows 의 file:///c%3A/… 는 c:\… 가 되므로 드라이브 문자를 대문자로 맞춘다 (Claude·Codex 의 C:\ 와 같은 프로젝트로 묶이게).
527
+ return process.platform === 'win32' ? p.replace(/^[a-z](?=:)/, (d) => d.toUpperCase()) : p;
526
528
  } catch (e) {
527
529
  debug('agy', 'workspace_uris parse failed', e);
528
530
  return null;
@@ -747,6 +749,8 @@ export function collectAgy({ showEnded, budget }) {
747
749
  now: g.lastTool ?? g.events.at(-1)?.text ?? '',
748
750
  startedAt: null,
749
751
  updatedAt: r.updatedAt ?? Date.now(),
752
+ // 대기 시작 시각 (--line 요약용). 기록에 시각이 없으면 지금 시각으로 메우지 않고 null.
753
+ waitSince: wait ? (r.updatedAt ?? null) : null,
750
754
  tokens,
751
755
  context: { used: g.prompt, window: contextWindow(g.model, g.prompt) },
752
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 }) {
@@ -4,18 +4,23 @@ import { join, basename } from 'node:path';
4
4
  import { homedir } from 'node:os';
5
5
  import { JsonlTail } from '../tail.mjs';
6
6
  import { loadCache, markDirty } from '../cache.mjs';
7
- import { findProcesses, isCodex, openFiles, processStart } from '../procs.mjs';
7
+ import { canListProcesses, findProcesses, isCodex, openFiles, processStart } from '../procs.mjs';
8
8
  import { addActivity, emptyTokens, parseTs, pushEvent, describeTool, isNoisePrompt } from './common.mjs';
9
9
  import { addChange, mergeFiles } from './files.mjs';
10
10
  import { codexCost } from '../pricing.mjs';
11
11
  import { parsePatch, extractPatch, patchSucceeded } from './patch.mjs';
12
12
  import { debug, debugIo } from '../log.mjs';
13
+ import { lastName } from '../paths.mjs';
13
14
 
14
15
  // 지시 탭에 쓰는 지시 목록은 최근 것만 남긴다.
15
16
  const MAX_TURNS = 50;
16
17
 
17
18
  const ROOT = join(process.env.CODEX_HOME ?? join(homedir(), '.codex'), 'sessions');
18
19
  const RECENT_MS = 24 * 3600 * 1000;
20
+ // 프로세스 목록을 못 얻는 OS(지금은 Windows)에서는 이 시간 안에 바뀐 기록을 실행 중으로 본다.
21
+ // codex 는 답할 때마다 기록에 쓰므로, 답을 읽고 다음 지시를 쓰는 동안(대개 몇 분)은 남고 닫은 세션은 곧 빠진다.
22
+ // Claude 팀원의 MEMBER_STALE_MS(15분)보다 짧게 둔다. 실제 프로세스가 없으니 끝난 세션이 오래 남는 쪽이 더 헷갈린다.
23
+ export const NO_PROC_LIVE_MS = 10 * 60_000;
19
24
 
20
25
  const states = new Map();
21
26
 
@@ -280,11 +285,14 @@ function applyLine(st, x) {
280
285
 
281
286
  export const _test = { newState, applyLine, phaseOf, snapshot };
282
287
 
283
- export function collectCodex({ showEnded, budget, filesOf = openFiles, startOf = processStart }) {
284
- const procs = findProcesses(isCodex);
285
- if (!procs.length && !showEnded) return [];
288
+ export function collectCodex({ showEnded, budget, filesOf = openFiles, startOf = processStart, canList = canListProcesses }) {
289
+ // 프로세스를 못 세면 숨기지 않고 최근에 바뀐 기록으로 판정한다 (pid 는 null).
290
+ const blind = !canList();
291
+ const procs = blind ? [] : findProcesses(isCodex);
292
+ if (!procs.length && !showEnded && !blind) return [];
286
293
 
287
- const files = recentFiles();
294
+ const fresh = (f) => Date.now() - f.mtime <= NO_PROC_LIVE_MS;
295
+ const files = blind && !showEnded ? recentFiles().filter(fresh) : recentFiles();
288
296
  const read = (path) => {
289
297
  let st = states.get(path);
290
298
  if (!st) states.set(path, (st = newState(path)));
@@ -336,6 +344,8 @@ export function collectCodex({ showEnded, budget, filesOf = openFiles, startOf =
336
344
  }
337
345
  }
338
346
 
347
+ if (blind) for (const f of files) if (fresh(f)) liveByPath.set(f.path, null);
348
+
339
349
  const seen = new Set(files.map((f) => f.path));
340
350
  for (const path of states.keys()) if (!seen.has(path)) states.delete(path);
341
351
 
@@ -353,9 +363,9 @@ export function collectCodex({ showEnded, budget, filesOf = openFiles, startOf =
353
363
  id: st.id,
354
364
  pid: pid ?? null,
355
365
  kind: 'interactive',
356
- name: basename(st.cwd ?? '') || 'codex',
366
+ name: lastName(st.cwd) || 'codex',
357
367
  cwd: st.cwd,
358
- project: basename(st.cwd ?? ''),
368
+ project: lastName(st.cwd),
359
369
  branch: st.branch,
360
370
  model: st.model,
361
371
  live,
@@ -381,7 +391,7 @@ export function collectCodex({ showEnded, budget, filesOf = openFiles, startOf =
381
391
  // 아직 세션 파일을 만들지 않은(첫 입력 전) codex 프로세스도 보여 준다.
382
392
  for (const [cwd, pids] of slots) {
383
393
  for (const pid of pids) {
384
- out.push({ tool: 'codex', id: `pid-${pid}`, pid, kind: 'interactive', name: basename(cwd ?? '') || 'codex', cwd, project: basename(cwd ?? ''), live: true, status: 'idle', phase: { kind: 'idle', msg: 'firstInput' }, cost: null, now: '', updatedAt: Date.now(), tokens: emptyTokens(), context: { used: 0, window: 0 }, events: [], members: [] });
394
+ out.push({ tool: 'codex', id: `pid-${pid}`, pid, kind: 'interactive', name: lastName(cwd) || 'codex', cwd, project: lastName(cwd), live: true, status: 'idle', phase: { kind: 'idle', msg: 'firstInput' }, cost: null, now: '', updatedAt: Date.now(), tokens: emptyTokens(), context: { used: 0, window: 0 }, events: [], members: [] });
385
395
  }
386
396
  }
387
397
  return out;