triflux 3.1.0-dev.5 → 3.2.0-dev.2

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.
@@ -0,0 +1,110 @@
1
+ // hub/team/pane.mjs — pane별 CLI 실행 + stdin 주입
2
+ // 의존성: child_process, fs, os, path (Node.js 내장)만 사용
3
+ import { writeFileSync, unlinkSync, mkdirSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { tmpdir } from "node:os";
6
+ import { detectMultiplexer, tmuxExec } from "./session.mjs";
7
+
8
+ /** Windows 경로를 MSYS2/Git Bash tmux용 POSIX 경로로 변환 */
9
+ function toTmuxPath(p) {
10
+ if (process.platform !== "win32") return p;
11
+
12
+ const normalized = p.replace(/\\/g, "/");
13
+ const m = normalized.match(/^([A-Za-z]):\/(.*)$/);
14
+ if (!m) return normalized;
15
+
16
+ const drive = m[1].toLowerCase();
17
+ const rest = m[2];
18
+ const mux = detectMultiplexer();
19
+
20
+ // wsl tmux는 /mnt/c/... 경로를 사용
21
+ if (mux === "wsl-tmux") {
22
+ return `/mnt/${drive}/${rest}`;
23
+ }
24
+
25
+ // Git Bash/MSYS tmux는 /c/... 경로를 사용
26
+ return `/${drive}/${rest}`;
27
+ }
28
+
29
+ /** tmux 커맨드 실행 (session.mjs와 동일 패턴) */
30
+ function tmux(args, opts = {}) {
31
+ return tmuxExec(args, {
32
+ encoding: "utf8",
33
+ timeout: 10000,
34
+ stdio: ["pipe", "pipe", "pipe"],
35
+ ...opts,
36
+ });
37
+ }
38
+
39
+ /**
40
+ * CLI 에이전트 시작 커맨드 생성
41
+ * @param {'codex'|'gemini'|'claude'} cli
42
+ * @returns {string} 실행할 셸 커맨드
43
+ */
44
+ export function buildCliCommand(cli) {
45
+ switch (cli) {
46
+ case "codex":
47
+ // interactive REPL 진입 — MCP는 ~/.codex/config.json에 사전 등록
48
+ return "codex";
49
+ case "gemini":
50
+ // interactive 모드 — MCP는 ~/.gemini/settings.json에 사전 등록
51
+ return "gemini";
52
+ case "claude":
53
+ // interactive 모드
54
+ return "claude";
55
+ default:
56
+ return cli; // 커스텀 CLI 허용
57
+ }
58
+ }
59
+
60
+ /**
61
+ * tmux pane에 CLI 시작
62
+ * @param {string} target — 예: tfx-team-abc:0.1
63
+ * @param {string} command — 실행할 커맨드
64
+ */
65
+ export function startCliInPane(target, command) {
66
+ // 특수문자 이스케이프: 작은따옴표 내부에서 안전하도록
67
+ const escaped = command.replace(/'/g, "'\\''");
68
+ tmux(`send-keys -t ${target} '${escaped}' Enter`);
69
+ }
70
+
71
+ /**
72
+ * pane에 프롬프트 주입 (load-buffer + paste-buffer 방식)
73
+ * 멀티라인 + 특수문자 안전, 크기 제한 없음
74
+ * @param {string} target — 예: tfx-team-abc:0.1
75
+ * @param {string} prompt — 주입할 텍스트
76
+ */
77
+ export function injectPrompt(target, prompt) {
78
+ // 임시 파일에 프롬프트 저장
79
+ const tmpDir = join(tmpdir(), "tfx-team");
80
+ mkdirSync(tmpDir, { recursive: true });
81
+
82
+ // pane ID를 파일명에 포함 (충돌 방지)
83
+ const safeTarget = target.replace(/[:.]/g, "-");
84
+ const tmpFile = join(tmpDir, `prompt-${safeTarget}-${Date.now()}.txt`);
85
+
86
+ try {
87
+ writeFileSync(tmpFile, prompt, "utf8");
88
+
89
+ // tmux load-buffer → paste-buffer → Enter (Windows 경로 변환 필요)
90
+ tmux(`load-buffer ${toTmuxPath(tmpFile)}`);
91
+ tmux(`paste-buffer -t ${target}`);
92
+ tmux(`send-keys -t ${target} Enter`);
93
+ } finally {
94
+ // 임시 파일 정리
95
+ try {
96
+ unlinkSync(tmpFile);
97
+ } catch {
98
+ // 정리 실패 무시
99
+ }
100
+ }
101
+ }
102
+
103
+ /**
104
+ * pane에 키 입력 전송
105
+ * @param {string} target — 예: tfx-team-abc:0.1
106
+ * @param {string} keys — tmux 키 표현 (예: 'C-c', 'Enter')
107
+ */
108
+ export function sendKeys(target, keys) {
109
+ tmux(`send-keys -t ${target} ${keys}`);
110
+ }
@@ -0,0 +1,529 @@
1
+ // hub/team/session.mjs — tmux/wt 세션 생명주기 관리
2
+ // 의존성: child_process (Node.js 내장)만 사용
3
+ import { execSync, spawnSync } from "node:child_process";
4
+
5
+ const GIT_BASH_CANDIDATES = [
6
+ "C:/Program Files/Git/bin/bash.exe",
7
+ "C:/Program Files/Git/usr/bin/bash.exe",
8
+ ];
9
+
10
+ function findGitBashExe() {
11
+ for (const p of GIT_BASH_CANDIDATES) {
12
+ try {
13
+ execSync(`"${p}" --version`, { stdio: "ignore", timeout: 3000 });
14
+ return p;
15
+ } catch {
16
+ // 다음 후보
17
+ }
18
+ }
19
+ return null;
20
+ }
21
+
22
+ /** Windows Terminal 실행 파일 존재 여부 */
23
+ export function hasWindowsTerminal() {
24
+ if (process.platform !== "win32") return false;
25
+ try {
26
+ execSync("where wt.exe", { stdio: "ignore", timeout: 3000 });
27
+ return true;
28
+ } catch {
29
+ return false;
30
+ }
31
+ }
32
+
33
+ /** 현재 프로세스가 Windows Terminal 내에서 실행 중인지 여부 */
34
+ export function hasWindowsTerminalSession() {
35
+ return process.platform === "win32" && !!process.env.WT_SESSION;
36
+ }
37
+
38
+ /** tmux 실행 가능 여부 확인 */
39
+ function hasTmux() {
40
+ try {
41
+ execSync("tmux -V", { stdio: "ignore", timeout: 3000 });
42
+ return true;
43
+ } catch {
44
+ return false;
45
+ }
46
+ }
47
+
48
+ /** WSL2 내 tmux 사용 가능 여부 (Windows 전용) */
49
+ function hasWslTmux() {
50
+ try {
51
+ execSync("wsl tmux -V", { stdio: "ignore", timeout: 5000 });
52
+ return true;
53
+ } catch {
54
+ return false;
55
+ }
56
+ }
57
+
58
+ /** Git Bash 내 tmux 사용 가능 여부 (Windows 전용) */
59
+ function hasGitBashTmux() {
60
+ const bash = findGitBashExe();
61
+ if (!bash) return false;
62
+ try {
63
+ const r = spawnSync(bash, ["-lc", "tmux -V"], {
64
+ encoding: "utf8",
65
+ timeout: 5000,
66
+ stdio: ["ignore", "pipe", "pipe"],
67
+ });
68
+ return (r.status ?? 1) === 0;
69
+ } catch {
70
+ return false;
71
+ }
72
+ }
73
+
74
+ /**
75
+ * 터미널 멀티플렉서 감지
76
+ * @returns {'tmux'|'git-bash-tmux'|'wsl-tmux'|null}
77
+ */
78
+ export function detectMultiplexer() {
79
+ if (hasTmux()) return "tmux";
80
+ if (process.platform === "win32" && hasGitBashTmux()) return "git-bash-tmux";
81
+ if (process.platform === "win32" && hasWslTmux()) return "wsl-tmux";
82
+ return null;
83
+ }
84
+
85
+ /**
86
+ * tmux 커맨드 실행 (wsl-tmux 투명 지원)
87
+ * @param {string} args — tmux 서브커맨드 + 인자
88
+ * @param {object} opts — execSync 옵션
89
+ * @returns {string} stdout
90
+ */
91
+ function tmux(args, opts = {}) {
92
+ const mux = detectMultiplexer();
93
+ if (!mux) {
94
+ throw new Error(
95
+ "tmux 미발견.\n\n" +
96
+ "tfx team은 tmux가 필요합니다:\n" +
97
+ " WSL2: wsl sudo apt install tmux\n" +
98
+ " macOS: brew install tmux\n" +
99
+ " Linux: apt install tmux\n\n" +
100
+ "Windows에서는 WSL2를 권장합니다:\n" +
101
+ " 1. wsl --install\n" +
102
+ " 2. wsl sudo apt install tmux\n" +
103
+ " 3. tfx team \"작업\" (자동으로 WSL tmux 사용)"
104
+ );
105
+ }
106
+ if (mux === "git-bash-tmux") {
107
+ const bash = findGitBashExe();
108
+ if (!bash) throw new Error("git-bash-tmux 감지 실패");
109
+ const r = spawnSync(bash, ["-lc", `tmux ${args}`], {
110
+ encoding: "utf8",
111
+ timeout: 10000,
112
+ stdio: ["pipe", "pipe", "pipe"],
113
+ ...opts,
114
+ });
115
+ if ((r.status ?? 1) !== 0) {
116
+ const e = new Error(r.stderr || "tmux command failed");
117
+ e.status = r.status;
118
+ throw e;
119
+ }
120
+ return (r.stdout || "").trim();
121
+ }
122
+
123
+ const prefix = mux === "wsl-tmux" ? "wsl tmux" : "tmux";
124
+ const result = execSync(`${prefix} ${args}`, {
125
+ encoding: "utf8",
126
+ timeout: 10000,
127
+ stdio: ["pipe", "pipe", "pipe"],
128
+ ...opts,
129
+ });
130
+ return result != null ? result.trim() : "";
131
+ }
132
+
133
+ /**
134
+ * tmux 명령 직접 실행 (고수준 모듈에서 재사용)
135
+ * @param {string} args
136
+ * @param {object} opts
137
+ * @returns {string}
138
+ */
139
+ export function tmuxExec(args, opts = {}) {
140
+ return tmux(args, opts);
141
+ }
142
+
143
+ /**
144
+ * 현재 멀티플렉서 환경에 맞는 attach 실행 스펙 반환
145
+ * @param {string} sessionName
146
+ * @returns {{ command: string, args: string[] }}
147
+ */
148
+ export function resolveAttachCommand(sessionName) {
149
+ const mux = detectMultiplexer();
150
+ if (!mux) {
151
+ throw new Error("tmux 미발견");
152
+ }
153
+
154
+ if (mux === "git-bash-tmux") {
155
+ const bash = findGitBashExe();
156
+ if (!bash) throw new Error("git-bash-tmux 감지 실패");
157
+ return {
158
+ command: bash,
159
+ args: ["-lc", `tmux attach-session -t ${sessionName}`],
160
+ };
161
+ }
162
+
163
+ if (mux === "wsl-tmux") {
164
+ return {
165
+ command: "wsl",
166
+ args: ["tmux", "attach-session", "-t", sessionName],
167
+ };
168
+ }
169
+
170
+ return {
171
+ command: "tmux",
172
+ args: ["attach-session", "-t", sessionName],
173
+ };
174
+ }
175
+
176
+ /**
177
+ * wt.exe 커맨드 실행
178
+ * @param {string[]} args
179
+ * @param {object} opts
180
+ * @returns {string}
181
+ */
182
+ function wt(args, opts = {}) {
183
+ if (!hasWindowsTerminal()) {
184
+ throw new Error("wt.exe 미발견");
185
+ }
186
+
187
+ const r = spawnSync("wt.exe", args, {
188
+ encoding: "utf8",
189
+ timeout: 10000,
190
+ stdio: ["ignore", "pipe", "pipe"],
191
+ windowsHide: true,
192
+ ...opts,
193
+ });
194
+ if ((r.status ?? 1) !== 0) {
195
+ const e = new Error((r.stderr || r.stdout || "wt command failed").trim());
196
+ e.status = r.status;
197
+ throw e;
198
+ }
199
+ return (r.stdout || "").trim();
200
+ }
201
+
202
+ /**
203
+ * Windows Terminal pane 분할용 cmd.exe 인자 구성
204
+ * @param {string} command
205
+ * @returns {string[]}
206
+ */
207
+ function buildWtCmdArgs(command) {
208
+ return ["cmd.exe", "/c", command];
209
+ }
210
+
211
+ /**
212
+ * Windows Terminal 독립 모드 세션 생성
213
+ * - 현재 pane를 앵커로 사용하고, 우측(1xN) 또는 하단(Nx1)으로만 분할
214
+ * - 생성한 pane에 즉시 CLI 커맨드를 실행
215
+ * @param {string} sessionName
216
+ * @param {object} opts
217
+ * @param {'1xN'|'Nx1'} opts.layout
218
+ * @param {Array<{title:string,command:string,cwd?:string}>} opts.paneCommands
219
+ * @returns {{ sessionName: string, panes: string[], titles: string[], layout: '1xN'|'Nx1', paneCount: number, anchorPane: string }}
220
+ */
221
+ export function createWtSession(sessionName, opts = {}) {
222
+ const { layout = "1xN", paneCommands = [] } = opts;
223
+
224
+ if (!hasWindowsTerminalSession()) {
225
+ throw new Error("WT_SESSION 미감지");
226
+ }
227
+ if (!hasWindowsTerminal()) {
228
+ throw new Error("wt.exe 미발견");
229
+ }
230
+ if (!Array.isArray(paneCommands) || paneCommands.length === 0) {
231
+ throw new Error("paneCommands가 비어 있음");
232
+ }
233
+
234
+ const splitFlag = layout === "Nx1" ? "-H" : "-V";
235
+ const panes = [];
236
+ const titles = [];
237
+
238
+ for (let i = 0; i < paneCommands.length; i++) {
239
+ const pane = paneCommands[i] || {};
240
+ const title = pane.title || `${sessionName}-${i + 1}`;
241
+ const command = String(pane.command || "").trim();
242
+ const cwd = pane.cwd || process.cwd();
243
+ if (!command) continue;
244
+
245
+ wt(["-w", "0", "sp", splitFlag, "--title", title, "-d", cwd, ...buildWtCmdArgs(command)]);
246
+ panes.push(`wt:${i}`);
247
+ titles.push(title);
248
+ }
249
+
250
+ return {
251
+ sessionName,
252
+ panes,
253
+ titles,
254
+ layout: layout === "Nx1" ? "Nx1" : "1xN",
255
+ paneCount: panes.length,
256
+ anchorPane: "wt:anchor",
257
+ };
258
+ }
259
+
260
+ /**
261
+ * Windows Terminal pane 포커스 이동
262
+ * @param {number} paneIndex - createWtSession()에서 생성한 pane 인덱스(0 기반)
263
+ * @param {object} opts
264
+ * @param {'1xN'|'Nx1'} opts.layout
265
+ * @returns {boolean}
266
+ */
267
+ export function focusWtPane(paneIndex, opts = {}) {
268
+ if (!hasWindowsTerminalSession() || !hasWindowsTerminal()) return false;
269
+ const idx = Number(paneIndex);
270
+ if (!Number.isInteger(idx) || idx < 0) return false;
271
+
272
+ const layout = opts.layout === "Nx1" ? "Nx1" : "1xN";
273
+ const backDir = layout === "Nx1" ? "up" : "left";
274
+ const stepDir = layout === "Nx1" ? "down" : "right";
275
+
276
+ // 앵커로 최대한 복귀
277
+ for (let i = 0; i < 10; i++) {
278
+ try { wt(["-w", "0", "move-focus", backDir]); } catch { break; }
279
+ }
280
+
281
+ for (let i = 0; i <= idx; i++) {
282
+ wt(["-w", "0", "move-focus", stepDir]);
283
+ }
284
+ return true;
285
+ }
286
+
287
+ /**
288
+ * Windows Terminal에서 생성한 팀 pane 정리
289
+ * @param {object} opts
290
+ * @param {'1xN'|'Nx1'} opts.layout
291
+ * @param {number} opts.paneCount
292
+ * @returns {number} 닫힌 pane 수 (best-effort)
293
+ */
294
+ export function closeWtSession(opts = {}) {
295
+ if (!hasWindowsTerminalSession() || !hasWindowsTerminal()) return 0;
296
+
297
+ const paneCount = Math.max(0, Number(opts.paneCount || 0));
298
+ if (paneCount === 0) return 0;
299
+
300
+ const layout = opts.layout === "Nx1" ? "Nx1" : "1xN";
301
+ const backDir = layout === "Nx1" ? "up" : "left";
302
+ const stepDir = layout === "Nx1" ? "down" : "right";
303
+ let closed = 0;
304
+
305
+ // 앵커(원래 tfx 실행 pane)로 최대한 복귀
306
+ for (let i = 0; i < 10; i++) {
307
+ try { wt(["-w", "0", "move-focus", backDir]); } catch { break; }
308
+ }
309
+
310
+ for (let i = 0; i < paneCount; i++) {
311
+ try {
312
+ wt(["-w", "0", "move-focus", stepDir]);
313
+ wt(["-w", "0", "close-pane"]);
314
+ closed++;
315
+ } catch {
316
+ break;
317
+ }
318
+ }
319
+
320
+ return closed;
321
+ }
322
+
323
+ /**
324
+ * tmux 세션 생성 + 레이아웃 분할
325
+ * @param {string} sessionName — 세션 이름
326
+ * @param {object} opts
327
+ * @param {'2x2'|'1xN'|'Nx1'} opts.layout — 레이아웃 (기본 2x2)
328
+ * @param {number} opts.paneCount — pane 수 (기본 4)
329
+ * @returns {{ sessionName: string, panes: string[] }}
330
+ */
331
+ export function createSession(sessionName, opts = {}) {
332
+ const { layout = "2x2", paneCount = 4 } = opts;
333
+
334
+ // 기존 세션 정리
335
+ if (sessionExists(sessionName)) {
336
+ killSession(sessionName);
337
+ }
338
+
339
+ // 새 세션 생성 (detached)
340
+ tmux(`new-session -d -s ${sessionName} -x 220 -y 55`);
341
+
342
+ const panes = [`${sessionName}:0.0`];
343
+
344
+ if (layout === "2x2" && paneCount >= 3) {
345
+ // 3-pane 기본: lead 왼쪽, workers 오른쪽 상/하
346
+ // 4-pane: 좌/우 각각 상/하(균등 2x2)
347
+ tmux(`split-window -h -t ${sessionName}:0.0`);
348
+ tmux(`split-window -v -t ${sessionName}:0.1`);
349
+ if (paneCount >= 4) {
350
+ tmux(`split-window -v -t ${sessionName}:0.0`);
351
+ }
352
+ // pane ID 재수집
353
+ panes.length = 0;
354
+ for (let i = 0; i < Math.min(paneCount, 4); i++) {
355
+ panes.push(`${sessionName}:0.${i}`);
356
+ }
357
+ } else if (layout === "1xN") {
358
+ // 세로 분할(좌/우 컬럼 확장)
359
+ for (let i = 1; i < paneCount; i++) {
360
+ tmux(`split-window -h -t ${sessionName}:0`);
361
+ }
362
+ tmux(`select-layout -t ${sessionName}:0 even-horizontal`);
363
+ panes.length = 0;
364
+ for (let i = 0; i < paneCount; i++) {
365
+ panes.push(`${sessionName}:0.${i}`);
366
+ }
367
+ } else {
368
+ // Nx1 가로 분할(상/하 스택)
369
+ for (let i = 1; i < paneCount; i++) {
370
+ tmux(`split-window -v -t ${sessionName}:0`);
371
+ }
372
+ tmux(`select-layout -t ${sessionName}:0 even-vertical`);
373
+ panes.length = 0;
374
+ for (let i = 0; i < paneCount; i++) {
375
+ panes.push(`${sessionName}:0.${i}`);
376
+ }
377
+ }
378
+
379
+ return { sessionName, panes };
380
+ }
381
+
382
+ /**
383
+ * pane 포커스 이동
384
+ * @param {string} target
385
+ * @param {object} opts
386
+ * @param {boolean} opts.zoom
387
+ */
388
+ export function focusPane(target, opts = {}) {
389
+ const { zoom = false } = opts;
390
+ tmux(`select-pane -t ${target}`);
391
+ if (zoom) {
392
+ try { tmux(`resize-pane -t ${target} -Z`); } catch {}
393
+ }
394
+ }
395
+
396
+ /**
397
+ * 팀메이트 조작 키 바인딩 설정
398
+ * - Shift+Down: 다음 팀메이트
399
+ * - Shift+Up: 이전 팀메이트
400
+ * - Escape: 현재 팀메이트 인터럽트(C-c)
401
+ * - Ctrl+T: 태스크 목록 표시
402
+ * @param {string} sessionName
403
+ * @param {object} opts
404
+ * @param {boolean} opts.inProcess
405
+ * @param {string} opts.taskListCommand
406
+ */
407
+ export function configureTeammateKeybindings(sessionName, opts = {}) {
408
+ const { inProcess = false, taskListCommand = "" } = opts;
409
+ const cond = `#{==:#{session_name},${sessionName}}`;
410
+
411
+ if (inProcess) {
412
+ // 단일 뷰(zoom) 상태에서 팀메이트 순환
413
+ tmux(`bind-key -T root -n S-Down if-shell -F '${cond}' 'select-pane -t :.+ \\; resize-pane -Z' 'send-keys S-Down'`);
414
+ tmux(`bind-key -T root -n S-Up if-shell -F '${cond}' 'select-pane -t :.- \\; resize-pane -Z' 'send-keys S-Up'`);
415
+ } else {
416
+ // 분할 뷰에서 팀메이트 순환
417
+ tmux(`bind-key -T root -n S-Down if-shell -F '${cond}' 'select-pane -t :.+' 'send-keys S-Down'`);
418
+ tmux(`bind-key -T root -n S-Up if-shell -F '${cond}' 'select-pane -t :.-' 'send-keys S-Up'`);
419
+ }
420
+
421
+ // 현재 활성 pane 인터럽트
422
+ tmux(`bind-key -T root -n Escape if-shell -F '${cond}' 'send-keys C-c' 'send-keys Escape'`);
423
+
424
+ // 태스크 목록 토글 (tmux 3.2+ popup 우선, 실패 시 안내 메시지)
425
+ if (taskListCommand) {
426
+ const escaped = taskListCommand.replace(/'/g, "'\\''");
427
+ try {
428
+ tmux(`bind-key -T root -n C-t if-shell -F '${cond}' \"display-popup -E '${escaped}'\" \"send-keys C-t\"`);
429
+ } catch {
430
+ tmux(`bind-key -T root -n C-t if-shell -F '${cond}' 'display-message "tfx team tasks 명령으로 태스크 확인"' 'send-keys C-t'`);
431
+ }
432
+ }
433
+ }
434
+
435
+ /**
436
+ * tmux 세션 연결 (포그라운드 전환)
437
+ * @param {string} sessionName
438
+ */
439
+ export function attachSession(sessionName) {
440
+ if (!process.stdout.isTTY || !process.stdin.isTTY) {
441
+ throw new Error("현재 터미널은 tmux attach를 지원하지 않음 (non-TTY)");
442
+ }
443
+
444
+ const { command, args } = resolveAttachCommand(sessionName);
445
+ const r = spawnSync(command, args, {
446
+ stdio: "inherit",
447
+ timeout: 0, // 타임아웃 없음 (사용자가 detach할 때까지)
448
+ });
449
+ if ((r.status ?? 1) !== 0) {
450
+ throw new Error(`tmux attach 실패 (exit=${r.status})`);
451
+ }
452
+ }
453
+
454
+ /**
455
+ * tmux 세션 존재 확인
456
+ * @param {string} sessionName
457
+ * @returns {boolean}
458
+ */
459
+ export function sessionExists(sessionName) {
460
+ try {
461
+ tmux(`has-session -t ${sessionName}`, { stdio: "ignore" });
462
+ return true;
463
+ } catch {
464
+ return false;
465
+ }
466
+ }
467
+
468
+ /**
469
+ * tmux 세션 종료
470
+ * @param {string} sessionName
471
+ */
472
+ export function killSession(sessionName) {
473
+ try {
474
+ tmux(`kill-session -t ${sessionName}`, { stdio: "ignore" });
475
+ } catch {
476
+ // 이미 종료된 세션 — 무시
477
+ }
478
+ }
479
+
480
+ /**
481
+ * tfx-team- 접두사 세션 목록
482
+ * @returns {string[]}
483
+ */
484
+ export function listSessions() {
485
+ try {
486
+ const output = tmux('list-sessions -F "#{session_name}"');
487
+ return output
488
+ .split("\n")
489
+ .filter((s) => s.startsWith("tfx-team-"));
490
+ } catch {
491
+ return [];
492
+ }
493
+ }
494
+
495
+ /**
496
+ * 세션 attach client 수 조회
497
+ * @param {string} sessionName
498
+ * @returns {number|null}
499
+ */
500
+ export function getSessionAttachedCount(sessionName) {
501
+ try {
502
+ const output = tmux('list-sessions -F "#{session_name} #{session_attached}"');
503
+ const line = output
504
+ .split("\n")
505
+ .find((l) => l.startsWith(`${sessionName} `));
506
+ if (!line) return null;
507
+ const n = parseInt(line.split(" ")[1], 10);
508
+ return Number.isFinite(n) ? n : null;
509
+ } catch {
510
+ return null;
511
+ }
512
+ }
513
+
514
+ /**
515
+ * pane 마지막 N줄 캡처
516
+ * @param {string} target — 예: tfx-team-abc:0.1
517
+ * @param {number} lines — 캡처할 줄 수 (기본 5)
518
+ * @returns {string}
519
+ */
520
+ export function capturePaneOutput(target, lines = 5) {
521
+ try {
522
+ // -l 플래그는 일부 tmux 빌드(MSYS2)에서 미지원 → 전체 캡처 후 JS에서 절삭
523
+ const full = tmux(`capture-pane -t ${target} -p`);
524
+ const nonEmpty = full.split("\n").filter((l) => l.trim() !== "");
525
+ return nonEmpty.slice(-lines).join("\n");
526
+ } catch {
527
+ return "";
528
+ }
529
+ }