triflux 8.11.2 → 8.12.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.
Files changed (103) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.ko.md +1 -1
  3. package/README.md +1 -1
  4. package/hooks/hooks.json +56 -51
  5. package/hub/pipeline/index.mjs +318 -318
  6. package/hub/routing/q-learning.mjs +2 -1
  7. package/hub/schema.sql +146 -146
  8. package/hub/team/cli/commands/kill.mjs +37 -37
  9. package/hub/team/cli/commands/start/index.mjs +3 -2
  10. package/hub/team/cli/commands/start/parse-args.mjs +5 -0
  11. package/hub/team/cli/commands/start/start-headless.mjs +2 -1
  12. package/hub/team/cli/commands/stop.mjs +31 -31
  13. package/hub/team/cli/commands/task.mjs +30 -30
  14. package/hub/team/cli/help.mjs +41 -40
  15. package/hub/team/cli/services/hub-client.mjs +208 -208
  16. package/hub/team/cli/services/native-control.mjs +118 -118
  17. package/hub/team/cli/services/runtime-mode.mjs +62 -62
  18. package/hub/team/cli/services/state-store.mjs +48 -48
  19. package/hub/team/dashboard-anchor.mjs +14 -0
  20. package/hub/team/dashboard.mjs +274 -274
  21. package/hub/team/headless.mjs +44 -19
  22. package/hub/team/native.mjs +649 -649
  23. package/hub/tools.mjs +554 -554
  24. package/hub/workers/delegator-mcp.mjs +21 -1
  25. package/package.json +1 -1
  26. package/scripts/__tests__/remote-spawn-transfer.test.mjs +117 -0
  27. package/scripts/__tests__/remote-spawn.test.mjs +78 -0
  28. package/scripts/cache-buildup.mjs +401 -0
  29. package/scripts/headless-guard.mjs +10 -3
  30. package/scripts/hub-ensure.mjs +120 -120
  31. package/scripts/lib/mcp-filter.mjs +720 -720
  32. package/scripts/lib/remote-spawn-transfer.mjs +196 -0
  33. package/scripts/mcp-check.mjs +237 -127
  34. package/scripts/mcp-gateway-ensure.mjs +6 -8
  35. package/scripts/mcp-gateway-integration-test.mjs +228 -0
  36. package/scripts/mcp-gateway-start.mjs +42 -16
  37. package/scripts/mcp-gateway-start.ps1 +17 -14
  38. package/scripts/mcp-gateway-verify.mjs +1 -1
  39. package/scripts/preflight-cache.mjs +137 -137
  40. package/scripts/remote-spawn.mjs +404 -40
  41. package/scripts/setup.mjs +18 -0
  42. package/scripts/tfx-route-worker.mjs +165 -165
  43. package/scripts/tfx-route.sh +85 -16
  44. package/scripts/token-snapshot.mjs +575 -575
  45. package/skills/tfx-analysis/SKILL.md +101 -101
  46. package/skills/tfx-autopilot/SKILL.md +112 -112
  47. package/skills/tfx-autoresearch/SKILL.md +1 -0
  48. package/skills/tfx-autoroute/SKILL.md +184 -184
  49. package/skills/tfx-codex-swarm/SKILL.md +449 -0
  50. package/skills/tfx-codex-swarm/evals/evals.json +26 -0
  51. package/skills/tfx-codex-swarm-workspace/iteration-1/benchmark.json +33 -0
  52. package/skills/tfx-codex-swarm-workspace/iteration-1/full-swarm-all-prds/eval_metadata.json +42 -0
  53. package/skills/tfx-codex-swarm-workspace/iteration-1/full-swarm-all-prds/with_skill/grading.json +11 -0
  54. package/skills/tfx-codex-swarm-workspace/iteration-1/full-swarm-all-prds/with_skill/outputs/analysis.md +87 -0
  55. package/skills/tfx-codex-swarm-workspace/iteration-1/full-swarm-all-prds/with_skill/outputs/classification.md +35 -0
  56. package/skills/tfx-codex-swarm-workspace/iteration-1/full-swarm-all-prds/with_skill/outputs/commands.sh +275 -0
  57. package/skills/tfx-codex-swarm-workspace/iteration-1/full-swarm-all-prds/with_skill/outputs/routing.md +56 -0
  58. package/skills/tfx-codex-swarm-workspace/iteration-1/full-swarm-all-prds/with_skill/timing.json +5 -0
  59. package/skills/tfx-codex-swarm-workspace/iteration-1/full-swarm-all-prds/without_skill/grading.json +11 -0
  60. package/skills/tfx-codex-swarm-workspace/iteration-1/full-swarm-all-prds/without_skill/outputs/analysis.md +92 -0
  61. package/skills/tfx-codex-swarm-workspace/iteration-1/full-swarm-all-prds/without_skill/outputs/classification.md +71 -0
  62. package/skills/tfx-codex-swarm-workspace/iteration-1/full-swarm-all-prds/without_skill/outputs/commands.sh +264 -0
  63. package/skills/tfx-codex-swarm-workspace/iteration-1/full-swarm-all-prds/without_skill/outputs/routing.md +113 -0
  64. package/skills/tfx-codex-swarm-workspace/iteration-1/full-swarm-all-prds/without_skill/timing.json +5 -0
  65. package/skills/tfx-codex-swarm-workspace/iteration-1/implicit-swarm-no-keywords/eval_metadata.json +32 -0
  66. package/skills/tfx-codex-swarm-workspace/iteration-1/implicit-swarm-no-keywords/with_skill/grading.json +9 -0
  67. package/skills/tfx-codex-swarm-workspace/iteration-1/implicit-swarm-no-keywords/with_skill/outputs/analysis.md +96 -0
  68. package/skills/tfx-codex-swarm-workspace/iteration-1/implicit-swarm-no-keywords/with_skill/outputs/classification.md +38 -0
  69. package/skills/tfx-codex-swarm-workspace/iteration-1/implicit-swarm-no-keywords/with_skill/outputs/commands.sh +151 -0
  70. package/skills/tfx-codex-swarm-workspace/iteration-1/implicit-swarm-no-keywords/with_skill/outputs/routing.md +51 -0
  71. package/skills/tfx-codex-swarm-workspace/iteration-1/implicit-swarm-no-keywords/with_skill/timing.json +5 -0
  72. package/skills/tfx-codex-swarm-workspace/iteration-1/implicit-swarm-no-keywords/without_skill/grading.json +9 -0
  73. package/skills/tfx-codex-swarm-workspace/iteration-1/implicit-swarm-no-keywords/without_skill/outputs/analysis.md +127 -0
  74. package/skills/tfx-codex-swarm-workspace/iteration-1/implicit-swarm-no-keywords/without_skill/outputs/classification.md +57 -0
  75. package/skills/tfx-codex-swarm-workspace/iteration-1/implicit-swarm-no-keywords/without_skill/outputs/commands.sh +129 -0
  76. package/skills/tfx-codex-swarm-workspace/iteration-1/implicit-swarm-no-keywords/without_skill/outputs/routing.md +84 -0
  77. package/skills/tfx-codex-swarm-workspace/iteration-1/implicit-swarm-no-keywords/without_skill/timing.json +5 -0
  78. package/skills/tfx-codex-swarm-workspace/iteration-1/selective-spawn-with-override/eval_metadata.json +27 -0
  79. package/skills/tfx-codex-swarm-workspace/iteration-1/selective-spawn-with-override/with_skill/grading.json +8 -0
  80. package/skills/tfx-codex-swarm-workspace/iteration-1/selective-spawn-with-override/with_skill/outputs/analysis.md +98 -0
  81. package/skills/tfx-codex-swarm-workspace/iteration-1/selective-spawn-with-override/with_skill/outputs/classification.md +65 -0
  82. package/skills/tfx-codex-swarm-workspace/iteration-1/selective-spawn-with-override/with_skill/outputs/commands.sh +123 -0
  83. package/skills/tfx-codex-swarm-workspace/iteration-1/selective-spawn-with-override/with_skill/outputs/routing.md +66 -0
  84. package/skills/tfx-codex-swarm-workspace/iteration-1/selective-spawn-with-override/with_skill/timing.json +5 -0
  85. package/skills/tfx-codex-swarm-workspace/iteration-1/selective-spawn-with-override/without_skill/grading.json +8 -0
  86. package/skills/tfx-codex-swarm-workspace/iteration-1/selective-spawn-with-override/without_skill/outputs/analysis.md +88 -0
  87. package/skills/tfx-codex-swarm-workspace/iteration-1/selective-spawn-with-override/without_skill/outputs/classification.md +40 -0
  88. package/skills/tfx-codex-swarm-workspace/iteration-1/selective-spawn-with-override/without_skill/outputs/commands.sh +130 -0
  89. package/skills/tfx-codex-swarm-workspace/iteration-1/selective-spawn-with-override/without_skill/outputs/routing.md +61 -0
  90. package/skills/tfx-codex-swarm-workspace/iteration-1/selective-spawn-with-override/without_skill/timing.json +5 -0
  91. package/skills/tfx-profile/SKILL.md +141 -51
  92. package/skills/tfx-qa/SKILL.md +117 -117
  93. package/skills/tfx-remote-spawn/references/hosts.json +16 -16
  94. package/skills/tfx-review/SKILL.md +51 -51
  95. package/skills/tfx-setup/SKILL.md +20 -0
  96. package/tui/gemini-profile.mjs +254 -0
  97. package/tui/setup.mjs +36 -1
  98. package/scripts/claude-logged.ps1 +0 -54
  99. package/scripts/demo-tui.mjs +0 -59
  100. package/skills/.omc/state/agent-replay-8f0e10a9-9693-4410-96f5-a6b07e8ed995.jsonl +0 -1
  101. package/skills/.omc/state/idle-notif-cooldown.json +0 -3
  102. package/skills/.omc/state/last-tool-error.json +0 -7
  103. package/skills/.omc/state/subagent-tracking.json +0 -7
@@ -1,40 +1,41 @@
1
- import { AMBER, BOLD, DIM, GRAY, RESET, WHITE } from "../shared.mjs";
2
-
3
- export function renderTeamHelp() {
4
- console.log(`
5
- ${AMBER}${BOLD}⬡ tfx multi${RESET} ${DIM}멀티-CLI 팀 모드 (Lead + Teammates)${RESET}
6
-
7
- ${BOLD}시작${RESET}
8
- ${WHITE}tfx multi "작업 설명"${RESET}
9
- ${WHITE}tfx multi --agents codex,gemini --lead claude "작업"${RESET}
10
- ${WHITE}tfx multi --teammate-mode tmux "작업"${RESET}
11
- ${WHITE}tfx multi --teammate-mode wt "작업"${RESET} ${DIM}(Windows Terminal split-pane)${RESET}
12
- ${WHITE}tfx multi --layout 1xN "작업"${RESET} ${DIM}(세로 분할 컬럼)${RESET}
13
- ${WHITE}tfx multi --layout Nx1 "작업"${RESET} ${DIM}(가로 분할 스택)${RESET}
14
- ${WHITE}tfx multi --dashboard-layout auto "작업"${RESET} ${DIM}(dashboard viewer 레이아웃 자동 결정)${RESET}
15
- ${WHITE}tfx multi --dashboard-size 0.4 "작업"${RESET} ${DIM}(대시보드 분할 비율 0.2~0.8, 기본 0.50)${RESET}
16
- ${WHITE}tfx multi --teammate-mode in-process "작업"${RESET} ${DIM}(tmux 불필요)${RESET}
17
-
18
- ${BOLD}제어${RESET}
19
- ${WHITE}tfx multi status${RESET} ${GRAY}현재 팀 상태${RESET}
20
- ${WHITE}tfx multi debug${RESET} ${DIM}[--lines 30]${RESET} ${GRAY}강화 디버그 출력(환경/세션/pane tail)${RESET}
21
- ${WHITE}tfx multi tasks${RESET} ${GRAY}공유 태스크 목록${RESET}
22
- ${WHITE}tfx multi task${RESET} ${DIM}<pending|progress|done> <T1>${RESET} ${GRAY}태스크 상태 갱신${RESET}
23
- ${WHITE}tfx multi attach${RESET} ${DIM}[--wt]${RESET} ${GRAY}세션 재연결 (WT 분할은 opt-in)${RESET}
24
- ${WHITE}tfx multi focus${RESET} ${DIM}<lead|이름|번호> [--wt]${RESET} ${GRAY}특정 팀메이트 포커스${RESET}
25
- ${WHITE}tfx multi send${RESET} ${DIM}<lead|이름|번호> "msg"${RESET} ${GRAY}팀메이트에 메시지 주입${RESET}
26
- ${WHITE}tfx multi interrupt${RESET} ${DIM}<대상>${RESET} ${GRAY}팀메이트 인터럽트(C-c)${RESET}
27
- ${WHITE}tfx multi control${RESET} ${DIM}<대상> <cmd>${RESET} ${GRAY}리드 제어명령(interrupt|stop|pause|resume)${RESET}
28
- ${WHITE}tfx multi stop${RESET} ${GRAY}graceful 종료${RESET}
29
- ${WHITE}tfx multi kill${RESET} ${GRAY}모든 팀 세션 강제 종료${RESET}
30
- ${WHITE}tfx multi list${RESET} ${GRAY}활성 세션 목록${RESET}
31
-
32
- ${BOLD}키 조작(Claude teammate 스타일, tmux 모드)${RESET}
33
- ${WHITE}Shift+Down${RESET} ${GRAY}다음 팀메이트${RESET}
34
- ${WHITE}Shift+Tab${RESET} ${GRAY}이전 팀메이트 (권장)${RESET}
35
- ${WHITE}Shift+Left${RESET} ${GRAY}이전 팀메이트 (대체)${RESET}
36
- ${WHITE}Shift+Up${RESET} ${GRAY}미지원 (Claude Code가 캡처 불가, scroll-up 충돌)${RESET}
37
- ${WHITE}Escape${RESET} ${GRAY}현재 팀메이트 인터럽트${RESET}
38
- ${WHITE}Ctrl+T${RESET} ${GRAY}태스크 목록 토글${RESET}
39
- `);
40
- }
1
+ import { AMBER, BOLD, DIM, GRAY, RESET, WHITE } from "../shared.mjs";
2
+
3
+ export function renderTeamHelp() {
4
+ console.log(`
5
+ ${AMBER}${BOLD}⬡ tfx multi${RESET} ${DIM}멀티-CLI 팀 모드 (Lead + Teammates)${RESET}
6
+
7
+ ${BOLD}시작${RESET}
8
+ ${WHITE}tfx multi "작업 설명"${RESET}
9
+ ${WHITE}tfx multi --agents codex,gemini --lead claude "작업"${RESET}
10
+ ${WHITE}tfx multi --teammate-mode tmux "작업"${RESET}
11
+ ${WHITE}tfx multi --teammate-mode wt "작업"${RESET} ${DIM}(Windows Terminal split-pane)${RESET}
12
+ ${WHITE}tfx multi --layout 1xN "작업"${RESET} ${DIM}(세로 분할 컬럼)${RESET}
13
+ ${WHITE}tfx multi --layout Nx1 "작업"${RESET} ${DIM}(가로 분할 스택)${RESET}
14
+ ${WHITE}tfx multi --dashboard-layout auto "작업"${RESET} ${DIM}(dashboard viewer 레이아웃 자동 결정)${RESET}
15
+ ${WHITE}tfx multi --dashboard-size 0.4 "작업"${RESET} ${DIM}(대시보드 분할 비율 0.2~0.8, 기본 0.50)${RESET}
16
+ ${WHITE}tfx multi --dashboard-anchor window "작업"${RESET} ${DIM}(대시보드 고정 위치: window|tab, 기본 window)${RESET}
17
+ ${WHITE}tfx multi --teammate-mode in-process "작업"${RESET} ${DIM}(tmux 불필요)${RESET}
18
+
19
+ ${BOLD}제어${RESET}
20
+ ${WHITE}tfx multi status${RESET} ${GRAY}현재 상태${RESET}
21
+ ${WHITE}tfx multi debug${RESET} ${DIM}[--lines 30]${RESET} ${GRAY}강화 디버그 출력(환경/세션/pane tail)${RESET}
22
+ ${WHITE}tfx multi tasks${RESET} ${GRAY}공유 태스크 목록${RESET}
23
+ ${WHITE}tfx multi task${RESET} ${DIM}<pending|progress|done> <T1>${RESET} ${GRAY}태스크 상태 갱신${RESET}
24
+ ${WHITE}tfx multi attach${RESET} ${DIM}[--wt]${RESET} ${GRAY}세션 재연결 (WT 분할은 opt-in)${RESET}
25
+ ${WHITE}tfx multi focus${RESET} ${DIM}<lead|이름|번호> [--wt]${RESET} ${GRAY}특정 팀메이트 포커스${RESET}
26
+ ${WHITE}tfx multi send${RESET} ${DIM}<lead|이름|번호> "msg"${RESET} ${GRAY}팀메이트에 메시지 주입${RESET}
27
+ ${WHITE}tfx multi interrupt${RESET} ${DIM}<대상>${RESET} ${GRAY}팀메이트 인터럽트(C-c)${RESET}
28
+ ${WHITE}tfx multi control${RESET} ${DIM}<대상> <cmd>${RESET} ${GRAY}리드 제어명령(interrupt|stop|pause|resume)${RESET}
29
+ ${WHITE}tfx multi stop${RESET} ${GRAY}graceful 종료${RESET}
30
+ ${WHITE}tfx multi kill${RESET} ${GRAY}모든 세션 강제 종료${RESET}
31
+ ${WHITE}tfx multi list${RESET} ${GRAY}활성 세션 목록${RESET}
32
+
33
+ ${BOLD} 조작(Claude teammate 스타일, tmux 모드)${RESET}
34
+ ${WHITE}Shift+Down${RESET} ${GRAY}다음 팀메이트${RESET}
35
+ ${WHITE}Shift+Tab${RESET} ${GRAY}이전 팀메이트 (권장)${RESET}
36
+ ${WHITE}Shift+Left${RESET} ${GRAY}이전 팀메이트 (대체)${RESET}
37
+ ${WHITE}Shift+Up${RESET} ${GRAY}미지원 (Claude Code가 캡처 불가, scroll-up 충돌)${RESET}
38
+ ${WHITE}Escape${RESET} ${GRAY}현재 팀메이트 인터럽트${RESET}
39
+ ${WHITE}Ctrl+T${RESET} ${GRAY}태스크 목록 토글${RESET}
40
+ `);
41
+ }
@@ -1,208 +1,208 @@
1
- import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
2
- import { join } from "node:path";
3
- import { spawn } from "node:child_process";
4
-
5
- import { HUB_PID_DIR, PKG_ROOT } from "./state-store.mjs";
6
- export { nativeGetStatus } from "./native-control.mjs";
7
-
8
- const HUB_PID_FILE = join(HUB_PID_DIR, "hub.pid");
9
- const LOOPBACK_HOSTS = new Set(["127.0.0.1", "localhost", "::1"]);
10
-
11
- export function formatHostForUrl(host) {
12
- return host.includes(":") ? `[${host}]` : host;
13
- }
14
-
15
- export function buildHubBaseUrl(host, port) {
16
- return `http://${formatHostForUrl(host)}:${port}`;
17
- }
18
-
19
- export function getDefaultHubPort() {
20
- const envPortRaw = Number(process.env.TFX_HUB_PORT || "27888");
21
- return Number.isFinite(envPortRaw) && envPortRaw > 0 ? envPortRaw : 27888;
22
- }
23
-
24
- export function getDefaultHubUrl() {
25
- return `${buildHubBaseUrl("127.0.0.1", getDefaultHubPort())}/mcp`;
26
- }
27
-
28
- function normalizeLoopbackHost(host) {
29
- if (typeof host !== "string") return "127.0.0.1";
30
- const candidate = host.trim();
31
- return LOOPBACK_HOSTS.has(candidate) ? candidate : "127.0.0.1";
32
- }
33
-
34
- async function probeHubStatus(host, port, timeoutMs = 1500) {
35
- try {
36
- const res = await fetch(`${buildHubBaseUrl(host, port)}/status`, {
37
- signal: AbortSignal.timeout(timeoutMs),
38
- });
39
- if (!res.ok) return null;
40
- const data = await res.json();
41
- return data?.hub ? data : null;
42
- } catch {
43
- return null;
44
- }
45
- }
46
-
47
- export async function getHubInfo() {
48
- const probePort = getDefaultHubPort();
49
-
50
- if (existsSync(HUB_PID_FILE)) {
51
- try {
52
- const raw = JSON.parse(readFileSync(HUB_PID_FILE, "utf8"));
53
- const pid = Number(raw?.pid);
54
- if (!Number.isFinite(pid) || pid <= 0) throw new Error("invalid pid");
55
- process.kill(pid, 0);
56
- const host = normalizeLoopbackHost(raw?.host);
57
- const port = Number(raw?.port) || 27888;
58
- const status = await probeHubStatus(host, port, 1200);
59
- return {
60
- ...raw,
61
- pid,
62
- host,
63
- port,
64
- url: `${buildHubBaseUrl(host, port)}/mcp`,
65
- ...(status ? {} : { degraded: true }),
66
- };
67
- } catch {
68
- try { unlinkSync(HUB_PID_FILE); } catch {}
69
- }
70
- }
71
-
72
- for (const portCandidate of Array.from(new Set([probePort, 27888]))) {
73
- const data = await probeHubStatus("127.0.0.1", portCandidate, 1200);
74
- if (!data) continue;
75
- const port = Number(data.port) || portCandidate;
76
- const pid = Number(data.pid);
77
- const recovered = {
78
- pid: Number.isFinite(pid) ? pid : null,
79
- host: "127.0.0.1",
80
- port,
81
- url: `${buildHubBaseUrl("127.0.0.1", port)}/mcp`,
82
- discovered: true,
83
- };
84
- if (Number.isFinite(recovered.pid) && recovered.pid > 0) {
85
- try {
86
- mkdirSync(HUB_PID_DIR, { recursive: true });
87
- writeFileSync(HUB_PID_FILE, JSON.stringify({ ...recovered, started: Date.now() }));
88
- } catch {}
89
- }
90
- return recovered;
91
- }
92
- return null;
93
- }
94
-
95
- export async function startHubDaemon() {
96
- const serverPath = join(PKG_ROOT, "hub", "server.mjs");
97
- if (!existsSync(serverPath)) {
98
- const error = new Error("hub/server.mjs 없음");
99
- error.code = "HUB_SERVER_MISSING";
100
- throw error;
101
- }
102
-
103
- const child = spawn(process.execPath, [serverPath], {
104
- env: { ...process.env },
105
- stdio: "ignore",
106
- detached: true,
107
- windowsHide: true,
108
- });
109
- child.unref();
110
-
111
- const expectedPort = getDefaultHubPort();
112
- const deadline = Date.now() + 3000;
113
- while (Date.now() < deadline) {
114
- const status = await probeHubStatus("127.0.0.1", expectedPort, 500);
115
- if (status?.hub) {
116
- return {
117
- pid: Number(status.pid) || child.pid,
118
- host: "127.0.0.1",
119
- port: expectedPort,
120
- url: `${buildHubBaseUrl("127.0.0.1", expectedPort)}/mcp`,
121
- };
122
- }
123
- await new Promise((resolve) => setTimeout(resolve, 100));
124
- }
125
-
126
- return null;
127
- }
128
-
129
- /**
130
- * Hub가 살아있는지 확인하고, 죽어있으면 재시작을 시도한다.
131
- * exponential backoff: 1초, 2초, 4초
132
- * 모든 재시작 실패 시 에러를 throw한다 (silent fail 아님).
133
- * @param {number} [maxRetries=3]
134
- * @returns {Promise<object>} Hub 정보
135
- * @throws {Error} 모든 재시작 시도 실패 시
136
- */
137
- export async function ensureHubAlive(maxRetries = 3) {
138
- const hub = await getHubInfo();
139
- if (hub && !hub.degraded) return hub;
140
-
141
- let lastError = null;
142
- for (let i = 0; i < maxRetries; i++) {
143
- try {
144
- const restarted = await startHubDaemon();
145
- if (restarted) {
146
- // 재시작 후 연결 복구 확인
147
- const recovered = await getHubInfo();
148
- if (recovered) return recovered;
149
- }
150
- } catch (err) {
151
- lastError = err;
152
- }
153
- // 다음 재시도 전 대기: 1초, 2초, 4초 (마지막 시도 후에는 대기 없음)
154
- if (i < maxRetries - 1) {
155
- const backoffMs = Math.pow(2, i) * 1000; // i=0: 1초, i=1: 2초, i=2: 4초
156
- await new Promise((resolve) => setTimeout(resolve, backoffMs));
157
- }
158
- }
159
-
160
- const error = new Error(`Hub 재시작 ${maxRetries}회 모두 실패${lastError ? `: ${lastError.message}` : ""}`);
161
- error.code = "HUB_RESTART_FAILED";
162
- error.cause = lastError;
163
- throw error;
164
- }
165
-
166
- export async function fetchHubTaskList(state) {
167
- const hubBase = (state?.hubUrl || getDefaultHubUrl()).replace(/\/mcp$/, "");
168
- const teamName = state?.native?.teamName || state?.sessionName || null;
169
- if (!teamName) return [];
170
-
171
- try {
172
- const res = await fetch(`${hubBase}/bridge/team/task-list`, {
173
- method: "POST",
174
- headers: { "Content-Type": "application/json" },
175
- body: JSON.stringify({ team_name: teamName }),
176
- signal: AbortSignal.timeout(2000),
177
- });
178
- const data = await res.json();
179
- return data?.ok ? (data.data?.tasks || []) : [];
180
- } catch {
181
- return [];
182
- }
183
- }
184
-
185
- export async function publishLeadControl(state, targetMember, command, reason = "") {
186
- const hubBase = (state?.hubUrl || getDefaultHubUrl()).replace(/\/mcp$/, "");
187
- const leadAgent = (state?.members || []).find((member) => member.role === "lead")?.agentId || "lead";
188
-
189
- try {
190
- const res = await fetch(`${hubBase}/bridge/control`, {
191
- method: "POST",
192
- headers: { "Content-Type": "application/json" },
193
- body: JSON.stringify({
194
- from_agent: leadAgent,
195
- to_agent: targetMember.agentId,
196
- command,
197
- reason,
198
- payload: {
199
- issued_by: leadAgent,
200
- issued_at: Date.now(),
201
- },
202
- }),
203
- });
204
- return !!res.ok;
205
- } catch {
206
- return false;
207
- }
208
- }
1
+ import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { spawn } from "node:child_process";
4
+
5
+ import { HUB_PID_DIR, PKG_ROOT } from "./state-store.mjs";
6
+ export { nativeGetStatus } from "./native-control.mjs";
7
+
8
+ const HUB_PID_FILE = join(HUB_PID_DIR, "hub.pid");
9
+ const LOOPBACK_HOSTS = new Set(["127.0.0.1", "localhost", "::1"]);
10
+
11
+ export function formatHostForUrl(host) {
12
+ return host.includes(":") ? `[${host}]` : host;
13
+ }
14
+
15
+ export function buildHubBaseUrl(host, port) {
16
+ return `http://${formatHostForUrl(host)}:${port}`;
17
+ }
18
+
19
+ export function getDefaultHubPort() {
20
+ const envPortRaw = Number(process.env.TFX_HUB_PORT || "27888");
21
+ return Number.isFinite(envPortRaw) && envPortRaw > 0 ? envPortRaw : 27888;
22
+ }
23
+
24
+ export function getDefaultHubUrl() {
25
+ return `${buildHubBaseUrl("127.0.0.1", getDefaultHubPort())}/mcp`;
26
+ }
27
+
28
+ function normalizeLoopbackHost(host) {
29
+ if (typeof host !== "string") return "127.0.0.1";
30
+ const candidate = host.trim();
31
+ return LOOPBACK_HOSTS.has(candidate) ? candidate : "127.0.0.1";
32
+ }
33
+
34
+ async function probeHubStatus(host, port, timeoutMs = 1500) {
35
+ try {
36
+ const res = await fetch(`${buildHubBaseUrl(host, port)}/status`, {
37
+ signal: AbortSignal.timeout(timeoutMs),
38
+ });
39
+ if (!res.ok) return null;
40
+ const data = await res.json();
41
+ return data?.hub ? data : null;
42
+ } catch {
43
+ return null;
44
+ }
45
+ }
46
+
47
+ export async function getHubInfo() {
48
+ const probePort = getDefaultHubPort();
49
+
50
+ if (existsSync(HUB_PID_FILE)) {
51
+ try {
52
+ const raw = JSON.parse(readFileSync(HUB_PID_FILE, "utf8"));
53
+ const pid = Number(raw?.pid);
54
+ if (!Number.isFinite(pid) || pid <= 0) throw new Error("invalid pid");
55
+ process.kill(pid, 0);
56
+ const host = normalizeLoopbackHost(raw?.host);
57
+ const port = Number(raw?.port) || 27888;
58
+ const status = await probeHubStatus(host, port, 1200);
59
+ return {
60
+ ...raw,
61
+ pid,
62
+ host,
63
+ port,
64
+ url: `${buildHubBaseUrl(host, port)}/mcp`,
65
+ ...(status ? {} : { degraded: true }),
66
+ };
67
+ } catch {
68
+ try { unlinkSync(HUB_PID_FILE); } catch {}
69
+ }
70
+ }
71
+
72
+ for (const portCandidate of Array.from(new Set([probePort, 27888]))) {
73
+ const data = await probeHubStatus("127.0.0.1", portCandidate, 1200);
74
+ if (!data) continue;
75
+ const port = Number(data.port) || portCandidate;
76
+ const pid = Number(data.pid);
77
+ const recovered = {
78
+ pid: Number.isFinite(pid) ? pid : null,
79
+ host: "127.0.0.1",
80
+ port,
81
+ url: `${buildHubBaseUrl("127.0.0.1", port)}/mcp`,
82
+ discovered: true,
83
+ };
84
+ if (Number.isFinite(recovered.pid) && recovered.pid > 0) {
85
+ try {
86
+ mkdirSync(HUB_PID_DIR, { recursive: true });
87
+ writeFileSync(HUB_PID_FILE, JSON.stringify({ ...recovered, started: Date.now() }));
88
+ } catch {}
89
+ }
90
+ return recovered;
91
+ }
92
+ return null;
93
+ }
94
+
95
+ export async function startHubDaemon() {
96
+ const serverPath = join(PKG_ROOT, "hub", "server.mjs");
97
+ if (!existsSync(serverPath)) {
98
+ const error = new Error("hub/server.mjs 없음");
99
+ error.code = "HUB_SERVER_MISSING";
100
+ throw error;
101
+ }
102
+
103
+ const child = spawn(process.execPath, [serverPath], {
104
+ env: { ...process.env },
105
+ stdio: "ignore",
106
+ detached: true,
107
+ windowsHide: true,
108
+ });
109
+ child.unref();
110
+
111
+ const expectedPort = getDefaultHubPort();
112
+ const deadline = Date.now() + 3000;
113
+ while (Date.now() < deadline) {
114
+ const status = await probeHubStatus("127.0.0.1", expectedPort, 500);
115
+ if (status?.hub) {
116
+ return {
117
+ pid: Number(status.pid) || child.pid,
118
+ host: "127.0.0.1",
119
+ port: expectedPort,
120
+ url: `${buildHubBaseUrl("127.0.0.1", expectedPort)}/mcp`,
121
+ };
122
+ }
123
+ await new Promise((resolve) => setTimeout(resolve, 100));
124
+ }
125
+
126
+ return null;
127
+ }
128
+
129
+ /**
130
+ * Hub가 살아있는지 확인하고, 죽어있으면 재시작을 시도한다.
131
+ * exponential backoff: 1초, 2초, 4초
132
+ * 모든 재시작 실패 시 에러를 throw한다 (silent fail 아님).
133
+ * @param {number} [maxRetries=3]
134
+ * @returns {Promise<object>} Hub 정보
135
+ * @throws {Error} 모든 재시작 시도 실패 시
136
+ */
137
+ export async function ensureHubAlive(maxRetries = 3) {
138
+ const hub = await getHubInfo();
139
+ if (hub && !hub.degraded) return hub;
140
+
141
+ let lastError = null;
142
+ for (let i = 0; i < maxRetries; i++) {
143
+ try {
144
+ const restarted = await startHubDaemon();
145
+ if (restarted) {
146
+ // 재시작 후 연결 복구 확인
147
+ const recovered = await getHubInfo();
148
+ if (recovered) return recovered;
149
+ }
150
+ } catch (err) {
151
+ lastError = err;
152
+ }
153
+ // 다음 재시도 전 대기: 1초, 2초, 4초 (마지막 시도 후에는 대기 없음)
154
+ if (i < maxRetries - 1) {
155
+ const backoffMs = Math.pow(2, i) * 1000; // i=0: 1초, i=1: 2초, i=2: 4초
156
+ await new Promise((resolve) => setTimeout(resolve, backoffMs));
157
+ }
158
+ }
159
+
160
+ const error = new Error(`Hub 재시작 ${maxRetries}회 모두 실패${lastError ? `: ${lastError.message}` : ""}`);
161
+ error.code = "HUB_RESTART_FAILED";
162
+ error.cause = lastError;
163
+ throw error;
164
+ }
165
+
166
+ export async function fetchHubTaskList(state) {
167
+ const hubBase = (state?.hubUrl || getDefaultHubUrl()).replace(/\/mcp$/, "");
168
+ const teamName = state?.native?.teamName || state?.sessionName || null;
169
+ if (!teamName) return [];
170
+
171
+ try {
172
+ const res = await fetch(`${hubBase}/bridge/team/task-list`, {
173
+ method: "POST",
174
+ headers: { "Content-Type": "application/json" },
175
+ body: JSON.stringify({ team_name: teamName }),
176
+ signal: AbortSignal.timeout(2000),
177
+ });
178
+ const data = await res.json();
179
+ return data?.ok ? (data.data?.tasks || []) : [];
180
+ } catch {
181
+ return [];
182
+ }
183
+ }
184
+
185
+ export async function publishLeadControl(state, targetMember, command, reason = "") {
186
+ const hubBase = (state?.hubUrl || getDefaultHubUrl()).replace(/\/mcp$/, "");
187
+ const leadAgent = (state?.members || []).find((member) => member.role === "lead")?.agentId || "lead";
188
+
189
+ try {
190
+ const res = await fetch(`${hubBase}/bridge/control`, {
191
+ method: "POST",
192
+ headers: { "Content-Type": "application/json" },
193
+ body: JSON.stringify({
194
+ from_agent: leadAgent,
195
+ to_agent: targetMember.agentId,
196
+ command,
197
+ reason,
198
+ payload: {
199
+ issued_by: leadAgent,
200
+ issued_at: Date.now(),
201
+ },
202
+ }),
203
+ });
204
+ return !!res.ok;
205
+ } catch {
206
+ return false;
207
+ }
208
+ }