triflux 10.9.10 → 10.9.11

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 (79) hide show
  1. package/CLAUDE.md +212 -0
  2. package/hub/account-broker.mjs +7 -0
  3. package/hub/cli-adapter-base.mjs +3 -0
  4. package/hub/server.mjs +153 -7
  5. package/package.json +21 -56
  6. package/references/hosts.json +46 -0
  7. package/skills/tfx-workspace/async-tests/run-tests.sh +203 -0
  8. package/skills/tfx-workspace/evals/evals.json +79 -0
  9. package/skills/tfx-workspace/iteration-1/benchmark.json +524 -0
  10. package/skills/tfx-workspace/iteration-1/codex-gemini-remap/eval_metadata.json +11 -0
  11. package/skills/tfx-workspace/iteration-1/codex-gemini-remap/old_skill/grading.json +25 -0
  12. package/skills/tfx-workspace/iteration-1/codex-gemini-remap/old_skill/outputs/analysis.md +154 -0
  13. package/skills/tfx-workspace/iteration-1/codex-gemini-remap/old_skill/timing.json +5 -0
  14. package/skills/tfx-workspace/iteration-1/codex-gemini-remap/with_skill/grading.json +25 -0
  15. package/skills/tfx-workspace/iteration-1/codex-gemini-remap/with_skill/outputs/analysis.md +126 -0
  16. package/skills/tfx-workspace/iteration-1/codex-gemini-remap/with_skill/timing.json +5 -0
  17. package/skills/tfx-workspace/iteration-1/doctor-diagnosis/eval_metadata.json +11 -0
  18. package/skills/tfx-workspace/iteration-1/doctor-diagnosis/old_skill/grading.json +25 -0
  19. package/skills/tfx-workspace/iteration-1/doctor-diagnosis/old_skill/outputs/analysis.md +119 -0
  20. package/skills/tfx-workspace/iteration-1/doctor-diagnosis/old_skill/timing.json +5 -0
  21. package/skills/tfx-workspace/iteration-1/doctor-diagnosis/with_skill/grading.json +25 -0
  22. package/skills/tfx-workspace/iteration-1/doctor-diagnosis/with_skill/outputs/analysis.md +115 -0
  23. package/skills/tfx-workspace/iteration-1/doctor-diagnosis/with_skill/timing.json +5 -0
  24. package/skills/tfx-workspace/iteration-1/hub-start-sequence/eval_metadata.json +10 -0
  25. package/skills/tfx-workspace/iteration-1/hub-start-sequence/old_skill/grading.json +20 -0
  26. package/skills/tfx-workspace/iteration-1/hub-start-sequence/old_skill/outputs/analysis.md +86 -0
  27. package/skills/tfx-workspace/iteration-1/hub-start-sequence/old_skill/timing.json +5 -0
  28. package/skills/tfx-workspace/iteration-1/hub-start-sequence/with_skill/grading.json +20 -0
  29. package/skills/tfx-workspace/iteration-1/hub-start-sequence/with_skill/outputs/analysis.md +81 -0
  30. package/skills/tfx-workspace/iteration-1/hub-start-sequence/with_skill/timing.json +5 -0
  31. package/skills/tfx-workspace/iteration-1/multi-team-creation/eval_metadata.json +12 -0
  32. package/skills/tfx-workspace/iteration-1/multi-team-creation/old_skill/grading.json +30 -0
  33. package/skills/tfx-workspace/iteration-1/multi-team-creation/old_skill/outputs/analysis.md +316 -0
  34. package/skills/tfx-workspace/iteration-1/multi-team-creation/old_skill/timing.json +5 -0
  35. package/skills/tfx-workspace/iteration-1/multi-team-creation/with_skill/grading.json +30 -0
  36. package/skills/tfx-workspace/iteration-1/multi-team-creation/with_skill/outputs/analysis.md +352 -0
  37. package/skills/tfx-workspace/iteration-1/multi-team-creation/with_skill/timing.json +5 -0
  38. package/skills/tfx-workspace/iteration-1/review.html +1325 -0
  39. package/skills/tfx-workspace/iteration-1/routing-implement-shortcut/eval_metadata.json +12 -0
  40. package/skills/tfx-workspace/iteration-1/routing-implement-shortcut/old_skill/grading.json +30 -0
  41. package/skills/tfx-workspace/iteration-1/routing-implement-shortcut/old_skill/outputs/analysis.md +97 -0
  42. package/skills/tfx-workspace/iteration-1/routing-implement-shortcut/old_skill/timing.json +5 -0
  43. package/skills/tfx-workspace/iteration-1/routing-implement-shortcut/with_skill/grading.json +30 -0
  44. package/skills/tfx-workspace/iteration-1/routing-implement-shortcut/with_skill/outputs/analysis.md +94 -0
  45. package/skills/tfx-workspace/iteration-1/routing-implement-shortcut/with_skill/timing.json +5 -0
  46. package/skills/tfx-workspace/iteration-1/routing-multi-task-triage/eval_metadata.json +12 -0
  47. package/skills/tfx-workspace/iteration-1/routing-multi-task-triage/old_skill/grading.json +30 -0
  48. package/skills/tfx-workspace/iteration-1/routing-multi-task-triage/old_skill/outputs/analysis.md +209 -0
  49. package/skills/tfx-workspace/iteration-1/routing-multi-task-triage/old_skill/timing.json +5 -0
  50. package/skills/tfx-workspace/iteration-1/routing-multi-task-triage/with_skill/grading.json +30 -0
  51. package/skills/tfx-workspace/iteration-1/routing-multi-task-triage/with_skill/outputs/analysis.md +193 -0
  52. package/skills/tfx-workspace/iteration-1/routing-multi-task-triage/with_skill/timing.json +5 -0
  53. package/skills/tfx-workspace/iteration-2/benchmark.json +144 -0
  54. package/skills/tfx-workspace/iteration-2/multi-team-creation-refactored/eval_metadata.json +13 -0
  55. package/skills/tfx-workspace/iteration-2/multi-team-creation-refactored/old_skill/grading.json +35 -0
  56. package/skills/tfx-workspace/iteration-2/multi-team-creation-refactored/old_skill/outputs/analysis.md +382 -0
  57. package/skills/tfx-workspace/iteration-2/multi-team-creation-refactored/old_skill/timing.json +5 -0
  58. package/skills/tfx-workspace/iteration-2/multi-team-creation-refactored/with_skill/grading.json +35 -0
  59. package/skills/tfx-workspace/iteration-2/multi-team-creation-refactored/with_skill/outputs/analysis.md +333 -0
  60. package/skills/tfx-workspace/iteration-2/multi-team-creation-refactored/with_skill/timing.json +5 -0
  61. package/skills/tfx-workspace/iteration-2/review.html +1325 -0
  62. package/skills/tfx-workspace/skill-snapshot/tfx-auto/SKILL.md +217 -0
  63. package/skills/tfx-workspace/skill-snapshot/tfx-auto-codex/SKILL.md +77 -0
  64. package/skills/tfx-workspace/skill-snapshot/tfx-codex/SKILL.md +65 -0
  65. package/skills/tfx-workspace/skill-snapshot/tfx-doctor/SKILL.md +94 -0
  66. package/skills/tfx-workspace/skill-snapshot/tfx-gemini/SKILL.md +82 -0
  67. package/skills/tfx-workspace/skill-snapshot/tfx-hub/SKILL.md +133 -0
  68. package/skills/tfx-workspace/skill-snapshot/tfx-multi/SKILL.md +426 -0
  69. package/skills/tfx-workspace/skill-snapshot/tfx-setup/SKILL.md +101 -0
  70. package/.claude-plugin/marketplace.json +0 -34
  71. package/.claude-plugin/plugin.json +0 -22
  72. package/config/mcp-registry.json +0 -29
  73. package/tui/codex-profile.mjs +0 -457
  74. package/tui/core.mjs +0 -266
  75. package/tui/doctor.mjs +0 -375
  76. package/tui/gemini-profile.mjs +0 -299
  77. package/tui/monitor-data.mjs +0 -152
  78. package/tui/monitor.mjs +0 -339
  79. package/tui/setup.mjs +0 -598
package/CLAUDE.md ADDED
@@ -0,0 +1,212 @@
1
+ <!-- prompt-hygiene:ignore line_count_warning -->
2
+ # triflux — Claude Code 운영 가이드
3
+
4
+ <core-systems>
5
+ ## 핵심 스킬 시스템 (항상 인지)
6
+
7
+ 이 프로젝트는 3개의 스킬 시스템을 동시에 사용한다. 어떤 작업이든 해당 시스템의 스킬이 있는지 먼저 확인한다.
8
+
9
+ | 시스템 | 접두사 | 용도 | 스킬 수 |
10
+ |--------|--------|------|---------|
11
+ | **triflux** | `/tfx-*` | CLI 라우팅, 멀티모델 오케스트레이션, 스웜, 원격 실행 | ~40개 |
12
+ | **gstack** | `/` (접두사 없음) | QA, ship, investigate, design, review, checkpoint | ~35개 |
13
+ | **omc** | `/oh-my-claudecode:*` | autopilot, ralph, team, ultrawork, ccg | ~25개 |
14
+
15
+ 스킬을 모르면 자연어 라우팅(아래)으로 자동 매핑된다.
16
+ 세션 종료 전 메모리 파일이 3개+ 변경됐으면 `/memory-hygiene` 제안을 검토한다.
17
+ </core-systems>
18
+
19
+ <psmux-wt>
20
+ ## psmux/WT 규칙
21
+
22
+ psmux 세션·WT 패인을 생성/조작/정리할 때 `tfx-psmux-rules` 스킬을 참조한다.
23
+ WT 프리징 방지: exit → sleep 2 → kill 순서. 바로 kill하지 않는다.
24
+
25
+ ### wt.exe → wt-manager 경유
26
+
27
+ safety-guard가 `wt.exe`, `wt new-tab`, `wt split-pane`, `Start-Process wt`를 차단한다.
28
+ `hub/team/wt-manager.mjs`의 API를 사용한다.
29
+
30
+ | 용도 | API |
31
+ |------|-----|
32
+ | 새 탭 | `createTab({ title, command, profile, cwd })` |
33
+ | 패인 분할 | `splitPane({ direction: 'H'\|'V', title, command })` |
34
+ | 다중 배치 | `applySplitLayout([{ title, command, direction }])` |
35
+ | 탭 정리 | `closeTab(title)` / `closeStale({ olderThanMs, titlePattern })` |
36
+
37
+ 차단과 대안은 항상 쌍으로 존재해야 한다. 차단만 추가하고 대안을 안 만들면 데드락.
38
+
39
+ ### psmux에서 Codex 실행
40
+
41
+ | 방식 | 동작 | 이유 |
42
+ |------|------|------|
43
+ | `codex` (interactive) | 불가 | psmux에서 TTY를 못 잡음 |
44
+ | `codex < prompt.md` | 불가 | "stdin is not a terminal" |
45
+ | `codex exec "$(cat prompt.md)" -s danger-full-access --dangerously-bypass-approvals-and-sandbox` | 사용 | 유일한 안전 경로 |
46
+
47
+ `codex exec`는 config.toml `approval_mode`를 무시하므로 `--dangerously-bypass-approvals-and-sandbox` 필수.
48
+ `-s` 유효값: read-only, workspace-write, danger-full-access.
49
+ </psmux-wt>
50
+
51
+ <codex-config>
52
+ ## Codex config.toml
53
+
54
+ config.toml에 이미 설정된 값은 CLI 플래그로 중복 지정하지 않는다.
55
+
56
+ | config.toml에 있으면 | CLI에서 생략 |
57
+ |---------------------|-------------|
58
+ | `sandbox = "elevated"` | `--full-auto` |
59
+ | `approval_mode = "full-auto"` | `--full-auto` |
60
+
61
+ 안전 패턴: config.toml에 기본값을 두고, CLI에서는 `--profile` 선택만 한다.
62
+ </codex-config>
63
+
64
+ <account-broker>
65
+ ## AccountBroker (계정 브로커)
66
+
67
+ conductor, headless, swarm-hypervisor가 하나의 AccountBroker 싱글턴을 공유한다.
68
+
69
+ | 항목 | 설명 |
70
+ |------|------|
71
+ | 계정별 CircuitBreaker | 장애 격리 — 한 계정 오류가 다른 계정에 전파되지 않음 |
72
+ | busy 플래그 | 동일 계정 이중 임대(double-lease) 방지 |
73
+ | `/broker/reload` | 장시간 세션 중 accounts.json 핫리로드 |
74
+ | EventEmitter 이벤트 | `lease`, `release`, `cooldown`, `tierFallback`, `circuitOpen`, `circuitClose`, `noAvailableAccounts` — HUD 연동용 |
75
+ </account-broker>
76
+
77
+ <remote>
78
+ ## 원격 실행
79
+
80
+ ### 스킬 구분
81
+
82
+ | 스킬 | 대상 | 방식 |
83
+ |------|------|------|
84
+ | tfx-codex-swarm | 로컬 전용 | 로컬 worktree + psmux |
85
+ | tfx-remote-spawn | Claude Code 원격 | SSH → Claude Code 세션 → 내부 tfx 라우팅 |
86
+
87
+ codex를 SSH 너머로 직접 실행하지 않는다. config.toml 충돌 + TTY 문제.
88
+ 원격에서 codex가 필요하면: remote-spawn → Claude Code → Claude가 내부에서 codex 호출.
89
+
90
+ ### SSH 패턴
91
+
92
+ hosts.json `os` 필드로 대상 셸을 판단한다. safety-guard도 이 필드를 참조.
93
+
94
+ | 대상 OS | 셸 | 패턴 |
95
+ |---------|-----|------|
96
+ | windows | PowerShell | scp + `pwsh -File` 필수. `$var` → `$env:VAR`, `2>/dev/null` → `2>$null` |
97
+ | darwin | zsh | 인라인 가능. brew PATH 주의 (`/opt/homebrew/bin`) |
98
+ | linux | bash | 인라인 가능. 표준 POSIX |
99
+
100
+ - `~` → `$HOME` 변환은 모든 OS 공통
101
+ </remote>
102
+
103
+ <headless-retrieval>
104
+ ## Headless 결과 회수
105
+
106
+ background로 실행한 headless 결과는 **반드시 task-notification 완료 후** 읽는다.
107
+
108
+ | 패턴 | 올바름 | 이유 |
109
+ |------|--------|------|
110
+ | task-notification 후 output 파일 읽기 | YES | 프로세스 종료 = 워커 전부 완료 |
111
+ | task-notification 전 output 파일 tail | NO | 시작 메시지만 보이고 "실패"로 오진 |
112
+ | psmux capture-pane으로 중간 체크 | NO | 워커 진행 중이면 빈 화면일 수 있음 |
113
+
114
+ 완료 마커: `=== HEADLESS_COMPLETE succeeded=N failed=N total=N ===`
115
+ 워커 상세: `$TMPDIR/tfx-headless/{sessionName}-worker-N.txt`
116
+ </headless-retrieval>
117
+
118
+ <cross-review>
119
+ ## 교차 검증
120
+
121
+ - Claude 작성 코드 → Codex 리뷰
122
+ - Codex 작성 코드 → Claude 리뷰
123
+ - 동일 모델 self-approve 하지 않는다
124
+ - git commit 전 미검증 파일 감지 시 nudge
125
+ </cross-review>
126
+
127
+ <session-context>
128
+ ## 맥락 이탈 판단
129
+
130
+ 현재 세션 맥락과 무관한 요청이 감지되면 psmux 격리를 제안한다.
131
+
132
+ | 확신도 | 신호 | 행동 |
133
+ |--------|------|------|
134
+ | 확실 | "새 탭", "별도로", "새 세션" | 바로 psmux spawn |
135
+ | 높음 | 다른 프로젝트/스택 언급 | 분리 제안 |
136
+ | 중간 | 작업 유형 전환 | 분리 제안 + 현재 세션 옵션 |
137
+ | 낮음 | 현재 작업 연장 | 세션 유지 |
138
+ </session-context>
139
+
140
+ <routing>
141
+ ## 자연어 → 스킬 라우팅
142
+
143
+ 사용자가 스킬명을 모르더라도 자연어로 요청하면 아래 규칙에 따라 적절한 스킬을 호출한다.
144
+
145
+ ### 행동 유형 → 스킬 매핑
146
+
147
+ | 의도 | 자연어 신호 | 스킬 |
148
+ |------|-----------|------|
149
+ | 구현/수정 | 만들어, 고쳐, 구현해, 짜줘, 수정해, 바꿔 | tfx-auto |
150
+ | 리뷰 | 봐줘, 리뷰해, 검토해, 괜찮아? | tfx-review |
151
+ | 분석 | 분석해, 어떻게 돌아가?, 구조가 뭐야 | tfx-analysis |
152
+ | 계획 | 계획, 어떻게 하지, 설계해 | tfx-plan |
153
+ | 검색 | 찾아, 어디있어, 파일 찾아 | tfx-find |
154
+ | 리서치 (빠른) | 검색해줘, 찾아봐, 공식문서, 이거 뭐야 | tfx-research |
155
+ | 리서치 (자율) | 자율 리서치, 검색하고 정리해, research and plan | tfx-autoresearch |
156
+ | 테스트 | 테스트, 검증, 돌려봐, QA | tfx-qa |
157
+ | 정리 | 정리해, 슬롭 제거, 클린업 | tfx-prune |
158
+ | 토론 | 뭐가 나을까, 비교해, A vs B | tfx-debate |
159
+
160
+ ### 깊이 수정자
161
+
162
+ | 수정자 | 신호 | 효과 |
163
+ |--------|------|------|
164
+ | 기본 | (없음), 빠르게, 간단히 | Light 스킬 |
165
+ | 깊이 | 제대로, 꼼꼼히, 철저히 | Deep 스킬 (tfx-deep-*). 예외: tfx-deep-interview는 Gemini 단독 |
166
+ | 합의 | 3자, 교차, 다각도 | consensus 프로토콜 |
167
+ | 반복 | 끝까지, 멈추지마, ralph | persist 모드 |
168
+ | 자율 | 알아서, 자동으로, autopilot | autopilot 모드 |
169
+
170
+ ### CLI 라우팅
171
+
172
+ headless-guard가 `codex exec` / `gemini -y -p` 직접 호출을 차단한다. tfx 스킬 경유 필수.
173
+
174
+ **Layer 1 — Light** (tfx-route.sh → 단일 CLI)
175
+
176
+ | 스킬 | CLI | 용도 |
177
+ |------|-----|------|
178
+ | tfx-auto | 자동 | 통합 진입점 |
179
+ | tfx-codex | Codex | Codex 전용 |
180
+ | tfx-gemini | Gemini | Gemini 전용 |
181
+ | tfx-autopilot | Codex→검증 | 단일 파일, 5분 이내 |
182
+ | tfx-autoroute | 자동 승격 | 실패→더 강한 모델 |
183
+
184
+ **Layer 2 — Deep** (headless 3-CLI 합의)
185
+
186
+ tfx-deep-review, tfx-deep-qa, tfx-deep-plan, tfx-deep-research, tfx-consensus, tfx-debate, tfx-panel, tfx-fullcycle, tfx-persist
187
+
188
+ **Layer 3 — Remote/병렬**
189
+
190
+ | 스킬 | 용도 |
191
+ |------|------|
192
+ | tfx-multi | 2+개 태스크 headless 병렬 |
193
+ | tfx-swarm | PRD별 worktree + 다중 모델(Codex/Gemini/Claude) + 다중 기기(로컬+원격) |
194
+ | tfx-remote-spawn | Claude Code 원격 세션 (SSH, setup 필수) |
195
+
196
+ **Claude 네이티브** (CLI 불필요): tfx-find, tfx-forge, tfx-prune, tfx-index, tfx-setup, tfx-doctor, tfx-hooks, tfx-hub
197
+
198
+ 자원 우선순위: remote-spawn > swarm > multi > Light > 로컬 단독
199
+
200
+ ### 충돌 해소
201
+
202
+ - ralph = persist alias
203
+ - "auto" 단독 → tfx-auto. "알아서 해" → tfx-autopilot
204
+ - "코드에서 찾아" → tfx-find. "알아봐" → tfx-research
205
+ - 복합 의도: "구현하고 리뷰까지" → tfx-auto → cross-review hook
206
+
207
+ ### Q-Learning 동적 라우팅 (실험적)
208
+
209
+ - `TRIFLUX_DYNAMIC_ROUTING=true` 또는 `1` 설정 시 Q-Learning 기반 동적 스킬 라우팅 활성화
210
+ - `routing-weights.json` + Q-table로 스킬 선택 최적화
211
+ - 기본 비활성
212
+ </routing>
@@ -354,6 +354,13 @@ class AccountBroker extends EventEmitter {
354
354
  if (isHalfOpen) {
355
355
  this.emit("circuitClose", { id: accountId });
356
356
  }
357
+ } else if (result?.skipCircuit) {
358
+ // 인프라 에러 — circuit/cooldown에 카운트하지 않음
359
+ circuitUpdate = {
360
+ failureTimestamps: acct.failureTimestamps,
361
+ circuitOpenedAt: acct.circuitOpenedAt,
362
+ circuitTrialInFlight: acct.circuitTrialInFlight,
363
+ };
357
364
  } else {
358
365
  circuitUpdate = this.#recordCircuitFailure(acct, isHalfOpen, now);
359
366
  if (circuitUpdate.circuitOpenedAt !== acct.circuitOpenedAt) {
@@ -282,6 +282,9 @@ export async function executeWithCircuitBroker({
282
282
  const coolMs = parseRetryAfterMs(text, provider);
283
283
  brokerMod.broker.markRateLimited(lease.id, coolMs);
284
284
  brokerMod.broker.emit("cooldown", { id: lease.id, provider, coolMs, reason: "quota_exhausted" });
285
+ } else if (lastResult.failureMode === "crash") {
286
+ // 인프라 에러(모듈 누락, 서버 에러 등)는 계정 문제가 아님 → circuit/cooldown 건너뜀
287
+ brokerMod.broker.release(lease.id, { ok: false, skipCircuit: true });
285
288
  } else {
286
289
  brokerMod.broker.release(lease.id, { ok: false });
287
290
  }
package/hub/server.mjs CHANGED
@@ -719,6 +719,16 @@ export async function startHub({
719
719
  return;
720
720
  }
721
721
 
722
+ if (path === "/broker/quota-refresh" && (req.method === "POST" || req.method === "GET")) {
723
+ try {
724
+ const results = await refreshAllAccountQuotas();
725
+ return writeJson(res, 200, { ok: true, results, ts: Date.now() });
726
+ } catch (err) {
727
+ hubLog.error({ err: String(err?.message || err) }, "broker.quota_refresh_error");
728
+ return writeJson(res, 200, { ok: false, error: String(err?.message || err) });
729
+ }
730
+ }
731
+
722
732
  if (path === "/broker/reload" && req.method === "POST") {
723
733
  const result = reloadBroker();
724
734
  if (!result.ok) {
@@ -1667,17 +1677,70 @@ function cleanupStaleSpawnSessions(log) {
1667
1677
  return killed;
1668
1678
  }
1669
1679
 
1680
+ // ── Quota check for all accounts ───────────────────────────────
1681
+
1682
+ const QUOTA_CACHE_PATH = join(CACHE_DIR, "broker-quota-cache.json");
1683
+
1684
+ async function checkSingleAccountQuota(acct) {
1685
+ const authPath = join(PID_DIR, acct.authFile);
1686
+ if (!existsSync(authPath)) return { id: acct.id, status: "no_auth" };
1687
+ try {
1688
+ const auth = JSON.parse(readFileSync(authPath, "utf8"));
1689
+ if (acct.provider === "codex") {
1690
+ const token = auth.tokens?.access_token || auth.OPENAI_API_KEY || "";
1691
+ if (!token) return { id: acct.id, status: "no_token" };
1692
+ const r = await fetch("https://api.openai.com/v1/chat/completions", {
1693
+ method: "POST", signal: AbortSignal.timeout(8000),
1694
+ headers: { Authorization: "Bearer " + token, "Content-Type": "application/json" },
1695
+ body: JSON.stringify({ model: "gpt-4.1-nano", messages: [{ role: "user", content: "hi" }], max_tokens: 1 }),
1696
+ });
1697
+ const hdrs = Object.fromEntries([...r.headers.entries()].filter(([k]) => /ratelimit/i.test(k)));
1698
+ if (r.status === 429) return { id: acct.id, status: "quota_hit", http: 429, headers: hdrs };
1699
+ if (r.status === 401) {
1700
+ // 401이어도 ratelimit 헤더가 있으면 쿼터 정보 추출 가능
1701
+ return { id: acct.id, status: "auth_error", http: 401, headers: hdrs };
1702
+ }
1703
+ return { id: acct.id, status: r.ok ? "ok" : "error", http: r.status, headers: hdrs };
1704
+ }
1705
+ // gemini — OAuth token refresh needed for accurate check
1706
+ return { id: acct.id, status: "oauth_check_needed" };
1707
+ } catch (e) {
1708
+ return { id: acct.id, status: "error", message: e.message?.substring(0, 60) };
1709
+ }
1710
+ }
1711
+
1712
+ async function refreshAllAccountQuotas() {
1713
+ const snap = brokerInstance?.snapshot() || [];
1714
+ const checks = snap.filter(a => a.authFile).map(a => checkSingleAccountQuota(a));
1715
+ const results = await Promise.all(checks);
1716
+ // 캐시 저장
1717
+ try {
1718
+ writeFileSync(QUOTA_CACHE_PATH, JSON.stringify({ ts: Date.now(), results }));
1719
+ } catch { /* best-effort */ }
1720
+ return results;
1721
+ }
1722
+
1723
+ function loadQuotaCache() {
1724
+ try {
1725
+ if (!existsSync(QUOTA_CACHE_PATH)) return null;
1726
+ return JSON.parse(readFileSync(QUOTA_CACHE_PATH, "utf8"));
1727
+ } catch { return null; }
1728
+ }
1729
+
1670
1730
  // ── Broker Dashboard HTML ──────────────────────────────────────
1671
1731
 
1672
1732
  function renderBrokerDashboard() {
1673
1733
  return `<!DOCTYPE html><html lang="ko"><head><meta charset="utf-8">
1674
1734
  <title>Account Broker Dashboard</title>
1675
- <meta http-equiv="refresh" content="30">
1676
1735
  <style>
1677
1736
  *{margin:0;padding:0;box-sizing:border-box}
1678
1737
  body{background:#0a0a0b;color:#e8e8ec;font:14px/1.6 'SF Mono',Consolas,monospace;padding:24px}
1679
- h1{font-size:18px;color:#a8b1ff;margin-bottom:16px}
1680
- .grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(340px,1fr));gap:12px}
1738
+ h1{font-size:18px;color:#a8b1ff;margin-bottom:8px}
1739
+ .toolbar{margin-bottom:16px;display:flex;gap:8px;align-items:center}
1740
+ .toolbar button{background:#1a1a2e;color:#a8b1ff;border:1px solid rgba(255,255,255,0.1);border-radius:4px;padding:4px 12px;cursor:pointer;font:12px inherit}
1741
+ .toolbar button:hover{background:#252547}
1742
+ .toolbar .status-text{font-size:11px;color:#555}
1743
+ .grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(380px,1fr));gap:12px}
1681
1744
  .card{background:#141416;border:1px solid rgba(255,255,255,0.06);border-radius:8px;padding:16px}
1682
1745
  .card.available{border-left:3px solid #34d399}
1683
1746
  .card.busy{border-left:3px solid #fbbf24}
@@ -1690,16 +1753,75 @@ h1{font-size:18px;color:#a8b1ff;margin-bottom:16px}
1690
1753
  .status.busy{background:#451a03;color:#fbbf24}
1691
1754
  .status.cooldown{background:#450a0a;color:#f87171}
1692
1755
  .status.circuit-open{background:#450a0a;color:#ef4444}
1693
- .meta{margin-top:8px;font-size:11px;color:#666;line-height:1.8}
1756
+ .gauge{margin-top:8px}
1757
+ .gauge-row{display:flex;align-items:center;gap:8px;margin:3px 0}
1758
+ .gauge-label{font-size:10px;color:#888;width:28px;text-align:right}
1759
+ .gauge-bar{flex:1;height:8px;background:#1a1a1e;border-radius:4px;overflow:hidden}
1760
+ .gauge-fill{height:100%;border-radius:4px;transition:width .3s}
1761
+ .gauge-fill.green{background:linear-gradient(90deg,#34d399,#059669)}
1762
+ .gauge-fill.yellow{background:linear-gradient(90deg,#fbbf24,#d97706)}
1763
+ .gauge-fill.red{background:linear-gradient(90deg,#f87171,#dc2626)}
1764
+ .gauge-pct{font-size:10px;color:#999;width:32px}
1765
+ .gauge-reset{font-size:9px;color:#555}
1766
+ .meta{margin-top:6px;font-size:11px;color:#666;line-height:1.8}
1694
1767
  .meta b{color:#999}
1695
1768
  .timer{color:#f87171;font-weight:600}
1696
- .refresh{color:#555;font-size:11px;margin-top:16px}
1769
+ .refresh-bar{color:#555;font-size:11px;margin-top:16px}
1697
1770
  </style></head><body>
1698
- <h1>🔑 Account Broker Dashboard</h1>
1771
+ <h1>Account Broker Dashboard</h1>
1772
+ <div class="toolbar">
1773
+ <button onclick="checkQuotas()">Check All Quotas</button>
1774
+ <button onclick="reloadBroker()">Reload Broker</button>
1775
+ <span id="toolbar-status" class="status-text"></span>
1776
+ </div>
1699
1777
  <div id="grid" class="grid"></div>
1700
- <p class="refresh">auto-refresh: 10s | <a href="/broker/snapshot" style="color:#666">JSON API</a></p>
1778
+ <p class="refresh-bar">auto-refresh: 10s | <a href="/broker/snapshot" style="color:#666">JSON</a> | <a href="/broker/quota-refresh" style="color:#666">Quota API</a></p>
1701
1779
  <script>
1780
+ let quotaData={};
1702
1781
  function fmt(ms){if(ms<=0)return'-';const s=Math.floor(ms/1000),m=Math.floor(s/60),h=Math.floor(m/60),d=Math.floor(h/24);if(d>0)return d+'d '+h%24+'h';if(h>0)return h+'h '+m%60+'m';if(m>0)return m+'m '+s%60+'s';return s+'s'}
1782
+
1783
+ function gaugeColor(pct){return pct<60?'green':pct<85?'yellow':'red'}
1784
+
1785
+ function renderGauge(label,pct,resetTs){
1786
+ if(pct==null)return '';
1787
+ const now=Date.now()/1000;
1788
+ const resetIn=resetTs>now?fmt((resetTs-now)*1000):'';
1789
+ return '<div class="gauge-row"><span class="gauge-label">'+label+'</span>'+
1790
+ '<div class="gauge-bar"><div class="gauge-fill '+gaugeColor(pct)+'" style="width:'+pct+'%"></div></div>'+
1791
+ '<span class="gauge-pct">'+pct+'%</span>'+
1792
+ (resetIn?'<span class="gauge-reset">reset '+resetIn+'</span>':'')+
1793
+ '</div>';
1794
+ }
1795
+
1796
+ function renderQuotaGauges(acctId){
1797
+ const q=quotaData[acctId];
1798
+ if(!q)return '<div class="gauge"><div class="gauge-row"><span style="font-size:10px;color:#444">quota: click Check All Quotas</span></div></div>';
1799
+ if(q.status==='quota_hit')return '<div class="gauge"><div class="gauge-row"><span style="font-size:10px;color:#f87171">QUOTA EXHAUSTED</span></div></div>';
1800
+ if(q.status==='auth_error'||q.status==='no_token'||q.status==='oauth_check_needed'){
1801
+ // 401이어도 ratelimit 헤더가 있으면 표시
1802
+ const h=q.headers||{};
1803
+ const limReq=h['x-ratelimit-limit-requests'],remReq=h['x-ratelimit-remaining-requests'];
1804
+ const limTok=h['x-ratelimit-limit-tokens'],remTok=h['x-ratelimit-remaining-tokens'];
1805
+ if(limReq){
1806
+ const pctReq=Math.round((1-remReq/limReq)*100);
1807
+ const pctTok=limTok?Math.round((1-remTok/limTok)*100):null;
1808
+ return '<div class="gauge">'+renderGauge('req',pctReq,0)+(pctTok!=null?renderGauge('tok',pctTok,0):'')+'</div>';
1809
+ }
1810
+ return '<div class="gauge"><div class="gauge-row"><span style="font-size:10px;color:#fbbf24">'+(q.status==='oauth_check_needed'?'OAuth refresh needed':'auth: token refresh needed')+'</span></div></div>';
1811
+ }
1812
+ if(q.status==='ok'||q.status==='error'){
1813
+ const h=q.headers||{};
1814
+ const limReq=h['x-ratelimit-limit-requests'],remReq=h['x-ratelimit-remaining-requests'];
1815
+ const limTok=h['x-ratelimit-limit-tokens'],remTok=h['x-ratelimit-remaining-tokens'];
1816
+ const resetReq=h['x-ratelimit-reset-requests'],resetTok=h['x-ratelimit-reset-tokens'];
1817
+ if(!limReq)return '';
1818
+ const pctReq=Math.round((1-remReq/limReq)*100);
1819
+ const pctTok=limTok?Math.round((1-remTok/limTok)*100):null;
1820
+ return '<div class="gauge">'+renderGauge('req',pctReq,0)+(pctTok!=null?renderGauge('tok',pctTok,0):'')+'</div>';
1821
+ }
1822
+ return '';
1823
+ }
1824
+
1703
1825
  async function refresh(){
1704
1826
  try{
1705
1827
  const r=await fetch('/broker/snapshot');
@@ -1719,6 +1841,7 @@ async function refresh(){
1719
1841
  '<div class="id">'+a.id+'</div>'+
1720
1842
  '<span class="status '+st+'">'+sl+'</span>'+
1721
1843
  (cd>0?'<span class="timer" style="margin-left:8px">'+fmt(cd)+' remaining</span>':'')+
1844
+ renderQuotaGauges(a.id)+
1722
1845
  '<div class="meta">'+
1723
1846
  '<b>Sessions:</b> '+a.totalSessions+
1724
1847
  (a.lastUsedAt?' | <b>Last:</b> '+new Date(a.lastUsedAt).toLocaleTimeString():'')+
@@ -1728,6 +1851,29 @@ async function refresh(){
1728
1851
  }).join('');
1729
1852
  }catch(e){console.error('refresh failed',e)}
1730
1853
  }
1854
+
1855
+ async function checkQuotas(){
1856
+ const el=document.getElementById('toolbar-status');
1857
+ el.textContent='checking quotas...';
1858
+ try{
1859
+ const r=await fetch('/broker/quota-refresh',{method:'POST'});
1860
+ const d=await r.json();
1861
+ if(d.ok){
1862
+ d.results.forEach(q=>{quotaData[q.id]=q});
1863
+ el.textContent='updated '+d.results.length+' accounts ('+new Date().toLocaleTimeString()+')';
1864
+ refresh();
1865
+ }else{el.textContent='error';}
1866
+ }catch(e){el.textContent='failed: '+e.message;}
1867
+ }
1868
+
1869
+ async function reloadBroker(){
1870
+ await fetch('/broker/reload',{method:'POST'});
1871
+ document.getElementById('toolbar-status').textContent='broker reloaded';
1872
+ refresh();
1873
+ }
1874
+
1875
+ // 캐시에서 초기 로드
1876
+ fetch('/broker/quota-refresh').catch(()=>{});
1731
1877
  refresh();setInterval(refresh,10000);
1732
1878
  </script></body></html>`;
1733
1879
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "triflux",
3
- "version": "10.9.10",
3
+ "version": "10.9.11",
4
4
  "description": "CLI-first multi-model orchestrator for Claude Code — route tasks to Codex, Gemini, and Claude",
5
5
  "type": "module",
6
6
  "bin": {
@@ -13,69 +13,26 @@
13
13
  "tfx-doctor-tui": "bin/tfx-doctor-tui.mjs",
14
14
  "tfx-setup-tui": "bin/tfx-setup-tui.mjs"
15
15
  },
16
+ "engines": {
17
+ "node": ">=18.0.0"
18
+ },
19
+ "dependencies": {
20
+ "@triflux/core": "10.0.1",
21
+ "@triflux/remote": "^10.0.0-alpha.1"
22
+ },
16
23
  "files": [
17
24
  "bin",
18
- "tui",
19
- "hub",
20
- "config",
21
25
  "skills",
22
- "!skills/tfx-workspace",
23
- "!**/failure-reports",
24
- "scripts",
25
26
  "hooks",
26
27
  "hud",
28
+ "scripts",
29
+ "hub",
27
30
  "mesh",
28
- ".claude-plugin",
31
+ "references",
32
+ "CLAUDE.md",
29
33
  "README.md",
30
- "README.ko.md",
31
34
  "LICENSE"
32
35
  ],
33
- "workspaces": [
34
- "packages/core",
35
- "packages/remote",
36
- "packages/triflux"
37
- ],
38
- "scripts": {
39
- "pack": "node scripts/pack.mjs all",
40
- "pack:core": "node scripts/pack.mjs core",
41
- "pack:remote": "node scripts/pack.mjs remote",
42
- "setup": "node scripts/setup.mjs",
43
- "preinstall": "node scripts/preinstall.mjs",
44
- "postinstall": "node scripts/setup.mjs",
45
- "lint": "biome check .",
46
- "lint:fix": "biome check --fix .",
47
- "health": "npm test && npm run lint",
48
- "test": "node scripts/test-lock.mjs --test --test-force-exit --test-concurrency=8 \"tests/**/*.test.mjs\" \"scripts/__tests__/**/*.test.mjs\"",
49
- "test:unit": "node scripts/test-lock.mjs --test --test-force-exit --test-concurrency=8 tests/unit/**/*.test.mjs",
50
- "test:integration": "node scripts/test-lock.mjs --test --test-force-exit --test-concurrency=8 tests/integration/**/*.test.mjs",
51
- "test:route-smoke": "node scripts/test-lock.mjs --test scripts/test-tfx-route-no-claude-native.mjs",
52
- "test:contract": "node scripts/test-lock.mjs --test --test-force-exit --test-concurrency=8 tests/contract/**/*.test.mjs",
53
- "test:coverage": "node --experimental-test-coverage --test-coverage-lines=60 --test-coverage-functions=60 --test --test-force-exit --test-concurrency=8 \"tests/**/*.test.mjs\"",
54
- "gen:skill-docs": "node scripts/gen-skill-docs.mjs",
55
- "gen:skill-manifest": "node scripts/gen-skill-manifest.mjs"
56
- },
57
- "engines": {
58
- "node": ">=18.0.0"
59
- },
60
- "repository": {
61
- "type": "git",
62
- "url": "git+https://github.com/tellang/triflux.git"
63
- },
64
- "homepage": "https://github.com/tellang/triflux#readme",
65
- "author": "tellang",
66
- "license": "MIT",
67
- "dependencies": {
68
- "@modelcontextprotocol/sdk": "^1.27.1",
69
- "better-sqlite3": "^12.6.2",
70
- "pino": "^10.3.1",
71
- "pino-pretty": "^13.1.3",
72
- "systray2": "^2.1.4",
73
- "zod": "^4.0.0"
74
- },
75
- "devDependencies": {
76
- "@biomejs/biome": "^2.0.0",
77
- "knip": "^6.3.0"
78
- },
79
36
  "keywords": [
80
37
  "claude-code",
81
38
  "plugin",
@@ -86,5 +43,13 @@
86
43
  "multi-model",
87
44
  "triflux",
88
45
  "tfx"
89
- ]
46
+ ],
47
+ "author": "tellang",
48
+ "license": "MIT",
49
+ "homepage": "https://github.com/tellang/triflux#readme",
50
+ "repository": {
51
+ "type": "git",
52
+ "url": "git+https://github.com/tellang/triflux.git",
53
+ "directory": "packages/triflux"
54
+ }
90
55
  }
@@ -0,0 +1,46 @@
1
+ {
2
+ "hosts": {
3
+ "ultra4": {
4
+ "description": "Windows 데스크탑 (22코어/64GB RAM)",
5
+ "aliases": ["울트라", "울트라4", "데스크탑"],
6
+ "default_dir": "~/Desktop/Projects/cli/triflux",
7
+ "tailscale": {
8
+ "ip": "100.110.136.64",
9
+ "dns": "ultra-book-4-1",
10
+ "ssh_mode": "ssh-over-vpn"
11
+ },
12
+ "ssh_user": "SSAFY",
13
+ "os": "windows",
14
+ "specs": {
15
+ "cores": 22,
16
+ "ram_gb": 64,
17
+ "codex": "0.118.0",
18
+ "node": "24.14.0"
19
+ },
20
+ "capabilities": ["codex", "claude", "high-memory"]
21
+ },
22
+ "m2": {
23
+ "description": "MacBook Air M2 (8코어/16GB RAM)",
24
+ "aliases": ["맥", "맥북", "m2"],
25
+ "default_dir": "~/Desktop/Projects/triflux",
26
+ "tailscale": {
27
+ "ip": "100.104.61.126",
28
+ "dns": "tellang의-macbook-air",
29
+ "ssh_mode": "ssh-over-vpn"
30
+ },
31
+ "ssh_user": "tellang",
32
+ "os": "darwin",
33
+ "specs": {
34
+ "cores": 8,
35
+ "ram_gb": 16,
36
+ "claude": "2.1.89",
37
+ "codex": "0.114.0",
38
+ "gemini": "0.33.1",
39
+ "node": "25.9.0"
40
+ },
41
+ "capabilities": ["codex", "claude", "gemini"]
42
+ }
43
+ },
44
+ "default_host": "m2",
45
+ "triggers": ["원격에서", "다른 머신에서", "다른 컴퓨터에서"]
46
+ }