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,815 @@
1
+ """Pluggable Worker Adapter Framework for letitloop.
2
+
3
+ Provides unified execution interfaces for various backend agents and CLIs:
4
+ Claude Code, Google Antigravity, OpenCode, Hermes Agent, Cline, Aider, Omniroute,
5
+ Script executors, Direct LLM APIs, Docker sandboxes, and local tool-calling LLMs.
6
+ """
7
+
8
+ import json
9
+ import os
10
+ import re
11
+ import subprocess
12
+ import sys
13
+ import urllib.error
14
+ import urllib.request
15
+ from abc import ABC, abstractmethod
16
+ from typing import Any, Callable, Dict, List, Optional
17
+
18
+ from orchestrator import process_guard
19
+
20
+
21
+ class BaseWorkerAdapter(ABC):
22
+ """Abstract base worker adapter interface."""
23
+
24
+ def __init__(self, name: str, config: Optional[Dict[str, Any]] = None):
25
+ self.name = name
26
+ self.config = config or {}
27
+
28
+ def is_available(self) -> bool:
29
+ """Check if the worker CLI binary is available on system PATH."""
30
+ import shutil
31
+
32
+ binary = getattr(self, "cli_binary", self.name)
33
+ return shutil.which(binary) is not None
34
+
35
+ @abstractmethod
36
+ def execute(self, prompt: str, workspace_root: str, task_id: str, timeout: int = 300) -> Dict[str, Any]:
37
+ """Execute the worker on the given task and prompt."""
38
+ raise NotImplementedError
39
+
40
+
41
+ class MockWorkerAdapter(BaseWorkerAdapter):
42
+ """Deterministic mock worker for fast testing and dry-run execution."""
43
+
44
+ def __init__(self, name: str = "mock", config: Optional[Dict[str, Any]] = None):
45
+ super().__init__(name, config)
46
+ self.call_history: List[Dict[str, Any]] = []
47
+
48
+ def execute(self, prompt: str, workspace_root: str, task_id: str, timeout: int = 300) -> Dict[str, Any]:
49
+ if not os.environ.get("PYTEST_CURRENT_TEST") and not os.environ.get("LIL_TEST_MODE"):
50
+ import sys
51
+
52
+ print(
53
+ f"[SECURITY WARNING] Running with MockWorkerAdapter on task {task_id}. Execution is simulated!",
54
+ file=sys.stderr,
55
+ )
56
+
57
+ result = {
58
+ "exit_code": 0,
59
+ "stdout": f"Mock execution succeeded for {task_id}",
60
+ "stderr": "",
61
+ "approach": "mock_default",
62
+ "modified_files": [],
63
+ }
64
+ self.call_history.append({"task_id": task_id, "prompt": prompt})
65
+ return result
66
+
67
+
68
+ class ScriptWorkerAdapter(BaseWorkerAdapter):
69
+ """Executes a local Python or Shell script worker."""
70
+
71
+ def __init__(self, script_command: str, name: str = "script", config: Optional[Dict[str, Any]] = None):
72
+ super().__init__(name, config)
73
+ self.script_command = script_command
74
+
75
+ def execute(self, prompt: str, workspace_root: str, task_id: str, timeout: int = 300) -> Dict[str, Any]:
76
+ env = dict(os.environ)
77
+ env["LIL_TASK_ID"] = task_id
78
+ env["LIL_WORKSPACE_ROOT"] = workspace_root
79
+
80
+ try:
81
+ popen_kwargs = dict(
82
+ stdin=subprocess.PIPE,
83
+ text=True,
84
+ cwd=workspace_root,
85
+ env=env,
86
+ )
87
+ popen_kwargs.update(process_guard.containment_kwargs())
88
+ proc = subprocess.Popen( # nosec B602
89
+ self.script_command,
90
+ shell=True,
91
+ stdout=subprocess.PIPE,
92
+ stderr=subprocess.PIPE,
93
+ **popen_kwargs,
94
+ )
95
+ job = process_guard.attach_containment(proc)
96
+ try:
97
+ try:
98
+ stdout, stderr = proc.communicate(input=prompt, timeout=timeout)
99
+ except subprocess.TimeoutExpired:
100
+ # Kill the whole tree (children included) before reporting the timeout.
101
+ process_guard.kill_process_tree(proc.pid)
102
+ try:
103
+ proc.communicate(timeout=5)
104
+ except Exception:
105
+ pass
106
+ return {
107
+ "exit_code": 124,
108
+ "stdout": "",
109
+ "stderr": f"Script execution timed out after {timeout} seconds",
110
+ "approach": "timeout",
111
+ }
112
+ finally:
113
+ process_guard.close_job_handle(job)
114
+ return {
115
+ "exit_code": proc.returncode,
116
+ "stdout": stdout or "",
117
+ "stderr": stderr or "",
118
+ "approach": f"script:{self.script_command}",
119
+ }
120
+ except Exception as e:
121
+ return {
122
+ "exit_code": 1,
123
+ "stdout": "",
124
+ "stderr": f"Failed to execute script worker: {e}",
125
+ "approach": "error",
126
+ }
127
+
128
+
129
+ class ClaudeCodeWorkerAdapter(BaseWorkerAdapter):
130
+ """Executes tasks via the Claude Code CLI."""
131
+
132
+ def __init__(self, name: str = "claude-code", config: Optional[Dict[str, Any]] = None):
133
+ super().__init__(name, config)
134
+ self.cli_binary = self.config.get("binary", "claude")
135
+
136
+ def execute(self, prompt: str, workspace_root: str, task_id: str, timeout: int = 600) -> Dict[str, Any]:
137
+ cmd = [self.cli_binary, "-p", prompt, "--dangerously-skip-permissions"]
138
+ try:
139
+ proc = subprocess.run(
140
+ cmd,
141
+ capture_output=True,
142
+ text=True,
143
+ cwd=workspace_root,
144
+ timeout=timeout,
145
+ )
146
+ return {
147
+ "exit_code": proc.returncode,
148
+ "stdout": proc.stdout,
149
+ "stderr": proc.stderr,
150
+ "approach": "claude_code_autonomous",
151
+ }
152
+ except Exception as e:
153
+ return {
154
+ "exit_code": 1,
155
+ "stdout": "",
156
+ "stderr": f"Claude Code invocation error: {e}",
157
+ "approach": "error",
158
+ }
159
+
160
+
161
+ class AntigravityCliWorkerAdapter(BaseWorkerAdapter):
162
+ """Executes tasks via the Google Antigravity CLI (`agy`)."""
163
+
164
+ def __init__(self, name: str = "antigravity-cli", config: Optional[Dict[str, Any]] = None):
165
+ super().__init__(name, config)
166
+ self.cli_binary = self.config.get("binary", "agy")
167
+
168
+ def execute(self, prompt: str, workspace_root: str, task_id: str, timeout: int = 600) -> Dict[str, Any]:
169
+ import shutil
170
+
171
+ executable = shutil.which(self.cli_binary) or self.cli_binary
172
+ cmd = [executable, "-p", prompt, "--dangerously-skip-permissions"]
173
+
174
+ try:
175
+ proc = subprocess.run(
176
+ cmd,
177
+ capture_output=True,
178
+ text=True,
179
+ cwd=workspace_root,
180
+ timeout=timeout,
181
+ stdin=subprocess.DEVNULL,
182
+ )
183
+ return {
184
+ "exit_code": proc.returncode,
185
+ "stdout": proc.stdout,
186
+ "stderr": proc.stderr,
187
+ "approach": "antigravity_cli_exec",
188
+ }
189
+ except Exception as e:
190
+ return {
191
+ "exit_code": 1,
192
+ "stdout": "",
193
+ "stderr": f"Antigravity CLI execution error: {e}",
194
+ "approach": "error",
195
+ }
196
+
197
+
198
+ class OpenCodeWorkerAdapter(BaseWorkerAdapter):
199
+ """Executes tasks via the OpenCode CLI."""
200
+
201
+ def __init__(self, name: str = "opencode", config: Optional[Dict[str, Any]] = None):
202
+ super().__init__(name, config)
203
+ self.cli_binary = self.config.get("binary", "opencode")
204
+
205
+ def execute(self, prompt: str, workspace_root: str, task_id: str, timeout: int = 600) -> Dict[str, Any]:
206
+ cmd = [self.cli_binary, "run", "--prompt", prompt, "--workspace", workspace_root]
207
+ try:
208
+ proc = subprocess.run(
209
+ cmd,
210
+ capture_output=True,
211
+ text=True,
212
+ cwd=workspace_root,
213
+ timeout=timeout,
214
+ )
215
+ return {
216
+ "exit_code": proc.returncode,
217
+ "stdout": proc.stdout,
218
+ "stderr": proc.stderr,
219
+ "approach": "opencode_run",
220
+ }
221
+ except Exception as e:
222
+ return {
223
+ "exit_code": 1,
224
+ "stdout": "",
225
+ "stderr": f"OpenCode execution error: {e}",
226
+ "approach": "error",
227
+ }
228
+
229
+
230
+ class HermesWorkerAdapter(BaseWorkerAdapter):
231
+ """Executes tasks via the Nous Research Hermes Agent CLI."""
232
+
233
+ def __init__(self, name: str = "hermes", config: Optional[Dict[str, Any]] = None):
234
+ super().__init__(name, config)
235
+ self.cli_binary = self.config.get("binary", "hermes")
236
+
237
+ def execute(self, prompt: str, workspace_root: str, task_id: str, timeout: int = 600) -> Dict[str, Any]:
238
+ cmd = [self.cli_binary, "exec", "--prompt", prompt, "--path", workspace_root]
239
+ try:
240
+ proc = subprocess.run(
241
+ cmd,
242
+ capture_output=True,
243
+ text=True,
244
+ cwd=workspace_root,
245
+ timeout=timeout,
246
+ )
247
+ return {
248
+ "exit_code": proc.returncode,
249
+ "stdout": proc.stdout,
250
+ "stderr": proc.stderr,
251
+ "approach": "hermes_agent_exec",
252
+ }
253
+ except Exception as e:
254
+ return {
255
+ "exit_code": 1,
256
+ "stdout": "",
257
+ "stderr": f"Hermes Agent execution error: {e}",
258
+ "approach": "error",
259
+ }
260
+
261
+
262
+ class ClineWorkerAdapter(BaseWorkerAdapter):
263
+ """Executes tasks via the Cline CLI / headless runner."""
264
+
265
+ def __init__(self, name: str = "cline", config: Optional[Dict[str, Any]] = None):
266
+ super().__init__(name, config)
267
+ self.cli_binary = self.config.get("binary", "cline")
268
+
269
+ def execute(self, prompt: str, workspace_root: str, task_id: str, timeout: int = 600) -> Dict[str, Any]:
270
+ cmd = [self.cli_binary, "--prompt", prompt, "--cwd", workspace_root, "--yes"]
271
+ try:
272
+ proc = subprocess.run(
273
+ cmd,
274
+ capture_output=True,
275
+ text=True,
276
+ cwd=workspace_root,
277
+ timeout=timeout,
278
+ )
279
+ return {
280
+ "exit_code": proc.returncode,
281
+ "stdout": proc.stdout,
282
+ "stderr": proc.stderr,
283
+ "approach": "cline_autonomous",
284
+ }
285
+ except Exception as e:
286
+ return {
287
+ "exit_code": 1,
288
+ "stdout": "",
289
+ "stderr": f"Cline execution error: {e}",
290
+ "approach": "error",
291
+ }
292
+
293
+
294
+ class AiderWorkerAdapter(BaseWorkerAdapter):
295
+ """Executes tasks via the Aider CLI pair programmer."""
296
+
297
+ def __init__(self, name: str = "aider", config: Optional[Dict[str, Any]] = None):
298
+ super().__init__(name, config)
299
+ self.cli_binary = self.config.get("binary", "aider")
300
+
301
+ def execute(self, prompt: str, workspace_root: str, task_id: str, timeout: int = 600) -> Dict[str, Any]:
302
+ cmd = [self.cli_binary, "--message", prompt, "--no-git", "--yes-always"]
303
+ try:
304
+ proc = subprocess.run(
305
+ cmd,
306
+ capture_output=True,
307
+ text=True,
308
+ cwd=workspace_root,
309
+ timeout=timeout,
310
+ )
311
+ return {
312
+ "exit_code": proc.returncode,
313
+ "stdout": proc.stdout,
314
+ "stderr": proc.stderr,
315
+ "approach": "aider_pair_programmer",
316
+ }
317
+ except Exception as e:
318
+ return {
319
+ "exit_code": 1,
320
+ "stdout": "",
321
+ "stderr": f"Aider execution error: {e}",
322
+ "approach": "error",
323
+ }
324
+
325
+
326
+ class OmnirouteWorkerAdapter(BaseWorkerAdapter):
327
+ """Executes tasks through the Omniroute routing gateway."""
328
+
329
+ def __init__(self, name: str = "omniroute", config: Optional[Dict[str, Any]] = None):
330
+ super().__init__(name, config)
331
+ self.endpoint = self.config.get("base_url", "http://localhost:8000/v1")
332
+ self.model = self.config.get("model", "omniroute:auto")
333
+
334
+ def execute(self, prompt: str, workspace_root: str, task_id: str, timeout: int = 300) -> Dict[str, Any]:
335
+ from .llm import call_llm
336
+
337
+ try:
338
+ response = call_llm(
339
+ prompt=prompt,
340
+ model=self.model,
341
+ timeout_s=timeout,
342
+ system_prompt="You are an autonomous software engineering agent tasked with completing a scoped unit task.",
343
+ )
344
+ return {
345
+ "exit_code": 0,
346
+ "stdout": response,
347
+ "stderr": "",
348
+ "approach": "omniroute_gateway",
349
+ }
350
+ except Exception as e:
351
+ return {
352
+ "exit_code": 1,
353
+ "stdout": "",
354
+ "stderr": f"Omniroute gateway execution error: {e}",
355
+ "approach": "error",
356
+ }
357
+
358
+
359
+ class CodexWorkerAdapter(BaseWorkerAdapter):
360
+ """Executes tasks via the OpenAI Codex CLI."""
361
+
362
+ def __init__(self, name: str = "codex", config: Optional[Dict[str, Any]] = None):
363
+ super().__init__(name, config)
364
+ self.cli_binary = self.config.get("binary", "codex")
365
+
366
+ def execute(self, prompt: str, workspace_root: str, task_id: str, timeout: int = 600) -> Dict[str, Any]:
367
+ cmd = [self.cli_binary, "exec", "--prompt", prompt, "--path", workspace_root]
368
+ try:
369
+ proc = subprocess.run(
370
+ cmd,
371
+ capture_output=True,
372
+ text=True,
373
+ cwd=workspace_root,
374
+ timeout=timeout,
375
+ )
376
+ return {
377
+ "exit_code": proc.returncode,
378
+ "stdout": proc.stdout,
379
+ "stderr": proc.stderr,
380
+ "approach": "codex_cli_exec",
381
+ }
382
+ except Exception as e:
383
+ return {
384
+ "exit_code": 1,
385
+ "stdout": "",
386
+ "stderr": f"Codex CLI execution error: {e}",
387
+ "approach": "error",
388
+ }
389
+
390
+
391
+ def _docker_host_path(host_path: str) -> str:
392
+ """Normalize a host path for a docker -v spec (POSIX separators, no drive colon)."""
393
+ posix = str(host_path).replace("\\", "/")
394
+ # 'C:/ws' -> '/c/ws' style avoids the ambiguous drive-letter colon in -v specs.
395
+ if len(posix) >= 2 and posix[1] == ":":
396
+ posix = "/" + posix[0].lower() + posix[2:]
397
+ return posix
398
+
399
+
400
+ class DockerWorkerAdapter(BaseWorkerAdapter):
401
+ """Executes tasks inside an isolated Docker sandbox container."""
402
+
403
+ CONTAINER_WORKSPACE = "/workspace"
404
+
405
+ def __init__(self, name: str = "docker", config: Optional[Dict[str, Any]] = None):
406
+ super().__init__(name, config)
407
+ self.image = self.config.get("image", "python:3.11-slim")
408
+ self.network = self.config.get("network", "none")
409
+ self.cpus = self.config.get("cpus", "1.0")
410
+ self.memory = self.config.get("memory", "512m")
411
+ self.script_command = self.config.get("script", 'cat "${LIL_INSTRUCTIONS}"')
412
+
413
+ def is_available(self) -> bool:
414
+ return self._docker_available()
415
+
416
+ def _docker_available(self) -> bool:
417
+ """Check the Docker CLI answers `docker info` (daemon reachable)."""
418
+ try:
419
+ proc = subprocess.run(["docker", "info"], capture_output=True, text=True, timeout=10)
420
+ return proc.returncode == 0
421
+ except (OSError, subprocess.TimeoutExpired):
422
+ return False
423
+
424
+ def _build_volumes(self, workspace_root: str) -> List[str]:
425
+ """Build -v mount specs: each allow path rw, root ro unless fully covered.
426
+
427
+ Host paths outside the workspace (absolute escapes or parent traversals)
428
+ are refused - they would mount arbitrary host directories into the
429
+ container. Such allows are skipped with a stderr warning.
430
+ """
431
+ ws_abs = os.path.abspath(workspace_root)
432
+ ws_norm = os.path.normcase(ws_abs) if os.name == "nt" else ws_abs
433
+ scope = self.config.get("workspace_scope") or {}
434
+ allows = [str(a).strip().replace("\\", "/") for a in scope.get("allow", []) if str(a).strip()]
435
+ fully_covered = any(a in (".", "./") for a in allows)
436
+
437
+ volumes = [(ws_abs, self.CONTAINER_WORKSPACE, "rw" if fully_covered else "ro")]
438
+ seen = {ws_abs.lower()}
439
+ for allow in allows:
440
+ if allow in (".", "./"):
441
+ continue
442
+ if bool(re.match(r"^[a-zA-Z]:", allow)) or allow.startswith("/"):
443
+ print(
444
+ f"[docker] refusing allow outside workspace: {allow!r} -> {allow!r}",
445
+ file=sys.stderr,
446
+ )
447
+ continue
448
+ host = os.path.normpath(os.path.join(ws_abs, allow))
449
+ host_norm = os.path.normcase(host) if os.name == "nt" else host
450
+ # Refuse host paths outside the workspace (absolute escape or parent traversal).
451
+ if os.path.commonpath([ws_norm, host_norm]) != ws_norm:
452
+ print(
453
+ f"[docker] refusing allow outside workspace: {allow!r} -> {host!r}",
454
+ file=sys.stderr,
455
+ )
456
+ continue
457
+ if host.lower() in seen:
458
+ continue
459
+ seen.add(host.lower())
460
+ volumes.append((host, f"{self.CONTAINER_WORKSPACE}/{allow.rstrip('/')}", "rw"))
461
+ return [f"{_docker_host_path(host)}:{container}:{mode}" for host, container, mode in volumes]
462
+
463
+ def _build_run_argv(self, prompt: str, workspace_root: str, task_id: str) -> List[str]:
464
+ """Build the full `docker run` argv and stage the brief as a read-only file."""
465
+ scratch_dir = os.path.join(workspace_root, "scratch")
466
+ os.makedirs(scratch_dir, exist_ok=True)
467
+ instructions_name = f"docker_instructions_{task_id}.txt"
468
+ with open(os.path.join(scratch_dir, instructions_name), "w", encoding="utf-8") as f:
469
+ f.write(prompt)
470
+ instructions_container = f"{self.CONTAINER_WORKSPACE}/scratch/{instructions_name}"
471
+
472
+ argv = [
473
+ "docker",
474
+ "run",
475
+ "--rm",
476
+ "--network",
477
+ str(self.network),
478
+ "--cpus",
479
+ str(self.cpus),
480
+ "--memory",
481
+ str(self.memory),
482
+ ]
483
+ for volume in self._build_volumes(workspace_root):
484
+ argv.extend(["-v", volume])
485
+ argv.extend(["-w", self.CONTAINER_WORKSPACE])
486
+ argv.extend(
487
+ [
488
+ "-e",
489
+ f"LIL_TASK_ID={task_id}",
490
+ "-e",
491
+ f"LIL_WORKSPACE_ROOT={self.CONTAINER_WORKSPACE}",
492
+ "-e",
493
+ f"LIL_INSTRUCTIONS={instructions_container}",
494
+ ]
495
+ )
496
+ argv.append(self.image)
497
+ argv.extend(["/bin/sh", "-c", self.script_command])
498
+ return argv
499
+
500
+ def execute(self, prompt: str, workspace_root: str, task_id: str, timeout: int = 600) -> Dict[str, Any]:
501
+ if not self._docker_available():
502
+ return {
503
+ "exit_code": 1,
504
+ "stdout": "",
505
+ "stderr": "Docker daemon unreachable: `docker info` failed or timed out; cannot run sandbox worker",
506
+ "approach": "error",
507
+ }
508
+ try:
509
+ cmd = self._build_run_argv(prompt, workspace_root, task_id)
510
+ proc = subprocess.run(
511
+ cmd,
512
+ input=prompt,
513
+ capture_output=True,
514
+ text=True,
515
+ cwd=workspace_root,
516
+ timeout=timeout,
517
+ )
518
+ return {
519
+ "exit_code": proc.returncode,
520
+ "stdout": proc.stdout,
521
+ "stderr": proc.stderr,
522
+ "approach": "docker_sandbox",
523
+ }
524
+ except subprocess.TimeoutExpired:
525
+ return {
526
+ "exit_code": 124,
527
+ "stdout": "",
528
+ "stderr": f"Docker sandbox execution timed out after {timeout} seconds",
529
+ "approach": "timeout",
530
+ }
531
+ except Exception as e:
532
+ return {
533
+ "exit_code": 1,
534
+ "stdout": "",
535
+ "stderr": f"Docker sandbox execution error: {e}",
536
+ "approach": "error",
537
+ }
538
+
539
+
540
+ REPAIR_NUDGE = (
541
+ "Your previous response contained no valid tool call and no final answer. "
542
+ "Either call one of the provided tools, or reply with your complete final answer as plain text."
543
+ )
544
+
545
+
546
+ class LocalToolWorkerAdapter(BaseWorkerAdapter):
547
+ """Executes tasks via a local OpenAI-compatible LLM using native tool calling.
548
+
549
+ Talks to Ollama / vLLM / LM Studio style endpoints ({base_url}/chat/completions),
550
+ runs model tool calls against a sandboxed local registry, and journals every
551
+ turn to <workspace_root>/scratch/orchestrator_runs/<task_id>/worker_output.log.
552
+ """
553
+
554
+ def __init__(
555
+ self,
556
+ name: str = "local-tool",
557
+ config: Optional[Dict[str, Any]] = None,
558
+ transport: Optional[Callable[..., Dict[str, Any]]] = None,
559
+ ):
560
+ super().__init__(name, config)
561
+ self.base_url = self.config.get("base_url", "http://localhost:11434/v1")
562
+ self.model = self.config.get("model")
563
+ self.max_turns = int(self.config.get("max_turns", 8))
564
+ self.api_key = self.config.get("api_key")
565
+ self._transport = transport
566
+
567
+ def is_available(self) -> bool:
568
+ """Endpoint-backed adapter: available whenever a model is configured."""
569
+ return bool(self.model)
570
+
571
+ @staticmethod
572
+ def _system_prompt() -> str:
573
+ return (
574
+ "You are an autonomous software engineering agent completing a scoped unit task. "
575
+ "The user message contains the task objective and constraints.\n"
576
+ "TOOL RULES:\n"
577
+ "- Use the provided tools (read_file, write_file, replace_lines, execute_command) "
578
+ "to inspect and modify the workspace.\n"
579
+ "- Prefer acting through tools over printing code blocks.\n"
580
+ "- When the task is complete, reply with ONLY a short plain-text final summary and no tool call.\n"
581
+ "SCOPE LIMITS:\n"
582
+ "- Only read or write files inside the workspace paths allowed by the task.\n"
583
+ "- Never attempt to escape the workspace or access paths outside it.\n"
584
+ "- Do not run git commands, deploys, or anything mutating files outside the workspace."
585
+ )
586
+
587
+ def _http_transport(
588
+ self, messages: List[Dict[str, Any]], tools: List[Dict[str, Any]], timeout_s: int
589
+ ) -> Dict[str, Any]:
590
+ url = f"{str(self.base_url).rstrip('/')}/chat/completions"
591
+ headers = {"content-type": "application/json"}
592
+ if self.api_key:
593
+ headers["Authorization"] = f"Bearer {self.api_key}"
594
+ payload = {"model": self.model, "messages": messages, "tools": tools}
595
+ body = json.dumps(payload).encode("utf-8")
596
+ req = urllib.request.Request(url, data=body, headers=headers, method="POST")
597
+ try:
598
+ with urllib.request.urlopen(req, timeout=timeout_s) as resp: # nosec B310
599
+ raw = resp.read().decode("utf-8", errors="replace")
600
+ except urllib.error.HTTPError as e:
601
+ detail = ""
602
+ try:
603
+ detail = e.read().decode("utf-8", errors="replace")[:500]
604
+ except OSError:
605
+ pass
606
+ raise RuntimeError(f"HTTP {e.code} from local LLM endpoint: {detail or e.reason}") from e
607
+ except urllib.error.URLError as e:
608
+ raise RuntimeError(f"connection failed to local LLM endpoint: {e.reason}") from e
609
+ return json.loads(raw)
610
+
611
+ def _extract_native_tool_calls(self, message: Dict[str, Any]) -> List[Dict[str, Any]]:
612
+ calls: List[Dict[str, Any]] = []
613
+ for tc in message.get("tool_calls") or []:
614
+ if not isinstance(tc, dict):
615
+ continue
616
+ fn = tc.get("function") or {}
617
+ name = fn.get("name")
618
+ arguments = fn.get("arguments", {})
619
+ if isinstance(arguments, str):
620
+ try:
621
+ arguments = json.loads(arguments)
622
+ except json.JSONDecodeError:
623
+ arguments = {}
624
+ if not isinstance(arguments, dict):
625
+ arguments = {}
626
+ if name:
627
+ calls.append({"id": tc.get("id") or f"call_{len(calls)}", "name": name, "arguments": arguments})
628
+ return calls
629
+
630
+ @staticmethod
631
+ def _invoke_tool(registry: Any, call: Dict[str, Any]) -> str:
632
+ from .local_tool_calling import ToolCallingError
633
+
634
+ try:
635
+ result = registry.execute_call(call["name"], call["arguments"])
636
+ except ToolCallingError as e:
637
+ return f"TOOL ERROR: {e}"
638
+ except Exception as e:
639
+ return f"TOOL ERROR: {e}"
640
+ if isinstance(result, dict):
641
+ return json.dumps(result)
642
+ return str(result)
643
+
644
+ @staticmethod
645
+ def _open_journal(workspace_root: str, task_id: str) -> str:
646
+ run_dir = os.path.join(workspace_root, "scratch", "orchestrator_runs", task_id)
647
+ os.makedirs(run_dir, exist_ok=True)
648
+ return os.path.join(run_dir, "worker_output.log")
649
+
650
+ @staticmethod
651
+ def _append_journal(log_path: str, turn: int, exit_code: int, stdout_text: str, stderr_text: str) -> None:
652
+ with open(log_path, "a", encoding="utf-8") as f:
653
+ f.write(f"=== TURN {turn} ===\n")
654
+ f.write(f"EXIT CODE: {exit_code}\n")
655
+ f.write("--- STDOUT ---\n")
656
+ f.write(stdout_text)
657
+ f.write("\n--- STDERR ---\n")
658
+ f.write(stderr_text)
659
+ f.write("\n")
660
+
661
+ def execute(self, prompt: str, workspace_root: str, task_id: str, timeout: int = 600) -> Dict[str, Any]:
662
+ if not self.model:
663
+ return {
664
+ "exit_code": 1,
665
+ "stdout": "",
666
+ "stderr": "LocalToolWorkerAdapter requires a 'model' config value",
667
+ "approach": "error",
668
+ }
669
+ from .local_tool_calling import LocalToolRegistry, build_default_registry
670
+
671
+ scope = self.config.get("workspace_scope") or {"allow": ["."], "deny": []}
672
+ registry = build_default_registry(workspace_root, scope)
673
+ tools = registry.get_openai_tools()
674
+ messages: List[Dict[str, Any]] = [
675
+ {"role": "system", "content": self._system_prompt()},
676
+ {"role": "user", "content": prompt},
677
+ ]
678
+ transport = self._transport or (lambda msgs, tls: self._http_transport(msgs, tls, timeout))
679
+ journal_path = self._open_journal(workspace_root, task_id)
680
+ repair_nudged = False
681
+
682
+ try:
683
+ for turn in range(1, self.max_turns + 1):
684
+ data = transport(messages, tools)
685
+ choice = (data.get("choices") or [{}])[0]
686
+ message = choice.get("message", {}) if isinstance(choice, dict) else {}
687
+ content = message.get("content") or ""
688
+ calls = self._extract_native_tool_calls(message)
689
+ native = bool(calls)
690
+ if not calls:
691
+ calls = [
692
+ {"id": f"call_{idx}", "name": parsed["name"], "arguments": parsed.get("arguments") or {}}
693
+ for idx, parsed in enumerate(LocalToolRegistry.parse_tool_calls(content))
694
+ ]
695
+
696
+ if not calls:
697
+ if str(content).strip():
698
+ self._append_journal(journal_path, turn, 0, f"FINAL ANSWER:\n{content}", "")
699
+ return {
700
+ "exit_code": 0,
701
+ "stdout": content,
702
+ "stderr": "",
703
+ "approach": "local_tool_calling",
704
+ }
705
+ if not repair_nudged:
706
+ repair_nudged = True
707
+ self._append_journal(
708
+ journal_path,
709
+ turn,
710
+ 1,
711
+ "GARBAGE TURN: no usable tool call or final answer; sending repair nudge",
712
+ "no usable model response",
713
+ )
714
+ messages.append({"role": "assistant", "content": content})
715
+ messages.append({"role": "user", "content": REPAIR_NUDGE})
716
+ continue
717
+ self._append_journal(
718
+ journal_path,
719
+ turn,
720
+ 1,
721
+ "GARBAGE TURN persists after repair nudge; aborting",
722
+ "no usable model response after repair nudge",
723
+ )
724
+ return {
725
+ "exit_code": 1,
726
+ "stdout": "",
727
+ "stderr": "model produced no usable tool call or final answer after repair nudge",
728
+ "approach": "error",
729
+ }
730
+
731
+ if native:
732
+ messages.append(message)
733
+ else:
734
+ messages.append(
735
+ {
736
+ "role": "assistant",
737
+ "content": content,
738
+ "tool_calls": [
739
+ {
740
+ "id": c["id"],
741
+ "type": "function",
742
+ "function": {"name": c["name"], "arguments": json.dumps(c["arguments"])},
743
+ }
744
+ for c in calls
745
+ ],
746
+ }
747
+ )
748
+
749
+ summary_lines = []
750
+ for call in calls:
751
+ result_text = self._invoke_tool(registry, call)
752
+ summary_lines.append(
753
+ f"{call['name']}({json.dumps(call['arguments'], sort_keys=True)}) -> {result_text[:500]}"
754
+ )
755
+ messages.append(
756
+ {
757
+ "role": "tool",
758
+ "tool_call_id": call["id"],
759
+ "name": call["name"],
760
+ "content": result_text,
761
+ }
762
+ )
763
+ self._append_journal(journal_path, turn, 0, "\n".join(summary_lines), "")
764
+ except Exception as e:
765
+ return {
766
+ "exit_code": 1,
767
+ "stdout": "",
768
+ "stderr": f"Local tool-calling execution error: {e}",
769
+ "approach": "error",
770
+ }
771
+
772
+ self._append_journal(
773
+ journal_path, self.max_turns, 1, "MAX TURNS reached without final answer", "max_turns exceeded"
774
+ )
775
+ return {
776
+ "exit_code": 1,
777
+ "stdout": "",
778
+ "stderr": f"Local tool-calling worker hit max_turns ({self.max_turns}) without a final answer",
779
+ "approach": "error",
780
+ "success": False,
781
+ "reason": "max_turns",
782
+ }
783
+
784
+
785
+ class WorkerRegistry:
786
+ """Registry to register and resolve custom worker adapters dynamically."""
787
+
788
+ _adapters: Dict[str, BaseWorkerAdapter] = {
789
+ "mock": MockWorkerAdapter("mock"),
790
+ "claude-code": ClaudeCodeWorkerAdapter("claude-code"),
791
+ "claude": ClaudeCodeWorkerAdapter("claude"),
792
+ "antigravity-cli": AntigravityCliWorkerAdapter("antigravity-cli"),
793
+ "antigravity": AntigravityCliWorkerAdapter("antigravity"),
794
+ "agy": AntigravityCliWorkerAdapter("agy"),
795
+ "opencode": OpenCodeWorkerAdapter("opencode"),
796
+ "hermes": HermesWorkerAdapter("hermes"),
797
+ "cline": ClineWorkerAdapter("cline"),
798
+ "aider": AiderWorkerAdapter("aider"),
799
+ "omniroute": OmnirouteWorkerAdapter("omniroute"),
800
+ "codex": CodexWorkerAdapter("codex"),
801
+ "local-tool": LocalToolWorkerAdapter("local-tool"),
802
+ "docker": DockerWorkerAdapter("docker"),
803
+ }
804
+
805
+ @classmethod
806
+ def register(cls, name: str, adapter: BaseWorkerAdapter):
807
+ cls._adapters[name] = adapter
808
+
809
+ @classmethod
810
+ def get(cls, name: str) -> Optional[BaseWorkerAdapter]:
811
+ return cls._adapters.get(name)
812
+
813
+ @classmethod
814
+ def list_available(cls) -> List[str]:
815
+ return list(cls._adapters.keys())