@sejuneoh/aitop 0.40.0 → 0.41.1
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 +50 -4
- package/bin/aitop.mjs +35 -7
- package/package.json +1 -1
- package/src/config.mjs +53 -0
- package/src/doctor.mjs +34 -17
- package/src/i18n.mjs +55 -4
- package/src/json.mjs +13 -1
- package/src/keys.mjs +5 -0
- package/src/notify.mjs +4 -1
- package/src/order.mjs +12 -1
- package/src/remote.mjs +372 -0
- package/src/resume.mjs +44 -1
- package/src/sources/agy-ledger.mjs +129 -27
- package/src/sources/antigravity.mjs +29 -6
- package/src/ui/detail.mjs +5 -1
- package/src/ui/table.mjs +28 -2
- package/src/ui.mjs +23 -10
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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)의 세션은 그 폴더를 변수로 집어 줘야 도구가 기록을 찾는다.
|