@sejuneoh/aitop 0.29.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 +9 -1
- package/bin/aitop.mjs +20 -0
- package/package.json +1 -1
- package/src/config.mjs +14 -5
- package/src/doctor.mjs +52 -19
- package/src/help.mjs +2 -1
- package/src/i18n.mjs +32 -2
- package/src/json.mjs +3 -0
- package/src/keys.mjs +2 -0
- package/src/notify.mjs +5 -2
- package/src/resume.mjs +57 -0
- package/src/sources/claude-ledger.mjs +55 -45
- package/src/sources/claude-tracker.mjs +45 -2
- package/src/sources/claude.mjs +138 -64
- 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/ui/chrome.mjs +14 -2
- package/src/ui/detail.mjs +36 -1
package/README.md
CHANGED
|
@@ -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
|
|
|
@@ -75,6 +77,8 @@ aitop --on-waiting 'my-hook.sh' run a command with /bin/sh -c for the same
|
|
|
75
77
|
|
|
76
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.
|
|
77
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
|
+
|
|
78
82
|
### tmux status line
|
|
79
83
|
|
|
80
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.
|
|
@@ -90,6 +94,10 @@ Keys: `↑↓` select · `n` next session to check · `/` search · `s` sort ·
|
|
|
90
94
|
|
|
91
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).
|
|
92
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
|
+
|
|
93
101
|
## License
|
|
94
102
|
|
|
95
103
|
[MIT](https://github.com/SejuneOh/aitop/blob/main/LICENSE)
|
package/bin/aitop.mjs
CHANGED
|
@@ -83,6 +83,9 @@ process.env.AITOP_COLOR_BLIND = opt.colorBlind ? '1' : '0';
|
|
|
83
83
|
if (config.values.icons.source === 'file') process.env.AITOP_ICONS = opt.icons;
|
|
84
84
|
// 폭이 모호한 기호를 2칸으로 셀지는 글자 폭 계산(text.mjs)이 쓴다. 화면 모듈은 그릴 때마다 이 값을 본다.
|
|
85
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 });
|
|
86
89
|
const { BRAND, userVarsSeq } = await import('../src/brand.mjs');
|
|
87
90
|
const { keysText } = await import('../src/help.mjs');
|
|
88
91
|
const { debug, initLog, logPath } = await import('../src/log.mjs');
|
|
@@ -209,6 +212,7 @@ const { createAttention, updateAttention, markSeen, nextAttention, windowTitle,
|
|
|
209
212
|
const { createNotifier } = await import('../src/notify.mjs');
|
|
210
213
|
const { onKey, fixFocus } = await import('../src/keys.mjs');
|
|
211
214
|
const { admit, createLoading, latchReady } = await import('../src/loading.mjs');
|
|
215
|
+
const { osc52, resumeCmd } = await import('../src/resume.mjs');
|
|
212
216
|
|
|
213
217
|
// 요청 전체 보기는 기본으로 꺼 둔다. 켜지 않으면 상세 패널에도 --json 에도 나가지 않는다.
|
|
214
218
|
const showRequests = opt.showRequests;
|
|
@@ -402,8 +406,24 @@ function keepSelectionVisible() {
|
|
|
402
406
|
if (list.length && !list.some((s) => s.id === view.selectedId)) select(list[0].id);
|
|
403
407
|
}
|
|
404
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
|
+
|
|
405
424
|
stdin.setEncoding('utf8');
|
|
406
425
|
const act = {
|
|
426
|
+
copy,
|
|
407
427
|
quit,
|
|
408
428
|
refresh,
|
|
409
429
|
move,
|
package/package.json
CHANGED
package/src/config.mjs
CHANGED
|
@@ -4,11 +4,12 @@
|
|
|
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
11
|
import { EVENT_KINDS } from './notify.mjs';
|
|
12
|
+
import { DIR_ENV, pathLike, splitPaths } from './sources/dirs.mjs';
|
|
12
13
|
|
|
13
14
|
const bool = (v) => typeof v === 'boolean';
|
|
14
15
|
const oneOf = (...xs) => (v) => xs.includes(v);
|
|
@@ -47,6 +48,8 @@ export function budgetDayOption(argv) {
|
|
|
47
48
|
}
|
|
48
49
|
|
|
49
50
|
const BOOL = ['true', 'false'];
|
|
51
|
+
// 기록 폴더 목록: 절대 경로(또는 ~ 로 시작) 문자열 배열, 1~16개.
|
|
52
|
+
const pathList = (v) => Array.isArray(v) && v.length > 0 && v.length <= 16 && v.every(pathLike);
|
|
50
53
|
// expect, envExpect: 둘 중 하나면 [a, b], 아니면 i18n 키. 문구는 쓸 때 지금 언어로 만든다.
|
|
51
54
|
const expectText = (x) => (Array.isArray(x) ? t('cfg.either', { a: x[0], b: x[1] }) : t(x));
|
|
52
55
|
|
|
@@ -74,6 +77,10 @@ export const KEYS = {
|
|
|
74
77
|
ambiguous: { ok: oneOf('narrow', 'wide'), expect: ['narrow', 'wide'], def: 'narrow', env: ['AITOP_AMBIGUOUS', (v) => (v === 'narrow' || v === 'wide' ? v : undefined)], envProblem: true },
|
|
75
78
|
// --help·--doctor·오류 문구의 언어(i18n.mjs). 기본값은 로캘(LC_ALL > LC_MESSAGES > LANG)이 ko 로 시작하면 ko, 아니면 en.
|
|
76
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)] },
|
|
77
84
|
};
|
|
78
85
|
|
|
79
86
|
// Windows 는 XDG_CONFIG_HOME 이 없으면 %APPDATA%\aitop\config.json.
|
|
@@ -159,8 +166,10 @@ export function resolveConfig({ flags = {}, env = process.env, file } = {}) {
|
|
|
159
166
|
const fromEnv = spec.env && env[spec.env[0]] != null ? spec.env[1](env[spec.env[0]]) : undefined;
|
|
160
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) }));
|
|
161
168
|
if (flags[key] !== undefined) values[key] = { value: flags[key], source: 'flag' };
|
|
162
|
-
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' };
|
|
163
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] };
|
|
164
173
|
// 기본값이 함수면 환경에서 고른다 (lang 은 로캘).
|
|
165
174
|
else values[key] = { value: typeof spec.def === 'function' ? spec.def(env) : spec.def, source: 'default' };
|
|
166
175
|
}
|
|
@@ -171,9 +180,9 @@ export function resolveConfig({ flags = {}, env = process.env, file } = {}) {
|
|
|
171
180
|
export function configText(cfg) {
|
|
172
181
|
const out = [t('cfg.file', { path: stripControl(cfg.path), state: t(cfg.exists ? 'cfg.exists' : 'cfg.missing') }), ''];
|
|
173
182
|
for (const [key, { value, source }] of Object.entries(cfg.values)) {
|
|
174
|
-
// 배열(notify 의
|
|
175
|
-
const v = value == null ? (key === 'theme' ? 'auto' : '-') : typeof value === 'string' ? JSON.stringify(value) : Array.isArray(value) ? value.join(',') : String(value);
|
|
176
|
-
out.push(`${key.padEnd(14)}${v.padEnd(12)} ${source}`);
|
|
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})` : ''}`);
|
|
177
186
|
}
|
|
178
187
|
if (cfg.problems.length) out.push('', ...cfg.problems.map((p) => `! ${stripControl(p)}`));
|
|
179
188
|
return out.join('\n');
|
package/src/doctor.mjs
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// 가장 최근 기록을 읽을 수 있는지. aitop --doctor, 빈 화면, --json 의 tools 가 같은 결과를 쓴다.
|
|
3
3
|
// 기록 내용은 읽어 내보내지 않는다 (Gemini 는 형식 확인용으로 JSON 키 이름만 보인다).
|
|
4
4
|
import { readdirSync, readFileSync, statSync, existsSync, openSync, readSync, closeSync } from 'node:fs';
|
|
5
|
-
import { join } from 'node:path';
|
|
5
|
+
import { basename, join } from 'node:path';
|
|
6
6
|
import { homedir, platform } from 'node:os';
|
|
7
7
|
import { findProcesses, isCodex, isGemini, isAgy, canListProcesses, isAlive, isSessionAlive } from './procs.mjs';
|
|
8
8
|
import { AGY_ROOT } from './sources/antigravity.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).
|
|
@@ -112,23 +111,49 @@ function liveSessionFile(path) {
|
|
|
112
111
|
}
|
|
113
112
|
}
|
|
114
113
|
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
const
|
|
119
|
-
const
|
|
120
|
-
|
|
121
|
-
: null;
|
|
122
|
-
|
|
123
|
-
|
|
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 };
|
|
124
128
|
}
|
|
125
129
|
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
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);
|
|
129
153
|
const running = canListProcesses() ? findProcesses(isCodex).length : null;
|
|
130
|
-
|
|
131
|
-
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 };
|
|
132
157
|
}
|
|
133
158
|
|
|
134
159
|
// Gemini 는 세션 기록 형식을 아직 모른다. 프로세스만 세고, 기록 폴더가 있으면 형식 확인용 키 이름을 남긴다.
|
|
@@ -179,10 +204,12 @@ export function hintOf(r, lang = 'ko') {
|
|
|
179
204
|
return null;
|
|
180
205
|
}
|
|
181
206
|
|
|
182
|
-
|
|
207
|
+
// home: 후보 폴더를 찾을 홈 폴더 (테스트에서 바꿔 끼운다).
|
|
208
|
+
export function checkTools({ home = HOME } = {}) {
|
|
209
|
+
const cand = candidateDirs({ home });
|
|
183
210
|
const tools = {};
|
|
184
211
|
for (const fn of [claude, codex, gemini, agy]) {
|
|
185
|
-
const r = fn();
|
|
212
|
+
const r = fn === claude ? claude(cand.claude) : fn === codex ? codex(cand.codex) : fn();
|
|
186
213
|
r.hint = hintOf(r, 'ko');
|
|
187
214
|
tools[r.tool] = r;
|
|
188
215
|
}
|
|
@@ -232,8 +259,14 @@ export function doctorText(result, version, now = Date.now(), lang = getLang())
|
|
|
232
259
|
for (const t of Object.values(result.tools)) {
|
|
233
260
|
const d = describe(t, now, lang);
|
|
234
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)}`);
|
|
235
264
|
out.push(` ${d.detail}`);
|
|
236
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
|
+
}
|
|
237
270
|
}
|
|
238
271
|
if ('notifier' in result) out.push('', notifierText(result.notifier, result.platform, lang));
|
|
239
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
|
},
|
|
@@ -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.
|
package/src/i18n.mjs
CHANGED
|
@@ -67,6 +67,7 @@ const HELP_KO = `{logo} aitop - 터미널에서 Claude Code · Codex · Antigrav
|
|
|
67
67
|
캐시만 읽는다. 캐시가 없어 1.5초 안에 못 읽으면 ... 을 낸다. 작업 중 수와 Antigravity 의 대기 수는
|
|
68
68
|
1분 안에 aitop 화면·--once·--json 이 남긴 요약이 있을 때만 보인다
|
|
69
69
|
aitop --json 세션 목록과 사용량 합계를 JSON 으로 한 번 출력한다 (--all 과 함께 쓸 수 있다)
|
|
70
|
+
세션마다 resumeCmd 에 그 세션을 이어 여는 명령을 넣는다 (예: cd /repo && claude --resume <id>, 없으면 null)
|
|
70
71
|
aitop --report daily [--by tool|model|project] [--days N] [--json] 최근 N일(기본·최대 30)의 날짜별 토큰·비용(API 정가 환산)을
|
|
71
72
|
도구별·모델별·프로젝트별 표로 내고 끝낸다. 최근 날짜가 위, 맨 아래는 합계. 처음 실행은 30일치 기록을 읽느라 오래 걸릴 수 있다
|
|
72
73
|
프로젝트는 작업 폴더의 마지막 이름이고, 열이 터미널 폭을 넘으면 비용이 작은 쪽을 (그 외) 로 합친다
|
|
@@ -98,11 +99,15 @@ const HELP_KO = `{logo} aitop - 터미널에서 Claude Code · Codex · Antigrav
|
|
|
98
99
|
예) { "theme": "light", "icons": "plain", "bell": true, "notify": true, "onWaiting": "say 대기", "budgetDay": 50, "ambiguous": "wide", "hideIdleTools": false }
|
|
99
100
|
notify 에 ["waiting", "done", "context"] 처럼 종류를 주면 그 종류만 알린다. doneMinutes: done 알림 기준 작업 시간(분, 기본 3)
|
|
100
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 은 쓰지 않는다 (없으면 그 경로를 읽는다)
|
|
101
105
|
onWaiting 은 파일 소유자가 나이고 그룹·다른 사용자가 쓸 수 없을 때(chmod 600)만 받는다.
|
|
102
106
|
옵션 > 환경 변수 > 설정 파일 순서로 정한다. 잘못된 값은 무시하고 --doctor 에 알린다.
|
|
103
107
|
|
|
104
108
|
{keys}
|
|
105
|
-
실시간 화면에서 ? 를 누르면 지금 화면의 키부터
|
|
109
|
+
실시간 화면에서 ? 를 누르면 지금 화면의 키부터 보인다
|
|
110
|
+
y 는 고른 세션을 이어 여는 명령을 OSC 52 로 클립보드에 복사한다. 지원하지 않는 터미널(tmux 는 set-clipboard on 필요)은 조용히 무시하니 상세 패널의 명령을 직접 복사한다`;
|
|
106
111
|
|
|
107
112
|
const HELP_EN = `{logo} aitop - watch Claude Code, Codex, Antigravity and Gemini sessions live in your terminal
|
|
108
113
|
|
|
@@ -115,6 +120,7 @@ const HELP_EN = `{logo} aitop - watch Claude Code, Codex, Antigravity and Gemini
|
|
|
115
120
|
Reads only the cache. With no cache it prints ... after 1.5 seconds. The running count and waiting Antigravity sessions
|
|
116
121
|
show only when the live screen, --once or --json left a summary in the last minute
|
|
117
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)
|
|
118
124
|
aitop --report daily [--by tool|model|project] [--days N] [--json] print daily tokens and cost (API list price) for the last N days
|
|
119
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
|
|
120
126
|
A project is the last folder name of the working directory. Columns beyond the terminal width are merged into (others)
|
|
@@ -147,11 +153,15 @@ const HELP_EN = `{logo} aitop - watch Claude Code, Codex, Antigravity and Gemini
|
|
|
147
153
|
e.g. { "theme": "light", "icons": "plain", "bell": true, "notify": true, "onWaiting": "say waiting", "budgetDay": 50, "ambiguous": "wide", "hideIdleTools": false, "lang": "en" }
|
|
148
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
|
|
149
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)
|
|
150
159
|
onWaiting is accepted only when you own the file and no group or other user can write it (chmod 600).
|
|
151
160
|
Order: option > env var > config file. Bad values are ignored and reported by --doctor.
|
|
152
161
|
|
|
153
162
|
{keys}
|
|
154
|
-
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`;
|
|
155
165
|
|
|
156
166
|
export const STRINGS = {
|
|
157
167
|
ko: {
|
|
@@ -178,6 +188,7 @@ export const STRINGS = {
|
|
|
178
188
|
'key.back': '뒤로',
|
|
179
189
|
'key.switchSession': '세션 바꾸기',
|
|
180
190
|
'key.close': '닫기',
|
|
191
|
+
'key.copy': '명령 복사',
|
|
181
192
|
'key.pick': '고르기',
|
|
182
193
|
'key.promptTab': '지시 탭',
|
|
183
194
|
'key.diff': 'diff',
|
|
@@ -258,6 +269,7 @@ export const STRINGS = {
|
|
|
258
269
|
'cfg.command': '실행할 명령 문자열',
|
|
259
270
|
'cfg.notify': 'true, false 또는 waiting·done·context 배열',
|
|
260
271
|
'cfg.positive': '0 보다 큰 수',
|
|
272
|
+
'cfg.paths': '절대 경로(또는 ~/...) 문자열 배열, 1~16개',
|
|
261
273
|
'cfg.file': '설정 파일: {path} ({state})',
|
|
262
274
|
'cfg.exists': '있음',
|
|
263
275
|
'cfg.missing': '없음',
|
|
@@ -271,6 +283,10 @@ export const STRINGS = {
|
|
|
271
283
|
'doctor.state.limited': '일부 지원',
|
|
272
284
|
'doctor.noFolder': '기록 폴더 없음',
|
|
273
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"])',
|
|
274
290
|
'doctor.last': '마지막 {ago} 전',
|
|
275
291
|
'doctor.runningUnknown': '실행 수 확인 불가 (Linux·WSL·macOS 만 지원)',
|
|
276
292
|
'doctor.running': '실행 {n}',
|
|
@@ -373,6 +389,8 @@ export const STRINGS = {
|
|
|
373
389
|
'foot.showDetail': '상세 열기',
|
|
374
390
|
'foot.unpin': '고정 해제',
|
|
375
391
|
'foot.costMode': '비용 기준',
|
|
392
|
+
'foot.copied': '이어 여는 명령을 클립보드로 보냄 (OSC 52)',
|
|
393
|
+
'foot.copyNone': '이 세션은 이어 여는 명령이 없다',
|
|
376
394
|
'foot.clearSearch': '검색 지우기',
|
|
377
395
|
|
|
378
396
|
'help.title': '도움말 · ? 또는 Esc 로 닫기',
|
|
@@ -418,6 +436,7 @@ export const STRINGS = {
|
|
|
418
436
|
'hk.detail.switch': '다른 세션을 고르면 상세도 따라 바뀐다',
|
|
419
437
|
'hk.detail.files': '변경 파일 목록으로',
|
|
420
438
|
'hk.detail.close': '상세 패널 닫기',
|
|
439
|
+
'hk.detail.copy': '이어 여는 명령을 클립보드로 복사 (OSC 52, 지원하지 않는 터미널은 조용히 무시)',
|
|
421
440
|
'hk.files.pick': '파일 고르기',
|
|
422
441
|
'hk.files.tabs': '지시 탭: 이번 지시 · 편집이 있던 이전 지시 T번호 · 전체',
|
|
423
442
|
'hk.files.diff': '고른 파일의 diff 보기',
|
|
@@ -489,6 +508,7 @@ export const STRINGS = {
|
|
|
489
508
|
'detail.sub': ' +서브{n}',
|
|
490
509
|
'detail.netTag': '캐시제외 ',
|
|
491
510
|
'detail.session': '세션',
|
|
511
|
+
'detail.resume': '이어 열기',
|
|
492
512
|
'detail.folder': '폴더',
|
|
493
513
|
'detail.branch': '브랜치',
|
|
494
514
|
'detail.model': '모델',
|
|
@@ -544,6 +564,7 @@ export const STRINGS = {
|
|
|
544
564
|
'key.back': 'back',
|
|
545
565
|
'key.switchSession': 'switch session',
|
|
546
566
|
'key.close': 'close',
|
|
567
|
+
'key.copy': 'copy cmd',
|
|
547
568
|
'key.pick': 'pick',
|
|
548
569
|
'key.promptTab': 'prompt tabs',
|
|
549
570
|
'key.diff': 'diff',
|
|
@@ -623,6 +644,7 @@ export const STRINGS = {
|
|
|
623
644
|
'cfg.command': 'a command string',
|
|
624
645
|
'cfg.notify': 'true, false or a list of waiting, done, context',
|
|
625
646
|
'cfg.positive': 'a number above 0',
|
|
647
|
+
'cfg.paths': 'a list of 1 to 16 absolute paths (or ~/...)',
|
|
626
648
|
'cfg.file': 'Config file: {path} ({state})',
|
|
627
649
|
'cfg.exists': 'found',
|
|
628
650
|
'cfg.missing': 'not found',
|
|
@@ -636,6 +658,10 @@ export const STRINGS = {
|
|
|
636
658
|
'doctor.state.limited': { long: 'partial support', short: 'partial' },
|
|
637
659
|
'doctor.noFolder': 'no log folder',
|
|
638
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"])',
|
|
639
665
|
'doctor.last': 'last {ago} ago',
|
|
640
666
|
'doctor.runningUnknown': 'cannot count running (Linux, WSL and macOS only)',
|
|
641
667
|
'doctor.running': 'running {n}',
|
|
@@ -736,6 +762,8 @@ export const STRINGS = {
|
|
|
736
762
|
'foot.showDetail': 'show detail',
|
|
737
763
|
'foot.unpin': 'unpin',
|
|
738
764
|
'foot.costMode': 'cost',
|
|
765
|
+
'foot.copied': 'resume command sent to clipboard (OSC 52)',
|
|
766
|
+
'foot.copyNone': 'no resume command for this session',
|
|
739
767
|
'foot.clearSearch': 'clear search',
|
|
740
768
|
|
|
741
769
|
'help.title': 'Help · ? or Esc to close',
|
|
@@ -780,6 +808,7 @@ export const STRINGS = {
|
|
|
780
808
|
'hk.detail.switch': 'Pick another session, the detail follows',
|
|
781
809
|
'hk.detail.files': 'Open the changed files',
|
|
782
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)',
|
|
783
812
|
'hk.files.pick': 'Pick a file',
|
|
784
813
|
'hk.files.tabs': 'Prompt tabs: latest, earlier (T number), all',
|
|
785
814
|
'hk.files.diff': 'View the diff of the file',
|
|
@@ -849,6 +878,7 @@ export const STRINGS = {
|
|
|
849
878
|
'detail.sub': ' +sub{n}',
|
|
850
879
|
'detail.netTag': 'no cache ',
|
|
851
880
|
'detail.session': 'Session',
|
|
881
|
+
'detail.resume': 'Resume',
|
|
852
882
|
'detail.folder': 'Folder',
|
|
853
883
|
'detail.branch': 'Branch',
|
|
854
884
|
'detail.model': 'Model',
|
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/notify.mjs
CHANGED
|
@@ -151,6 +151,9 @@ export function waitingEnv(s) {
|
|
|
151
151
|
};
|
|
152
152
|
}
|
|
153
153
|
|
|
154
|
+
// 알림 본문의 세션 이름: 사용자가 붙인 이름(/rename, thread_name)이 있으면 그것, 없으면 예전처럼 프로젝트.
|
|
155
|
+
const whoOf = (s) => s.customName || s.project || s.id || '';
|
|
156
|
+
|
|
154
157
|
// 알림 제목·본문은 화면 언어를 따른다 (AITOP_WAITING_FOR 와 달리 사람이 읽는 글이라).
|
|
155
158
|
// kind 가 done·context 면 그 종류의 문구를 쓴다. context 본문에는 사용률(%)을 붙인다.
|
|
156
159
|
export function notifyText(sessions, lang = getLang(), kind = 'waiting') {
|
|
@@ -159,12 +162,12 @@ export function notifyText(sessions, lang = getLang(), kind = 'waiting') {
|
|
|
159
162
|
if (sessions.length !== 1) return { title: t(`notify.${kind}.title`, null, o), body: t(`notify.${kind}.many`, { n: sessions.length }, o) };
|
|
160
163
|
const s = sessions[0];
|
|
161
164
|
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
|
|
165
|
+
return { title: t(`notify.${kind}.one`, { tool: s.tool ?? '?' }, o), body: stripControl(`${whoOf(s)}${kind === 'context' ? pct : ''}`) };
|
|
163
166
|
}
|
|
164
167
|
if (sessions.length === 1) {
|
|
165
168
|
const s = sessions[0];
|
|
166
169
|
const label = waitingLabel(s, lang);
|
|
167
|
-
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 : ''}`) };
|
|
168
171
|
}
|
|
169
172
|
return { title: t('notify.title', null, o), body: t('notify.many', { n: sessions.length }, o) };
|
|
170
173
|
}
|
package/src/resume.mjs
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// 고른 세션을 다른 터미널에서 이어 여는 명령과 OSC 52 클립보드 복사 (#214).
|
|
2
|
+
// 명령을 보이고 복사만 한다. 세션에는 아무것도 보내지 않는다 (읽기 전용).
|
|
3
|
+
|
|
4
|
+
import { stripControl } from './text.mjs';
|
|
5
|
+
import { homeEnv } from './sources/dirs.mjs';
|
|
6
|
+
|
|
7
|
+
// 제어 문자(C0, DEL, C1, 폭 0·방향 바꿈 글자)와 탭·줄바꿈을 지운다. 줄바꿈이 섞이면 붙여 넣을 때 명령이 바로 실행될 수 있다.
|
|
8
|
+
export const stripControls = (s) => stripControl(s).replace(/[\t\n]/g, '');
|
|
9
|
+
|
|
10
|
+
// POSIX 셸 따옴표. 안전한 글자만 있으면 그대로, 아니면 '...' 로 감싸고 ' 는 '\'' 로 바꾼다.
|
|
11
|
+
export function shellQuote(s) {
|
|
12
|
+
const v = stripControls(s);
|
|
13
|
+
// = 로 시작하는 단어는 zsh 가 명령 경로로 바꾸므로(=cmd) 따옴표로 감싼다.
|
|
14
|
+
if (v && /^[A-Za-z0-9_@%+:,./-][A-Za-z0-9_@%+=:,./-]*$/.test(v)) return v;
|
|
15
|
+
return `'${v.replace(/'/g, `'\\''`)}'`;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// Codex 기록 파일 이름(rollout-2025-...-<uuid>.jsonl)에서 세션 UUID 를 꺼낸다. `codex resume <UUID>` 가 받는 값이다.
|
|
19
|
+
const UUID = /([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:\.jsonl)?$/i;
|
|
20
|
+
export const codexId = (id) => UUID.exec(String(id ?? ''))?.[1] ?? null;
|
|
21
|
+
// Claude 세션 id 는 UUID 다. 그 밖의 값(예: --dangerously-skip-permissions)은 옵션으로 읽힐 수 있어 받지 않는다.
|
|
22
|
+
const isUuid = (id) => /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id);
|
|
23
|
+
// agy 대화 id 도 UUID 다 (conversations/<UUID>.db, 2026-11-16 이 PC 의 파일 이름 모양으로 확인).
|
|
24
|
+
|
|
25
|
+
// 도구별 이어 열기 인자. 알 수 없으면 null.
|
|
26
|
+
// claude: claude --resume <UUID> (작업 폴더를 알 때만)
|
|
27
|
+
// codex: codex resume <id> (codex-cli 0.107 의 `codex resume --help` 로 확인)
|
|
28
|
+
// antigravity(agy, tool 'gemini' 이고 id 가 대화 id): agy --conversation <id> (agy --help 로 확인)
|
|
29
|
+
// Gemini CLI 와 기록 없이 프로세스만 본 세션(pid-·agy- id)은 id 가 없어 null.
|
|
30
|
+
function resumeArgs(s) {
|
|
31
|
+
const id = stripControls(s.id);
|
|
32
|
+
if (!id || /^(pid|agy)-/.test(id)) return null;
|
|
33
|
+
// Claude 는 작업 폴더별로 기록을 찾으므로 폴더를 모르면 다른 폴더에서는 찾지 못한다. 그때는 만들지 않는다.
|
|
34
|
+
if (s.tool === 'claude') return isUuid(id) && stripControls(s.cwd) ? ['claude', '--resume', id] : null;
|
|
35
|
+
if (s.tool === 'codex') {
|
|
36
|
+
const u = codexId(id);
|
|
37
|
+
return u ? ['codex', 'resume', u] : null;
|
|
38
|
+
}
|
|
39
|
+
if (s.tool === 'gemini') return isUuid(id) ? ['agy', '--conversation', id] : null;
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// 세션을 이어 여는 한 줄 명령. 작업 폴더를 알면 cd 를 앞에 붙인다. 만들 수 없으면 null.
|
|
44
|
+
export function resumeCmd(s) {
|
|
45
|
+
if (!s) return null;
|
|
46
|
+
const args = resumeArgs(s);
|
|
47
|
+
if (!args) return null;
|
|
48
|
+
// 기본 폴더가 아닌 설정 폴더(#212)의 세션은 그 폴더를 변수로 집어 줘야 도구가 기록을 찾는다.
|
|
49
|
+
const kind = s.tool === 'claude' ? 'claude' : s.tool === 'codex' ? 'codex' : null;
|
|
50
|
+
const env = kind ? homeEnv(kind, stripControls(s.home)) : null;
|
|
51
|
+
const run = (env ? `${env[0]}=${shellQuote(env[1])} ` : '') + args.map(shellQuote).join(' ');
|
|
52
|
+
const cwd = stripControls(s.cwd);
|
|
53
|
+
return cwd ? `cd ${shellQuote(cwd)} && ${run}` : run;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// OSC 52 클립보드 쓰기: ESC ] 52 ; c ; <base64> BEL. 터미널이 지원하지 않으면 조용히 무시된다.
|
|
57
|
+
export const osc52 = (text) => `\x1b]52;c;${Buffer.from(String(text), 'utf8').toString('base64')}\x07`;
|