@trac3er/oh-my-god 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (229) hide show
  1. package/.claude-plugin/marketplace.json +36 -0
  2. package/.claude-plugin/plugin.json +23 -0
  3. package/.claude-plugin/scripts/install.sh +49 -0
  4. package/.claude-plugin/scripts/uninstall.sh +80 -0
  5. package/.claude-plugin/scripts/update.sh +84 -0
  6. package/.mcp.json +20 -0
  7. package/LICENSE +21 -0
  8. package/OMG-setup.sh +1093 -0
  9. package/README.md +335 -0
  10. package/THIRD_PARTY_NOTICES.md +24 -0
  11. package/UPSTREAM_DIFF.md +20 -0
  12. package/agents/__init__.py +1 -0
  13. package/agents/_model_roles.yaml +26 -0
  14. package/agents/designer.md +67 -0
  15. package/agents/explore.md +60 -0
  16. package/agents/model_roles.py +196 -0
  17. package/agents/omg-api-builder.md +23 -0
  18. package/agents/omg-architect-mode.md +43 -0
  19. package/agents/omg-architect.md +13 -0
  20. package/agents/omg-backend-engineer.md +43 -0
  21. package/agents/omg-critic.md +16 -0
  22. package/agents/omg-database-engineer.md +43 -0
  23. package/agents/omg-escalation-router.md +17 -0
  24. package/agents/omg-executor.md +12 -0
  25. package/agents/omg-frontend-designer.md +42 -0
  26. package/agents/omg-implement-mode.md +50 -0
  27. package/agents/omg-infra-engineer.md +43 -0
  28. package/agents/omg-qa-tester.md +16 -0
  29. package/agents/omg-research-mode.md +43 -0
  30. package/agents/omg-security-auditor.md +43 -0
  31. package/agents/omg-testing-engineer.md +43 -0
  32. package/agents/plan.md +80 -0
  33. package/agents/quick_task.md +64 -0
  34. package/agents/reviewer.md +83 -0
  35. package/agents/task.md +71 -0
  36. package/commands/OMG:ccg.md +22 -0
  37. package/commands/OMG:compat.md +57 -0
  38. package/commands/OMG:crazy.md +125 -0
  39. package/commands/OMG:domain-init.md +11 -0
  40. package/commands/OMG:escalate.md +52 -0
  41. package/commands/OMG:health-check.md +45 -0
  42. package/commands/OMG:init.md +134 -0
  43. package/commands/OMG:mode.md +44 -0
  44. package/commands/OMG:project-init.md +11 -0
  45. package/commands/OMG:ralph-start.md +43 -0
  46. package/commands/OMG:ralph-stop.md +23 -0
  47. package/commands/OMG:teams.md +39 -0
  48. package/commands/ai-commit.md +113 -0
  49. package/commands/ccg.md +9 -0
  50. package/commands/create-agent.md +183 -0
  51. package/commands/omc-teams.md +9 -0
  52. package/commands/session-branch.md +85 -0
  53. package/commands/session-fork.md +53 -0
  54. package/commands/session-merge.md +134 -0
  55. package/commands/theme.md +44 -0
  56. package/config/lsp_languages.yaml +324 -0
  57. package/config/themes/catppuccin-frappe.yaml +14 -0
  58. package/config/themes/catppuccin-latte.yaml +14 -0
  59. package/config/themes/catppuccin-macchiato.yaml +14 -0
  60. package/config/themes/catppuccin-mocha.yaml +14 -0
  61. package/config/themes/dracula.yaml +14 -0
  62. package/config/themes/gruvbox-dark.yaml +14 -0
  63. package/config/themes/nord.yaml +14 -0
  64. package/config/themes/one-dark.yaml +14 -0
  65. package/config/themes/solarized-dark.yaml +14 -0
  66. package/config/themes/tokyo-night.yaml +14 -0
  67. package/control_plane/__init__.py +2 -0
  68. package/control_plane/openapi.yaml +109 -0
  69. package/control_plane/server.py +107 -0
  70. package/control_plane/service.py +148 -0
  71. package/crates/omg-natives/Cargo.toml +17 -0
  72. package/crates/omg-natives/src/clipboard.rs +5 -0
  73. package/crates/omg-natives/src/glob.rs +15 -0
  74. package/crates/omg-natives/src/grep.rs +15 -0
  75. package/crates/omg-natives/src/highlight.rs +15 -0
  76. package/crates/omg-natives/src/html.rs +14 -0
  77. package/crates/omg-natives/src/image.rs +5 -0
  78. package/crates/omg-natives/src/keys.rs +5 -0
  79. package/crates/omg-natives/src/lib.rs +36 -0
  80. package/crates/omg-natives/src/prof.rs +5 -0
  81. package/crates/omg-natives/src/ps.rs +5 -0
  82. package/crates/omg-natives/src/shell.rs +5 -0
  83. package/crates/omg-natives/src/task.rs +5 -0
  84. package/crates/omg-natives/src/text.rs +14 -0
  85. package/hooks/_agent_registry.py +421 -0
  86. package/hooks/_budget.py +31 -0
  87. package/hooks/_common.py +476 -0
  88. package/hooks/_learnings.py +126 -0
  89. package/hooks/_memory.py +103 -0
  90. package/hooks/circuit-breaker.py +270 -0
  91. package/hooks/config-guard.py +163 -0
  92. package/hooks/context_pressure.py +53 -0
  93. package/hooks/credential_store.py +801 -0
  94. package/hooks/fetch-rate-limits.py +212 -0
  95. package/hooks/firewall.py +48 -0
  96. package/hooks/hashline-formatter-bridge.py +224 -0
  97. package/hooks/hashline-injector.py +273 -0
  98. package/hooks/hashline-validator.py +216 -0
  99. package/hooks/idle-detector.py +95 -0
  100. package/hooks/intentgate-keyword-detector.py +188 -0
  101. package/hooks/magic-keyword-router.py +195 -0
  102. package/hooks/policy_engine.py +310 -0
  103. package/hooks/post-tool-failure.py +19 -0
  104. package/hooks/post-write.py +199 -0
  105. package/hooks/pre-compact.py +204 -0
  106. package/hooks/pre-tool-inject.py +98 -0
  107. package/hooks/prompt-enhancer.py +672 -0
  108. package/hooks/quality-runner.py +191 -0
  109. package/hooks/secret-guard.py +47 -0
  110. package/hooks/session-end-capture.py +137 -0
  111. package/hooks/session-start.py +275 -0
  112. package/hooks/shadow_manager.py +297 -0
  113. package/hooks/state_migration.py +209 -0
  114. package/hooks/stop-gate.py +7 -0
  115. package/hooks/stop_dispatcher.py +929 -0
  116. package/hooks/test-validator.py +138 -0
  117. package/hooks/todo-state-tracker.py +114 -0
  118. package/hooks/tool-ledger.py +126 -0
  119. package/hooks/trust_review.py +524 -0
  120. package/install.sh +9 -0
  121. package/omg_natives/__init__.py +186 -0
  122. package/omg_natives/_bindings.py +165 -0
  123. package/omg_natives/clipboard.py +36 -0
  124. package/omg_natives/glob.py +42 -0
  125. package/omg_natives/grep.py +61 -0
  126. package/omg_natives/highlight.py +54 -0
  127. package/omg_natives/html.py +157 -0
  128. package/omg_natives/image.py +51 -0
  129. package/omg_natives/keys.py +46 -0
  130. package/omg_natives/prof.py +39 -0
  131. package/omg_natives/ps.py +93 -0
  132. package/omg_natives/shell.py +58 -0
  133. package/omg_natives/task.py +41 -0
  134. package/omg_natives/text.py +50 -0
  135. package/package.json +26 -0
  136. package/plugins/README.md +82 -0
  137. package/plugins/advanced/commands/OMG:code-review.md +114 -0
  138. package/plugins/advanced/commands/OMG:deep-plan.md +221 -0
  139. package/plugins/advanced/commands/OMG:handoff.md +115 -0
  140. package/plugins/advanced/commands/OMG:learn.md +110 -0
  141. package/plugins/advanced/commands/OMG:maintainer.md +31 -0
  142. package/plugins/advanced/commands/OMG:ralph-start.md +43 -0
  143. package/plugins/advanced/commands/OMG:ralph-stop.md +23 -0
  144. package/plugins/advanced/commands/OMG:security-review.md +119 -0
  145. package/plugins/advanced/commands/OMG:sequential-thinking.md +20 -0
  146. package/plugins/advanced/commands/OMG:ship.md +46 -0
  147. package/plugins/advanced/plugin.json +96 -0
  148. package/plugins/core/plugin.json +82 -0
  149. package/pytest.ini +5 -0
  150. package/registry/__init__.py +1 -0
  151. package/registry/verify_artifact.py +90 -0
  152. package/rules/contextual/architect-mode.md +9 -0
  153. package/rules/contextual/big-picture.md +20 -0
  154. package/rules/contextual/code-hygiene.md +26 -0
  155. package/rules/contextual/context-management.md +19 -0
  156. package/rules/contextual/context-minimization.md +32 -0
  157. package/rules/contextual/ddd-sdd.md +28 -0
  158. package/rules/contextual/dependency-safety.md +16 -0
  159. package/rules/contextual/doc-check.md +13 -0
  160. package/rules/contextual/implement-mode.md +9 -0
  161. package/rules/contextual/infra-safety.md +14 -0
  162. package/rules/contextual/outside-in.md +13 -0
  163. package/rules/contextual/persistent-mode.md +24 -0
  164. package/rules/contextual/research-mode.md +9 -0
  165. package/rules/contextual/security-domains.md +25 -0
  166. package/rules/contextual/vision-detection.md +27 -0
  167. package/rules/contextual/web-search.md +25 -0
  168. package/rules/contextual/write-verify.md +23 -0
  169. package/rules/core/00-truth.md +20 -0
  170. package/rules/core/01-surgical.md +19 -0
  171. package/rules/core/02-circuit-breaker.md +22 -0
  172. package/rules/core/03-ensemble.md +28 -0
  173. package/rules/core/04-testing.md +30 -0
  174. package/runtime/__init__.py +32 -0
  175. package/runtime/adapters/__init__.py +13 -0
  176. package/runtime/adapters/claude.py +60 -0
  177. package/runtime/adapters/gpt.py +53 -0
  178. package/runtime/adapters/local.py +53 -0
  179. package/runtime/business_workflow.py +220 -0
  180. package/runtime/compat.py +1299 -0
  181. package/runtime/custom_agent_loader.py +366 -0
  182. package/runtime/dispatcher.py +47 -0
  183. package/runtime/ecosystem.py +371 -0
  184. package/runtime/legacy_compat.py +7 -0
  185. package/runtime/omc_compat.py +7 -0
  186. package/runtime/omc_contract_snapshot.json +916 -0
  187. package/runtime/omg_compat_contract_snapshot.json +916 -0
  188. package/runtime/subagent_dispatcher.py +362 -0
  189. package/runtime/team_router.py +838 -0
  190. package/scripts/check-omc-contract-snapshot.py +12 -0
  191. package/scripts/check-omg-compat-contract-snapshot.py +137 -0
  192. package/scripts/check-omg-standalone-clean.py +102 -0
  193. package/scripts/legacy_to_omg_migrate.py +29 -0
  194. package/scripts/migrate-omc.py +464 -0
  195. package/scripts/omc_to_omg_migrate.py +12 -0
  196. package/scripts/omg.py +493 -0
  197. package/scripts/settings-merge.py +224 -0
  198. package/scripts/verify-no-omc.sh +5 -0
  199. package/scripts/verify-standalone.sh +21 -0
  200. package/templates/idea.yml +30 -0
  201. package/templates/policy.yaml +15 -0
  202. package/templates/profile.yaml +25 -0
  203. package/templates/runtime.yaml +12 -0
  204. package/templates/working-memory.md +17 -0
  205. package/tools/__init__.py +2 -0
  206. package/tools/browser_consent.py +289 -0
  207. package/tools/browser_stealth.py +481 -0
  208. package/tools/browser_tool.py +448 -0
  209. package/tools/changelog_generator.py +268 -0
  210. package/tools/commit_splitter.py +361 -0
  211. package/tools/config_discovery.py +151 -0
  212. package/tools/config_merger.py +449 -0
  213. package/tools/git_inspector.py +298 -0
  214. package/tools/lsp_client.py +275 -0
  215. package/tools/lsp_discovery.py +231 -0
  216. package/tools/lsp_operations.py +392 -0
  217. package/tools/python_repl.py +656 -0
  218. package/tools/python_sandbox.py +609 -0
  219. package/tools/search_providers/__init__.py +77 -0
  220. package/tools/search_providers/brave.py +115 -0
  221. package/tools/search_providers/exa.py +116 -0
  222. package/tools/search_providers/jina.py +104 -0
  223. package/tools/search_providers/perplexity.py +139 -0
  224. package/tools/search_providers/synthetic.py +74 -0
  225. package/tools/session_snapshot.py +736 -0
  226. package/tools/ssh_manager.py +912 -0
  227. package/tools/theme_engine.py +294 -0
  228. package/tools/theme_selector.py +137 -0
  229. package/tools/web_search.py +622 -0
@@ -0,0 +1,838 @@
1
+ """Internal team router for OMG standalone operation."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import dataclass, asdict
5
+ from datetime import datetime, timezone
6
+ from concurrent.futures import ThreadPoolExecutor, as_completed
7
+ import logging
8
+ import os
9
+ import re
10
+ import shutil
11
+ import subprocess
12
+ from typing import Any
13
+
14
+ # --- Path resolution (never relies on CWD) ---
15
+ _ROUTER_DIR = os.path.dirname(os.path.abspath(__file__))
16
+ _OMG_ROOT = os.path.dirname(_ROUTER_DIR)
17
+
18
+ _logger = logging.getLogger(__name__)
19
+
20
+ @dataclass
21
+ class TeamDispatchRequest:
22
+ target: str # codex | gemini | ccg | auto
23
+ problem: str
24
+ context: str = ""
25
+ files: list[str] | None = None
26
+ expected_outcome: str = ""
27
+
28
+
29
+ @dataclass
30
+ class TeamDispatchResult:
31
+ status: str
32
+ findings: list[str]
33
+ actions: list[str]
34
+ evidence: dict[str, Any]
35
+
36
+ def to_dict(self) -> dict[str, Any]:
37
+ out = asdict(self)
38
+ out["schema"] = "TeamDispatchResult"
39
+ return out
40
+
41
+
42
+ def _infer_target(problem: str) -> str:
43
+ p = problem.lower()
44
+ # Explicit target keywords should always win.
45
+ ccg_kw = bool(re.search(r"\bccg\b", p)) or "tri-track" in p or "tri track" in p
46
+ gemini_kw = bool(re.search(r"\bgemini\b", p))
47
+ codex_kw = bool(re.search(r"\bcodex\b", p))
48
+
49
+ if ccg_kw or (gemini_kw and codex_kw):
50
+ return "ccg"
51
+ if gemini_kw:
52
+ return "gemini"
53
+ if codex_kw:
54
+ return "codex"
55
+
56
+ ui_signals = ["ui", "ux", "layout", "css", "visual", "responsive", "frontend"]
57
+ code_signals = ["auth", "security", "backend", "debug", "performance", "algorithm"]
58
+ ccg_signals = [
59
+ "full-stack",
60
+ "full stack",
61
+ "front-end and back-end",
62
+ "frontend and backend",
63
+ "backend and frontend",
64
+ "cross-functional",
65
+ "review everything",
66
+ "architecture",
67
+ "system design",
68
+ "e2e",
69
+ "end-to-end",
70
+ ]
71
+
72
+ ui_hit = any(k in p for k in ui_signals)
73
+ code_hit = any(k in p for k in code_signals)
74
+ ccg_hit = any(k in p for k in ccg_signals)
75
+
76
+ if ccg_hit or (ui_hit and code_hit):
77
+ return "ccg"
78
+ if ui_hit:
79
+ return "gemini"
80
+ if code_hit:
81
+ return "codex"
82
+ return "codex"
83
+
84
+
85
+ def _check_tool_available(tool_name: str) -> bool:
86
+ """Return True if *tool_name* is on PATH, else log a warning."""
87
+ if shutil.which(tool_name) is not None:
88
+ return True
89
+ _logger.warning("Tool %r not found on PATH — skipping %s dispatch", tool_name, tool_name)
90
+ return False
91
+
92
+
93
+ def _run_tool(cmd: list[str], *, timeout: int = 30) -> subprocess.CompletedProcess[str]:
94
+ """Run an external tool with a mandatory timeout.
95
+
96
+ Every subprocess call in the team router MUST go through this helper
97
+ to guarantee the ``timeout`` parameter is always set.
98
+ """
99
+ return subprocess.run(
100
+ cmd,
101
+ capture_output=True,
102
+ text=True,
103
+ check=False,
104
+ timeout=timeout,
105
+ )
106
+
107
+
108
+ _TOOL_MAP: dict[str, str] = {
109
+ "codex": "codex",
110
+ "gemini": "gemini",
111
+ }
112
+
113
+ _INSTALL_HINTS: dict[str, str] = {
114
+ "codex": "Install Codex CLI: npm install -g @openai/codex",
115
+ "gemini": "Install Gemini CLI: npm install -g @google/gemini-cli",
116
+ }
117
+
118
+
119
+ def _auth_status_command(tool_name: str) -> list[str] | None:
120
+ if tool_name == "codex":
121
+ return ["codex", "auth", "status"]
122
+ if tool_name == "gemini":
123
+ return ["gemini", "auth", "status"]
124
+ return None
125
+
126
+
127
+ def _check_tool_auth(tool_name: str) -> tuple[bool | None, str]:
128
+ cmd = _auth_status_command(tool_name)
129
+ if cmd is None:
130
+ return None, "auth status check not supported"
131
+ try:
132
+ probe = _run_tool(cmd, timeout=15)
133
+ except subprocess.TimeoutExpired:
134
+ return None, "auth status check timed out"
135
+ except FileNotFoundError:
136
+ return False, "CLI is not installed"
137
+ except Exception as exc:
138
+ return None, f"auth status check failed: {exc}"
139
+
140
+ output = f"{probe.stdout}\n{probe.stderr}".lower()
141
+ if probe.returncode == 0:
142
+ if "not logged" in output or "not authenticated" in output or "login required" in output:
143
+ return False, "CLI is installed but not authenticated"
144
+ return True, "CLI is authenticated"
145
+
146
+ unsupported_markers = ("unknown command", "unrecognized", "invalid choice", "did you mean")
147
+ if any(marker in output for marker in unsupported_markers):
148
+ return None, "auth status subcommand is unavailable"
149
+ if "not logged" in output or "not authenticated" in output or "login" in output:
150
+ return False, "CLI is installed but not authenticated"
151
+ return None, f"unable to verify auth status (exit={probe.returncode})"
152
+
153
+
154
+ def _collect_cli_health(target: str) -> dict[str, dict[str, Any]]:
155
+ if target == "ccg":
156
+ providers = ("codex", "gemini")
157
+ elif target in ("codex", "gemini"):
158
+ providers = (target,)
159
+ else:
160
+ providers = tuple()
161
+
162
+ health: dict[str, dict[str, Any]] = {}
163
+ for provider in providers:
164
+ available = _check_tool_available(provider)
165
+ auth_ok: bool | None = None
166
+ auth_message = "CLI is not installed"
167
+ if available:
168
+ auth_ok, auth_message = _check_tool_auth(provider)
169
+ live_connection = bool(available and auth_ok is True)
170
+ health[provider] = {
171
+ "available": available,
172
+ "auth_ok": auth_ok,
173
+ "live_connection": live_connection,
174
+ "status_message": auth_message,
175
+ "install_hint": _INSTALL_HINTS.get(provider, ""),
176
+ }
177
+ return health
178
+
179
+
180
+ def dispatch_team(req: TeamDispatchRequest) -> TeamDispatchResult:
181
+ target = req.target.lower().strip()
182
+ if target == "auto":
183
+ target = _infer_target(req.problem)
184
+
185
+ findings = [f"Target router selected: {target}", f"Problem: {req.problem}"]
186
+ if req.files:
187
+ findings.append(f"Focus files: {', '.join(req.files[:8])}")
188
+ if req.expected_outcome:
189
+ findings.append(f"Expected: {req.expected_outcome}")
190
+
191
+ cli_health = _collect_cli_health(target)
192
+ for provider, info in cli_health.items():
193
+ if info.get("live_connection"):
194
+ findings.append(f"{provider} live connection: ready")
195
+ continue
196
+ if not info.get("available"):
197
+ findings.append(f"{provider} live connection: missing CLI ({info.get('install_hint', '').strip()})")
198
+ continue
199
+ findings.append(f"{provider} live connection: unavailable ({info.get('status_message', 'unknown status')})")
200
+
201
+ actions = []
202
+ if target == "codex":
203
+ actions.extend(
204
+ [
205
+ "Perform deep code-level analysis",
206
+ "Prioritize security and root-cause checks",
207
+ "Return fix strategy with verification commands",
208
+ ]
209
+ )
210
+ elif target == "gemini":
211
+ actions.extend(
212
+ [
213
+ "Perform UI/UX and visual structure review",
214
+ "Return accessibility and responsive design improvements",
215
+ "Return component-level edit suggestions",
216
+ ]
217
+ )
218
+ else:
219
+ actions.extend(
220
+ [
221
+ "Run parallel backend and frontend review tracks",
222
+ "Synthesize cross-cutting findings",
223
+ "Return merged action plan with dependency order",
224
+ ]
225
+ )
226
+
227
+ evidence = {
228
+ "target": target,
229
+ "generated_at": datetime.now(timezone.utc).isoformat(),
230
+ "context_length": len(req.context or ""),
231
+ "file_count": len(req.files or []),
232
+ "cli_health": cli_health,
233
+ "live_connection": all(h.get("live_connection") for h in cli_health.values()) if cli_health else True,
234
+ }
235
+
236
+ return TeamDispatchResult(status="ok", findings=findings, actions=actions, evidence=evidence)
237
+
238
+
239
+ def package_prompt(agent_name: str, user_prompt: str, project_dir: str) -> str:
240
+ """Build structured prompt for external CLI dispatch."""
241
+ # Import here to avoid circular imports at module level
242
+ import sys as _sys
243
+
244
+ _hooks_dir = os.path.join(
245
+ os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
246
+ "hooks",
247
+ )
248
+ if _hooks_dir not in _sys.path:
249
+ _sys.path.insert(0, _hooks_dir)
250
+ try:
251
+ from _agent_registry import AGENT_REGISTRY # pyright: ignore[reportMissingImports]
252
+
253
+ agent = AGENT_REGISTRY.get(agent_name, {})
254
+ description = agent.get("description", f"{agent_name} specialist")
255
+ agent = AGENT_REGISTRY.get(agent_name, {})
256
+ description = agent.get("description", f"{agent_name} specialist")
257
+ model_version = agent.get("model_version", "not specified")
258
+ return (
259
+ f"You are a {description}\n\n"
260
+ f"Model: {model_version}\n"
261
+ f"Project: {project_dir}\n"
262
+ f"Task: {user_prompt}\n\n"
263
+ f"Constraints: Follow existing patterns. No hardcoded secrets. Verify changes."
264
+ )
265
+ except Exception:
266
+ return f"Task: {user_prompt}\nProject: {project_dir}"
267
+
268
+
269
+ def invoke_codex(prompt: str, project_dir: str, timeout: int = 120) -> dict[str, Any]:
270
+ """Invoke codex-cli as subprocess. Returns result dict with model/output/exit_code or error/fallback."""
271
+ if not _check_tool_available("codex"):
272
+ return {"error": "codex-cli not found", "fallback": "claude"}
273
+ try:
274
+ result = _run_tool(
275
+ ["codex", "exec", "--json", prompt],
276
+ timeout=timeout,
277
+ )
278
+ return {
279
+ "model": "codex-cli",
280
+ "output": result.stdout,
281
+ "exit_code": result.returncode,
282
+ }
283
+ except subprocess.TimeoutExpired:
284
+ return {"error": "codex-cli timeout", "fallback": "claude"}
285
+ except FileNotFoundError:
286
+ return {"error": "codex-cli not found", "fallback": "claude"}
287
+ except Exception as exc:
288
+ return {"error": str(exc), "fallback": "claude"}
289
+
290
+
291
+ def invoke_gemini(prompt: str, project_dir: str, timeout: int = 120) -> dict[str, Any]:
292
+ """Invoke gemini-cli as subprocess. Returns result dict with model/output/exit_code or error/fallback."""
293
+ if not _check_tool_available("gemini"):
294
+ return {"error": "gemini-cli not found", "fallback": "claude"}
295
+ try:
296
+ result = _run_tool(
297
+ ["gemini", "-p", prompt],
298
+ timeout=timeout,
299
+ )
300
+ return {
301
+ "model": "gemini-cli",
302
+ "output": result.stdout,
303
+ "exit_code": result.returncode,
304
+ }
305
+ except subprocess.TimeoutExpired:
306
+ return {"error": "gemini-cli timeout", "fallback": "claude"}
307
+ except FileNotFoundError:
308
+ return {"error": "gemini-cli not found", "fallback": "claude"}
309
+ except Exception as exc:
310
+ return {"error": str(exc), "fallback": "claude"}
311
+
312
+
313
+ def dispatch_to_model(agent_name: str, user_prompt: str, project_dir: str) -> dict[str, Any]:
314
+ """Dispatch a task to the preferred model for this agent.
315
+
316
+ Returns result dict. If preferred model unavailable, returns fallback dict.
317
+ """
318
+ import sys as _sys
319
+
320
+ _hooks_dir = os.path.join(
321
+ os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
322
+ "hooks",
323
+ )
324
+ if _hooks_dir not in _sys.path:
325
+ _sys.path.insert(0, _hooks_dir)
326
+ try:
327
+ from _agent_registry import AGENT_REGISTRY, detect_available_models # pyright: ignore[reportMissingImports]
328
+
329
+ agent = AGENT_REGISTRY.get(agent_name)
330
+ if not agent:
331
+ return {"error": f"Unknown agent: {agent_name}", "fallback": "claude"}
332
+
333
+ available = detect_available_models()
334
+ preferred = agent.get("preferred_model", "claude")
335
+ packaged = package_prompt(agent_name, user_prompt, project_dir)
336
+
337
+ if preferred == "codex-cli" and available.get("codex-cli"):
338
+ return invoke_codex(packaged, project_dir)
339
+ if preferred == "gemini-cli" and available.get("gemini-cli"):
340
+ return invoke_gemini(packaged, project_dir)
341
+ # Fallback: use Claude native task() dispatch
342
+ return {
343
+ "fallback": "claude",
344
+ "category": agent.get("task_category", "deep"),
345
+ "skills": agent.get("skills", []),
346
+ "model_version": agent.get("model_version", "unknown"),
347
+ }
348
+ except Exception as exc:
349
+ return {"error": str(exc), "fallback": "claude"}
350
+
351
+
352
+ def get_core_agent_model(agent_name: str) -> dict[str, Any] | None:
353
+ """Get model preference for a core (non-keyword-matched) agent."""
354
+ import sys as _sys
355
+ _hooks_dir = os.path.join(
356
+ os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
357
+ "hooks",
358
+ )
359
+ if _hooks_dir not in _sys.path:
360
+ _sys.path.insert(0, _hooks_dir)
361
+ try:
362
+ from _agent_registry import CORE_AGENT_MODELS # pyright: ignore[reportMissingImports]
363
+ return CORE_AGENT_MODELS.get(agent_name)
364
+ except Exception:
365
+ return None
366
+
367
+
368
+
369
+ def execute_agents_sequentially(
370
+ agent_tasks: list[dict[str, Any]],
371
+ project_dir: str,
372
+ timeout_per_agent: int = 120
373
+ ) -> list[dict[str, Any]]:
374
+ """Execute agents sequentially (one at a time) for CRAZY mode.
375
+
376
+ Args:
377
+ agent_tasks: List of {agent_name, prompt, order} dicts
378
+ project_dir: Working directory
379
+ timeout_per_agent: Timeout for each agent invocation
380
+
381
+ Returns:
382
+ List of results in execution order
383
+ """
384
+ # Sort by order if specified
385
+ sorted_tasks = sorted(agent_tasks, key=lambda x: x.get("order", 0))
386
+
387
+ results: list[dict[str, Any]] = []
388
+
389
+ for task in sorted_tasks:
390
+ agent_name = task.get("agent_name", "executor")
391
+ prompt = task.get("prompt", "")
392
+
393
+ print(f"[CRAZY] Launching {agent_name}...")
394
+
395
+ # Dispatch to the appropriate model
396
+ result = dispatch_to_model(agent_name, prompt, project_dir)
397
+
398
+ if result.get("fallback") == "claude":
399
+ print(f"[CRAZY] {agent_name} using Claude (native)")
400
+ status = "fallback-claude"
401
+ elif "error" in result:
402
+ print(f"[CRAZY] {agent_name} error: {result['error']}")
403
+ status = "error"
404
+ else:
405
+ print(f"[CRAZY] {agent_name} completed (exit={result.get('exit_code', 'unknown')})")
406
+ status = "completed" if result.get("exit_code") == 0 else "failed"
407
+
408
+ results.append({
409
+ "agent": agent_name,
410
+ "order": task.get("order", 0),
411
+ "status": status,
412
+ **result
413
+ })
414
+
415
+ return results
416
+
417
+
418
+ def execute_agents_parallel(
419
+ agent_tasks: list[dict[str, Any]],
420
+ project_dir: str,
421
+ timeout_per_agent: int = 120,
422
+ ) -> list[dict[str, Any]]:
423
+ indexed_tasks: list[tuple[int, int, dict[str, Any]]] = [
424
+ (idx, int(task.get("order", 0)), task) for idx, task in enumerate(agent_tasks)
425
+ ]
426
+ sorted_tasks = sorted(indexed_tasks, key=lambda x: (x[1], x[0]))
427
+ if not sorted_tasks:
428
+ return []
429
+
430
+ max_workers = min(len(sorted_tasks), 5)
431
+ results_by_index: dict[int, dict[str, Any]] = {}
432
+
433
+ with ThreadPoolExecutor(max_workers=max_workers) as pool:
434
+ future_map = {
435
+ pool.submit(
436
+ dispatch_to_model,
437
+ str(task_info[2].get("agent_name", "executor")),
438
+ str(task_info[2].get("prompt", "")),
439
+ project_dir,
440
+ ): task_info
441
+ for task_info in sorted_tasks
442
+ }
443
+
444
+ for future in as_completed(future_map):
445
+ task_info = future_map[future]
446
+ task = task_info[2]
447
+ order = task_info[1]
448
+ task_index = task_info[0]
449
+ agent_name = str(task.get("agent_name", "executor"))
450
+
451
+ try:
452
+ result = future.result(timeout=timeout_per_agent)
453
+ except Exception as exc:
454
+ result = {"error": str(exc), "fallback": "claude"}
455
+
456
+ if result.get("fallback") == "claude":
457
+ status = "fallback-claude"
458
+ elif "error" in result:
459
+ status = "error"
460
+ else:
461
+ status = "completed" if result.get("exit_code") == 0 else "failed"
462
+
463
+ results_by_index[task_index] = {
464
+ "agent": agent_name,
465
+ "order": order,
466
+ "status": status,
467
+ **result,
468
+ }
469
+
470
+ ordered_results = [results_by_index[task_info[0]] for task_info in sorted_tasks]
471
+ return ordered_results
472
+
473
+
474
+ def execute_crazy_mode(
475
+ problem: str,
476
+ project_dir: str,
477
+ context: str | None = None,
478
+ files: list[str] | None = None
479
+ ) -> dict[str, Any]:
480
+ print("[CRAZY] Starting parallel agent execution...")
481
+ print(f"[CRAZY] Problem: {problem[:100]}...")
482
+
483
+ # Build context package
484
+ context_parts = []
485
+ if context:
486
+ context_parts.append(context)
487
+ if files:
488
+ context_parts.append(f"Focus files: {', '.join(files[:8])}")
489
+ full_context = "\n\n".join(context_parts) if context_parts else ""
490
+
491
+ worker_tasks = [
492
+ {
493
+ "agent_name": "architect-mode",
494
+ "prompt": (
495
+ f"Plan decomposition for: {problem}\n\n"
496
+ f"Focus: scope, sequencing, dependency ordering, risk control.\n\n"
497
+ f"Context:\n{full_context}"
498
+ ),
499
+ "order": 1,
500
+ },
501
+ {
502
+ "agent_name": "backend-engineer",
503
+ "prompt": (
504
+ f"Backend implementation strategy for: {problem}\n\n"
505
+ f"Focus: APIs, data flow, failure handling, performance.\n\n"
506
+ f"Context:\n{full_context}"
507
+ ),
508
+ "order": 2,
509
+ },
510
+ {
511
+ "agent_name": "frontend-designer",
512
+ "prompt": (
513
+ f"Frontend/UI strategy for: {problem}\n\n"
514
+ f"Focus: UX, accessibility, responsive behavior, component structure.\n\n"
515
+ f"Context:\n{full_context}"
516
+ ),
517
+ "order": 3,
518
+ },
519
+ {
520
+ "agent_name": "security-auditor",
521
+ "prompt": (
522
+ f"Security review strategy for: {problem}\n\n"
523
+ f"Focus: auth, secrets, input validation, abuse vectors.\n\n"
524
+ f"Context:\n{full_context}"
525
+ ),
526
+ "order": 4,
527
+ },
528
+ {
529
+ "agent_name": "testing-engineer",
530
+ "prompt": (
531
+ f"Verification strategy for: {problem}\n\n"
532
+ f"Focus: unit/integration/e2e coverage and failure reproduction.\n\n"
533
+ f"Context:\n{full_context}"
534
+ ),
535
+ "order": 5,
536
+ },
537
+ ]
538
+
539
+ results = execute_agents_parallel(worker_tasks, project_dir)
540
+
541
+ result_blocks: list[str] = []
542
+ for r in results:
543
+ result_blocks.append(
544
+ f"**{r.get('agent', 'unknown')} [{r.get('status', 'unknown')}]:**\n"
545
+ f"{r.get('output', r.get('error', 'No output'))}"
546
+ )
547
+
548
+ synthesis_prompt = (
549
+ "Synthesize results from five specialized tracks:\n\n"
550
+ + "\n\n".join(result_blocks)
551
+ + "\n\nProvide a unified action plan with dependency ordering."
552
+ )
553
+
554
+ model_mix = {
555
+ "gpt": [r.get("agent") for r in results if r.get("model") == "codex-cli"],
556
+ "gemini": [r.get("agent") for r in results if r.get("model") == "gemini-cli"],
557
+ "claude": [r.get("agent") for r in results if r.get("fallback") == "claude"],
558
+ }
559
+
560
+ return {
561
+ "status": "ok",
562
+ "phases": [
563
+ {"phase": 1, "agent": "claude-orchestrator", "status": "completed"},
564
+ *[
565
+ {
566
+ "phase": idx,
567
+ "agent": r.get("agent"),
568
+ "status": r.get("status", "unknown"),
569
+ "model": r.get("model", r.get("fallback", "unknown")),
570
+ "output": r.get("output", ""),
571
+ }
572
+ for idx, r in enumerate(results, start=2)
573
+ ],
574
+ {"phase": 7, "agent": "claude-synthesis", "prompt": synthesis_prompt},
575
+ ],
576
+ "parallel_execution": True,
577
+ "sequential_execution": False,
578
+ "worker_count": len(results),
579
+ "target_worker_count": 5,
580
+ "model_mix": model_mix,
581
+ "findings": [
582
+ f"Workers launched: {len(results)}/5",
583
+ f"GPT tracks: {len(model_mix['gpt'])}",
584
+ f"Gemini tracks: {len(model_mix['gemini'])}",
585
+ f"Claude tracks: {len(model_mix['claude'])}",
586
+ ],
587
+ }
588
+
589
+
590
+ # =============================================================================
591
+ # Round-Robin Credential Distribution (Feature: OMG_ROUND_ROBIN_ENABLED)
592
+ # =============================================================================
593
+
594
+
595
+ def _fnv1a_hash(data: str) -> int:
596
+ """FNV-1a 32-bit hash for session-stable key assignment.
597
+
598
+ Deterministic: same input always produces the same hash.
599
+ Used to pin a session to a consistent starting key index.
600
+ """
601
+ h = 2166136261
602
+ for c in data.encode():
603
+ h ^= c
604
+ h = (h * 16777619) & 0xFFFFFFFF
605
+ return h
606
+
607
+
608
+ def _get_hooks_imports():
609
+ """Lazy-import credential_store and get_feature_flag.
610
+
611
+ Returns (credential_store_module, get_feature_flag_func) or (None, None).
612
+ Adds hooks dir to sys.path if needed (same pattern as package_prompt).
613
+ """
614
+ import sys as _sys
615
+
616
+ _hooks_dir = os.path.join(_OMG_ROOT, "hooks")
617
+ if _hooks_dir not in _sys.path:
618
+ _sys.path.insert(0, _hooks_dir)
619
+ try:
620
+ from _common import get_feature_flag # pyright: ignore[reportMissingImports]
621
+ import credential_store # pyright: ignore[reportMissingImports]
622
+
623
+ return credential_store, get_feature_flag
624
+ except ImportError:
625
+ return None, None
626
+
627
+
628
+ def get_active_credential(provider: str, session_id: str | None = None) -> str | None:
629
+ """Get active API key for provider via round-robin.
630
+
631
+ Returns key string or None if credential store disabled/unavailable.
632
+ Feature flag: OMG_ROUND_ROBIN_ENABLED
633
+
634
+ Args:
635
+ provider: Provider name (e.g., 'anthropic', 'openai')
636
+ session_id: Optional session ID for deterministic key assignment via FNV-1a hash
637
+ """
638
+ cred_mod, get_flag = _get_hooks_imports()
639
+ if cred_mod is None or get_flag is None:
640
+ return None
641
+
642
+ if not get_flag("ROUND_ROBIN", default=False):
643
+ return None
644
+
645
+ passphrase = os.environ.get("OMG_CREDENTIAL_PASSPHRASE")
646
+ if not passphrase:
647
+ return None
648
+
649
+ try:
650
+ store = cred_mod.load_store(passphrase)
651
+ except (ValueError, OSError):
652
+ return None
653
+
654
+ providers = store.get("providers", {})
655
+ if provider not in providers:
656
+ return None
657
+
658
+ pdata = providers[provider]
659
+ keys = pdata.get("keys", [])
660
+ if not keys:
661
+ return None
662
+
663
+ # Pick key index: session-stable via FNV-1a or current active_index
664
+ if session_id:
665
+ idx = _fnv1a_hash(session_id) % len(keys)
666
+ else:
667
+ idx = pdata.get("active_index", 0)
668
+ if idx < 0 or idx >= len(keys):
669
+ idx = 0
670
+
671
+ # Track usage on selected key
672
+ keys[idx]["usage_count"] = keys[idx].get("usage_count", 0) + 1
673
+ keys[idx]["last_used"] = datetime.now(timezone.utc).isoformat()
674
+
675
+ # Advance active_index for next non-session call (round-robin)
676
+ if not session_id:
677
+ pdata["active_index"] = (idx + 1) % len(keys)
678
+
679
+ # Persist updated stats (best-effort)
680
+ try:
681
+ cred_mod.save_store(store, passphrase)
682
+ except (ValueError, OSError):
683
+ pass
684
+
685
+ return keys[idx].get("key")
686
+
687
+
688
+ def on_rate_limit(provider: str, session_id: str | None = None) -> str | None:
689
+ """Advance to next credential for provider on 429. Returns new active key.
690
+
691
+ Called when a rate limit (HTTP 429) is encountered. Advances to the next
692
+ available key in the rotation and returns it.
693
+
694
+ Args:
695
+ provider: Provider name (e.g., 'anthropic', 'openai')
696
+ session_id: Optional session ID (currently unused, reserved for future)
697
+ """
698
+ cred_mod, get_flag = _get_hooks_imports()
699
+ if cred_mod is None or get_flag is None:
700
+ return None
701
+
702
+ if not get_flag("ROUND_ROBIN", default=False):
703
+ return None
704
+
705
+ passphrase = os.environ.get("OMG_CREDENTIAL_PASSPHRASE")
706
+ if not passphrase:
707
+ return None
708
+
709
+ try:
710
+ store = cred_mod.load_store(passphrase)
711
+ except (ValueError, OSError):
712
+ return None
713
+
714
+ providers = store.get("providers", {})
715
+ if provider not in providers:
716
+ return None
717
+
718
+ pdata = providers[provider]
719
+ keys = pdata.get("keys", [])
720
+ if not keys:
721
+ return None
722
+
723
+ current_idx = pdata.get("active_index", 0)
724
+ if current_idx < 0 or current_idx >= len(keys):
725
+ current_idx = 0
726
+
727
+ # Advance to next key
728
+ new_idx = (current_idx + 1) % len(keys)
729
+ pdata["active_index"] = new_idx
730
+
731
+ # Persist (best-effort)
732
+ try:
733
+ cred_mod.save_store(store, passphrase)
734
+ except (ValueError, OSError):
735
+ pass
736
+
737
+ return keys[new_idx].get("key")
738
+
739
+
740
+ # =============================================================================
741
+ # Role-Based Routing (Feature: OMG_ROLE_ROUTING_ENABLED)
742
+ # =============================================================================
743
+
744
+
745
+ def get_role_from_env() -> str | None:
746
+ """Read the active role from OMG_ACTIVE_ROLE environment variable.
747
+
748
+ Returns:
749
+ Role name string (e.g., 'smol', 'slow') or None if not set.
750
+ """
751
+ val = os.environ.get("OMG_ACTIVE_ROLE", "").strip().lower()
752
+ return val if val else None
753
+
754
+
755
+ def route_with_role(task_text: str, role: str | None = None) -> dict[str, Any]:
756
+ """Select model based on role + task classification.
757
+
758
+ Resolution order for role:
759
+ 1. Explicit `role` parameter
760
+ 2. OMG_ACTIVE_ROLE env var (via get_role_from_env())
761
+ 3. CLI args (--smol, --slow, --plan, --commit) via parse_role_args()
762
+ 4. None → fall back to existing routing
763
+
764
+ Feature flag: OMG_ROLE_ROUTING_ENABLED (default: False)
765
+ When disabled, returns a baseline dict from existing _infer_target().
766
+
767
+ Args:
768
+ task_text: Description of the task to route.
769
+ role: Optional explicit role name override.
770
+
771
+ Returns:
772
+ Dict with keys: model, provider, role, reason
773
+ """
774
+ import sys as _sys
775
+
776
+ # Baseline: always compute the existing routing target
777
+ existing_target = _infer_target(task_text)
778
+ baseline = {
779
+ "model": None,
780
+ "provider": existing_target,
781
+ "role": None,
782
+ "reason": f"intent-based routing to {existing_target}",
783
+ }
784
+
785
+ # Check feature flag via lazy import
786
+ _hooks_dir = os.path.join(_OMG_ROOT, "hooks")
787
+ if _hooks_dir not in _sys.path:
788
+ _sys.path.insert(0, _hooks_dir)
789
+ try:
790
+ from _common import get_feature_flag # pyright: ignore[reportMissingImports]
791
+ except ImportError:
792
+ # If _common unavailable, check env var directly
793
+ env_val = os.environ.get("OMG_ROLE_ROUTING_ENABLED", "").lower()
794
+ if env_val not in ("1", "true", "yes"):
795
+ return baseline
796
+ get_feature_flag = None # type: ignore[assignment]
797
+
798
+ if get_feature_flag is not None and not get_feature_flag("ROLE_ROUTING", default=False):
799
+ return baseline
800
+
801
+ # Resolve role: explicit param → env var → CLI args
802
+ resolved_role = role
803
+ if resolved_role is None:
804
+ resolved_role = get_role_from_env()
805
+ if resolved_role is None:
806
+ # Lazy import parse_role_args from agents.model_roles
807
+ _agents_dir = os.path.join(_OMG_ROOT, "agents")
808
+ if _agents_dir not in _sys.path:
809
+ _sys.path.insert(0, _agents_dir)
810
+ try:
811
+ from model_roles import parse_role_args # pyright: ignore[reportMissingImports]
812
+ resolved_role = parse_role_args(_sys.argv[1:])
813
+ except ImportError:
814
+ pass
815
+
816
+ # No role resolved → return baseline
817
+ if resolved_role is None:
818
+ return baseline
819
+
820
+ # Get role config via lazy import
821
+ _agents_dir = os.path.join(_OMG_ROOT, "agents")
822
+ if _agents_dir not in _sys.path:
823
+ _sys.path.insert(0, _agents_dir)
824
+ try:
825
+ from model_roles import get_role # pyright: ignore[reportMissingImports]
826
+ role_config = get_role(resolved_role)
827
+ except ImportError:
828
+ return baseline
829
+
830
+ if not role_config:
831
+ return baseline
832
+
833
+ return {
834
+ "model": role_config.get("model"),
835
+ "provider": role_config.get("model", existing_target),
836
+ "role": resolved_role,
837
+ "reason": f"role-based routing: {resolved_role} → {role_config.get('model', 'unknown')}",
838
+ }