@sejuneoh/aitop 0.40.0 → 0.41.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 CHANGED
@@ -22,7 +22,7 @@
22
22
  - `y` copies a resume command, and `--report sessions` prints yesterday's sessions with cost for your standup.
23
23
  - **No hooks, nothing sent.**
24
24
  - Claude Code, Codex CLI and Antigravity CLI side by side, from [several history folders](#several-claude-or-codex-profiles) (`~/.claude`, `~/.claude-work`, ...).
25
- - aitop only reads the logs they already write. It changes no settings and needs no network, ports or dependencies.
25
+ - aitop only reads the logs they already write. It changes no settings and needs no network, ports or dependencies. The one exception is the opt-in [`--remote`](#remote-hosts-and-wsl-distros), which runs your own `ssh` or `wsl.exe`.
26
26
 
27
27
  **Contents**
28
28
 
@@ -30,7 +30,7 @@
30
30
  - [Features](#features)
31
31
  - [Subagents](#subagents) · [Daily and monthly reports](#daily-and-monthly-reports) · [Session report](#session-report) · [Call tree](#call-tree)
32
32
  - [Notifications](#notifications) · [tmux status line](#tmux-status-line) · [Several Claude or Codex profiles](#several-claude-or-codex-profiles)
33
- - [Resume a session elsewhere](#resume-a-session-elsewhere) · [JSON output](#json-output) · [Language](#language)
33
+ - [Resume a session elsewhere](#resume-a-session-elsewhere) · [Remote hosts and WSL distros](#remote-hosts-and-wsl-distros) · [JSON output](#json-output) · [Language](#language)
34
34
  - [How it differs from similar tools](#how-it-differs-from-similar-tools) · [Install](#install) · [License](#license)
35
35
 
36
36
  ## Quick start
@@ -90,7 +90,7 @@
90
90
  - **Tokens and cost** per session and for today / last 7 days, estimated at public API list prices. This is not your bill.
91
91
  - **Changed files and diffs** per session and per prompt.
92
92
  - **Artifacts** a Claude or Cowork session (or its subagents) published with the Artifact tool, with clickable links.
93
- - **Read-only**: no network, no ports, no dependencies. It only reads the session logs each CLI already writes.
93
+ - **Read-only**: no network, no ports, no dependencies. It only reads the session logs each CLI already writes. Only [`--remote`](#remote-hosts-and-wsl-distros), when you turn it on, uses the network (through your `ssh`).
94
94
 
95
95
  <details>
96
96
  <summary>Details: stopped sessions, cache countdown, tool run time, context gauge, artifacts, tool line</summary>
@@ -332,7 +332,7 @@ Alerts when a session starts waiting, finishes a long turn or fills its context.
332
332
 
333
333
  - The hook keeps its name (`--on-waiting`) for all kinds.
334
334
  - It gets `AITOP_EVENT` (`waiting`, `done` or `context`) in its environment.
335
- - It also gets `AITOP_TOOL`, `AITOP_PROJECT`, `AITOP_SESSION_ID`, `AITOP_CWD` and `AITOP_WAITING_FOR`.
335
+ - It also gets `AITOP_TOOL`, `AITOP_PROJECT`, `AITOP_SESSION_ID`, `AITOP_CWD` and `AITOP_WAITING_FOR`, plus `AITOP_HOST` (the [remote](#remote-hosts-and-wsl-distros) name, empty for local sessions).
336
336
 
337
337
  **Config file and switches**
338
338
 
@@ -536,6 +536,50 @@ Continue a session elsewhere, for example when you cannot jump to its tab, as in
536
536
 
537
537
  </details>
538
538
 
539
+ ## Remote hosts and WSL distros
540
+
541
+ See sessions on machines you manage (a VM, a dev server, another WSL distro) on the same screen.
542
+
543
+ > `aitop --remote dev,me@vm2,wsl:Ubuntu-22.04`
544
+ >
545
+ > config file: `"remotes": ["dev", "wsl:Ubuntu"]`
546
+
547
+ - aitop must be installed on each remote. Every 10 seconds aitop runs `ssh -o BatchMode=yes -o ConnectTimeout=5 -T -- <host> aitop --json --no-remote` (WSL: `wsl.exe -d <distro> -- aitop --json --no-remote`) for all remotes in parallel, 20 seconds per call.
548
+ - Auth and host trust are left to your ssh config and agent. aitop never asks for or stores passwords or keys, and never turns off host key checking.
549
+ - This is the only feature that uses the network, and only when you turn it on. `--no-remote` turns off the config file list for one run.
550
+ - The table keeps local sessions on top. Each remote follows under its own line: `── dev · 3 sessions · 10s ago ──`, or `── dev · not connected (timed out) ──`. Sorting, grouping and waiting-first work inside each block.
551
+ - Waiting bell and desktop alerts include remote sessions. `--on-waiting` gets `AITOP_HOST`.
552
+ - `y` copies a local command that reopens the session there: `ssh -t dev 'cd /repo && claude --resume <id>'` (WSL: `wsl.exe -d Ubuntu --cd /repo -- claude --resume <id>`).
553
+ - `--once` and `--json` wait for all remotes before printing.
554
+
555
+ <details>
556
+ <summary>Details: names, errors, what is not fetched</summary>
557
+
558
+ **Names**
559
+
560
+ - An ssh host alias or `user@host` (letters, digits, `.`, `_`, `-`), or `wsl:<distro>`. Up to 16.
561
+ - Values starting with `-`, ports (`host:22`), spaces and shell characters are refused at start (exit 2). Put a port or jump host in an `~/.ssh/config` alias.
562
+ - There is no automatic WSL distro discovery; name the distro.
563
+
564
+ **Errors on the remote line**
565
+
566
+ - auth failed, unreachable, no aitop on remote (exit 127), remote aitop too old (no `--no-remote` or no `schema` in its JSON), remote aitop newer (larger `schema`), timed out, bad response (broken JSON or over 8MB). Remote error output is not shown.
567
+ - A short connection drop keeps the remote's last sessions (the line shows the error and how old they are) and clears them after 3 failures in a row or 60 seconds. When a remote first connects, or comes back after being cleared, sessions already waiting are not alerted.
568
+ - So after a long drop (once the sessions were cleared), a session that started waiting during the drop is not alerted either: it becomes part of the new baseline.
569
+
570
+ **"no aitop on remote" although it is installed**
571
+
572
+ - `ssh host aitop` runs a non-login shell, so an aitop installed with nvm, fnm or a user npm prefix may not be on its `PATH`.
573
+ - Fix on the remote: put the `PATH` line (for example `export NVM_DIR=...` and `. "$NVM_DIR/nvm.sh"`) at the top of `~/.bashrc`, before the "If not running interactively, return" line, or link it once: `sudo ln -s "$(command -v aitop)" /usr/local/bin/aitop` (run it in a shell where `aitop` works; for nvm, link `node` the same way).
574
+
575
+ **Not fetched**
576
+
577
+ - Diffs (the detail panel shows file stats only), artifact sources (links still work), the remote usage totals (remote cost is not added to the header) and requests (`--show-requests`).
578
+ - `--report` and `--line` stay local.
579
+ - Remote output is treated as untrusted: only known fields are kept, text is stripped of control characters, masked and cut to 200 characters, and the counts are capped (500 sessions, 200 files, 50 members per remote).
580
+
581
+ </details>
582
+
539
583
  ## JSON output
540
584
 
541
585
  > `aitop --json`
@@ -545,6 +589,8 @@ Continue a session elsewhere, for example when you cannot jump to its tab, as in
545
589
  - `--json` prints a snapshot as JSON and exits.
546
590
  - For scripts, use `phaseKind`, a stable state name: `think`, `write`, `tool`, `team`, `waiting`, `idle`, `stopped`, `done`, `ended` (or `null`).
547
591
  - `stopReason` says why a session is `stopped`: `{ "kind": "auth" }` login needed, `network` connection lost, `api` any other API error. `null` otherwise.
592
+ - `schema` (top level) is the JSON shape version, now `1`. It goes up only when an existing field changes meaning or shape.
593
+ - With [`--remote`](#remote-hosts-and-wsl-distros): each session has `host` (`null` for local) and `remoteId` (its id on that host; `id` is `<host>:<id>`), and `remotes` lists each remote as `{ name, kind, ok, error, version, schema, at }` (`[]` when off). `usage` stays local.
548
594
 
549
595
  <details>
550
596
  <summary>Details: text fields and where other fields are described</summary>
package/bin/aitop.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { readFileSync } from 'node:fs';
3
- import { budgetDayOption, configJson, configPath, configText, readConfigFile, resolveConfig } from '../src/config.mjs';
3
+ import { budgetDayOption, configJson, configPath, configText, parseRemote, readConfigFile, remoteOption, resolveConfig } from '../src/config.mjs';
4
4
  import { langOption, pickLang, setLang, t } from '../src/i18n.mjs';
5
5
  import { notifyOptions } from '../src/notify.mjs';
6
6
  import { lineOption } from '../src/line.mjs';
@@ -11,7 +11,7 @@ import { mask, setAmbiguous, stripControl } from '../src/text.mjs';
11
11
  const KNOWN = new Set(['-h', '--help', '-v', '--version', '--once', '--all', '--json', '--doctor', '--bell', '--show-requests', '--print-config', '--no-bell', '--no-all', '--no-show-requests', '--debug', '--no-debug', '--color-blind', '--no-color-blind']);
12
12
  const THEMES = ['light', 'dark'];
13
13
  // 잘못 친 옵션에 제안할 후보. KNOWN 의 긴 옵션과, 다른 모듈이 먼저 꺼내는 값 옵션을 합친다.
14
- const OPTIONS = [...[...KNOWN].filter((o) => o.startsWith('--')), '--theme', '--lang', '--notify', '--no-notify', '--on-waiting', '--no-on-waiting', '--budget-day', '--no-budget-day', '--line', '--line-width', '--report', '--by', '--days', '--months', '--since', '--plan', '--md', '--show-prompts'];
14
+ const OPTIONS = [...[...KNOWN].filter((o) => o.startsWith('--')), '--theme', '--lang', '--notify', '--no-notify', '--on-waiting', '--no-on-waiting', '--budget-day', '--no-budget-day', '--line', '--line-width', '--report', '--by', '--days', '--months', '--since', '--plan', '--md', '--show-prompts', '--remote', '--no-remote'];
15
15
  const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
16
16
 
17
17
  // 언어는 다른 옵션의 오류 문구보다 먼저 정한다: --lang > AITOP_LANG > 설정 파일 lang > LC_ALL > LC_MESSAGES > LANG.
@@ -50,10 +50,16 @@ if (report.error) {
50
50
  process.stderr.write(`aitop: ${report.error}\n`);
51
51
  process.exit(2);
52
52
  }
53
+ // --remote <목록>, --remote=<목록>, --no-remote 는 remoteOption 이 꺼낸다 (#308). 잘못된 호스트 이름은 여기서 끝낸다.
54
+ const remoteOpt = remoteOption(report.rest);
55
+ if (remoteOpt.error) {
56
+ process.stderr.write(`aitop: ${remoteOpt.error}\n`);
57
+ process.exit(2);
58
+ }
53
59
  // 사용자가 준 NO_COLOR. 아래에서 파이프 출력이면 NO_COLOR 를 켜므로 그 전에 읽어 둔다 (tmux 의 #() 는 TTY 가 아니다).
54
60
  const userNoColor = Boolean(process.env.NO_COLOR);
55
61
  // --theme light, --theme=light 처럼 값을 받는 옵션은 따로 꺼낸다.
56
- const argv = report.rest;
62
+ const argv = remoteOpt.rest;
57
63
  let theme = null;
58
64
  const rest = [];
59
65
  for (let i = 0; i < argv.length; i++) {
@@ -75,7 +81,7 @@ const flag = (name) => {
75
81
  const notifyFlag = cli.notify ? (cli.eventsSet ? cli.events : true) : notifyOptions(cliArgs, { notify: true }).notify ? undefined : false;
76
82
  // onWaiting 은 --on-waiting 이 뒤에 오면 그 명령, --no-on-waiting 이 뒤에 오면 null(끔), 둘 다 없으면 정하지 않은 것이다.
77
83
  const onWaitingFlag = cli.onWaiting ?? (notifyOptions(cliArgs, { onWaiting: 'x' }).onWaiting === null ? null : undefined);
78
- const config = resolveConfig({ flags: { theme: THEMES.includes(theme) ? theme : undefined, colorBlind: flag('color-blind'), bell: flag('bell'), showRequests: flag('show-requests'), all: flag('all'), debug: flag('debug'), notify: notifyFlag, onWaiting: onWaitingFlag, budgetDay: budget.value, lang: langOpt.value }, file: cfgFile });
84
+ const config = resolveConfig({ flags: { theme: THEMES.includes(theme) ? theme : undefined, colorBlind: flag('color-blind'), bell: flag('bell'), showRequests: flag('show-requests'), all: flag('all'), debug: flag('debug'), notify: notifyFlag, onWaiting: onWaitingFlag, budgetDay: budget.value, lang: langOpt.value, remotes: remoteOpt.value }, file: cfgFile });
79
85
  const opt = Object.fromEntries(Object.entries(config.values).map(([k, v]) => [k, v.value]));
80
86
  // 알림은 설정 파일 값(onWaiting 은 권한 검사를 통과한 것만)을 깔고 명령줄 옵션이 덮는다.
81
87
  const fromFile = (k) => (config.values[k].source === 'file' ? config.values[k].value : undefined);
@@ -270,7 +276,7 @@ if (args.has('--doctor')) {
270
276
  // 진단은 한 번 돌고 끝나므로 Windows 의 첫 PowerShell CIM 호출을 더 오래 기다린다 (procs.mjs WIN_DOCTOR_TIMEOUT_MS).
271
277
  const { setFirstScanTimeout, WIN_DOCTOR_TIMEOUT_MS } = await import('../src/procs.mjs');
272
278
  setFirstScanTimeout(WIN_DOCTOR_TIMEOUT_MS);
273
- const result = { ...checkTools(), config: configJson(config), log: { on: log.on, path: log.path } };
279
+ const result = { ...checkTools(), config: configJson(config), log: { on: log.on, path: log.path }, remotes: (opt.remotes ?? []).map((n) => parseRemote(n)?.name).filter(Boolean) };
274
280
  await printAndExit(args.has('--json') ? JSON.stringify({ version: VERSION, ...result, tools: toolsJson(result.tools) }, null, 2) : doctorText(result, VERSION));
275
281
  }
276
282
 
@@ -290,6 +296,16 @@ const { onKey, fixFocus } = await import('../src/keys.mjs');
290
296
  const { admit, createLoading, latchReady } = await import('../src/loading.mjs');
291
297
  const { osc52, resumeCmd } = await import('../src/resume.mjs');
292
298
 
299
+ // --remote (#308): 원격을 켰을 때만 remote.mjs 를 불러온다 (--report·--line 은 위에서 이미 끝났다).
300
+ // 폴러가 뒤에서 원격마다 aitop --json 을 부르고, refresh 가 그 마지막 결과를 로컬 세션 뒤에 붙인다.
301
+ let poller = null;
302
+ let mergeRemote = null;
303
+ if (opt.remotes?.length) {
304
+ const remote = await import('../src/remote.mjs');
305
+ poller = remote.createRemotePoller(remote.remoteTargets(opt.remotes));
306
+ mergeRemote = remote.mergeRemote;
307
+ }
308
+
293
309
  // 요청 전체 보기는 기본으로 꺼 둔다. 켜지 않으면 상세 패널에도 --json 에도 나가지 않는다.
294
310
  const showRequests = opt.showRequests;
295
311
  // settings: 도움말(?)에 보이는 지금 설정 값.
@@ -328,6 +344,8 @@ const eventWatch = notifier && eventKinds.length ? createEventWatch({ doneMs: op
328
344
  // 알림(벨·--notify·--on-waiting)은 화면에 올리지 않은 갱신에서도 그대로 돈다. 돌려주는 값은 화면 데이터를 바꿨는지.
329
345
  function refresh({ throttle = false } = {}) {
330
346
  const data = collect({ showEnded: view.showEnded, selectedId: view.selectedId, budgetBytes: once ? Infinity : TICK_BUDGET, budgetMs: once ? Infinity : TICK_MS });
347
+ // 원격 결과를 붙인다. 새로 붙은 원격의 세션은 응답 대기 알림의 기준선으로만 넣는다 (remote.mjs mergeRemote).
348
+ if (poller) mergeRemote(data, poller, waitWatch);
331
349
  // 준비 완료를 먼저 정해, 처음 고르는 세션도 이번 갱신의 정렬을 따르게 한다.
332
350
  if (!once) latchReady(loading, data.sessionsMore);
333
351
  if (!data.sessions.some((s) => s.id === view.selectedId)) {
@@ -388,10 +406,13 @@ function select(id) {
388
406
  }
389
407
 
390
408
  if (once) {
409
+ // --once·--json 은 모든 원격이 끝날 때(원격마다 최대 20초)까지 기다린 뒤 낸다.
410
+ if (poller) await poller.pollAll();
391
411
  refresh();
392
412
  flushCache();
393
413
  // --line 이 작업 중 수를 낼 수 있게 요약을 남긴다 (summary.mjs).
394
- writeSummary(summarize(view.data.sessions));
414
+ // 원격 세션(#308)은 --line 이 다루지 않으므로 요약에 넣지 않는다.
415
+ writeSummary(summarize(view.data.sessions.filter((s) => !s.host)));
395
416
  const size = (v) => (Number(v) > 0 ? Math.floor(Number(v)) : 0);
396
417
  const W = process.stdout.columns || size(process.env.COLUMNS) || 140;
397
418
  const H = process.stdout.rows || size(process.env.LINES) || 40;
@@ -445,12 +466,14 @@ function leaveScreen() {
445
466
  }
446
467
 
447
468
  restore = () => {
469
+ poller?.stop();
448
470
  notifier?.killAll();
449
471
  leaveScreen();
450
472
  flushCache();
451
473
  };
452
474
 
453
475
  function quit() {
476
+ poller?.stop();
454
477
  notifier?.killAll();
455
478
  leaveScreen();
456
479
  flushCache();
@@ -469,6 +492,7 @@ process.on('SIGCONT', () => {
469
492
  });
470
493
  process.on('uncaughtException', (err) => {
471
494
  debug('aitop', 'uncaughtException', err);
495
+ poller?.stop();
472
496
  notifier?.killAll();
473
497
  leaveScreen();
474
498
  try {
@@ -534,6 +558,8 @@ const act = {
534
558
  keepVisible: keepSelectionVisible,
535
559
  // 아티팩트 원본을 뒤에서 찾은 뒤 다시 그린다 (#307).
536
560
  redraw: () => draw(),
561
+ // 키 줄에 잠깐 안내를 띄운다 (원격 세션의 아티팩트 원본 막힘, #308).
562
+ notice: (key) => toast(key),
537
563
  };
538
564
 
539
565
  stdin.on('data', (key) => {
@@ -546,7 +572,7 @@ let lastFlush = 0;
546
572
  const writeSummaryThrottled = createSummaryWriter();
547
573
  function tick() {
548
574
  const shown = refresh({ throttle: true });
549
- if (loading.ready && view.data) writeSummaryThrottled(view.data.sessions);
575
+ if (loading.ready && view.data) writeSummaryThrottled(view.data.sessions.filter((s) => !s.host));
550
576
  const more = lastMore;
551
577
  if (more ? Date.now() - lastFlush > LOADING_FLUSH_MS : Date.now() - lastFlush > 15_000) {
552
578
  flushCache();
@@ -557,3 +583,5 @@ function tick() {
557
583
  }
558
584
 
559
585
  setTimeout(tick, 30);
586
+ // 원격은 화면에 들어간 뒤 뒤에서 부른다. 결과는 다음 갱신(1초 안)에 붙는다.
587
+ poller?.start();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sejuneoh/aitop",
3
- "version": "0.40.0",
3
+ "version": "0.41.0",
4
4
  "description": "터미널에서 Claude Code · Codex · Antigravity · Gemini 세션과 토큰을 실시간으로 보는 읽기 전용 모니터",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/config.mjs CHANGED
@@ -47,6 +47,57 @@ export function budgetDayOption(argv) {
47
47
  return { value, rest, error };
48
48
  }
49
49
 
50
+ // 원격(#308): SSH 호스트(별칭, user@host) 또는 wsl:<배포판>. 원격 실행은 remote.mjs 가 하고, 여기는 이름만 확인한다
51
+ // (remote.mjs 는 원격을 켤 때만 불러오므로 확인 규칙은 늘 불러오는 이 모듈에 둔다).
52
+ // ssh 인자로 들어가므로 - 로 시작하는 값(-oProxyCommand=…), 포트(:22), 공백·셸 메타 문자는 받지 않는다. 포트는 ~/.ssh/config 별칭으로 준다.
53
+ export const REMOTE_MAX = 16;
54
+ const SSH_HOST = /^([A-Za-z0-9][A-Za-z0-9._-]{0,63}@)?[A-Za-z0-9][A-Za-z0-9._-]{0,252}$/;
55
+ const WSL_DISTRO = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
56
+ // 'dev' → { name: 'dev', kind: 'ssh', target: 'dev' }, 'wsl:Ubuntu' → { name: 'wsl:Ubuntu', kind: 'wsl', target: 'Ubuntu' }. 잘못되면 null.
57
+ export function parseRemote(v) {
58
+ if (typeof v !== 'string') return null;
59
+ const w = /^wsl:(.*)$/i.exec(v);
60
+ if (w) return WSL_DISTRO.test(w[1]) ? { name: `wsl:${w[1]}`, kind: 'wsl', target: w[1] } : null;
61
+ return SSH_HOST.test(v) ? { name: v, kind: 'ssh', target: v } : null;
62
+ }
63
+ // 같은 원격인지 가르는 열쇠. WSL 배포판 이름은 대소문자를 가리지 않으므로(wsl.exe -d) 작은 글자로 맞춘다. ssh 호스트는 그대로.
64
+ export const remoteKey = (r) => (r.kind === 'wsl' ? r.name.toLowerCase() : r.name);
65
+ const remoteList = (v) => Array.isArray(v) && v.length > 0 && v.length <= REMOTE_MAX && v.every((x) => parseRemote(x) != null);
66
+
67
+ // argv 에서 --remote <목록>, --remote=<목록>, --no-remote 를 꺼낸다. 목록은 쉼표로 잇는다. 뒤에 준 쪽을 따른다.
68
+ // value: 이름 배열, null(--no-remote, 설정 파일 remotes 도 끔), undefined(주지 않음).
69
+ export function remoteOption(argv) {
70
+ let value;
71
+ let error = null;
72
+ const rest = [];
73
+ for (let i = 0; i < argv.length; i++) {
74
+ const a = argv[i];
75
+ if (a === '--no-remote') {
76
+ value = null;
77
+ continue;
78
+ }
79
+ const m = /^--remote(?:=(.*))?$/.exec(a);
80
+ if (!m) {
81
+ rest.push(a);
82
+ continue;
83
+ }
84
+ const next = argv[i + 1];
85
+ const raw = m[1] ?? (next == null || next.startsWith('-') ? '' : argv[++i]);
86
+ const list = raw.split(',').map((x) => x.trim()).filter(Boolean);
87
+ const bad = list.find((x) => parseRemote(x) == null);
88
+ if (!list.length) error ??= t('opt.remoteMissing');
89
+ else if (bad != null) error ??= t('opt.remoteBad', { value: JSON.stringify(stripControl(bad).slice(0, 80)) });
90
+ else if (list.length > REMOTE_MAX) error ??= t('opt.remoteMany', { n: REMOTE_MAX });
91
+ // 같은 이름을 두 번 주면 한 번만 부른다 (WSL 배포판은 대소문자 무시, 처음 적은 표기).
92
+ else {
93
+ const seen = new Map();
94
+ for (const r of list.map(parseRemote)) if (!seen.has(remoteKey(r))) seen.set(remoteKey(r), r.name);
95
+ value = [...seen.values()];
96
+ }
97
+ }
98
+ return { value, rest, error };
99
+ }
100
+
50
101
  const BOOL = ['true', 'false'];
51
102
  // 기록 폴더 목록: 절대 경로(또는 ~ 로 시작) 문자열 배열, 1~16개.
52
103
  const pathList = (v) => Array.isArray(v) && v.length > 0 && v.length <= 16 && v.every(pathLike);
@@ -88,6 +139,8 @@ export const KEYS = {
88
139
  // Claude Desktop Cowork(에이전트 모드) 세션을 담은 앱 폴더 (#304, cowork.mjs findCoworkRoots). 모양은 agyApp 과 같다.
89
140
  // AITOP_COWORK_HOME(경로 또는 off) > 설정 파일 > 기본(true, 저절로 찾음).
90
141
  cowork: { ok: (v) => bool(v) || pathList(v), expect: 'cfg.cowork', def: true, env: ['AITOP_COWORK_HOME', coworkEnv], envProblem: true, envExpect: 'cfg.agyAppEnv' },
142
+ // 모아 볼 원격 (#308): SSH 호스트 또는 wsl:<배포판> 배열, 1~16개. --remote 가 덮고 --no-remote 는 끈다 (null).
143
+ remotes: { ok: remoteList, expect: 'cfg.remotes', def: null },
91
144
  };
92
145
 
93
146
  // Windows 는 XDG_CONFIG_HOME 이 없으면 %APPDATA%\aitop\config.json.
package/src/doctor.mjs CHANGED
@@ -357,5 +357,7 @@ export function doctorText(result, version, now = Date.now(), lang = getLang())
357
357
  const on = result.log.on;
358
358
  out.push('', tr('doctor.debug', { mark: on ? '✓' : '○', state: pad(logWord, stateW), path: tilde(result.log.path), tail: on ? '' : tr('doctor.debugTail', null, o) }, o));
359
359
  }
360
+ // --remote(#308)로 정한 원격 목록. 점검은 접속하지 않는다 (네트워크를 쓰지 않음).
361
+ if (result.remotes?.length) out.push('', tr('doctor.remotes', { mark: '○', list: result.remotes.join(', ') }, o));
360
362
  return stripControl(out.join('\n'));
361
363
  }
package/src/i18n.mjs CHANGED
@@ -68,6 +68,10 @@ const HELP_KO = `{logo} aitop - 터미널에서 Claude Code · Codex · Antigrav
68
68
  1분 안에 aitop 화면·--once·--json 이 남긴 요약이 있을 때만 보인다
69
69
  aitop --json 세션 목록과 사용량 합계를 JSON 으로 한 번 출력한다 (--all 과 함께 쓸 수 있다)
70
70
  세션마다 resumeCmd 에 그 세션을 이어 여는 명령을 넣는다 (예: cd /repo && claude --resume <id>, 없으면 null)
71
+ aitop --remote dev,me@vm2,wsl:Ubuntu-22.04 SSH 원격과 WSL 배포판의 세션을 함께 본다. 각 원격에서 aitop --json --no-remote 를
72
+ ssh -o BatchMode=yes(wsl.exe -d <배포판>)로 10초마다 실행한다 (원격에도 aitop 설치 필요, 한 번에 20초 제한).
73
+ 인증은 내 ssh 설정·agent 에 맡기고 비밀번호는 묻지 않는다. 표에는 로컬 세션 아래 호스트별 '── dev · 3 세션 ──' 줄로 나뉜다.
74
+ 원격 세션은 변경 내용(diff)·아티팩트 원본을 가져오지 않고, 비용은 헤더 합계에 더하지 않는다 (설정 파일 remotes, --no-remote 로 끔)
71
75
  aitop --report daily [--by tool|model|project] [--days N] [--json] 최근 N일(기본·최대 30)의 날짜별 토큰·비용(API 정가 환산)을
72
76
  도구별·모델별·프로젝트별 표로 내고 끝낸다. 최근 날짜가 위, 맨 아래는 합계. 처음 실행은 30일치 기록을 읽느라 오래 걸릴 수 있다
73
77
  프로젝트는 작업 폴더의 마지막 이름이고, 열이 터미널 폭을 넘으면 비용이 작은 쪽을 (그 외) 로 합친다
@@ -86,14 +90,14 @@ const HELP_KO = `{logo} aitop - 터미널에서 Claude Code · Codex · Antigrav
86
90
  aitop --notify=waiting,done,context 알릴 종류를 고른다 (--notify 만 주면 설정 파일 notify 배열, 없으면 waiting). done: 3분(설정 파일 doneMinutes, 응답 대기 시간 빼고) 넘게 작업하던 세션이 다음 지시를
87
91
  기다리면 한 번. context: 컨텍스트가 90% 를 넘으면 한 번 (85% 아래로 내려가면 다시)
88
92
  aitop --on-waiting <명령> 알릴 일이 생기면 /bin/sh -c (Windows 는 cmd.exe /c) 로 명령을 실행한다 (내 권한으로 실행, 10초 제한). 종류는 --notify 를 따른다 (--no-notify 여도)
89
- 세션 정보는 환경변수로만: AITOP_EVENT(waiting|done|context) AITOP_TOOL AITOP_PROJECT AITOP_SESSION_ID AITOP_CWD AITOP_WAITING_FOR
93
+ 세션 정보는 환경변수로만: AITOP_EVENT(waiting|done|context) AITOP_TOOL AITOP_PROJECT AITOP_SESSION_ID AITOP_CWD AITOP_WAITING_FOR AITOP_HOST(원격 세션만)
90
94
  aitop --show-requests 응답 대기 요청 전체를 상세 패널·--json 에 보인다 (AITOP_SHOW_REQUESTS=1). 비밀값 가림은 최선일 뿐이라 명령 속 비밀값이 보일 수 있다
91
95
  aitop --budget-day <달러> 하루 예산. 헤더에 오늘 $12.30/$50 처럼 보이고, 오늘 끝 예상 비용(오늘 + 최근 속도 × 자정까지, 늘 API 환산)이
92
96
  80% 를 넘으면 '예상 $45', 100% 를 넘으면 '예상 $60!' 로 알린다 (AITOP_BUDGET_DAY, 설정 파일 budgetDay)
93
97
  aitop --theme light|dark 밝은 배경 / 어두운 배경 색 (없으면 COLORFGBG 로 고른다)
94
98
  aitop --color-blind 적록 색약용 색. 응답 대기·돈·경고·diff 를 노랑·파랑 계열로 가른다 (AITOP_COLOR_BLIND=1, 설정 파일 colorBlind). --theme 과 함께 쓴다
95
99
  aitop --lang ko|en 화면·--help·--doctor·오류 문구의 언어 (AITOP_LANG, 설정 파일 lang, 없으면 LC_ALL·LC_MESSAGES·LANG 이 ko 로 시작할 때 한국어)
96
- aitop --no-bell · --no-all · --no-show-requests · --no-notify · --no-on-waiting · --no-budget-day · --no-debug · --no-color-blind 설정 파일에서 켠 값을 이번 실행만 끈다
100
+ aitop --no-bell · --no-all · --no-show-requests · --no-notify · --no-on-waiting · --no-budget-day · --no-debug · --no-color-blind · --no-remote 설정 파일에서 켠 값을 이번 실행만 끈다
97
101
  aitop --debug 디버그 로그를 남긴다 (AITOP_DEBUG=1, 설정 파일 debug). 기록 형식이 바뀌어 값이 빌 때 원인 확인용
98
102
  {logPath} (1MB 넘으면 .1 로 하나만 남김, 오류 이름·파일 이름만 쓰고 비밀값은 가림)
99
103
  aitop --print-config 설정 값마다 값과 출처(flag/env/file/default), 설정 파일 위치를 보인다 (--json 과 함께 쓸 수 있다)
@@ -109,6 +113,7 @@ const HELP_KO = `{logo} aitop - 터미널에서 Claude Code · Codex · Antigrav
109
113
  claudeDirs, codexHomes: 읽을 Claude 설정 폴더·Codex 홈 목록 (예: ["~/.claude", "~/.claude-work"], 기본 ~/.claude, ~/.codex).
110
114
  AITOP_CLAUDE_DIRS, AITOP_CODEX_HOMES 에 경로를 : (Windows 는 ;) 로 이어 주면 설정 파일보다 먼저 쓴다.
111
115
  설정 파일 목록이 있으면 물려받은 CLAUDE_CONFIG_DIR, CODEX_HOME 은 쓰지 않는다 (없으면 그 경로를 읽는다)
116
+ remotes: 모아 볼 원격 목록 (예: ["dev", "wsl:Ubuntu"]). --remote 가 덮는다
112
117
  onWaiting 은 파일 소유자가 나이고 그룹·다른 사용자가 쓸 수 없을 때(chmod 600)만 받는다.
113
118
  옵션 > 환경 변수 > 설정 파일 순서로 정한다. 잘못된 값은 무시하고 --doctor 에 알린다.
114
119
 
@@ -128,6 +133,10 @@ const HELP_EN = `{logo} aitop - watch Claude Code, Codex, Antigravity and Gemini
128
133
  show only when the live screen, --once or --json left a summary in the last minute
129
134
  aitop --json print the session list and usage totals as JSON once (works with --all)
130
135
  Each session has resumeCmd, the command that reopens it (e.g. cd /repo && claude --resume <id>, null if none)
136
+ aitop --remote dev,me@vm2,wsl:Ubuntu-22.04 also show sessions on SSH hosts and WSL distros. Runs aitop --json --no-remote on each one
137
+ with ssh -o BatchMode=yes (wsl.exe -d <distro>) every 10 seconds (aitop must be installed there, 20 second limit per call).
138
+ Auth is left to your ssh config and agent; no password prompts. The table splits them below local sessions with '── dev · 3 sessions ──' lines.
139
+ Remote diffs and artifact sources are not fetched, and remote cost is not added to the header (config remotes, off with --no-remote)
131
140
  aitop --report daily [--by tool|model|project] [--days N] [--json] print daily tokens and cost (API list price) for the last N days
132
141
  (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
133
142
  A project is the last folder name of the working directory. Columns beyond the terminal width are merged into (others)
@@ -148,14 +157,14 @@ const HELP_EN = `{logo} aitop - watch Claude Code, Codex, Antigravity and Gemini
148
157
  aitop --notify=waiting,done,context pick what to notify about (plain --notify: the config notify list, else waiting). done: once when a session that worked for
149
158
  over 3 minutes (config doneMinutes, approval waits not counted) waits for its next instruction. context: once when context passes 90% (again after it drops below 85%)
150
159
  aitop --on-waiting <cmd> run a command with /bin/sh -c (cmd.exe /c on Windows) when there is something to notify (runs as you, 10 second limit). Follows the --notify kinds (even with --no-notify)
151
- Session info is passed only in env vars: AITOP_EVENT(waiting|done|context) AITOP_TOOL AITOP_PROJECT AITOP_SESSION_ID AITOP_CWD AITOP_WAITING_FOR
160
+ Session info is passed only in env vars: AITOP_EVENT(waiting|done|context) AITOP_TOOL AITOP_PROJECT AITOP_SESSION_ID AITOP_CWD AITOP_WAITING_FOR AITOP_HOST(remote sessions only)
152
161
  aitop --show-requests show full waiting requests in the detail panel and --json (AITOP_SHOW_REQUESTS=1). Secret masking is best effort, so secrets in commands may show
153
162
  aitop --budget-day <usd> daily budget. The header shows today $12.30/$50, and it warns when the projected end-of-day cost (today + recent rate until midnight, always API cost)
154
163
  passes 80%, and in the warning color with ! past 100% (AITOP_BUDGET_DAY, config budgetDay)
155
164
  aitop --theme light|dark colors for a light or dark background (picked from COLORFGBG if not set)
156
165
  aitop --color-blind red-green color blind palette. Waiting, money, warnings and diffs use yellow and blue (AITOP_COLOR_BLIND=1, config colorBlind). Works with --theme
157
166
  aitop --lang ko|en language for the screen, --help, --doctor and error messages (AITOP_LANG, config lang, else Korean when LC_ALL, LC_MESSAGES or LANG starts with ko)
158
- aitop --no-bell · --no-all · --no-show-requests · --no-notify · --no-on-waiting · --no-budget-day · --no-debug · --no-color-blind turn off a config file setting for this run
167
+ aitop --no-bell · --no-all · --no-show-requests · --no-notify · --no-on-waiting · --no-budget-day · --no-debug · --no-color-blind · --no-remote turn off a config file setting for this run
159
168
  aitop --debug write a debug log (AITOP_DEBUG=1, config debug). Useful when a log format changes and values go blank
160
169
  {logPath} (keeps one .1 file past 1MB, writes only error and file names, masks secrets)
161
170
  aitop --print-config show each setting with its value, source (flag/env/file/default) and the config file path (works with --json)
@@ -171,6 +180,7 @@ const HELP_EN = `{logo} aitop - watch Claude Code, Codex, Antigravity and Gemini
171
180
  claudeDirs, codexHomes: Claude config folders and Codex homes to read (e.g. ["~/.claude", "~/.claude-work"], default ~/.claude, ~/.codex).
172
181
  AITOP_CLAUDE_DIRS and AITOP_CODEX_HOMES take paths joined with : (; on Windows) and win over the config file.
173
182
  With a config list, an inherited CLAUDE_CONFIG_DIR or CODEX_HOME is not used (without one, that path is read)
183
+ remotes: remote hosts to show (e.g. ["dev", "wsl:Ubuntu"]). --remote overrides it
174
184
  onWaiting is accepted only when you own the file and no group or other user can write it (chmod 600).
175
185
  Order: option > env var > config file. Bad values are ignored and reported by --doctor.
176
186
 
@@ -267,6 +277,9 @@ export const STRINGS = {
267
277
  'opt.daysDaily': '--days 는 --report daily 와 함께 쓴다 (monthly 는 --months)',
268
278
  'opt.monthsMonthly': '--months 는 --report monthly 와 함께 쓴다 (daily 는 --days)',
269
279
  'opt.reportOnly': '--by, --days, --months 는 --report 와 함께 쓴다',
280
+ 'opt.remoteMissing': '--remote 값이 없습니다 (쉼표로 이은 SSH 호스트 또는 wsl:<배포판>)',
281
+ 'opt.remoteBad': '--remote 값 {value} 이 잘못되었습니다 (SSH 호스트 별칭·user@host 또는 wsl:<배포판>. - 로 시작하는 값·포트(:22)·공백은 받지 않는다. 포트는 ~/.ssh/config 별칭으로 준다)',
282
+ 'opt.remoteMany': '--remote 는 {n}개까지 준다',
270
283
 
271
284
  // 기간 리포트 (--report daily). 도구·모델 이름은 번역하지 않는다.
272
285
  'report.title': '날짜별 사용량 · 최근 {n}일 ({from} ~ {to}) · {by} · API 정가 환산',
@@ -348,6 +361,7 @@ export const STRINGS = {
348
361
  'cfg.paths': '절대 경로(또는 ~/...) 문자열 배열, 1~16개',
349
362
  'cfg.agyApp': 'true, false 또는 절대 경로(또는 ~/...) 배열',
350
363
  'cfg.cowork': 'true, false 또는 Claude 앱 폴더 절대 경로(또는 ~/...) 배열',
364
+ 'cfg.remotes': 'SSH 호스트(별칭·user@host) 또는 "wsl:<배포판>" 문자열 배열, 1~16개',
351
365
  'cfg.agyAppEnv': 'off 또는 절대 경로(또는 ~/...) 목록',
352
366
  'cfg.masked': '설정 파일의 {key} 는 {name} 이 있어 무시합니다',
353
367
  'cfg.file': '설정 파일: {path} ({state})',
@@ -400,6 +414,7 @@ export const STRINGS = {
400
414
  'doctor.debugOn': '켬',
401
415
  'doctor.debugOff': '꺼짐',
402
416
  'doctor.debugTail': ' · --debug 로 켬',
417
+ 'doctor.remotes': '{mark} 원격 {list} (점검에서는 접속하지 않는다)',
403
418
 
404
419
  // 상태 문구 (phaseText 가 phase.msg ?? phase.kind 로 고른다). --json 의 phase 는 늘 이 한국어 표로 만든다.
405
420
  'phase.ended': '종료',
@@ -471,6 +486,19 @@ export const STRINGS = {
471
486
  'member.sdk': '-p',
472
487
  'session.auto': '자동',
473
488
  'group.count': '{n}개',
489
+ // 원격 호스트 구분 줄 (#308): '── dev · 3 세션 · 10초 전 ──', 실패하면 '── dev · 연결 안 됨 (시간 초과) ──'.
490
+ 'remote.count': '{n} 세션',
491
+ 'remote.secAgo': '{n}초 전',
492
+ 'remote.minAgo': '{n}분 전',
493
+ 'remote.pending': '연결 중…',
494
+ 'remote.down': '연결 안 됨 ({why})',
495
+ 'remote.err.auth': '인증 실패',
496
+ 'remote.err.unreachable': '접속 실패',
497
+ 'remote.err.notFound': '원격에 aitop 없음',
498
+ 'remote.err.old': '원격 aitop 이 옛 버전',
499
+ 'remote.err.newer': '원격 aitop 이 더 새 버전',
500
+ 'remote.err.timeout': '시간 초과',
501
+ 'remote.err.bad': '잘못된 응답',
474
502
  'group.waiting': '응답 대기',
475
503
  'group.pinned': '고정',
476
504
  'group.noFolder': '(폴더 없음)',
@@ -512,6 +540,7 @@ export const STRINGS = {
512
540
  'foot.costMode': '비용 기준',
513
541
  'foot.copied': '이어 여는 명령을 클립보드로 보냄 (OSC 52)',
514
542
  'foot.copyNone': '이 세션은 이어 여는 명령이 없다',
543
+ 'foot.remoteNoSource': '원격 세션은 아티팩트 원본을 열 수 없다 (링크만)',
515
544
  'foot.notify': '알림:{v}',
516
545
  'foot.notifyHint': '응답 대기 알림 켜기: a',
517
546
  'foot.notifyOn': '응답 대기 알림 켬 (이번 실행만)',
@@ -635,6 +664,8 @@ export const STRINGS = {
635
664
  'detail.hidden': '비밀값이 있을 수 있는 파일이라 변경 내용을 숨겼습니다',
636
665
  'detail.deleted': '이 파일을 삭제했습니다',
637
666
  'detail.noHunks': '보관된 변경 내용이 없습니다',
667
+ 'detail.remoteDiff': '원격 세션은 변경 내용 없음 (파일 통계만 받는다)',
668
+ 'detail.host': '호스트',
638
669
  // 소스(claude·codex)가 메인 세션의 변경에 붙이는 이름. 화면에서만 바꾼다.
639
670
  'detail.main': '메인',
640
671
  'detail.cut': '… {n}줄 생략',
@@ -798,6 +829,9 @@ export const STRINGS = {
798
829
  'opt.daysDaily': '--days only works with --report daily (use --months for monthly)',
799
830
  'opt.monthsMonthly': '--months only works with --report monthly (use --days for daily)',
800
831
  'opt.reportOnly': '--by, --days and --months only work with --report',
832
+ 'opt.remoteMissing': '--remote needs a value (SSH hosts or wsl:<distro>, joined with commas)',
833
+ 'opt.remoteBad': 'bad --remote value {value} (an SSH host alias, user@host or wsl:<distro>. Values starting with -, ports (:22) and spaces are not accepted. Set a port with an alias in ~/.ssh/config)',
834
+ 'opt.remoteMany': '--remote takes at most {n} hosts',
801
835
 
802
836
  'report.title': 'Daily usage, last {n} days ({from} to {to}), {by}, API list price',
803
837
  'report.by.tool': 'by tool',
@@ -877,6 +911,7 @@ export const STRINGS = {
877
911
  'cfg.paths': 'a list of 1 to 16 absolute paths (or ~/...)',
878
912
  'cfg.agyApp': 'true, false, or a list of absolute paths (or ~/...)',
879
913
  'cfg.cowork': 'true, false, or a list of absolute Claude app folder paths (or ~/...)',
914
+ 'cfg.remotes': 'a list of 1 to 16 SSH hosts (alias or user@host) or "wsl:<distro>" strings',
880
915
  'cfg.agyAppEnv': 'off or a list of absolute paths (or ~/...)',
881
916
  'cfg.masked': 'ignoring {key} in the config file because {name} is set',
882
917
  'cfg.file': 'Config file: {path} ({state})',
@@ -929,6 +964,7 @@ export const STRINGS = {
929
964
  'doctor.debugOn': 'on',
930
965
  'doctor.debugOff': 'off',
931
966
  'doctor.debugTail': ' · turn on with --debug',
967
+ 'doctor.remotes': '{mark} remote {list} (not contacted by the check)',
932
968
 
933
969
  'phase.ended': 'Ended',
934
970
  'phase.done': 'Done',
@@ -993,6 +1029,18 @@ export const STRINGS = {
993
1029
  'member.sdk': '-p',
994
1030
  'session.auto': 'auto',
995
1031
  'group.count': '{n}',
1032
+ 'remote.count': '{n} sessions',
1033
+ 'remote.secAgo': '{n}s ago',
1034
+ 'remote.minAgo': '{n}m ago',
1035
+ 'remote.pending': 'connecting…',
1036
+ 'remote.down': 'not connected ({why})',
1037
+ 'remote.err.auth': 'auth failed',
1038
+ 'remote.err.unreachable': 'unreachable',
1039
+ 'remote.err.notFound': 'no aitop on remote',
1040
+ 'remote.err.old': 'remote aitop too old',
1041
+ 'remote.err.newer': 'remote aitop newer',
1042
+ 'remote.err.timeout': 'timed out',
1043
+ 'remote.err.bad': 'bad response',
996
1044
  'group.waiting': 'Waiting',
997
1045
  'group.pinned': 'Pinned',
998
1046
  'group.noFolder': '(no folder)',
@@ -1034,6 +1082,7 @@ export const STRINGS = {
1034
1082
  'foot.costMode': 'cost',
1035
1083
  'foot.copied': 'resume command sent to clipboard (OSC 52)',
1036
1084
  'foot.copyNone': 'no resume command for this session',
1085
+ 'foot.remoteNoSource': 'remote sessions cannot open artifact sources (link only)',
1037
1086
  'foot.notify': 'alerts:{v}',
1038
1087
  'foot.notifyHint': 'turn on waiting alerts: a',
1039
1088
  'foot.notifyOn': 'waiting alerts on (this run only)',
@@ -1155,6 +1204,8 @@ export const STRINGS = {
1155
1204
  'detail.hidden': 'Changes hidden because this file may hold secrets',
1156
1205
  'detail.deleted': 'This file was deleted',
1157
1206
  'detail.noHunks': 'No saved changes',
1207
+ 'detail.remoteDiff': 'No changes for remote sessions (file stats only)',
1208
+ 'detail.host': 'Host',
1158
1209
  'detail.main': 'main',
1159
1210
  'detail.cut': { one: '… {n} line cut', other: '… {n} lines cut' },
1160
1211
  'detail.dropped': { one: '… {n} older change cut (over the limit)', other: '… {n} older changes cut (over the limit)' },
package/src/json.mjs CHANGED
@@ -21,20 +21,32 @@ const usageOf = (u) => (u ? { ...u, ...('cost' in u ? { cost: money(u.cost) } :
21
21
 
22
22
  // version 은 aitop 버전, tools 는 aitop --doctor 와 같은 도구별 점검 결과다.
23
23
  // opts.showRequests: 응답 대기 요청 전체(waitDetail)를 넣는다. 기본은 꺼져 있다.
24
+ // opts.platform: 원격 세션(#308) resumeCmd 의 로컬 셸 따옴표를 고르는 플랫폼 (기본 process.platform, 테스트에서 바꿔 끼운다).
24
25
  // opts.budgetDay: 하루 예산. 있으면 usage.budget 에 예산, 오늘 끝 예상 비용(API 정가 환산, 화면과 같은 기준), 단계를 넣는다.
25
26
  // --json 의 phase 문구. 한국어 표로 만든다 (영어 화면 1/3 의 계약).
26
27
  const koPhase = (p) => (p?.kind ? phaseText(p, { lang: 'ko' }) : null);
27
28
 
29
+ // --json 모양의 버전 (#308). 다른 aitop 이 --remote 로 이 출력을 읽을 때 모양이 맞는지 본다.
30
+ // 필드를 더하기만 하면 그대로 두고, 있던 필드의 뜻이나 모양을 바꿀 때 올린다.
31
+ export const SCHEMA = 1;
32
+ const remoteOf = (r) => ({ name: r.name, kind: r.kind, ok: Boolean(r.ok), error: r.error ?? null, version: r.version ?? null, schema: r.schema ?? null, at: iso(r.at) });
33
+
28
34
  export function toJson(data, version = null, opts = {}) {
29
35
  const b = data.usage ? projectBudget(data.usage, opts.budgetDay, { now: data.at ?? Date.now() }) : null;
30
36
  return {
31
37
  version,
38
+ schema: SCHEMA,
32
39
  at: iso(data.at),
33
40
  tools: toolsJson(data.tools?.tools),
34
41
  usage: data.usage ? { today: usageOf(data.usage.today), last7days: { ...usageOf(data.usage.week), ...dailyOf(data.usage.days7) }, lastHour: lastHourOf(data.usage.lastHour), complete: data.usage.loading == null, ...(b ? { budget: { day: b.day, projected: money(b.projected), unknown: b.unknown, level: b.level } } : {}) } : null,
42
+ // --remote 로 모은 원격마다 마지막 결과 (#308). 원격을 켜지 않으면 빈 배열. at 은 마지막으로 성공한 시각.
43
+ remotes: (data.remotes ?? []).map(remoteOf),
35
44
  sessions: data.sessions.map((s) => ({
36
45
  tool: s.tool,
46
+ // 원격 세션의 id 는 '<host>:<원래 id>' 이고 원래 id 는 remoteId 에 있다. 로컬 세션은 host·remoteId 가 null.
37
47
  id: s.id,
48
+ host: s.host ?? null,
49
+ remoteId: s.host ? (s.remoteId ?? null) : null,
38
50
  name: s.name ?? null,
39
51
  project: s.project ?? null,
40
52
  cwd: s.cwd ?? null,
@@ -61,7 +73,7 @@ export function toJson(data, version = null, opts = {}) {
61
73
  toolStartedAt: iso(s.toolStartedAt),
62
74
  waitingFor: s.waitingFor ?? null,
63
75
  // 이 세션을 이어 여는 셸 명령 (resume.mjs). 만들 수 없으면 null.
64
- resumeCmd: resumeCmd(s),
76
+ resumeCmd: resumeCmd(s, { platform: opts.platform }),
65
77
  // 허락을 기다리는 요청의 전체 내용 (Bash 명령, 파일 경로 등). --show-requests 를 켰을 때만 넣는다. 비밀값 가림은 최선을 다할 뿐이다.
66
78
  ...(opts.showRequests ? { waitDetail: s.waitDetail ?? null } : {}),
67
79
  now: s.now || null,
package/src/keys.mjs CHANGED
@@ -127,6 +127,11 @@ function stepArtifact(view, delta) {
127
127
  function openArtifact(view, act) {
128
128
  const a = pickedArtifact(view);
129
129
  if (!a) return;
130
+ // 원격 세션(#308)의 원본은 원격 기록에 있어 열지 않는다. 목록에 남고 키 줄에 안내만 띄운다.
131
+ if (selectedSession(view)?.host) {
132
+ act?.notice?.('foot.remoteNoSource');
133
+ return;
134
+ }
130
135
  view.focus = 'artifact';
131
136
  view.artScroll = 0;
132
137
  if (act?.loadArtifact) {
package/src/notify.mjs CHANGED
@@ -224,11 +224,14 @@ export function waitingEnv(s) {
224
224
  AITOP_SESSION_ID: String(s.id ?? ''),
225
225
  AITOP_CWD: String(s.cwd ?? ''),
226
226
  AITOP_WAITING_FOR: waitingLabel(s),
227
+ // --remote 로 본 원격 세션이면 그 호스트 이름 (#308). 로컬 세션은 빈 값.
228
+ AITOP_HOST: String(s.host ?? ''),
227
229
  };
228
230
  }
229
231
 
230
232
  // 알림 본문의 세션 이름: 사용자가 붙인 이름(/rename, thread_name)이 있으면 그것, 없으면 예전처럼 프로젝트.
231
- const whoOf = (s) => s.customName || s.project || s.id || '';
233
+ // 원격 세션(#308)은 앞에 호스트를 붙인다 (dev · aitop).
234
+ const whoOf = (s) => (s.host ? `${s.host} · ` : '') + (s.customName || s.project || s.id || '');
232
235
 
233
236
  // 알림 제목·본문은 화면 언어를 따른다 (AITOP_WAITING_FOR 와 달리 사람이 읽는 글이라).
234
237
  // kind 가 done·context 면 그 종류의 문구를 쓴다. context 본문에는 사용률(%)을 붙인다.
package/src/order.mjs CHANGED
@@ -53,7 +53,18 @@ const GROUP_KEY = { project: projectOf, tool: (s) => s.tool ?? '?' };
53
53
  // groups 는 묶을 때만 있다: { name, count, cost, unknown, waiting, pinned, sessions }. 묶음은 그 안의 첫 세션이 정렬에서 앞선 순으로 놓인다.
54
54
  // pins: 고정한 세션 id (고정한 순서). 화면에 없는 id 는 건너뛴다.
55
55
  // ready: false 면 준비 완료 전이다 (compare 참고). 응답 대기 세션은 그동안에도 맨 위로 올린다.
56
- export function arrange(sessions, { sort = 'default', group = 'none', costMode = 'api', pins = [], ready = true } = {}) {
56
+ // --remote(#308)로 받은 원격 세션(host 가 있는 세션)은 로컬 세션 아래에 호스트별 구획으로 둔다. 구획 안의 정렬·묶기·대기 우선은 위 규칙 그대로다.
57
+ // 그때 hosts 는 [{ host, sessions, groups }] (원격 순서는 remotes 에 준 이름 순서, 없으면 처음 나온 순서), sessions·groups 는 로컬 몫과 구획을 차례로 이은 것이다.
58
+ // 원격 세션이 없으면 hosts 는 null 이고 결과는 예전과 같다.
59
+ export function arrange(sessions, opts = {}) {
60
+ if (!sessions.some((s) => s.host)) return { ...arrangeOne(sessions, opts), hosts: null };
61
+ const local = arrangeOne(sessions.filter((s) => !s.host), opts);
62
+ const names = [...new Set([...(opts.remotes ?? []).map((r) => r.name), ...sessions.filter((s) => s.host).map((s) => s.host)])];
63
+ const hosts = names.map((host) => ({ host, ...arrangeOne(sessions.filter((s) => s.host === host), opts) }));
64
+ return { sessions: [...local.sessions, ...hosts.flatMap((h) => h.sessions)], groups: local.groups, hosts };
65
+ }
66
+
67
+ function arrangeOne(sessions, { sort = 'default', group = 'none', costMode = 'api', pins = [], ready = true } = {}) {
57
68
  const cmp = compare(sort, costMode, ready);
58
69
  const rank = new Map((pins ?? []).map((id, i) => [id, i]));
59
70
  const waiting = sessions.filter(callsYou).sort(cmp);
package/src/remote.mjs ADDED
@@ -0,0 +1,372 @@
1
+ // --remote (#308): SSH 원격과 WSL 배포판에서 `aitop --json --no-remote` 를 돌려 그 세션을 함께 본다.
2
+ // 원격을 켰을 때만 bin 이 이 모듈을 불러온다 (켜지 않으면 시작 시간·화면이 예전과 같다).
3
+ // 실행은 child_process.execFile 에 인자 배열로만 한다 (셸 없음). 인증·호스트 신뢰는 사용자의 ssh 설정·agent 에 맡기고
4
+ // BatchMode=yes 로 비밀번호를 묻지 않게 한다. StrictHostKeyChecking 은 건드리지 않는다.
5
+ // 원격 출력은 믿지 않는 입력이다: 정해진 필드만 골라 값을 확인하고 다시 만든다. 원격 stderr 는 화면에 내지 않는다.
6
+ import { execFile } from 'node:child_process';
7
+ import { STRINGS } from './i18n.mjs';
8
+ import { mask, stripControl } from './text.mjs';
9
+ import { artifactLink } from './sources/artifacts.mjs';
10
+ import { SCHEMA } from './json.mjs';
11
+ import { bySession } from './collect.mjs';
12
+ import { parseRemote, remoteKey } from './config.mjs';
13
+
14
+ // 한 번 호출의 시간 상한, 출력 상한, 다시 부르는 간격. AITOP_REMOTE_TIMEOUT_MS 는 테스트에서 시간 초과를 짧게 흉내 낼 때 쓴다.
15
+ export const TIMEOUT_MS = 20_000;
16
+ export const MAX_BUFFER = 8 * 1024 * 1024;
17
+ export const INTERVAL_MS = 10_000;
18
+ // 원격 하나에서 받는 개수 상한.
19
+ export const MAX_SESSIONS = 500;
20
+ export const MAX_FILES = 200;
21
+ export const MAX_MEMBERS = 50;
22
+ export const MAX_ARTIFACTS = 20;
23
+ const STR_MAX = 200;
24
+ // 폴더·파일 경로는 줄이면 이어 열기(y)와 파일 이름이 틀어지므로 조금 길게 둔다.
25
+ const PATH_MAX = 1024;
26
+
27
+ const REMOTE_ARGS = ['aitop', '--json', '--no-remote'];
28
+
29
+ // 실행할 파일과 인자. fake(AITOP_REMOTE_FAKE, 테스트 전용 node 스크립트)가 있으면 ssh·wsl.exe 대신 그 스크립트를 node 로 부른다:
30
+ // node <script> <ssh|wsl> <대상> aitop --json --no-remote. 셸을 거치지 않으므로 Windows CI 에서도 같다.
31
+ export function remoteCommand(r, { fake = process.env.AITOP_REMOTE_FAKE, node = process.execPath } = {}) {
32
+ if (fake) return [node, [fake, r.kind, r.target, ...REMOTE_ARGS]];
33
+ if (r.kind === 'wsl') return ['wsl.exe', ['-d', r.target, '--', ...REMOTE_ARGS]];
34
+ return ['ssh', ['-o', 'BatchMode=yes', '-o', 'ConnectTimeout=5', '-T', '--', r.target, ...REMOTE_ARGS]];
35
+ }
36
+
37
+ // wsl.exe 의 오류 출력은 UTF-16 이라 글자 사이에 NUL 이 낀다. 판정에만 쓰므로 NUL 을 지우고 읽는다.
38
+ const errText = (b) => String(Buffer.isBuffer(b) ? b.toString('utf8') : (b ?? '')).replace(/\0/g, '');
39
+
40
+ // 끝난 호출을 오류 코드로 가른다. ok 면 null.
41
+ // auth: ssh 인증·호스트 키 실패, unreachable: 접속 실패(그 밖의 ssh 255, 없는 배포판 등), notFound: 원격에 aitop 이 없음(127) 또는 ssh·wsl.exe 가 없음,
42
+ // old: --no-remote 를 모르는 옛 aitop(2) 또는 schema 가 없는 출력, newer: 더 큰 schema, timeout: 시간 초과, bad: 깨진 JSON·크기 초과.
43
+ export function classify({ err = null, stdout = '', stderr = '' } = {}) {
44
+ if (err) {
45
+ if (err.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER') return { error: 'bad' };
46
+ if (err.code === 'ENOENT') return { error: 'notFound' };
47
+ if (err.killed || err.timedOut) return { error: 'timeout' };
48
+ const code = typeof err.code === 'number' ? err.code : null;
49
+ const why = errText(stderr);
50
+ if (code === 127) return { error: 'notFound' };
51
+ if (code === 2) return { error: 'old' };
52
+ if (/permission denied|host key verification failed|too many authentication failures|no supported authentication/i.test(why)) return { error: 'auth' };
53
+ if (/command not found|not recognized|no such file or directory/i.test(why) && code !== 255) return { error: 'notFound' };
54
+ return { error: 'unreachable' };
55
+ }
56
+ let json;
57
+ try {
58
+ json = JSON.parse(errText(stdout));
59
+ } catch {
60
+ return { error: 'bad' };
61
+ }
62
+ if (!json || typeof json !== 'object' || Array.isArray(json) || !Array.isArray(json.sessions)) return { error: 'bad' };
63
+ if (typeof json.schema !== 'number' || !Number.isInteger(json.schema)) return { error: 'old', version: cleanStr(json.version, 40) };
64
+ if (json.schema > SCHEMA) return { error: 'newer', version: cleanStr(json.version, 40), schema: json.schema };
65
+ return { error: null, json };
66
+ }
67
+
68
+ // ── 정리 규칙 ────────────────────────────────────────────
69
+
70
+ const TOOLS = new Set(['claude', 'codex', 'gemini', 'cowork']);
71
+ const STATUSES = new Set(['waiting', 'busy', 'shell', 'live', 'idle', 'ended']);
72
+ const MEMBER_STATUSES = new Set(['busy', 'idle', 'waiting', 'done']);
73
+ const STOP_KINDS = new Set(['auth', 'network', 'api']);
74
+ const SOURCES = new Set(['cli', 'app']);
75
+
76
+ export function cleanStr(v, max = STR_MAX) {
77
+ if (typeof v !== 'string') return null;
78
+ // 색·커서 이동 같은 escape 열은 통째로 지운 뒤 남은 제어 문자를 지운다 (ESC 만 지우면 '[31m' 이 글자로 남는다).
79
+ const s = mask(stripControl(v.replace(/\x1b\[[0-9;?]*[ -\/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)?/g, ''))).replace(/[\t\n\r]/g, ' ').slice(0, max);
80
+ return s || null;
81
+ }
82
+ const num = (v) => (typeof v === 'number' && Number.isFinite(v) && v >= 0 ? v : null);
83
+ const count = (v) => num(v) ?? 0;
84
+ const time = (v) => {
85
+ if (typeof v !== 'string' || v.length > 40) return null;
86
+ const ms = Date.parse(v);
87
+ return Number.isFinite(ms) && ms > 0 ? ms : null;
88
+ };
89
+ const arr = (v, max) => (Array.isArray(v) ? v.slice(0, max) : []);
90
+ const obj = (v) => (v && typeof v === 'object' && !Array.isArray(v) ? v : {});
91
+
92
+ // --json 의 phase 는 늘 한국어 문구(i18n.mjs 의 ko 표)라, 그 표를 거꾸로 맞춰 phase 객체({ kind, msg, args })를 되살린다.
93
+ // 그래야 영어 화면에서도 지금 언어로 보이고, 응답 대기 사유(what)가 알림에 들어간다. 맞는 문구가 없으면 kind 의 기본 문구를 쓴다.
94
+ const PHASE_MSGS = {
95
+ ended: ['ended'],
96
+ done: ['done'],
97
+ idle: ['idle', 'starting', 'firstInput', 'noPrompt', 'geminiLimited', 'agyOldNode'],
98
+ waiting: ['waiting'],
99
+ stopped: ['stopAuth', 'stopNetwork', 'stopApi'],
100
+ tool: ['tool', 'shell', 'toolUnknown'],
101
+ team: ['team'],
102
+ think: ['think', 'working', 'steps', 'loading'],
103
+ write: ['write'],
104
+ };
105
+ const FALLBACK_MSG = { tool: 'toolUnknown', think: 'working', stopped: 'stopApi' };
106
+ const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
107
+ const templateRe = (tpl) => new RegExp(`^${escapeRe(tpl).replace(/\\\{(\w+)\\\}/g, '(?<$1>.+?)')}$`);
108
+ const AGENTS_RE = new RegExp(`^(.*) · ${escapeRe(STRINGS.ko['phase.agents']).replace(/\\\{n\\\}/, '(\\d+)')}$`);
109
+
110
+ export function phaseFrom(kind, text) {
111
+ if (kind === 'unseen') kind = 'done';
112
+ if (typeof kind !== 'string' || !Object.hasOwn(PHASE_MSGS, kind)) return null;
113
+ let rest = cleanStr(text) ?? '';
114
+ const args = {};
115
+ const ag = AGENTS_RE.exec(rest);
116
+ if (ag) {
117
+ rest = ag[1];
118
+ args.agents = Math.min(999, Number(ag[2]));
119
+ }
120
+ if (kind === 'waiting') {
121
+ const head = STRINGS.ko['phase.waiting'];
122
+ if (rest.startsWith(`${head} · `)) args.what = rest.slice(head.length + 3);
123
+ return { kind, args };
124
+ }
125
+ for (const msg of PHASE_MSGS[kind]) {
126
+ const m = templateRe(STRINGS.ko[`phase.${msg}`]).exec(rest);
127
+ if (m) return { kind, ...(msg !== kind ? { msg } : {}), args: { ...m.groups, ...args } };
128
+ }
129
+ const msg = FALLBACK_MSG[kind];
130
+ return { kind, ...(msg ? { msg } : {}), args };
131
+ }
132
+
133
+ function cleanTokens(t) {
134
+ const o = obj(t);
135
+ const opt = (v) => num(v);
136
+ return { total: count(o.total), input: count(o.input), output: count(o.output), cacheRead: count(o.cacheRead), cacheWrite: count(o.cacheWrite), main: opt(o.main), sub: opt(o.sub), subCount: opt(o.subCount) };
137
+ }
138
+
139
+ function cleanFile(f) {
140
+ const o = obj(f);
141
+ const path = cleanStr(o.path, PATH_MAX);
142
+ if (!path) return null;
143
+ // 변경 내용(diff)은 받지 않는다. 상세 패널이 '원격 세션은 변경 내용 없음' 을 보이도록 remote 를 붙인다.
144
+ return { path, created: o.created === true, edits: count(o.edits), add: count(o.writtenLines), del: count(o.deletedLines), at: time(o.updatedAt) ?? 0, agents: arr(o.agents, 10).map((x) => cleanStr(x, 60)).filter(Boolean), hunks: [], remote: true };
145
+ }
146
+
147
+ function cleanMember(m) {
148
+ const o = obj(m);
149
+ const name = cleanStr(o.name, 80);
150
+ if (!name) return null;
151
+ return {
152
+ name,
153
+ task: cleanStr(o.task),
154
+ model: cleanStr(o.model, 80),
155
+ status: MEMBER_STATUSES.has(o.status) ? o.status : 'done',
156
+ phase: phaseFrom(o.phaseKind, o.phase),
157
+ tokens: count(o.tokens),
158
+ cost: num(o.cost),
159
+ startedAt: time(o.startedAt),
160
+ lastActivityAt: time(o.lastActivityAt),
161
+ };
162
+ }
163
+
164
+ function cleanArtifact(a, i) {
165
+ const o = obj(a);
166
+ return { id: `r${i}`, title: cleanStr(o.title), url: artifactLink(o.url), from: num(o.versionFrom), to: num(o.versionTo), at: time(o.updatedAt) ?? 0, audience: cleanStr(o.audience, 20), edits: o.viaEdits === true };
167
+ }
168
+
169
+ // 원격 세션 하나를 허용 필드만으로 다시 만든다. 쓸 수 없으면 null.
170
+ // waitDetail·resumeCmd·pid·tools·usage 는 받지 않는다 (이어 열기는 resume.mjs 가 host·remoteId 로 다시 만든다).
171
+ export function cleanSession(raw, host) {
172
+ const o = obj(raw);
173
+ const remoteId = cleanStr(o.id);
174
+ if (!remoteId || !TOOLS.has(o.tool)) return null;
175
+ const status = STATUSES.has(o.status) ? o.status : 'idle';
176
+ const stop = obj(o.stopReason);
177
+ const ctx = obj(o.context);
178
+ const phase = phaseFrom(o.phaseKind, o.phase);
179
+ return {
180
+ tool: o.tool,
181
+ id: `${host}:${remoteId}`,
182
+ remoteId,
183
+ host,
184
+ name: cleanStr(o.name),
185
+ project: cleanStr(o.project),
186
+ cwd: cleanStr(o.cwd, PATH_MAX),
187
+ branch: cleanStr(o.branch),
188
+ model: cleanStr(o.model, 80),
189
+ kind: cleanStr(o.kind, 40),
190
+ entrypoint: cleanStr(o.entrypoint, 40),
191
+ source: SOURCES.has(o.source) ? o.source : null,
192
+ auto: o.auto === true,
193
+ live: o.live === true,
194
+ status,
195
+ phase: phase ?? (status === 'ended' ? { kind: 'ended' } : null),
196
+ stopReason: STOP_KINDS.has(stop.kind) ? { kind: stop.kind } : null,
197
+ cacheExpiresAt: time(o.cacheExpiresAt),
198
+ toolStartedAt: time(o.toolStartedAt),
199
+ waitingFor: cleanStr(o.waitingFor),
200
+ now: cleanStr(o.now) ?? '',
201
+ startedAt: time(o.startedAt),
202
+ updatedAt: time(o.updatedAt),
203
+ tokens: cleanTokens(o.tokens),
204
+ cost: num(o.cost),
205
+ costNoCache: num(o.costNoCache),
206
+ costUnknown: o.costUnknown === true,
207
+ context: { used: count(ctx.used), window: num(ctx.window) },
208
+ files: arr(o.files, MAX_FILES).map(cleanFile).filter(Boolean),
209
+ artifacts: arr(o.artifacts, MAX_ARTIFACTS).map(cleanArtifact),
210
+ members: arr(o.members, MAX_MEMBERS).map(cleanMember).filter(Boolean),
211
+ };
212
+ }
213
+
214
+ export function cleanSessions(json, host) {
215
+ const seen = new Set();
216
+ const out = [];
217
+ for (const raw of arr(json?.sessions, MAX_SESSIONS)) {
218
+ const s = cleanSession(raw, host);
219
+ // 같은 id 가 두 번 오면 화면 선택이 꼬이므로 처음 것만 둔다.
220
+ if (!s || seen.has(s.id)) continue;
221
+ seen.add(s.id);
222
+ out.push(s);
223
+ }
224
+ return out.sort(bySession);
225
+ }
226
+
227
+ // ── 실행 ────────────────────────────────────────────────
228
+
229
+ // 원격 하나를 한 번 부른다. 돌려주는 값: { name, kind, ok, error, version, schema, at, sessions }. 거부하지 않는다.
230
+ // at 은 이번 호출이 끝난 시각 (실패면 null). opts.onChild 는 끝낼 때 죽일 수 있게 자식을 받는다.
231
+ export function runRemote(r, { timeoutMs = TIMEOUT_MS, exec = execFile, now = Date.now, onChild = () => {}, fake } = {}) {
232
+ const [file, args] = remoteCommand(r, fake === undefined ? {} : { fake });
233
+ return new Promise((resolve) => {
234
+ let child;
235
+ let timedOut = false;
236
+ let timer;
237
+ const done = (err, stdout, stderr) => {
238
+ clearTimeout(timer);
239
+ if (err && timedOut) err.timedOut = true;
240
+ const c = classify({ err, stdout, stderr });
241
+ const base = { name: r.name, kind: r.kind, version: null, schema: null, at: null, sessions: [] };
242
+ if (c.error) return resolve({ ...base, ok: false, error: c.error, version: c.version ?? null, schema: c.schema ?? null });
243
+ resolve({ ...base, ok: true, error: null, version: cleanStr(c.json.version, 40), schema: c.json.schema, at: now(), sessions: cleanSessions(c.json, r.name) });
244
+ };
245
+ try {
246
+ child = exec(file, args, { encoding: 'buffer', maxBuffer: MAX_BUFFER, windowsHide: true, shell: false }, done);
247
+ } catch (err) {
248
+ return done(err, '', '');
249
+ }
250
+ // 원격 aitop 은 입력을 읽지 않는다. 입력을 바로 닫아 ssh 가 기다리지 않게 한다.
251
+ try {
252
+ child?.stdin?.end();
253
+ } catch {}
254
+ onChild(child);
255
+ // execFile 의 timeout 대신 직접 재서 SIGKILL 한다 (ssh 가 SIGTERM 을 받고도 접속을 붙잡는 경우가 있다).
256
+ timer = setTimeout(() => {
257
+ timedOut = true;
258
+ try {
259
+ child?.kill('SIGKILL');
260
+ } catch {}
261
+ }, timeoutMs);
262
+ });
263
+ }
264
+
265
+ // 이름 목록(설정 값)을 대상 목록으로. 잘못된 이름은 빼고, 같은 이름은 한 번만 (WSL 배포판은 대소문자를 가리지 않고 처음 적은 표기를 남긴다).
266
+ export function remoteTargets(names = []) {
267
+ const out = new Map();
268
+ for (const n of names ?? []) {
269
+ const r = parseRemote(n);
270
+ if (r && !out.has(remoteKey(r))) out.set(remoteKey(r), r);
271
+ }
272
+ return [...out.values()];
273
+ }
274
+
275
+ // 잠깐 실패해도 직전 세션을 남겨 둔다 (선택·포커스가 풀리지 않고, 돌아올 때 알림이 한꺼번에 울리지 않게).
276
+ // 이만큼 연달아 실패하거나 마지막 성공에서 이만큼 지나면 그때 비운다.
277
+ export const KEEP_FAILS = 3;
278
+ export const KEEP_MS = 60_000;
279
+
280
+ // 모든 원격을 병렬로 부르고, 원격마다 마지막 결과를 들고 있는 폴러.
281
+ // 실시간 화면: start() 가 바로 한 번, 그 뒤 intervalMs 마다 부른다. 앞 호출이 아직 돌고 있는 원격은 그 차례를 건너뛴다.
282
+ // --once·--json: pollAll() 이 모든 원격이 끝날 때까지 기다린다. stop() 은 타이머를 멈추고 돌고 있는 자식을 죽인다.
283
+ // 실패하면 상태(ok·error)는 바로 실패로 바꾸되, 세션은 KEEP_FAILS 번 또는 KEEP_MS 동안 직전 것을 남긴다 (시각 at 은 마지막 성공).
284
+ // 세션이 비어 있던 원격(처음이거나 오래 실패해 비운 뒤)에 결과가 붙으면 그 세션 id 를 takeAttached() 로 한 번 넘긴다.
285
+ // bin 은 그 세션을 알림의 기준선으로만 쓰고 알리지 않는다 (이미 응답 대기인 원격 세션이 새 대기로 잡히지 않게).
286
+ export function createRemotePoller(targets, { intervalMs = INTERVAL_MS, timeoutMs = Number(process.env.AITOP_REMOTE_TIMEOUT_MS) > 0 ? Number(process.env.AITOP_REMOTE_TIMEOUT_MS) : TIMEOUT_MS, run = runRemote, onUpdate = () => {}, now = Date.now, keepFails = KEEP_FAILS, keepMs = KEEP_MS } = {}) {
287
+ const state = new Map(targets.map((r) => [r.name, { name: r.name, kind: r.kind, ok: false, error: null, pending: true, version: null, schema: null, at: null, sessions: [], fails: 0, attached: false }]));
288
+ const inflight = new Map();
289
+ const children = new Set();
290
+ let fresh = [];
291
+ let timer = null;
292
+ let stopped = false;
293
+
294
+ const apply = (name, res) => {
295
+ const prev = state.get(name);
296
+ if (res.ok) {
297
+ // 비어 있던 원격에 붙는 첫 결과: 기준선으로 넘긴다.
298
+ if (!prev.attached) fresh.push(...res.sessions.map((s) => s.id));
299
+ state.set(name, { ...res, pending: false, fails: 0, attached: true });
300
+ return;
301
+ }
302
+ const fails = prev.fails + 1;
303
+ const stale = fails >= keepFails || (prev.at != null && now() - prev.at >= keepMs);
304
+ const keep = prev.attached && !stale;
305
+ state.set(name, { ...res, pending: false, at: prev.at, fails, attached: keep, sessions: keep ? prev.sessions : [], version: res.version ?? prev.version });
306
+ };
307
+
308
+ const pollOne = (r) => {
309
+ if (inflight.has(r.name)) return inflight.get(r.name);
310
+ let mine = null;
311
+ const p = run(r, {
312
+ timeoutMs,
313
+ onChild: (c) => {
314
+ mine = c;
315
+ if (c) children.add(c);
316
+ },
317
+ }).then((res) => {
318
+ children.delete(mine);
319
+ inflight.delete(r.name);
320
+ if (stopped) return;
321
+ apply(r.name, res);
322
+ onUpdate();
323
+ });
324
+ inflight.set(r.name, p);
325
+ return p;
326
+ };
327
+ const pollAll = () => Promise.all(targets.map(pollOne));
328
+
329
+ return {
330
+ pollAll,
331
+ start() {
332
+ pollAll();
333
+ timer = setInterval(pollAll, intervalMs);
334
+ timer.unref?.();
335
+ },
336
+ stop() {
337
+ stopped = true;
338
+ clearInterval(timer);
339
+ for (const c of children) {
340
+ try {
341
+ c.kill('SIGKILL');
342
+ } catch {}
343
+ }
344
+ children.clear();
345
+ },
346
+ // 새로 붙은 원격의 세션 id (부를 때마다 비운다).
347
+ takeAttached() {
348
+ const out = fresh;
349
+ fresh = [];
350
+ return out;
351
+ },
352
+ // 화면·--json 이 쓰는 지금 결과. statuses 는 원격 순서대로, sessions 는 원격 순서대로 이어 붙인다.
353
+ snapshot() {
354
+ const statuses = targets.map((r) => {
355
+ const s = state.get(r.name);
356
+ return { name: s.name, kind: s.kind, ok: s.ok, error: s.error, pending: s.pending, version: s.version, schema: s.schema, at: s.at, count: s.sessions.length };
357
+ });
358
+ return { statuses, sessions: targets.flatMap((r) => state.get(r.name).sessions) };
359
+ },
360
+ };
361
+ }
362
+
363
+ // bin 의 갱신(refresh)이 부른다: 폴러의 지금 결과를 data 에 붙이고, 새로 붙은 원격의 세션 id 를 응답 대기 감시(attention.mjs createWaitWatch)의
364
+ // seen 에 넣는다. 그러면 원격이 처음 붙거나 오래 끊겼다 다시 붙을 때 이미 응답 대기인 세션을 새 대기로 알리지 않는다.
365
+ // 끝남·context 알림(createEventWatch)은 처음 보는 세션을 기준선으로 잡으므로(done 은 작업 중을 본 뒤에만, context 는 first) 따로 할 일이 없다.
366
+ export function mergeRemote(data, poller, waitWatch) {
367
+ const snap = poller.snapshot();
368
+ data.sessions.push(...snap.sessions);
369
+ data.remotes = snap.statuses;
370
+ for (const id of poller.takeAttached()) waitWatch?.seen.add(id);
371
+ return data;
372
+ }
package/src/resume.mjs CHANGED
@@ -41,9 +41,52 @@ function resumeArgs(s) {
41
41
  return null;
42
42
  }
43
43
 
44
+ // PowerShell 작은따옴표 (Windows 에서 원격 세션 명령을 붙여 넣는 로컬 셸). 안전한 글자만이면 그대로, 아니면 '...' 로 감싸고 ' 는 '' 로.
45
+ // - 로 시작하는 값(-- 포함)과 @ 가 든 값도 감싼다 (PowerShell 이 매개변수 끝 표시나 splatting 으로 읽지 않게).
46
+ export function psQuote(v) {
47
+ return /^[A-Za-z0-9_./:\\][A-Za-z0-9_./:\\-]*$/.test(v) ? v : `'${v.replace(/'/g, "''")}'`;
48
+ }
49
+
50
+ // PowerShell 이 작은따옴표 안에서도 따옴표로 읽는 유니코드 따옴표(‘ ’ ‚ ‛ 등), Windows PowerShell 5.1 이 네이티브 명령에 넘길 때 깨뜨리는 ",
51
+ // 그리고 붙여 넣을 때 위험한 글자(제어 문자·줄바꿈·NUL·백틱·$, 폭 0·방향 바꿈 글자). 이런 값이 있으면 Windows 에서는 명령을 만들지 않는다.
52
+ const PS_UNSAFE = /[\x00-\x1f\x7f-\x9f`$"\u2018-\u201f\u2028\u2029\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff]/;
53
+
54
+ // 원격 세션(#308)의 이어 열기: 원격이 준 resumeCmd 는 믿지 않고, 원래 id·도구·폴더로 여기서 다시 만든다.
55
+ // ssh: ssh -t <host> 'cd <폴더> && claude --resume <id>' (원격 셸이 받는 한 줄을 통째로 따옴표로 감싼다).
56
+ // WSL: wsl.exe -d <배포판> --cd <폴더> -- claude --resume <id>. 기본이 아닌 기록 폴더 변수는 원격에서 알 수 없어 붙이지 않는다.
57
+ // 로컬이 Windows 면 붙여 넣는 셸을 PowerShell 로 보고 로컬 쪽 인자를 PowerShell 따옴표로 감싼다.
58
+ // ssh 의 원격 쪽 한 줄은 원격 POSIX 셸이 읽으므로 POSIX 따옴표로 만든 뒤 그 줄 전체를 PowerShell 따옴표로 한 번 더 감싼다.
59
+ function remoteResumeCmd(s, platform) {
60
+ const win = platform === 'win32';
61
+ // Windows 에서는 위험한 글자를 지워서 넘기지 않고 아예 만들지 않는다.
62
+ if (win && [s.host, s.cwd, s.remoteId].some((v) => v != null && PS_UNSAFE.test(String(v)))) return null;
63
+ const host = stripControls(s.host);
64
+ const local = { ...s, host: null, id: s.remoteId, home: null };
65
+ const wsl = /^wsl:(.+)$/i.exec(host);
66
+ let words;
67
+ if (wsl) {
68
+ const args = resumeArgs(local);
69
+ if (!args) return null;
70
+ const cwd = stripControls(s.cwd);
71
+ words = ['wsl.exe', '-d', wsl[1], ...(cwd ? ['--cd', cwd] : []), '--', ...args];
72
+ } else {
73
+ const inner = resumeCmd(local);
74
+ if (!inner || !host) return null;
75
+ words = ['ssh', '-t', host, inner];
76
+ }
77
+ if (win && words.some((w) => PS_UNSAFE.test(w))) return null;
78
+ // Windows PowerShell 5.1 은 공백이 든 인자를 "…" 로 감싸 넘기는데, 값이 \ 로 끝나면 받는 쪽이 \" 를 " 로 읽어 뒤 인자를 먹는다.
79
+ // 그런 값(공백·탭이 있고 \ 로 끝남)이 있으면 만들지 않는다.
80
+ if (win && words.some((w) => /[ \t]/.test(w) && w.endsWith('\\'))) return null;
81
+ // 맨 앞 실행 파일 이름은 따옴표 없이 둔다 (PowerShell 은 따옴표로 시작하면 명령이 아니라 글로 읽는다).
82
+ return [words[0], ...words.slice(1).map(win ? psQuote : shellQuote)].join(' ');
83
+ }
84
+
44
85
  // 세션을 이어 여는 한 줄 명령. 작업 폴더를 알면 cd 를 앞에 붙인다. 만들 수 없으면 null.
45
- export function resumeCmd(s) {
86
+ // platform 은 원격 세션(#308)의 로컬 셸 따옴표를 고를 때만 쓴다 (테스트에서 바꿔 끼운다). 로컬 세션은 늘 POSIX 따옴표다.
87
+ export function resumeCmd(s, { platform = process.platform } = {}) {
46
88
  if (!s) return null;
89
+ if (s.host) return remoteResumeCmd(s, platform);
47
90
  const args = resumeArgs(s);
48
91
  if (!args) return null;
49
92
  // 기본 폴더가 아닌 설정 폴더(#212)의 세션은 그 폴더를 변수로 집어 줘야 도구가 기록을 찾는다.
package/src/ui/detail.mjs CHANGED
@@ -60,6 +60,8 @@ export function fileRow(f, cwd, w, selected) {
60
60
  // 같은 파일을 여러 번 고치면 줄 번호 기준이 매번 달라져 하나의 diff 로 합칠 수 없다.
61
61
  export function diffBody(f, w) {
62
62
  if (f.hidden) return [[INDENT, { t: tr('detail.hidden'), fg: PALETTE.info, italic: true }]];
63
+ // 원격 세션(#308)은 파일 통계만 받고 변경 내용은 가져오지 않는다.
64
+ if (f.remote) return [[INDENT, { t: tr('detail.remoteDiff'), fg: PALETTE.info, italic: true }]];
63
65
  if (!f.hunks.length) return [[INDENT, { t: tr(f.deleted ? 'detail.deleted' : 'detail.noHunks'), fg: PALETTE.info, italic: true }]];
64
66
  const nums = w >= 50;
65
67
  const textW = w - 1 - (nums ? 5 : 0);
@@ -529,7 +531,8 @@ export function resumeSummary(s, w) {
529
531
  export function detail(s, W, H, frame, view) {
530
532
  const tc = PALETTE.tools[s.tool];
531
533
  // 제목: 세션 이름은 진하게, 도구·모델은 도구 색으로.
532
- const title = [{ t: s.name ?? s.tool, fg: PALETTE.text, bold: true }, { t: ` ${s.tool}${s.model ? ' · ' + s.model : ''}`, fg: tc }];
534
+ // 원격 세션(#308)은 제목 끝에 '@ 호스트' 를 붙인다.
535
+ const title = [{ t: s.name ?? s.tool, fg: PALETTE.text, bold: true }, { t: ` ${s.tool}${s.model ? ' · ' + s.model : ''}`, fg: tc }, ...(s.host ? [{ t: ` @ ${s.host}`, fg: PALETTE.muted }] : [])];
533
536
  if (W < NARROW_W) {
534
537
  const inner = W - 4;
535
538
  // 셋째 줄(이어 열기)은 오른쪽 칸이 넉넉할(ROOMY 줄 이상 남을) 때만 둔다. 낮은 화면의 구획 배치는 그대로다.
@@ -550,6 +553,7 @@ export function detail(s, W, H, frame, view) {
550
553
  const cache = cacheState(s);
551
554
  if (cache) L.push([{ t: ' ' }, { t: cache.expired ? tr('detail.cacheExpired', { ttl: cache.ttl }) : tr('detail.cacheLeft', { t: cache.left, ttl: cache.ttl }), fg: cache.expired ? PALETTE.info : cache.fg, bold: cache.bold }]);
552
555
  section(tr('detail.session'));
556
+ if (s.host) kv(tr('detail.host'), s.host);
553
557
  kv(tr('detail.folder'), tilde(s.cwd));
554
558
  if (s.branch) kv(tr('detail.branch'), s.branch);
555
559
  kv(tr('detail.model'), s.model ?? '-');
package/src/ui/table.mjs CHANGED
@@ -15,7 +15,7 @@ import { callsYou, isStopped } from '../attention.mjs';
15
15
  export function filterSessions(sessions, query) {
16
16
  const q = (query ?? '').trim().toLowerCase();
17
17
  if (!q) return sessions;
18
- return sessions.filter((s) => [s.name, s.project, s.cwd, s.model, s.tool].some((v) => String(v ?? '').toLowerCase().includes(q)));
18
+ return sessions.filter((s) => [s.name, s.project, s.cwd, s.model, s.tool, s.host].some((v) => String(v ?? '').toLowerCase().includes(q)));
19
19
  }
20
20
 
21
21
  // 표 폭이 WIDE 이상이면 COST 와 CONTEXT 막대 11칸을 그대로 두고, 폭에 따라 MODEL(104~)·PROJECT(110~) 를 더한다.
@@ -138,7 +138,7 @@ export function header(view, W) {
138
138
  const bar = u?.loading == null && u?.days7?.length ? [{ t: ' ', bg: B }, ...weekBar(u.days7, view.costMode).map((x) => ({ ...x, bg: B }))] : null;
139
139
  const week = (tok, withBar = false) => period(t('hdr.week'), u.week, tok, [], withBar && bar ? bar : []);
140
140
  // 장부를 못 읽었으면 화면에 있는 세션(모든 도구)의 누적 토큰이라도 보인다.
141
- const fallback = [{ t: `Σ ${fmtTokens(sessions.reduce((a, s) => a + (s.tokens?.total ?? 0), 0))} tok`, fg: PALETTE.muted, bg: B }];
141
+ const fallback = [{ t: `Σ ${fmtTokens(sessions.reduce((a, s) => a + (s.host ? 0 : (s.tokens?.total ?? 0)), 0))} tok`, fg: PALETTE.muted, bg: B }];
142
142
  const clockSeg = { t: clock(view.data.at), fg: PALETTE.muted, bg: B };
143
143
  // 비용은 API 정가 환산이다 (구독 요금제의 실제 청구액이 아님). 폭이 되면 그렇다고 적는다.
144
144
  const api = { t: `${t(net ? 'hdr.netLong' : 'hdr.apiLong')} `, fg: net ? PALETTE.brand : PALETTE.info, bg: B };
@@ -533,3 +533,29 @@ export function groupRow(g, W) {
533
533
  ...(g.cost > 0 || g.unknown ? [{ t: ' · ', fg: PALETTE.info }, { t: money(g.cost, g.unknown), fg: PALETTE.muted }] : []),
534
534
  ], W);
535
535
  }
536
+
537
+ // 원격 구분 줄 (#308): '── dev · 3 세션 · 10초 전 ──', 실패하면 '── dev · 연결 안 됨 (시간 초과) ──', 첫 결과 전에는 '── dev · 연결 중… ──'.
538
+ // r 은 remote.mjs 폴러의 상태({ name, ok, error, pending, at }), n 은 이 구획에 보이는 세션 수.
539
+ // 폭이 모자라면 호스트 이름을 먼저 줄이고 상태 글은 남긴다.
540
+ export function remoteAgo(at, now = NOW) {
541
+ if (!at) return '';
542
+ const sec = Math.max(0, Math.floor((now - at) / 1000));
543
+ return sec < 60 ? t('remote.secAgo', { n: sec }) : t('remote.minAgo', { n: Math.floor(sec / 60) });
544
+ }
545
+
546
+ export function remoteRow(r, n, W) {
547
+ const h = glyphs().rule;
548
+ const down = !r.ok && !r.pending;
549
+ // 잠깐 끊겨 직전 세션을 남겨 둔 동안(n > 0)은 실패 뒤에 그 세션을 받은 시각을 붙인다.
550
+ const ago = r.at ? ` · ${remoteAgo(r.at)}` : '';
551
+ const state = !r.ok && r.pending ? t('remote.pending') : down ? `${t('remote.down', { why: t(`remote.err.${r.error ?? 'unreachable'}`) })}${n ? ago : ''}` : `${t('remote.count', { n })}${ago}`;
552
+ const tail = ` · ${state} `;
553
+ const room = Math.max(1, W - 3 - width(tail) - 2);
554
+ const name = truncate(r.name, room);
555
+ return line([
556
+ { t: `${h}${h} `, fg: PALETTE.line },
557
+ { t: name, fg: PALETTE.muted, bold: true },
558
+ { t: tail, fg: down ? PALETTE.alert : PALETTE.info },
559
+ { t: h.repeat(Math.max(0, W - 3 - width(name) - width(tail))), fg: PALETTE.line },
560
+ ], W);
561
+ }
package/src/ui.mjs CHANGED
@@ -4,7 +4,7 @@ import { BRAND } from './brand.mjs';
4
4
  import { PALETTE } from './ui/theme.mjs';
5
5
  import { glyphMoves, line, setNow } from './ui/draw.mjs';
6
6
  import { glyphs } from './ui/glyphs.mjs';
7
- import { TABLE_BOX_H, columns, emptyLines, filterSessions, groupRow, header, memberRow, sessionRow, tableBox, tableHeader, toolStrip, topCost } from './ui/table.mjs';
7
+ import { TABLE_BOX_H, columns, emptyLines, filterSessions, groupRow, header, memberRow, remoteRow, sessionRow, tableBox, tableHeader, toolStrip, topCost } from './ui/table.mjs';
8
8
  import { detail } from './ui/detail.mjs';
9
9
  import { artifactScreen } from './ui/artifact-view.mjs';
10
10
  import { detailOpen, footer, help } from './ui/chrome.mjs';
@@ -65,7 +65,9 @@ export function render(view, W, H) {
65
65
  return lines;
66
66
  }
67
67
  const { errors } = view.data;
68
- const { sessions, groups } = arrange(filterSessions(view.data.sessions, view.filter), view);
68
+ // 원격(#308) 상태 목록. 원격을 켜지 않았으면 비어 있고 화면은 예전과 같다.
69
+ const remotes = view.data.remotes ?? [];
70
+ const { sessions, groups, hosts } = arrange(filterSessions(view.data.sessions, view.filter), { ...view, remotes });
69
71
  const boxed = H >= TABLE_BOX_H && W >= 60;
70
72
  const TW = boxed ? W - 4 : W;
71
73
  const c = columns(TW);
@@ -93,12 +95,23 @@ export function render(view, W, H) {
93
95
  rows.push({ s });
94
96
  s.members.forEach((m, i) => rows.push({ s, m, last: i === s.members.length - 1 }));
95
97
  };
96
- if (groups) {
97
- for (const g of groups) {
98
- rows.push({ g });
99
- g.sessions.forEach(pushSession);
100
- }
101
- } else sessions.forEach(pushSession);
98
+ const pushPart = (part) => {
99
+ if (part.groups) {
100
+ for (const g of part.groups) {
101
+ rows.push({ g });
102
+ g.sessions.forEach(pushSession);
103
+ }
104
+ } else part.sessions.forEach(pushSession);
105
+ };
106
+ // 로컬 세션이 맨 위, 그 아래 원격마다 구분 줄 하나와 그 원격의 세션 (구획 안의 정렬·묶기는 arrange 가 정한다).
107
+ pushPart({ groups, sessions: hosts ? sessions.filter((s) => !s.host) : sessions });
108
+ const parts = new Map((hosts ?? []).map((h) => [h.host, h]));
109
+ const names = [...new Set([...remotes.map((r) => r.name), ...parts.keys()])];
110
+ for (const name of names) {
111
+ const part = parts.get(name) ?? { sessions: [], groups: null };
112
+ rows.push({ remote: remotes.find((r) => r.name === name) ?? { name, ok: true, at: null }, n: part.sessions.length });
113
+ pushPart(part);
114
+ }
102
115
  const sel = sessions.find((s) => s.id === view.selectedId) ?? sessions[0];
103
116
  const open = detailOpen(view, H);
104
117
  const wantDetail = open && Boolean(sel);
@@ -118,13 +131,13 @@ export function render(view, W, H) {
118
131
  const lastOfSel = selRow + (sel?.members.length ?? 0);
119
132
  let start = Math.min(Math.max(0, lastOfSel - shown + 1), Math.max(0, rows.length - shown), selRow);
120
133
  // 고른 세션이 묶음의 첫 행이고 자리가 남으면 그 묶음 머리도 보이게 한 줄 올린다.
121
- if (start === selRow && rows[start - 1]?.g && lastOfSel - start + 2 <= shown) start--;
134
+ if (start === selRow && (rows[start - 1]?.g || rows[start - 1]?.remote) && lastOfSel - start + 2 <= shown) start--;
122
135
  const isSession = (r) => r.s && !r.m;
123
136
  const visible = rows.slice(start, start + shown);
124
137
  // 준비 완료 전에는 값이 커지는 대로 ▲ 가 옮겨 다니므로 붙이지 않는다.
125
138
  const hot = view.ready === false ? null : topCost(visible.filter(isSession).map((r) => r.s), view.costMode);
126
139
  if (!sessions.length) table.push(...(view.filter ? [line([{ t: ` ${t('ui.noMatch', { q: view.filter })}`, fg: PALETTE.muted, italic: true }], TW)] : emptyLines(view, TW)));
127
- for (const r of visible) table.push(r.g ? groupRow(r.g, TW) : r.m ? memberRow(r.m, r.last, c, TW, view.frame, r.s.model, view.costMode, r.s.status) : sessionRow(r.s, c, TW, r.s === sel, view.frame, hot, view.costMode, Boolean(view.pins?.includes(r.s.id))));
140
+ for (const r of visible) table.push(r.remote ? remoteRow(r.remote, r.n, TW) : r.g ? groupRow(r.g, TW) : r.m ? memberRow(r.m, r.last, c, TW, view.frame, r.s.model, view.costMode, r.s.status) : sessionRow(r.s, c, TW, r.s === sel, view.frame, hot, view.costMode, Boolean(view.pins?.includes(r.s.id))));
128
141
  if (clipped) {
129
142
  const onScreen = new Set(visible.filter(isSession).map((r) => r.s));
130
143
  const hidden = sessions.filter((s) => !onScreen.has(s));