@sejuneoh/aitop 0.22.0 → 0.23.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/json.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  import { projectBudget } from './budget.mjs';
2
2
  import { toolsJson } from './doctor.mjs';
3
+ import { phaseText } from './i18n.mjs';
3
4
 
4
5
  // aitop --json 출력. 다른 스크립트나 AI 가 읽기 쉬운 모양으로 세션 목록과 사용량 합계를 담는다.
5
6
  // 텍스트는 수집 단계에서 이미 비밀값 가림이 적용돼 있다.
@@ -18,6 +19,9 @@ const usageOf = (u) => (u ? { ...u, ...('cost' in u ? { cost: money(u.cost) } :
18
19
  // version 은 aitop 버전, tools 는 aitop --doctor 와 같은 도구별 점검 결과다.
19
20
  // opts.showRequests: 응답 대기 요청 전체(waitDetail)를 넣는다. 기본은 꺼져 있다.
20
21
  // opts.budgetDay: 하루 예산. 있으면 usage.budget 에 예산, 오늘 끝 예상 비용(API 정가 환산, 화면과 같은 기준), 단계를 넣는다.
22
+ // --json 의 phase 문구. 한국어 표로 만든다 (영어 화면 1/3 의 계약).
23
+ const koPhase = (p) => (p?.kind ? phaseText(p, { lang: 'ko' }) : null);
24
+
21
25
  export function toJson(data, version = null, opts = {}) {
22
26
  const b = data.usage ? projectBudget(data.usage, opts.budgetDay, { now: data.at ?? Date.now() }) : null;
23
27
  return {
@@ -37,7 +41,9 @@ export function toJson(data, version = null, opts = {}) {
37
41
  pid: s.pid ?? null,
38
42
  live: Boolean(s.live),
39
43
  status: s.status,
40
- phase: s.phase?.text ?? null,
44
+ // phase 는 화면 언어와 상관없이 늘 한국어 문구(예전과 같은 글)로 두고, 언어와 상관없는 상태 이름은 phaseKind 로 준다.
45
+ phase: koPhase(s.phase),
46
+ phaseKind: s.phase?.kind ?? null,
41
47
  waitingFor: s.waitingFor ?? null,
42
48
  // 허락을 기다리는 요청의 전체 내용 (Bash 명령, 파일 경로 등). --show-requests 를 켰을 때만 넣는다. 비밀값 가림은 최선을 다할 뿐이다.
43
49
  ...(opts.showRequests ? { waitDetail: s.waitDetail ?? null } : {}),
@@ -51,7 +57,7 @@ export function toJson(data, version = null, opts = {}) {
51
57
  context: { used: s.context?.used ?? 0, window: s.context?.window ?? null },
52
58
  // 변경 내용(diff)은 넣지 않고 파일별 통계만 넣는다. 줄 수는 편집마다 더한 누적값이다 (git diff 아님).
53
59
  files: (s.files ?? []).map((f) => ({ path: f.path, created: Boolean(f.created), edits: f.edits, writtenLines: f.add, deletedLines: f.del, updatedAt: iso(f.at), agents: f.agents ?? [] })),
54
- members: (s.members ?? []).map((m) => ({ name: m.name, task: m.task ?? null, model: m.model ?? null, status: m.status, phase: m.phase?.text ?? null, tokens: m.tokens ?? 0, cost: money(m.cost) })),
60
+ members: (s.members ?? []).map((m) => ({ name: m.name, task: m.task ?? null, model: m.model ?? null, status: m.status, phase: koPhase(m.phase), phaseKind: m.phase?.kind ?? null, tokens: m.tokens ?? 0, cost: money(m.cost) })),
55
61
  })),
56
62
  };
57
63
  }
package/src/line.mjs CHANGED
@@ -1,6 +1,8 @@
1
1
  // aitop --line: tmux 상태줄 같은 곳에 넣을 한 줄 요약. 예) $54.13/$50 wait 2 $3.1/h
2
2
  // 글자는 ASCII 만 쓴다 (이모지·폭이 모호한 기호는 tmux 에서 칸이 어긋난다). 표기는 짧은 영어 약어로 고정하고 번역하지 않는다.
3
3
  // 색은 --line=tmux 일 때 tmux 서식(#[fg=colourN])으로만 넣고 ANSI 코드는 쓰지 않는다. NO_COLOR 면 서식도 넣지 않는다.
4
+ // 옵션 오류 문구만 i18n 으로 지금 언어를 따른다.
5
+ import { t } from './i18n.mjs';
4
6
 
5
7
  export const MODES = ['plain', 'tmux'];
6
8
  export const DEFAULT_WIDTH = 40;
@@ -24,7 +26,7 @@ export function lineOption(argv) {
24
26
  if (m) {
25
27
  const v = m[1] ?? 'plain';
26
28
  if (MODES.includes(v)) mode = v;
27
- else error ??= `--line 값 ${JSON.stringify(v)} 이 잘못되었습니다 (plain 또는 tmux)`;
29
+ else error ??= t('opt.lineBad', { value: JSON.stringify(v) });
28
30
  continue;
29
31
  }
30
32
  const w = /^--line-width(?:=(.*))?$/.exec(a);
@@ -35,7 +37,7 @@ export function lineOption(argv) {
35
37
  const raw = w[1] ?? (argv[i + 1]?.startsWith('-') ? '' : (argv[++i] ?? ''));
36
38
  const n = /^\d+$/.test(raw) ? Number(raw) : NaN;
37
39
  if (n > 0) width = n;
38
- else error ??= raw === '' ? '--line-width 값이 없습니다 (글자 수)' : `--line-width 값 ${JSON.stringify(raw)} 이 잘못되었습니다 (0 보다 큰 정수)`;
40
+ else error ??= raw === '' ? t('opt.lineWidthMissing') : t('opt.lineWidthBad', { value: JSON.stringify(raw) });
39
41
  }
40
42
  return { mode, width, rest, error };
41
43
  }
package/src/notify.mjs CHANGED
@@ -4,6 +4,7 @@ import { spawn } from 'node:child_process';
4
4
  import { accessSync, constants, readFileSync } from 'node:fs';
5
5
  import { join, delimiter } from 'node:path';
6
6
  import { mask, stripControl } from './text.mjs';
7
+ import { getLang, phaseText, t } from './i18n.mjs';
7
8
 
8
9
  export const HOOK_TIMEOUT_MS = 10_000;
9
10
  const LABEL_MAX = 120;
@@ -42,8 +43,8 @@ export function notifyOptions(argv, config = {}, valueOpts = VALUE_OPTS) {
42
43
  continue;
43
44
  }
44
45
  const v = m[1] ?? (i + 1 < argv.length ? argv[++i] : '');
45
- if (!v.trim()) error = '--on-waiting 값이 없습니다 (실행할 명령)';
46
- else if (m[1] == null && v.startsWith('-')) error = `--on-waiting 값이 - 로 시작합니다 (${v}). 명령이 맞으면 --on-waiting='${v}' 처럼 = 로 붙여 쓴다`;
46
+ if (!v.trim()) error = t('opt.onWaitingMissing');
47
+ else if (m[1] == null && v.startsWith('-')) error = t('opt.onWaitingDash', { value: v });
47
48
  else onWaiting = v;
48
49
  }
49
50
  return { notify, onWaiting, rest, error };
@@ -103,8 +104,11 @@ export function notifierCommand(notifier, title, body) {
103
104
  const escapeMarkup = (t) => String(t).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
104
105
 
105
106
  // 세션에서 짧은 대기 사유. "응답 대기 · Bash" → "Bash". 비밀값처럼 보이는 것은 가린다.
106
- export function waitingLabel(s) {
107
- const text = String(s.phase?.kind === 'waiting' ? (s.phase.text ?? '') : '').replace(/^응답 대기(?: · )?/, '');
107
+ // AITOP_WAITING_FOR 로도 넘기는 값이라 기본은 화면 언어와 상관없이 예전과 같은 한국어 문구다. 알림 본문은 lang 으로 화면 언어를 준다.
108
+ // 요청도 에이전트도 없으면 빈 글.
109
+ export function waitingLabel(s, lang = 'ko') {
110
+ const a = s.phase?.args ?? {};
111
+ const text = s.phase?.kind === 'waiting' && (a.what || a.agents) ? phaseText(s.phase, { lang, short: true }) : '';
108
112
  const one = stripControl(text).replace(/\s+/g, ' ').trim();
109
113
  return mask(one.length > LABEL_MAX ? one.slice(0, LABEL_MAX - 1) + '…' : one);
110
114
  }
@@ -120,13 +124,15 @@ export function waitingEnv(s) {
120
124
  };
121
125
  }
122
126
 
123
- export function notifyText(sessions) {
127
+ // 알림 제목·본문은 화면 언어를 따른다 (AITOP_WAITING_FOR 와 달리 사람이 읽는 글이라).
128
+ export function notifyText(sessions, lang = getLang()) {
129
+ const o = { lang };
124
130
  if (sessions.length === 1) {
125
131
  const s = sessions[0];
126
- const label = waitingLabel(s);
127
- return { title: `aitop: 응답 대기 (${s.tool ?? '?'})`, body: stripControl(`${s.project ?? s.id ?? ''}${label ? ' · ' + label : ''}`) };
132
+ const label = waitingLabel(s, lang);
133
+ return { title: t('notify.one', { tool: s.tool ?? '?' }, o), body: stripControl(`${s.project ?? s.id ?? ''}${label ? ' · ' + label : ''}`) };
128
134
  }
129
- return { title: 'aitop: 응답 대기', body: `${sessions.length}개 세션이 응답을 기다립니다` };
135
+ return { title: t('notify.title', null, o), body: t('notify.many', { n: sessions.length }, o) };
130
136
  }
131
137
 
132
138
  // 한 번에 하나만 실행하는 자식 프로세스 실행기.
package/src/order.mjs CHANGED
@@ -8,10 +8,11 @@ import { costOf } from './ui/draw.mjs';
8
8
 
9
9
  export const SORTS = ['default', 'cost', 'context', 'recent'];
10
10
  export const GROUPS = ['none', 'project', 'tool'];
11
- export const SORT_LABEL = { default: '기본', cost: '비용', context: '컨텍스트', recent: '최근' };
12
- export const GROUP_LABEL = { none: '없음', project: '프로젝트', tool: '도구' };
13
11
  export const WAITING_GROUP = '응답 대기';
14
12
  export const PINNED_GROUP = '고정';
13
+ // 폴더를 모르는 세션의 프로젝트 묶음 이름. 응답 대기·고정·폴더 없음 이름은 묶음 키라 ko 로 두고 화면(ui/table.mjs groupRow)이 지금 언어로 바꾼다.
14
+ // 정렬·묶기 이름(s:비용 g:프로젝트)은 i18n.mjs 의 sort.*·groupBy.* 에 있다.
15
+ export const NO_FOLDER = '(폴더 없음)';
15
16
 
16
17
  // pins 에 id 가 있으면 빼고, 없으면 끝에 붙인다 (고정한 순서를 지킨다). 새 배열을 돌려준다.
17
18
  export const togglePin = (pins = [], id) => (pins.includes(id) ? pins.filter((x) => x !== id) : [...pins, id]);
@@ -35,7 +36,7 @@ export function compare(sort, costMode = 'api') {
35
36
  return (a, b) => ended(a) - ended(b) || key(b, costMode) - key(a, costMode);
36
37
  }
37
38
 
38
- const projectOf = (s) => s.project || String(s.cwd ?? '').split('/').filter(Boolean).at(-1) || '(폴더 없음)';
39
+ const projectOf = (s) => s.project || String(s.cwd ?? '').split('/').filter(Boolean).at(-1) || NO_FOLDER;
39
40
  const GROUP_KEY = { project: projectOf, tool: (s) => s.tool ?? '?' };
40
41
 
41
42
  // 돌려주는 sessions 는 화면에 그리는 순서 그대로다 (↑↓·n 도 이 순서를 따른다).
@@ -605,7 +605,7 @@ function member(r, g) {
605
605
  task: r.title ?? '',
606
606
  status: r.running ? 'busy' : 'done',
607
607
  started: g.tokens.total > 0,
608
- phase: r.running ? { kind: 'think', text: `작업 중 · ${r.steps}단계` } : { kind: 'done', text: '완료' },
608
+ phase: r.running ? { kind: 'think', msg: 'steps', args: { n: r.steps } } : { kind: 'done' },
609
609
  now: '',
610
610
  tokens: g.tokens.total,
611
611
  cost: g.cost,
@@ -639,24 +639,25 @@ export function waitingFor(g) {
639
639
  // 실행 중일 때는 아직 바뀌는 중인 단계, 없으면 마지막으로 끝난 단계로 지금 할 일을 짐작한다.
640
640
  // 끝난 답변이 도구 호출을 냈으면 그 도구를 실행할 차례이고, 끝난 도구 호출 뒤에는 모델이 결과를 읽고 생각한다.
641
641
  export function phaseOf(live, r, g, runningMembers = 0) {
642
- if (!live) return { kind: 'ended', text: '종료' };
643
- const extra = runningMembers ? ` · 에이전트 ${runningMembers}개 실행 중` : '';
642
+ if (!live) return { kind: 'ended' };
643
+ // 같이 도는 에이전트 수는 args.agents 로 보내고, 화면이 문구 뒤에 붙인다.
644
+ const extra = runningMembers ? { agents: runningMembers } : {};
644
645
  const wait = waitingFor(g);
645
- if (wait) return { kind: 'waiting', text: `응답 대기 · ${wait}${extra}` };
646
- if (!r.running) return { kind: 'idle', text: '다음 지시 대기' };
646
+ if (wait) return { kind: 'waiting', args: { what: wait, ...extra } };
647
+ if (!r.running) return { kind: 'idle' };
647
648
  // 바뀌는 중인 단계와 끝난 단계 가운데 더 뒤의 것이 지금 하는 일이다 (앞의 명령이 오래 도는 동안 뒤 단계가 이어질 수 있다).
648
649
  const open = g.open && (!g.last || (g.open.idx ?? Infinity) > (g.last.idx ?? -1));
649
650
  const s = open ? g.open : (g.last ?? g.open);
650
651
  let p;
651
- if (!s) p = { kind: 'think', text: `작업 중 · ${r.steps}단계` };
652
- else if (s.type === STEP.TOOL && open) p = { kind: 'tool', text: `도구 실행 · ${s.tool?.what || '도구'}` };
653
- else if (s.type === STEP.REPLY && !open && s.tool) p = { kind: 'tool', text: `도구 실행 · ${s.tool.what}` };
654
- else if (s.type === STEP.REPLY) p = { kind: 'write', text: '답변 작성 중' };
655
- else p = { kind: 'think', text: '생각 중' };
656
- return { ...p, text: p.text + extra };
652
+ if (!s) p = { kind: 'think', msg: 'steps', args: { n: r.steps } };
653
+ else if (s.type === STEP.TOOL && open) p = s.tool?.what ? { kind: 'tool', args: { what: s.tool.what } } : { kind: 'tool', msg: 'toolUnknown' };
654
+ else if (s.type === STEP.REPLY && !open && s.tool) p = { kind: 'tool', args: { what: s.tool.what } };
655
+ else if (s.type === STEP.REPLY) p = { kind: 'write' };
656
+ else p = { kind: 'think' };
657
+ return runningMembers ? { ...p, args: { ...p.args, ...extra } } : p;
657
658
  }
658
659
 
659
- function placeholder(p, text) {
660
+ function placeholder(p, msg) {
660
661
  return {
661
662
  tool: 'gemini',
662
663
  id: `agy-${p.pid}`,
@@ -668,7 +669,7 @@ function placeholder(p, text) {
668
669
  model: null,
669
670
  live: true,
670
671
  status: 'idle',
671
- phase: { kind: 'idle', text },
672
+ phase: { kind: 'idle', msg },
672
673
  cost: null,
673
674
  now: '',
674
675
  updatedAt: Date.now(),
@@ -683,7 +684,7 @@ export function collectAgy({ showEnded, budget }) {
683
684
  const procs = findProcesses(isAgy);
684
685
  // 기록 폴더가 없으면 agy 를 실행한 적이 없는 것이다 (테스트에서 AITOP_AGY_HOME 으로 실제 기록과 떼어 놓을 때도 쓴다).
685
686
  if (!existsSync(AGY_ROOT) || (!procs.length && !showEnded)) return [];
686
- if (!loadSqlite()) return procs.map((p) => placeholder(p, '실행 중 (세부 정보는 Node 22.15 이상)'));
687
+ if (!loadSqlite()) return procs.map((p) => placeholder(p, 'agyOldNode'));
687
688
 
688
689
  const rows = readSummaries();
689
690
  const { live, loose } = matchLive(procs, rows);
@@ -755,7 +756,7 @@ export function collectAgy({ showEnded, budget }) {
755
756
  members: isLive ? members : [],
756
757
  });
757
758
  }
758
- for (const p of loose) out.push(placeholder(p, '첫 입력 대기'));
759
+ for (const p of loose) out.push(placeholder(p, 'firstInput'));
759
760
 
760
761
  const keep = new Set(rows.map((r) => r.id));
761
762
  for (const id of convs.keys()) if (!keep.has(id)) convs.delete(id);
@@ -175,9 +175,9 @@ export class ClaudeTracker {
175
175
  const open = [...this.pending.values()];
176
176
  const agents = open.filter((p) => p.name === 'Agent' || p.name === 'Task');
177
177
  const tools = open.filter((p) => p.name !== 'Agent' && p.name !== 'Task');
178
- if (tools.length) return { kind: 'tool', text: `도구 실행 · ${tools.at(-1).name}` };
179
- if (agents.length) return { kind: 'team', text: `팀원 ${agents.length}명 작업 중` };
180
- if (this.lastKind === 'prompt' || this.lastKind === 'result') return { kind: 'think', text: '생각 중' };
181
- return { kind: 'write', text: '답변 작성 중' };
178
+ if (tools.length) return { kind: 'tool', args: { what: tools.at(-1).name } };
179
+ if (agents.length) return { kind: 'team', args: { n: agents.length } };
180
+ if (this.lastKind === 'prompt' || this.lastKind === 'result') return { kind: 'think' };
181
+ return { kind: 'write' };
182
182
  }
183
183
  }
@@ -70,7 +70,7 @@ export function _stats() {
70
70
  }
71
71
 
72
72
  function loadingPhase(t) {
73
- return t?.loading != null ? { kind: 'think', text: `기록 읽는 중 ${Math.floor(t.loading * 100)}%` } : null;
73
+ return t?.loading != null ? { kind: 'think', msg: 'loading', args: { pct: Math.floor(t.loading * 100) } } : null;
74
74
  }
75
75
 
76
76
  // 서브에이전트 전체(끝난 것 포함)의 토큰·비용 합계. 메인 세션 합계에 더해 화면에 보인다.
@@ -128,7 +128,7 @@ function readMembers(transcript, parent, budget) {
128
128
  task: meta.description ?? '',
129
129
  status: finished ? 'done' : 'busy',
130
130
  started,
131
- phase: finished ? { kind: 'done', text: '완료' } : !started ? { kind: 'idle', text: '시작 중' } : loadingPhase(t) ?? t.phase(),
131
+ phase: finished ? { kind: 'done' } : !started ? { kind: 'idle', msg: 'starting' } : loadingPhase(t) ?? t.phase(),
132
132
  now: t.lastTool,
133
133
  tokens: t.tokens.total,
134
134
  cost: t.cost,
@@ -148,25 +148,25 @@ function statusOf(entry, alive, mtime) {
148
148
  return Date.now() - mtime < 5000 ? 'busy' : 'idle';
149
149
  }
150
150
 
151
- // 응답 대기는 Claude Code 가 세션 파일에 적은 값이다. 그동안 서브에이전트가 돌고 있으면 함께 적어 구분되게 한다.
151
+ // 응답 대기는 Claude Code 가 세션 파일에 적은 값이다. 그동안 서브에이전트가 돌고 있으면 수를 args.agents 로 함께 보내 구분되게 한다.
152
152
  function withRunningMembers(phase, status, members) {
153
153
  if (status !== 'waiting') return phase;
154
154
  const running = members.filter((m) => m.status !== 'done' && m.phase?.kind !== 'done').length;
155
- return running ? { ...phase, text: `${phase.text} · 에이전트 ${running}개 실행 중` } : phase;
155
+ return running ? { ...phase, args: { ...phase.args, agents: running } } : phase;
156
156
  }
157
157
 
158
158
  function phaseOf(status, entry, t) {
159
159
  switch (status) {
160
160
  case 'ended':
161
- return { kind: 'ended', text: '종료' };
161
+ return { kind: 'ended' };
162
162
  case 'waiting':
163
- return { kind: 'waiting', text: entry.waitingFor ? `응답 대기 · ${entry.waitingFor}` : '응답 대기' };
163
+ return entry.waitingFor ? { kind: 'waiting', args: { what: entry.waitingFor } } : { kind: 'waiting' };
164
164
  case 'shell':
165
- return { kind: 'tool', text: '쉘 명령 실행 중' };
165
+ return { kind: 'tool', msg: 'shell' };
166
166
  case 'idle':
167
- return { kind: 'idle', text: '다음 지시 대기' };
167
+ return { kind: 'idle' };
168
168
  default:
169
- return loadingPhase(t) ?? (t ? t.phase() : { kind: 'think', text: '작업 중' });
169
+ return loadingPhase(t) ?? (t ? t.phase() : { kind: 'think', msg: 'working' });
170
170
  }
171
171
  }
172
172
 
@@ -276,7 +276,7 @@ function endedFromTranscripts(known, selectedId, budget) {
276
276
  live: false,
277
277
  lazy: !t,
278
278
  status: 'ended',
279
- phase: loadingPhase(t) ?? { kind: 'ended', text: '종료' },
279
+ phase: loadingPhase(t) ?? { kind: 'ended' },
280
280
  waitingFor: null,
281
281
  now: '',
282
282
  startedAt: head.startedAt,
@@ -171,11 +171,11 @@ function snapshot(st) {
171
171
  }
172
172
 
173
173
  function phaseOf(st, live) {
174
- if (!live) return { kind: 'ended', text: '종료' };
175
- if (!st.busy) return { kind: 'idle', text: '다음 지시 대기' };
174
+ if (!live) return { kind: 'ended' };
175
+ if (!st.busy) return { kind: 'idle' };
176
176
  const open = [...st.pending.values()];
177
- if (open.length) return { kind: 'tool', text: `도구 실행 · ${open.at(-1)}` };
178
- return st.lastKind === 'reply' ? { kind: 'write', text: '답변 작성 중' } : { kind: 'think', text: '생각 중' };
177
+ if (open.length) return { kind: 'tool', args: { what: open.at(-1) } };
178
+ return st.lastKind === 'reply' ? { kind: 'write' } : { kind: 'think' };
179
179
  }
180
180
 
181
181
  function applyLine(st, x) {
@@ -367,7 +367,7 @@ export function collectCodex({ showEnded, budget, filesOf = openFiles, startOf =
367
367
  // 아직 세션 파일을 만들지 않은(첫 입력 전) codex 프로세스도 보여 준다.
368
368
  for (const [cwd, pids] of slots) {
369
369
  for (const pid of pids) {
370
- 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', text: '첫 입력 대기' }, cost: null, now: '', updatedAt: Date.now(), tokens: emptyTokens(), context: { used: 0, window: 0 }, events: [], members: [] });
370
+ 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: [] });
371
371
  }
372
372
  }
373
373
  return out;
@@ -14,7 +14,7 @@ export function collectGemini() {
14
14
  project: basename(p.cwd ?? ''),
15
15
  live: true,
16
16
  status: 'live',
17
- phase: { kind: 'idle', text: '실행 중 (세부 정보 미지원)' },
17
+ phase: { kind: 'idle', msg: 'geminiLimited' },
18
18
  cost: null,
19
19
  now: '',
20
20
  updatedAt: Date.now(),
package/src/ui/chrome.mjs CHANGED
@@ -3,8 +3,8 @@ import { pad, width } from '../text.mjs';
3
3
  import { NO_COLOR, PALETTE } from './theme.mjs';
4
4
  import { box, line, segsWidth } from './draw.mjs';
5
5
  import { glyphs, legendMark } from './glyphs.mjs';
6
- import { GROUP_LABEL, SORT_LABEL } from '../order.mjs';
7
- import { COMMON, OPTIONS, VIEWS, helpContext, keysLine, settingsLine } from '../help.mjs';
6
+ import { COMMON, VIEWS, helpContext, keysLine, options, settingsLine, viewText } from '../help.mjs';
7
+ import { getLang, t } from '../i18n.mjs';
8
8
 
9
9
  // 상세 패널을 기본으로 여는 최소 화면 높이. 이보다 낮으면 세션 표에 줄을 준다.
10
10
  export const DETAIL_MIN_H = 24;
@@ -14,55 +14,61 @@ export function detailOpen(view, H) {
14
14
  return view.showDetail === 'auto' ? H >= DETAIL_MIN_H : Boolean(view.showDetail);
15
15
  }
16
16
 
17
- // 상태 기호와 열 설명. 키는 help.mjs 의 VIEWS 에서 화면별로 고른다.
18
- export const LEGEND = [
19
- ['상태 기호', null],
20
- ['⠋', '작업 중 (STATUS 칸에 생각·답변, 도구 실행, 팀원 작업. 색으로도 나뉜다)'],
21
- ['◆', '응답 대기 (권한·질문). 행 배경이 강조된다'],
22
- ['●', '완료 · 확인 전 (작업이 끝났는데 아직 선택해 보지 않음)'],
23
- ['○', '다음 지시 대기'],
24
- ['·', '종료'],
25
- ['★', '고정한 세션 (p). SESSION 칸 앞에 붙는다'],
17
+ // 상태 기호와 열 설명 [기호·열 이름, i18n 키]. 키는 help.mjs 의 VIEWS 에서 화면별로 고른다.
18
+ const LEGEND_IDS = [
19
+ ['help.legend', null],
20
+ ['⠋', 'legend.busy'],
21
+ ['◆', 'legend.waiting'],
22
+ ['●', 'legend.unseen'],
23
+ ['○', 'legend.idle'],
24
+ ['·', 'legend.ended'],
25
+ ['★', 'legend.pin'],
26
26
  ['', ''],
27
- ['열', null],
28
- ['STATUS', '지금 단계. 큰 기록을 처음 읽는 동안은 기록 읽는 중 N%'],
29
- ['TOKENS', '세션 누적 토큰 (서브에이전트 포함, 캐시 읽기 포함)'],
30
- ['COST', 'API 정가로 환산한 비용 (Codex 는 OpenAI 정가 추정). ? 는 가격표에 없는 모델 포함'],
31
- ['CONTEXT', '마지막 요청의 컨텍스트 사용률 (모델별 창 크기 기준)'],
32
- ['IDLE', '마지막 활동 후 지난 시간. 작업 중이면 now'],
33
- ['숨김 N', '도구 줄 끝: 7일 동안 안 쓴 도구를 숨김. 다시 보려면 설정 파일에 "hideIdleTools": false'],
34
- ['+N', '도구 줄 끝: 화면이 좁아 접은 도구 수 (넓히면 보인다)'],
35
- ['오늘 / 7일', '헤더 오른쪽. 날짜별 합계, API 정가 환산이며 구독 요금제의 청구액이 아니다'],
36
- ['변경 파일', 'Edit/Write(Codex 는 apply_patch) 로 고친 파일과 편집 횟수. git diff 가 아니다'],
27
+ ['help.columns', null],
28
+ ['STATUS', 'legend.status'],
29
+ ['TOKENS', 'legend.tokens'],
30
+ ['COST', 'legend.cost'],
31
+ ['CONTEXT', 'legend.context'],
32
+ ['IDLE', 'legend.idleCol'],
33
+ ['legend.hiddenKey', 'legend.hidden'],
34
+ ['+N', 'legend.folded'],
35
+ ['legend.periodKey', 'legend.period'],
36
+ ['legend.filesKey', 'legend.files'],
37
37
  ];
38
38
 
39
+ // 지금 언어의 상태 기호·열 설명. 제목 줄은 설명이 null 이다.
40
+ export const legend = () => LEGEND_IDS.map(([k, d]) => [/^(help|legend)\./.test(k) ? t(k) : k, d ? t(d) : d]);
41
+
39
42
  // 도움말 줄 목록: 지금 화면의 키 → (표에 검색어가 걸려 있으면) 그 키 → (상세 패널이 열려 있으면) 상세 패널 키 → 어디서나 쓰는 키 → 다른 화면 한 줄씩 → 옵션 → 상태 기호·열.
40
43
  // 넓으면(100칸 이상) 키는 왼쪽, 옵션·기호·열은 오른쪽 칸에 둔다.
41
44
  export function helpSections(view = {}, open = false) {
42
45
  const ctx = helpContext(view);
43
46
  const here = ctx === 'table' ? ['table', ...(view.filter ? ['filtered'] : []), ...(open ? ['detail'] : [])] : [ctx];
44
- const keys = [...here.map((n) => VIEWS[n]), COMMON].flatMap((v, i) => [...(i ? [['', '']] : []), [`${v.title}${i ? '' : ' (지금 화면)'}`, null], ...v.keys.map(([k, t]) => [k, t])]);
47
+ const keys = [...here.map((n) => VIEWS[n]), COMMON].map((v) => viewText(v)).flatMap((v, i) => [...(i ? [['', '']] : []), [`${v.title}${i ? '' : t('help.here')}`, null], ...v.keys]);
45
48
  const others = Object.keys(VIEWS).filter((n) => !here.includes(n));
46
- const rest = [['', ''], ['다른 화면', null], ...others.map((n) => [VIEWS[n].title, keysLine(n), 'dim'])];
49
+ const rest = [['', ''], [t('help.others'), null], ...others.map((n) => [viewText(VIEWS[n]).title, keysLine(n), 'dim'])];
47
50
  const now = settingsLine(view.settings);
48
- const options = [
49
- ['옵션', null],
50
- ...OPTIONS,
51
- ...(view.settings?.configPath ? [['설정 파일', view.settings.configPath, 'dim']] : []),
52
- ...(now ? [['지금', now]] : []),
51
+ const opts = [
52
+ [t('help.options'), null],
53
+ ...options(),
54
+ ...(view.settings?.configPath ? [[t('help.config'), view.settings.configPath, 'dim']] : []),
55
+ ...(now ? [[t('help.now'), now]] : []),
53
56
  ];
54
- return { keys: [...keys, ...rest], more: [...options, ['', ''], ...LEGEND.map(([k, t]) => [legendMark(k), t])] };
57
+ return { keys: [...keys, ...rest], more: [...opts, ['', ''], ...legend().map(([k, d]) => [legendMark(k), d])] };
55
58
  }
56
59
 
57
60
  // 키 칸 폭은 제목 줄 사이 묶음마다 그 묶음의 가장 긴 키에 맞춘다 (12~21칸).
61
+ // 영어는 키 이름(Typing a search, Changed files)이 길어 설명과 붙어 보이므로 사이를 2칸 둔다 (한국어는 예전대로 1칸).
58
62
  function helpLines(list) {
59
63
  const out = [];
64
+ const gap = getLang() === 'ko' ? 1 : 2;
65
+ const cap = 20 + gap;
60
66
  let kw = 12;
61
67
  list.forEach(([k, v, dim], i) => {
62
68
  if (v == null) {
63
69
  const next = list.slice(i + 1);
64
70
  const block = next.slice(0, Math.max(0, next.findIndex((e) => e[1] == null)) || next.length);
65
- kw = Math.min(21, Math.max(12, ...block.filter((e) => e[1]).map((e) => width(e[0]) + 1)));
71
+ kw = Math.min(cap, Math.max(12, ...block.filter((e) => e[1]).map((e) => width(e[0]) + gap)));
66
72
  out.push([{ t: k, fg: PALETTE.brand, bold: true }]);
67
73
  } else out.push([{ t: pad(k, kw), fg: PALETTE.text, bold: !dim }, { t: v, fg: dim ? PALETTE.info : PALETTE.muted }]);
68
74
  });
@@ -71,7 +77,7 @@ function helpLines(list) {
71
77
 
72
78
  // 줄이 넘치면 scroll 만큼 내려 보이고, 아래에 남은 줄이 있으면 마지막 줄에 알린다.
73
79
  function windowOf(lines, n, scroll) {
74
- const more = (k) => [{ t: `… ${k}줄 더 · ↑↓ 로 스크롤`, fg: PALETTE.info, italic: true }];
80
+ const more = (k) => [{ t: t('help.more', { n: k }), fg: PALETTE.info, italic: true }];
75
81
  const part = lines.slice(scroll, scroll + n);
76
82
  const left = lines.length - scroll - n;
77
83
  return left > 0 ? [...part.slice(0, n - 1), more(left + 1)] : part;
@@ -80,7 +86,7 @@ function windowOf(lines, n, scroll) {
80
86
  // view.helpScroll: ↑↓ 로 내린 줄 수. 넘치지 않으면 0. 내릴 수 있는 끝은 view.helpMax 에 남긴다 (keys.mjs 가 쓴다).
81
87
  export function help(W, H, view = {}, open = false) {
82
88
  const { keys, more } = helpSections(view, open);
83
- const title = '도움말 · ? 또는 Esc 로 닫기';
89
+ const title = t('help.title');
84
90
  const rows = H - 2;
85
91
  const wide = W >= 100;
86
92
  const cols = wide ? [helpLines(keys), helpLines(more)] : [helpLines([...keys, ['', ''], ...more])];
@@ -97,7 +103,7 @@ export function help(W, H, view = {}, open = false) {
97
103
  // 키 칩. 색이 없으면 [f] 처럼 괄호로 보인다.
98
104
  export const keyChip = (k) => (NO_COLOR ? { t: `[${k}]` } : { t: ` ${k} `, fg: PALETTE.chipText, bg: PALETTE.muted, bold: true });
99
105
 
100
- export const keyLabel = (t) => ({ t: ` ${t} `, fg: PALETTE.muted });
106
+ export const keyLabel = (v) => ({ t: ` ${v} `, fg: PALETTE.muted });
101
107
 
102
108
  // items: { k, t, keep } 또는 { segs, keep }. 폭이 모자라면 keep 이 아닌 항목을 오른쪽부터 뺀다.
103
109
  export function hintBar(items, W, right = '') {
@@ -114,50 +120,52 @@ export function hintBar(items, W, right = '') {
114
120
  // 정렬·묶기가 기본이 아닐 때만 지금 상태를 짧게 보인다 (예: s:비용 g:프로젝트). 표 순서를 읽는 데 필요하므로 d·e·c 안내보다 늦게 빠진다.
115
121
  function orderHint(view) {
116
122
  const parts = [
117
- ...(view.sort && view.sort !== 'default' ? [['s', SORT_LABEL[view.sort]]] : []),
118
- ...(view.group && view.group !== 'none' ? [['g', GROUP_LABEL[view.group]]] : []),
123
+ ...(view.sort && view.sort !== 'default' ? [['s', t(`sort.${view.sort}`)]] : []),
124
+ ...(view.group && view.group !== 'none' ? [['g', t(`groupBy.${view.group}`)]] : []),
119
125
  ];
120
126
  if (!parts.length) return null;
121
- const segs = parts.flatMap(([k, t], i) => [{ t: i ? ' ' : '', fg: PALETTE.info }, { t: k, fg: PALETTE.muted, bold: true }, { t: `:${t}`, fg: PALETTE.info }]);
127
+ const segs = parts.flatMap(([k, v], i) => [{ t: i ? ' ' : '', fg: PALETTE.info }, { t: k, fg: PALETTE.muted, bold: true }, { t: `:${v}`, fg: PALETTE.info }]);
122
128
  return { segs: [...segs, { t: ' ' }] };
123
129
  }
124
130
 
125
131
  export function footer(view, W, matched, sel) {
132
+ const RO = t('foot.readOnly');
126
133
  const tail = [
127
- { k: '?', t: '도움', keep: true },
128
- { k: 'q', t: '나가기', keep: true },
134
+ { k: '?', t: t('foot.help'), keep: true },
135
+ { k: 'q', t: t('key.quit'), keep: true },
129
136
  ];
137
+ const ended = { k: 'e', t: t(view.showEnded ? 'foot.hideEnded' : 'foot.showEnded') };
130
138
  // 도움말이 열려 있으면 ↑↓ 는 도움말을 스크롤하고 ? · Esc 는 닫는다.
131
- if (view.help) return hintBar([{ k: '↑↓', t: '스크롤' }, { k: '?', t: '도움 닫기', keep: true }, { k: 'Esc', t: '닫기' }, { k: 'q', t: '나가기', keep: true }], W, '⊘ 읽기전용');
139
+ if (view.help) return hintBar([{ k: '↑↓', t: t('key.scroll') }, { k: '?', t: t('foot.closeHelp'), keep: true }, { k: 'Esc', t: t('key.close') }, { k: 'q', t: t('key.quit'), keep: true }], W, RO);
132
140
  if (view.searching) {
133
141
  const input = NO_COLOR ? [{ t: '[/]' }] : [{ t: ' / ', fg: PALETTE.chipText, bg: PALETTE.brand, bold: true }];
134
- return hintBar([{ segs: [...input, { t: ` ${view.filter ?? ''}`, fg: PALETTE.text, bold: true }, { t: glyphs().cursor, fg: PALETTE.brand }, { t: ` ${matched}개 `, fg: PALETTE.muted }], keep: true }, { k: '⏎', t: '적용', keep: true }, { k: 'Esc', t: '지우기', keep: true }], W);
142
+ return hintBar([{ segs: [...input, { t: ` ${view.filter ?? ''}`, fg: PALETTE.text, bold: true }, { t: glyphs().cursor, fg: PALETTE.brand }, { t: ` ${t('foot.count', { n: matched })} `, fg: PALETTE.muted }], keep: true }, { k: '⏎', t: t('key.apply'), keep: true }, { k: 'Esc', t: t('foot.clear'), keep: true }], W);
135
143
  }
136
144
  if (view.focus) {
137
145
  const keys =
138
146
  view.focus === 'diff'
139
- ? [{ k: '↑↓', t: '스크롤' }, { k: 'space', t: '페이지' }, { k: '[ ]', t: '이전·다음 파일' }, { k: 'Esc', t: '파일 목록으로', keep: true }]
140
- : [{ k: '←→', t: '지시' }, { k: '↑↓', t: '파일 선택' }, { k: '⏎', t: 'diff 보기' }, { k: 'Esc', t: '세션으로', keep: true }];
141
- return hintBar([...keys, ...tail], W, '⊘ 읽기전용');
147
+ ? [{ k: '↑↓', t: t('key.scroll') }, { k: 'space', t: t('key.page') }, { k: '[ ]', t: t('key.prevNext') }, { k: 'Esc', t: t('foot.toFiles'), keep: true }]
148
+ : [{ k: '←→', t: t('foot.prompts') }, { k: '↑↓', t: t('foot.pickFile') }, { k: '⏎', t: t('foot.viewDiff') }, { k: 'Esc', t: t('foot.toSessions'), keep: true }];
149
+ return hintBar([...keys, ...tail], W, RO);
142
150
  }
143
151
  // 세션이 하나도 없으면 쓸 수 있는 키만 남긴다.
144
- if (!view.filter && !view.data?.sessions?.length) return hintBar([{ k: 'e', t: view.showEnded ? '종료 숨김' : '종료 포함' }, ...tail], W, '⊘ 읽기전용');
152
+ if (!view.filter && !view.data?.sessions?.length) return hintBar([ended, ...tail], W, RO);
145
153
  const order = orderHint(view);
146
154
  const search = view.filter
147
- ? { segs: [{ t: ` /${view.filter} `, fg: PALETTE.chipText, bg: PALETTE.brand, bold: true }, { t: ` ${matched}개 `, fg: PALETTE.muted }, keyChip('Esc'), keyLabel('검색 지우기')], keep: true }
148
- : { k: '/', t: '검색' };
155
+ ? { segs: [{ t: ` /${view.filter} `, fg: PALETTE.chipText, bg: PALETTE.brand, bold: true }, { t: ` ${t('foot.count', { n: matched })} `, fg: PALETTE.muted }, keyChip('Esc'), keyLabel(t('foot.clearSearch'))], keep: true }
156
+ : { k: '/', t: t('key.search') };
149
157
  const items = [
150
158
  search,
151
- { k: '↑↓', t: '선택' },
152
- { k: 'n', t: '다음' },
159
+ { k: '↑↓', t: t('key.select') },
160
+ { k: 'n', t: t('foot.next') },
153
161
  ...(order ? [order] : []),
154
- ...(sel?.files?.length ? [{ k: 'f', t: '파일' }] : []),
155
- { k: 'd', t: view.showDetail ? '상세 닫기' : '상세 열기' },
156
- { k: 'e', t: view.showEnded ? '종료 숨김' : '종료 포함' },
157
- { k: 'c', t: '비용 기준' },
162
+ ...(sel?.files?.length ? [{ k: 'f', t: t('foot.files') }] : []),
163
+ { k: 'd', t: t(view.showDetail ? 'foot.hideDetail' : 'foot.showDetail') },
164
+ ended,
165
+ { k: 'c', t: t('foot.costMode') },
158
166
  // 고정은 폭이 모자라면 가장 먼저 빠진다.
159
- ...(sel ? [{ k: 'p', t: view.pins?.includes(sel.id) ? '고정 해제' : '고정' }] : []),
167
+ ...(sel ? [{ k: 'p', t: t(view.pins?.includes(sel.id) ? 'foot.unpin' : 'key.pin') }] : []),
160
168
  ...tail,
161
169
  ];
162
- return hintBar(items, W, '⊘ 읽기전용');
170
+ return hintBar(items, W, RO);
163
171
  }