@su-record/vibe 2.7.10 → 2.7.12

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 (282) hide show
  1. package/.env.example +37 -37
  2. package/CLAUDE.md +126 -222
  3. package/LICENSE +21 -21
  4. package/README.md +580 -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 +266 -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 +260 -260
  54. package/commands/vibe.run.md +83 -0
  55. package/commands/vibe.spec.review.md +558 -558
  56. package/commands/vibe.utils.md +413 -413
  57. package/commands/vibe.voice.md +79 -79
  58. package/dist/cli/auth.d.ts +1 -1
  59. package/dist/cli/auth.d.ts.map +1 -1
  60. package/dist/cli/auth.js +15 -7
  61. package/dist/cli/auth.js.map +1 -1
  62. package/dist/cli/collaborator.js +52 -52
  63. package/dist/cli/commands/evolution.js +12 -12
  64. package/dist/cli/commands/index.d.ts +1 -0
  65. package/dist/cli/commands/index.d.ts.map +1 -1
  66. package/dist/cli/commands/index.js +1 -0
  67. package/dist/cli/commands/index.js.map +1 -1
  68. package/dist/cli/commands/info.d.ts.map +1 -1
  69. package/dist/cli/commands/info.js +62 -56
  70. package/dist/cli/commands/info.js.map +1 -1
  71. package/dist/cli/commands/init.d.ts.map +1 -1
  72. package/dist/cli/commands/init.js +9 -6
  73. package/dist/cli/commands/init.js.map +1 -1
  74. package/dist/cli/commands/remove.js +14 -14
  75. package/dist/cli/commands/sentinel.js +27 -27
  76. package/dist/cli/commands/skills.d.ts +13 -0
  77. package/dist/cli/commands/skills.d.ts.map +1 -0
  78. package/dist/cli/commands/skills.js +83 -0
  79. package/dist/cli/commands/skills.js.map +1 -0
  80. package/dist/cli/commands/slack.js +10 -10
  81. package/dist/cli/commands/telegram.js +12 -12
  82. package/dist/cli/commands/update.d.ts.map +1 -1
  83. package/dist/cli/commands/update.js +3 -0
  84. package/dist/cli/commands/update.js.map +1 -1
  85. package/dist/cli/detect.js +32 -32
  86. package/dist/cli/index.d.ts.map +1 -1
  87. package/dist/cli/index.js +64 -47
  88. package/dist/cli/index.js.map +1 -1
  89. package/dist/cli/llm/claude-commands.js +16 -16
  90. package/dist/cli/llm/config.js +18 -18
  91. package/dist/cli/llm/gemini-commands.js +47 -47
  92. package/dist/cli/llm/gpt-commands.js +19 -19
  93. package/dist/cli/llm/help.js +21 -21
  94. package/dist/cli/postinstall/constants.d.ts +8 -0
  95. package/dist/cli/postinstall/constants.d.ts.map +1 -1
  96. package/dist/cli/postinstall/constants.js +33 -0
  97. package/dist/cli/postinstall/constants.js.map +1 -1
  98. package/dist/cli/postinstall/cursor-agents.js +32 -32
  99. package/dist/cli/postinstall/cursor-rules.js +83 -83
  100. package/dist/cli/postinstall/cursor-skills.js +743 -743
  101. package/dist/cli/postinstall/index.d.ts +1 -1
  102. package/dist/cli/postinstall/index.d.ts.map +1 -1
  103. package/dist/cli/postinstall/index.js +1 -1
  104. package/dist/cli/postinstall/index.js.map +1 -1
  105. package/dist/cli/setup/ProjectSetup.d.ts.map +1 -1
  106. package/dist/cli/setup/ProjectSetup.js +5 -0
  107. package/dist/cli/setup/ProjectSetup.js.map +1 -1
  108. package/dist/cli/setup/Provisioner.js +42 -42
  109. package/dist/cli/types.d.ts +1 -0
  110. package/dist/cli/types.d.ts.map +1 -1
  111. package/dist/infra/lib/DeepInit.js +24 -24
  112. package/dist/infra/lib/IterationTracker.js +11 -11
  113. package/dist/infra/lib/PythonParser.js +108 -108
  114. package/dist/infra/lib/ReviewRace.js +96 -96
  115. package/dist/infra/lib/SkillFrontmatter.js +28 -28
  116. package/dist/infra/lib/SkillQualityGate.js +9 -9
  117. package/dist/infra/lib/SkillRepository.js +159 -159
  118. package/dist/infra/lib/UltraQA.js +99 -99
  119. package/dist/infra/lib/autonomy/AuditStore.js +41 -41
  120. package/dist/infra/lib/autonomy/ConfirmationStore.js +30 -30
  121. package/dist/infra/lib/autonomy/EventOutbox.js +38 -38
  122. package/dist/infra/lib/autonomy/PolicyEngine.js +18 -18
  123. package/dist/infra/lib/autonomy/SecuritySentinel.js +1 -1
  124. package/dist/infra/lib/autonomy/SuggestionStore.js +33 -33
  125. package/dist/infra/lib/embedding/VectorStore.js +22 -22
  126. package/dist/infra/lib/evolution/AgentAnalyzer.js +10 -10
  127. package/dist/infra/lib/evolution/DescriptionOptimizer.d.ts +79 -0
  128. package/dist/infra/lib/evolution/DescriptionOptimizer.d.ts.map +1 -0
  129. package/dist/infra/lib/evolution/DescriptionOptimizer.js +259 -0
  130. package/dist/infra/lib/evolution/DescriptionOptimizer.js.map +1 -0
  131. package/dist/infra/lib/evolution/GenerationRegistry.js +36 -36
  132. package/dist/infra/lib/evolution/InsightStore.js +90 -90
  133. package/dist/infra/lib/evolution/RollbackManager.js +5 -5
  134. package/dist/infra/lib/evolution/SkillBenchmark.d.ts +81 -0
  135. package/dist/infra/lib/evolution/SkillBenchmark.d.ts.map +1 -0
  136. package/dist/infra/lib/evolution/SkillBenchmark.js +233 -0
  137. package/dist/infra/lib/evolution/SkillBenchmark.js.map +1 -0
  138. package/dist/infra/lib/evolution/SkillClassifier.d.ts +35 -0
  139. package/dist/infra/lib/evolution/SkillClassifier.d.ts.map +1 -0
  140. package/dist/infra/lib/evolution/SkillClassifier.js +167 -0
  141. package/dist/infra/lib/evolution/SkillClassifier.js.map +1 -0
  142. package/dist/infra/lib/evolution/SkillEvalRunner.d.ts +102 -0
  143. package/dist/infra/lib/evolution/SkillEvalRunner.d.ts.map +1 -0
  144. package/dist/infra/lib/evolution/SkillEvalRunner.js +256 -0
  145. package/dist/infra/lib/evolution/SkillEvalRunner.js.map +1 -0
  146. package/dist/infra/lib/evolution/SkillGapDetector.js +10 -10
  147. package/dist/infra/lib/evolution/UsageTracker.js +28 -28
  148. package/dist/infra/lib/evolution/__tests__/eval.test.d.ts +2 -0
  149. package/dist/infra/lib/evolution/__tests__/eval.test.d.ts.map +1 -0
  150. package/dist/infra/lib/evolution/__tests__/eval.test.js +539 -0
  151. package/dist/infra/lib/evolution/__tests__/eval.test.js.map +1 -0
  152. package/dist/infra/lib/evolution/index.d.ts +8 -0
  153. package/dist/infra/lib/evolution/index.d.ts.map +1 -1
  154. package/dist/infra/lib/evolution/index.js +5 -0
  155. package/dist/infra/lib/evolution/index.js.map +1 -1
  156. package/dist/infra/lib/gemini/constants.js +14 -14
  157. package/dist/infra/lib/gemini/orchestration.js +5 -5
  158. package/dist/infra/lib/gpt/oauth.js +44 -44
  159. package/dist/infra/lib/gpt/orchestration.js +4 -4
  160. package/dist/infra/lib/memory/KnowledgeGraph.js +4 -4
  161. package/dist/infra/lib/memory/MemorySearch.js +57 -57
  162. package/dist/infra/lib/memory/MemoryStorage.js +181 -181
  163. package/dist/infra/lib/memory/ObservationStore.js +28 -28
  164. package/dist/infra/lib/memory/ReflectionStore.js +30 -30
  165. package/dist/infra/lib/memory/SessionRAGRetriever.js +7 -7
  166. package/dist/infra/lib/memory/SessionRAGStore.js +225 -225
  167. package/dist/infra/lib/memory/SessionSummarizer.js +9 -9
  168. package/dist/infra/orchestrator/AgentManager.js +12 -12
  169. package/dist/infra/orchestrator/AgentRegistry.js +65 -65
  170. package/dist/infra/orchestrator/MultiLlmResearch.js +8 -8
  171. package/dist/infra/orchestrator/SwarmOrchestrator.test.js +16 -16
  172. package/dist/infra/orchestrator/parallelResearch.js +24 -24
  173. package/dist/tools/convention/analyzeComplexity.test.js +115 -115
  174. package/dist/tools/convention/validateCodeQuality.test.js +104 -104
  175. package/dist/tools/memory/createMemoryTimeline.js +10 -10
  176. package/dist/tools/memory/getMemoryGraph.js +12 -12
  177. package/dist/tools/memory/getSessionContext.js +9 -9
  178. package/dist/tools/memory/linkMemories.js +14 -14
  179. package/dist/tools/memory/listMemories.js +4 -4
  180. package/dist/tools/memory/recallMemory.js +4 -4
  181. package/dist/tools/memory/saveMemory.js +4 -4
  182. package/dist/tools/memory/searchMemoriesAdvanced.js +23 -23
  183. package/dist/tools/semantic/analyzeDependencyGraph.js +12 -12
  184. package/dist/tools/semantic/astGrep.test.js +6 -6
  185. package/dist/tools/spec/prdParser.test.js +171 -171
  186. package/dist/tools/spec/specGenerator.js +169 -169
  187. package/dist/tools/spec/traceabilityMatrix.js +64 -64
  188. package/dist/tools/spec/traceabilityMatrix.test.js +28 -28
  189. package/hooks/gemini-hooks.json +73 -73
  190. package/hooks/hooks.json +137 -137
  191. package/hooks/scripts/code-check.js +70 -70
  192. package/hooks/scripts/context-save.js +212 -212
  193. package/hooks/scripts/hud-status.js +291 -291
  194. package/hooks/scripts/keyword-detector.js +214 -214
  195. package/hooks/scripts/llm-orchestrate.js +646 -646
  196. package/hooks/scripts/post-edit.js +32 -32
  197. package/hooks/scripts/pre-tool-guard.js +125 -125
  198. package/hooks/scripts/prompt-dispatcher.js +185 -185
  199. package/hooks/scripts/sentinel-guard.js +104 -104
  200. package/hooks/scripts/session-start.js +106 -106
  201. package/hooks/scripts/stop-notify.js +209 -209
  202. package/hooks/scripts/utils.js +100 -100
  203. package/languages/csharp-unity.md +515 -515
  204. package/languages/gdscript-godot.md +470 -470
  205. package/languages/ruby-rails.md +489 -489
  206. package/languages/typescript-angular.md +433 -433
  207. package/languages/typescript-astro.md +416 -416
  208. package/languages/typescript-electron.md +406 -406
  209. package/languages/typescript-nestjs.md +524 -524
  210. package/languages/typescript-svelte.md +407 -407
  211. package/languages/typescript-tauri.md +365 -365
  212. package/package.json +121 -121
  213. package/skills/agents-md/SKILL.md +120 -120
  214. package/skills/arch-guard/SKILL.md +180 -0
  215. package/skills/brand-assets/SKILL.md +146 -146
  216. package/skills/capability-loop/SKILL.md +167 -0
  217. package/skills/characterization-test/SKILL.md +206 -206
  218. package/skills/commerce-patterns/SKILL.md +59 -59
  219. package/skills/commit-push-pr/SKILL.md +75 -75
  220. package/skills/context7-usage/SKILL.md +105 -105
  221. package/skills/core-capabilities/SKILL.md +48 -48
  222. package/skills/e2e-commerce/SKILL.md +57 -57
  223. package/skills/exec-plan/SKILL.md +147 -0
  224. package/skills/frontend-design/SKILL.md +73 -73
  225. package/skills/git-worktree/SKILL.md +72 -72
  226. package/skills/handoff/SKILL.md +109 -109
  227. package/skills/parallel-research/SKILL.md +87 -87
  228. package/skills/priority-todos/SKILL.md +63 -63
  229. package/skills/seo-checklist/SKILL.md +57 -57
  230. package/skills/techdebt/SKILL.md +122 -122
  231. package/skills/tool-fallback/SKILL.md +103 -103
  232. package/skills/typescript-advanced-types/SKILL.md +65 -65
  233. package/skills/ui-ux-pro-max/SKILL.md +206 -206
  234. package/skills/vercel-react-best-practices/SKILL.md +59 -59
  235. package/skills/video-production/SKILL.md +51 -51
  236. package/vibe/config.json +29 -29
  237. package/vibe/constitution.md +227 -227
  238. package/vibe/rules/principles/communication-guide.md +98 -98
  239. package/vibe/rules/principles/development-philosophy.md +52 -52
  240. package/vibe/rules/principles/quick-start.md +102 -102
  241. package/vibe/rules/quality/bdd-contract-testing.md +393 -393
  242. package/vibe/rules/quality/checklist.md +276 -276
  243. package/vibe/rules/quality/performance.md +236 -236
  244. package/vibe/rules/quality/testing-strategy.md +440 -440
  245. package/vibe/rules/standards/anti-patterns.md +541 -541
  246. package/vibe/rules/standards/code-structure.md +291 -291
  247. package/vibe/rules/standards/complexity-metrics.md +313 -313
  248. package/vibe/rules/standards/git-workflow.md +237 -237
  249. package/vibe/rules/standards/naming-conventions.md +198 -198
  250. package/vibe/rules/standards/security.md +305 -305
  251. package/vibe/rules/writing/document-style.md +74 -74
  252. package/vibe/setup.sh +31 -31
  253. package/vibe/templates/constitution-template.md +252 -252
  254. package/vibe/templates/contract-backend-template.md +526 -526
  255. package/vibe/templates/contract-frontend-template.md +599 -599
  256. package/vibe/templates/feature-template.md +96 -96
  257. package/vibe/templates/spec-template.md +221 -221
  258. package/vibe/ui-ux-data/charts.csv +26 -26
  259. package/vibe/ui-ux-data/colors.csv +97 -97
  260. package/vibe/ui-ux-data/icons.csv +101 -101
  261. package/vibe/ui-ux-data/landing.csv +31 -31
  262. package/vibe/ui-ux-data/products.csv +96 -96
  263. package/vibe/ui-ux-data/react-performance.csv +45 -45
  264. package/vibe/ui-ux-data/stacks/astro.csv +54 -54
  265. package/vibe/ui-ux-data/stacks/flutter.csv +53 -53
  266. package/vibe/ui-ux-data/stacks/html-tailwind.csv +56 -56
  267. package/vibe/ui-ux-data/stacks/jetpack-compose.csv +53 -53
  268. package/vibe/ui-ux-data/stacks/nextjs.csv +53 -53
  269. package/vibe/ui-ux-data/stacks/nuxt-ui.csv +51 -51
  270. package/vibe/ui-ux-data/stacks/nuxtjs.csv +59 -59
  271. package/vibe/ui-ux-data/stacks/react-native.csv +52 -52
  272. package/vibe/ui-ux-data/stacks/react.csv +54 -54
  273. package/vibe/ui-ux-data/stacks/shadcn.csv +61 -61
  274. package/vibe/ui-ux-data/stacks/svelte.csv +54 -54
  275. package/vibe/ui-ux-data/stacks/swiftui.csv +51 -51
  276. package/vibe/ui-ux-data/stacks/vue.csv +50 -50
  277. package/vibe/ui-ux-data/styles.csv +68 -68
  278. package/vibe/ui-ux-data/typography.csv +57 -57
  279. package/vibe/ui-ux-data/ui-reasoning.csv +101 -101
  280. package/vibe/ui-ux-data/ux-guidelines.csv +99 -99
  281. package/vibe/ui-ux-data/version.json +31 -31
  282. package/vibe/ui-ux-data/web-interface.csv +31 -31
@@ -1,646 +1,646 @@
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 (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();