@su-record/vibe 2.7.12 → 2.7.14

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 (331) hide show
  1. package/.env.example +37 -37
  2. package/CLAUDE.md +126 -126
  3. package/LICENSE +21 -21
  4. package/README.md +449 -580
  5. package/agents/architect-low.md +41 -41
  6. package/agents/architect-medium.md +59 -59
  7. package/agents/architect.md +80 -80
  8. package/agents/build-error-resolver.md +115 -115
  9. package/agents/compounder.md +261 -261
  10. package/agents/diagrammer.md +178 -178
  11. package/agents/docs/api-documenter.md +99 -99
  12. package/agents/docs/changelog-writer.md +93 -93
  13. package/agents/e2e-tester.md +294 -266
  14. package/agents/explorer-low.md +42 -42
  15. package/agents/explorer-medium.md +59 -59
  16. package/agents/explorer.md +48 -48
  17. package/agents/implementer-low.md +43 -43
  18. package/agents/implementer-medium.md +52 -52
  19. package/agents/implementer.md +54 -54
  20. package/agents/junior-mentor.md +141 -141
  21. package/agents/planning/requirements-analyst.md +84 -84
  22. package/agents/planning/ux-advisor.md +83 -83
  23. package/agents/qa/acceptance-tester.md +86 -86
  24. package/agents/qa/edge-case-finder.md +93 -93
  25. package/agents/refactor-cleaner.md +143 -143
  26. package/agents/research/best-practices-agent.md +199 -199
  27. package/agents/research/codebase-patterns-agent.md +157 -157
  28. package/agents/research/framework-docs-agent.md +188 -188
  29. package/agents/research/security-advisory-agent.md +213 -213
  30. package/agents/review/architecture-reviewer.md +107 -107
  31. package/agents/review/complexity-reviewer.md +116 -116
  32. package/agents/review/data-integrity-reviewer.md +88 -88
  33. package/agents/review/git-history-reviewer.md +103 -103
  34. package/agents/review/performance-reviewer.md +86 -86
  35. package/agents/review/python-reviewer.md +150 -150
  36. package/agents/review/rails-reviewer.md +139 -139
  37. package/agents/review/react-reviewer.md +144 -144
  38. package/agents/review/security-reviewer.md +80 -80
  39. package/agents/review/simplicity-reviewer.md +140 -140
  40. package/agents/review/test-coverage-reviewer.md +116 -116
  41. package/agents/review/typescript-reviewer.md +127 -127
  42. package/agents/searcher.md +54 -54
  43. package/agents/simplifier.md +120 -120
  44. package/agents/tester.md +49 -49
  45. package/agents/ui/ui-a11y-auditor.md +93 -93
  46. package/agents/ui/ui-antipattern-detector.md +94 -94
  47. package/agents/ui/ui-dataviz-advisor.md +69 -69
  48. package/agents/ui/ui-design-system-gen.md +57 -57
  49. package/agents/ui/ui-industry-analyzer.md +49 -49
  50. package/agents/ui/ui-layout-architect.md +65 -65
  51. package/agents/ui/ui-stack-implementer.md +68 -68
  52. package/agents/ui/ux-compliance-reviewer.md +81 -81
  53. package/agents/ui-previewer.md +258 -260
  54. package/commands/vibe.analyze.md +8 -0
  55. package/commands/vibe.review.md +10 -3
  56. package/commands/vibe.run.md +2078 -2022
  57. package/commands/vibe.spec.md +10 -10
  58. package/commands/vibe.spec.review.md +565 -558
  59. package/commands/vibe.utils.md +413 -413
  60. package/commands/vibe.verify.md +45 -0
  61. package/dist/cli/auth.d.ts.map +1 -1
  62. package/dist/cli/auth.js +1 -7
  63. package/dist/cli/auth.js.map +1 -1
  64. package/dist/cli/collaborator.js +52 -52
  65. package/dist/cli/commands/evolution.js +12 -12
  66. package/dist/cli/commands/info.d.ts.map +1 -1
  67. package/dist/cli/commands/info.js +55 -70
  68. package/dist/cli/commands/info.js.map +1 -1
  69. package/dist/cli/commands/init.d.ts.map +1 -1
  70. package/dist/cli/commands/init.js +6 -7
  71. package/dist/cli/commands/init.js.map +1 -1
  72. package/dist/cli/commands/remove.js +14 -14
  73. package/dist/cli/commands/sentinel.js +27 -27
  74. package/dist/cli/commands/setup.js +1 -1
  75. package/dist/cli/commands/setup.js.map +1 -1
  76. package/dist/cli/commands/skills.js +5 -5
  77. package/dist/cli/commands/slack.js +10 -10
  78. package/dist/cli/commands/telegram.js +12 -12
  79. package/dist/cli/commands/update.d.ts.map +1 -1
  80. package/dist/cli/commands/update.js +3 -4
  81. package/dist/cli/commands/update.js.map +1 -1
  82. package/dist/cli/detect.js +32 -32
  83. package/dist/cli/index.js +51 -55
  84. package/dist/cli/index.js.map +1 -1
  85. package/dist/cli/llm/claude-commands.js +16 -16
  86. package/dist/cli/llm/config.js +20 -20
  87. package/dist/cli/llm/config.js.map +1 -1
  88. package/dist/cli/llm/gemini-commands.d.ts +4 -6
  89. package/dist/cli/llm/gemini-commands.d.ts.map +1 -1
  90. package/dist/cli/llm/gemini-commands.js +52 -322
  91. package/dist/cli/llm/gemini-commands.js.map +1 -1
  92. package/dist/cli/llm/gpt-commands.js +21 -21
  93. package/dist/cli/llm/gpt-commands.js.map +1 -1
  94. package/dist/cli/llm/help.js +21 -21
  95. package/dist/cli/postinstall/constants.js +1 -1
  96. package/dist/cli/postinstall/constants.js.map +1 -1
  97. package/dist/cli/postinstall/cursor-agents.js +32 -32
  98. package/dist/cli/postinstall/cursor-rules.js +83 -83
  99. package/dist/cli/postinstall/cursor-skills.js +743 -743
  100. package/dist/cli/postinstall/inline-skills.js +1 -1
  101. package/dist/cli/postinstall/inline-skills.js.map +1 -1
  102. package/dist/cli/setup/Provisioner.js +42 -42
  103. package/dist/cli/types.d.ts +2 -18
  104. package/dist/cli/types.d.ts.map +1 -1
  105. package/dist/cli/utils.d.ts +0 -9
  106. package/dist/cli/utils.d.ts.map +1 -1
  107. package/dist/cli/utils.js +0 -28
  108. package/dist/cli/utils.js.map +1 -1
  109. package/dist/infra/lib/DeepInit.js +24 -24
  110. package/dist/infra/lib/IterationTracker.js +11 -11
  111. package/dist/infra/lib/PythonParser.js +108 -108
  112. package/dist/infra/lib/ReviewRace.js +96 -96
  113. package/dist/infra/lib/SkillFrontmatter.js +28 -28
  114. package/dist/infra/lib/SkillQualityGate.js +9 -9
  115. package/dist/infra/lib/SkillRepository.js +159 -159
  116. package/dist/infra/lib/UltraQA.js +99 -99
  117. package/dist/infra/lib/autonomy/AuditStore.js +41 -41
  118. package/dist/infra/lib/autonomy/ConfirmationStore.js +30 -30
  119. package/dist/infra/lib/autonomy/EventOutbox.js +38 -38
  120. package/dist/infra/lib/autonomy/PolicyEngine.js +18 -18
  121. package/dist/infra/lib/autonomy/SecuritySentinel.js +1 -1
  122. package/dist/infra/lib/autonomy/SuggestionStore.js +33 -33
  123. package/dist/infra/lib/config/GlobalConfigManager.d.ts +0 -2
  124. package/dist/infra/lib/config/GlobalConfigManager.d.ts.map +1 -1
  125. package/dist/infra/lib/config/GlobalConfigManager.js +0 -27
  126. package/dist/infra/lib/config/GlobalConfigManager.js.map +1 -1
  127. package/dist/infra/lib/embedding/VectorStore.js +22 -22
  128. package/dist/infra/lib/evolution/AgentAnalyzer.js +10 -10
  129. package/dist/infra/lib/evolution/DescriptionOptimizer.js +21 -21
  130. package/dist/infra/lib/evolution/GenerationRegistry.js +36 -36
  131. package/dist/infra/lib/evolution/InsightStore.js +90 -90
  132. package/dist/infra/lib/evolution/RollbackManager.js +5 -5
  133. package/dist/infra/lib/evolution/SkillBenchmark.js +23 -23
  134. package/dist/infra/lib/evolution/SkillEvalRunner.js +50 -50
  135. package/dist/infra/lib/evolution/SkillGapDetector.js +10 -10
  136. package/dist/infra/lib/evolution/UsageTracker.js +28 -28
  137. package/dist/infra/lib/gemini/auth.d.ts +4 -16
  138. package/dist/infra/lib/gemini/auth.d.ts.map +1 -1
  139. package/dist/infra/lib/gemini/auth.js +10 -405
  140. package/dist/infra/lib/gemini/auth.js.map +1 -1
  141. package/dist/infra/lib/gemini/capabilities.d.ts +4 -8
  142. package/dist/infra/lib/gemini/capabilities.d.ts.map +1 -1
  143. package/dist/infra/lib/gemini/capabilities.js +8 -166
  144. package/dist/infra/lib/gemini/capabilities.js.map +1 -1
  145. package/dist/infra/lib/gemini/chat.d.ts +4 -13
  146. package/dist/infra/lib/gemini/chat.d.ts.map +1 -1
  147. package/dist/infra/lib/gemini/chat.js +10 -323
  148. package/dist/infra/lib/gemini/chat.js.map +1 -1
  149. package/dist/infra/lib/gemini/completion.d.ts +5 -15
  150. package/dist/infra/lib/gemini/completion.d.ts.map +1 -1
  151. package/dist/infra/lib/gemini/completion.js +6 -97
  152. package/dist/infra/lib/gemini/completion.js.map +1 -1
  153. package/dist/infra/lib/gemini/constants.d.ts +2 -31
  154. package/dist/infra/lib/gemini/constants.d.ts.map +1 -1
  155. package/dist/infra/lib/gemini/constants.js +2 -77
  156. package/dist/infra/lib/gemini/constants.js.map +1 -1
  157. package/dist/infra/lib/gemini/index.d.ts +5 -8
  158. package/dist/infra/lib/gemini/index.d.ts.map +1 -1
  159. package/dist/infra/lib/gemini/index.js +4 -7
  160. package/dist/infra/lib/gemini/index.js.map +1 -1
  161. package/dist/infra/lib/gemini/models.d.ts +3 -4
  162. package/dist/infra/lib/gemini/models.d.ts.map +1 -1
  163. package/dist/infra/lib/gemini/models.js +8 -84
  164. package/dist/infra/lib/gemini/models.js.map +1 -1
  165. package/dist/infra/lib/gemini/orchestration.js +5 -5
  166. package/dist/infra/lib/gemini/types.d.ts +16 -44
  167. package/dist/infra/lib/gemini/types.d.ts.map +1 -1
  168. package/dist/infra/lib/gemini/types.js +1 -1
  169. package/dist/infra/lib/gpt/auth.d.ts +2 -5
  170. package/dist/infra/lib/gpt/auth.d.ts.map +1 -1
  171. package/dist/infra/lib/gpt/auth.js +8 -38
  172. package/dist/infra/lib/gpt/auth.js.map +1 -1
  173. package/dist/infra/lib/gpt/chat.d.ts +3 -3
  174. package/dist/infra/lib/gpt/chat.d.ts.map +1 -1
  175. package/dist/infra/lib/gpt/chat.js +37 -53
  176. package/dist/infra/lib/gpt/chat.js.map +1 -1
  177. package/dist/infra/lib/gpt/constants.d.ts +2 -5
  178. package/dist/infra/lib/gpt/constants.d.ts.map +1 -1
  179. package/dist/infra/lib/gpt/constants.js +4 -9
  180. package/dist/infra/lib/gpt/constants.js.map +1 -1
  181. package/dist/infra/lib/gpt/embedding.d.ts +1 -1
  182. package/dist/infra/lib/gpt/embedding.js +3 -3
  183. package/dist/infra/lib/gpt/embedding.js.map +1 -1
  184. package/dist/infra/lib/gpt/oauth.d.ts +6 -39
  185. package/dist/infra/lib/gpt/oauth.d.ts.map +1 -1
  186. package/dist/infra/lib/gpt/oauth.js +8 -340
  187. package/dist/infra/lib/gpt/oauth.js.map +1 -1
  188. package/dist/infra/lib/gpt/orchestration.js +5 -5
  189. package/dist/infra/lib/gpt/orchestration.js.map +1 -1
  190. package/dist/infra/lib/gpt/specializations.d.ts +2 -2
  191. package/dist/infra/lib/gpt/specializations.js +3 -3
  192. package/dist/infra/lib/gpt/specializations.js.map +1 -1
  193. package/dist/infra/lib/gpt/types.d.ts +1 -1
  194. package/dist/infra/lib/gpt/types.d.ts.map +1 -1
  195. package/dist/infra/lib/llm/auth/AuthProfileManager.d.ts +2 -2
  196. package/dist/infra/lib/llm/auth/AuthProfileManager.d.ts.map +1 -1
  197. package/dist/infra/lib/llm/auth/AuthProfileManager.js.map +1 -1
  198. package/dist/infra/lib/llm/auth/AuthProfileManager.test.js +1 -1
  199. package/dist/infra/lib/llm/auth/AuthProfileManager.test.js.map +1 -1
  200. package/dist/infra/lib/llm/auth/TokenRefresher.d.ts +1 -1
  201. package/dist/infra/lib/llm/auth/TokenRefresher.js +1 -1
  202. package/dist/infra/lib/llm/auth/index.d.ts +2 -12
  203. package/dist/infra/lib/llm/auth/index.d.ts.map +1 -1
  204. package/dist/infra/lib/llm/auth/index.js +5 -63
  205. package/dist/infra/lib/llm/auth/index.js.map +1 -1
  206. package/dist/infra/lib/llm/types.d.ts +1 -1
  207. package/dist/infra/lib/llm/types.d.ts.map +1 -1
  208. package/dist/infra/lib/memory/KnowledgeGraph.js +4 -4
  209. package/dist/infra/lib/memory/MemorySearch.js +57 -57
  210. package/dist/infra/lib/memory/MemoryStorage.js +181 -181
  211. package/dist/infra/lib/memory/ObservationStore.js +28 -28
  212. package/dist/infra/lib/memory/ReflectionStore.js +30 -30
  213. package/dist/infra/lib/memory/SessionRAGRetriever.js +7 -7
  214. package/dist/infra/lib/memory/SessionRAGStore.js +225 -225
  215. package/dist/infra/lib/memory/SessionSummarizer.js +9 -9
  216. package/dist/infra/orchestrator/AgentManager.js +12 -12
  217. package/dist/infra/orchestrator/AgentRegistry.js +65 -65
  218. package/dist/infra/orchestrator/MultiLlmResearch.js +8 -8
  219. package/dist/infra/orchestrator/SwarmOrchestrator.test.js +16 -16
  220. package/dist/infra/orchestrator/parallelResearch.js +24 -24
  221. package/dist/tools/convention/analyzeComplexity.test.js +115 -115
  222. package/dist/tools/convention/validateCodeQuality.test.js +104 -104
  223. package/dist/tools/memory/createMemoryTimeline.js +10 -10
  224. package/dist/tools/memory/getMemoryGraph.js +12 -12
  225. package/dist/tools/memory/getSessionContext.js +9 -9
  226. package/dist/tools/memory/linkMemories.js +14 -14
  227. package/dist/tools/memory/listMemories.js +4 -4
  228. package/dist/tools/memory/recallMemory.js +4 -4
  229. package/dist/tools/memory/saveMemory.js +4 -4
  230. package/dist/tools/memory/searchMemoriesAdvanced.js +23 -23
  231. package/dist/tools/semantic/analyzeDependencyGraph.js +12 -12
  232. package/dist/tools/semantic/astGrep.test.js +6 -6
  233. package/dist/tools/spec/prdParser.test.js +171 -171
  234. package/dist/tools/spec/specGenerator.js +169 -169
  235. package/dist/tools/spec/traceabilityMatrix.js +64 -64
  236. package/dist/tools/spec/traceabilityMatrix.test.js +28 -28
  237. package/hooks/gemini-hooks.json +73 -73
  238. package/hooks/hooks.json +137 -137
  239. package/hooks/scripts/code-check.js +70 -70
  240. package/hooks/scripts/context-save.js +212 -212
  241. package/hooks/scripts/hud-status.js +291 -291
  242. package/hooks/scripts/keyword-detector.js +214 -214
  243. package/hooks/scripts/llm-orchestrate.js +475 -646
  244. package/hooks/scripts/post-edit.js +32 -32
  245. package/hooks/scripts/pre-tool-guard.js +125 -125
  246. package/hooks/scripts/prompt-dispatcher.js +185 -185
  247. package/hooks/scripts/sentinel-guard.js +104 -104
  248. package/hooks/scripts/session-start.js +106 -106
  249. package/hooks/scripts/stop-notify.js +209 -209
  250. package/hooks/scripts/utils.js +100 -100
  251. package/languages/csharp-unity.md +515 -515
  252. package/languages/gdscript-godot.md +470 -470
  253. package/languages/ruby-rails.md +489 -489
  254. package/languages/typescript-angular.md +433 -433
  255. package/languages/typescript-astro.md +416 -416
  256. package/languages/typescript-electron.md +406 -406
  257. package/languages/typescript-nestjs.md +524 -524
  258. package/languages/typescript-svelte.md +407 -407
  259. package/languages/typescript-tauri.md +365 -365
  260. package/package.json +121 -121
  261. package/skills/agents-md/SKILL.md +120 -120
  262. package/skills/arch-guard/SKILL.md +180 -180
  263. package/skills/brand-assets/SKILL.md +146 -146
  264. package/skills/capability-loop/SKILL.md +167 -167
  265. package/skills/characterization-test/SKILL.md +206 -206
  266. package/skills/commerce-patterns/SKILL.md +59 -59
  267. package/skills/commit-push-pr/SKILL.md +75 -75
  268. package/skills/context7-usage/SKILL.md +105 -105
  269. package/skills/core-capabilities/SKILL.md +48 -48
  270. package/skills/e2e-commerce/SKILL.md +57 -57
  271. package/skills/exec-plan/SKILL.md +147 -147
  272. package/skills/frontend-design/SKILL.md +73 -73
  273. package/skills/git-worktree/SKILL.md +72 -72
  274. package/skills/handoff/SKILL.md +109 -109
  275. package/skills/parallel-research/SKILL.md +87 -87
  276. package/skills/priority-todos/SKILL.md +63 -63
  277. package/skills/seo-checklist/SKILL.md +57 -57
  278. package/skills/techdebt/SKILL.md +122 -122
  279. package/skills/tool-fallback/SKILL.md +103 -103
  280. package/skills/typescript-advanced-types/SKILL.md +66 -65
  281. package/skills/ui-ux-pro-max/SKILL.md +206 -206
  282. package/skills/vercel-react-best-practices/SKILL.md +59 -59
  283. package/skills/video-production/SKILL.md +51 -51
  284. package/vibe/config.json +29 -29
  285. package/vibe/constitution.md +227 -227
  286. package/vibe/rules/principles/communication-guide.md +98 -98
  287. package/vibe/rules/principles/development-philosophy.md +52 -52
  288. package/vibe/rules/principles/quick-start.md +102 -102
  289. package/vibe/rules/quality/bdd-contract-testing.md +393 -393
  290. package/vibe/rules/quality/checklist.md +276 -276
  291. package/vibe/rules/quality/performance.md +236 -236
  292. package/vibe/rules/quality/testing-strategy.md +440 -440
  293. package/vibe/rules/standards/anti-patterns.md +541 -541
  294. package/vibe/rules/standards/code-structure.md +291 -291
  295. package/vibe/rules/standards/complexity-metrics.md +313 -313
  296. package/vibe/rules/standards/git-workflow.md +237 -237
  297. package/vibe/rules/standards/naming-conventions.md +198 -198
  298. package/vibe/rules/standards/security.md +305 -305
  299. package/vibe/rules/writing/document-style.md +74 -74
  300. package/vibe/setup.sh +31 -31
  301. package/vibe/templates/constitution-template.md +252 -252
  302. package/vibe/templates/contract-backend-template.md +526 -526
  303. package/vibe/templates/contract-frontend-template.md +599 -599
  304. package/vibe/templates/feature-template.md +96 -96
  305. package/vibe/templates/spec-template.md +221 -221
  306. package/vibe/ui-ux-data/charts.csv +26 -26
  307. package/vibe/ui-ux-data/colors.csv +97 -97
  308. package/vibe/ui-ux-data/icons.csv +101 -101
  309. package/vibe/ui-ux-data/landing.csv +31 -31
  310. package/vibe/ui-ux-data/products.csv +96 -96
  311. package/vibe/ui-ux-data/react-performance.csv +45 -45
  312. package/vibe/ui-ux-data/stacks/astro.csv +54 -54
  313. package/vibe/ui-ux-data/stacks/flutter.csv +53 -53
  314. package/vibe/ui-ux-data/stacks/html-tailwind.csv +56 -56
  315. package/vibe/ui-ux-data/stacks/jetpack-compose.csv +53 -53
  316. package/vibe/ui-ux-data/stacks/nextjs.csv +53 -53
  317. package/vibe/ui-ux-data/stacks/nuxt-ui.csv +51 -51
  318. package/vibe/ui-ux-data/stacks/nuxtjs.csv +59 -59
  319. package/vibe/ui-ux-data/stacks/react-native.csv +52 -52
  320. package/vibe/ui-ux-data/stacks/react.csv +54 -54
  321. package/vibe/ui-ux-data/stacks/shadcn.csv +61 -61
  322. package/vibe/ui-ux-data/stacks/svelte.csv +54 -54
  323. package/vibe/ui-ux-data/stacks/swiftui.csv +51 -51
  324. package/vibe/ui-ux-data/stacks/vue.csv +50 -50
  325. package/vibe/ui-ux-data/styles.csv +68 -68
  326. package/vibe/ui-ux-data/typography.csv +57 -57
  327. package/vibe/ui-ux-data/ui-reasoning.csv +101 -101
  328. package/vibe/ui-ux-data/ux-guidelines.csv +99 -99
  329. package/vibe/ui-ux-data/version.json +31 -31
  330. package/vibe/ui-ux-data/web-interface.csv +31 -31
  331. package/commands/vibe.voice.md +0 -79
@@ -1,646 +1,475 @@
1
- /**
2
- * UserPromptSubmit Hook - LLM 오케스트레이션 (GPT/Gemini)
3
- *
4
- * Usage:
5
- * node llm-orchestrate.js <provider> <mode> "prompt"
6
- * node llm-orchestrate.js <provider> <mode> "systemPrompt" "prompt"
7
- *
8
- * provider: gpt | gemini
9
- * mode: orchestrate | orchestrate-json | image | analyze-image
10
- *
11
- * Image Mode:
12
- * node llm-orchestrate.js gemini image "prompt" --output "./image.png"
13
- * node llm-orchestrate.js gemini image "prompt" --output "./image.png" --size "1920x1080"
14
- *
15
- * Features:
16
- * - CLI-based: GPT → codex exec, Gemini → gemini -p (CLI quota first → Antigravity API fallback)
17
- * - Exponential backoff retry (3 attempts)
18
- * - Auto fallback: gpt ↔ gemini
19
- * - Overload/rate-limit detection
20
- * - Image generation (Gemini API, Nano Banana model)
21
- * - Image analysis (Gemini API multimodal)
22
- *
23
- * Analyze-Image Mode:
24
- * node llm-orchestrate.js gemini analyze-image "./image.png" "Analyze this UI"
25
- * node llm-orchestrate.js gemini analyze-image "./image.png" "prompt" --system "system prompt"
26
- *
27
- * Input: JSON from stdin with { prompt: string } (when no CLI args)
28
- */
29
- import { getLibBaseUrl, readVibeConfig } from './utils.js';
30
- import fs from 'fs';
31
- import path from 'path';
32
- import os from 'os';
33
- import crypto from 'crypto';
34
- import { execSync, spawn } from 'child_process';
35
-
36
- const LIB_URL = getLibBaseUrl();
37
- const DEFAULT_SYSTEM_PROMPT = 'You are a helpful assistant.';
38
-
39
- const provider = process.argv[2] || 'gemini';
40
- const mode = process.argv[3] || 'orchestrate';
41
-
42
- // Retry configuration
43
- const MAX_RETRIES = 3;
44
- const INITIAL_DELAY_MS = 2000;
45
-
46
- // Errors that should skip retry and go to fallback immediately
47
- const SKIP_RETRY_PATTERNS = [
48
- /rate.?limit/i,
49
- /quota/i,
50
- /unauthorized/i,
51
- /forbidden/i,
52
- /authentication/i,
53
- /401/,
54
- /403/,
55
- /429/,
56
- ];
57
-
58
- // Errors that should trigger retry with backoff
59
- const RETRY_PATTERNS = [
60
- /overload/i,
61
- /503/,
62
- /5\d\d/,
63
- /network/i,
64
- /timeout/i,
65
- /ECONNRESET/i,
66
- /ETIMEDOUT/i,
67
- /spawn error/i,
68
- ];
69
-
70
- function shouldSkipRetry(errorMsg) {
71
- return SKIP_RETRY_PATTERNS.some(pattern => pattern.test(errorMsg));
72
- }
73
-
74
- function shouldRetry(errorMsg) {
75
- return RETRY_PATTERNS.some(pattern => pattern.test(errorMsg));
76
- }
77
-
78
- function sleep(ms) {
79
- return new Promise(resolve => setTimeout(resolve, ms));
80
- }
81
-
82
- // ============================================
83
- // Image Generation (delegates to gemini-api)
84
- // ============================================
85
-
86
- function parseImageArgs(args) {
87
- const result = { prompt: null, output: './generated-image.png', size: '1024x1024', model: 'nano-banana' };
88
- for (let i = 0; i < args.length; i++) {
89
- if (args[i] === '--output' || args[i] === '-o') {
90
- result.output = args[++i];
91
- } else if (args[i] === '--size' || args[i] === '-s') {
92
- result.size = args[++i];
93
- } else if (args[i] === '--pro') {
94
- result.model = 'nano-banana-pro';
95
- } else if (!args[i].startsWith('-') && !result.prompt) {
96
- result.prompt = args[i];
97
- }
98
- }
99
- return result;
100
- }
101
-
102
- // ============================================
103
- // Image Analysis (delegates to gemini-api)
104
- // ============================================
105
-
106
- function parseAnalyzeImageArgs(args) {
107
- const result = { imagePath: null, prompt: null, systemPrompt: null };
108
- for (let i = 0; i < args.length; i++) {
109
- if (args[i] === '--system' || args[i] === '-s') {
110
- result.systemPrompt = args[++i];
111
- } else if (!args[i].startsWith('-')) {
112
- if (!result.imagePath) {
113
- result.imagePath = args[i];
114
- } else if (!result.prompt) {
115
- result.prompt = args[i];
116
- }
117
- }
118
- }
119
- return result;
120
- }
121
-
122
- // ============================================
123
- // Voice Transcription (record + Gemini STT)
124
- // ============================================
125
-
126
- function parseVoiceArgs(args) {
127
- const result = { pro: false, lang: null, duration: 60 };
128
- for (let i = 0; i < args.length; i++) {
129
- if (args[i] === '--pro') {
130
- result.pro = true;
131
- } else if (args[i] === '--lang' || args[i] === '-l') {
132
- result.lang = args[++i];
133
- } else if (args[i] === '--duration' || args[i] === '-d') {
134
- result.duration = parseInt(args[++i], 10) || 60;
135
- }
136
- }
137
- return result;
138
- }
139
-
140
- function checkSoxInstalled() {
141
- try {
142
- execSync('sox --version', { stdio: 'pipe' });
143
- return true;
144
- } catch {
145
- return false;
146
- }
147
- }
148
-
149
- function recordAudio(outputPath, maxDuration) {
150
- return new Promise((resolve, reject) => {
151
- const soxProcess = spawn('sox', [
152
- '-d',
153
- '-r', '16000',
154
- '-c', '1',
155
- '-b', '16',
156
- '-t', 'wav',
157
- outputPath,
158
- 'trim', '0', String(maxDuration),
159
- ], { stdio: ['pipe', 'pipe', 'pipe'] });
160
-
161
- let stderrData = '';
162
- soxProcess.stderr.on('data', (data) => {
163
- stderrData += data.toString();
164
- });
165
-
166
- // Enter 키로 녹음 중지
167
- if (process.stdin.setRawMode) {
168
- process.stdin.setRawMode(true);
169
- }
170
- process.stdin.resume();
171
-
172
- const onKeypress = (key) => {
173
- if (key[0] === 13 || key[0] === 10 || key[0] === 3) {
174
- if (process.stdin.setRawMode) {
175
- process.stdin.setRawMode(false);
176
- }
177
- process.stdin.pause();
178
- process.stdin.removeListener('data', onKeypress);
179
- soxProcess.kill('SIGTERM');
180
- }
181
- };
182
- process.stdin.on('data', onKeypress);
183
-
184
- soxProcess.on('close', () => {
185
- if (process.stdin.setRawMode) {
186
- process.stdin.setRawMode(false);
187
- }
188
- process.stdin.pause();
189
- process.stdin.removeListener('data', onKeypress);
190
-
191
- if (fs.existsSync(outputPath) && fs.statSync(outputPath).size > 44) {
192
- resolve(outputPath);
193
- } else {
194
- reject(new Error(`Recording failed: ${stderrData || 'empty audio'}`));
195
- }
196
- });
197
-
198
- soxProcess.on('error', (err) => {
199
- if (process.stdin.setRawMode) {
200
- process.stdin.setRawMode(false);
201
- }
202
- process.stdin.pause();
203
- process.stdin.removeListener('data', onKeypress);
204
- reject(new Error(`Sox process error: ${err.message}`));
205
- });
206
- });
207
- }
208
-
209
- // ============================================
210
- // CLI Provider Functions
211
- // ============================================
212
-
213
- const CLI_TIMEOUT_MS = 120000;
214
- const IS_WINDOWS = os.platform() === 'win32';
215
-
216
- function spawnCli(cmd, args, options) {
217
- // Windows: .cmd shim은 spawn 직접 실행 불가 → cmd.exe /c 로 실행
218
- if (IS_WINDOWS) {
219
- return spawn(process.env.ComSpec || 'cmd.exe', ['/c', cmd, ...args], options);
220
- }
221
- return spawn(cmd, args, options);
222
- }
223
-
224
- function buildCliPrompt(prompt, sysPrompt, jsonMode) {
225
- let fullPrompt = sysPrompt && sysPrompt !== DEFAULT_SYSTEM_PROMPT
226
- ? `[System]\n${sysPrompt}\n\n[User]\n${prompt}`
227
- : prompt;
228
- if (jsonMode) {
229
- fullPrompt += '\n\nIMPORTANT: You must respond with valid JSON only.';
230
- }
231
- return fullPrompt;
232
- }
233
-
234
- function isAntigravityAuth() {
235
- const vibeConfig = readVibeConfig();
236
- if (vibeConfig.credentials?.gemini?.oauthSource === 'antigravity') return true;
237
- const oauthCredsPath = path.join(os.homedir(), '.gemini', 'oauth_creds.json');
238
- try {
239
- if (fs.existsSync(oauthCredsPath)) {
240
- const creds = JSON.parse(fs.readFileSync(oauthCredsPath, 'utf8'));
241
- if (creds.scope?.includes('cclog') || creds.scope?.includes('experimentsandconfigs')) return true;
242
- }
243
- } catch { /* not antigravity */ }
244
- return false;
245
- }
246
-
247
- function callCodexCli(prompt, sysPrompt, jsonMode, model) {
248
- const fullPrompt = buildCliPrompt(prompt, sysPrompt, jsonMode);
249
- const outputFile = path.join(os.tmpdir(), `vibe-codex-${crypto.randomUUID()}.txt`);
250
- // stdin pipe로 프롬프트 전달 (shell escaping 이슈 회피)
251
- const args = ['exec', '-m', model, '--sandbox', 'read-only', '--ephemeral', '-o', outputFile, '-'];
252
-
253
- // config에 저장된 API key를 환경변수로 전달 (임베딩과 동일한 키 사용)
254
- const vibeConfig = readVibeConfig();
255
- const apiKey = vibeConfig.credentials?.gpt?.apiKey || process.env.OPENAI_API_KEY;
256
- const env = apiKey ? { ...process.env, OPENAI_API_KEY: apiKey } : process.env;
257
-
258
- return new Promise((resolve, reject) => {
259
- const proc = spawnCli('codex', args, {
260
- stdio: ['pipe', 'pipe', 'pipe'],
261
- timeout: CLI_TIMEOUT_MS,
262
- env,
263
- });
264
- proc.stdin.write(fullPrompt);
265
- proc.stdin.end();
266
-
267
- let stderr = '';
268
- proc.stderr.on('data', (d) => { stderr += d.toString(); });
269
-
270
- proc.on('close', (code) => {
271
- if (code === 0 && fs.existsSync(outputFile)) {
272
- const result = fs.readFileSync(outputFile, 'utf8');
273
- try { fs.unlinkSync(outputFile); } catch { /* ignore */ }
274
- resolve(result);
275
- } else {
276
- try { fs.unlinkSync(outputFile); } catch { /* ignore */ }
277
- reject(new Error(`codex exec failed (code ${code}): ${stderr.slice(0, 500)}`));
278
- }
279
- });
280
-
281
- proc.on('error', (err) => {
282
- try { fs.unlinkSync(outputFile); } catch { /* ignore */ }
283
- reject(new Error(`codex exec spawn error: ${err.message}`));
284
- });
285
- });
286
- }
287
-
288
- function callGeminiCli(prompt, sysPrompt, jsonMode, model) {
289
- const fullPrompt = buildCliPrompt(prompt, sysPrompt, jsonMode);
290
- // -p 로 headless 모드, stdin으로 프롬프트 전달 (stdin is appended to -p value)
291
- const args = ['-p', '.', '-o', 'text'];
292
- if (model) args.push('-m', model);
293
-
294
- return new Promise((resolve, reject) => {
295
- const proc = spawnCli('gemini', args, {
296
- stdio: ['pipe', 'pipe', 'pipe'],
297
- timeout: CLI_TIMEOUT_MS,
298
- });
299
- proc.stdin.write(fullPrompt);
300
- proc.stdin.end();
301
-
302
- let stdout = '';
303
- let stderr = '';
304
- proc.stdout.on('data', (d) => { stdout += d.toString(); });
305
- proc.stderr.on('data', (d) => { stderr += d.toString(); });
306
-
307
- proc.on('close', (code) => {
308
- if (code === 0 && stdout.trim()) {
309
- resolve(stdout.trim());
310
- } else {
311
- reject(new Error(`gemini cli failed (code ${code}): ${(stderr || stdout).slice(0, 500)}`));
312
- }
313
- });
314
-
315
- proc.on('error', (err) => {
316
- reject(new Error(`gemini cli spawn error: ${err.message}`));
317
- });
318
- });
319
- }
320
-
321
- async function callProvider(providerName, prompt, sysPrompt, jsonMode) {
322
- const vibeConfig = readVibeConfig();
323
-
324
- if (providerName === 'gpt' || providerName === 'gpt-spark') {
325
- const isSpark = providerName === 'gpt-spark';
326
- const model = isSpark
327
- ? (vibeConfig.models?.gptSpark || process.env.GPT_SPARK_MODEL || 'gpt-5.3-codex-spark')
328
- : (vibeConfig.models?.gpt || process.env.GPT_MODEL || 'gpt-5.3-codex');
329
- return await callCodexCli(prompt, sysPrompt, jsonMode, model);
330
- }
331
-
332
- if (providerName === 'gemini') {
333
- // 1차: gemini CLI (일반 쿼터 먼저 소진)
334
- const model = vibeConfig.models?.gemini || process.env.GEMINI_MODEL || 'gemini-3-pro-preview';
335
- try {
336
- return await callGeminiCli(prompt, sysPrompt, jsonMode, model);
337
- } catch (cliErr) {
338
- // 2차: Antigravity API fallback (프리미엄 쿼터 아껴둠)
339
- if (isAntigravityAuth()) {
340
- console.error(`[GEMINI] CLI failed, falling back to Antigravity API...`);
341
- const modulePath = `${LIB_URL}gemini-api.js`;
342
- const module = await import(modulePath);
343
- return await module.coreGeminiOrchestrate(prompt, sysPrompt, { jsonMode });
344
- }
345
- throw cliErr;
346
- }
347
- }
348
-
349
- throw new Error(`Unknown provider: ${providerName}`);
350
- }
351
-
352
- async function callWithRetry(providerName, prompt, sysPrompt, jsonMode) {
353
- let lastError;
354
-
355
- for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
356
- try {
357
- return { success: true, result: await callProvider(providerName, prompt, sysPrompt, jsonMode) };
358
- } catch (e) {
359
- lastError = e;
360
- const errorMsg = e.message || String(e);
361
-
362
- // Skip retry for auth/quota errors - go to fallback immediately
363
- if (shouldSkipRetry(errorMsg)) {
364
- return { success: false, error: errorMsg, skipToFallback: true };
365
- }
366
-
367
- // Retry with backoff for transient errors
368
- if (shouldRetry(errorMsg) && attempt < MAX_RETRIES) {
369
- const delay = INITIAL_DELAY_MS * Math.pow(2, attempt - 1);
370
- console.error(`[${providerName.toUpperCase()}] Retry ${attempt}/${MAX_RETRIES} after ${delay}ms...`);
371
- await sleep(delay);
372
- continue;
373
- }
374
-
375
- // Unknown error or max retries reached
376
- return { success: false, error: errorMsg, skipToFallback: false };
377
- }
378
- }
379
-
380
- return { success: false, error: lastError?.message || 'Max retries exceeded', skipToFallback: false };
381
- }
382
-
383
- async function main() {
384
- // Image mode handling
385
- if (mode === 'image') {
386
- if (provider !== 'gemini') {
387
- console.log('[IMAGE] Error: Image generation only supports gemini provider');
388
- return;
389
- }
390
-
391
- const imageArgs = parseImageArgs(process.argv.slice(4));
392
- if (!imageArgs.prompt) {
393
- console.log('[IMAGE] Error: --prompt is required');
394
- return;
395
- }
396
-
397
- // Ensure output directory exists
398
- const outputDir = path.dirname(imageArgs.output);
399
- if (outputDir && outputDir !== '.' && !fs.existsSync(outputDir)) {
400
- fs.mkdirSync(outputDir, { recursive: true });
401
- }
402
-
403
- const modelLabel = imageArgs.model === 'nano-banana-pro' ? 'Nano Banana Pro' : 'Nano Banana';
404
- console.error(`[IMAGE] Generating with ${modelLabel}...`);
405
- console.error(` Prompt: ${imageArgs.prompt}`);
406
- console.error(` Size: ${imageArgs.size}`);
407
- console.error(` Model: ${modelLabel}`);
408
- console.error(` Output: ${imageArgs.output}`);
409
-
410
- try {
411
- const geminiApi = await import(`${LIB_URL}gemini-api.js`);
412
- const image = await geminiApi.generateImage(imageArgs.prompt, { size: imageArgs.size, model: imageArgs.model });
413
- fs.writeFileSync(imageArgs.output, image.data);
414
- const stats = fs.statSync(imageArgs.output);
415
- const sizeKB = (stats.size / 1024).toFixed(1);
416
-
417
- console.log(JSON.stringify({
418
- success: true,
419
- path: path.resolve(imageArgs.output),
420
- size: stats.size,
421
- sizeKB: `${sizeKB} KB`,
422
- prompt: imageArgs.prompt
423
- }));
424
- } catch (err) {
425
- console.log(JSON.stringify({
426
- success: false,
427
- error: err.message,
428
- prompt: imageArgs.prompt
429
- }));
430
- }
431
- return;
432
- }
433
-
434
- // Analyze-image mode handling
435
- if (mode === 'analyze-image') {
436
- if (provider !== 'gemini') {
437
- console.log('[ANALYZE-IMAGE] Error: Image analysis only supports gemini provider');
438
- return;
439
- }
440
-
441
- const analyzeArgs = parseAnalyzeImageArgs(process.argv.slice(4));
442
- if (!analyzeArgs.imagePath) {
443
- console.log('[ANALYZE-IMAGE] Error: image path is required');
444
- return;
445
- }
446
- if (!analyzeArgs.prompt) {
447
- console.log('[ANALYZE-IMAGE] Error: analysis prompt is required');
448
- return;
449
- }
450
-
451
- const absolutePath = path.resolve(analyzeArgs.imagePath);
452
- if (!fs.existsSync(absolutePath)) {
453
- console.log(JSON.stringify({
454
- success: false,
455
- error: `Image file not found: ${absolutePath}`,
456
- imagePath: analyzeArgs.imagePath,
457
- }));
458
- return;
459
- }
460
-
461
- console.error(`[ANALYZE-IMAGE] Analyzing image with Gemini...`);
462
- console.error(` Image: ${absolutePath}`);
463
- console.error(` Prompt: ${analyzeArgs.prompt}`);
464
-
465
- try {
466
- const geminiApi = await import(`${LIB_URL}gemini-api.js`);
467
- const options = {};
468
- if (analyzeArgs.systemPrompt) {
469
- options.systemPrompt = analyzeArgs.systemPrompt;
470
- }
471
- const analysis = await geminiApi.analyzeImage(absolutePath, analyzeArgs.prompt, options);
472
-
473
- console.log(JSON.stringify({
474
- success: true,
475
- analysis,
476
- imagePath: absolutePath,
477
- }));
478
- } catch (err) {
479
- console.log(JSON.stringify({
480
- success: false,
481
- error: err.message,
482
- imagePath: absolutePath,
483
- }));
484
- }
485
- return;
486
- }
487
-
488
- // Voice mode handling
489
- if (mode === 'voice') {
490
- if (provider !== 'gemini') {
491
- console.log(JSON.stringify({
492
- success: false,
493
- error: 'Voice transcription only supports gemini provider',
494
- }));
495
- return;
496
- }
497
-
498
- if (!checkSoxInstalled()) {
499
- console.log(JSON.stringify({
500
- success: false,
501
- error: 'sox is not installed. Install with: brew install sox (macOS) or apt install sox (Linux)',
502
- }));
503
- return;
504
- }
505
-
506
- const voiceArgs = parseVoiceArgs(process.argv.slice(4));
507
- const voiceModel = voiceArgs.pro ? 'gemini-3-pro' : 'gemini-3-flash';
508
- const tmpFile = path.join(os.tmpdir(), `vibe-voice-${crypto.randomUUID()}.wav`);
509
-
510
- console.error(`[VOICE] Recording audio... (press Enter to stop, max ${voiceArgs.duration}s)`);
511
- console.error(` Model: ${voiceModel}`);
512
- if (voiceArgs.lang) {
513
- console.error(` Language: ${voiceArgs.lang}`);
514
- }
515
-
516
- try {
517
- await recordAudio(tmpFile, voiceArgs.duration);
518
-
519
- const stats = fs.statSync(tmpFile);
520
- const fileSizeKB = (stats.size / 1024).toFixed(1);
521
- console.error(`[VOICE] Recording complete (${fileSizeKB} KB). Transcribing...`);
522
-
523
- const geminiApi = await import(`${LIB_URL}gemini-api.js`);
524
- const result = await geminiApi.transcribeAudio(tmpFile, {
525
- model: voiceModel,
526
- language: voiceArgs.lang || undefined,
527
- });
528
-
529
- try { fs.unlinkSync(tmpFile); } catch { /* ignore */ }
530
-
531
- console.log(JSON.stringify({
532
- success: true,
533
- transcription: result.transcription,
534
- duration: result.duration,
535
- model: result.model,
536
- }));
537
- } catch (err) {
538
- try { fs.unlinkSync(tmpFile); } catch { /* ignore */ }
539
-
540
- console.log(JSON.stringify({
541
- success: false,
542
- error: err.message,
543
- }));
544
- }
545
- return;
546
- }
547
-
548
- // Text generation mode (orchestrate / orchestrate-json)
549
- let prompt;
550
- let systemPrompt = DEFAULT_SYSTEM_PROMPT;
551
-
552
- // --input <file> 플래그를 먼저 확인 (위치 인자보다 우선)
553
- const inputFlagIdx = process.argv.indexOf('--input');
554
- if (inputFlagIdx !== -1 && process.argv[inputFlagIdx + 1]) {
555
- const inputFile = process.argv[inputFlagIdx + 1];
556
-
557
- // Path traversal 방지: 절대경로로 resolve 후 임시 디렉토리 또는 프로젝트 내 확인
558
- const resolvedInput = path.resolve(inputFile);
559
- const allowedDirs = [os.tmpdir(), process.cwd()];
560
- const isAllowed = allowedDirs.some(dir => resolvedInput.startsWith(path.resolve(dir)));
561
- if (!isAllowed) {
562
- console.log(`[${provider.toUpperCase()}] Error: Input file must be in temp directory or project directory`);
563
- return;
564
- }
565
-
566
- try {
567
- const inputData = fs.readFileSync(resolvedInput, 'utf8');
568
- const parsed = JSON.parse(inputData);
569
- prompt = parsed.prompt;
570
- if (parsed.systemPrompt) {
571
- systemPrompt = parsed.systemPrompt;
572
- }
573
- } catch (err) {
574
- console.log(`[${provider.toUpperCase()}] Error: Failed to read input file: ${err.message}`);
575
- return;
576
- }
577
- } else {
578
- // CLI argument 사용
579
- // Usage 1: node script.js gpt orchestrate "system prompt" "user prompt"
580
- // Usage 2: node script.js gpt orchestrate "user prompt" (uses default system prompt)
581
- const arg4 = process.argv[4]?.trim();
582
- const arg5 = process.argv.slice(5).join(' ').trim();
583
-
584
- if (arg5) {
585
- // 5번째 인자가 있으면: arg4=시스템 프롬프트, arg5=사용자 프롬프트
586
- systemPrompt = arg4;
587
- prompt = arg5;
588
- } else if (arg4) {
589
- // 4번째 인자만 있으면: arg4=사용자 프롬프트 (시스템 프롬프트는 기본값)
590
- prompt = arg4;
591
- } else {
592
- // Hook에서 호출: stdin으로 JSON 입력 (fallback)
593
- let inputData = '';
594
- for await (const chunk of process.stdin) {
595
- inputData += chunk;
596
- }
597
-
598
- try {
599
- const parsed = JSON.parse(inputData);
600
- prompt = parsed.prompt;
601
- } catch {
602
- console.log(`[${provider.toUpperCase()}] Error: Invalid JSON input`);
603
- return;
604
- }
605
- }
606
- }
607
-
608
- // 접두사 제거
609
- const prefixPatterns = {
610
- gpt: /^(gpt[-.\s]|지피티-|vibe-gpt-)\s*/i,
611
- 'gpt-spark': /^(gpt[-.\s]|지피티-|vibe-gpt-)\s*/i,
612
- gemini: /^(gemini[-.\s]|제미나이-|vibe-gemini-)\s*/i,
613
- };
614
- const cleanPrompt = prompt.replace(prefixPatterns[provider] || /^/, '').trim();
615
- const jsonMode = mode === 'orchestrate-json';
616
-
617
- // Provider chain: primary → cross fallback
618
- // gpt-spark fallback: gpt-spark → gemini (spark는 full gpt로 fallback하지 않음)
619
- const providerLabels = { gpt: 'GPT-5.3', 'gpt-spark': 'GPT-5.3 Spark', gemini: 'Gemini-3' };
620
- const isGpt = provider === 'gpt' || provider === 'gpt-spark';
621
- const providerChain = isGpt
622
- ? [provider, 'gemini']
623
- : ['gemini', 'gpt'];
624
-
625
- for (const currentProvider of providerChain) {
626
- const label = providerLabels[currentProvider] || currentProvider.toUpperCase();
627
- const result = await callWithRetry(currentProvider, cleanPrompt, systemPrompt, jsonMode);
628
-
629
- if (result.success) {
630
- console.log(`${label} response: ${result.result}`);
631
- return;
632
- }
633
-
634
- // Log failure and try fallback
635
- if (currentProvider !== providerChain[providerChain.length - 1]) {
636
- const nextProvider = providerChain[providerChain.indexOf(currentProvider) + 1];
637
- const nextLabel = providerLabels[nextProvider] || nextProvider.toUpperCase();
638
- console.error(`[${currentProvider.toUpperCase()}] Failed: ${result.error}. Falling back to ${nextLabel}...`);
639
- } else {
640
- // All providers failed
641
- console.log(`[LLM] Error: All providers failed. Last error: ${result.error}`);
642
- }
643
- }
644
- }
645
-
646
- main();
1
+ /**
2
+ * UserPromptSubmit Hook - LLM 오케스트레이션 (GPT/Gemini)
3
+ *
4
+ * Usage:
5
+ * node llm-orchestrate.js <provider> <mode> "prompt"
6
+ * node llm-orchestrate.js <provider> <mode> "systemPrompt" "prompt"
7
+ *
8
+ * provider: gpt | gemini
9
+ * mode: orchestrate | orchestrate-json | image | analyze-image
10
+ *
11
+ * Image Mode:
12
+ * node llm-orchestrate.js gemini image "prompt" --output "./image.png"
13
+ * node llm-orchestrate.js gemini image "prompt" --output "./image.png" --size "1920x1080"
14
+ *
15
+ * Features:
16
+ * - CLI-based: GPT → codex exec, Gemini → gemini -p
17
+ * - Exponential backoff retry (3 attempts)
18
+ * - Auto fallback: gpt ↔ gemini
19
+ * - Overload/rate-limit detection
20
+ * - Image generation (Gemini API, Gemini Flash Image model)
21
+ * - Image analysis (Gemini API multimodal)
22
+ *
23
+ * Analyze-Image Mode:
24
+ * node llm-orchestrate.js gemini analyze-image "./image.png" "Analyze this UI"
25
+ * node llm-orchestrate.js gemini analyze-image "./image.png" "prompt" --system "system prompt"
26
+ *
27
+ * Input: JSON from stdin with { prompt: string } (when no CLI args)
28
+ */
29
+ import { getLibBaseUrl, readVibeConfig } from './utils.js';
30
+ import fs from 'fs';
31
+ import path from 'path';
32
+ import os from 'os';
33
+ import crypto from 'crypto';
34
+ import { execSync, spawn } from 'child_process';
35
+
36
+ const LIB_URL = getLibBaseUrl();
37
+ const DEFAULT_SYSTEM_PROMPT = 'You are a helpful assistant.';
38
+
39
+ const provider = process.argv[2] || 'gemini';
40
+ const mode = process.argv[3] || 'orchestrate';
41
+
42
+ // Retry configuration
43
+ const MAX_RETRIES = 3;
44
+ const INITIAL_DELAY_MS = 2000;
45
+
46
+ // Errors that should skip retry and go to fallback immediately
47
+ const SKIP_RETRY_PATTERNS = [
48
+ /rate.?limit/i,
49
+ /quota/i,
50
+ /unauthorized/i,
51
+ /forbidden/i,
52
+ /authentication/i,
53
+ /401/,
54
+ /403/,
55
+ /429/,
56
+ ];
57
+
58
+ // Errors that should trigger retry with backoff
59
+ const RETRY_PATTERNS = [
60
+ /overload/i,
61
+ /503/,
62
+ /5\d\d/,
63
+ /network/i,
64
+ /timeout/i,
65
+ /ECONNRESET/i,
66
+ /ETIMEDOUT/i,
67
+ /spawn error/i,
68
+ ];
69
+
70
+ function shouldSkipRetry(errorMsg) {
71
+ return SKIP_RETRY_PATTERNS.some(pattern => pattern.test(errorMsg));
72
+ }
73
+
74
+ function shouldRetry(errorMsg) {
75
+ return RETRY_PATTERNS.some(pattern => pattern.test(errorMsg));
76
+ }
77
+
78
+ function sleep(ms) {
79
+ return new Promise(resolve => setTimeout(resolve, ms));
80
+ }
81
+
82
+ // ============================================
83
+ // Image Generation (delegates to gemini-api)
84
+ // ============================================
85
+
86
+ function parseImageArgs(args) {
87
+ const result = { prompt: null, output: './generated-image.png', size: '1024x1024', model: 'nano-banana' };
88
+ for (let i = 0; i < args.length; i++) {
89
+ if (args[i] === '--output' || args[i] === '-o') {
90
+ result.output = args[++i];
91
+ } else if (args[i] === '--size' || args[i] === '-s') {
92
+ result.size = args[++i];
93
+ } else if (args[i] === '--pro') {
94
+ result.model = 'nano-banana-pro';
95
+ } else if (!args[i].startsWith('-') && !result.prompt) {
96
+ result.prompt = args[i];
97
+ }
98
+ }
99
+ return result;
100
+ }
101
+
102
+ // ============================================
103
+ // Image Analysis (delegates to gemini-api)
104
+ // ============================================
105
+
106
+ function parseAnalyzeImageArgs(args) {
107
+ const result = { imagePath: null, prompt: null, systemPrompt: null };
108
+ for (let i = 0; i < args.length; i++) {
109
+ if (args[i] === '--system' || args[i] === '-s') {
110
+ result.systemPrompt = args[++i];
111
+ } else if (!args[i].startsWith('-')) {
112
+ if (!result.imagePath) {
113
+ result.imagePath = args[i];
114
+ } else if (!result.prompt) {
115
+ result.prompt = args[i];
116
+ }
117
+ }
118
+ }
119
+ return result;
120
+ }
121
+
122
+ // ============================================
123
+ // CLI Provider Functions
124
+ // ============================================
125
+
126
+ const CLI_TIMEOUT_MS = 120000;
127
+ const IS_WINDOWS = os.platform() === 'win32';
128
+
129
+ function spawnCli(cmd, args, options) {
130
+ // Windows: .cmd shim은 spawn 직접 실행 불가 → cmd.exe /c 로 실행
131
+ if (IS_WINDOWS) {
132
+ return spawn(process.env.ComSpec || 'cmd.exe', ['/c', cmd, ...args], options);
133
+ }
134
+ return spawn(cmd, args, options);
135
+ }
136
+
137
+ function buildCliPrompt(prompt, sysPrompt, jsonMode) {
138
+ let fullPrompt = sysPrompt && sysPrompt !== DEFAULT_SYSTEM_PROMPT
139
+ ? `[System]\n${sysPrompt}\n\n[User]\n${prompt}`
140
+ : prompt;
141
+ if (jsonMode) {
142
+ fullPrompt += '\n\nIMPORTANT: You must respond with valid JSON only.';
143
+ }
144
+ return fullPrompt;
145
+ }
146
+
147
+
148
+ function callCodexCli(prompt, sysPrompt, jsonMode, model) {
149
+ const fullPrompt = buildCliPrompt(prompt, sysPrompt, jsonMode);
150
+ const outputFile = path.join(os.tmpdir(), `vibe-codex-${crypto.randomUUID()}.txt`);
151
+ // stdin pipe로 프롬프트 전달 (shell escaping 이슈 회피)
152
+ const args = ['exec', '-m', model, '--sandbox', 'read-only', '--ephemeral', '-o', outputFile, '-'];
153
+
154
+ // config에 저장된 API key를 환경변수로 전달 (임베딩과 동일한 키 사용)
155
+ const vibeConfig = readVibeConfig();
156
+ const apiKey = vibeConfig.credentials?.gpt?.apiKey || process.env.OPENAI_API_KEY;
157
+ const env = apiKey ? { ...process.env, OPENAI_API_KEY: apiKey } : process.env;
158
+
159
+ return new Promise((resolve, reject) => {
160
+ const proc = spawnCli('codex', args, {
161
+ stdio: ['pipe', 'pipe', 'pipe'],
162
+ timeout: CLI_TIMEOUT_MS,
163
+ env,
164
+ });
165
+ proc.stdin.write(fullPrompt);
166
+ proc.stdin.end();
167
+
168
+ let stderr = '';
169
+ proc.stderr.on('data', (d) => { stderr += d.toString(); });
170
+
171
+ proc.on('close', (code) => {
172
+ if (code === 0 && fs.existsSync(outputFile)) {
173
+ const result = fs.readFileSync(outputFile, 'utf8');
174
+ try { fs.unlinkSync(outputFile); } catch { /* ignore */ }
175
+ resolve(result);
176
+ } else {
177
+ try { fs.unlinkSync(outputFile); } catch { /* ignore */ }
178
+ reject(new Error(`codex exec failed (code ${code}): ${stderr.slice(0, 500)}`));
179
+ }
180
+ });
181
+
182
+ proc.on('error', (err) => {
183
+ try { fs.unlinkSync(outputFile); } catch { /* ignore */ }
184
+ reject(new Error(`codex exec spawn error: ${err.message}`));
185
+ });
186
+ });
187
+ }
188
+
189
+ function callGeminiCli(prompt, sysPrompt, jsonMode, model) {
190
+ const fullPrompt = buildCliPrompt(prompt, sysPrompt, jsonMode);
191
+ // -p headless 모드, stdin으로 프롬프트 전달 (stdin is appended to -p value)
192
+ const args = ['-p', '.', '-o', 'text'];
193
+ if (model) args.push('-m', model);
194
+
195
+ return new Promise((resolve, reject) => {
196
+ const proc = spawnCli('gemini', args, {
197
+ stdio: ['pipe', 'pipe', 'pipe'],
198
+ timeout: CLI_TIMEOUT_MS,
199
+ });
200
+ proc.stdin.write(fullPrompt);
201
+ proc.stdin.end();
202
+
203
+ let stdout = '';
204
+ let stderr = '';
205
+ proc.stdout.on('data', (d) => { stdout += d.toString(); });
206
+ proc.stderr.on('data', (d) => { stderr += d.toString(); });
207
+
208
+ proc.on('close', (code) => {
209
+ if (code === 0 && stdout.trim()) {
210
+ resolve(stdout.trim());
211
+ } else {
212
+ reject(new Error(`gemini cli failed (code ${code}): ${(stderr || stdout).slice(0, 500)}`));
213
+ }
214
+ });
215
+
216
+ proc.on('error', (err) => {
217
+ reject(new Error(`gemini cli spawn error: ${err.message}`));
218
+ });
219
+ });
220
+ }
221
+
222
+ async function callProvider(providerName, prompt, sysPrompt, jsonMode) {
223
+ const vibeConfig = readVibeConfig();
224
+
225
+ if (providerName === 'gpt' || providerName === 'gpt-codex') {
226
+ const isCodex = providerName === 'gpt-codex';
227
+ const model = isCodex
228
+ ? (vibeConfig.models?.gptCodex || process.env.GPT_CODEX_MODEL || 'gpt-5.3-codex')
229
+ : (vibeConfig.models?.gpt || process.env.GPT_MODEL || 'gpt-5.4');
230
+ return await callCodexCli(prompt, sysPrompt, jsonMode, model);
231
+ }
232
+
233
+ if (providerName === 'gemini') {
234
+ const model = vibeConfig.models?.gemini || process.env.GEMINI_MODEL || 'gemini-3.1-pro-preview';
235
+ return await callGeminiCli(prompt, sysPrompt, jsonMode, model);
236
+ }
237
+
238
+ throw new Error(`Unknown provider: ${providerName}`);
239
+ }
240
+
241
+ async function callWithRetry(providerName, prompt, sysPrompt, jsonMode) {
242
+ let lastError;
243
+
244
+ for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
245
+ try {
246
+ return { success: true, result: await callProvider(providerName, prompt, sysPrompt, jsonMode) };
247
+ } catch (e) {
248
+ lastError = e;
249
+ const errorMsg = e.message || String(e);
250
+
251
+ // Skip retry for auth/quota errors - go to fallback immediately
252
+ if (shouldSkipRetry(errorMsg)) {
253
+ return { success: false, error: errorMsg, skipToFallback: true };
254
+ }
255
+
256
+ // Retry with backoff for transient errors
257
+ if (shouldRetry(errorMsg) && attempt < MAX_RETRIES) {
258
+ const delay = INITIAL_DELAY_MS * Math.pow(2, attempt - 1);
259
+ console.error(`[${providerName.toUpperCase()}] Retry ${attempt}/${MAX_RETRIES} after ${delay}ms...`);
260
+ await sleep(delay);
261
+ continue;
262
+ }
263
+
264
+ // Unknown error or max retries reached
265
+ return { success: false, error: errorMsg, skipToFallback: false };
266
+ }
267
+ }
268
+
269
+ return { success: false, error: lastError?.message || 'Max retries exceeded', skipToFallback: false };
270
+ }
271
+
272
+ async function main() {
273
+ // Image mode handling
274
+ if (mode === 'image') {
275
+ if (provider !== 'gemini') {
276
+ console.log('[IMAGE] Error: Image generation only supports gemini provider');
277
+ return;
278
+ }
279
+
280
+ const imageArgs = parseImageArgs(process.argv.slice(4));
281
+ if (!imageArgs.prompt) {
282
+ console.log('[IMAGE] Error: --prompt is required');
283
+ return;
284
+ }
285
+
286
+ // Ensure output directory exists
287
+ const outputDir = path.dirname(imageArgs.output);
288
+ if (outputDir && outputDir !== '.' && !fs.existsSync(outputDir)) {
289
+ fs.mkdirSync(outputDir, { recursive: true });
290
+ }
291
+
292
+ const modelLabel = imageArgs.model === 'nano-banana-pro' ? 'Gemini Pro Image' : 'Gemini Flash Image';
293
+ console.error(`[IMAGE] Generating with ${modelLabel}...`);
294
+ console.error(` Prompt: ${imageArgs.prompt}`);
295
+ console.error(` Size: ${imageArgs.size}`);
296
+ console.error(` Model: ${modelLabel}`);
297
+ console.error(` Output: ${imageArgs.output}`);
298
+
299
+ try {
300
+ const geminiApi = await import(`${LIB_URL}gemini-api.js`);
301
+ const image = await geminiApi.generateImage(imageArgs.prompt, { size: imageArgs.size, model: imageArgs.model });
302
+ fs.writeFileSync(imageArgs.output, image.data);
303
+ const stats = fs.statSync(imageArgs.output);
304
+ const sizeKB = (stats.size / 1024).toFixed(1);
305
+
306
+ console.log(JSON.stringify({
307
+ success: true,
308
+ path: path.resolve(imageArgs.output),
309
+ size: stats.size,
310
+ sizeKB: `${sizeKB} KB`,
311
+ prompt: imageArgs.prompt
312
+ }));
313
+ } catch (err) {
314
+ console.log(JSON.stringify({
315
+ success: false,
316
+ error: err.message,
317
+ prompt: imageArgs.prompt
318
+ }));
319
+ }
320
+ return;
321
+ }
322
+
323
+ // Analyze-image mode handling
324
+ if (mode === 'analyze-image') {
325
+ if (provider !== 'gemini') {
326
+ console.log('[ANALYZE-IMAGE] Error: Image analysis only supports gemini provider');
327
+ return;
328
+ }
329
+
330
+ const analyzeArgs = parseAnalyzeImageArgs(process.argv.slice(4));
331
+ if (!analyzeArgs.imagePath) {
332
+ console.log('[ANALYZE-IMAGE] Error: image path is required');
333
+ return;
334
+ }
335
+ if (!analyzeArgs.prompt) {
336
+ console.log('[ANALYZE-IMAGE] Error: analysis prompt is required');
337
+ return;
338
+ }
339
+
340
+ const absolutePath = path.resolve(analyzeArgs.imagePath);
341
+ if (!fs.existsSync(absolutePath)) {
342
+ console.log(JSON.stringify({
343
+ success: false,
344
+ error: `Image file not found: ${absolutePath}`,
345
+ imagePath: analyzeArgs.imagePath,
346
+ }));
347
+ return;
348
+ }
349
+
350
+ console.error(`[ANALYZE-IMAGE] Analyzing image with Gemini...`);
351
+ console.error(` Image: ${absolutePath}`);
352
+ console.error(` Prompt: ${analyzeArgs.prompt}`);
353
+
354
+ try {
355
+ const geminiApi = await import(`${LIB_URL}gemini-api.js`);
356
+ const options = {};
357
+ if (analyzeArgs.systemPrompt) {
358
+ options.systemPrompt = analyzeArgs.systemPrompt;
359
+ }
360
+ const analysis = await geminiApi.analyzeImage(absolutePath, analyzeArgs.prompt, options);
361
+
362
+ console.log(JSON.stringify({
363
+ success: true,
364
+ analysis,
365
+ imagePath: absolutePath,
366
+ }));
367
+ } catch (err) {
368
+ console.log(JSON.stringify({
369
+ success: false,
370
+ error: err.message,
371
+ imagePath: absolutePath,
372
+ }));
373
+ }
374
+ return;
375
+ }
376
+
377
+ // Text generation mode (orchestrate / orchestrate-json)
378
+ let prompt;
379
+ let systemPrompt = DEFAULT_SYSTEM_PROMPT;
380
+
381
+ // --input <file> 플래그를 먼저 확인 (위치 인자보다 우선)
382
+ const inputFlagIdx = process.argv.indexOf('--input');
383
+ if (inputFlagIdx !== -1 && process.argv[inputFlagIdx + 1]) {
384
+ const inputFile = process.argv[inputFlagIdx + 1];
385
+
386
+ // Path traversal 방지: 절대경로로 resolve 후 임시 디렉토리 또는 프로젝트 내 확인
387
+ const resolvedInput = path.resolve(inputFile);
388
+ const allowedDirs = [os.tmpdir(), process.cwd()];
389
+ const isAllowed = allowedDirs.some(dir => resolvedInput.startsWith(path.resolve(dir)));
390
+ if (!isAllowed) {
391
+ console.log(`[${provider.toUpperCase()}] Error: Input file must be in temp directory or project directory`);
392
+ return;
393
+ }
394
+
395
+ try {
396
+ const inputData = fs.readFileSync(resolvedInput, 'utf8');
397
+ const parsed = JSON.parse(inputData);
398
+ prompt = parsed.prompt;
399
+ if (parsed.systemPrompt) {
400
+ systemPrompt = parsed.systemPrompt;
401
+ }
402
+ } catch (err) {
403
+ console.log(`[${provider.toUpperCase()}] Error: Failed to read input file: ${err.message}`);
404
+ return;
405
+ }
406
+ } else {
407
+ // CLI argument 사용
408
+ // Usage 1: node script.js gpt orchestrate "system prompt" "user prompt"
409
+ // Usage 2: node script.js gpt orchestrate "user prompt" (uses default system prompt)
410
+ const arg4 = process.argv[4]?.trim();
411
+ const arg5 = process.argv.slice(5).join(' ').trim();
412
+
413
+ if (arg5) {
414
+ // 5번째 인자가 있으면: arg4=시스템 프롬프트, arg5=사용자 프롬프트
415
+ systemPrompt = arg4;
416
+ prompt = arg5;
417
+ } else if (arg4) {
418
+ // 4번째 인자만 있으면: arg4=사용자 프롬프트 (시스템 프롬프트는 기본값)
419
+ prompt = arg4;
420
+ } else {
421
+ // Hook에서 호출: stdin으로 JSON 입력 (fallback)
422
+ let inputData = '';
423
+ for await (const chunk of process.stdin) {
424
+ inputData += chunk;
425
+ }
426
+
427
+ try {
428
+ const parsed = JSON.parse(inputData);
429
+ prompt = parsed.prompt;
430
+ } catch {
431
+ console.log(`[${provider.toUpperCase()}] Error: Invalid JSON input`);
432
+ return;
433
+ }
434
+ }
435
+ }
436
+
437
+ // 접두사 제거
438
+ const prefixPatterns = {
439
+ gpt: /^(gpt[-.\s]|지피티-|vibe-gpt-)\s*/i,
440
+ 'gpt-codex': /^(gpt[-.\s]|지피티-|vibe-gpt-)\s*/i,
441
+ gemini: /^(gemini[-.\s]|제미나이-|vibe-gemini-)\s*/i,
442
+ };
443
+ const cleanPrompt = prompt.replace(prefixPatterns[provider] || /^/, '').trim();
444
+ const jsonMode = mode === 'orchestrate-json';
445
+
446
+ // Provider chain: primary → cross fallback
447
+ // gpt-codex fallback: gpt-codex gemini (codex는 full gpt로 fallback하지 않음)
448
+ const providerLabels = { gpt: 'GPT', 'gpt-codex': 'GPT Codex', gemini: 'Gemini' };
449
+ const isGpt = provider === 'gpt' || provider === 'gpt-codex';
450
+ const providerChain = isGpt
451
+ ? [provider, 'gemini']
452
+ : ['gemini', 'gpt'];
453
+
454
+ for (const currentProvider of providerChain) {
455
+ const label = providerLabels[currentProvider] || currentProvider.toUpperCase();
456
+ const result = await callWithRetry(currentProvider, cleanPrompt, systemPrompt, jsonMode);
457
+
458
+ if (result.success) {
459
+ console.log(`${label} response: ${result.result}`);
460
+ return;
461
+ }
462
+
463
+ // Log failure and try fallback
464
+ if (currentProvider !== providerChain[providerChain.length - 1]) {
465
+ const nextProvider = providerChain[providerChain.indexOf(currentProvider) + 1];
466
+ const nextLabel = providerLabels[nextProvider] || nextProvider.toUpperCase();
467
+ console.error(`[${currentProvider.toUpperCase()}] Failed: ${result.error}. Falling back to ${nextLabel}...`);
468
+ } else {
469
+ // All providers failed
470
+ console.log(`[LLM] Error: All providers failed. Last error: ${result.error}`);
471
+ }
472
+ }
473
+ }
474
+
475
+ main();