letitloop 0.2.0__py3-none-any.whl

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 (175) hide show
  1. letitloop-0.2.0.dist-info/METADATA +232 -0
  2. letitloop-0.2.0.dist-info/RECORD +175 -0
  3. letitloop-0.2.0.dist-info/WHEEL +5 -0
  4. letitloop-0.2.0.dist-info/entry_points.txt +4 -0
  5. letitloop-0.2.0.dist-info/licenses/LICENSE +21 -0
  6. letitloop-0.2.0.dist-info/top_level.txt +1 -0
  7. orchestrator/SKILL.md +292 -0
  8. orchestrator/__init__.py +151 -0
  9. orchestrator/anti_ouroboros.py +78 -0
  10. orchestrator/approval.py +139 -0
  11. orchestrator/ast_node_splicer.py +130 -0
  12. orchestrator/ast_splicer.py +94 -0
  13. orchestrator/audit.py +88 -0
  14. orchestrator/budget.py +195 -0
  15. orchestrator/checkpoint.py +248 -0
  16. orchestrator/cli.py +1971 -0
  17. orchestrator/codebase_introspector.py +66 -0
  18. orchestrator/component_slicer.py +185 -0
  19. orchestrator/config.py +152 -0
  20. orchestrator/contract.py +404 -0
  21. orchestrator/dag_validator.py +172 -0
  22. orchestrator/elasticity_governor.py +80 -0
  23. orchestrator/env_doctor.py +166 -0
  24. orchestrator/errors.py +211 -0
  25. orchestrator/events.py +120 -0
  26. orchestrator/evidence.py +203 -0
  27. orchestrator/exceptions.py +37 -0
  28. orchestrator/experimental/arena_arbiter.py +260 -0
  29. orchestrator/experimental/fuzz_engine.py +206 -0
  30. orchestrator/experimental/mutation_tester.py +382 -0
  31. orchestrator/failure.py +226 -0
  32. orchestrator/fast_sandbox.py +126 -0
  33. orchestrator/feasibility_gate.py +115 -0
  34. orchestrator/feedback.py +302 -0
  35. orchestrator/fixtures/__init__.py +0 -0
  36. orchestrator/fixtures/example_contract.json +50 -0
  37. orchestrator/fixtures/generated/evidence-cli-run-test-step-1.json +47 -0
  38. orchestrator/fixtures/generated/evidence-cli-run-test-step-2.json +47 -0
  39. orchestrator/fixtures/generated/evidence-inject-test-a.json +47 -0
  40. orchestrator/fixtures/generated/evidence-inject-test-b.json +47 -0
  41. orchestrator/fixtures/generated/evidence-inject-test-c.json +47 -0
  42. orchestrator/fixtures/generated/evidence-json-test-a.json +47 -0
  43. orchestrator/fixtures/generated/evidence-json-test-b.json +47 -0
  44. orchestrator/fixtures/generated/fail-report-fail-task-1.json +47 -0
  45. orchestrator/fixtures/generated/fail-report-json-task-1.json +47 -0
  46. orchestrator/fixtures/generated/fail-report-success-task-1.json +47 -0
  47. orchestrator/fixtures/generated/fuzz-engine-design.json +63 -0
  48. orchestrator/fixtures/generated/fuzz-engine-impl.json +62 -0
  49. orchestrator/fixtures/generated/fuzz-engine-tests.json +62 -0
  50. orchestrator/fixtures/generated/fuzz-engine-verify.json +62 -0
  51. orchestrator/fixtures/generated/goal-orch-step-1.json +63 -0
  52. orchestrator/fixtures/generated/goal-orch-step-2.json +62 -0
  53. orchestrator/fixtures/generated/goal-orch-step-3.json +62 -0
  54. orchestrator/fixtures/generated/goal-orch-step-4.json +62 -0
  55. orchestrator/fixtures/generated/goal-orch-step-5.json +62 -0
  56. orchestrator/fixtures/generated/goal-orch-step-6.json +63 -0
  57. orchestrator/fixtures/generated/implement-a-thread-safe-token-bucket-rat-task-1.json +53 -0
  58. orchestrator/fixtures/generated/orchestrator-checkpoint-rollback-3.json +63 -0
  59. orchestrator/fixtures/generated/orchestrator-checkpoint-rollback.json +62 -0
  60. orchestrator/fixtures/generated/orchestrator-live-telemetry-2.json +62 -0
  61. orchestrator/fixtures/generated/orchestrator-live-telemetry.json +62 -0
  62. orchestrator/fixtures/generated/orchestrator-spec-synthesis-1.json +62 -0
  63. orchestrator/fixtures/generated/orchestrator-spec-synthesis.json +62 -0
  64. orchestrator/fixtures/generated/orchestrator-test-verification-4.json +62 -0
  65. orchestrator/fixtures/generated/orchestrator-test-verification.json +62 -0
  66. orchestrator/fixtures/generated/perf-step-1.json +61 -0
  67. orchestrator/fixtures/generated/perf-step-2.json +62 -0
  68. orchestrator/fixtures/generated/perf-step-3.json +62 -0
  69. orchestrator/fixtures/generated/perf-step-4.json +62 -0
  70. orchestrator/fixtures/generated/perf-step-5.json +63 -0
  71. orchestrator/fixtures/generated/phase2-proof-two-step-step-1.json +47 -0
  72. orchestrator/fixtures/generated/phase2-proof-two-step-step-2.json +47 -0
  73. orchestrator/fixtures/generated/planner-spec-synthesis-impl.json +59 -0
  74. orchestrator/fixtures/generated/self-evolution-ast-formatter.json +69 -0
  75. orchestrator/fixtures/generated/self-evolution-checkpoint-rollback.json +70 -0
  76. orchestrator/fixtures/generated/self-evolution-spec-synthesis.json +70 -0
  77. orchestrator/fixtures/generated/self-evolution-step-1.json +70 -0
  78. orchestrator/fixtures/generated/self-evolution-step-2.json +70 -0
  79. orchestrator/fixtures/generated/self-evolution-step-3.json +70 -0
  80. orchestrator/fixtures/generated/self-evolution-step-4.json +70 -0
  81. orchestrator/fixtures/generated/self-evolution-step-5.json +65 -0
  82. orchestrator/fixtures/generated/self-evolution-telemetry.json +70 -0
  83. orchestrator/fixtures/generated/self-evolution-tests.json +71 -0
  84. orchestrator/fixtures/generated/spec-telemetry-research-design.json +64 -0
  85. orchestrator/fixtures/generated/spec-telemetry-step-1.json +62 -0
  86. orchestrator/fixtures/generated/spec-telemetry-step-2.json +62 -0
  87. orchestrator/fixtures/generated/spec-telemetry-step-3.json +62 -0
  88. orchestrator/fixtures/generated/spec-telemetry-step-4.json +62 -0
  89. orchestrator/fixtures/generated/spec-telemetry-step-5.json +62 -0
  90. orchestrator/fixtures/generated/spec-telemetry-verification.json +58 -0
  91. orchestrator/fixtures/generated/token-bucket-impl.json +69 -0
  92. orchestrator/fixtures/generated/token-bucket-step-1.json +70 -0
  93. orchestrator/fixtures/generated/token-bucket-step-2.json +70 -0
  94. orchestrator/fixtures/generated/token-bucket-step-3.json +60 -0
  95. orchestrator/fixtures/generated/token-bucket-tests.json +70 -0
  96. orchestrator/fixtures/generated/token-bucket-verify.json +61 -0
  97. orchestrator/fixtures/generated/trace-ux-tests-step-1.json +64 -0
  98. orchestrator/fixtures/generated/trace-ux-tests-step-2.json +64 -0
  99. orchestrator/fixtures/generated/trace-ux-tests-step-3.json +62 -0
  100. orchestrator/fixtures/generated/tui-live-telemetry-impl.json +59 -0
  101. orchestrator/fixtures/phase1_proof_escalation_contract.json +41 -0
  102. orchestrator/fixtures/phase1_proof_happy_path_contract.json +83 -0
  103. orchestrator/fixtures/phase1_proof_qc_contract.json +41 -0
  104. orchestrator/fixtures/phase1_proof_repair_contract.json +41 -0
  105. orchestrator/fixtures/phase2_proof_two_step_goal.json +15 -0
  106. orchestrator/fixtures/run_proofs.py +299 -0
  107. orchestrator/fixtures/test_normalizer.py +16 -0
  108. orchestrator/generator.py +239 -0
  109. orchestrator/goal.py +245 -0
  110. orchestrator/handoff.py +86 -0
  111. orchestrator/hybrid_worker.py +840 -0
  112. orchestrator/impossibility.py +162 -0
  113. orchestrator/limits.py +60 -0
  114. orchestrator/live_evolution_engine.py +247 -0
  115. orchestrator/llm.py +291 -0
  116. orchestrator/local_tool_calling.py +285 -0
  117. orchestrator/lock.py +404 -0
  118. orchestrator/mcp_client.py +571 -0
  119. orchestrator/mcp_server.py +344 -0
  120. orchestrator/memory_bridge.py +182 -0
  121. orchestrator/metrics.py +159 -0
  122. orchestrator/micro_epoch.py +42 -0
  123. orchestrator/models.py +350 -0
  124. orchestrator/parsing.py +237 -0
  125. orchestrator/patch_applier.py +154 -0
  126. orchestrator/plan_preview.py +138 -0
  127. orchestrator/plan_quality.py +357 -0
  128. orchestrator/planner.py +532 -0
  129. orchestrator/preferences.py +115 -0
  130. orchestrator/preflight.py +141 -0
  131. orchestrator/process_guard.py +357 -0
  132. orchestrator/prometheus_exporter.py +207 -0
  133. orchestrator/prompts.py +275 -0
  134. orchestrator/proposal_ledger.py +194 -0
  135. orchestrator/provenance.py +263 -0
  136. orchestrator/provider_scheduler.py +394 -0
  137. orchestrator/qc/__init__.py +153 -0
  138. orchestrator/qc/aggregator.py +330 -0
  139. orchestrator/qc/parsing.py +287 -0
  140. orchestrator/qc/personas.py +242 -0
  141. orchestrator/qc/runner.py +569 -0
  142. orchestrator/qc_overrule.py +87 -0
  143. orchestrator/qc_review.py +282 -0
  144. orchestrator/quality_lenses.py +314 -0
  145. orchestrator/quality_plan.py +449 -0
  146. orchestrator/quality_plane.py +103 -0
  147. orchestrator/reconcile.py +191 -0
  148. orchestrator/replanner.py +433 -0
  149. orchestrator/research.py +176 -0
  150. orchestrator/review_artifact.py +672 -0
  151. orchestrator/safety.py +271 -0
  152. orchestrator/schemas.py +230 -0
  153. orchestrator/scope.py +466 -0
  154. orchestrator/sensory_radar.py +79 -0
  155. orchestrator/skill_installer.py +140 -0
  156. orchestrator/sse_server.py +160 -0
  157. orchestrator/state.py +871 -0
  158. orchestrator/subprocess_helper.py +131 -0
  159. orchestrator/supervisor/__init__.py +184 -0
  160. orchestrator/supervisor/_shared.py +164 -0
  161. orchestrator/supervisor/cleanup.py +185 -0
  162. orchestrator/supervisor/core.py +1680 -0
  163. orchestrator/supervisor/recovery.py +367 -0
  164. orchestrator/supervisor/reporting.py +251 -0
  165. orchestrator/surgical_extractor.py +119 -0
  166. orchestrator/telemetry.py +61 -0
  167. orchestrator/templates.py +268 -0
  168. orchestrator/token_gate.py +245 -0
  169. orchestrator/tui.py +649 -0
  170. orchestrator/verifier.py +1103 -0
  171. orchestrator/webhooks.py +168 -0
  172. orchestrator/worker.py +469 -0
  173. orchestrator/worker_adapters.py +815 -0
  174. orchestrator/worker_pool.py +121 -0
  175. orchestrator/worktree.py +364 -0
@@ -0,0 +1,42 @@
1
+ """
2
+ orchestrator/micro_epoch.py
3
+ Write-Ahead Log (WAL) Micro-Epoch state manager.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ import time
10
+ from dataclasses import asdict, dataclass
11
+ from pathlib import Path
12
+
13
+
14
+ @dataclass
15
+ class EpochRecord:
16
+ epoch_id: int
17
+ timestamp: float
18
+ task_id: str
19
+ diff_summary: str
20
+ is_committed: bool
21
+
22
+
23
+ class MicroEpochManager:
24
+ """Manages WAL state and atomic commits during autonomous evolution."""
25
+
26
+ def __init__(self, state_dir: Path):
27
+ self.state_dir = Path(state_dir)
28
+ self.state_dir.mkdir(parents=True, exist_ok=True)
29
+ self.wal_file = self.state_dir / "wal.jsonl"
30
+ self.checkpoint_file = self.state_dir / "state.checkpoint.json"
31
+
32
+ def record_task_completion(self, task_id: str, diff_summary: str) -> EpochRecord:
33
+ rec = EpochRecord(
34
+ epoch_id=int(time.time()),
35
+ timestamp=time.time(),
36
+ task_id=task_id,
37
+ diff_summary=diff_summary,
38
+ is_committed=True,
39
+ )
40
+ with open(self.wal_file, "a", encoding="utf-8") as f:
41
+ f.write(json.dumps(asdict(rec)) + "\n")
42
+ return rec
orchestrator/models.py ADDED
@@ -0,0 +1,350 @@
1
+ """Centralized model string registry and dynamic thinking budget configuration.
2
+
3
+ Single source of truth for all model IDs, provider routing, and model-specific compute allocation.
4
+ Ground truth updated for 2026 frontier model generations:
5
+ - OpenAI: GPT-5.6 Series (Sol, Terra, Luna, Cyber), o3, o3-mini, o4-mini, o1
6
+ - Anthropic: Claude 5 Series (Opus 5, Sonnet 5, Fable 5, Haiku 4.5), Claude 3.7 Sonnet
7
+ - Google: Gemini 3 Series (3.7 Flash, 3.6 Flash, 3.5 Flash Lite, 3.1 Pro), Gemini 2.5 Pro / Flash
8
+ - DeepSeek: V4 Series (DeepSeek-V4 Pro, DeepSeek-V4 Flash), DeepSeek-Chat (V3), DeepSeek-Reasoner (R1)
9
+ - Kimi: Kimi K3, Kimi K2
10
+ - Gateways: Omniroute, OpenRouter, Groq, Ollama
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import os
17
+ from typing import Any, Dict, List, Optional, Set
18
+
19
+
20
+ class ThinkingBudget:
21
+ """Dynamic thinking budget token targets across execution phases."""
22
+
23
+ PLANNING = 4096 # High thinking for deep architectural DAG planning
24
+ QC = 2048 # Deep verification and multi-lens critique
25
+ WORKER_STANDARD = 0 # 0 thinking tokens for instantaneous code edits / tests (<3s)
26
+ WORKER_COMPLEX = 1024 # Targeted reasoning for multi-file refactors
27
+
28
+ @classmethod
29
+ def budget_for(cls, phase_or_task_type: str) -> int:
30
+ """Resolve dynamic thinking token budget for a given phase or task type."""
31
+ phase = (phase_or_task_type or "").lower()
32
+ if "plan" in phase or "propose" in phase or "architect" in phase:
33
+ return cls.PLANNING
34
+ if "qc" in phase or "critique" in phase or "audit" in phase or "review" in phase:
35
+ return cls.QC
36
+ if "complex" in phase or "refactor" in phase:
37
+ return cls.WORKER_COMPLEX
38
+ return cls.WORKER_STANDARD
39
+
40
+
41
+ class ModelThinkingConfig:
42
+ """Model-specific dynamic thinking and reasoning configuration engine."""
43
+
44
+ REASONING_MODELS_OPENAI: Set[str] = {
45
+ "gpt-5.6-sol",
46
+ "gpt-5.6-terra",
47
+ "gpt-5.6-luna",
48
+ "gpt-5.6-cyber",
49
+ "o1",
50
+ "o1-mini",
51
+ "o1-preview",
52
+ "o3",
53
+ "o3-mini",
54
+ "o4-mini",
55
+ }
56
+
57
+ THINKING_MODELS_ANTHROPIC: Set[str] = {
58
+ "claude-opus-5",
59
+ "claude-sonnet-5",
60
+ "claude-fable-5",
61
+ "claude-haiku-4-5",
62
+ "claude-3-7-sonnet",
63
+ "claude-3-7-sonnet-20250219",
64
+ "claude-3-7-sonnet-latest",
65
+ "claude-3.7-sonnet",
66
+ "claude-opus-4",
67
+ "claude-sonnet-4",
68
+ }
69
+
70
+ THINKING_MODELS_GEMINI: Set[str] = {
71
+ "gemini-3.7-flash",
72
+ "gemini-3.6-flash",
73
+ "gemini-3.5-flash-lite",
74
+ "gemini-3.1-pro",
75
+ "gemini-2.5-pro",
76
+ "gemini-2.5-flash",
77
+ "gemini-3.7-flash-latest",
78
+ }
79
+
80
+ @classmethod
81
+ def is_anthropic_thinking_model(cls, model_id: str) -> bool:
82
+ mid = model_id.lower()
83
+ return any(m in mid for m in cls.THINKING_MODELS_ANTHROPIC)
84
+
85
+ @classmethod
86
+ def is_openai_reasoning_model(cls, model_id: str) -> bool:
87
+ mid = model_id.lower()
88
+ return any(m in mid for m in cls.REASONING_MODELS_OPENAI)
89
+
90
+ @classmethod
91
+ def is_gemini_thinking_model(cls, model_id: str) -> bool:
92
+ mid = model_id.lower()
93
+ return any(m in mid for m in cls.THINKING_MODELS_GEMINI)
94
+
95
+ @classmethod
96
+ def apply_thinking_config(
97
+ cls,
98
+ model_id: str,
99
+ provider: str,
100
+ payload: Dict[str, Any],
101
+ thinking_budget: Optional[int] = None,
102
+ phase: str = "worker",
103
+ ) -> None:
104
+ """Mutate payload in-place to apply model-safe thinking / reasoning parameters.
105
+
106
+ Enforces strict provider rules:
107
+ - Anthropic: budget_tokens >= 1024 if enabled, max_tokens > budget_tokens, no temperature != 1.0.
108
+ If budget == 0 (standard worker), thinking is cleanly omitted for sub-3s response.
109
+ - Gemini: passes extra_body.google.thinking_config.thinking_budget (0 for instant response).
110
+ - OpenAI: passes reasoning_effort ('low', 'medium', 'high') to reasoning models (gpt-5.6 series, o1, o3, o4);
111
+ never passes reasoning_effort to standard non-reasoning models (gpt-4o, gpt-4o-mini) to prevent 400 errors.
112
+ """
113
+ budget = thinking_budget if thinking_budget is not None else ThinkingBudget.budget_for(phase)
114
+
115
+ if provider == "anthropic":
116
+ if cls.is_anthropic_thinking_model(model_id) and budget >= 1024:
117
+ payload["thinking"] = {"type": "enabled", "budget_tokens": budget}
118
+ current_max = payload.get("max_tokens", 4096)
119
+ if current_max <= budget:
120
+ payload["max_tokens"] = budget + 2048
121
+ payload.pop("temperature", None)
122
+ else:
123
+ payload.pop("thinking", None)
124
+
125
+ elif provider == "gemini":
126
+ if cls.is_gemini_thinking_model(model_id) or "gemini" in model_id.lower():
127
+ payload["extra_body"] = {"google": {"thinking_config": {"thinking_budget": budget}}}
128
+ if budget > 0:
129
+ current_max = payload.get("max_tokens", 4096)
130
+ if current_max <= budget:
131
+ payload["max_tokens"] = budget + 4096
132
+
133
+ elif provider == "openai":
134
+ if cls.is_openai_reasoning_model(model_id):
135
+ if budget == 0:
136
+ payload["reasoning_effort"] = "low"
137
+ elif budget >= 4096:
138
+ payload["reasoning_effort"] = "high"
139
+ else:
140
+ payload["reasoning_effort"] = "medium"
141
+ else:
142
+ payload.pop("reasoning_effort", None)
143
+
144
+
145
+ class ModelRegistry:
146
+ # Default workhorse & QC reviewer
147
+ WORKER = "gemini-3.7-flash"
148
+ QC = "gemini-3.1-pro"
149
+ WORKER_PREFIXED = f"gemini:{WORKER}"
150
+ QC_PREFIXED = f"gemini:{QC}"
151
+ WORKER_FALLBACK = "gemini:gemini-3.6-flash"
152
+ QC_FALLBACK = "gemini:gemini-3.7-flash"
153
+ HYBRID = f"hybrid:{WORKER_PREFIXED}"
154
+ FALLBACK = "gemini:gemini-3.6-flash"
155
+ OPUS = "claude-opus-5"
156
+ KIMI = "kimi-k3"
157
+
158
+ # OpenAI 2026 Generation
159
+ GPT_SOL = "openai:gpt-5.6-sol"
160
+ GPT_TERRA = "openai:gpt-5.6-terra"
161
+ GPT_LUNA = "openai:gpt-5.6-luna"
162
+ GPT_CYBER = "openai:gpt-5.6-cyber"
163
+ O3 = "openai:o3"
164
+ O3_MINI = "openai:o3-mini"
165
+ O4_MINI = "openai:o4-mini"
166
+ O1 = "openai:o1"
167
+ O1_MINI = "openai:o1-mini"
168
+ GPT_4O = "openai:gpt-4o"
169
+ GPT_4O_MINI = "openai:gpt-4o-mini"
170
+
171
+ # Anthropic Claude 5 Generation
172
+ CLAUDE_OPUS_5 = "anthropic:claude-opus-5"
173
+ CLAUDE_SONNET_5 = "anthropic:claude-sonnet-5"
174
+ CLAUDE_FABLE_5 = "anthropic:claude-fable-5"
175
+ CLAUDE_HAIKU_4_5 = "anthropic:claude-haiku-4-5"
176
+ CLAUDE_3_7_SONNET = "anthropic:claude-3-7-sonnet-latest"
177
+ CLAUDE_3_5_SONNET = "anthropic:claude-3-5-sonnet-latest"
178
+ CLAUDE_3_OPUS = "anthropic:claude-3-opus-latest"
179
+
180
+ # Google Gemini 3 Generation
181
+ GEMINI_3_7_FLASH = "gemini:gemini-3.7-flash"
182
+ GEMINI_3_6_FLASH = "gemini:gemini-3.6-flash"
183
+ GEMINI_3_5_FLASH_LITE = "gemini:gemini-3.5-flash-lite"
184
+ GEMINI_3_1_PRO = "gemini:gemini-3.1-pro"
185
+ GEMINI_2_5_PRO = "gemini:gemini-2.5-pro"
186
+ GEMINI_2_5_FLASH = "gemini:gemini-2.5-flash"
187
+
188
+ # DeepSeek V4 Generation
189
+ DEEPSEEK_V4_PRO = "deepseek:deepseek-v4-pro"
190
+ DEEPSEEK_V4_FLASH = "deepseek:deepseek-v4-flash"
191
+ DEEPSEEK_CHAT = "deepseek:deepseek-chat"
192
+ DEEPSEEK_REASONER = "deepseek:deepseek-reasoner"
193
+
194
+ # Kimi Generation
195
+ KIMI_K3 = "kimi:kimi-k3"
196
+ KIMI_K2 = "kimi:kimi-k2"
197
+
198
+ # Gateways
199
+ OMNIROUTE_AUTO = "omniroute:auto"
200
+
201
+ @classmethod
202
+ def default_worker(cls) -> str:
203
+ """Effective worker model (env WORKER_MODEL wins over default)."""
204
+ if "WORKER_MODEL" in os.environ:
205
+ return os.environ["WORKER_MODEL"]
206
+ return cls.WORKER_PREFIXED
207
+
208
+ @classmethod
209
+ def default_qc(cls) -> str:
210
+ """Effective QC model (env QC_MODEL wins over default)."""
211
+ if "QC_MODEL" in os.environ:
212
+ return os.environ["QC_MODEL"]
213
+ return cls.QC_PREFIXED
214
+
215
+ @classmethod
216
+ def prefixed(cls, model: Optional[str] = None) -> str:
217
+ return f"gemini:{model or cls.WORKER}"
218
+
219
+ @classmethod
220
+ def hybrid(cls, model: Optional[str] = None) -> str:
221
+ return f"hybrid:gemini:{model or cls.WORKER}"
222
+
223
+ @classmethod
224
+ def is_hybrid(cls, model: str) -> bool:
225
+ return model.startswith("hybrid:")
226
+
227
+ @classmethod
228
+ def strip_hybrid_prefix(cls, model: str) -> str:
229
+ return model[7:] if model.startswith("hybrid:") else model
230
+
231
+
232
+ # ---------------------------------------------------------------------------
233
+ # Cost/risk tiering (issue #19): cheap/standard/frontier ladders used by the
234
+ # risk-aware provider router. Tier 1 = cheapest, tier 3 = most capable.
235
+
236
+ MODEL_TIERS: Dict[int, List[str]] = {
237
+ 1: ["gemini-2.5-flash-lite", "qwen2.5-coder"],
238
+ 2: ["gemini-2.5-flash", "claude-3-5-haiku", "gpt-4o-mini"],
239
+ 3: ["claude-3-5-sonnet", "gpt-4o", "deepseek-r1"],
240
+ }
241
+
242
+ _TIER_ONE_RISKS = ("trivial", "boilerplate", "format")
243
+ _TIER_THREE_RISKS = ("crucible", "architecture", "high_risk")
244
+
245
+ # Ordered cheapest-first; substring families checked tier by tier so that
246
+ # specific families ("flash-lite") win over generic ones ("flash").
247
+ _TIER_FAMILIES: Dict[int, tuple] = {
248
+ 1: ("flash-lite", "flashlite", "qwen"),
249
+ 2: ("haiku", "4o-mini"),
250
+ 3: ("sonnet", "opus", "gpt-4o", "deepseek", "reasoner"),
251
+ }
252
+
253
+
254
+ def _bare_model_id(model: str) -> str:
255
+ """Lowercased bare model id with provider/hybrid prefixes stripped.
256
+
257
+ Handles three id shapes:
258
+ - ``model`` / ``model:tag`` (Ollama-style tag kept only for bare ids)
259
+ - ``provider/model`` and ``provider/model:tag`` (slash form: drop path, drop tag)
260
+ - ``provider:model`` (hybrid worker prefix: keep the model part)
261
+ """
262
+ text = (model or "").strip().lower()
263
+ if "/" in text:
264
+ # Slash form: provider/model[:tag] -> model[:tag] -> model
265
+ text = text.rsplit("/", 1)[-1]
266
+ if ":" in text:
267
+ text = text.rsplit(":", 1)[0]
268
+ return text
269
+ while ":" in text:
270
+ head, _, tail = text.partition(":")
271
+ if not tail:
272
+ break
273
+ text = tail
274
+ return text
275
+
276
+
277
+ def model_tiers() -> Dict[int, List[str]]:
278
+ """Effective tier ladder; LETITLOOP_MODEL_TIERS JSON overrides the default."""
279
+ raw = os.environ.get("LETITLOOP_MODEL_TIERS", "")
280
+ if raw:
281
+ try:
282
+ parsed = json.loads(raw)
283
+ except ValueError:
284
+ parsed = None
285
+ if isinstance(parsed, dict) and parsed:
286
+ try:
287
+ overridden = {int(tier): [str(m) for m in models] for tier, models in parsed.items() if models}
288
+ except (TypeError, ValueError):
289
+ overridden = {}
290
+ if overridden:
291
+ return overridden
292
+ return {tier: list(models) for tier, models in MODEL_TIERS.items()}
293
+
294
+
295
+ def classify_model(model: str) -> int:
296
+ """Classify a model id into its cost tier (1 cheapest .. 3 frontier).
297
+
298
+ Exact ladder membership first, then substring/family match against known
299
+ families. Unknown models default to tier 2 (standard).
300
+ """
301
+ bare = _bare_model_id(model)
302
+ tiers = model_tiers()
303
+ ordered = sorted(tiers)
304
+ for tier in ordered:
305
+ if bare in {_bare_model_id(m) for m in tiers[tier]}:
306
+ return int(tier)
307
+ for tier in ordered:
308
+ if any(family in bare for family in _TIER_FAMILIES.get(int(tier), ())):
309
+ return int(tier)
310
+ return 2
311
+
312
+
313
+ def tier_for_risk(risk_hint: str) -> int:
314
+ """Map a task risk hint to a target tier ('' / unknown hints default to 2)."""
315
+ hint = (risk_hint or "").strip().lower().replace("-", "_")
316
+ if hint in _TIER_ONE_RISKS:
317
+ return 1
318
+ if hint in _TIER_THREE_RISKS:
319
+ return 3
320
+ return 2
321
+
322
+
323
+ def escalation_ladder(start_model: Optional[str] = None, start_tier: Optional[int] = None) -> List[str]:
324
+ """Ordered deduped candidate sequence ascending from the starting tier.
325
+
326
+ The starting model (when given) heads the ladder, followed by the rest of
327
+ its tier and then every higher tier in order.
328
+ """
329
+ tiers = model_tiers()
330
+ lo, hi = min(tiers), max(tiers)
331
+ if start_tier is None:
332
+ start_tier = classify_model(start_model) if start_model else lo
333
+ try:
334
+ base = int(start_tier)
335
+ except (TypeError, ValueError):
336
+ base = lo
337
+ base = max(lo, min(hi, base))
338
+ sequence: List[str] = []
339
+ if start_model and start_model.strip():
340
+ sequence.append(start_model.strip())
341
+ for tier in range(base, hi + 1):
342
+ sequence.extend(tiers.get(tier, []))
343
+ seen: Set[str] = set()
344
+ ladder: List[str] = []
345
+ for candidate in sequence:
346
+ key = _bare_model_id(candidate)
347
+ if key and key not in seen:
348
+ seen.add(key)
349
+ ladder.append(candidate)
350
+ return ladder
@@ -0,0 +1,237 @@
1
+ """Robust LLM output parser — multi-tier artifact extraction from model responses."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import re
8
+ from dataclasses import dataclass, field
9
+ from typing import List
10
+
11
+ RE_XML_FILE = re.compile(
12
+ r'<file\s+(?:path|name)=["\']([^"\']+)["\']\s*>([\s\S]*?)(?:</file>|$)',
13
+ re.IGNORECASE,
14
+ )
15
+ RE_HEADER_FENCE = re.compile(
16
+ r"(?:^|\n)([\w\/\.\-\_\\]+\.[a-zA-Z0-9]+)\s*\n```(?:([a-zA-Z0-9_\-\+]+)\s+)?\n([\s\S]*?)(?:```|$)",
17
+ )
18
+ RE_ANNOTATED_FENCE = re.compile(
19
+ r'```([a-zA-Z0-9_\-\+]+)?:(?:\s*path=)?["\']?([\w\/\.\-\_\\]+\.[a-zA-Z0-9]+)["\']?\s*\n([\s\S]*?)(?:```|$)',
20
+ )
21
+ RE_GENERIC_FENCE = re.compile(
22
+ r"```([a-zA-Z0-9_\-\+]+)?\s*\n([\s\S]*?)(?:```|$)",
23
+ )
24
+ RE_FENCE_MARKER = re.compile(r"^```", re.MULTILINE)
25
+
26
+
27
+ @dataclass
28
+ class ParsedArtifact:
29
+ path: str
30
+ content: str
31
+ language: str
32
+ parser_tier: str
33
+
34
+
35
+ @dataclass
36
+ class ParseResult:
37
+ ok: bool
38
+ artifacts: List[ParsedArtifact] = field(default_factory=list)
39
+ error: str = ""
40
+ raw_length: int = 0
41
+
42
+
43
+ def sanitize_text(text: str) -> str:
44
+ text = text.replace("\ufeff", "").replace("\u200b", "").replace("\u200c", "")
45
+ return text.replace("\r\n", "\n").replace("\r", "\n")
46
+
47
+
48
+ def repair_unclosed_fences(text: str) -> str:
49
+ matches = list(RE_FENCE_MARKER.finditer(text))
50
+ if len(matches) % 2 != 0:
51
+ text = text.rstrip() + "\n```"
52
+ return text
53
+
54
+
55
+ def _strip_llm_chatter(text: str) -> str:
56
+ pat = re.compile(
57
+ r"(?i)^\s*(sure!|here is the|i\'?m (sorry|unable)|as an ai|i hope|let me know|the output has been)",
58
+ re.MULTILINE,
59
+ )
60
+ return pat.sub("", text).strip()
61
+
62
+
63
+ def _detect_language(path: str) -> str:
64
+ ext = os.path.splitext(path)[1].lower()
65
+ mapping = {
66
+ ".py": "python",
67
+ ".js": "javascript",
68
+ ".ts": "typescript",
69
+ ".json": "json",
70
+ ".yaml": "yaml",
71
+ ".yml": "yaml",
72
+ ".go": "go",
73
+ ".rs": "rust",
74
+ ".md": "markdown",
75
+ ".html": "html",
76
+ ".css": "css",
77
+ ".sh": "shell",
78
+ ".ps1": "powershell",
79
+ ".bat": "batch",
80
+ }
81
+ return mapping.get(ext, "text")
82
+
83
+
84
+ def _is_path_acceptable(
85
+ proposed: str,
86
+ expected_paths: List[str],
87
+ ) -> bool:
88
+ norm = proposed.replace("\\", "/")
89
+ if norm.startswith("/"):
90
+ return False
91
+ if norm[1:3] == ":\\" if len(norm) > 2 else False:
92
+ return False
93
+ if ".." in norm.split("/") or ".." in norm.split("\\"):
94
+ return False
95
+ if proposed in expected_paths:
96
+ return True
97
+ for ep in expected_paths:
98
+ if ep.replace("\\", "/") == norm:
99
+ return True
100
+ return False
101
+
102
+
103
+ def parse_llm_artifacts(
104
+ raw_output: str,
105
+ expected_paths: List[str],
106
+ ) -> ParseResult:
107
+ raw_length = len(raw_output)
108
+ if not raw_output or not raw_output.strip():
109
+ return ParseResult(ok=False, error="empty model output", raw_length=raw_length)
110
+
111
+ text = sanitize_text(raw_output)
112
+ text = text.strip()
113
+
114
+ artifacts: List[ParsedArtifact] = []
115
+ used_tiers: List[str] = []
116
+
117
+ def _accept(artifact: ParsedArtifact) -> bool:
118
+ if not _is_path_acceptable(artifact.path, expected_paths):
119
+ return False
120
+ artifacts.append(artifact)
121
+ used_tiers.append(artifact.parser_tier)
122
+ return True
123
+
124
+ _rejected = False
125
+
126
+ # Tier 0: Search/Replace Delta Blocks
127
+ from .patch_applier import SearchReplacePatchParser
128
+
129
+ sr_chunks = SearchReplacePatchParser.parse_chunks(text)
130
+ if sr_chunks:
131
+ if len(expected_paths) == 1:
132
+ p = expected_paths[0]
133
+ _accept(
134
+ ParsedArtifact(path=p, content=text, language=_detect_language(p), parser_tier="T0_SearchReplaceDelta")
135
+ )
136
+ return ParseResult(ok=True, artifacts=artifacts, raw_length=raw_length)
137
+
138
+ # Tier 1: JSON array
139
+ try:
140
+ if text.startswith("[") and text.endswith("]"):
141
+ data = json.loads(text)
142
+ if isinstance(data, list):
143
+ for item in data:
144
+ if isinstance(item, dict) and "path" in item and "content" in item:
145
+ p = item["path"]
146
+ c = item["content"]
147
+ lang = item.get("language", _detect_language(p))
148
+ if not _accept(ParsedArtifact(path=p, content=c, language=lang, parser_tier="T1_JSON")):
149
+ _rejected = True
150
+ if artifacts:
151
+ return ParseResult(ok=True, artifacts=artifacts, raw_length=raw_length)
152
+ if _rejected:
153
+ return ParseResult(ok=False, error="JSON artifact path not allowed", raw_length=raw_length)
154
+ except (json.JSONDecodeError, ValueError):
155
+ pass
156
+ artifacts.clear()
157
+
158
+ # Tier 2: XML file tags
159
+ xml_matches = RE_XML_FILE.findall(text)
160
+ _rejected = False
161
+ if xml_matches:
162
+ for path, content in xml_matches:
163
+ path = path.strip()
164
+ content = content.lstrip("\n")
165
+ lang = _detect_language(path)
166
+ if not _accept(ParsedArtifact(path=path, content=content, language=lang, parser_tier="T2_XML")):
167
+ _rejected = True
168
+ if artifacts:
169
+ return ParseResult(ok=True, artifacts=artifacts, raw_length=raw_length)
170
+ if _rejected:
171
+ return ParseResult(ok=False, error="XML artifact path not allowed", raw_length=raw_length)
172
+ artifacts.clear()
173
+
174
+ # Tier 3: Header + code fence (GPT-Engineer style)
175
+ header_matches = RE_HEADER_FENCE.findall(text)
176
+ _rejected = False
177
+ if header_matches:
178
+ for path, lang_tag, content in header_matches:
179
+ path = path.strip()
180
+ lang = lang_tag or _detect_language(path)
181
+ if not _accept(ParsedArtifact(path=path, content=content, language=lang, parser_tier="T3_HeaderFence")):
182
+ _rejected = True
183
+ if artifacts:
184
+ return ParseResult(ok=True, artifacts=artifacts, raw_length=raw_length)
185
+ if _rejected:
186
+ return ParseResult(ok=False, error="Header-fence artifact path not allowed", raw_length=raw_length)
187
+ artifacts.clear()
188
+
189
+ # Tier 4: Annotated fence (path embedded in language tag)
190
+ annotated = RE_ANNOTATED_FENCE.findall(text)
191
+ _rejected = False
192
+ if annotated:
193
+ for lang_tag, path, content in annotated:
194
+ path = path.strip()
195
+ lang = lang_tag or _detect_language(path)
196
+ if not _accept(ParsedArtifact(path=path, content=content, language=lang, parser_tier="T4_AnnotatedFence")):
197
+ _rejected = True
198
+ if artifacts:
199
+ return ParseResult(ok=True, artifacts=artifacts, raw_length=raw_length)
200
+ if _rejected:
201
+ return ParseResult(ok=False, error="Annotated fence path not allowed", raw_length=raw_length)
202
+ artifacts.clear()
203
+
204
+ # Tier 5: Generic code fence (no path)
205
+ generic = RE_GENERIC_FENCE.findall(text)
206
+ if generic:
207
+ if len(generic) == 1 and len(expected_paths) == 1:
208
+ lang_tag, content = generic[0]
209
+ path = expected_paths[0]
210
+ lang = lang_tag or _detect_language(path)
211
+ _accept(ParsedArtifact(path=path, content=content, language=lang, parser_tier="T5_GenericFence"))
212
+ return ParseResult(ok=True, artifacts=artifacts, raw_length=raw_length)
213
+ elif len(generic) == len(expected_paths):
214
+ for idx, (lang_tag, content) in enumerate(generic):
215
+ path = expected_paths[idx]
216
+ lang = lang_tag or _detect_language(path)
217
+ _accept(ParsedArtifact(path=path, content=content, language=lang, parser_tier="T5_GenericFence"))
218
+ return ParseResult(ok=True, artifacts=artifacts, raw_length=raw_length)
219
+ return ParseResult(ok=False, error="generic fence count mismatch with expected paths", raw_length=raw_length)
220
+ artifacts.clear()
221
+
222
+ # Tier 6: Whole-body fallback (single expected output only)
223
+ if len(expected_paths) == 1:
224
+ cleaned = _strip_llm_chatter(text)
225
+ if not cleaned:
226
+ cleaned = text
227
+ _accept(
228
+ ParsedArtifact(
229
+ path=expected_paths[0],
230
+ content=cleaned,
231
+ language=_detect_language(expected_paths[0]),
232
+ parser_tier="T6_WholeBodyFallback",
233
+ )
234
+ )
235
+ return ParseResult(ok=True, artifacts=artifacts, raw_length=raw_length)
236
+
237
+ return ParseResult(ok=False, error="no parseable artifacts found in model output", raw_length=raw_length)